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