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