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