Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Parse/ParsePragma.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- ParsePragma.cpp - Language specific pragma parsing ---------------===//
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 the language specific #pragma handlers.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/AST/ASTContext.h"
14
#include "clang/Basic/PragmaKinds.h"
15
#include "clang/Basic/TargetInfo.h"
16
#include "clang/Lex/Preprocessor.h"
17
#include "clang/Lex/Token.h"
18
#include "clang/Parse/LoopHint.h"
19
#include "clang/Parse/ParseDiagnostic.h"
20
#include "clang/Parse/Parser.h"
21
#include "clang/Parse/RAIIObjectsForParser.h"
22
#include "clang/Sema/EnterExpressionEvaluationContext.h"
23
#include "clang/Sema/Scope.h"
24
#include "llvm/ADT/ArrayRef.h"
25
#include "llvm/ADT/StringSwitch.h"
26
#include <optional>
27
using namespace clang;
28
29
namespace {
30
31
struct PragmaAlignHandler : public PragmaHandler {
32
46
  explicit PragmaAlignHandler() : PragmaHandler("align") {}
33
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
34
                    Token &FirstToken) override;
35
};
36
37
struct PragmaGCCVisibilityHandler : public PragmaHandler {
38
46
  explicit PragmaGCCVisibilityHandler() : PragmaHandler("visibility") {}
39
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
40
                    Token &FirstToken) override;
41
};
42
43
struct PragmaOptionsHandler : public PragmaHandler {
44
46
  explicit PragmaOptionsHandler() : PragmaHandler("options") {}
45
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
46
                    Token &FirstToken) override;
47
};
48
49
struct PragmaPackHandler : public PragmaHandler {
50
46
  explicit PragmaPackHandler() : PragmaHandler("pack") {}
51
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
52
                    Token &FirstToken) override;
53
};
54
55
struct PragmaClangSectionHandler : public PragmaHandler {
56
  explicit PragmaClangSectionHandler(Sema &S)
57
46
             : PragmaHandler("section"), Actions(S) {}
58
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
59
                    Token &FirstToken) override;
60
61
private:
62
  Sema &Actions;
63
};
64
65
struct PragmaMSStructHandler : public PragmaHandler {
66
46
  explicit PragmaMSStructHandler() : PragmaHandler("ms_struct") {}
67
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
68
                    Token &FirstToken) override;
69
};
70
71
struct PragmaUnusedHandler : public PragmaHandler {
72
46
  PragmaUnusedHandler() : PragmaHandler("unused") {}
73
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
74
                    Token &FirstToken) override;
75
};
76
77
struct PragmaWeakHandler : public PragmaHandler {
78
46
  explicit PragmaWeakHandler() : PragmaHandler("weak") {}
79
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
80
                    Token &FirstToken) override;
81
};
82
83
struct PragmaRedefineExtnameHandler : public PragmaHandler {
84
46
  explicit PragmaRedefineExtnameHandler() : PragmaHandler("redefine_extname") {}
85
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
86
                    Token &FirstToken) override;
87
};
88
89
struct PragmaOpenCLExtensionHandler : public PragmaHandler {
90
0
  PragmaOpenCLExtensionHandler() : PragmaHandler("EXTENSION") {}
91
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
92
                    Token &FirstToken) override;
93
};
94
95
96
struct PragmaFPContractHandler : public PragmaHandler {
97
46
  PragmaFPContractHandler() : PragmaHandler("FP_CONTRACT") {}
98
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
99
                    Token &FirstToken) override;
100
};
101
102
// Pragma STDC implementations.
103
104
/// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
105
struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
106
46
  PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
107
108
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
109
0
                    Token &Tok) override {
110
0
    Token PragmaName = Tok;
111
0
    if (!PP.getTargetInfo().hasStrictFP() && !PP.getLangOpts().ExpStrictFP) {
112
0
      PP.Diag(Tok.getLocation(), diag::warn_pragma_fp_ignored)
113
0
          << PragmaName.getIdentifierInfo()->getName();
114
0
      return;
115
0
    }
116
0
    tok::OnOffSwitch OOS;
117
0
    if (PP.LexOnOffSwitch(OOS))
118
0
     return;
119
120
0
    MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
121
0
                                1);
122
0
    Toks[0].startToken();
123
0
    Toks[0].setKind(tok::annot_pragma_fenv_access);
124
0
    Toks[0].setLocation(Tok.getLocation());
125
0
    Toks[0].setAnnotationEndLoc(Tok.getLocation());
126
0
    Toks[0].setAnnotationValue(reinterpret_cast<void*>(
127
0
                               static_cast<uintptr_t>(OOS)));
128
0
    PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
129
0
                        /*IsReinject=*/false);
130
0
  }
131
};
132
133
/// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
134
struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
135
46
  PragmaSTDC_CX_LIMITED_RANGEHandler() : PragmaHandler("CX_LIMITED_RANGE") {}
136
137
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
138
0
                    Token &Tok) override {
139
0
    tok::OnOffSwitch OOS;
140
0
    if (PP.LexOnOffSwitch(OOS))
141
0
      return;
142
143
0
    MutableArrayRef<Token> Toks(
144
0
        PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
145
146
0
    Toks[0].startToken();
147
0
    Toks[0].setKind(tok::annot_pragma_cx_limited_range);
148
0
    Toks[0].setLocation(Tok.getLocation());
149
0
    Toks[0].setAnnotationEndLoc(Tok.getLocation());
150
0
    Toks[0].setAnnotationValue(
151
0
        reinterpret_cast<void *>(static_cast<uintptr_t>(OOS)));
152
0
    PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
153
0
                        /*IsReinject=*/false);
154
0
  }
155
};
156
157
/// Handler for "\#pragma STDC FENV_ROUND ...".
158
struct PragmaSTDC_FENV_ROUNDHandler : public PragmaHandler {
159
46
  PragmaSTDC_FENV_ROUNDHandler() : PragmaHandler("FENV_ROUND") {}
160
161
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
162
                    Token &Tok) override;
163
};
164
165
/// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
166
struct PragmaSTDC_UnknownHandler : public PragmaHandler {
167
46
  PragmaSTDC_UnknownHandler() = default;
168
169
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
170
0
                    Token &UnknownTok) override {
171
    // C99 6.10.6p2, unknown forms are not allowed.
172
0
    PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
173
0
  }
174
};
175
176
struct PragmaFPHandler : public PragmaHandler {
177
46
  PragmaFPHandler() : PragmaHandler("fp") {}
178
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
179
                    Token &FirstToken) override;
180
};
181
182
// A pragma handler to be the base of the NoOpenMPHandler and NoOpenACCHandler,
183
// which are identical other than the name given to them, and the diagnostic
184
// emitted.
185
template <diag::kind IgnoredDiag>
186
struct PragmaNoSupportHandler : public PragmaHandler {
187
92
  PragmaNoSupportHandler(StringRef Name) : PragmaHandler(Name) {}
ParsePragma.cpp:(anonymous namespace)::PragmaNoSupportHandler<2009u>::PragmaNoSupportHandler(llvm::StringRef)
Line
Count
Source
187
46
  PragmaNoSupportHandler(StringRef Name) : PragmaHandler(Name) {}
ParsePragma.cpp:(anonymous namespace)::PragmaNoSupportHandler<1975u>::PragmaNoSupportHandler(llvm::StringRef)
Line
Count
Source
187
46
  PragmaNoSupportHandler(StringRef Name) : PragmaHandler(Name) {}
188
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
189
                    Token &FirstToken) override;
190
};
191
192
struct PragmaNoOpenMPHandler
193
    : public PragmaNoSupportHandler<diag::warn_pragma_omp_ignored> {
194
46
  PragmaNoOpenMPHandler() : PragmaNoSupportHandler("omp") {}
195
};
196
197
struct PragmaNoOpenACCHandler
198
    : public PragmaNoSupportHandler<diag::warn_pragma_acc_ignored> {
199
46
  PragmaNoOpenACCHandler() : PragmaNoSupportHandler("acc") {}
200
};
201
202
// A pragma handler to be the base for the OpenMPHandler and OpenACCHandler,
203
// which are identical other than the tokens used for the start/end of a pragma
204
// section, and some diagnostics.
205
template <tok::TokenKind StartTok, tok::TokenKind EndTok,
206
          diag::kind UnexpectedDiag>
207
struct PragmaSupportHandler : public PragmaHandler {
208
0
  PragmaSupportHandler(StringRef Name) : PragmaHandler(Name) {}
Unexecuted instantiation: ParsePragma.cpp:(anonymous namespace)::PragmaSupportHandler<(clang::tok::TokenKind)430, (clang::tok::TokenKind)431, 1647u>::PragmaSupportHandler(llvm::StringRef)
Unexecuted instantiation: ParsePragma.cpp:(anonymous namespace)::PragmaSupportHandler<(clang::tok::TokenKind)432, (clang::tok::TokenKind)433, 1379u>::PragmaSupportHandler(llvm::StringRef)
209
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
210
                    Token &FirstToken) override;
211
};
212
213
struct PragmaOpenMPHandler
214
    : public PragmaSupportHandler<tok::annot_pragma_openmp,
215
                                  tok::annot_pragma_openmp_end,
216
                                  diag::err_omp_unexpected_directive> {
217
0
  PragmaOpenMPHandler() : PragmaSupportHandler("omp") {}
218
};
219
220
struct PragmaOpenACCHandler
221
    : public PragmaSupportHandler<tok::annot_pragma_openacc,
222
                                  tok::annot_pragma_openacc_end,
223
                                  diag::err_acc_unexpected_directive> {
224
0
  PragmaOpenACCHandler() : PragmaSupportHandler("acc") {}
225
};
226
227
/// PragmaCommentHandler - "\#pragma comment ...".
228
struct PragmaCommentHandler : public PragmaHandler {
229
  PragmaCommentHandler(Sema &Actions)
230
46
    : PragmaHandler("comment"), Actions(Actions) {}
231
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
232
                    Token &FirstToken) override;
233
234
private:
235
  Sema &Actions;
236
};
237
238
struct PragmaDetectMismatchHandler : public PragmaHandler {
239
  PragmaDetectMismatchHandler(Sema &Actions)
240
0
    : PragmaHandler("detect_mismatch"), Actions(Actions) {}
241
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
242
                    Token &FirstToken) override;
243
244
private:
245
  Sema &Actions;
246
};
247
248
struct PragmaFloatControlHandler : public PragmaHandler {
249
  PragmaFloatControlHandler(Sema &Actions)
250
46
      : PragmaHandler("float_control") {}
251
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
252
                    Token &FirstToken) override;
253
};
254
255
struct PragmaMSPointersToMembers : public PragmaHandler {
256
0
  explicit PragmaMSPointersToMembers() : PragmaHandler("pointers_to_members") {}
257
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
258
                    Token &FirstToken) override;
259
};
260
261
struct PragmaMSVtorDisp : public PragmaHandler {
262
0
  explicit PragmaMSVtorDisp() : PragmaHandler("vtordisp") {}
263
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
264
                    Token &FirstToken) override;
265
};
266
267
struct PragmaMSPragma : public PragmaHandler {
268
0
  explicit PragmaMSPragma(const char *name) : PragmaHandler(name) {}
269
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
270
                    Token &FirstToken) override;
271
};
272
273
/// PragmaOptimizeHandler - "\#pragma clang optimize on/off".
274
struct PragmaOptimizeHandler : public PragmaHandler {
275
  PragmaOptimizeHandler(Sema &S)
276
46
    : PragmaHandler("optimize"), Actions(S) {}
277
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
278
                    Token &FirstToken) override;
279
280
private:
281
  Sema &Actions;
282
};
283
284
struct PragmaLoopHintHandler : public PragmaHandler {
285
46
  PragmaLoopHintHandler() : PragmaHandler("loop") {}
286
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
287
                    Token &FirstToken) override;
288
};
289
290
struct PragmaUnrollHintHandler : public PragmaHandler {
291
184
  PragmaUnrollHintHandler(const char *name) : PragmaHandler(name) {}
292
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
293
                    Token &FirstToken) override;
294
};
295
296
struct PragmaMSRuntimeChecksHandler : public EmptyPragmaHandler {
297
0
  PragmaMSRuntimeChecksHandler() : EmptyPragmaHandler("runtime_checks") {}
298
};
299
300
struct PragmaMSIntrinsicHandler : public PragmaHandler {
301
0
  PragmaMSIntrinsicHandler() : PragmaHandler("intrinsic") {}
302
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
303
                    Token &FirstToken) override;
304
};
305
306
// "\#pragma fenv_access (on)".
307
struct PragmaMSFenvAccessHandler : public PragmaHandler {
308
0
  PragmaMSFenvAccessHandler() : PragmaHandler("fenv_access") {}
309
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
310
0
                    Token &FirstToken) override {
311
0
    StringRef PragmaName = FirstToken.getIdentifierInfo()->getName();
312
0
    if (!PP.getTargetInfo().hasStrictFP() && !PP.getLangOpts().ExpStrictFP) {
313
0
      PP.Diag(FirstToken.getLocation(), diag::warn_pragma_fp_ignored)
314
0
          << PragmaName;
315
0
      return;
316
0
    }
317
318
0
    Token Tok;
319
0
    PP.Lex(Tok);
320
0
    if (Tok.isNot(tok::l_paren)) {
321
0
      PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen)
322
0
          << PragmaName;
323
0
      return;
324
0
    }
325
0
    PP.Lex(Tok); // Consume the l_paren.
326
0
    if (Tok.isNot(tok::identifier)) {
327
0
      PP.Diag(Tok.getLocation(), diag::warn_pragma_ms_fenv_access);
328
0
      return;
329
0
    }
330
0
    const IdentifierInfo *II = Tok.getIdentifierInfo();
331
0
    tok::OnOffSwitch OOS;
332
0
    if (II->isStr("on")) {
333
0
      OOS = tok::OOS_ON;
334
0
      PP.Lex(Tok);
335
0
    } else if (II->isStr("off")) {
336
0
      OOS = tok::OOS_OFF;
337
0
      PP.Lex(Tok);
338
0
    } else {
339
0
      PP.Diag(Tok.getLocation(), diag::warn_pragma_ms_fenv_access);
340
0
      return;
341
0
    }
342
0
    if (Tok.isNot(tok::r_paren)) {
343
0
      PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen)
344
0
          << PragmaName;
345
0
      return;
346
0
    }
347
0
    PP.Lex(Tok); // Consume the r_paren.
348
349
0
    if (Tok.isNot(tok::eod)) {
350
0
      PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
351
0
          << PragmaName;
352
0
      return;
353
0
    }
354
355
0
    MutableArrayRef<Token> Toks(
356
0
        PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
357
0
    Toks[0].startToken();
358
0
    Toks[0].setKind(tok::annot_pragma_fenv_access_ms);
359
0
    Toks[0].setLocation(FirstToken.getLocation());
360
0
    Toks[0].setAnnotationEndLoc(Tok.getLocation());
361
0
    Toks[0].setAnnotationValue(
362
0
        reinterpret_cast<void*>(static_cast<uintptr_t>(OOS)));
363
0
    PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
364
0
                        /*IsReinject=*/false);
365
0
  }
366
};
367
368
struct PragmaForceCUDAHostDeviceHandler : public PragmaHandler {
369
  PragmaForceCUDAHostDeviceHandler(Sema &Actions)
370
0
      : PragmaHandler("force_cuda_host_device"), Actions(Actions) {}
371
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
372
                    Token &FirstToken) override;
373
374
private:
375
  Sema &Actions;
376
};
377
378
/// PragmaAttributeHandler - "\#pragma clang attribute ...".
379
struct PragmaAttributeHandler : public PragmaHandler {
380
  PragmaAttributeHandler(AttributeFactory &AttrFactory)
381
46
      : PragmaHandler("attribute"), AttributesForPragmaAttribute(AttrFactory) {}
382
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
383
                    Token &FirstToken) override;
384
385
  /// A pool of attributes that were parsed in \#pragma clang attribute.
386
  ParsedAttributes AttributesForPragmaAttribute;
387
};
388
389
struct PragmaMaxTokensHereHandler : public PragmaHandler {
390
46
  PragmaMaxTokensHereHandler() : PragmaHandler("max_tokens_here") {}
391
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
392
                    Token &FirstToken) override;
393
};
394
395
struct PragmaMaxTokensTotalHandler : public PragmaHandler {
396
46
  PragmaMaxTokensTotalHandler() : PragmaHandler("max_tokens_total") {}
397
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
398
                    Token &FirstToken) override;
399
};
400
401
struct PragmaRISCVHandler : public PragmaHandler {
402
  PragmaRISCVHandler(Sema &Actions)
403
0
      : PragmaHandler("riscv"), Actions(Actions) {}
404
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
405
                    Token &FirstToken) override;
406
407
private:
408
  Sema &Actions;
409
};
410
411
0
void markAsReinjectedForRelexing(llvm::MutableArrayRef<clang::Token> Toks) {
412
0
  for (auto &T : Toks)
413
0
    T.setFlag(clang::Token::IsReinjected);
414
0
}
415
}  // end namespace
416
417
46
void Parser::initializePragmaHandlers() {
418
46
  AlignHandler = std::make_unique<PragmaAlignHandler>();
419
46
  PP.AddPragmaHandler(AlignHandler.get());
420
421
46
  GCCVisibilityHandler = std::make_unique<PragmaGCCVisibilityHandler>();
422
46
  PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
423
424
46
  OptionsHandler = std::make_unique<PragmaOptionsHandler>();
425
46
  PP.AddPragmaHandler(OptionsHandler.get());
426
427
46
  PackHandler = std::make_unique<PragmaPackHandler>();
428
46
  PP.AddPragmaHandler(PackHandler.get());
429
430
46
  MSStructHandler = std::make_unique<PragmaMSStructHandler>();
431
46
  PP.AddPragmaHandler(MSStructHandler.get());
432
433
46
  UnusedHandler = std::make_unique<PragmaUnusedHandler>();
434
46
  PP.AddPragmaHandler(UnusedHandler.get());
435
436
46
  WeakHandler = std::make_unique<PragmaWeakHandler>();
437
46
  PP.AddPragmaHandler(WeakHandler.get());
438
439
46
  RedefineExtnameHandler = std::make_unique<PragmaRedefineExtnameHandler>();
440
46
  PP.AddPragmaHandler(RedefineExtnameHandler.get());
441
442
46
  FPContractHandler = std::make_unique<PragmaFPContractHandler>();
443
46
  PP.AddPragmaHandler("STDC", FPContractHandler.get());
444
445
46
  STDCFenvAccessHandler = std::make_unique<PragmaSTDC_FENV_ACCESSHandler>();
446
46
  PP.AddPragmaHandler("STDC", STDCFenvAccessHandler.get());
447
448
46
  STDCFenvRoundHandler = std::make_unique<PragmaSTDC_FENV_ROUNDHandler>();
449
46
  PP.AddPragmaHandler("STDC", STDCFenvRoundHandler.get());
450
451
46
  STDCCXLIMITHandler = std::make_unique<PragmaSTDC_CX_LIMITED_RANGEHandler>();
452
46
  PP.AddPragmaHandler("STDC", STDCCXLIMITHandler.get());
453
454
46
  STDCUnknownHandler = std::make_unique<PragmaSTDC_UnknownHandler>();
455
46
  PP.AddPragmaHandler("STDC", STDCUnknownHandler.get());
456
457
46
  PCSectionHandler = std::make_unique<PragmaClangSectionHandler>(Actions);
458
46
  PP.AddPragmaHandler("clang", PCSectionHandler.get());
459
460
46
  if (getLangOpts().OpenCL) {
461
0
    OpenCLExtensionHandler = std::make_unique<PragmaOpenCLExtensionHandler>();
462
0
    PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
463
464
0
    PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
465
0
  }
466
46
  if (getLangOpts().OpenMP)
467
0
    OpenMPHandler = std::make_unique<PragmaOpenMPHandler>();
468
46
  else
469
46
    OpenMPHandler = std::make_unique<PragmaNoOpenMPHandler>();
470
46
  PP.AddPragmaHandler(OpenMPHandler.get());
471
472
46
  if (getLangOpts().OpenACC)
473
0
    OpenACCHandler = std::make_unique<PragmaOpenACCHandler>();
474
46
  else
475
46
    OpenACCHandler = std::make_unique<PragmaNoOpenACCHandler>();
476
46
  PP.AddPragmaHandler(OpenACCHandler.get());
477
478
46
  if (getLangOpts().MicrosoftExt ||
479
46
      getTargetInfo().getTriple().isOSBinFormatELF()) {
480
46
    MSCommentHandler = std::make_unique<PragmaCommentHandler>(Actions);
481
46
    PP.AddPragmaHandler(MSCommentHandler.get());
482
46
  }
483
484
46
  FloatControlHandler = std::make_unique<PragmaFloatControlHandler>(Actions);
485
46
  PP.AddPragmaHandler(FloatControlHandler.get());
486
46
  if (getLangOpts().MicrosoftExt) {
487
0
    MSDetectMismatchHandler =
488
0
        std::make_unique<PragmaDetectMismatchHandler>(Actions);
489
0
    PP.AddPragmaHandler(MSDetectMismatchHandler.get());
490
0
    MSPointersToMembers = std::make_unique<PragmaMSPointersToMembers>();
491
0
    PP.AddPragmaHandler(MSPointersToMembers.get());
492
0
    MSVtorDisp = std::make_unique<PragmaMSVtorDisp>();
493
0
    PP.AddPragmaHandler(MSVtorDisp.get());
494
0
    MSInitSeg = std::make_unique<PragmaMSPragma>("init_seg");
495
0
    PP.AddPragmaHandler(MSInitSeg.get());
496
0
    MSDataSeg = std::make_unique<PragmaMSPragma>("data_seg");
497
0
    PP.AddPragmaHandler(MSDataSeg.get());
498
0
    MSBSSSeg = std::make_unique<PragmaMSPragma>("bss_seg");
499
0
    PP.AddPragmaHandler(MSBSSSeg.get());
500
0
    MSConstSeg = std::make_unique<PragmaMSPragma>("const_seg");
501
0
    PP.AddPragmaHandler(MSConstSeg.get());
502
0
    MSCodeSeg = std::make_unique<PragmaMSPragma>("code_seg");
503
0
    PP.AddPragmaHandler(MSCodeSeg.get());
504
0
    MSSection = std::make_unique<PragmaMSPragma>("section");
505
0
    PP.AddPragmaHandler(MSSection.get());
506
0
    MSStrictGuardStackCheck =
507
0
        std::make_unique<PragmaMSPragma>("strict_gs_check");
508
0
    PP.AddPragmaHandler(MSStrictGuardStackCheck.get());
509
0
    MSFunction = std::make_unique<PragmaMSPragma>("function");
510
0
    PP.AddPragmaHandler(MSFunction.get());
511
0
    MSAllocText = std::make_unique<PragmaMSPragma>("alloc_text");
512
0
    PP.AddPragmaHandler(MSAllocText.get());
513
0
    MSOptimize = std::make_unique<PragmaMSPragma>("optimize");
514
0
    PP.AddPragmaHandler(MSOptimize.get());
515
0
    MSRuntimeChecks = std::make_unique<PragmaMSRuntimeChecksHandler>();
516
0
    PP.AddPragmaHandler(MSRuntimeChecks.get());
517
0
    MSIntrinsic = std::make_unique<PragmaMSIntrinsicHandler>();
518
0
    PP.AddPragmaHandler(MSIntrinsic.get());
519
0
    MSFenvAccess = std::make_unique<PragmaMSFenvAccessHandler>();
520
0
    PP.AddPragmaHandler(MSFenvAccess.get());
521
0
  }
522
523
46
  if (getLangOpts().CUDA) {
524
0
    CUDAForceHostDeviceHandler =
525
0
        std::make_unique<PragmaForceCUDAHostDeviceHandler>(Actions);
526
0
    PP.AddPragmaHandler("clang", CUDAForceHostDeviceHandler.get());
527
0
  }
528
529
46
  OptimizeHandler = std::make_unique<PragmaOptimizeHandler>(Actions);
530
46
  PP.AddPragmaHandler("clang", OptimizeHandler.get());
531
532
46
  LoopHintHandler = std::make_unique<PragmaLoopHintHandler>();
533
46
  PP.AddPragmaHandler("clang", LoopHintHandler.get());
534
535
46
  UnrollHintHandler = std::make_unique<PragmaUnrollHintHandler>("unroll");
536
46
  PP.AddPragmaHandler(UnrollHintHandler.get());
537
46
  PP.AddPragmaHandler("GCC", UnrollHintHandler.get());
538
539
46
  NoUnrollHintHandler = std::make_unique<PragmaUnrollHintHandler>("nounroll");
540
46
  PP.AddPragmaHandler(NoUnrollHintHandler.get());
541
46
  PP.AddPragmaHandler("GCC", NoUnrollHintHandler.get());
542
543
46
  UnrollAndJamHintHandler =
544
46
      std::make_unique<PragmaUnrollHintHandler>("unroll_and_jam");
545
46
  PP.AddPragmaHandler(UnrollAndJamHintHandler.get());
546
547
46
  NoUnrollAndJamHintHandler =
548
46
      std::make_unique<PragmaUnrollHintHandler>("nounroll_and_jam");
549
46
  PP.AddPragmaHandler(NoUnrollAndJamHintHandler.get());
550
551
46
  FPHandler = std::make_unique<PragmaFPHandler>();
552
46
  PP.AddPragmaHandler("clang", FPHandler.get());
553
554
46
  AttributePragmaHandler =
555
46
      std::make_unique<PragmaAttributeHandler>(AttrFactory);
556
46
  PP.AddPragmaHandler("clang", AttributePragmaHandler.get());
557
558
46
  MaxTokensHerePragmaHandler = std::make_unique<PragmaMaxTokensHereHandler>();
559
46
  PP.AddPragmaHandler("clang", MaxTokensHerePragmaHandler.get());
560
561
46
  MaxTokensTotalPragmaHandler = std::make_unique<PragmaMaxTokensTotalHandler>();
562
46
  PP.AddPragmaHandler("clang", MaxTokensTotalPragmaHandler.get());
563
564
46
  if (getTargetInfo().getTriple().isRISCV()) {
565
0
    RISCVPragmaHandler = std::make_unique<PragmaRISCVHandler>(Actions);
566
0
    PP.AddPragmaHandler("clang", RISCVPragmaHandler.get());
567
0
  }
568
46
}
569
570
46
void Parser::resetPragmaHandlers() {
571
  // Remove the pragma handlers we installed.
572
46
  PP.RemovePragmaHandler(AlignHandler.get());
573
46
  AlignHandler.reset();
574
46
  PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
575
46
  GCCVisibilityHandler.reset();
576
46
  PP.RemovePragmaHandler(OptionsHandler.get());
577
46
  OptionsHandler.reset();
578
46
  PP.RemovePragmaHandler(PackHandler.get());
579
46
  PackHandler.reset();
580
46
  PP.RemovePragmaHandler(MSStructHandler.get());
581
46
  MSStructHandler.reset();
582
46
  PP.RemovePragmaHandler(UnusedHandler.get());
583
46
  UnusedHandler.reset();
584
46
  PP.RemovePragmaHandler(WeakHandler.get());
585
46
  WeakHandler.reset();
586
46
  PP.RemovePragmaHandler(RedefineExtnameHandler.get());
587
46
  RedefineExtnameHandler.reset();
588
589
46
  if (getLangOpts().OpenCL) {
590
0
    PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
591
0
    OpenCLExtensionHandler.reset();
592
0
    PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
593
0
  }
594
46
  PP.RemovePragmaHandler(OpenMPHandler.get());
595
46
  OpenMPHandler.reset();
596
597
46
  PP.RemovePragmaHandler(OpenACCHandler.get());
598
46
  OpenACCHandler.reset();
599
600
46
  if (getLangOpts().MicrosoftExt ||
601
46
      getTargetInfo().getTriple().isOSBinFormatELF()) {
602
46
    PP.RemovePragmaHandler(MSCommentHandler.get());
603
46
    MSCommentHandler.reset();
604
46
  }
605
606
46
  PP.RemovePragmaHandler("clang", PCSectionHandler.get());
607
46
  PCSectionHandler.reset();
608
609
46
  PP.RemovePragmaHandler(FloatControlHandler.get());
610
46
  FloatControlHandler.reset();
611
46
  if (getLangOpts().MicrosoftExt) {
612
0
    PP.RemovePragmaHandler(MSDetectMismatchHandler.get());
613
0
    MSDetectMismatchHandler.reset();
614
0
    PP.RemovePragmaHandler(MSPointersToMembers.get());
615
0
    MSPointersToMembers.reset();
616
0
    PP.RemovePragmaHandler(MSVtorDisp.get());
617
0
    MSVtorDisp.reset();
618
0
    PP.RemovePragmaHandler(MSInitSeg.get());
619
0
    MSInitSeg.reset();
620
0
    PP.RemovePragmaHandler(MSDataSeg.get());
621
0
    MSDataSeg.reset();
622
0
    PP.RemovePragmaHandler(MSBSSSeg.get());
623
0
    MSBSSSeg.reset();
624
0
    PP.RemovePragmaHandler(MSConstSeg.get());
625
0
    MSConstSeg.reset();
626
0
    PP.RemovePragmaHandler(MSCodeSeg.get());
627
0
    MSCodeSeg.reset();
628
0
    PP.RemovePragmaHandler(MSSection.get());
629
0
    MSSection.reset();
630
0
    PP.RemovePragmaHandler(MSStrictGuardStackCheck.get());
631
0
    MSStrictGuardStackCheck.reset();
632
0
    PP.RemovePragmaHandler(MSFunction.get());
633
0
    MSFunction.reset();
634
0
    PP.RemovePragmaHandler(MSAllocText.get());
635
0
    MSAllocText.reset();
636
0
    PP.RemovePragmaHandler(MSRuntimeChecks.get());
637
0
    MSRuntimeChecks.reset();
638
0
    PP.RemovePragmaHandler(MSIntrinsic.get());
639
0
    MSIntrinsic.reset();
640
0
    PP.RemovePragmaHandler(MSOptimize.get());
641
0
    MSOptimize.reset();
642
0
    PP.RemovePragmaHandler(MSFenvAccess.get());
643
0
    MSFenvAccess.reset();
644
0
  }
645
646
46
  if (getLangOpts().CUDA) {
647
0
    PP.RemovePragmaHandler("clang", CUDAForceHostDeviceHandler.get());
648
0
    CUDAForceHostDeviceHandler.reset();
649
0
  }
650
651
46
  PP.RemovePragmaHandler("STDC", FPContractHandler.get());
652
46
  FPContractHandler.reset();
653
654
46
  PP.RemovePragmaHandler("STDC", STDCFenvAccessHandler.get());
655
46
  STDCFenvAccessHandler.reset();
656
657
46
  PP.RemovePragmaHandler("STDC", STDCFenvRoundHandler.get());
658
46
  STDCFenvRoundHandler.reset();
659
660
46
  PP.RemovePragmaHandler("STDC", STDCCXLIMITHandler.get());
661
46
  STDCCXLIMITHandler.reset();
662
663
46
  PP.RemovePragmaHandler("STDC", STDCUnknownHandler.get());
664
46
  STDCUnknownHandler.reset();
665
666
46
  PP.RemovePragmaHandler("clang", OptimizeHandler.get());
667
46
  OptimizeHandler.reset();
668
669
46
  PP.RemovePragmaHandler("clang", LoopHintHandler.get());
670
46
  LoopHintHandler.reset();
671
672
46
  PP.RemovePragmaHandler(UnrollHintHandler.get());
673
46
  PP.RemovePragmaHandler("GCC", UnrollHintHandler.get());
674
46
  UnrollHintHandler.reset();
675
676
46
  PP.RemovePragmaHandler(NoUnrollHintHandler.get());
677
46
  PP.RemovePragmaHandler("GCC", NoUnrollHintHandler.get());
678
46
  NoUnrollHintHandler.reset();
679
680
46
  PP.RemovePragmaHandler(UnrollAndJamHintHandler.get());
681
46
  UnrollAndJamHintHandler.reset();
682
683
46
  PP.RemovePragmaHandler(NoUnrollAndJamHintHandler.get());
684
46
  NoUnrollAndJamHintHandler.reset();
685
686
46
  PP.RemovePragmaHandler("clang", FPHandler.get());
687
46
  FPHandler.reset();
688
689
46
  PP.RemovePragmaHandler("clang", AttributePragmaHandler.get());
690
46
  AttributePragmaHandler.reset();
691
692
46
  PP.RemovePragmaHandler("clang", MaxTokensHerePragmaHandler.get());
693
46
  MaxTokensHerePragmaHandler.reset();
694
695
46
  PP.RemovePragmaHandler("clang", MaxTokensTotalPragmaHandler.get());
696
46
  MaxTokensTotalPragmaHandler.reset();
697
698
46
  if (getTargetInfo().getTriple().isRISCV()) {
699
0
    PP.RemovePragmaHandler("clang", RISCVPragmaHandler.get());
700
0
    RISCVPragmaHandler.reset();
701
0
  }
702
46
}
703
704
/// Handle the annotation token produced for #pragma unused(...)
705
///
706
/// Each annot_pragma_unused is followed by the argument token so e.g.
707
/// "#pragma unused(x,y)" becomes:
708
/// annot_pragma_unused 'x' annot_pragma_unused 'y'
709
0
void Parser::HandlePragmaUnused() {
710
0
  assert(Tok.is(tok::annot_pragma_unused));
711
0
  SourceLocation UnusedLoc = ConsumeAnnotationToken();
712
0
  Actions.ActOnPragmaUnused(Tok, getCurScope(), UnusedLoc);
713
0
  ConsumeToken(); // The argument token.
714
0
}
715
716
0
void Parser::HandlePragmaVisibility() {
717
0
  assert(Tok.is(tok::annot_pragma_vis));
718
0
  const IdentifierInfo *VisType =
719
0
    static_cast<IdentifierInfo *>(Tok.getAnnotationValue());
720
0
  SourceLocation VisLoc = ConsumeAnnotationToken();
721
0
  Actions.ActOnPragmaVisibility(VisType, VisLoc);
722
0
}
723
724
0
void Parser::HandlePragmaPack() {
725
0
  assert(Tok.is(tok::annot_pragma_pack));
726
0
  Sema::PragmaPackInfo *Info =
727
0
      static_cast<Sema::PragmaPackInfo *>(Tok.getAnnotationValue());
728
0
  SourceLocation PragmaLoc = Tok.getLocation();
729
0
  ExprResult Alignment;
730
0
  if (Info->Alignment.is(tok::numeric_constant)) {
731
0
    Alignment = Actions.ActOnNumericConstant(Info->Alignment);
732
0
    if (Alignment.isInvalid()) {
733
0
      ConsumeAnnotationToken();
734
0
      return;
735
0
    }
736
0
  }
737
0
  Actions.ActOnPragmaPack(PragmaLoc, Info->Action, Info->SlotLabel,
738
0
                          Alignment.get());
739
  // Consume the token after processing the pragma to enable pragma-specific
740
  // #include warnings.
741
0
  ConsumeAnnotationToken();
742
0
}
743
744
0
void Parser::HandlePragmaMSStruct() {
745
0
  assert(Tok.is(tok::annot_pragma_msstruct));
746
0
  PragmaMSStructKind Kind = static_cast<PragmaMSStructKind>(
747
0
      reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
748
0
  Actions.ActOnPragmaMSStruct(Kind);
749
0
  ConsumeAnnotationToken();
750
0
}
751
752
0
void Parser::HandlePragmaAlign() {
753
0
  assert(Tok.is(tok::annot_pragma_align));
754
0
  Sema::PragmaOptionsAlignKind Kind =
755
0
    static_cast<Sema::PragmaOptionsAlignKind>(
756
0
    reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
757
0
  Actions.ActOnPragmaOptionsAlign(Kind, Tok.getLocation());
758
  // Consume the token after processing the pragma to enable pragma-specific
759
  // #include warnings.
760
0
  ConsumeAnnotationToken();
761
0
}
762
763
0
void Parser::HandlePragmaDump() {
764
0
  assert(Tok.is(tok::annot_pragma_dump));
765
0
  ConsumeAnnotationToken();
766
0
  if (Tok.is(tok::eod)) {
767
0
    PP.Diag(Tok, diag::warn_pragma_debug_missing_argument) << "dump";
768
0
  } else if (NextToken().is(tok::eod)) {
769
0
    if (Tok.isNot(tok::identifier)) {
770
0
      PP.Diag(Tok, diag::warn_pragma_debug_unexpected_argument);
771
0
      ConsumeAnyToken();
772
0
      ExpectAndConsume(tok::eod);
773
0
      return;
774
0
    }
775
0
    IdentifierInfo *II = Tok.getIdentifierInfo();
776
0
    Actions.ActOnPragmaDump(getCurScope(), Tok.getLocation(), II);
777
0
    ConsumeToken();
778
0
  } else {
779
0
    SourceLocation StartLoc = Tok.getLocation();
780
0
    EnterExpressionEvaluationContext Ctx(
781
0
      Actions, Sema::ExpressionEvaluationContext::Unevaluated);
782
0
    ExprResult E = ParseExpression();
783
0
    if (!E.isUsable() || E.get()->containsErrors()) {
784
      // Diagnostics were emitted during parsing. No action needed.
785
0
    } else if (E.get()->getDependence() != ExprDependence::None) {
786
0
      PP.Diag(StartLoc, diag::warn_pragma_debug_dependent_argument)
787
0
        << E.get()->isTypeDependent()
788
0
        << SourceRange(StartLoc, Tok.getLocation());
789
0
    } else {
790
0
      Actions.ActOnPragmaDump(E.get());
791
0
    }
792
0
    SkipUntil(tok::eod, StopBeforeMatch);
793
0
  }
794
0
  ExpectAndConsume(tok::eod);
795
0
}
796
797
0
void Parser::HandlePragmaWeak() {
798
0
  assert(Tok.is(tok::annot_pragma_weak));
799
0
  SourceLocation PragmaLoc = ConsumeAnnotationToken();
800
0
  Actions.ActOnPragmaWeakID(Tok.getIdentifierInfo(), PragmaLoc,
801
0
                            Tok.getLocation());
802
0
  ConsumeToken(); // The weak name.
803
0
}
804
805
0
void Parser::HandlePragmaWeakAlias() {
806
0
  assert(Tok.is(tok::annot_pragma_weakalias));
807
0
  SourceLocation PragmaLoc = ConsumeAnnotationToken();
808
0
  IdentifierInfo *WeakName = Tok.getIdentifierInfo();
809
0
  SourceLocation WeakNameLoc = Tok.getLocation();
810
0
  ConsumeToken();
811
0
  IdentifierInfo *AliasName = Tok.getIdentifierInfo();
812
0
  SourceLocation AliasNameLoc = Tok.getLocation();
813
0
  ConsumeToken();
814
0
  Actions.ActOnPragmaWeakAlias(WeakName, AliasName, PragmaLoc,
815
0
                               WeakNameLoc, AliasNameLoc);
816
817
0
}
818
819
0
void Parser::HandlePragmaRedefineExtname() {
820
0
  assert(Tok.is(tok::annot_pragma_redefine_extname));
821
0
  SourceLocation RedefLoc = ConsumeAnnotationToken();
822
0
  IdentifierInfo *RedefName = Tok.getIdentifierInfo();
823
0
  SourceLocation RedefNameLoc = Tok.getLocation();
824
0
  ConsumeToken();
825
0
  IdentifierInfo *AliasName = Tok.getIdentifierInfo();
826
0
  SourceLocation AliasNameLoc = Tok.getLocation();
827
0
  ConsumeToken();
828
0
  Actions.ActOnPragmaRedefineExtname(RedefName, AliasName, RedefLoc,
829
0
                                     RedefNameLoc, AliasNameLoc);
830
0
}
831
832
0
void Parser::HandlePragmaFPContract() {
833
0
  assert(Tok.is(tok::annot_pragma_fp_contract));
834
0
  tok::OnOffSwitch OOS =
835
0
    static_cast<tok::OnOffSwitch>(
836
0
    reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
837
838
0
  LangOptions::FPModeKind FPC;
839
0
  switch (OOS) {
840
0
  case tok::OOS_ON:
841
0
    FPC = LangOptions::FPM_On;
842
0
    break;
843
0
  case tok::OOS_OFF:
844
0
    FPC = LangOptions::FPM_Off;
845
0
    break;
846
0
  case tok::OOS_DEFAULT:
847
0
    FPC = getLangOpts().getDefaultFPContractMode();
848
0
    break;
849
0
  }
850
851
0
  SourceLocation PragmaLoc = ConsumeAnnotationToken();
852
0
  Actions.ActOnPragmaFPContract(PragmaLoc, FPC);
853
0
}
854
855
0
void Parser::HandlePragmaFloatControl() {
856
0
  assert(Tok.is(tok::annot_pragma_float_control));
857
858
  // The value that is held on the PragmaFloatControlStack encodes
859
  // the PragmaFloatControl kind and the MSStackAction kind
860
  // into a single 32-bit word. The MsStackAction is the high 16 bits
861
  // and the FloatControl is the lower 16 bits. Use shift and bit-and
862
  // to decode the parts.
863
0
  uintptr_t Value = reinterpret_cast<uintptr_t>(Tok.getAnnotationValue());
864
0
  Sema::PragmaMsStackAction Action =
865
0
      static_cast<Sema::PragmaMsStackAction>((Value >> 16) & 0xFFFF);
866
0
  PragmaFloatControlKind Kind = PragmaFloatControlKind(Value & 0xFFFF);
867
0
  SourceLocation PragmaLoc = ConsumeAnnotationToken();
868
0
  Actions.ActOnPragmaFloatControl(PragmaLoc, Action, Kind);
869
0
}
870
871
0
void Parser::HandlePragmaFEnvAccess() {
872
0
  assert(Tok.is(tok::annot_pragma_fenv_access) ||
873
0
         Tok.is(tok::annot_pragma_fenv_access_ms));
874
0
  tok::OnOffSwitch OOS =
875
0
    static_cast<tok::OnOffSwitch>(
876
0
    reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
877
878
0
  bool IsEnabled;
879
0
  switch (OOS) {
880
0
  case tok::OOS_ON:
881
0
    IsEnabled = true;
882
0
    break;
883
0
  case tok::OOS_OFF:
884
0
    IsEnabled = false;
885
0
    break;
886
0
  case tok::OOS_DEFAULT: // FIXME: Add this cli option when it makes sense.
887
0
    IsEnabled = false;
888
0
    break;
889
0
  }
890
891
0
  SourceLocation PragmaLoc = ConsumeAnnotationToken();
892
0
  Actions.ActOnPragmaFEnvAccess(PragmaLoc, IsEnabled);
893
0
}
894
895
0
void Parser::HandlePragmaFEnvRound() {
896
0
  assert(Tok.is(tok::annot_pragma_fenv_round));
897
0
  auto RM = static_cast<llvm::RoundingMode>(
898
0
      reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
899
900
0
  SourceLocation PragmaLoc = ConsumeAnnotationToken();
901
0
  Actions.ActOnPragmaFEnvRound(PragmaLoc, RM);
902
0
}
903
904
0
void Parser::HandlePragmaCXLimitedRange() {
905
0
  assert(Tok.is(tok::annot_pragma_cx_limited_range));
906
0
  tok::OnOffSwitch OOS = static_cast<tok::OnOffSwitch>(
907
0
      reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
908
909
0
  LangOptions::ComplexRangeKind Range;
910
0
  switch (OOS) {
911
0
  case tok::OOS_ON:
912
0
    Range = LangOptions::CX_Limited;
913
0
    break;
914
0
  case tok::OOS_OFF:
915
0
    Range = LangOptions::CX_Full;
916
0
    break;
917
0
  case tok::OOS_DEFAULT:
918
    // According to ISO C99 standard chapter 7.3.4, the default value
919
    // for the pragma is ``off'. -fcx-limited-range and -fcx-fortran-rules
920
    // control the default value of these pragmas.
921
0
    Range = getLangOpts().getComplexRange();
922
0
    break;
923
0
  }
924
925
0
  SourceLocation PragmaLoc = ConsumeAnnotationToken();
926
0
  Actions.ActOnPragmaCXLimitedRange(PragmaLoc, Range);
927
0
}
928
929
StmtResult Parser::HandlePragmaCaptured()
930
0
{
931
0
  assert(Tok.is(tok::annot_pragma_captured));
932
0
  ConsumeAnnotationToken();
933
934
0
  if (Tok.isNot(tok::l_brace)) {
935
0
    PP.Diag(Tok, diag::err_expected) << tok::l_brace;
936
0
    return StmtError();
937
0
  }
938
939
0
  SourceLocation Loc = Tok.getLocation();
940
941
0
  ParseScope CapturedRegionScope(this, Scope::FnScope | Scope::DeclScope |
942
0
                                           Scope::CompoundStmtScope);
943
0
  Actions.ActOnCapturedRegionStart(Loc, getCurScope(), CR_Default,
944
0
                                   /*NumParams=*/1);
945
946
0
  StmtResult R = ParseCompoundStatement();
947
0
  CapturedRegionScope.Exit();
948
949
0
  if (R.isInvalid()) {
950
0
    Actions.ActOnCapturedRegionError();
951
0
    return StmtError();
952
0
  }
953
954
0
  return Actions.ActOnCapturedRegionEnd(R.get());
955
0
}
956
957
namespace {
958
  enum OpenCLExtState : char {
959
    Disable, Enable, Begin, End
960
  };
961
  typedef std::pair<const IdentifierInfo *, OpenCLExtState> OpenCLExtData;
962
}
963
964
0
void Parser::HandlePragmaOpenCLExtension() {
965
0
  assert(Tok.is(tok::annot_pragma_opencl_extension));
966
0
  OpenCLExtData *Data = static_cast<OpenCLExtData*>(Tok.getAnnotationValue());
967
0
  auto State = Data->second;
968
0
  auto Ident = Data->first;
969
0
  SourceLocation NameLoc = Tok.getLocation();
970
0
  ConsumeAnnotationToken();
971
972
0
  auto &Opt = Actions.getOpenCLOptions();
973
0
  auto Name = Ident->getName();
974
  // OpenCL 1.1 9.1: "The all variant sets the behavior for all extensions,
975
  // overriding all previously issued extension directives, but only if the
976
  // behavior is set to disable."
977
0
  if (Name == "all") {
978
0
    if (State == Disable)
979
0
      Opt.disableAll();
980
0
    else
981
0
      PP.Diag(NameLoc, diag::warn_pragma_expected_predicate) << 1;
982
0
  } else if (State == Begin) {
983
0
    if (!Opt.isKnown(Name) || !Opt.isSupported(Name, getLangOpts())) {
984
0
      Opt.support(Name);
985
      // FIXME: Default behavior of the extension pragma is not defined.
986
      // Therefore, it should never be added by default.
987
0
      Opt.acceptsPragma(Name);
988
0
    }
989
0
  } else if (State == End) {
990
    // There is no behavior for this directive. We only accept this for
991
    // backward compatibility.
992
0
  } else if (!Opt.isKnown(Name) || !Opt.isWithPragma(Name))
993
0
    PP.Diag(NameLoc, diag::warn_pragma_unknown_extension) << Ident;
994
0
  else if (Opt.isSupportedExtension(Name, getLangOpts()))
995
0
    Opt.enable(Name, State == Enable);
996
0
  else if (Opt.isSupportedCoreOrOptionalCore(Name, getLangOpts()))
997
0
    PP.Diag(NameLoc, diag::warn_pragma_extension_is_core) << Ident;
998
0
  else
999
0
    PP.Diag(NameLoc, diag::warn_pragma_unsupported_extension) << Ident;
1000
0
}
1001
1002
0
void Parser::HandlePragmaMSPointersToMembers() {
1003
0
  assert(Tok.is(tok::annot_pragma_ms_pointers_to_members));
1004
0
  LangOptions::PragmaMSPointersToMembersKind RepresentationMethod =
1005
0
      static_cast<LangOptions::PragmaMSPointersToMembersKind>(
1006
0
          reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
1007
0
  SourceLocation PragmaLoc = ConsumeAnnotationToken();
1008
0
  Actions.ActOnPragmaMSPointersToMembers(RepresentationMethod, PragmaLoc);
1009
0
}
1010
1011
0
void Parser::HandlePragmaMSVtorDisp() {
1012
0
  assert(Tok.is(tok::annot_pragma_ms_vtordisp));
1013
0
  uintptr_t Value = reinterpret_cast<uintptr_t>(Tok.getAnnotationValue());
1014
0
  Sema::PragmaMsStackAction Action =
1015
0
      static_cast<Sema::PragmaMsStackAction>((Value >> 16) & 0xFFFF);
1016
0
  MSVtorDispMode Mode = MSVtorDispMode(Value & 0xFFFF);
1017
0
  SourceLocation PragmaLoc = ConsumeAnnotationToken();
1018
0
  Actions.ActOnPragmaMSVtorDisp(Action, PragmaLoc, Mode);
1019
0
}
1020
1021
0
void Parser::HandlePragmaMSPragma() {
1022
0
  assert(Tok.is(tok::annot_pragma_ms_pragma));
1023
  // Grab the tokens out of the annotation and enter them into the stream.
1024
0
  auto TheTokens =
1025
0
      (std::pair<std::unique_ptr<Token[]>, size_t> *)Tok.getAnnotationValue();
1026
0
  PP.EnterTokenStream(std::move(TheTokens->first), TheTokens->second, true,
1027
0
                      /*IsReinject=*/true);
1028
0
  SourceLocation PragmaLocation = ConsumeAnnotationToken();
1029
0
  assert(Tok.isAnyIdentifier());
1030
0
  StringRef PragmaName = Tok.getIdentifierInfo()->getName();
1031
0
  PP.Lex(Tok); // pragma kind
1032
1033
  // Figure out which #pragma we're dealing with.  The switch has no default
1034
  // because lex shouldn't emit the annotation token for unrecognized pragmas.
1035
0
  typedef bool (Parser::*PragmaHandler)(StringRef, SourceLocation);
1036
0
  PragmaHandler Handler =
1037
0
      llvm::StringSwitch<PragmaHandler>(PragmaName)
1038
0
          .Case("data_seg", &Parser::HandlePragmaMSSegment)
1039
0
          .Case("bss_seg", &Parser::HandlePragmaMSSegment)
1040
0
          .Case("const_seg", &Parser::HandlePragmaMSSegment)
1041
0
          .Case("code_seg", &Parser::HandlePragmaMSSegment)
1042
0
          .Case("section", &Parser::HandlePragmaMSSection)
1043
0
          .Case("init_seg", &Parser::HandlePragmaMSInitSeg)
1044
0
          .Case("strict_gs_check", &Parser::HandlePragmaMSStrictGuardStackCheck)
1045
0
          .Case("function", &Parser::HandlePragmaMSFunction)
1046
0
          .Case("alloc_text", &Parser::HandlePragmaMSAllocText)
1047
0
          .Case("optimize", &Parser::HandlePragmaMSOptimize);
1048
1049
0
  if (!(this->*Handler)(PragmaName, PragmaLocation)) {
1050
    // Pragma handling failed, and has been diagnosed.  Slurp up the tokens
1051
    // until eof (really end of line) to prevent follow-on errors.
1052
0
    while (Tok.isNot(tok::eof))
1053
0
      PP.Lex(Tok);
1054
0
    PP.Lex(Tok);
1055
0
  }
1056
0
}
1057
1058
bool Parser::HandlePragmaMSSection(StringRef PragmaName,
1059
0
                                   SourceLocation PragmaLocation) {
1060
0
  if (Tok.isNot(tok::l_paren)) {
1061
0
    PP.Diag(PragmaLocation, diag::warn_pragma_expected_lparen) << PragmaName;
1062
0
    return false;
1063
0
  }
1064
0
  PP.Lex(Tok); // (
1065
  // Parsing code for pragma section
1066
0
  if (Tok.isNot(tok::string_literal)) {
1067
0
    PP.Diag(PragmaLocation, diag::warn_pragma_expected_section_name)
1068
0
        << PragmaName;
1069
0
    return false;
1070
0
  }
1071
0
  ExprResult StringResult = ParseStringLiteralExpression();
1072
0
  if (StringResult.isInvalid())
1073
0
    return false; // Already diagnosed.
1074
0
  StringLiteral *SegmentName = cast<StringLiteral>(StringResult.get());
1075
0
  if (SegmentName->getCharByteWidth() != 1) {
1076
0
    PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
1077
0
        << PragmaName;
1078
0
    return false;
1079
0
  }
1080
0
  int SectionFlags = ASTContext::PSF_Read;
1081
0
  bool SectionFlagsAreDefault = true;
1082
0
  while (Tok.is(tok::comma)) {
1083
0
    PP.Lex(Tok); // ,
1084
    // Ignore "long" and "short".
1085
    // They are undocumented, but widely used, section attributes which appear
1086
    // to do nothing.
1087
0
    if (Tok.is(tok::kw_long) || Tok.is(tok::kw_short)) {
1088
0
      PP.Lex(Tok); // long/short
1089
0
      continue;
1090
0
    }
1091
1092
0
    if (!Tok.isAnyIdentifier()) {
1093
0
      PP.Diag(PragmaLocation, diag::warn_pragma_expected_action_or_r_paren)
1094
0
          << PragmaName;
1095
0
      return false;
1096
0
    }
1097
0
    ASTContext::PragmaSectionFlag Flag =
1098
0
      llvm::StringSwitch<ASTContext::PragmaSectionFlag>(
1099
0
      Tok.getIdentifierInfo()->getName())
1100
0
      .Case("read", ASTContext::PSF_Read)
1101
0
      .Case("write", ASTContext::PSF_Write)
1102
0
      .Case("execute", ASTContext::PSF_Execute)
1103
0
      .Case("shared", ASTContext::PSF_Invalid)
1104
0
      .Case("nopage", ASTContext::PSF_Invalid)
1105
0
      .Case("nocache", ASTContext::PSF_Invalid)
1106
0
      .Case("discard", ASTContext::PSF_Invalid)
1107
0
      .Case("remove", ASTContext::PSF_Invalid)
1108
0
      .Default(ASTContext::PSF_None);
1109
0
    if (Flag == ASTContext::PSF_None || Flag == ASTContext::PSF_Invalid) {
1110
0
      PP.Diag(PragmaLocation, Flag == ASTContext::PSF_None
1111
0
                                  ? diag::warn_pragma_invalid_specific_action
1112
0
                                  : diag::warn_pragma_unsupported_action)
1113
0
          << PragmaName << Tok.getIdentifierInfo()->getName();
1114
0
      return false;
1115
0
    }
1116
0
    SectionFlags |= Flag;
1117
0
    SectionFlagsAreDefault = false;
1118
0
    PP.Lex(Tok); // Identifier
1119
0
  }
1120
  // If no section attributes are specified, the section will be marked as
1121
  // read/write.
1122
0
  if (SectionFlagsAreDefault)
1123
0
    SectionFlags |= ASTContext::PSF_Write;
1124
0
  if (Tok.isNot(tok::r_paren)) {
1125
0
    PP.Diag(PragmaLocation, diag::warn_pragma_expected_rparen) << PragmaName;
1126
0
    return false;
1127
0
  }
1128
0
  PP.Lex(Tok); // )
1129
0
  if (Tok.isNot(tok::eof)) {
1130
0
    PP.Diag(PragmaLocation, diag::warn_pragma_extra_tokens_at_eol)
1131
0
        << PragmaName;
1132
0
    return false;
1133
0
  }
1134
0
  PP.Lex(Tok); // eof
1135
0
  Actions.ActOnPragmaMSSection(PragmaLocation, SectionFlags, SegmentName);
1136
0
  return true;
1137
0
}
1138
1139
bool Parser::HandlePragmaMSSegment(StringRef PragmaName,
1140
0
                                   SourceLocation PragmaLocation) {
1141
0
  if (Tok.isNot(tok::l_paren)) {
1142
0
    PP.Diag(PragmaLocation, diag::warn_pragma_expected_lparen) << PragmaName;
1143
0
    return false;
1144
0
  }
1145
0
  PP.Lex(Tok); // (
1146
0
  Sema::PragmaMsStackAction Action = Sema::PSK_Reset;
1147
0
  StringRef SlotLabel;
1148
0
  if (Tok.isAnyIdentifier()) {
1149
0
    StringRef PushPop = Tok.getIdentifierInfo()->getName();
1150
0
    if (PushPop == "push")
1151
0
      Action = Sema::PSK_Push;
1152
0
    else if (PushPop == "pop")
1153
0
      Action = Sema::PSK_Pop;
1154
0
    else {
1155
0
      PP.Diag(PragmaLocation,
1156
0
              diag::warn_pragma_expected_section_push_pop_or_name)
1157
0
          << PragmaName;
1158
0
      return false;
1159
0
    }
1160
0
    if (Action != Sema::PSK_Reset) {
1161
0
      PP.Lex(Tok); // push | pop
1162
0
      if (Tok.is(tok::comma)) {
1163
0
        PP.Lex(Tok); // ,
1164
        // If we've got a comma, we either need a label or a string.
1165
0
        if (Tok.isAnyIdentifier()) {
1166
0
          SlotLabel = Tok.getIdentifierInfo()->getName();
1167
0
          PP.Lex(Tok); // identifier
1168
0
          if (Tok.is(tok::comma))
1169
0
            PP.Lex(Tok);
1170
0
          else if (Tok.isNot(tok::r_paren)) {
1171
0
            PP.Diag(PragmaLocation, diag::warn_pragma_expected_punc)
1172
0
                << PragmaName;
1173
0
            return false;
1174
0
          }
1175
0
        }
1176
0
      } else if (Tok.isNot(tok::r_paren)) {
1177
0
        PP.Diag(PragmaLocation, diag::warn_pragma_expected_punc) << PragmaName;
1178
0
        return false;
1179
0
      }
1180
0
    }
1181
0
  }
1182
  // Grab the string literal for our section name.
1183
0
  StringLiteral *SegmentName = nullptr;
1184
0
  if (Tok.isNot(tok::r_paren)) {
1185
0
    if (Tok.isNot(tok::string_literal)) {
1186
0
      unsigned DiagID = Action != Sema::PSK_Reset ? !SlotLabel.empty() ?
1187
0
          diag::warn_pragma_expected_section_name :
1188
0
          diag::warn_pragma_expected_section_label_or_name :
1189
0
          diag::warn_pragma_expected_section_push_pop_or_name;
1190
0
      PP.Diag(PragmaLocation, DiagID) << PragmaName;
1191
0
      return false;
1192
0
    }
1193
0
    ExprResult StringResult = ParseStringLiteralExpression();
1194
0
    if (StringResult.isInvalid())
1195
0
      return false; // Already diagnosed.
1196
0
    SegmentName = cast<StringLiteral>(StringResult.get());
1197
0
    if (SegmentName->getCharByteWidth() != 1) {
1198
0
      PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
1199
0
          << PragmaName;
1200
0
      return false;
1201
0
    }
1202
    // Setting section "" has no effect
1203
0
    if (SegmentName->getLength())
1204
0
      Action = (Sema::PragmaMsStackAction)(Action | Sema::PSK_Set);
1205
0
  }
1206
0
  if (Tok.isNot(tok::r_paren)) {
1207
0
    PP.Diag(PragmaLocation, diag::warn_pragma_expected_rparen) << PragmaName;
1208
0
    return false;
1209
0
  }
1210
0
  PP.Lex(Tok); // )
1211
0
  if (Tok.isNot(tok::eof)) {
1212
0
    PP.Diag(PragmaLocation, diag::warn_pragma_extra_tokens_at_eol)
1213
0
        << PragmaName;
1214
0
    return false;
1215
0
  }
1216
0
  PP.Lex(Tok); // eof
1217
0
  Actions.ActOnPragmaMSSeg(PragmaLocation, Action, SlotLabel,
1218
0
                           SegmentName, PragmaName);
1219
0
  return true;
1220
0
}
1221
1222
// #pragma init_seg({ compiler | lib | user | "section-name" [, func-name]} )
1223
bool Parser::HandlePragmaMSInitSeg(StringRef PragmaName,
1224
0
                                   SourceLocation PragmaLocation) {
1225
0
  if (getTargetInfo().getTriple().getEnvironment() != llvm::Triple::MSVC) {
1226
0
    PP.Diag(PragmaLocation, diag::warn_pragma_init_seg_unsupported_target);
1227
0
    return false;
1228
0
  }
1229
1230
0
  if (ExpectAndConsume(tok::l_paren, diag::warn_pragma_expected_lparen,
1231
0
                       PragmaName))
1232
0
    return false;
1233
1234
  // Parse either the known section names or the string section name.
1235
0
  StringLiteral *SegmentName = nullptr;
1236
0
  if (Tok.isAnyIdentifier()) {
1237
0
    auto *II = Tok.getIdentifierInfo();
1238
0
    StringRef Section = llvm::StringSwitch<StringRef>(II->getName())
1239
0
                            .Case("compiler", "\".CRT$XCC\"")
1240
0
                            .Case("lib", "\".CRT$XCL\"")
1241
0
                            .Case("user", "\".CRT$XCU\"")
1242
0
                            .Default("");
1243
1244
0
    if (!Section.empty()) {
1245
      // Pretend the user wrote the appropriate string literal here.
1246
0
      Token Toks[1];
1247
0
      Toks[0].startToken();
1248
0
      Toks[0].setKind(tok::string_literal);
1249
0
      Toks[0].setLocation(Tok.getLocation());
1250
0
      Toks[0].setLiteralData(Section.data());
1251
0
      Toks[0].setLength(Section.size());
1252
0
      SegmentName =
1253
0
          cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
1254
0
      PP.Lex(Tok);
1255
0
    }
1256
0
  } else if (Tok.is(tok::string_literal)) {
1257
0
    ExprResult StringResult = ParseStringLiteralExpression();
1258
0
    if (StringResult.isInvalid())
1259
0
      return false;
1260
0
    SegmentName = cast<StringLiteral>(StringResult.get());
1261
0
    if (SegmentName->getCharByteWidth() != 1) {
1262
0
      PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
1263
0
          << PragmaName;
1264
0
      return false;
1265
0
    }
1266
    // FIXME: Add support for the '[, func-name]' part of the pragma.
1267
0
  }
1268
1269
0
  if (!SegmentName) {
1270
0
    PP.Diag(PragmaLocation, diag::warn_pragma_expected_init_seg) << PragmaName;
1271
0
    return false;
1272
0
  }
1273
1274
0
  if (ExpectAndConsume(tok::r_paren, diag::warn_pragma_expected_rparen,
1275
0
                       PragmaName) ||
1276
0
      ExpectAndConsume(tok::eof, diag::warn_pragma_extra_tokens_at_eol,
1277
0
                       PragmaName))
1278
0
    return false;
1279
1280
0
  Actions.ActOnPragmaMSInitSeg(PragmaLocation, SegmentName);
1281
0
  return true;
1282
0
}
1283
1284
// #pragma strict_gs_check(pop)
1285
// #pragma strict_gs_check(push, "on" | "off")
1286
// #pragma strict_gs_check("on" | "off")
1287
bool Parser::HandlePragmaMSStrictGuardStackCheck(
1288
0
    StringRef PragmaName, SourceLocation PragmaLocation) {
1289
0
  if (ExpectAndConsume(tok::l_paren, diag::warn_pragma_expected_lparen,
1290
0
                       PragmaName))
1291
0
    return false;
1292
1293
0
  Sema::PragmaMsStackAction Action = Sema::PSK_Set;
1294
0
  if (Tok.is(tok::identifier)) {
1295
0
    StringRef PushPop = Tok.getIdentifierInfo()->getName();
1296
0
    if (PushPop == "push") {
1297
0
      PP.Lex(Tok);
1298
0
      Action = Sema::PSK_Push;
1299
0
      if (ExpectAndConsume(tok::comma, diag::warn_pragma_expected_punc,
1300
0
                           PragmaName))
1301
0
        return false;
1302
0
    } else if (PushPop == "pop") {
1303
0
      PP.Lex(Tok);
1304
0
      Action = Sema::PSK_Pop;
1305
0
    }
1306
0
  }
1307
1308
0
  bool Value = false;
1309
0
  if (Action & Sema::PSK_Push || Action & Sema::PSK_Set) {
1310
0
    const IdentifierInfo *II = Tok.getIdentifierInfo();
1311
0
    if (II && II->isStr("off")) {
1312
0
      PP.Lex(Tok);
1313
0
      Value = false;
1314
0
    } else if (II && II->isStr("on")) {
1315
0
      PP.Lex(Tok);
1316
0
      Value = true;
1317
0
    } else {
1318
0
      PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_action)
1319
0
          << PragmaName;
1320
0
      return false;
1321
0
    }
1322
0
  }
1323
1324
  // Finish the pragma: ')' $
1325
0
  if (ExpectAndConsume(tok::r_paren, diag::warn_pragma_expected_rparen,
1326
0
                       PragmaName))
1327
0
    return false;
1328
1329
0
  if (ExpectAndConsume(tok::eof, diag::warn_pragma_extra_tokens_at_eol,
1330
0
                       PragmaName))
1331
0
    return false;
1332
1333
0
  Actions.ActOnPragmaMSStrictGuardStackCheck(PragmaLocation, Action, Value);
1334
0
  return true;
1335
0
}
1336
1337
bool Parser::HandlePragmaMSAllocText(StringRef PragmaName,
1338
0
                                     SourceLocation PragmaLocation) {
1339
0
  Token FirstTok = Tok;
1340
0
  if (ExpectAndConsume(tok::l_paren, diag::warn_pragma_expected_lparen,
1341
0
                       PragmaName))
1342
0
    return false;
1343
1344
0
  StringRef Section;
1345
0
  if (Tok.is(tok::string_literal)) {
1346
0
    ExprResult StringResult = ParseStringLiteralExpression();
1347
0
    if (StringResult.isInvalid())
1348
0
      return false; // Already diagnosed.
1349
0
    StringLiteral *SegmentName = cast<StringLiteral>(StringResult.get());
1350
0
    if (SegmentName->getCharByteWidth() != 1) {
1351
0
      PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
1352
0
          << PragmaName;
1353
0
      return false;
1354
0
    }
1355
0
    Section = SegmentName->getString();
1356
0
  } else if (Tok.is(tok::identifier)) {
1357
0
    Section = Tok.getIdentifierInfo()->getName();
1358
0
    PP.Lex(Tok);
1359
0
  } else {
1360
0
    PP.Diag(PragmaLocation, diag::warn_pragma_expected_section_name)
1361
0
        << PragmaName;
1362
0
    return false;
1363
0
  }
1364
1365
0
  if (ExpectAndConsume(tok::comma, diag::warn_pragma_expected_comma,
1366
0
                       PragmaName))
1367
0
    return false;
1368
1369
0
  SmallVector<std::tuple<IdentifierInfo *, SourceLocation>> Functions;
1370
0
  while (true) {
1371
0
    if (Tok.isNot(tok::identifier)) {
1372
0
      PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
1373
0
          << PragmaName;
1374
0
      return false;
1375
0
    }
1376
1377
0
    IdentifierInfo *II = Tok.getIdentifierInfo();
1378
0
    Functions.emplace_back(II, Tok.getLocation());
1379
1380
0
    PP.Lex(Tok);
1381
0
    if (Tok.isNot(tok::comma))
1382
0
      break;
1383
0
    PP.Lex(Tok);
1384
0
  }
1385
1386
0
  if (ExpectAndConsume(tok::r_paren, diag::warn_pragma_expected_rparen,
1387
0
                       PragmaName) ||
1388
0
      ExpectAndConsume(tok::eof, diag::warn_pragma_extra_tokens_at_eol,
1389
0
                       PragmaName))
1390
0
    return false;
1391
1392
0
  Actions.ActOnPragmaMSAllocText(FirstTok.getLocation(), Section, Functions);
1393
0
  return true;
1394
0
}
1395
1396
0
static std::string PragmaLoopHintString(Token PragmaName, Token Option) {
1397
0
  StringRef Str = PragmaName.getIdentifierInfo()->getName();
1398
0
  std::string ClangLoopStr("clang loop ");
1399
0
  if (Str == "loop" && Option.getIdentifierInfo())
1400
0
    ClangLoopStr += Option.getIdentifierInfo()->getName();
1401
0
  return std::string(llvm::StringSwitch<StringRef>(Str)
1402
0
                         .Case("loop", ClangLoopStr)
1403
0
                         .Case("unroll_and_jam", Str)
1404
0
                         .Case("unroll", Str)
1405
0
                         .Default(""));
1406
0
}
1407
1408
0
bool Parser::HandlePragmaLoopHint(LoopHint &Hint) {
1409
0
  assert(Tok.is(tok::annot_pragma_loop_hint));
1410
0
  PragmaLoopHintInfo *Info =
1411
0
      static_cast<PragmaLoopHintInfo *>(Tok.getAnnotationValue());
1412
1413
0
  IdentifierInfo *PragmaNameInfo = Info->PragmaName.getIdentifierInfo();
1414
0
  Hint.PragmaNameLoc = IdentifierLoc::create(
1415
0
      Actions.Context, Info->PragmaName.getLocation(), PragmaNameInfo);
1416
1417
  // It is possible that the loop hint has no option identifier, such as
1418
  // #pragma unroll(4).
1419
0
  IdentifierInfo *OptionInfo = Info->Option.is(tok::identifier)
1420
0
                                   ? Info->Option.getIdentifierInfo()
1421
0
                                   : nullptr;
1422
0
  Hint.OptionLoc = IdentifierLoc::create(
1423
0
      Actions.Context, Info->Option.getLocation(), OptionInfo);
1424
1425
0
  llvm::ArrayRef<Token> Toks = Info->Toks;
1426
1427
  // Return a valid hint if pragma unroll or nounroll were specified
1428
  // without an argument.
1429
0
  auto IsLoopHint = llvm::StringSwitch<bool>(PragmaNameInfo->getName())
1430
0
                        .Cases("unroll", "nounroll", "unroll_and_jam",
1431
0
                               "nounroll_and_jam", true)
1432
0
                        .Default(false);
1433
1434
0
  if (Toks.empty() && IsLoopHint) {
1435
0
    ConsumeAnnotationToken();
1436
0
    Hint.Range = Info->PragmaName.getLocation();
1437
0
    return true;
1438
0
  }
1439
1440
  // The constant expression is always followed by an eof token, which increases
1441
  // the TokSize by 1.
1442
0
  assert(!Toks.empty() &&
1443
0
         "PragmaLoopHintInfo::Toks must contain at least one token.");
1444
1445
  // If no option is specified the argument is assumed to be a constant expr.
1446
0
  bool OptionUnroll = false;
1447
0
  bool OptionUnrollAndJam = false;
1448
0
  bool OptionDistribute = false;
1449
0
  bool OptionPipelineDisabled = false;
1450
0
  bool StateOption = false;
1451
0
  if (OptionInfo) { // Pragma Unroll does not specify an option.
1452
0
    OptionUnroll = OptionInfo->isStr("unroll");
1453
0
    OptionUnrollAndJam = OptionInfo->isStr("unroll_and_jam");
1454
0
    OptionDistribute = OptionInfo->isStr("distribute");
1455
0
    OptionPipelineDisabled = OptionInfo->isStr("pipeline");
1456
0
    StateOption = llvm::StringSwitch<bool>(OptionInfo->getName())
1457
0
                      .Case("vectorize", true)
1458
0
                      .Case("interleave", true)
1459
0
                      .Case("vectorize_predicate", true)
1460
0
                      .Default(false) ||
1461
0
                  OptionUnroll || OptionUnrollAndJam || OptionDistribute ||
1462
0
                  OptionPipelineDisabled;
1463
0
  }
1464
1465
0
  bool AssumeSafetyArg = !OptionUnroll && !OptionUnrollAndJam &&
1466
0
                         !OptionDistribute && !OptionPipelineDisabled;
1467
  // Verify loop hint has an argument.
1468
0
  if (Toks[0].is(tok::eof)) {
1469
0
    ConsumeAnnotationToken();
1470
0
    Diag(Toks[0].getLocation(), diag::err_pragma_loop_missing_argument)
1471
0
        << /*StateArgument=*/StateOption
1472
0
        << /*FullKeyword=*/(OptionUnroll || OptionUnrollAndJam)
1473
0
        << /*AssumeSafetyKeyword=*/AssumeSafetyArg;
1474
0
    return false;
1475
0
  }
1476
1477
  // Validate the argument.
1478
0
  if (StateOption) {
1479
0
    ConsumeAnnotationToken();
1480
0
    SourceLocation StateLoc = Toks[0].getLocation();
1481
0
    IdentifierInfo *StateInfo = Toks[0].getIdentifierInfo();
1482
1483
0
    bool Valid = StateInfo &&
1484
0
                 llvm::StringSwitch<bool>(StateInfo->getName())
1485
0
                     .Case("disable", true)
1486
0
                     .Case("enable", !OptionPipelineDisabled)
1487
0
                     .Case("full", OptionUnroll || OptionUnrollAndJam)
1488
0
                     .Case("assume_safety", AssumeSafetyArg)
1489
0
                     .Default(false);
1490
0
    if (!Valid) {
1491
0
      if (OptionPipelineDisabled) {
1492
0
        Diag(Toks[0].getLocation(), diag::err_pragma_pipeline_invalid_keyword);
1493
0
      } else {
1494
0
        Diag(Toks[0].getLocation(), diag::err_pragma_invalid_keyword)
1495
0
            << /*FullKeyword=*/(OptionUnroll || OptionUnrollAndJam)
1496
0
            << /*AssumeSafetyKeyword=*/AssumeSafetyArg;
1497
0
      }
1498
0
      return false;
1499
0
    }
1500
0
    if (Toks.size() > 2)
1501
0
      Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1502
0
          << PragmaLoopHintString(Info->PragmaName, Info->Option);
1503
0
    Hint.StateLoc = IdentifierLoc::create(Actions.Context, StateLoc, StateInfo);
1504
0
  } else if (OptionInfo && OptionInfo->getName() == "vectorize_width") {
1505
0
    PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/false,
1506
0
                        /*IsReinject=*/false);
1507
0
    ConsumeAnnotationToken();
1508
1509
0
    SourceLocation StateLoc = Toks[0].getLocation();
1510
0
    IdentifierInfo *StateInfo = Toks[0].getIdentifierInfo();
1511
0
    StringRef IsScalableStr = StateInfo ? StateInfo->getName() : "";
1512
1513
    // Look for vectorize_width(fixed|scalable)
1514
0
    if (IsScalableStr == "scalable" || IsScalableStr == "fixed") {
1515
0
      PP.Lex(Tok); // Identifier
1516
1517
0
      if (Toks.size() > 2) {
1518
0
        Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1519
0
            << PragmaLoopHintString(Info->PragmaName, Info->Option);
1520
0
        while (Tok.isNot(tok::eof))
1521
0
          ConsumeAnyToken();
1522
0
      }
1523
1524
0
      Hint.StateLoc =
1525
0
          IdentifierLoc::create(Actions.Context, StateLoc, StateInfo);
1526
1527
0
      ConsumeToken(); // Consume the constant expression eof terminator.
1528
0
    } else {
1529
      // Enter constant expression including eof terminator into token stream.
1530
0
      ExprResult R = ParseConstantExpression();
1531
1532
0
      if (R.isInvalid() && !Tok.is(tok::comma))
1533
0
        Diag(Toks[0].getLocation(),
1534
0
             diag::note_pragma_loop_invalid_vectorize_option);
1535
1536
0
      bool Arg2Error = false;
1537
0
      if (Tok.is(tok::comma)) {
1538
0
        PP.Lex(Tok); // ,
1539
1540
0
        StateInfo = Tok.getIdentifierInfo();
1541
0
        IsScalableStr = StateInfo->getName();
1542
1543
0
        if (IsScalableStr != "scalable" && IsScalableStr != "fixed") {
1544
0
          Diag(Tok.getLocation(),
1545
0
               diag::err_pragma_loop_invalid_vectorize_option);
1546
0
          Arg2Error = true;
1547
0
        } else
1548
0
          Hint.StateLoc =
1549
0
              IdentifierLoc::create(Actions.Context, StateLoc, StateInfo);
1550
1551
0
        PP.Lex(Tok); // Identifier
1552
0
      }
1553
1554
      // Tokens following an error in an ill-formed constant expression will
1555
      // remain in the token stream and must be removed.
1556
0
      if (Tok.isNot(tok::eof)) {
1557
0
        Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1558
0
            << PragmaLoopHintString(Info->PragmaName, Info->Option);
1559
0
        while (Tok.isNot(tok::eof))
1560
0
          ConsumeAnyToken();
1561
0
      }
1562
1563
0
      ConsumeToken(); // Consume the constant expression eof terminator.
1564
1565
0
      if (Arg2Error || R.isInvalid() ||
1566
0
          Actions.CheckLoopHintExpr(R.get(), Toks[0].getLocation()))
1567
0
        return false;
1568
1569
      // Argument is a constant expression with an integer type.
1570
0
      Hint.ValueExpr = R.get();
1571
0
    }
1572
0
  } else {
1573
    // Enter constant expression including eof terminator into token stream.
1574
0
    PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/false,
1575
0
                        /*IsReinject=*/false);
1576
0
    ConsumeAnnotationToken();
1577
0
    ExprResult R = ParseConstantExpression();
1578
1579
    // Tokens following an error in an ill-formed constant expression will
1580
    // remain in the token stream and must be removed.
1581
0
    if (Tok.isNot(tok::eof)) {
1582
0
      Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1583
0
          << PragmaLoopHintString(Info->PragmaName, Info->Option);
1584
0
      while (Tok.isNot(tok::eof))
1585
0
        ConsumeAnyToken();
1586
0
    }
1587
1588
0
    ConsumeToken(); // Consume the constant expression eof terminator.
1589
1590
0
    if (R.isInvalid() ||
1591
0
        Actions.CheckLoopHintExpr(R.get(), Toks[0].getLocation()))
1592
0
      return false;
1593
1594
    // Argument is a constant expression with an integer type.
1595
0
    Hint.ValueExpr = R.get();
1596
0
  }
1597
1598
0
  Hint.Range = SourceRange(Info->PragmaName.getLocation(),
1599
0
                           Info->Toks.back().getLocation());
1600
0
  return true;
1601
0
}
1602
1603
namespace {
1604
struct PragmaAttributeInfo {
1605
  enum ActionType { Push, Pop, Attribute };
1606
  ParsedAttributes &Attributes;
1607
  ActionType Action;
1608
  const IdentifierInfo *Namespace = nullptr;
1609
  ArrayRef<Token> Tokens;
1610
1611
0
  PragmaAttributeInfo(ParsedAttributes &Attributes) : Attributes(Attributes) {}
1612
};
1613
1614
#include "clang/Parse/AttrSubMatchRulesParserStringSwitches.inc"
1615
1616
} // end anonymous namespace
1617
1618
0
static StringRef getIdentifier(const Token &Tok) {
1619
0
  if (Tok.is(tok::identifier))
1620
0
    return Tok.getIdentifierInfo()->getName();
1621
0
  const char *S = tok::getKeywordSpelling(Tok.getKind());
1622
0
  if (!S)
1623
0
    return "";
1624
0
  return S;
1625
0
}
1626
1627
0
static bool isAbstractAttrMatcherRule(attr::SubjectMatchRule Rule) {
1628
0
  using namespace attr;
1629
0
  switch (Rule) {
1630
0
#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)                           \
1631
0
  case Value:                                                                  \
1632
0
    return IsAbstract;
1633
0
#include "clang/Basic/AttrSubMatchRulesList.inc"
1634
0
  }
1635
0
  llvm_unreachable("Invalid attribute subject match rule");
1636
0
  return false;
1637
0
}
1638
1639
static void diagnoseExpectedAttributeSubjectSubRule(
1640
    Parser &PRef, attr::SubjectMatchRule PrimaryRule, StringRef PrimaryRuleName,
1641
0
    SourceLocation SubRuleLoc) {
1642
0
  auto Diagnostic =
1643
0
      PRef.Diag(SubRuleLoc,
1644
0
                diag::err_pragma_attribute_expected_subject_sub_identifier)
1645
0
      << PrimaryRuleName;
1646
0
  if (const char *SubRules = validAttributeSubjectMatchSubRules(PrimaryRule))
1647
0
    Diagnostic << /*SubRulesSupported=*/1 << SubRules;
1648
0
  else
1649
0
    Diagnostic << /*SubRulesSupported=*/0;
1650
0
}
1651
1652
static void diagnoseUnknownAttributeSubjectSubRule(
1653
    Parser &PRef, attr::SubjectMatchRule PrimaryRule, StringRef PrimaryRuleName,
1654
0
    StringRef SubRuleName, SourceLocation SubRuleLoc) {
1655
1656
0
  auto Diagnostic =
1657
0
      PRef.Diag(SubRuleLoc, diag::err_pragma_attribute_unknown_subject_sub_rule)
1658
0
      << SubRuleName << PrimaryRuleName;
1659
0
  if (const char *SubRules = validAttributeSubjectMatchSubRules(PrimaryRule))
1660
0
    Diagnostic << /*SubRulesSupported=*/1 << SubRules;
1661
0
  else
1662
0
    Diagnostic << /*SubRulesSupported=*/0;
1663
0
}
1664
1665
bool Parser::ParsePragmaAttributeSubjectMatchRuleSet(
1666
    attr::ParsedSubjectMatchRuleSet &SubjectMatchRules, SourceLocation &AnyLoc,
1667
0
    SourceLocation &LastMatchRuleEndLoc) {
1668
0
  bool IsAny = false;
1669
0
  BalancedDelimiterTracker AnyParens(*this, tok::l_paren);
1670
0
  if (getIdentifier(Tok) == "any") {
1671
0
    AnyLoc = ConsumeToken();
1672
0
    IsAny = true;
1673
0
    if (AnyParens.expectAndConsume())
1674
0
      return true;
1675
0
  }
1676
1677
0
  do {
1678
    // Parse the subject matcher rule.
1679
0
    StringRef Name = getIdentifier(Tok);
1680
0
    if (Name.empty()) {
1681
0
      Diag(Tok, diag::err_pragma_attribute_expected_subject_identifier);
1682
0
      return true;
1683
0
    }
1684
0
    std::pair<std::optional<attr::SubjectMatchRule>,
1685
0
              std::optional<attr::SubjectMatchRule> (*)(StringRef, bool)>
1686
0
        Rule = isAttributeSubjectMatchRule(Name);
1687
0
    if (!Rule.first) {
1688
0
      Diag(Tok, diag::err_pragma_attribute_unknown_subject_rule) << Name;
1689
0
      return true;
1690
0
    }
1691
0
    attr::SubjectMatchRule PrimaryRule = *Rule.first;
1692
0
    SourceLocation RuleLoc = ConsumeToken();
1693
1694
0
    BalancedDelimiterTracker Parens(*this, tok::l_paren);
1695
0
    if (isAbstractAttrMatcherRule(PrimaryRule)) {
1696
0
      if (Parens.expectAndConsume())
1697
0
        return true;
1698
0
    } else if (Parens.consumeOpen()) {
1699
0
      if (!SubjectMatchRules
1700
0
               .insert(
1701
0
                   std::make_pair(PrimaryRule, SourceRange(RuleLoc, RuleLoc)))
1702
0
               .second)
1703
0
        Diag(RuleLoc, diag::err_pragma_attribute_duplicate_subject)
1704
0
            << Name
1705
0
            << FixItHint::CreateRemoval(SourceRange(
1706
0
                   RuleLoc, Tok.is(tok::comma) ? Tok.getLocation() : RuleLoc));
1707
0
      LastMatchRuleEndLoc = RuleLoc;
1708
0
      continue;
1709
0
    }
1710
1711
    // Parse the sub-rules.
1712
0
    StringRef SubRuleName = getIdentifier(Tok);
1713
0
    if (SubRuleName.empty()) {
1714
0
      diagnoseExpectedAttributeSubjectSubRule(*this, PrimaryRule, Name,
1715
0
                                              Tok.getLocation());
1716
0
      return true;
1717
0
    }
1718
0
    attr::SubjectMatchRule SubRule;
1719
0
    if (SubRuleName == "unless") {
1720
0
      SourceLocation SubRuleLoc = ConsumeToken();
1721
0
      BalancedDelimiterTracker Parens(*this, tok::l_paren);
1722
0
      if (Parens.expectAndConsume())
1723
0
        return true;
1724
0
      SubRuleName = getIdentifier(Tok);
1725
0
      if (SubRuleName.empty()) {
1726
0
        diagnoseExpectedAttributeSubjectSubRule(*this, PrimaryRule, Name,
1727
0
                                                SubRuleLoc);
1728
0
        return true;
1729
0
      }
1730
0
      auto SubRuleOrNone = Rule.second(SubRuleName, /*IsUnless=*/true);
1731
0
      if (!SubRuleOrNone) {
1732
0
        std::string SubRuleUnlessName = "unless(" + SubRuleName.str() + ")";
1733
0
        diagnoseUnknownAttributeSubjectSubRule(*this, PrimaryRule, Name,
1734
0
                                               SubRuleUnlessName, SubRuleLoc);
1735
0
        return true;
1736
0
      }
1737
0
      SubRule = *SubRuleOrNone;
1738
0
      ConsumeToken();
1739
0
      if (Parens.consumeClose())
1740
0
        return true;
1741
0
    } else {
1742
0
      auto SubRuleOrNone = Rule.second(SubRuleName, /*IsUnless=*/false);
1743
0
      if (!SubRuleOrNone) {
1744
0
        diagnoseUnknownAttributeSubjectSubRule(*this, PrimaryRule, Name,
1745
0
                                               SubRuleName, Tok.getLocation());
1746
0
        return true;
1747
0
      }
1748
0
      SubRule = *SubRuleOrNone;
1749
0
      ConsumeToken();
1750
0
    }
1751
0
    SourceLocation RuleEndLoc = Tok.getLocation();
1752
0
    LastMatchRuleEndLoc = RuleEndLoc;
1753
0
    if (Parens.consumeClose())
1754
0
      return true;
1755
0
    if (!SubjectMatchRules
1756
0
             .insert(std::make_pair(SubRule, SourceRange(RuleLoc, RuleEndLoc)))
1757
0
             .second) {
1758
0
      Diag(RuleLoc, diag::err_pragma_attribute_duplicate_subject)
1759
0
          << attr::getSubjectMatchRuleSpelling(SubRule)
1760
0
          << FixItHint::CreateRemoval(SourceRange(
1761
0
                 RuleLoc, Tok.is(tok::comma) ? Tok.getLocation() : RuleEndLoc));
1762
0
      continue;
1763
0
    }
1764
0
  } while (IsAny && TryConsumeToken(tok::comma));
1765
1766
0
  if (IsAny)
1767
0
    if (AnyParens.consumeClose())
1768
0
      return true;
1769
1770
0
  return false;
1771
0
}
1772
1773
namespace {
1774
1775
/// Describes the stage at which attribute subject rule parsing was interrupted.
1776
enum class MissingAttributeSubjectRulesRecoveryPoint {
1777
  Comma,
1778
  ApplyTo,
1779
  Equals,
1780
  Any,
1781
  None,
1782
};
1783
1784
MissingAttributeSubjectRulesRecoveryPoint
1785
0
getAttributeSubjectRulesRecoveryPointForToken(const Token &Tok) {
1786
0
  if (const auto *II = Tok.getIdentifierInfo()) {
1787
0
    if (II->isStr("apply_to"))
1788
0
      return MissingAttributeSubjectRulesRecoveryPoint::ApplyTo;
1789
0
    if (II->isStr("any"))
1790
0
      return MissingAttributeSubjectRulesRecoveryPoint::Any;
1791
0
  }
1792
0
  if (Tok.is(tok::equal))
1793
0
    return MissingAttributeSubjectRulesRecoveryPoint::Equals;
1794
0
  return MissingAttributeSubjectRulesRecoveryPoint::None;
1795
0
}
1796
1797
/// Creates a diagnostic for the attribute subject rule parsing diagnostic that
1798
/// suggests the possible attribute subject rules in a fix-it together with
1799
/// any other missing tokens.
1800
DiagnosticBuilder createExpectedAttributeSubjectRulesTokenDiagnostic(
1801
    unsigned DiagID, ParsedAttributes &Attrs,
1802
0
    MissingAttributeSubjectRulesRecoveryPoint Point, Parser &PRef) {
1803
0
  SourceLocation Loc = PRef.getEndOfPreviousToken();
1804
0
  if (Loc.isInvalid())
1805
0
    Loc = PRef.getCurToken().getLocation();
1806
0
  auto Diagnostic = PRef.Diag(Loc, DiagID);
1807
0
  std::string FixIt;
1808
0
  MissingAttributeSubjectRulesRecoveryPoint EndPoint =
1809
0
      getAttributeSubjectRulesRecoveryPointForToken(PRef.getCurToken());
1810
0
  if (Point == MissingAttributeSubjectRulesRecoveryPoint::Comma)
1811
0
    FixIt = ", ";
1812
0
  if (Point <= MissingAttributeSubjectRulesRecoveryPoint::ApplyTo &&
1813
0
      EndPoint > MissingAttributeSubjectRulesRecoveryPoint::ApplyTo)
1814
0
    FixIt += "apply_to";
1815
0
  if (Point <= MissingAttributeSubjectRulesRecoveryPoint::Equals &&
1816
0
      EndPoint > MissingAttributeSubjectRulesRecoveryPoint::Equals)
1817
0
    FixIt += " = ";
1818
0
  SourceRange FixItRange(Loc);
1819
0
  if (EndPoint == MissingAttributeSubjectRulesRecoveryPoint::None) {
1820
    // Gather the subject match rules that are supported by the attribute.
1821
    // Add all the possible rules initially.
1822
0
    llvm::BitVector IsMatchRuleAvailable(attr::SubjectMatchRule_Last + 1, true);
1823
    // Remove the ones that are not supported by any of the attributes.
1824
0
    for (const ParsedAttr &Attribute : Attrs) {
1825
0
      SmallVector<std::pair<attr::SubjectMatchRule, bool>, 4> MatchRules;
1826
0
      Attribute.getMatchRules(PRef.getLangOpts(), MatchRules);
1827
0
      llvm::BitVector IsSupported(attr::SubjectMatchRule_Last + 1);
1828
0
      for (const auto &Rule : MatchRules) {
1829
        // Ensure that the missing rule is reported in the fix-it only when it's
1830
        // supported in the current language mode.
1831
0
        if (!Rule.second)
1832
0
          continue;
1833
0
        IsSupported[Rule.first] = true;
1834
0
      }
1835
0
      IsMatchRuleAvailable &= IsSupported;
1836
0
    }
1837
0
    if (IsMatchRuleAvailable.count() == 0) {
1838
      // FIXME: We can emit a "fix-it" with a subject list placeholder when
1839
      // placeholders will be supported by the fix-its.
1840
0
      return Diagnostic;
1841
0
    }
1842
0
    FixIt += "any(";
1843
0
    bool NeedsComma = false;
1844
0
    for (unsigned I = 0; I <= attr::SubjectMatchRule_Last; I++) {
1845
0
      if (!IsMatchRuleAvailable[I])
1846
0
        continue;
1847
0
      if (NeedsComma)
1848
0
        FixIt += ", ";
1849
0
      else
1850
0
        NeedsComma = true;
1851
0
      FixIt += attr::getSubjectMatchRuleSpelling(
1852
0
          static_cast<attr::SubjectMatchRule>(I));
1853
0
    }
1854
0
    FixIt += ")";
1855
    // Check if we need to remove the range
1856
0
    PRef.SkipUntil(tok::eof, Parser::StopBeforeMatch);
1857
0
    FixItRange.setEnd(PRef.getCurToken().getLocation());
1858
0
  }
1859
0
  if (FixItRange.getBegin() == FixItRange.getEnd())
1860
0
    Diagnostic << FixItHint::CreateInsertion(FixItRange.getBegin(), FixIt);
1861
0
  else
1862
0
    Diagnostic << FixItHint::CreateReplacement(
1863
0
        CharSourceRange::getCharRange(FixItRange), FixIt);
1864
0
  return Diagnostic;
1865
0
}
1866
1867
} // end anonymous namespace
1868
1869
0
void Parser::HandlePragmaAttribute() {
1870
0
  assert(Tok.is(tok::annot_pragma_attribute) &&
1871
0
         "Expected #pragma attribute annotation token");
1872
0
  SourceLocation PragmaLoc = Tok.getLocation();
1873
0
  auto *Info = static_cast<PragmaAttributeInfo *>(Tok.getAnnotationValue());
1874
0
  if (Info->Action == PragmaAttributeInfo::Pop) {
1875
0
    ConsumeAnnotationToken();
1876
0
    Actions.ActOnPragmaAttributePop(PragmaLoc, Info->Namespace);
1877
0
    return;
1878
0
  }
1879
  // Parse the actual attribute with its arguments.
1880
0
  assert((Info->Action == PragmaAttributeInfo::Push ||
1881
0
          Info->Action == PragmaAttributeInfo::Attribute) &&
1882
0
         "Unexpected #pragma attribute command");
1883
1884
0
  if (Info->Action == PragmaAttributeInfo::Push && Info->Tokens.empty()) {
1885
0
    ConsumeAnnotationToken();
1886
0
    Actions.ActOnPragmaAttributeEmptyPush(PragmaLoc, Info->Namespace);
1887
0
    return;
1888
0
  }
1889
1890
0
  PP.EnterTokenStream(Info->Tokens, /*DisableMacroExpansion=*/false,
1891
0
                      /*IsReinject=*/false);
1892
0
  ConsumeAnnotationToken();
1893
1894
0
  ParsedAttributes &Attrs = Info->Attributes;
1895
0
  Attrs.clearListOnly();
1896
1897
0
  auto SkipToEnd = [this]() {
1898
0
    SkipUntil(tok::eof, StopBeforeMatch);
1899
0
    ConsumeToken();
1900
0
  };
1901
1902
0
  if ((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1903
0
      Tok.isRegularKeywordAttribute()) {
1904
    // Parse the CXX11 style attribute.
1905
0
    ParseCXX11AttributeSpecifier(Attrs);
1906
0
  } else if (Tok.is(tok::kw___attribute)) {
1907
0
    ConsumeToken();
1908
0
    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
1909
0
                         "attribute"))
1910
0
      return SkipToEnd();
1911
0
    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "("))
1912
0
      return SkipToEnd();
1913
1914
    // FIXME: The practical usefulness of completion here is limited because
1915
    // we only get here if the line has balanced parens.
1916
0
    if (Tok.is(tok::code_completion)) {
1917
0
      cutOffParsing();
1918
      // FIXME: suppress completion of unsupported attributes?
1919
0
      Actions.CodeCompleteAttribute(AttributeCommonInfo::Syntax::AS_GNU);
1920
0
      return SkipToEnd();
1921
0
    }
1922
1923
    // Parse the comma-separated list of attributes.
1924
0
    do {
1925
0
      if (Tok.isNot(tok::identifier)) {
1926
0
        Diag(Tok, diag::err_pragma_attribute_expected_attribute_name);
1927
0
        SkipToEnd();
1928
0
        return;
1929
0
      }
1930
0
      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1931
0
      SourceLocation AttrNameLoc = ConsumeToken();
1932
1933
0
      if (Tok.isNot(tok::l_paren))
1934
0
        Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1935
0
                     ParsedAttr::Form::GNU());
1936
0
      else
1937
0
        ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, /*EndLoc=*/nullptr,
1938
0
                              /*ScopeName=*/nullptr,
1939
0
                              /*ScopeLoc=*/SourceLocation(),
1940
0
                              ParsedAttr::Form::GNU(),
1941
0
                              /*Declarator=*/nullptr);
1942
0
    } while (TryConsumeToken(tok::comma));
1943
1944
0
    if (ExpectAndConsume(tok::r_paren))
1945
0
      return SkipToEnd();
1946
0
    if (ExpectAndConsume(tok::r_paren))
1947
0
      return SkipToEnd();
1948
0
  } else if (Tok.is(tok::kw___declspec)) {
1949
0
    ParseMicrosoftDeclSpecs(Attrs);
1950
0
  } else {
1951
0
    Diag(Tok, diag::err_pragma_attribute_expected_attribute_syntax);
1952
0
    if (Tok.getIdentifierInfo()) {
1953
      // If we suspect that this is an attribute suggest the use of
1954
      // '__attribute__'.
1955
0
      if (ParsedAttr::getParsedKind(
1956
0
              Tok.getIdentifierInfo(), /*ScopeName=*/nullptr,
1957
0
              ParsedAttr::AS_GNU) != ParsedAttr::UnknownAttribute) {
1958
0
        SourceLocation InsertStartLoc = Tok.getLocation();
1959
0
        ConsumeToken();
1960
0
        if (Tok.is(tok::l_paren)) {
1961
0
          ConsumeAnyToken();
1962
0
          SkipUntil(tok::r_paren, StopBeforeMatch);
1963
0
          if (Tok.isNot(tok::r_paren))
1964
0
            return SkipToEnd();
1965
0
        }
1966
0
        Diag(Tok, diag::note_pragma_attribute_use_attribute_kw)
1967
0
            << FixItHint::CreateInsertion(InsertStartLoc, "__attribute__((")
1968
0
            << FixItHint::CreateInsertion(Tok.getEndLoc(), "))");
1969
0
      }
1970
0
    }
1971
0
    SkipToEnd();
1972
0
    return;
1973
0
  }
1974
1975
0
  if (Attrs.empty() || Attrs.begin()->isInvalid()) {
1976
0
    SkipToEnd();
1977
0
    return;
1978
0
  }
1979
1980
0
  for (const ParsedAttr &Attribute : Attrs) {
1981
0
    if (!Attribute.isSupportedByPragmaAttribute()) {
1982
0
      Diag(PragmaLoc, diag::err_pragma_attribute_unsupported_attribute)
1983
0
          << Attribute;
1984
0
      SkipToEnd();
1985
0
      return;
1986
0
    }
1987
0
  }
1988
1989
  // Parse the subject-list.
1990
0
  if (!TryConsumeToken(tok::comma)) {
1991
0
    createExpectedAttributeSubjectRulesTokenDiagnostic(
1992
0
        diag::err_expected, Attrs,
1993
0
        MissingAttributeSubjectRulesRecoveryPoint::Comma, *this)
1994
0
        << tok::comma;
1995
0
    SkipToEnd();
1996
0
    return;
1997
0
  }
1998
1999
0
  if (Tok.isNot(tok::identifier)) {
2000
0
    createExpectedAttributeSubjectRulesTokenDiagnostic(
2001
0
        diag::err_pragma_attribute_invalid_subject_set_specifier, Attrs,
2002
0
        MissingAttributeSubjectRulesRecoveryPoint::ApplyTo, *this);
2003
0
    SkipToEnd();
2004
0
    return;
2005
0
  }
2006
0
  const IdentifierInfo *II = Tok.getIdentifierInfo();
2007
0
  if (!II->isStr("apply_to")) {
2008
0
    createExpectedAttributeSubjectRulesTokenDiagnostic(
2009
0
        diag::err_pragma_attribute_invalid_subject_set_specifier, Attrs,
2010
0
        MissingAttributeSubjectRulesRecoveryPoint::ApplyTo, *this);
2011
0
    SkipToEnd();
2012
0
    return;
2013
0
  }
2014
0
  ConsumeToken();
2015
2016
0
  if (!TryConsumeToken(tok::equal)) {
2017
0
    createExpectedAttributeSubjectRulesTokenDiagnostic(
2018
0
        diag::err_expected, Attrs,
2019
0
        MissingAttributeSubjectRulesRecoveryPoint::Equals, *this)
2020
0
        << tok::equal;
2021
0
    SkipToEnd();
2022
0
    return;
2023
0
  }
2024
2025
0
  attr::ParsedSubjectMatchRuleSet SubjectMatchRules;
2026
0
  SourceLocation AnyLoc, LastMatchRuleEndLoc;
2027
0
  if (ParsePragmaAttributeSubjectMatchRuleSet(SubjectMatchRules, AnyLoc,
2028
0
                                              LastMatchRuleEndLoc)) {
2029
0
    SkipToEnd();
2030
0
    return;
2031
0
  }
2032
2033
  // Tokens following an ill-formed attribute will remain in the token stream
2034
  // and must be removed.
2035
0
  if (Tok.isNot(tok::eof)) {
2036
0
    Diag(Tok, diag::err_pragma_attribute_extra_tokens_after_attribute);
2037
0
    SkipToEnd();
2038
0
    return;
2039
0
  }
2040
2041
  // Consume the eof terminator token.
2042
0
  ConsumeToken();
2043
2044
  // Handle a mixed push/attribute by desurging to a push, then an attribute.
2045
0
  if (Info->Action == PragmaAttributeInfo::Push)
2046
0
    Actions.ActOnPragmaAttributeEmptyPush(PragmaLoc, Info->Namespace);
2047
2048
0
  for (ParsedAttr &Attribute : Attrs) {
2049
0
    Actions.ActOnPragmaAttributeAttribute(Attribute, PragmaLoc,
2050
0
                                          SubjectMatchRules);
2051
0
  }
2052
0
}
2053
2054
// #pragma GCC visibility comes in two variants:
2055
//   'push' '(' [visibility] ')'
2056
//   'pop'
2057
void PragmaGCCVisibilityHandler::HandlePragma(Preprocessor &PP,
2058
                                              PragmaIntroducer Introducer,
2059
0
                                              Token &VisTok) {
2060
0
  SourceLocation VisLoc = VisTok.getLocation();
2061
2062
0
  Token Tok;
2063
0
  PP.LexUnexpandedToken(Tok);
2064
2065
0
  const IdentifierInfo *PushPop = Tok.getIdentifierInfo();
2066
2067
0
  const IdentifierInfo *VisType;
2068
0
  if (PushPop && PushPop->isStr("pop")) {
2069
0
    VisType = nullptr;
2070
0
  } else if (PushPop && PushPop->isStr("push")) {
2071
0
    PP.LexUnexpandedToken(Tok);
2072
0
    if (Tok.isNot(tok::l_paren)) {
2073
0
      PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen)
2074
0
        << "visibility";
2075
0
      return;
2076
0
    }
2077
0
    PP.LexUnexpandedToken(Tok);
2078
0
    VisType = Tok.getIdentifierInfo();
2079
0
    if (!VisType) {
2080
0
      PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
2081
0
        << "visibility";
2082
0
      return;
2083
0
    }
2084
0
    PP.LexUnexpandedToken(Tok);
2085
0
    if (Tok.isNot(tok::r_paren)) {
2086
0
      PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen)
2087
0
        << "visibility";
2088
0
      return;
2089
0
    }
2090
0
  } else {
2091
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
2092
0
      << "visibility";
2093
0
    return;
2094
0
  }
2095
0
  SourceLocation EndLoc = Tok.getLocation();
2096
0
  PP.LexUnexpandedToken(Tok);
2097
0
  if (Tok.isNot(tok::eod)) {
2098
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
2099
0
      << "visibility";
2100
0
    return;
2101
0
  }
2102
2103
0
  auto Toks = std::make_unique<Token[]>(1);
2104
0
  Toks[0].startToken();
2105
0
  Toks[0].setKind(tok::annot_pragma_vis);
2106
0
  Toks[0].setLocation(VisLoc);
2107
0
  Toks[0].setAnnotationEndLoc(EndLoc);
2108
0
  Toks[0].setAnnotationValue(
2109
0
      const_cast<void *>(static_cast<const void *>(VisType)));
2110
0
  PP.EnterTokenStream(std::move(Toks), 1, /*DisableMacroExpansion=*/true,
2111
0
                      /*IsReinject=*/false);
2112
0
}
2113
2114
// #pragma pack(...) comes in the following delicious flavors:
2115
//   pack '(' [integer] ')'
2116
//   pack '(' 'show' ')'
2117
//   pack '(' ('push' | 'pop') [',' identifier] [, integer] ')'
2118
void PragmaPackHandler::HandlePragma(Preprocessor &PP,
2119
                                     PragmaIntroducer Introducer,
2120
0
                                     Token &PackTok) {
2121
0
  SourceLocation PackLoc = PackTok.getLocation();
2122
2123
0
  Token Tok;
2124
0
  PP.Lex(Tok);
2125
0
  if (Tok.isNot(tok::l_paren)) {
2126
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "pack";
2127
0
    return;
2128
0
  }
2129
2130
0
  Sema::PragmaMsStackAction Action = Sema::PSK_Reset;
2131
0
  StringRef SlotLabel;
2132
0
  Token Alignment;
2133
0
  Alignment.startToken();
2134
0
  PP.Lex(Tok);
2135
0
  if (Tok.is(tok::numeric_constant)) {
2136
0
    Alignment = Tok;
2137
2138
0
    PP.Lex(Tok);
2139
2140
    // In MSVC/gcc, #pragma pack(4) sets the alignment without affecting
2141
    // the push/pop stack.
2142
    // In Apple gcc/XL, #pragma pack(4) is equivalent to #pragma pack(push, 4)
2143
0
    Action = (PP.getLangOpts().ApplePragmaPack || PP.getLangOpts().XLPragmaPack)
2144
0
                 ? Sema::PSK_Push_Set
2145
0
                 : Sema::PSK_Set;
2146
0
  } else if (Tok.is(tok::identifier)) {
2147
0
    const IdentifierInfo *II = Tok.getIdentifierInfo();
2148
0
    if (II->isStr("show")) {
2149
0
      Action = Sema::PSK_Show;
2150
0
      PP.Lex(Tok);
2151
0
    } else {
2152
0
      if (II->isStr("push")) {
2153
0
        Action = Sema::PSK_Push;
2154
0
      } else if (II->isStr("pop")) {
2155
0
        Action = Sema::PSK_Pop;
2156
0
      } else {
2157
0
        PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_action) << "pack";
2158
0
        return;
2159
0
      }
2160
0
      PP.Lex(Tok);
2161
2162
0
      if (Tok.is(tok::comma)) {
2163
0
        PP.Lex(Tok);
2164
2165
0
        if (Tok.is(tok::numeric_constant)) {
2166
0
          Action = (Sema::PragmaMsStackAction)(Action | Sema::PSK_Set);
2167
0
          Alignment = Tok;
2168
2169
0
          PP.Lex(Tok);
2170
0
        } else if (Tok.is(tok::identifier)) {
2171
0
          SlotLabel = Tok.getIdentifierInfo()->getName();
2172
0
          PP.Lex(Tok);
2173
2174
0
          if (Tok.is(tok::comma)) {
2175
0
            PP.Lex(Tok);
2176
2177
0
            if (Tok.isNot(tok::numeric_constant)) {
2178
0
              PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_malformed);
2179
0
              return;
2180
0
            }
2181
2182
0
            Action = (Sema::PragmaMsStackAction)(Action | Sema::PSK_Set);
2183
0
            Alignment = Tok;
2184
2185
0
            PP.Lex(Tok);
2186
0
          }
2187
0
        } else {
2188
0
          PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_malformed);
2189
0
          return;
2190
0
        }
2191
0
      }
2192
0
    }
2193
0
  } else if (PP.getLangOpts().ApplePragmaPack ||
2194
0
             PP.getLangOpts().XLPragmaPack) {
2195
    // In MSVC/gcc, #pragma pack() resets the alignment without affecting
2196
    // the push/pop stack.
2197
    // In Apple gcc and IBM XL, #pragma pack() is equivalent to #pragma
2198
    // pack(pop).
2199
0
    Action = Sema::PSK_Pop;
2200
0
  }
2201
2202
0
  if (Tok.isNot(tok::r_paren)) {
2203
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen) << "pack";
2204
0
    return;
2205
0
  }
2206
2207
0
  SourceLocation RParenLoc = Tok.getLocation();
2208
0
  PP.Lex(Tok);
2209
0
  if (Tok.isNot(tok::eod)) {
2210
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "pack";
2211
0
    return;
2212
0
  }
2213
2214
0
  Sema::PragmaPackInfo *Info =
2215
0
      PP.getPreprocessorAllocator().Allocate<Sema::PragmaPackInfo>(1);
2216
0
  Info->Action = Action;
2217
0
  Info->SlotLabel = SlotLabel;
2218
0
  Info->Alignment = Alignment;
2219
2220
0
  MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
2221
0
                              1);
2222
0
  Toks[0].startToken();
2223
0
  Toks[0].setKind(tok::annot_pragma_pack);
2224
0
  Toks[0].setLocation(PackLoc);
2225
0
  Toks[0].setAnnotationEndLoc(RParenLoc);
2226
0
  Toks[0].setAnnotationValue(static_cast<void*>(Info));
2227
0
  PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
2228
0
                      /*IsReinject=*/false);
2229
0
}
2230
2231
// #pragma ms_struct on
2232
// #pragma ms_struct off
2233
void PragmaMSStructHandler::HandlePragma(Preprocessor &PP,
2234
                                         PragmaIntroducer Introducer,
2235
0
                                         Token &MSStructTok) {
2236
0
  PragmaMSStructKind Kind = PMSST_OFF;
2237
2238
0
  Token Tok;
2239
0
  PP.Lex(Tok);
2240
0
  if (Tok.isNot(tok::identifier)) {
2241
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_ms_struct);
2242
0
    return;
2243
0
  }
2244
0
  SourceLocation EndLoc = Tok.getLocation();
2245
0
  const IdentifierInfo *II = Tok.getIdentifierInfo();
2246
0
  if (II->isStr("on")) {
2247
0
    Kind = PMSST_ON;
2248
0
    PP.Lex(Tok);
2249
0
  }
2250
0
  else if (II->isStr("off") || II->isStr("reset"))
2251
0
    PP.Lex(Tok);
2252
0
  else {
2253
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_ms_struct);
2254
0
    return;
2255
0
  }
2256
2257
0
  if (Tok.isNot(tok::eod)) {
2258
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
2259
0
      << "ms_struct";
2260
0
    return;
2261
0
  }
2262
2263
0
  MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
2264
0
                              1);
2265
0
  Toks[0].startToken();
2266
0
  Toks[0].setKind(tok::annot_pragma_msstruct);
2267
0
  Toks[0].setLocation(MSStructTok.getLocation());
2268
0
  Toks[0].setAnnotationEndLoc(EndLoc);
2269
0
  Toks[0].setAnnotationValue(reinterpret_cast<void*>(
2270
0
                             static_cast<uintptr_t>(Kind)));
2271
0
  PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
2272
0
                      /*IsReinject=*/false);
2273
0
}
2274
2275
// #pragma clang section bss="abc" data="" rodata="def" text="" relro=""
2276
void PragmaClangSectionHandler::HandlePragma(Preprocessor &PP,
2277
                                             PragmaIntroducer Introducer,
2278
0
                                             Token &FirstToken) {
2279
2280
0
  Token Tok;
2281
0
  auto SecKind = Sema::PragmaClangSectionKind::PCSK_Invalid;
2282
2283
0
  PP.Lex(Tok); // eat 'section'
2284
0
  while (Tok.isNot(tok::eod)) {
2285
0
    if (Tok.isNot(tok::identifier)) {
2286
0
      PP.Diag(Tok.getLocation(), diag::err_pragma_expected_clang_section_name) << "clang section";
2287
0
      return;
2288
0
    }
2289
2290
0
    const IdentifierInfo *SecType = Tok.getIdentifierInfo();
2291
0
    if (SecType->isStr("bss"))
2292
0
      SecKind = Sema::PragmaClangSectionKind::PCSK_BSS;
2293
0
    else if (SecType->isStr("data"))
2294
0
      SecKind = Sema::PragmaClangSectionKind::PCSK_Data;
2295
0
    else if (SecType->isStr("rodata"))
2296
0
      SecKind = Sema::PragmaClangSectionKind::PCSK_Rodata;
2297
0
    else if (SecType->isStr("relro"))
2298
0
      SecKind = Sema::PragmaClangSectionKind::PCSK_Relro;
2299
0
    else if (SecType->isStr("text"))
2300
0
      SecKind = Sema::PragmaClangSectionKind::PCSK_Text;
2301
0
    else {
2302
0
      PP.Diag(Tok.getLocation(), diag::err_pragma_expected_clang_section_name) << "clang section";
2303
0
      return;
2304
0
    }
2305
2306
0
    SourceLocation PragmaLocation = Tok.getLocation();
2307
0
    PP.Lex(Tok); // eat ['bss'|'data'|'rodata'|'text']
2308
0
    if (Tok.isNot(tok::equal)) {
2309
0
      PP.Diag(Tok.getLocation(), diag::err_pragma_clang_section_expected_equal) << SecKind;
2310
0
      return;
2311
0
    }
2312
2313
0
    std::string SecName;
2314
0
    if (!PP.LexStringLiteral(Tok, SecName, "pragma clang section", false))
2315
0
      return;
2316
2317
0
    Actions.ActOnPragmaClangSection(
2318
0
        PragmaLocation,
2319
0
        (SecName.size() ? Sema::PragmaClangSectionAction::PCSA_Set
2320
0
                        : Sema::PragmaClangSectionAction::PCSA_Clear),
2321
0
        SecKind, SecName);
2322
0
  }
2323
0
}
2324
2325
// #pragma 'align' '=' {'native','natural','mac68k','power','reset'}
2326
// #pragma 'options 'align' '=' {'native','natural','mac68k','power','reset'}
2327
// #pragma 'align' '(' {'native','natural','mac68k','power','reset'} ')'
2328
static void ParseAlignPragma(Preprocessor &PP, Token &FirstTok,
2329
0
                             bool IsOptions) {
2330
0
  Token Tok;
2331
2332
0
  if (IsOptions) {
2333
0
    PP.Lex(Tok);
2334
0
    if (Tok.isNot(tok::identifier) ||
2335
0
        !Tok.getIdentifierInfo()->isStr("align")) {
2336
0
      PP.Diag(Tok.getLocation(), diag::warn_pragma_options_expected_align);
2337
0
      return;
2338
0
    }
2339
0
  }
2340
2341
0
  PP.Lex(Tok);
2342
0
  if (PP.getLangOpts().XLPragmaPack) {
2343
0
    if (Tok.isNot(tok::l_paren)) {
2344
0
      PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "align";
2345
0
      return;
2346
0
    }
2347
0
  } else if (Tok.isNot(tok::equal)) {
2348
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_align_expected_equal)
2349
0
      << IsOptions;
2350
0
    return;
2351
0
  }
2352
2353
0
  PP.Lex(Tok);
2354
0
  if (Tok.isNot(tok::identifier)) {
2355
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
2356
0
      << (IsOptions ? "options" : "align");
2357
0
    return;
2358
0
  }
2359
2360
0
  Sema::PragmaOptionsAlignKind Kind = Sema::POAK_Natural;
2361
0
  const IdentifierInfo *II = Tok.getIdentifierInfo();
2362
0
  if (II->isStr("native"))
2363
0
    Kind = Sema::POAK_Native;
2364
0
  else if (II->isStr("natural"))
2365
0
    Kind = Sema::POAK_Natural;
2366
0
  else if (II->isStr("packed"))
2367
0
    Kind = Sema::POAK_Packed;
2368
0
  else if (II->isStr("power"))
2369
0
    Kind = Sema::POAK_Power;
2370
0
  else if (II->isStr("mac68k"))
2371
0
    Kind = Sema::POAK_Mac68k;
2372
0
  else if (II->isStr("reset"))
2373
0
    Kind = Sema::POAK_Reset;
2374
0
  else {
2375
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_align_invalid_option)
2376
0
      << IsOptions;
2377
0
    return;
2378
0
  }
2379
2380
0
  if (PP.getLangOpts().XLPragmaPack) {
2381
0
    PP.Lex(Tok);
2382
0
    if (Tok.isNot(tok::r_paren)) {
2383
0
      PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen) << "align";
2384
0
      return;
2385
0
    }
2386
0
  }
2387
2388
0
  SourceLocation EndLoc = Tok.getLocation();
2389
0
  PP.Lex(Tok);
2390
0
  if (Tok.isNot(tok::eod)) {
2391
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
2392
0
      << (IsOptions ? "options" : "align");
2393
0
    return;
2394
0
  }
2395
2396
0
  MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
2397
0
                              1);
2398
0
  Toks[0].startToken();
2399
0
  Toks[0].setKind(tok::annot_pragma_align);
2400
0
  Toks[0].setLocation(FirstTok.getLocation());
2401
0
  Toks[0].setAnnotationEndLoc(EndLoc);
2402
0
  Toks[0].setAnnotationValue(reinterpret_cast<void*>(
2403
0
                             static_cast<uintptr_t>(Kind)));
2404
0
  PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
2405
0
                      /*IsReinject=*/false);
2406
0
}
2407
2408
void PragmaAlignHandler::HandlePragma(Preprocessor &PP,
2409
                                      PragmaIntroducer Introducer,
2410
0
                                      Token &AlignTok) {
2411
0
  ParseAlignPragma(PP, AlignTok, /*IsOptions=*/false);
2412
0
}
2413
2414
void PragmaOptionsHandler::HandlePragma(Preprocessor &PP,
2415
                                        PragmaIntroducer Introducer,
2416
0
                                        Token &OptionsTok) {
2417
0
  ParseAlignPragma(PP, OptionsTok, /*IsOptions=*/true);
2418
0
}
2419
2420
// #pragma unused(identifier)
2421
void PragmaUnusedHandler::HandlePragma(Preprocessor &PP,
2422
                                       PragmaIntroducer Introducer,
2423
0
                                       Token &UnusedTok) {
2424
  // FIXME: Should we be expanding macros here? My guess is no.
2425
0
  SourceLocation UnusedLoc = UnusedTok.getLocation();
2426
2427
  // Lex the left '('.
2428
0
  Token Tok;
2429
0
  PP.Lex(Tok);
2430
0
  if (Tok.isNot(tok::l_paren)) {
2431
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "unused";
2432
0
    return;
2433
0
  }
2434
2435
  // Lex the declaration reference(s).
2436
0
  SmallVector<Token, 5> Identifiers;
2437
0
  SourceLocation RParenLoc;
2438
0
  bool LexID = true;
2439
2440
0
  while (true) {
2441
0
    PP.Lex(Tok);
2442
2443
0
    if (LexID) {
2444
0
      if (Tok.is(tok::identifier)) {
2445
0
        Identifiers.push_back(Tok);
2446
0
        LexID = false;
2447
0
        continue;
2448
0
      }
2449
2450
      // Illegal token!
2451
0
      PP.Diag(Tok.getLocation(), diag::warn_pragma_unused_expected_var);
2452
0
      return;
2453
0
    }
2454
2455
    // We are execting a ')' or a ','.
2456
0
    if (Tok.is(tok::comma)) {
2457
0
      LexID = true;
2458
0
      continue;
2459
0
    }
2460
2461
0
    if (Tok.is(tok::r_paren)) {
2462
0
      RParenLoc = Tok.getLocation();
2463
0
      break;
2464
0
    }
2465
2466
    // Illegal token!
2467
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_punc) << "unused";
2468
0
    return;
2469
0
  }
2470
2471
0
  PP.Lex(Tok);
2472
0
  if (Tok.isNot(tok::eod)) {
2473
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
2474
0
        "unused";
2475
0
    return;
2476
0
  }
2477
2478
  // Verify that we have a location for the right parenthesis.
2479
0
  assert(RParenLoc.isValid() && "Valid '#pragma unused' must have ')'");
2480
0
  assert(!Identifiers.empty() && "Valid '#pragma unused' must have arguments");
2481
2482
  // For each identifier token, insert into the token stream a
2483
  // annot_pragma_unused token followed by the identifier token.
2484
  // This allows us to cache a "#pragma unused" that occurs inside an inline
2485
  // C++ member function.
2486
2487
0
  MutableArrayRef<Token> Toks(
2488
0
      PP.getPreprocessorAllocator().Allocate<Token>(2 * Identifiers.size()),
2489
0
      2 * Identifiers.size());
2490
0
  for (unsigned i=0; i != Identifiers.size(); i++) {
2491
0
    Token &pragmaUnusedTok = Toks[2*i], &idTok = Toks[2*i+1];
2492
0
    pragmaUnusedTok.startToken();
2493
0
    pragmaUnusedTok.setKind(tok::annot_pragma_unused);
2494
0
    pragmaUnusedTok.setLocation(UnusedLoc);
2495
0
    idTok = Identifiers[i];
2496
0
  }
2497
0
  PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
2498
0
                      /*IsReinject=*/false);
2499
0
}
2500
2501
// #pragma weak identifier
2502
// #pragma weak identifier '=' identifier
2503
void PragmaWeakHandler::HandlePragma(Preprocessor &PP,
2504
                                     PragmaIntroducer Introducer,
2505
0
                                     Token &WeakTok) {
2506
0
  SourceLocation WeakLoc = WeakTok.getLocation();
2507
2508
0
  Token Tok;
2509
0
  PP.Lex(Tok);
2510
0
  if (Tok.isNot(tok::identifier)) {
2511
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) << "weak";
2512
0
    return;
2513
0
  }
2514
2515
0
  Token WeakName = Tok;
2516
0
  bool HasAlias = false;
2517
0
  Token AliasName;
2518
2519
0
  PP.Lex(Tok);
2520
0
  if (Tok.is(tok::equal)) {
2521
0
    HasAlias = true;
2522
0
    PP.Lex(Tok);
2523
0
    if (Tok.isNot(tok::identifier)) {
2524
0
      PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
2525
0
          << "weak";
2526
0
      return;
2527
0
    }
2528
0
    AliasName = Tok;
2529
0
    PP.Lex(Tok);
2530
0
  }
2531
2532
0
  if (Tok.isNot(tok::eod)) {
2533
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "weak";
2534
0
    return;
2535
0
  }
2536
2537
0
  if (HasAlias) {
2538
0
    MutableArrayRef<Token> Toks(
2539
0
        PP.getPreprocessorAllocator().Allocate<Token>(3), 3);
2540
0
    Token &pragmaUnusedTok = Toks[0];
2541
0
    pragmaUnusedTok.startToken();
2542
0
    pragmaUnusedTok.setKind(tok::annot_pragma_weakalias);
2543
0
    pragmaUnusedTok.setLocation(WeakLoc);
2544
0
    pragmaUnusedTok.setAnnotationEndLoc(AliasName.getLocation());
2545
0
    Toks[1] = WeakName;
2546
0
    Toks[2] = AliasName;
2547
0
    PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
2548
0
                        /*IsReinject=*/false);
2549
0
  } else {
2550
0
    MutableArrayRef<Token> Toks(
2551
0
        PP.getPreprocessorAllocator().Allocate<Token>(2), 2);
2552
0
    Token &pragmaUnusedTok = Toks[0];
2553
0
    pragmaUnusedTok.startToken();
2554
0
    pragmaUnusedTok.setKind(tok::annot_pragma_weak);
2555
0
    pragmaUnusedTok.setLocation(WeakLoc);
2556
0
    pragmaUnusedTok.setAnnotationEndLoc(WeakLoc);
2557
0
    Toks[1] = WeakName;
2558
0
    PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
2559
0
                        /*IsReinject=*/false);
2560
0
  }
2561
0
}
2562
2563
// #pragma redefine_extname identifier identifier
2564
void PragmaRedefineExtnameHandler::HandlePragma(Preprocessor &PP,
2565
                                                PragmaIntroducer Introducer,
2566
0
                                                Token &RedefToken) {
2567
0
  SourceLocation RedefLoc = RedefToken.getLocation();
2568
2569
0
  Token Tok;
2570
0
  PP.Lex(Tok);
2571
0
  if (Tok.isNot(tok::identifier)) {
2572
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) <<
2573
0
      "redefine_extname";
2574
0
    return;
2575
0
  }
2576
2577
0
  Token RedefName = Tok;
2578
0
  PP.Lex(Tok);
2579
2580
0
  if (Tok.isNot(tok::identifier)) {
2581
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
2582
0
        << "redefine_extname";
2583
0
    return;
2584
0
  }
2585
2586
0
  Token AliasName = Tok;
2587
0
  PP.Lex(Tok);
2588
2589
0
  if (Tok.isNot(tok::eod)) {
2590
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
2591
0
      "redefine_extname";
2592
0
    return;
2593
0
  }
2594
2595
0
  MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(3),
2596
0
                              3);
2597
0
  Token &pragmaRedefTok = Toks[0];
2598
0
  pragmaRedefTok.startToken();
2599
0
  pragmaRedefTok.setKind(tok::annot_pragma_redefine_extname);
2600
0
  pragmaRedefTok.setLocation(RedefLoc);
2601
0
  pragmaRedefTok.setAnnotationEndLoc(AliasName.getLocation());
2602
0
  Toks[1] = RedefName;
2603
0
  Toks[2] = AliasName;
2604
0
  PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
2605
0
                      /*IsReinject=*/false);
2606
0
}
2607
2608
void PragmaFPContractHandler::HandlePragma(Preprocessor &PP,
2609
                                           PragmaIntroducer Introducer,
2610
0
                                           Token &Tok) {
2611
0
  tok::OnOffSwitch OOS;
2612
0
  if (PP.LexOnOffSwitch(OOS))
2613
0
    return;
2614
2615
0
  MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
2616
0
                              1);
2617
0
  Toks[0].startToken();
2618
0
  Toks[0].setKind(tok::annot_pragma_fp_contract);
2619
0
  Toks[0].setLocation(Tok.getLocation());
2620
0
  Toks[0].setAnnotationEndLoc(Tok.getLocation());
2621
0
  Toks[0].setAnnotationValue(reinterpret_cast<void*>(
2622
0
                             static_cast<uintptr_t>(OOS)));
2623
0
  PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
2624
0
                      /*IsReinject=*/false);
2625
0
}
2626
2627
void PragmaOpenCLExtensionHandler::HandlePragma(Preprocessor &PP,
2628
                                                PragmaIntroducer Introducer,
2629
0
                                                Token &Tok) {
2630
0
  PP.LexUnexpandedToken(Tok);
2631
0
  if (Tok.isNot(tok::identifier)) {
2632
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) <<
2633
0
      "OPENCL";
2634
0
    return;
2635
0
  }
2636
0
  IdentifierInfo *Ext = Tok.getIdentifierInfo();
2637
0
  SourceLocation NameLoc = Tok.getLocation();
2638
2639
0
  PP.Lex(Tok);
2640
0
  if (Tok.isNot(tok::colon)) {
2641
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_colon) << Ext;
2642
0
    return;
2643
0
  }
2644
2645
0
  PP.Lex(Tok);
2646
0
  if (Tok.isNot(tok::identifier)) {
2647
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_predicate) << 0;
2648
0
    return;
2649
0
  }
2650
0
  IdentifierInfo *Pred = Tok.getIdentifierInfo();
2651
2652
0
  OpenCLExtState State;
2653
0
  if (Pred->isStr("enable")) {
2654
0
    State = Enable;
2655
0
  } else if (Pred->isStr("disable")) {
2656
0
    State = Disable;
2657
0
  } else if (Pred->isStr("begin"))
2658
0
    State = Begin;
2659
0
  else if (Pred->isStr("end"))
2660
0
    State = End;
2661
0
  else {
2662
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_predicate)
2663
0
      << Ext->isStr("all");
2664
0
    return;
2665
0
  }
2666
0
  SourceLocation StateLoc = Tok.getLocation();
2667
2668
0
  PP.Lex(Tok);
2669
0
  if (Tok.isNot(tok::eod)) {
2670
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
2671
0
      "OPENCL EXTENSION";
2672
0
    return;
2673
0
  }
2674
2675
0
  auto Info = PP.getPreprocessorAllocator().Allocate<OpenCLExtData>(1);
2676
0
  Info->first = Ext;
2677
0
  Info->second = State;
2678
0
  MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
2679
0
                              1);
2680
0
  Toks[0].startToken();
2681
0
  Toks[0].setKind(tok::annot_pragma_opencl_extension);
2682
0
  Toks[0].setLocation(NameLoc);
2683
0
  Toks[0].setAnnotationValue(static_cast<void*>(Info));
2684
0
  Toks[0].setAnnotationEndLoc(StateLoc);
2685
0
  PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
2686
0
                      /*IsReinject=*/false);
2687
2688
0
  if (PP.getPPCallbacks())
2689
0
    PP.getPPCallbacks()->PragmaOpenCLExtension(NameLoc, Ext,
2690
0
                                               StateLoc, State);
2691
0
}
2692
2693
/// Handle '#pragma omp ...' when OpenMP is disabled and '#pragma acc ...' when
2694
/// OpenACC is disabled.
2695
template <diag::kind IgnoredDiag>
2696
void PragmaNoSupportHandler<IgnoredDiag>::HandlePragma(
2697
0
    Preprocessor &PP, PragmaIntroducer Introducer, Token &FirstTok) {
2698
0
  if (!PP.getDiagnostics().isIgnored(IgnoredDiag, FirstTok.getLocation())) {
2699
0
    PP.Diag(FirstTok, IgnoredDiag);
2700
0
    PP.getDiagnostics().setSeverity(IgnoredDiag, diag::Severity::Ignored,
2701
0
                                    SourceLocation());
2702
0
  }
2703
0
  PP.DiscardUntilEndOfDirective();
2704
0
}
Unexecuted instantiation: ParsePragma.cpp:(anonymous namespace)::PragmaNoSupportHandler<2009u>::HandlePragma(clang::Preprocessor&, clang::PragmaIntroducer, clang::Token&)
Unexecuted instantiation: ParsePragma.cpp:(anonymous namespace)::PragmaNoSupportHandler<1975u>::HandlePragma(clang::Preprocessor&, clang::PragmaIntroducer, clang::Token&)
2705
2706
/// Handle '#pragma omp ...' when OpenMP is enabled, and handle '#pragma acc...'
2707
/// when OpenACC is enabled.
2708
template <tok::TokenKind StartTok, tok::TokenKind EndTok,
2709
          diag::kind UnexpectedDiag>
2710
void PragmaSupportHandler<StartTok, EndTok, UnexpectedDiag>::HandlePragma(
2711
0
    Preprocessor &PP, PragmaIntroducer Introducer, Token &FirstTok) {
2712
0
  SmallVector<Token, 16> Pragma;
2713
0
  Token Tok;
2714
0
  Tok.startToken();
2715
0
  Tok.setKind(StartTok);
2716
0
  Tok.setLocation(Introducer.Loc);
2717
2718
0
  while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof)) {
2719
0
    Pragma.push_back(Tok);
2720
0
    PP.Lex(Tok);
2721
0
    if (Tok.is(StartTok)) {
2722
0
      PP.Diag(Tok, UnexpectedDiag) << 0;
2723
0
      unsigned InnerPragmaCnt = 1;
2724
0
      while (InnerPragmaCnt != 0) {
2725
0
        PP.Lex(Tok);
2726
0
        if (Tok.is(StartTok))
2727
0
          ++InnerPragmaCnt;
2728
0
        else if (Tok.is(EndTok))
2729
0
          --InnerPragmaCnt;
2730
0
      }
2731
0
      PP.Lex(Tok);
2732
0
    }
2733
0
  }
2734
0
  SourceLocation EodLoc = Tok.getLocation();
2735
0
  Tok.startToken();
2736
0
  Tok.setKind(EndTok);
2737
0
  Tok.setLocation(EodLoc);
2738
0
  Pragma.push_back(Tok);
2739
2740
0
  auto Toks = std::make_unique<Token[]>(Pragma.size());
2741
0
  std::copy(Pragma.begin(), Pragma.end(), Toks.get());
2742
0
  PP.EnterTokenStream(std::move(Toks), Pragma.size(),
2743
0
                      /*DisableMacroExpansion=*/false, /*IsReinject=*/false);
2744
0
}
Unexecuted instantiation: ParsePragma.cpp:(anonymous namespace)::PragmaSupportHandler<(clang::tok::TokenKind)430, (clang::tok::TokenKind)431, 1647u>::HandlePragma(clang::Preprocessor&, clang::PragmaIntroducer, clang::Token&)
Unexecuted instantiation: ParsePragma.cpp:(anonymous namespace)::PragmaSupportHandler<(clang::tok::TokenKind)432, (clang::tok::TokenKind)433, 1379u>::HandlePragma(clang::Preprocessor&, clang::PragmaIntroducer, clang::Token&)
2745
2746
/// Handle '#pragma pointers_to_members'
2747
// The grammar for this pragma is as follows:
2748
//
2749
// <inheritance model> ::= ('single' | 'multiple' | 'virtual') '_inheritance'
2750
//
2751
// #pragma pointers_to_members '(' 'best_case' ')'
2752
// #pragma pointers_to_members '(' 'full_generality' [',' inheritance-model] ')'
2753
// #pragma pointers_to_members '(' inheritance-model ')'
2754
void PragmaMSPointersToMembers::HandlePragma(Preprocessor &PP,
2755
                                             PragmaIntroducer Introducer,
2756
0
                                             Token &Tok) {
2757
0
  SourceLocation PointersToMembersLoc = Tok.getLocation();
2758
0
  PP.Lex(Tok);
2759
0
  if (Tok.isNot(tok::l_paren)) {
2760
0
    PP.Diag(PointersToMembersLoc, diag::warn_pragma_expected_lparen)
2761
0
      << "pointers_to_members";
2762
0
    return;
2763
0
  }
2764
0
  PP.Lex(Tok);
2765
0
  const IdentifierInfo *Arg = Tok.getIdentifierInfo();
2766
0
  if (!Arg) {
2767
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
2768
0
      << "pointers_to_members";
2769
0
    return;
2770
0
  }
2771
0
  PP.Lex(Tok);
2772
2773
0
  LangOptions::PragmaMSPointersToMembersKind RepresentationMethod;
2774
0
  if (Arg->isStr("best_case")) {
2775
0
    RepresentationMethod = LangOptions::PPTMK_BestCase;
2776
0
  } else {
2777
0
    if (Arg->isStr("full_generality")) {
2778
0
      if (Tok.is(tok::comma)) {
2779
0
        PP.Lex(Tok);
2780
2781
0
        Arg = Tok.getIdentifierInfo();
2782
0
        if (!Arg) {
2783
0
          PP.Diag(Tok.getLocation(),
2784
0
                  diag::err_pragma_pointers_to_members_unknown_kind)
2785
0
              << Tok.getKind() << /*OnlyInheritanceModels*/ 0;
2786
0
          return;
2787
0
        }
2788
0
        PP.Lex(Tok);
2789
0
      } else if (Tok.is(tok::r_paren)) {
2790
        // #pragma pointers_to_members(full_generality) implicitly specifies
2791
        // virtual_inheritance.
2792
0
        Arg = nullptr;
2793
0
        RepresentationMethod = LangOptions::PPTMK_FullGeneralityVirtualInheritance;
2794
0
      } else {
2795
0
        PP.Diag(Tok.getLocation(), diag::err_expected_punc)
2796
0
            << "full_generality";
2797
0
        return;
2798
0
      }
2799
0
    }
2800
2801
0
    if (Arg) {
2802
0
      if (Arg->isStr("single_inheritance")) {
2803
0
        RepresentationMethod =
2804
0
            LangOptions::PPTMK_FullGeneralitySingleInheritance;
2805
0
      } else if (Arg->isStr("multiple_inheritance")) {
2806
0
        RepresentationMethod =
2807
0
            LangOptions::PPTMK_FullGeneralityMultipleInheritance;
2808
0
      } else if (Arg->isStr("virtual_inheritance")) {
2809
0
        RepresentationMethod =
2810
0
            LangOptions::PPTMK_FullGeneralityVirtualInheritance;
2811
0
      } else {
2812
0
        PP.Diag(Tok.getLocation(),
2813
0
                diag::err_pragma_pointers_to_members_unknown_kind)
2814
0
            << Arg << /*HasPointerDeclaration*/ 1;
2815
0
        return;
2816
0
      }
2817
0
    }
2818
0
  }
2819
2820
0
  if (Tok.isNot(tok::r_paren)) {
2821
0
    PP.Diag(Tok.getLocation(), diag::err_expected_rparen_after)
2822
0
        << (Arg ? Arg->getName() : "full_generality");
2823
0
    return;
2824
0
  }
2825
2826
0
  SourceLocation EndLoc = Tok.getLocation();
2827
0
  PP.Lex(Tok);
2828
0
  if (Tok.isNot(tok::eod)) {
2829
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
2830
0
      << "pointers_to_members";
2831
0
    return;
2832
0
  }
2833
2834
0
  Token AnnotTok;
2835
0
  AnnotTok.startToken();
2836
0
  AnnotTok.setKind(tok::annot_pragma_ms_pointers_to_members);
2837
0
  AnnotTok.setLocation(PointersToMembersLoc);
2838
0
  AnnotTok.setAnnotationEndLoc(EndLoc);
2839
0
  AnnotTok.setAnnotationValue(
2840
0
      reinterpret_cast<void *>(static_cast<uintptr_t>(RepresentationMethod)));
2841
0
  PP.EnterToken(AnnotTok, /*IsReinject=*/true);
2842
0
}
2843
2844
/// Handle '#pragma vtordisp'
2845
// The grammar for this pragma is as follows:
2846
//
2847
// <vtordisp-mode> ::= ('off' | 'on' | '0' | '1' | '2' )
2848
//
2849
// #pragma vtordisp '(' ['push' ','] vtordisp-mode ')'
2850
// #pragma vtordisp '(' 'pop' ')'
2851
// #pragma vtordisp '(' ')'
2852
void PragmaMSVtorDisp::HandlePragma(Preprocessor &PP,
2853
0
                                    PragmaIntroducer Introducer, Token &Tok) {
2854
0
  SourceLocation VtorDispLoc = Tok.getLocation();
2855
0
  PP.Lex(Tok);
2856
0
  if (Tok.isNot(tok::l_paren)) {
2857
0
    PP.Diag(VtorDispLoc, diag::warn_pragma_expected_lparen) << "vtordisp";
2858
0
    return;
2859
0
  }
2860
0
  PP.Lex(Tok);
2861
2862
0
  Sema::PragmaMsStackAction Action = Sema::PSK_Set;
2863
0
  const IdentifierInfo *II = Tok.getIdentifierInfo();
2864
0
  if (II) {
2865
0
    if (II->isStr("push")) {
2866
      // #pragma vtordisp(push, mode)
2867
0
      PP.Lex(Tok);
2868
0
      if (Tok.isNot(tok::comma)) {
2869
0
        PP.Diag(VtorDispLoc, diag::warn_pragma_expected_punc) << "vtordisp";
2870
0
        return;
2871
0
      }
2872
0
      PP.Lex(Tok);
2873
0
      Action = Sema::PSK_Push_Set;
2874
      // not push, could be on/off
2875
0
    } else if (II->isStr("pop")) {
2876
      // #pragma vtordisp(pop)
2877
0
      PP.Lex(Tok);
2878
0
      Action = Sema::PSK_Pop;
2879
0
    }
2880
    // not push or pop, could be on/off
2881
0
  } else {
2882
0
    if (Tok.is(tok::r_paren)) {
2883
      // #pragma vtordisp()
2884
0
      Action = Sema::PSK_Reset;
2885
0
    }
2886
0
  }
2887
2888
2889
0
  uint64_t Value = 0;
2890
0
  if (Action & Sema::PSK_Push || Action & Sema::PSK_Set) {
2891
0
    const IdentifierInfo *II = Tok.getIdentifierInfo();
2892
0
    if (II && II->isStr("off")) {
2893
0
      PP.Lex(Tok);
2894
0
      Value = 0;
2895
0
    } else if (II && II->isStr("on")) {
2896
0
      PP.Lex(Tok);
2897
0
      Value = 1;
2898
0
    } else if (Tok.is(tok::numeric_constant) &&
2899
0
               PP.parseSimpleIntegerLiteral(Tok, Value)) {
2900
0
      if (Value > 2) {
2901
0
        PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_integer)
2902
0
            << 0 << 2 << "vtordisp";
2903
0
        return;
2904
0
      }
2905
0
    } else {
2906
0
      PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_action)
2907
0
          << "vtordisp";
2908
0
      return;
2909
0
    }
2910
0
  }
2911
2912
  // Finish the pragma: ')' $
2913
0
  if (Tok.isNot(tok::r_paren)) {
2914
0
    PP.Diag(VtorDispLoc, diag::warn_pragma_expected_rparen) << "vtordisp";
2915
0
    return;
2916
0
  }
2917
0
  SourceLocation EndLoc = Tok.getLocation();
2918
0
  PP.Lex(Tok);
2919
0
  if (Tok.isNot(tok::eod)) {
2920
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
2921
0
        << "vtordisp";
2922
0
    return;
2923
0
  }
2924
2925
  // Enter the annotation.
2926
0
  Token AnnotTok;
2927
0
  AnnotTok.startToken();
2928
0
  AnnotTok.setKind(tok::annot_pragma_ms_vtordisp);
2929
0
  AnnotTok.setLocation(VtorDispLoc);
2930
0
  AnnotTok.setAnnotationEndLoc(EndLoc);
2931
0
  AnnotTok.setAnnotationValue(reinterpret_cast<void *>(
2932
0
      static_cast<uintptr_t>((Action << 16) | (Value & 0xFFFF))));
2933
0
  PP.EnterToken(AnnotTok, /*IsReinject=*/false);
2934
0
}
2935
2936
/// Handle all MS pragmas.  Simply forwards the tokens after inserting
2937
/// an annotation token.
2938
void PragmaMSPragma::HandlePragma(Preprocessor &PP,
2939
0
                                  PragmaIntroducer Introducer, Token &Tok) {
2940
0
  Token EoF, AnnotTok;
2941
0
  EoF.startToken();
2942
0
  EoF.setKind(tok::eof);
2943
0
  AnnotTok.startToken();
2944
0
  AnnotTok.setKind(tok::annot_pragma_ms_pragma);
2945
0
  AnnotTok.setLocation(Tok.getLocation());
2946
0
  AnnotTok.setAnnotationEndLoc(Tok.getLocation());
2947
0
  SmallVector<Token, 8> TokenVector;
2948
  // Suck up all of the tokens before the eod.
2949
0
  for (; Tok.isNot(tok::eod); PP.Lex(Tok)) {
2950
0
    TokenVector.push_back(Tok);
2951
0
    AnnotTok.setAnnotationEndLoc(Tok.getLocation());
2952
0
  }
2953
  // Add a sentinel EoF token to the end of the list.
2954
0
  TokenVector.push_back(EoF);
2955
  // We must allocate this array with new because EnterTokenStream is going to
2956
  // delete it later.
2957
0
  markAsReinjectedForRelexing(TokenVector);
2958
0
  auto TokenArray = std::make_unique<Token[]>(TokenVector.size());
2959
0
  std::copy(TokenVector.begin(), TokenVector.end(), TokenArray.get());
2960
0
  auto Value = new (PP.getPreprocessorAllocator())
2961
0
      std::pair<std::unique_ptr<Token[]>, size_t>(std::move(TokenArray),
2962
0
                                                  TokenVector.size());
2963
0
  AnnotTok.setAnnotationValue(Value);
2964
0
  PP.EnterToken(AnnotTok, /*IsReinject*/ false);
2965
0
}
2966
2967
/// Handle the \#pragma float_control extension.
2968
///
2969
/// The syntax is:
2970
/// \code
2971
///   #pragma float_control(keyword[, setting] [,push])
2972
/// \endcode
2973
/// Where 'keyword' and 'setting' are identifiers.
2974
// 'keyword' can be: precise, except, push, pop
2975
// 'setting' can be: on, off
2976
/// The optional arguments 'setting' and 'push' are supported only
2977
/// when the keyword is 'precise' or 'except'.
2978
void PragmaFloatControlHandler::HandlePragma(Preprocessor &PP,
2979
                                             PragmaIntroducer Introducer,
2980
0
                                             Token &Tok) {
2981
0
  Sema::PragmaMsStackAction Action = Sema::PSK_Set;
2982
0
  SourceLocation FloatControlLoc = Tok.getLocation();
2983
0
  Token PragmaName = Tok;
2984
0
  if (!PP.getTargetInfo().hasStrictFP() && !PP.getLangOpts().ExpStrictFP) {
2985
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_fp_ignored)
2986
0
        << PragmaName.getIdentifierInfo()->getName();
2987
0
    return;
2988
0
  }
2989
0
  PP.Lex(Tok);
2990
0
  if (Tok.isNot(tok::l_paren)) {
2991
0
    PP.Diag(FloatControlLoc, diag::err_expected) << tok::l_paren;
2992
0
    return;
2993
0
  }
2994
2995
  // Read the identifier.
2996
0
  PP.Lex(Tok);
2997
0
  if (Tok.isNot(tok::identifier)) {
2998
0
    PP.Diag(Tok.getLocation(), diag::err_pragma_float_control_malformed);
2999
0
    return;
3000
0
  }
3001
3002
  // Verify that this is one of the float control options.
3003
0
  IdentifierInfo *II = Tok.getIdentifierInfo();
3004
0
  PragmaFloatControlKind Kind =
3005
0
      llvm::StringSwitch<PragmaFloatControlKind>(II->getName())
3006
0
          .Case("precise", PFC_Precise)
3007
0
          .Case("except", PFC_Except)
3008
0
          .Case("push", PFC_Push)
3009
0
          .Case("pop", PFC_Pop)
3010
0
          .Default(PFC_Unknown);
3011
0
  PP.Lex(Tok); // the identifier
3012
0
  if (Kind == PFC_Unknown) {
3013
0
    PP.Diag(Tok.getLocation(), diag::err_pragma_float_control_malformed);
3014
0
    return;
3015
0
  } else if (Kind == PFC_Push || Kind == PFC_Pop) {
3016
0
    if (Tok.isNot(tok::r_paren)) {
3017
0
      PP.Diag(Tok.getLocation(), diag::err_pragma_float_control_malformed);
3018
0
      return;
3019
0
    }
3020
0
    PP.Lex(Tok); // Eat the r_paren
3021
0
    Action = (Kind == PFC_Pop) ? Sema::PSK_Pop : Sema::PSK_Push;
3022
0
  } else {
3023
0
    if (Tok.is(tok::r_paren))
3024
      // Selecting Precise or Except
3025
0
      PP.Lex(Tok); // the r_paren
3026
0
    else if (Tok.isNot(tok::comma)) {
3027
0
      PP.Diag(Tok.getLocation(), diag::err_pragma_float_control_malformed);
3028
0
      return;
3029
0
    } else {
3030
0
      PP.Lex(Tok); // ,
3031
0
      if (!Tok.isAnyIdentifier()) {
3032
0
        PP.Diag(Tok.getLocation(), diag::err_pragma_float_control_malformed);
3033
0
        return;
3034
0
      }
3035
0
      StringRef PushOnOff = Tok.getIdentifierInfo()->getName();
3036
0
      if (PushOnOff == "on")
3037
        // Kind is set correctly
3038
0
        ;
3039
0
      else if (PushOnOff == "off") {
3040
0
        if (Kind == PFC_Precise)
3041
0
          Kind = PFC_NoPrecise;
3042
0
        if (Kind == PFC_Except)
3043
0
          Kind = PFC_NoExcept;
3044
0
      } else if (PushOnOff == "push") {
3045
0
        Action = Sema::PSK_Push_Set;
3046
0
      } else {
3047
0
        PP.Diag(Tok.getLocation(), diag::err_pragma_float_control_malformed);
3048
0
        return;
3049
0
      }
3050
0
      PP.Lex(Tok); // the identifier
3051
0
      if (Tok.is(tok::comma)) {
3052
0
        PP.Lex(Tok); // ,
3053
0
        if (!Tok.isAnyIdentifier()) {
3054
0
          PP.Diag(Tok.getLocation(), diag::err_pragma_float_control_malformed);
3055
0
          return;
3056
0
        }
3057
0
        StringRef ExpectedPush = Tok.getIdentifierInfo()->getName();
3058
0
        if (ExpectedPush == "push") {
3059
0
          Action = Sema::PSK_Push_Set;
3060
0
        } else {
3061
0
          PP.Diag(Tok.getLocation(), diag::err_pragma_float_control_malformed);
3062
0
          return;
3063
0
        }
3064
0
        PP.Lex(Tok); // the push identifier
3065
0
      }
3066
0
      if (Tok.isNot(tok::r_paren)) {
3067
0
        PP.Diag(Tok.getLocation(), diag::err_pragma_float_control_malformed);
3068
0
        return;
3069
0
      }
3070
0
      PP.Lex(Tok); // the r_paren
3071
0
    }
3072
0
  }
3073
0
  SourceLocation EndLoc = Tok.getLocation();
3074
0
  if (Tok.isNot(tok::eod)) {
3075
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
3076
0
        << "float_control";
3077
0
    return;
3078
0
  }
3079
3080
  // Note: there is no accomodation for PP callback for this pragma.
3081
3082
  // Enter the annotation.
3083
0
  auto TokenArray = std::make_unique<Token[]>(1);
3084
0
  TokenArray[0].startToken();
3085
0
  TokenArray[0].setKind(tok::annot_pragma_float_control);
3086
0
  TokenArray[0].setLocation(FloatControlLoc);
3087
0
  TokenArray[0].setAnnotationEndLoc(EndLoc);
3088
  // Create an encoding of Action and Value by shifting the Action into
3089
  // the high 16 bits then union with the Kind.
3090
0
  TokenArray[0].setAnnotationValue(reinterpret_cast<void *>(
3091
0
      static_cast<uintptr_t>((Action << 16) | (Kind & 0xFFFF))));
3092
0
  PP.EnterTokenStream(std::move(TokenArray), 1,
3093
0
                      /*DisableMacroExpansion=*/false, /*IsReinject=*/false);
3094
0
}
3095
3096
/// Handle the Microsoft \#pragma detect_mismatch extension.
3097
///
3098
/// The syntax is:
3099
/// \code
3100
///   #pragma detect_mismatch("name", "value")
3101
/// \endcode
3102
/// Where 'name' and 'value' are quoted strings.  The values are embedded in
3103
/// the object file and passed along to the linker.  If the linker detects a
3104
/// mismatch in the object file's values for the given name, a LNK2038 error
3105
/// is emitted.  See MSDN for more details.
3106
void PragmaDetectMismatchHandler::HandlePragma(Preprocessor &PP,
3107
                                               PragmaIntroducer Introducer,
3108
0
                                               Token &Tok) {
3109
0
  SourceLocation DetectMismatchLoc = Tok.getLocation();
3110
0
  PP.Lex(Tok);
3111
0
  if (Tok.isNot(tok::l_paren)) {
3112
0
    PP.Diag(DetectMismatchLoc, diag::err_expected) << tok::l_paren;
3113
0
    return;
3114
0
  }
3115
3116
  // Read the name to embed, which must be a string literal.
3117
0
  std::string NameString;
3118
0
  if (!PP.LexStringLiteral(Tok, NameString,
3119
0
                           "pragma detect_mismatch",
3120
0
                           /*AllowMacroExpansion=*/true))
3121
0
    return;
3122
3123
  // Read the comma followed by a second string literal.
3124
0
  std::string ValueString;
3125
0
  if (Tok.isNot(tok::comma)) {
3126
0
    PP.Diag(Tok.getLocation(), diag::err_pragma_detect_mismatch_malformed);
3127
0
    return;
3128
0
  }
3129
3130
0
  if (!PP.LexStringLiteral(Tok, ValueString, "pragma detect_mismatch",
3131
0
                           /*AllowMacroExpansion=*/true))
3132
0
    return;
3133
3134
0
  if (Tok.isNot(tok::r_paren)) {
3135
0
    PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
3136
0
    return;
3137
0
  }
3138
0
  PP.Lex(Tok);  // Eat the r_paren.
3139
3140
0
  if (Tok.isNot(tok::eod)) {
3141
0
    PP.Diag(Tok.getLocation(), diag::err_pragma_detect_mismatch_malformed);
3142
0
    return;
3143
0
  }
3144
3145
  // If the pragma is lexically sound, notify any interested PPCallbacks.
3146
0
  if (PP.getPPCallbacks())
3147
0
    PP.getPPCallbacks()->PragmaDetectMismatch(DetectMismatchLoc, NameString,
3148
0
                                              ValueString);
3149
3150
0
  Actions.ActOnPragmaDetectMismatch(DetectMismatchLoc, NameString, ValueString);
3151
0
}
3152
3153
/// Handle the microsoft \#pragma comment extension.
3154
///
3155
/// The syntax is:
3156
/// \code
3157
///   #pragma comment(linker, "foo")
3158
/// \endcode
3159
/// 'linker' is one of five identifiers: compiler, exestr, lib, linker, user.
3160
/// "foo" is a string, which is fully macro expanded, and permits string
3161
/// concatenation, embedded escape characters etc.  See MSDN for more details.
3162
void PragmaCommentHandler::HandlePragma(Preprocessor &PP,
3163
                                        PragmaIntroducer Introducer,
3164
0
                                        Token &Tok) {
3165
0
  SourceLocation CommentLoc = Tok.getLocation();
3166
0
  PP.Lex(Tok);
3167
0
  if (Tok.isNot(tok::l_paren)) {
3168
0
    PP.Diag(CommentLoc, diag::err_pragma_comment_malformed);
3169
0
    return;
3170
0
  }
3171
3172
  // Read the identifier.
3173
0
  PP.Lex(Tok);
3174
0
  if (Tok.isNot(tok::identifier)) {
3175
0
    PP.Diag(CommentLoc, diag::err_pragma_comment_malformed);
3176
0
    return;
3177
0
  }
3178
3179
  // Verify that this is one of the 5 explicitly listed options.
3180
0
  IdentifierInfo *II = Tok.getIdentifierInfo();
3181
0
  PragmaMSCommentKind Kind =
3182
0
    llvm::StringSwitch<PragmaMSCommentKind>(II->getName())
3183
0
    .Case("linker",   PCK_Linker)
3184
0
    .Case("lib",      PCK_Lib)
3185
0
    .Case("compiler", PCK_Compiler)
3186
0
    .Case("exestr",   PCK_ExeStr)
3187
0
    .Case("user",     PCK_User)
3188
0
    .Default(PCK_Unknown);
3189
0
  if (Kind == PCK_Unknown) {
3190
0
    PP.Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind);
3191
0
    return;
3192
0
  }
3193
3194
0
  if (PP.getTargetInfo().getTriple().isOSBinFormatELF() && Kind != PCK_Lib) {
3195
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_comment_ignored)
3196
0
        << II->getName();
3197
0
    return;
3198
0
  }
3199
3200
  // Read the optional string if present.
3201
0
  PP.Lex(Tok);
3202
0
  std::string ArgumentString;
3203
0
  if (Tok.is(tok::comma) && !PP.LexStringLiteral(Tok, ArgumentString,
3204
0
                                                 "pragma comment",
3205
0
                                                 /*AllowMacroExpansion=*/true))
3206
0
    return;
3207
3208
  // FIXME: warn that 'exestr' is deprecated.
3209
  // FIXME: If the kind is "compiler" warn if the string is present (it is
3210
  // ignored).
3211
  // The MSDN docs say that "lib" and "linker" require a string and have a short
3212
  // list of linker options they support, but in practice MSVC doesn't
3213
  // issue a diagnostic.  Therefore neither does clang.
3214
3215
0
  if (Tok.isNot(tok::r_paren)) {
3216
0
    PP.Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
3217
0
    return;
3218
0
  }
3219
0
  PP.Lex(Tok);  // eat the r_paren.
3220
3221
0
  if (Tok.isNot(tok::eod)) {
3222
0
    PP.Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
3223
0
    return;
3224
0
  }
3225
3226
  // If the pragma is lexically sound, notify any interested PPCallbacks.
3227
0
  if (PP.getPPCallbacks())
3228
0
    PP.getPPCallbacks()->PragmaComment(CommentLoc, II, ArgumentString);
3229
3230
0
  Actions.ActOnPragmaMSComment(CommentLoc, Kind, ArgumentString);
3231
0
}
3232
3233
// #pragma clang optimize off
3234
// #pragma clang optimize on
3235
void PragmaOptimizeHandler::HandlePragma(Preprocessor &PP,
3236
                                         PragmaIntroducer Introducer,
3237
0
                                         Token &FirstToken) {
3238
0
  Token Tok;
3239
0
  PP.Lex(Tok);
3240
0
  if (Tok.is(tok::eod)) {
3241
0
    PP.Diag(Tok.getLocation(), diag::err_pragma_missing_argument)
3242
0
        << "clang optimize" << /*Expected=*/true << "'on' or 'off'";
3243
0
    return;
3244
0
  }
3245
0
  if (Tok.isNot(tok::identifier)) {
3246
0
    PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_invalid_argument)
3247
0
      << PP.getSpelling(Tok);
3248
0
    return;
3249
0
  }
3250
0
  const IdentifierInfo *II = Tok.getIdentifierInfo();
3251
  // The only accepted values are 'on' or 'off'.
3252
0
  bool IsOn = false;
3253
0
  if (II->isStr("on")) {
3254
0
    IsOn = true;
3255
0
  } else if (!II->isStr("off")) {
3256
0
    PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_invalid_argument)
3257
0
      << PP.getSpelling(Tok);
3258
0
    return;
3259
0
  }
3260
0
  PP.Lex(Tok);
3261
3262
0
  if (Tok.isNot(tok::eod)) {
3263
0
    PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_extra_argument)
3264
0
      << PP.getSpelling(Tok);
3265
0
    return;
3266
0
  }
3267
3268
0
  Actions.ActOnPragmaOptimize(IsOn, FirstToken.getLocation());
3269
0
}
3270
3271
namespace {
3272
/// Used as the annotation value for tok::annot_pragma_fp.
3273
struct TokFPAnnotValue {
3274
  enum FlagValues { On, Off, Fast };
3275
3276
  std::optional<LangOptions::FPModeKind> ContractValue;
3277
  std::optional<LangOptions::FPModeKind> ReassociateValue;
3278
  std::optional<LangOptions::FPModeKind> ReciprocalValue;
3279
  std::optional<LangOptions::FPExceptionModeKind> ExceptionsValue;
3280
  std::optional<LangOptions::FPEvalMethodKind> EvalMethodValue;
3281
};
3282
} // end anonymous namespace
3283
3284
void PragmaFPHandler::HandlePragma(Preprocessor &PP,
3285
0
                                   PragmaIntroducer Introducer, Token &Tok) {
3286
  // fp
3287
0
  Token PragmaName = Tok;
3288
0
  SmallVector<Token, 1> TokenList;
3289
3290
0
  PP.Lex(Tok);
3291
0
  if (Tok.isNot(tok::identifier)) {
3292
0
    PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_option)
3293
0
        << /*MissingOption=*/true << "";
3294
0
    return;
3295
0
  }
3296
3297
0
  auto *AnnotValue = new (PP.getPreprocessorAllocator()) TokFPAnnotValue;
3298
0
  while (Tok.is(tok::identifier)) {
3299
0
    IdentifierInfo *OptionInfo = Tok.getIdentifierInfo();
3300
3301
0
    auto FlagKind =
3302
0
        llvm::StringSwitch<std::optional<PragmaFPKind>>(OptionInfo->getName())
3303
0
            .Case("contract", PFK_Contract)
3304
0
            .Case("reassociate", PFK_Reassociate)
3305
0
            .Case("exceptions", PFK_Exceptions)
3306
0
            .Case("eval_method", PFK_EvalMethod)
3307
0
            .Case("reciprocal", PFK_Reciprocal)
3308
0
            .Default(std::nullopt);
3309
0
    if (!FlagKind) {
3310
0
      PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_option)
3311
0
          << /*MissingOption=*/false << OptionInfo;
3312
0
      return;
3313
0
    }
3314
0
    PP.Lex(Tok);
3315
3316
    // Read '('
3317
0
    if (Tok.isNot(tok::l_paren)) {
3318
0
      PP.Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
3319
0
      return;
3320
0
    }
3321
0
    PP.Lex(Tok);
3322
0
    bool isEvalMethodDouble =
3323
0
        Tok.is(tok::kw_double) && FlagKind == PFK_EvalMethod;
3324
3325
    // Don't diagnose if we have an eval_metod pragma with "double" kind.
3326
0
    if (Tok.isNot(tok::identifier) && !isEvalMethodDouble) {
3327
0
      PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_argument)
3328
0
          << PP.getSpelling(Tok) << OptionInfo->getName()
3329
0
          << static_cast<int>(*FlagKind);
3330
0
      return;
3331
0
    }
3332
0
    const IdentifierInfo *II = Tok.getIdentifierInfo();
3333
3334
0
    if (FlagKind == PFK_Contract) {
3335
0
      AnnotValue->ContractValue =
3336
0
          llvm::StringSwitch<std::optional<LangOptions::FPModeKind>>(
3337
0
              II->getName())
3338
0
              .Case("on", LangOptions::FPModeKind::FPM_On)
3339
0
              .Case("off", LangOptions::FPModeKind::FPM_Off)
3340
0
              .Case("fast", LangOptions::FPModeKind::FPM_Fast)
3341
0
              .Default(std::nullopt);
3342
0
      if (!AnnotValue->ContractValue) {
3343
0
        PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_argument)
3344
0
            << PP.getSpelling(Tok) << OptionInfo->getName() << *FlagKind;
3345
0
        return;
3346
0
      }
3347
0
    } else if (FlagKind == PFK_Reassociate || FlagKind == PFK_Reciprocal) {
3348
0
      auto &Value = FlagKind == PFK_Reassociate ? AnnotValue->ReassociateValue
3349
0
                                                : AnnotValue->ReciprocalValue;
3350
0
      Value = llvm::StringSwitch<std::optional<LangOptions::FPModeKind>>(
3351
0
                  II->getName())
3352
0
                  .Case("on", LangOptions::FPModeKind::FPM_On)
3353
0
                  .Case("off", LangOptions::FPModeKind::FPM_Off)
3354
0
                  .Default(std::nullopt);
3355
0
      if (!Value) {
3356
0
        PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_argument)
3357
0
            << PP.getSpelling(Tok) << OptionInfo->getName() << *FlagKind;
3358
0
        return;
3359
0
      }
3360
0
    } else if (FlagKind == PFK_Exceptions) {
3361
0
      AnnotValue->ExceptionsValue =
3362
0
          llvm::StringSwitch<std::optional<LangOptions::FPExceptionModeKind>>(
3363
0
              II->getName())
3364
0
              .Case("ignore", LangOptions::FPE_Ignore)
3365
0
              .Case("maytrap", LangOptions::FPE_MayTrap)
3366
0
              .Case("strict", LangOptions::FPE_Strict)
3367
0
              .Default(std::nullopt);
3368
0
      if (!AnnotValue->ExceptionsValue) {
3369
0
        PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_argument)
3370
0
            << PP.getSpelling(Tok) << OptionInfo->getName() << *FlagKind;
3371
0
        return;
3372
0
      }
3373
0
    } else if (FlagKind == PFK_EvalMethod) {
3374
0
      AnnotValue->EvalMethodValue =
3375
0
          llvm::StringSwitch<std::optional<LangOptions::FPEvalMethodKind>>(
3376
0
              II->getName())
3377
0
              .Case("source", LangOptions::FPEvalMethodKind::FEM_Source)
3378
0
              .Case("double", LangOptions::FPEvalMethodKind::FEM_Double)
3379
0
              .Case("extended", LangOptions::FPEvalMethodKind::FEM_Extended)
3380
0
              .Default(std::nullopt);
3381
0
      if (!AnnotValue->EvalMethodValue) {
3382
0
        PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_argument)
3383
0
            << PP.getSpelling(Tok) << OptionInfo->getName() << *FlagKind;
3384
0
        return;
3385
0
      }
3386
0
    }
3387
0
    PP.Lex(Tok);
3388
3389
    // Read ')'
3390
0
    if (Tok.isNot(tok::r_paren)) {
3391
0
      PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
3392
0
      return;
3393
0
    }
3394
0
    PP.Lex(Tok);
3395
0
  }
3396
3397
0
  if (Tok.isNot(tok::eod)) {
3398
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
3399
0
        << "clang fp";
3400
0
    return;
3401
0
  }
3402
3403
0
  Token FPTok;
3404
0
  FPTok.startToken();
3405
0
  FPTok.setKind(tok::annot_pragma_fp);
3406
0
  FPTok.setLocation(PragmaName.getLocation());
3407
0
  FPTok.setAnnotationEndLoc(PragmaName.getLocation());
3408
0
  FPTok.setAnnotationValue(reinterpret_cast<void *>(AnnotValue));
3409
0
  TokenList.push_back(FPTok);
3410
3411
0
  auto TokenArray = std::make_unique<Token[]>(TokenList.size());
3412
0
  std::copy(TokenList.begin(), TokenList.end(), TokenArray.get());
3413
3414
0
  PP.EnterTokenStream(std::move(TokenArray), TokenList.size(),
3415
0
                      /*DisableMacroExpansion=*/false, /*IsReinject=*/false);
3416
0
}
3417
3418
void PragmaSTDC_FENV_ROUNDHandler::HandlePragma(Preprocessor &PP,
3419
                                                PragmaIntroducer Introducer,
3420
0
                                                Token &Tok) {
3421
0
  Token PragmaName = Tok;
3422
0
  SmallVector<Token, 1> TokenList;
3423
0
  if (!PP.getTargetInfo().hasStrictFP() && !PP.getLangOpts().ExpStrictFP) {
3424
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_fp_ignored)
3425
0
        << PragmaName.getIdentifierInfo()->getName();
3426
0
    return;
3427
0
  }
3428
3429
0
  PP.Lex(Tok);
3430
0
  if (Tok.isNot(tok::identifier)) {
3431
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
3432
0
        << PragmaName.getIdentifierInfo()->getName();
3433
0
    return;
3434
0
  }
3435
0
  IdentifierInfo *II = Tok.getIdentifierInfo();
3436
3437
0
  auto RM =
3438
0
      llvm::StringSwitch<llvm::RoundingMode>(II->getName())
3439
0
          .Case("FE_TOWARDZERO", llvm::RoundingMode::TowardZero)
3440
0
          .Case("FE_TONEAREST", llvm::RoundingMode::NearestTiesToEven)
3441
0
          .Case("FE_UPWARD", llvm::RoundingMode::TowardPositive)
3442
0
          .Case("FE_DOWNWARD", llvm::RoundingMode::TowardNegative)
3443
0
          .Case("FE_TONEARESTFROMZERO", llvm::RoundingMode::NearestTiesToAway)
3444
0
          .Case("FE_DYNAMIC", llvm::RoundingMode::Dynamic)
3445
0
          .Default(llvm::RoundingMode::Invalid);
3446
0
  if (RM == llvm::RoundingMode::Invalid) {
3447
0
    PP.Diag(Tok.getLocation(), diag::warn_stdc_unknown_rounding_mode);
3448
0
    return;
3449
0
  }
3450
0
  PP.Lex(Tok);
3451
3452
0
  if (Tok.isNot(tok::eod)) {
3453
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
3454
0
        << "STDC FENV_ROUND";
3455
0
    return;
3456
0
  }
3457
3458
  // Until the pragma is fully implemented, issue a warning.
3459
0
  PP.Diag(Tok.getLocation(), diag::warn_stdc_fenv_round_not_supported);
3460
3461
0
  MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
3462
0
                              1);
3463
0
  Toks[0].startToken();
3464
0
  Toks[0].setKind(tok::annot_pragma_fenv_round);
3465
0
  Toks[0].setLocation(Tok.getLocation());
3466
0
  Toks[0].setAnnotationEndLoc(Tok.getLocation());
3467
0
  Toks[0].setAnnotationValue(
3468
0
      reinterpret_cast<void *>(static_cast<uintptr_t>(RM)));
3469
0
  PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
3470
0
                      /*IsReinject=*/false);
3471
0
}
3472
3473
0
void Parser::HandlePragmaFP() {
3474
0
  assert(Tok.is(tok::annot_pragma_fp));
3475
0
  auto *AnnotValue =
3476
0
      reinterpret_cast<TokFPAnnotValue *>(Tok.getAnnotationValue());
3477
3478
0
  if (AnnotValue->ReassociateValue)
3479
0
    Actions.ActOnPragmaFPValueChangingOption(
3480
0
        Tok.getLocation(), PFK_Reassociate,
3481
0
        *AnnotValue->ReassociateValue == LangOptions::FPModeKind::FPM_On);
3482
3483
0
  if (AnnotValue->ReciprocalValue)
3484
0
    Actions.ActOnPragmaFPValueChangingOption(
3485
0
        Tok.getLocation(), PFK_Reciprocal,
3486
0
        *AnnotValue->ReciprocalValue == LangOptions::FPModeKind::FPM_On);
3487
3488
0
  if (AnnotValue->ContractValue)
3489
0
    Actions.ActOnPragmaFPContract(Tok.getLocation(),
3490
0
                                  *AnnotValue->ContractValue);
3491
0
  if (AnnotValue->ExceptionsValue)
3492
0
    Actions.ActOnPragmaFPExceptions(Tok.getLocation(),
3493
0
                                    *AnnotValue->ExceptionsValue);
3494
0
  if (AnnotValue->EvalMethodValue)
3495
0
    Actions.ActOnPragmaFPEvalMethod(Tok.getLocation(),
3496
0
                                    *AnnotValue->EvalMethodValue);
3497
0
  ConsumeAnnotationToken();
3498
0
}
3499
3500
/// Parses loop or unroll pragma hint value and fills in Info.
3501
static bool ParseLoopHintValue(Preprocessor &PP, Token &Tok, Token PragmaName,
3502
                               Token Option, bool ValueInParens,
3503
0
                               PragmaLoopHintInfo &Info) {
3504
0
  SmallVector<Token, 1> ValueList;
3505
0
  int OpenParens = ValueInParens ? 1 : 0;
3506
  // Read constant expression.
3507
0
  while (Tok.isNot(tok::eod)) {
3508
0
    if (Tok.is(tok::l_paren))
3509
0
      OpenParens++;
3510
0
    else if (Tok.is(tok::r_paren)) {
3511
0
      OpenParens--;
3512
0
      if (OpenParens == 0 && ValueInParens)
3513
0
        break;
3514
0
    }
3515
3516
0
    ValueList.push_back(Tok);
3517
0
    PP.Lex(Tok);
3518
0
  }
3519
3520
0
  if (ValueInParens) {
3521
    // Read ')'
3522
0
    if (Tok.isNot(tok::r_paren)) {
3523
0
      PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
3524
0
      return true;
3525
0
    }
3526
0
    PP.Lex(Tok);
3527
0
  }
3528
3529
0
  Token EOFTok;
3530
0
  EOFTok.startToken();
3531
0
  EOFTok.setKind(tok::eof);
3532
0
  EOFTok.setLocation(Tok.getLocation());
3533
0
  ValueList.push_back(EOFTok); // Terminates expression for parsing.
3534
3535
0
  markAsReinjectedForRelexing(ValueList);
3536
0
  Info.Toks = llvm::ArrayRef(ValueList).copy(PP.getPreprocessorAllocator());
3537
3538
0
  Info.PragmaName = PragmaName;
3539
0
  Info.Option = Option;
3540
0
  return false;
3541
0
}
3542
3543
/// Handle the \#pragma clang loop directive.
3544
///  #pragma clang 'loop' loop-hints
3545
///
3546
///  loop-hints:
3547
///    loop-hint loop-hints[opt]
3548
///
3549
///  loop-hint:
3550
///    'vectorize' '(' loop-hint-keyword ')'
3551
///    'interleave' '(' loop-hint-keyword ')'
3552
///    'unroll' '(' unroll-hint-keyword ')'
3553
///    'vectorize_predicate' '(' loop-hint-keyword ')'
3554
///    'vectorize_width' '(' loop-hint-value ')'
3555
///    'interleave_count' '(' loop-hint-value ')'
3556
///    'unroll_count' '(' loop-hint-value ')'
3557
///    'pipeline' '(' disable ')'
3558
///    'pipeline_initiation_interval' '(' loop-hint-value ')'
3559
///
3560
///  loop-hint-keyword:
3561
///    'enable'
3562
///    'disable'
3563
///    'assume_safety'
3564
///
3565
///  unroll-hint-keyword:
3566
///    'enable'
3567
///    'disable'
3568
///    'full'
3569
///
3570
///  loop-hint-value:
3571
///    constant-expression
3572
///
3573
/// Specifying vectorize(enable) or vectorize_width(_value_) instructs llvm to
3574
/// try vectorizing the instructions of the loop it precedes. Specifying
3575
/// interleave(enable) or interleave_count(_value_) instructs llvm to try
3576
/// interleaving multiple iterations of the loop it precedes. The width of the
3577
/// vector instructions is specified by vectorize_width() and the number of
3578
/// interleaved loop iterations is specified by interleave_count(). Specifying a
3579
/// value of 1 effectively disables vectorization/interleaving, even if it is
3580
/// possible and profitable, and 0 is invalid. The loop vectorizer currently
3581
/// only works on inner loops.
3582
///
3583
/// The unroll and unroll_count directives control the concatenation
3584
/// unroller. Specifying unroll(enable) instructs llvm to unroll the loop
3585
/// completely if the trip count is known at compile time and unroll partially
3586
/// if the trip count is not known.  Specifying unroll(full) is similar to
3587
/// unroll(enable) but will unroll the loop only if the trip count is known at
3588
/// compile time.  Specifying unroll(disable) disables unrolling for the
3589
/// loop. Specifying unroll_count(_value_) instructs llvm to try to unroll the
3590
/// loop the number of times indicated by the value.
3591
void PragmaLoopHintHandler::HandlePragma(Preprocessor &PP,
3592
                                         PragmaIntroducer Introducer,
3593
0
                                         Token &Tok) {
3594
  // Incoming token is "loop" from "#pragma clang loop".
3595
0
  Token PragmaName = Tok;
3596
0
  SmallVector<Token, 1> TokenList;
3597
3598
  // Lex the optimization option and verify it is an identifier.
3599
0
  PP.Lex(Tok);
3600
0
  if (Tok.isNot(tok::identifier)) {
3601
0
    PP.Diag(Tok.getLocation(), diag::err_pragma_loop_invalid_option)
3602
0
        << /*MissingOption=*/true << "";
3603
0
    return;
3604
0
  }
3605
3606
0
  while (Tok.is(tok::identifier)) {
3607
0
    Token Option = Tok;
3608
0
    IdentifierInfo *OptionInfo = Tok.getIdentifierInfo();
3609
3610
0
    bool OptionValid = llvm::StringSwitch<bool>(OptionInfo->getName())
3611
0
                           .Case("vectorize", true)
3612
0
                           .Case("interleave", true)
3613
0
                           .Case("unroll", true)
3614
0
                           .Case("distribute", true)
3615
0
                           .Case("vectorize_predicate", true)
3616
0
                           .Case("vectorize_width", true)
3617
0
                           .Case("interleave_count", true)
3618
0
                           .Case("unroll_count", true)
3619
0
                           .Case("pipeline", true)
3620
0
                           .Case("pipeline_initiation_interval", true)
3621
0
                           .Default(false);
3622
0
    if (!OptionValid) {
3623
0
      PP.Diag(Tok.getLocation(), diag::err_pragma_loop_invalid_option)
3624
0
          << /*MissingOption=*/false << OptionInfo;
3625
0
      return;
3626
0
    }
3627
0
    PP.Lex(Tok);
3628
3629
    // Read '('
3630
0
    if (Tok.isNot(tok::l_paren)) {
3631
0
      PP.Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
3632
0
      return;
3633
0
    }
3634
0
    PP.Lex(Tok);
3635
3636
0
    auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
3637
0
    if (ParseLoopHintValue(PP, Tok, PragmaName, Option, /*ValueInParens=*/true,
3638
0
                           *Info))
3639
0
      return;
3640
3641
    // Generate the loop hint token.
3642
0
    Token LoopHintTok;
3643
0
    LoopHintTok.startToken();
3644
0
    LoopHintTok.setKind(tok::annot_pragma_loop_hint);
3645
0
    LoopHintTok.setLocation(Introducer.Loc);
3646
0
    LoopHintTok.setAnnotationEndLoc(PragmaName.getLocation());
3647
0
    LoopHintTok.setAnnotationValue(static_cast<void *>(Info));
3648
0
    TokenList.push_back(LoopHintTok);
3649
0
  }
3650
3651
0
  if (Tok.isNot(tok::eod)) {
3652
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
3653
0
        << "clang loop";
3654
0
    return;
3655
0
  }
3656
3657
0
  auto TokenArray = std::make_unique<Token[]>(TokenList.size());
3658
0
  std::copy(TokenList.begin(), TokenList.end(), TokenArray.get());
3659
3660
0
  PP.EnterTokenStream(std::move(TokenArray), TokenList.size(),
3661
0
                      /*DisableMacroExpansion=*/false, /*IsReinject=*/false);
3662
0
}
3663
3664
/// Handle the loop unroll optimization pragmas.
3665
///  #pragma unroll
3666
///  #pragma unroll unroll-hint-value
3667
///  #pragma unroll '(' unroll-hint-value ')'
3668
///  #pragma nounroll
3669
///  #pragma unroll_and_jam
3670
///  #pragma unroll_and_jam unroll-hint-value
3671
///  #pragma unroll_and_jam '(' unroll-hint-value ')'
3672
///  #pragma nounroll_and_jam
3673
///
3674
///  unroll-hint-value:
3675
///    constant-expression
3676
///
3677
/// Loop unrolling hints can be specified with '#pragma unroll' or
3678
/// '#pragma nounroll'. '#pragma unroll' can take a numeric argument optionally
3679
/// contained in parentheses. With no argument the directive instructs llvm to
3680
/// try to unroll the loop completely. A positive integer argument can be
3681
/// specified to indicate the number of times the loop should be unrolled.  To
3682
/// maximize compatibility with other compilers the unroll count argument can be
3683
/// specified with or without parentheses.  Specifying, '#pragma nounroll'
3684
/// disables unrolling of the loop.
3685
void PragmaUnrollHintHandler::HandlePragma(Preprocessor &PP,
3686
                                           PragmaIntroducer Introducer,
3687
0
                                           Token &Tok) {
3688
  // Incoming token is "unroll" for "#pragma unroll", or "nounroll" for
3689
  // "#pragma nounroll".
3690
0
  Token PragmaName = Tok;
3691
0
  PP.Lex(Tok);
3692
0
  auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
3693
0
  if (Tok.is(tok::eod)) {
3694
    // nounroll or unroll pragma without an argument.
3695
0
    Info->PragmaName = PragmaName;
3696
0
    Info->Option.startToken();
3697
0
  } else if (PragmaName.getIdentifierInfo()->getName() == "nounroll" ||
3698
0
             PragmaName.getIdentifierInfo()->getName() == "nounroll_and_jam") {
3699
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
3700
0
        << PragmaName.getIdentifierInfo()->getName();
3701
0
    return;
3702
0
  } else {
3703
    // Unroll pragma with an argument: "#pragma unroll N" or
3704
    // "#pragma unroll(N)".
3705
    // Read '(' if it exists.
3706
0
    bool ValueInParens = Tok.is(tok::l_paren);
3707
0
    if (ValueInParens)
3708
0
      PP.Lex(Tok);
3709
3710
0
    Token Option;
3711
0
    Option.startToken();
3712
0
    if (ParseLoopHintValue(PP, Tok, PragmaName, Option, ValueInParens, *Info))
3713
0
      return;
3714
3715
    // In CUDA, the argument to '#pragma unroll' should not be contained in
3716
    // parentheses.
3717
0
    if (PP.getLangOpts().CUDA && ValueInParens)
3718
0
      PP.Diag(Info->Toks[0].getLocation(),
3719
0
              diag::warn_pragma_unroll_cuda_value_in_parens);
3720
3721
0
    if (Tok.isNot(tok::eod)) {
3722
0
      PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
3723
0
          << "unroll";
3724
0
      return;
3725
0
    }
3726
0
  }
3727
3728
  // Generate the hint token.
3729
0
  auto TokenArray = std::make_unique<Token[]>(1);
3730
0
  TokenArray[0].startToken();
3731
0
  TokenArray[0].setKind(tok::annot_pragma_loop_hint);
3732
0
  TokenArray[0].setLocation(Introducer.Loc);
3733
0
  TokenArray[0].setAnnotationEndLoc(PragmaName.getLocation());
3734
0
  TokenArray[0].setAnnotationValue(static_cast<void *>(Info));
3735
0
  PP.EnterTokenStream(std::move(TokenArray), 1,
3736
0
                      /*DisableMacroExpansion=*/false, /*IsReinject=*/false);
3737
0
}
3738
3739
/// Handle the Microsoft \#pragma intrinsic extension.
3740
///
3741
/// The syntax is:
3742
/// \code
3743
///  #pragma intrinsic(memset)
3744
///  #pragma intrinsic(strlen, memcpy)
3745
/// \endcode
3746
///
3747
/// Pragma intrisic tells the compiler to use a builtin version of the
3748
/// function. Clang does it anyway, so the pragma doesn't really do anything.
3749
/// Anyway, we emit a warning if the function specified in \#pragma intrinsic
3750
/// isn't an intrinsic in clang and suggest to include intrin.h.
3751
void PragmaMSIntrinsicHandler::HandlePragma(Preprocessor &PP,
3752
                                            PragmaIntroducer Introducer,
3753
0
                                            Token &Tok) {
3754
0
  PP.Lex(Tok);
3755
3756
0
  if (Tok.isNot(tok::l_paren)) {
3757
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen)
3758
0
        << "intrinsic";
3759
0
    return;
3760
0
  }
3761
0
  PP.Lex(Tok);
3762
3763
0
  bool SuggestIntrinH = !PP.isMacroDefined("__INTRIN_H");
3764
3765
0
  while (Tok.is(tok::identifier)) {
3766
0
    IdentifierInfo *II = Tok.getIdentifierInfo();
3767
0
    if (!II->getBuiltinID())
3768
0
      PP.Diag(Tok.getLocation(), diag::warn_pragma_intrinsic_builtin)
3769
0
          << II << SuggestIntrinH;
3770
3771
0
    PP.Lex(Tok);
3772
0
    if (Tok.isNot(tok::comma))
3773
0
      break;
3774
0
    PP.Lex(Tok);
3775
0
  }
3776
3777
0
  if (Tok.isNot(tok::r_paren)) {
3778
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen)
3779
0
        << "intrinsic";
3780
0
    return;
3781
0
  }
3782
0
  PP.Lex(Tok);
3783
3784
0
  if (Tok.isNot(tok::eod))
3785
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
3786
0
        << "intrinsic";
3787
0
}
3788
3789
bool Parser::HandlePragmaMSFunction(StringRef PragmaName,
3790
0
                                    SourceLocation PragmaLocation) {
3791
0
  Token FirstTok = Tok;
3792
3793
0
  if (ExpectAndConsume(tok::l_paren, diag::warn_pragma_expected_lparen,
3794
0
                       PragmaName))
3795
0
    return false;
3796
3797
0
  bool SuggestIntrinH = !PP.isMacroDefined("__INTRIN_H");
3798
3799
0
  llvm::SmallVector<StringRef> NoBuiltins;
3800
0
  while (Tok.is(tok::identifier)) {
3801
0
    IdentifierInfo *II = Tok.getIdentifierInfo();
3802
0
    if (!II->getBuiltinID())
3803
0
      PP.Diag(Tok.getLocation(), diag::warn_pragma_intrinsic_builtin)
3804
0
          << II << SuggestIntrinH;
3805
0
    else
3806
0
      NoBuiltins.emplace_back(II->getName());
3807
3808
0
    PP.Lex(Tok);
3809
0
    if (Tok.isNot(tok::comma))
3810
0
      break;
3811
0
    PP.Lex(Tok); // ,
3812
0
  }
3813
3814
0
  if (ExpectAndConsume(tok::r_paren, diag::warn_pragma_expected_rparen,
3815
0
                       PragmaName) ||
3816
0
      ExpectAndConsume(tok::eof, diag::warn_pragma_extra_tokens_at_eol,
3817
0
                       PragmaName))
3818
0
    return false;
3819
3820
0
  Actions.ActOnPragmaMSFunction(FirstTok.getLocation(), NoBuiltins);
3821
0
  return true;
3822
0
}
3823
3824
// #pragma optimize("gsty", on|off)
3825
bool Parser::HandlePragmaMSOptimize(StringRef PragmaName,
3826
0
                                    SourceLocation PragmaLocation) {
3827
0
  Token FirstTok = Tok;
3828
0
  if (ExpectAndConsume(tok::l_paren, diag::warn_pragma_expected_lparen,
3829
0
                       PragmaName))
3830
0
    return false;
3831
3832
0
  if (Tok.isNot(tok::string_literal)) {
3833
0
    PP.Diag(PragmaLocation, diag::warn_pragma_expected_string) << PragmaName;
3834
0
    return false;
3835
0
  }
3836
0
  ExprResult StringResult = ParseStringLiteralExpression();
3837
0
  if (StringResult.isInvalid())
3838
0
    return false; // Already diagnosed.
3839
0
  StringLiteral *OptimizationList = cast<StringLiteral>(StringResult.get());
3840
0
  if (OptimizationList->getCharByteWidth() != 1) {
3841
0
    PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
3842
0
        << PragmaName;
3843
0
    return false;
3844
0
  }
3845
3846
0
  if (ExpectAndConsume(tok::comma, diag::warn_pragma_expected_comma,
3847
0
                       PragmaName))
3848
0
    return false;
3849
3850
0
  if (Tok.is(tok::eof) || Tok.is(tok::r_paren)) {
3851
0
    PP.Diag(PragmaLocation, diag::warn_pragma_missing_argument)
3852
0
        << PragmaName << /*Expected=*/true << "'on' or 'off'";
3853
0
    return false;
3854
0
  }
3855
0
  IdentifierInfo *II = Tok.getIdentifierInfo();
3856
0
  if (!II || (!II->isStr("on") && !II->isStr("off"))) {
3857
0
    PP.Diag(PragmaLocation, diag::warn_pragma_invalid_argument)
3858
0
        << PP.getSpelling(Tok) << PragmaName << /*Expected=*/true
3859
0
        << "'on' or 'off'";
3860
0
    return false;
3861
0
  }
3862
0
  bool IsOn = II->isStr("on");
3863
0
  PP.Lex(Tok);
3864
3865
0
  if (ExpectAndConsume(tok::r_paren, diag::warn_pragma_expected_rparen,
3866
0
                       PragmaName))
3867
0
    return false;
3868
3869
  // TODO: Add support for "sgty"
3870
0
  if (!OptimizationList->getString().empty()) {
3871
0
    PP.Diag(PragmaLocation, diag::warn_pragma_invalid_argument)
3872
0
        << OptimizationList->getString() << PragmaName << /*Expected=*/true
3873
0
        << "\"\"";
3874
0
    return false;
3875
0
  }
3876
3877
0
  if (ExpectAndConsume(tok::eof, diag::warn_pragma_extra_tokens_at_eol,
3878
0
                       PragmaName))
3879
0
    return false;
3880
3881
0
  Actions.ActOnPragmaMSOptimize(FirstTok.getLocation(), IsOn);
3882
0
  return true;
3883
0
}
3884
3885
void PragmaForceCUDAHostDeviceHandler::HandlePragma(
3886
0
    Preprocessor &PP, PragmaIntroducer Introducer, Token &Tok) {
3887
0
  Token FirstTok = Tok;
3888
3889
0
  PP.Lex(Tok);
3890
0
  IdentifierInfo *Info = Tok.getIdentifierInfo();
3891
0
  if (!Info || (!Info->isStr("begin") && !Info->isStr("end"))) {
3892
0
    PP.Diag(FirstTok.getLocation(),
3893
0
            diag::warn_pragma_force_cuda_host_device_bad_arg);
3894
0
    return;
3895
0
  }
3896
3897
0
  if (Info->isStr("begin"))
3898
0
    Actions.PushForceCUDAHostDevice();
3899
0
  else if (!Actions.PopForceCUDAHostDevice())
3900
0
    PP.Diag(FirstTok.getLocation(),
3901
0
            diag::err_pragma_cannot_end_force_cuda_host_device);
3902
3903
0
  PP.Lex(Tok);
3904
0
  if (!Tok.is(tok::eod))
3905
0
    PP.Diag(FirstTok.getLocation(),
3906
0
            diag::warn_pragma_force_cuda_host_device_bad_arg);
3907
0
}
3908
3909
/// Handle the #pragma clang attribute directive.
3910
///
3911
/// The syntax is:
3912
/// \code
3913
///  #pragma clang attribute push (attribute, subject-set)
3914
///  #pragma clang attribute push
3915
///  #pragma clang attribute (attribute, subject-set)
3916
///  #pragma clang attribute pop
3917
/// \endcode
3918
///
3919
/// There are also 'namespace' variants of push and pop directives. The bare
3920
/// '#pragma clang attribute (attribute, subject-set)' version doesn't require a
3921
/// namespace, since it always applies attributes to the most recently pushed
3922
/// group, regardless of namespace.
3923
/// \code
3924
///  #pragma clang attribute namespace.push (attribute, subject-set)
3925
///  #pragma clang attribute namespace.push
3926
///  #pragma clang attribute namespace.pop
3927
/// \endcode
3928
///
3929
/// The subject-set clause defines the set of declarations which receive the
3930
/// attribute. Its exact syntax is described in the LanguageExtensions document
3931
/// in Clang's documentation.
3932
///
3933
/// This directive instructs the compiler to begin/finish applying the specified
3934
/// attribute to the set of attribute-specific declarations in the active range
3935
/// of the pragma.
3936
void PragmaAttributeHandler::HandlePragma(Preprocessor &PP,
3937
                                          PragmaIntroducer Introducer,
3938
0
                                          Token &FirstToken) {
3939
0
  Token Tok;
3940
0
  PP.Lex(Tok);
3941
0
  auto *Info = new (PP.getPreprocessorAllocator())
3942
0
      PragmaAttributeInfo(AttributesForPragmaAttribute);
3943
3944
  // Parse the optional namespace followed by a period.
3945
0
  if (Tok.is(tok::identifier)) {
3946
0
    IdentifierInfo *II = Tok.getIdentifierInfo();
3947
0
    if (!II->isStr("push") && !II->isStr("pop")) {
3948
0
      Info->Namespace = II;
3949
0
      PP.Lex(Tok);
3950
3951
0
      if (!Tok.is(tok::period)) {
3952
0
        PP.Diag(Tok.getLocation(), diag::err_pragma_attribute_expected_period)
3953
0
            << II;
3954
0
        return;
3955
0
      }
3956
0
      PP.Lex(Tok);
3957
0
    }
3958
0
  }
3959
3960
0
  if (!Tok.isOneOf(tok::identifier, tok::l_paren)) {
3961
0
    PP.Diag(Tok.getLocation(),
3962
0
            diag::err_pragma_attribute_expected_push_pop_paren);
3963
0
    return;
3964
0
  }
3965
3966
  // Determine what action this pragma clang attribute represents.
3967
0
  if (Tok.is(tok::l_paren)) {
3968
0
    if (Info->Namespace) {
3969
0
      PP.Diag(Tok.getLocation(),
3970
0
              diag::err_pragma_attribute_namespace_on_attribute);
3971
0
      PP.Diag(Tok.getLocation(),
3972
0
              diag::note_pragma_attribute_namespace_on_attribute);
3973
0
      return;
3974
0
    }
3975
0
    Info->Action = PragmaAttributeInfo::Attribute;
3976
0
  } else {
3977
0
    const IdentifierInfo *II = Tok.getIdentifierInfo();
3978
0
    if (II->isStr("push"))
3979
0
      Info->Action = PragmaAttributeInfo::Push;
3980
0
    else if (II->isStr("pop"))
3981
0
      Info->Action = PragmaAttributeInfo::Pop;
3982
0
    else {
3983
0
      PP.Diag(Tok.getLocation(), diag::err_pragma_attribute_invalid_argument)
3984
0
          << PP.getSpelling(Tok);
3985
0
      return;
3986
0
    }
3987
3988
0
    PP.Lex(Tok);
3989
0
  }
3990
3991
  // Parse the actual attribute.
3992
0
  if ((Info->Action == PragmaAttributeInfo::Push && Tok.isNot(tok::eod)) ||
3993
0
      Info->Action == PragmaAttributeInfo::Attribute) {
3994
0
    if (Tok.isNot(tok::l_paren)) {
3995
0
      PP.Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
3996
0
      return;
3997
0
    }
3998
0
    PP.Lex(Tok);
3999
4000
    // Lex the attribute tokens.
4001
0
    SmallVector<Token, 16> AttributeTokens;
4002
0
    int OpenParens = 1;
4003
0
    while (Tok.isNot(tok::eod)) {
4004
0
      if (Tok.is(tok::l_paren))
4005
0
        OpenParens++;
4006
0
      else if (Tok.is(tok::r_paren)) {
4007
0
        OpenParens--;
4008
0
        if (OpenParens == 0)
4009
0
          break;
4010
0
      }
4011
4012
0
      AttributeTokens.push_back(Tok);
4013
0
      PP.Lex(Tok);
4014
0
    }
4015
4016
0
    if (AttributeTokens.empty()) {
4017
0
      PP.Diag(Tok.getLocation(), diag::err_pragma_attribute_expected_attribute);
4018
0
      return;
4019
0
    }
4020
0
    if (Tok.isNot(tok::r_paren)) {
4021
0
      PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
4022
0
      return;
4023
0
    }
4024
0
    SourceLocation EndLoc = Tok.getLocation();
4025
0
    PP.Lex(Tok);
4026
4027
    // Terminate the attribute for parsing.
4028
0
    Token EOFTok;
4029
0
    EOFTok.startToken();
4030
0
    EOFTok.setKind(tok::eof);
4031
0
    EOFTok.setLocation(EndLoc);
4032
0
    AttributeTokens.push_back(EOFTok);
4033
4034
0
    markAsReinjectedForRelexing(AttributeTokens);
4035
0
    Info->Tokens =
4036
0
        llvm::ArrayRef(AttributeTokens).copy(PP.getPreprocessorAllocator());
4037
0
  }
4038
4039
0
  if (Tok.isNot(tok::eod))
4040
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
4041
0
        << "clang attribute";
4042
4043
  // Generate the annotated pragma token.
4044
0
  auto TokenArray = std::make_unique<Token[]>(1);
4045
0
  TokenArray[0].startToken();
4046
0
  TokenArray[0].setKind(tok::annot_pragma_attribute);
4047
0
  TokenArray[0].setLocation(FirstToken.getLocation());
4048
0
  TokenArray[0].setAnnotationEndLoc(FirstToken.getLocation());
4049
0
  TokenArray[0].setAnnotationValue(static_cast<void *>(Info));
4050
0
  PP.EnterTokenStream(std::move(TokenArray), 1,
4051
0
                      /*DisableMacroExpansion=*/false, /*IsReinject=*/false);
4052
0
}
4053
4054
// Handle '#pragma clang max_tokens 12345'.
4055
void PragmaMaxTokensHereHandler::HandlePragma(Preprocessor &PP,
4056
                                              PragmaIntroducer Introducer,
4057
0
                                              Token &Tok) {
4058
0
  PP.Lex(Tok);
4059
0
  if (Tok.is(tok::eod)) {
4060
0
    PP.Diag(Tok.getLocation(), diag::err_pragma_missing_argument)
4061
0
        << "clang max_tokens_here" << /*Expected=*/true << "integer";
4062
0
    return;
4063
0
  }
4064
4065
0
  SourceLocation Loc = Tok.getLocation();
4066
0
  uint64_t MaxTokens;
4067
0
  if (Tok.isNot(tok::numeric_constant) ||
4068
0
      !PP.parseSimpleIntegerLiteral(Tok, MaxTokens)) {
4069
0
    PP.Diag(Tok.getLocation(), diag::err_pragma_expected_integer)
4070
0
        << "clang max_tokens_here";
4071
0
    return;
4072
0
  }
4073
4074
0
  if (Tok.isNot(tok::eod)) {
4075
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
4076
0
        << "clang max_tokens_here";
4077
0
    return;
4078
0
  }
4079
4080
0
  if (PP.getTokenCount() > MaxTokens) {
4081
0
    PP.Diag(Loc, diag::warn_max_tokens)
4082
0
        << PP.getTokenCount() << (unsigned)MaxTokens;
4083
0
  }
4084
0
}
4085
4086
// Handle '#pragma clang max_tokens_total 12345'.
4087
void PragmaMaxTokensTotalHandler::HandlePragma(Preprocessor &PP,
4088
                                               PragmaIntroducer Introducer,
4089
0
                                               Token &Tok) {
4090
0
  PP.Lex(Tok);
4091
0
  if (Tok.is(tok::eod)) {
4092
0
    PP.Diag(Tok.getLocation(), diag::err_pragma_missing_argument)
4093
0
        << "clang max_tokens_total" << /*Expected=*/true << "integer";
4094
0
    return;
4095
0
  }
4096
4097
0
  SourceLocation Loc = Tok.getLocation();
4098
0
  uint64_t MaxTokens;
4099
0
  if (Tok.isNot(tok::numeric_constant) ||
4100
0
      !PP.parseSimpleIntegerLiteral(Tok, MaxTokens)) {
4101
0
    PP.Diag(Tok.getLocation(), diag::err_pragma_expected_integer)
4102
0
        << "clang max_tokens_total";
4103
0
    return;
4104
0
  }
4105
4106
0
  if (Tok.isNot(tok::eod)) {
4107
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
4108
0
        << "clang max_tokens_total";
4109
0
    return;
4110
0
  }
4111
4112
0
  PP.overrideMaxTokens(MaxTokens, Loc);
4113
0
}
4114
4115
// Handle '#pragma clang riscv intrinsic vector'.
4116
//        '#pragma clang riscv intrinsic sifive_vector'.
4117
void PragmaRISCVHandler::HandlePragma(Preprocessor &PP,
4118
                                      PragmaIntroducer Introducer,
4119
0
                                      Token &FirstToken) {
4120
0
  Token Tok;
4121
0
  PP.Lex(Tok);
4122
0
  IdentifierInfo *II = Tok.getIdentifierInfo();
4123
4124
0
  if (!II || !II->isStr("intrinsic")) {
4125
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_argument)
4126
0
        << PP.getSpelling(Tok) << "riscv" << /*Expected=*/true << "'intrinsic'";
4127
0
    return;
4128
0
  }
4129
4130
0
  PP.Lex(Tok);
4131
0
  II = Tok.getIdentifierInfo();
4132
0
  if (!II || !(II->isStr("vector") || II->isStr("sifive_vector"))) {
4133
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_argument)
4134
0
        << PP.getSpelling(Tok) << "riscv" << /*Expected=*/true
4135
0
        << "'vector' or 'sifive_vector'";
4136
0
    return;
4137
0
  }
4138
4139
0
  PP.Lex(Tok);
4140
0
  if (Tok.isNot(tok::eod)) {
4141
0
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
4142
0
        << "clang riscv intrinsic";
4143
0
    return;
4144
0
  }
4145
4146
0
  if (II->isStr("vector"))
4147
0
    Actions.DeclareRISCVVBuiltins = true;
4148
0
  else if (II->isStr("sifive_vector"))
4149
0
    Actions.DeclareRISCVSiFiveVectorBuiltins = true;
4150
0
}