1 //===--- ParsePragma.cpp - Language specific pragma parsing ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the language specific #pragma handlers.
12 //===----------------------------------------------------------------------===//
14 #include "RAIIObjectsForParser.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/Lex/Preprocessor.h"
18 #include "clang/Parse/ParseDiagnostic.h"
19 #include "clang/Parse/Parser.h"
20 #include "clang/Sema/LoopHint.h"
21 #include "clang/Sema/Scope.h"
22 #include "llvm/ADT/StringSwitch.h"
23 using namespace clang;
27 struct PragmaAlignHandler : public PragmaHandler {
28 explicit PragmaAlignHandler() : PragmaHandler("align") {}
29 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
30 Token &FirstToken) override;
33 struct PragmaGCCVisibilityHandler : public PragmaHandler {
34 explicit PragmaGCCVisibilityHandler() : PragmaHandler("visibility") {}
35 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
36 Token &FirstToken) override;
39 struct PragmaOptionsHandler : public PragmaHandler {
40 explicit PragmaOptionsHandler() : PragmaHandler("options") {}
41 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
42 Token &FirstToken) override;
45 struct PragmaPackHandler : public PragmaHandler {
46 explicit PragmaPackHandler() : PragmaHandler("pack") {}
47 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
48 Token &FirstToken) override;
51 struct PragmaMSStructHandler : public PragmaHandler {
52 explicit PragmaMSStructHandler() : PragmaHandler("ms_struct") {}
53 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
54 Token &FirstToken) override;
57 struct PragmaUnusedHandler : public PragmaHandler {
58 PragmaUnusedHandler() : PragmaHandler("unused") {}
59 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
60 Token &FirstToken) override;
63 struct PragmaWeakHandler : public PragmaHandler {
64 explicit PragmaWeakHandler() : PragmaHandler("weak") {}
65 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
66 Token &FirstToken) override;
69 struct PragmaRedefineExtnameHandler : public PragmaHandler {
70 explicit PragmaRedefineExtnameHandler() : PragmaHandler("redefine_extname") {}
71 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
72 Token &FirstToken) override;
75 struct PragmaOpenCLExtensionHandler : public PragmaHandler {
76 PragmaOpenCLExtensionHandler() : PragmaHandler("EXTENSION") {}
77 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
78 Token &FirstToken) override;
82 struct PragmaFPContractHandler : public PragmaHandler {
83 PragmaFPContractHandler() : PragmaHandler("FP_CONTRACT") {}
84 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
85 Token &FirstToken) override;
88 struct PragmaNoOpenMPHandler : public PragmaHandler {
89 PragmaNoOpenMPHandler() : PragmaHandler("omp") { }
90 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
91 Token &FirstToken) override;
94 struct PragmaOpenMPHandler : public PragmaHandler {
95 PragmaOpenMPHandler() : PragmaHandler("omp") { }
96 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
97 Token &FirstToken) override;
100 /// PragmaCommentHandler - "\#pragma comment ...".
101 struct PragmaCommentHandler : public PragmaHandler {
102 PragmaCommentHandler(Sema &Actions)
103 : PragmaHandler("comment"), Actions(Actions) {}
104 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
105 Token &FirstToken) override;
110 struct PragmaDetectMismatchHandler : public PragmaHandler {
111 PragmaDetectMismatchHandler(Sema &Actions)
112 : PragmaHandler("detect_mismatch"), Actions(Actions) {}
113 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
114 Token &FirstToken) override;
119 struct PragmaMSPointersToMembers : public PragmaHandler {
120 explicit PragmaMSPointersToMembers() : PragmaHandler("pointers_to_members") {}
121 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
122 Token &FirstToken) override;
125 struct PragmaMSVtorDisp : public PragmaHandler {
126 explicit PragmaMSVtorDisp() : PragmaHandler("vtordisp") {}
127 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
128 Token &FirstToken) override;
131 struct PragmaMSPragma : public PragmaHandler {
132 explicit PragmaMSPragma(const char *name) : PragmaHandler(name) {}
133 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
134 Token &FirstToken) override;
137 /// PragmaOptimizeHandler - "\#pragma clang optimize on/off".
138 struct PragmaOptimizeHandler : public PragmaHandler {
139 PragmaOptimizeHandler(Sema &S)
140 : PragmaHandler("optimize"), Actions(S) {}
141 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
142 Token &FirstToken) override;
147 struct PragmaLoopHintHandler : public PragmaHandler {
148 PragmaLoopHintHandler() : PragmaHandler("loop") {}
149 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
150 Token &FirstToken) override;
153 struct PragmaUnrollHintHandler : public PragmaHandler {
154 PragmaUnrollHintHandler(const char *name) : PragmaHandler(name) {}
155 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
156 Token &FirstToken) override;
161 void Parser::initializePragmaHandlers() {
162 AlignHandler.reset(new PragmaAlignHandler());
163 PP.AddPragmaHandler(AlignHandler.get());
165 GCCVisibilityHandler.reset(new PragmaGCCVisibilityHandler());
166 PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
168 OptionsHandler.reset(new PragmaOptionsHandler());
169 PP.AddPragmaHandler(OptionsHandler.get());
171 PackHandler.reset(new PragmaPackHandler());
172 PP.AddPragmaHandler(PackHandler.get());
174 MSStructHandler.reset(new PragmaMSStructHandler());
175 PP.AddPragmaHandler(MSStructHandler.get());
177 UnusedHandler.reset(new PragmaUnusedHandler());
178 PP.AddPragmaHandler(UnusedHandler.get());
180 WeakHandler.reset(new PragmaWeakHandler());
181 PP.AddPragmaHandler(WeakHandler.get());
183 RedefineExtnameHandler.reset(new PragmaRedefineExtnameHandler());
184 PP.AddPragmaHandler(RedefineExtnameHandler.get());
186 FPContractHandler.reset(new PragmaFPContractHandler());
187 PP.AddPragmaHandler("STDC", FPContractHandler.get());
189 if (getLangOpts().OpenCL) {
190 OpenCLExtensionHandler.reset(new PragmaOpenCLExtensionHandler());
191 PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
193 PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
195 if (getLangOpts().OpenMP)
196 OpenMPHandler.reset(new PragmaOpenMPHandler());
198 OpenMPHandler.reset(new PragmaNoOpenMPHandler());
199 PP.AddPragmaHandler(OpenMPHandler.get());
201 if (getLangOpts().MicrosoftExt || getTargetInfo().getTriple().isPS4()) {
202 MSCommentHandler.reset(new PragmaCommentHandler(Actions));
203 PP.AddPragmaHandler(MSCommentHandler.get());
206 if (getLangOpts().MicrosoftExt) {
207 MSDetectMismatchHandler.reset(new PragmaDetectMismatchHandler(Actions));
208 PP.AddPragmaHandler(MSDetectMismatchHandler.get());
209 MSPointersToMembers.reset(new PragmaMSPointersToMembers());
210 PP.AddPragmaHandler(MSPointersToMembers.get());
211 MSVtorDisp.reset(new PragmaMSVtorDisp());
212 PP.AddPragmaHandler(MSVtorDisp.get());
213 MSInitSeg.reset(new PragmaMSPragma("init_seg"));
214 PP.AddPragmaHandler(MSInitSeg.get());
215 MSDataSeg.reset(new PragmaMSPragma("data_seg"));
216 PP.AddPragmaHandler(MSDataSeg.get());
217 MSBSSSeg.reset(new PragmaMSPragma("bss_seg"));
218 PP.AddPragmaHandler(MSBSSSeg.get());
219 MSConstSeg.reset(new PragmaMSPragma("const_seg"));
220 PP.AddPragmaHandler(MSConstSeg.get());
221 MSCodeSeg.reset(new PragmaMSPragma("code_seg"));
222 PP.AddPragmaHandler(MSCodeSeg.get());
223 MSSection.reset(new PragmaMSPragma("section"));
224 PP.AddPragmaHandler(MSSection.get());
227 OptimizeHandler.reset(new PragmaOptimizeHandler(Actions));
228 PP.AddPragmaHandler("clang", OptimizeHandler.get());
230 LoopHintHandler.reset(new PragmaLoopHintHandler());
231 PP.AddPragmaHandler("clang", LoopHintHandler.get());
233 UnrollHintHandler.reset(new PragmaUnrollHintHandler("unroll"));
234 PP.AddPragmaHandler(UnrollHintHandler.get());
236 NoUnrollHintHandler.reset(new PragmaUnrollHintHandler("nounroll"));
237 PP.AddPragmaHandler(NoUnrollHintHandler.get());
240 void Parser::resetPragmaHandlers() {
241 // Remove the pragma handlers we installed.
242 PP.RemovePragmaHandler(AlignHandler.get());
243 AlignHandler.reset();
244 PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
245 GCCVisibilityHandler.reset();
246 PP.RemovePragmaHandler(OptionsHandler.get());
247 OptionsHandler.reset();
248 PP.RemovePragmaHandler(PackHandler.get());
250 PP.RemovePragmaHandler(MSStructHandler.get());
251 MSStructHandler.reset();
252 PP.RemovePragmaHandler(UnusedHandler.get());
253 UnusedHandler.reset();
254 PP.RemovePragmaHandler(WeakHandler.get());
256 PP.RemovePragmaHandler(RedefineExtnameHandler.get());
257 RedefineExtnameHandler.reset();
259 if (getLangOpts().OpenCL) {
260 PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
261 OpenCLExtensionHandler.reset();
262 PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
264 PP.RemovePragmaHandler(OpenMPHandler.get());
265 OpenMPHandler.reset();
267 if (getLangOpts().MicrosoftExt || getTargetInfo().getTriple().isPS4()) {
268 PP.RemovePragmaHandler(MSCommentHandler.get());
269 MSCommentHandler.reset();
272 if (getLangOpts().MicrosoftExt) {
273 PP.RemovePragmaHandler(MSDetectMismatchHandler.get());
274 MSDetectMismatchHandler.reset();
275 PP.RemovePragmaHandler(MSPointersToMembers.get());
276 MSPointersToMembers.reset();
277 PP.RemovePragmaHandler(MSVtorDisp.get());
279 PP.RemovePragmaHandler(MSInitSeg.get());
281 PP.RemovePragmaHandler(MSDataSeg.get());
283 PP.RemovePragmaHandler(MSBSSSeg.get());
285 PP.RemovePragmaHandler(MSConstSeg.get());
287 PP.RemovePragmaHandler(MSCodeSeg.get());
289 PP.RemovePragmaHandler(MSSection.get());
293 PP.RemovePragmaHandler("STDC", FPContractHandler.get());
294 FPContractHandler.reset();
296 PP.RemovePragmaHandler("clang", OptimizeHandler.get());
297 OptimizeHandler.reset();
299 PP.RemovePragmaHandler("clang", LoopHintHandler.get());
300 LoopHintHandler.reset();
302 PP.RemovePragmaHandler(UnrollHintHandler.get());
303 UnrollHintHandler.reset();
305 PP.RemovePragmaHandler(NoUnrollHintHandler.get());
306 NoUnrollHintHandler.reset();
309 /// \brief Handle the annotation token produced for #pragma unused(...)
311 /// Each annot_pragma_unused is followed by the argument token so e.g.
312 /// "#pragma unused(x,y)" becomes:
313 /// annot_pragma_unused 'x' annot_pragma_unused 'y'
314 void Parser::HandlePragmaUnused() {
315 assert(Tok.is(tok::annot_pragma_unused));
316 SourceLocation UnusedLoc = ConsumeToken();
317 Actions.ActOnPragmaUnused(Tok, getCurScope(), UnusedLoc);
318 ConsumeToken(); // The argument token.
321 void Parser::HandlePragmaVisibility() {
322 assert(Tok.is(tok::annot_pragma_vis));
323 const IdentifierInfo *VisType =
324 static_cast<IdentifierInfo *>(Tok.getAnnotationValue());
325 SourceLocation VisLoc = ConsumeToken();
326 Actions.ActOnPragmaVisibility(VisType, VisLoc);
329 struct PragmaPackInfo {
330 Sema::PragmaPackKind Kind;
331 IdentifierInfo *Name;
333 SourceLocation LParenLoc;
334 SourceLocation RParenLoc;
337 void Parser::HandlePragmaPack() {
338 assert(Tok.is(tok::annot_pragma_pack));
339 PragmaPackInfo *Info =
340 static_cast<PragmaPackInfo *>(Tok.getAnnotationValue());
341 SourceLocation PragmaLoc = ConsumeToken();
342 ExprResult Alignment;
343 if (Info->Alignment.is(tok::numeric_constant)) {
344 Alignment = Actions.ActOnNumericConstant(Info->Alignment);
345 if (Alignment.isInvalid())
348 Actions.ActOnPragmaPack(Info->Kind, Info->Name, Alignment.get(), PragmaLoc,
349 Info->LParenLoc, Info->RParenLoc);
352 void Parser::HandlePragmaMSStruct() {
353 assert(Tok.is(tok::annot_pragma_msstruct));
354 Sema::PragmaMSStructKind Kind =
355 static_cast<Sema::PragmaMSStructKind>(
356 reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
357 Actions.ActOnPragmaMSStruct(Kind);
358 ConsumeToken(); // The annotation token.
361 void Parser::HandlePragmaAlign() {
362 assert(Tok.is(tok::annot_pragma_align));
363 Sema::PragmaOptionsAlignKind Kind =
364 static_cast<Sema::PragmaOptionsAlignKind>(
365 reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
366 SourceLocation PragmaLoc = ConsumeToken();
367 Actions.ActOnPragmaOptionsAlign(Kind, PragmaLoc);
370 void Parser::HandlePragmaWeak() {
371 assert(Tok.is(tok::annot_pragma_weak));
372 SourceLocation PragmaLoc = ConsumeToken();
373 Actions.ActOnPragmaWeakID(Tok.getIdentifierInfo(), PragmaLoc,
375 ConsumeToken(); // The weak name.
378 void Parser::HandlePragmaWeakAlias() {
379 assert(Tok.is(tok::annot_pragma_weakalias));
380 SourceLocation PragmaLoc = ConsumeToken();
381 IdentifierInfo *WeakName = Tok.getIdentifierInfo();
382 SourceLocation WeakNameLoc = Tok.getLocation();
384 IdentifierInfo *AliasName = Tok.getIdentifierInfo();
385 SourceLocation AliasNameLoc = Tok.getLocation();
387 Actions.ActOnPragmaWeakAlias(WeakName, AliasName, PragmaLoc,
388 WeakNameLoc, AliasNameLoc);
392 void Parser::HandlePragmaRedefineExtname() {
393 assert(Tok.is(tok::annot_pragma_redefine_extname));
394 SourceLocation RedefLoc = ConsumeToken();
395 IdentifierInfo *RedefName = Tok.getIdentifierInfo();
396 SourceLocation RedefNameLoc = Tok.getLocation();
398 IdentifierInfo *AliasName = Tok.getIdentifierInfo();
399 SourceLocation AliasNameLoc = Tok.getLocation();
401 Actions.ActOnPragmaRedefineExtname(RedefName, AliasName, RedefLoc,
402 RedefNameLoc, AliasNameLoc);
405 void Parser::HandlePragmaFPContract() {
406 assert(Tok.is(tok::annot_pragma_fp_contract));
407 tok::OnOffSwitch OOS =
408 static_cast<tok::OnOffSwitch>(
409 reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
410 Actions.ActOnPragmaFPContract(OOS);
411 ConsumeToken(); // The annotation token.
414 StmtResult Parser::HandlePragmaCaptured()
416 assert(Tok.is(tok::annot_pragma_captured));
419 if (Tok.isNot(tok::l_brace)) {
420 PP.Diag(Tok, diag::err_expected) << tok::l_brace;
424 SourceLocation Loc = Tok.getLocation();
426 ParseScope CapturedRegionScope(this, Scope::FnScope | Scope::DeclScope);
427 Actions.ActOnCapturedRegionStart(Loc, getCurScope(), CR_Default,
430 StmtResult R = ParseCompoundStatement();
431 CapturedRegionScope.Exit();
434 Actions.ActOnCapturedRegionError();
438 return Actions.ActOnCapturedRegionEnd(R.get());
442 typedef llvm::PointerIntPair<IdentifierInfo *, 1, bool> OpenCLExtData;
445 void Parser::HandlePragmaOpenCLExtension() {
446 assert(Tok.is(tok::annot_pragma_opencl_extension));
448 OpenCLExtData::getFromOpaqueValue(Tok.getAnnotationValue());
449 unsigned state = data.getInt();
450 IdentifierInfo *ename = data.getPointer();
451 SourceLocation NameLoc = Tok.getLocation();
452 ConsumeToken(); // The annotation token.
454 OpenCLOptions &f = Actions.getOpenCLOptions();
455 // OpenCL 1.1 9.1: "The all variant sets the behavior for all extensions,
456 // overriding all previously issued extension directives, but only if the
457 // behavior is set to disable."
458 if (state == 0 && ename->isStr("all")) {
459 #define OPENCLEXT(nm) f.nm = 0;
460 #include "clang/Basic/OpenCLExtensions.def"
462 #define OPENCLEXT(nm) else if (ename->isStr(#nm)) { f.nm = state; }
463 #include "clang/Basic/OpenCLExtensions.def"
465 PP.Diag(NameLoc, diag::warn_pragma_unknown_extension) << ename;
470 void Parser::HandlePragmaMSPointersToMembers() {
471 assert(Tok.is(tok::annot_pragma_ms_pointers_to_members));
472 LangOptions::PragmaMSPointersToMembersKind RepresentationMethod =
473 static_cast<LangOptions::PragmaMSPointersToMembersKind>(
474 reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
475 SourceLocation PragmaLoc = ConsumeToken(); // The annotation token.
476 Actions.ActOnPragmaMSPointersToMembers(RepresentationMethod, PragmaLoc);
479 void Parser::HandlePragmaMSVtorDisp() {
480 assert(Tok.is(tok::annot_pragma_ms_vtordisp));
481 uintptr_t Value = reinterpret_cast<uintptr_t>(Tok.getAnnotationValue());
482 Sema::PragmaVtorDispKind Kind =
483 static_cast<Sema::PragmaVtorDispKind>((Value >> 16) & 0xFFFF);
484 MSVtorDispAttr::Mode Mode = MSVtorDispAttr::Mode(Value & 0xFFFF);
485 SourceLocation PragmaLoc = ConsumeToken(); // The annotation token.
486 Actions.ActOnPragmaMSVtorDisp(Kind, PragmaLoc, Mode);
489 void Parser::HandlePragmaMSPragma() {
490 assert(Tok.is(tok::annot_pragma_ms_pragma));
491 // Grab the tokens out of the annotation and enter them into the stream.
492 auto TheTokens = (std::pair<Token*, size_t> *)Tok.getAnnotationValue();
493 PP.EnterTokenStream(TheTokens->first, TheTokens->second, true, true);
494 SourceLocation PragmaLocation = ConsumeToken(); // The annotation token.
495 assert(Tok.isAnyIdentifier());
496 StringRef PragmaName = Tok.getIdentifierInfo()->getName();
497 PP.Lex(Tok); // pragma kind
499 // Figure out which #pragma we're dealing with. The switch has no default
500 // because lex shouldn't emit the annotation token for unrecognized pragmas.
501 typedef bool (Parser::*PragmaHandler)(StringRef, SourceLocation);
502 PragmaHandler Handler = llvm::StringSwitch<PragmaHandler>(PragmaName)
503 .Case("data_seg", &Parser::HandlePragmaMSSegment)
504 .Case("bss_seg", &Parser::HandlePragmaMSSegment)
505 .Case("const_seg", &Parser::HandlePragmaMSSegment)
506 .Case("code_seg", &Parser::HandlePragmaMSSegment)
507 .Case("section", &Parser::HandlePragmaMSSection)
508 .Case("init_seg", &Parser::HandlePragmaMSInitSeg);
510 if (!(this->*Handler)(PragmaName, PragmaLocation)) {
511 // Pragma handling failed, and has been diagnosed. Slurp up the tokens
512 // until eof (really end of line) to prevent follow-on errors.
513 while (Tok.isNot(tok::eof))
519 bool Parser::HandlePragmaMSSection(StringRef PragmaName,
520 SourceLocation PragmaLocation) {
521 if (Tok.isNot(tok::l_paren)) {
522 PP.Diag(PragmaLocation, diag::warn_pragma_expected_lparen) << PragmaName;
526 // Parsing code for pragma section
527 if (Tok.isNot(tok::string_literal)) {
528 PP.Diag(PragmaLocation, diag::warn_pragma_expected_section_name)
532 ExprResult StringResult = ParseStringLiteralExpression();
533 if (StringResult.isInvalid())
534 return false; // Already diagnosed.
535 StringLiteral *SegmentName = cast<StringLiteral>(StringResult.get());
536 if (SegmentName->getCharByteWidth() != 1) {
537 PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
541 int SectionFlags = ASTContext::PSF_Read;
542 bool SectionFlagsAreDefault = true;
543 while (Tok.is(tok::comma)) {
545 // Ignore "long" and "short".
546 // They are undocumented, but widely used, section attributes which appear
548 if (Tok.is(tok::kw_long) || Tok.is(tok::kw_short)) {
549 PP.Lex(Tok); // long/short
553 if (!Tok.isAnyIdentifier()) {
554 PP.Diag(PragmaLocation, diag::warn_pragma_expected_action_or_r_paren)
558 ASTContext::PragmaSectionFlag Flag =
559 llvm::StringSwitch<ASTContext::PragmaSectionFlag>(
560 Tok.getIdentifierInfo()->getName())
561 .Case("read", ASTContext::PSF_Read)
562 .Case("write", ASTContext::PSF_Write)
563 .Case("execute", ASTContext::PSF_Execute)
564 .Case("shared", ASTContext::PSF_Invalid)
565 .Case("nopage", ASTContext::PSF_Invalid)
566 .Case("nocache", ASTContext::PSF_Invalid)
567 .Case("discard", ASTContext::PSF_Invalid)
568 .Case("remove", ASTContext::PSF_Invalid)
569 .Default(ASTContext::PSF_None);
570 if (Flag == ASTContext::PSF_None || Flag == ASTContext::PSF_Invalid) {
571 PP.Diag(PragmaLocation, Flag == ASTContext::PSF_None
572 ? diag::warn_pragma_invalid_specific_action
573 : diag::warn_pragma_unsupported_action)
574 << PragmaName << Tok.getIdentifierInfo()->getName();
577 SectionFlags |= Flag;
578 SectionFlagsAreDefault = false;
579 PP.Lex(Tok); // Identifier
581 // If no section attributes are specified, the section will be marked as
583 if (SectionFlagsAreDefault)
584 SectionFlags |= ASTContext::PSF_Write;
585 if (Tok.isNot(tok::r_paren)) {
586 PP.Diag(PragmaLocation, diag::warn_pragma_expected_rparen) << PragmaName;
590 if (Tok.isNot(tok::eof)) {
591 PP.Diag(PragmaLocation, diag::warn_pragma_extra_tokens_at_eol)
596 Actions.ActOnPragmaMSSection(PragmaLocation, SectionFlags, SegmentName);
600 bool Parser::HandlePragmaMSSegment(StringRef PragmaName,
601 SourceLocation PragmaLocation) {
602 if (Tok.isNot(tok::l_paren)) {
603 PP.Diag(PragmaLocation, diag::warn_pragma_expected_lparen) << PragmaName;
607 Sema::PragmaMsStackAction Action = Sema::PSK_Reset;
609 if (Tok.isAnyIdentifier()) {
610 StringRef PushPop = Tok.getIdentifierInfo()->getName();
611 if (PushPop == "push")
612 Action = Sema::PSK_Push;
613 else if (PushPop == "pop")
614 Action = Sema::PSK_Pop;
616 PP.Diag(PragmaLocation,
617 diag::warn_pragma_expected_section_push_pop_or_name)
621 if (Action != Sema::PSK_Reset) {
622 PP.Lex(Tok); // push | pop
623 if (Tok.is(tok::comma)) {
625 // If we've got a comma, we either need a label or a string.
626 if (Tok.isAnyIdentifier()) {
627 SlotLabel = Tok.getIdentifierInfo()->getName();
628 PP.Lex(Tok); // identifier
629 if (Tok.is(tok::comma))
631 else if (Tok.isNot(tok::r_paren)) {
632 PP.Diag(PragmaLocation, diag::warn_pragma_expected_punc)
637 } else if (Tok.isNot(tok::r_paren)) {
638 PP.Diag(PragmaLocation, diag::warn_pragma_expected_punc) << PragmaName;
643 // Grab the string literal for our section name.
644 StringLiteral *SegmentName = nullptr;
645 if (Tok.isNot(tok::r_paren)) {
646 if (Tok.isNot(tok::string_literal)) {
647 unsigned DiagID = Action != Sema::PSK_Reset ? !SlotLabel.empty() ?
648 diag::warn_pragma_expected_section_name :
649 diag::warn_pragma_expected_section_label_or_name :
650 diag::warn_pragma_expected_section_push_pop_or_name;
651 PP.Diag(PragmaLocation, DiagID) << PragmaName;
654 ExprResult StringResult = ParseStringLiteralExpression();
655 if (StringResult.isInvalid())
656 return false; // Already diagnosed.
657 SegmentName = cast<StringLiteral>(StringResult.get());
658 if (SegmentName->getCharByteWidth() != 1) {
659 PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
663 // Setting section "" has no effect
664 if (SegmentName->getLength())
665 Action = (Sema::PragmaMsStackAction)(Action | Sema::PSK_Set);
667 if (Tok.isNot(tok::r_paren)) {
668 PP.Diag(PragmaLocation, diag::warn_pragma_expected_rparen) << PragmaName;
672 if (Tok.isNot(tok::eof)) {
673 PP.Diag(PragmaLocation, diag::warn_pragma_extra_tokens_at_eol)
678 Actions.ActOnPragmaMSSeg(PragmaLocation, Action, SlotLabel,
679 SegmentName, PragmaName);
683 // #pragma init_seg({ compiler | lib | user | "section-name" [, func-name]} )
684 bool Parser::HandlePragmaMSInitSeg(StringRef PragmaName,
685 SourceLocation PragmaLocation) {
686 if (getTargetInfo().getTriple().getEnvironment() != llvm::Triple::MSVC) {
687 PP.Diag(PragmaLocation, diag::warn_pragma_init_seg_unsupported_target);
691 if (ExpectAndConsume(tok::l_paren, diag::warn_pragma_expected_lparen,
695 // Parse either the known section names or the string section name.
696 StringLiteral *SegmentName = nullptr;
697 if (Tok.isAnyIdentifier()) {
698 auto *II = Tok.getIdentifierInfo();
699 StringRef Section = llvm::StringSwitch<StringRef>(II->getName())
700 .Case("compiler", "\".CRT$XCC\"")
701 .Case("lib", "\".CRT$XCL\"")
702 .Case("user", "\".CRT$XCU\"")
705 if (!Section.empty()) {
706 // Pretend the user wrote the appropriate string literal here.
708 Toks[0].startToken();
709 Toks[0].setKind(tok::string_literal);
710 Toks[0].setLocation(Tok.getLocation());
711 Toks[0].setLiteralData(Section.data());
712 Toks[0].setLength(Section.size());
714 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
717 } else if (Tok.is(tok::string_literal)) {
718 ExprResult StringResult = ParseStringLiteralExpression();
719 if (StringResult.isInvalid())
721 SegmentName = cast<StringLiteral>(StringResult.get());
722 if (SegmentName->getCharByteWidth() != 1) {
723 PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
727 // FIXME: Add support for the '[, func-name]' part of the pragma.
731 PP.Diag(PragmaLocation, diag::warn_pragma_expected_init_seg) << PragmaName;
735 if (ExpectAndConsume(tok::r_paren, diag::warn_pragma_expected_rparen,
737 ExpectAndConsume(tok::eof, diag::warn_pragma_extra_tokens_at_eol,
741 Actions.ActOnPragmaMSInitSeg(PragmaLocation, SegmentName);
745 struct PragmaLoopHintInfo {
750 PragmaLoopHintInfo() : Toks(nullptr), TokSize(0) {}
753 static std::string PragmaLoopHintString(Token PragmaName, Token Option) {
754 std::string PragmaString;
755 if (PragmaName.getIdentifierInfo()->getName() == "loop") {
756 PragmaString = "clang loop ";
757 PragmaString += Option.getIdentifierInfo()->getName();
759 assert(PragmaName.getIdentifierInfo()->getName() == "unroll" &&
760 "Unexpected pragma name");
761 PragmaString = "unroll";
766 bool Parser::HandlePragmaLoopHint(LoopHint &Hint) {
767 assert(Tok.is(tok::annot_pragma_loop_hint));
768 PragmaLoopHintInfo *Info =
769 static_cast<PragmaLoopHintInfo *>(Tok.getAnnotationValue());
771 IdentifierInfo *PragmaNameInfo = Info->PragmaName.getIdentifierInfo();
772 Hint.PragmaNameLoc = IdentifierLoc::create(
773 Actions.Context, Info->PragmaName.getLocation(), PragmaNameInfo);
775 // It is possible that the loop hint has no option identifier, such as
776 // #pragma unroll(4).
777 IdentifierInfo *OptionInfo = Info->Option.is(tok::identifier)
778 ? Info->Option.getIdentifierInfo()
780 Hint.OptionLoc = IdentifierLoc::create(
781 Actions.Context, Info->Option.getLocation(), OptionInfo);
783 Token *Toks = Info->Toks;
784 size_t TokSize = Info->TokSize;
786 // Return a valid hint if pragma unroll or nounroll were specified
787 // without an argument.
788 bool PragmaUnroll = PragmaNameInfo->getName() == "unroll";
789 bool PragmaNoUnroll = PragmaNameInfo->getName() == "nounroll";
790 if (TokSize == 0 && (PragmaUnroll || PragmaNoUnroll)) {
791 ConsumeToken(); // The annotation token.
792 Hint.Range = Info->PragmaName.getLocation();
796 // The constant expression is always followed by an eof token, which increases
798 assert(TokSize > 0 &&
799 "PragmaLoopHintInfo::Toks must contain at least one token.");
801 // If no option is specified the argument is assumed to be a constant expr.
802 bool StateOption = false;
803 if (OptionInfo) { // Pragma unroll does not specify an option.
804 StateOption = llvm::StringSwitch<bool>(OptionInfo->getName())
805 .Case("vectorize", true)
806 .Case("interleave", true)
807 .Case("unroll", true)
811 // Verify loop hint has an argument.
812 if (Toks[0].is(tok::eof)) {
813 ConsumeToken(); // The annotation token.
814 Diag(Toks[0].getLocation(), diag::err_pragma_loop_missing_argument)
815 << /*StateArgument=*/StateOption << /*FullKeyword=*/PragmaUnroll;
819 // Validate the argument.
821 ConsumeToken(); // The annotation token.
822 bool OptionUnroll = OptionInfo->isStr("unroll");
823 SourceLocation StateLoc = Toks[0].getLocation();
824 IdentifierInfo *StateInfo = Toks[0].getIdentifierInfo();
825 if (!StateInfo || ((OptionUnroll ? !StateInfo->isStr("full")
826 : !StateInfo->isStr("enable")) &&
827 !StateInfo->isStr("disable"))) {
828 Diag(Toks[0].getLocation(), diag::err_pragma_invalid_keyword)
829 << /*FullKeyword=*/OptionUnroll;
833 Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
834 << PragmaLoopHintString(Info->PragmaName, Info->Option);
835 Hint.StateLoc = IdentifierLoc::create(Actions.Context, StateLoc, StateInfo);
837 // Enter constant expression including eof terminator into token stream.
838 PP.EnterTokenStream(Toks, TokSize, /*DisableMacroExpansion=*/false,
839 /*OwnsTokens=*/false);
840 ConsumeToken(); // The annotation token.
842 ExprResult R = ParseConstantExpression();
844 // Tokens following an error in an ill-formed constant expression will
845 // remain in the token stream and must be removed.
846 if (Tok.isNot(tok::eof)) {
847 Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
848 << PragmaLoopHintString(Info->PragmaName, Info->Option);
849 while (Tok.isNot(tok::eof))
853 ConsumeToken(); // Consume the constant expression eof terminator.
856 Actions.CheckLoopHintExpr(R.get(), Toks[0].getLocation()))
859 // Argument is a constant expression with an integer type.
860 Hint.ValueExpr = R.get();
863 Hint.Range = SourceRange(Info->PragmaName.getLocation(),
864 Info->Toks[TokSize - 1].getLocation());
868 // #pragma GCC visibility comes in two variants:
869 // 'push' '(' [visibility] ')'
871 void PragmaGCCVisibilityHandler::HandlePragma(Preprocessor &PP,
872 PragmaIntroducerKind Introducer,
874 SourceLocation VisLoc = VisTok.getLocation();
877 PP.LexUnexpandedToken(Tok);
879 const IdentifierInfo *PushPop = Tok.getIdentifierInfo();
881 const IdentifierInfo *VisType;
882 if (PushPop && PushPop->isStr("pop")) {
884 } else if (PushPop && PushPop->isStr("push")) {
885 PP.LexUnexpandedToken(Tok);
886 if (Tok.isNot(tok::l_paren)) {
887 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen)
891 PP.LexUnexpandedToken(Tok);
892 VisType = Tok.getIdentifierInfo();
894 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
898 PP.LexUnexpandedToken(Tok);
899 if (Tok.isNot(tok::r_paren)) {
900 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen)
905 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
909 SourceLocation EndLoc = Tok.getLocation();
910 PP.LexUnexpandedToken(Tok);
911 if (Tok.isNot(tok::eod)) {
912 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
917 Token *Toks = new Token[1];
918 Toks[0].startToken();
919 Toks[0].setKind(tok::annot_pragma_vis);
920 Toks[0].setLocation(VisLoc);
921 Toks[0].setAnnotationEndLoc(EndLoc);
922 Toks[0].setAnnotationValue(
923 const_cast<void*>(static_cast<const void*>(VisType)));
924 PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
925 /*OwnsTokens=*/true);
928 // #pragma pack(...) comes in the following delicious flavors:
929 // pack '(' [integer] ')'
930 // pack '(' 'show' ')'
931 // pack '(' ('push' | 'pop') [',' identifier] [, integer] ')'
932 void PragmaPackHandler::HandlePragma(Preprocessor &PP,
933 PragmaIntroducerKind Introducer,
935 SourceLocation PackLoc = PackTok.getLocation();
939 if (Tok.isNot(tok::l_paren)) {
940 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "pack";
944 Sema::PragmaPackKind Kind = Sema::PPK_Default;
945 IdentifierInfo *Name = nullptr;
947 Alignment.startToken();
948 SourceLocation LParenLoc = Tok.getLocation();
950 if (Tok.is(tok::numeric_constant)) {
955 // In MSVC/gcc, #pragma pack(4) sets the alignment without affecting
956 // the push/pop stack.
957 // In Apple gcc, #pragma pack(4) is equivalent to #pragma pack(push, 4)
958 if (PP.getLangOpts().ApplePragmaPack)
959 Kind = Sema::PPK_Push;
960 } else if (Tok.is(tok::identifier)) {
961 const IdentifierInfo *II = Tok.getIdentifierInfo();
962 if (II->isStr("show")) {
963 Kind = Sema::PPK_Show;
966 if (II->isStr("push")) {
967 Kind = Sema::PPK_Push;
968 } else if (II->isStr("pop")) {
969 Kind = Sema::PPK_Pop;
971 PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_action) << "pack";
976 if (Tok.is(tok::comma)) {
979 if (Tok.is(tok::numeric_constant)) {
983 } else if (Tok.is(tok::identifier)) {
984 Name = Tok.getIdentifierInfo();
987 if (Tok.is(tok::comma)) {
990 if (Tok.isNot(tok::numeric_constant)) {
991 PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_malformed);
1000 PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_malformed);
1005 } else if (PP.getLangOpts().ApplePragmaPack) {
1006 // In MSVC/gcc, #pragma pack() resets the alignment without affecting
1007 // the push/pop stack.
1008 // In Apple gcc #pragma pack() is equivalent to #pragma pack(pop).
1009 Kind = Sema::PPK_Pop;
1012 if (Tok.isNot(tok::r_paren)) {
1013 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen) << "pack";
1017 SourceLocation RParenLoc = Tok.getLocation();
1019 if (Tok.isNot(tok::eod)) {
1020 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "pack";
1024 PragmaPackInfo *Info =
1025 (PragmaPackInfo*) PP.getPreprocessorAllocator().Allocate(
1026 sizeof(PragmaPackInfo), llvm::alignOf<PragmaPackInfo>());
1027 new (Info) PragmaPackInfo();
1030 Info->Alignment = Alignment;
1031 Info->LParenLoc = LParenLoc;
1032 Info->RParenLoc = RParenLoc;
1035 (Token*) PP.getPreprocessorAllocator().Allocate(
1036 sizeof(Token) * 1, llvm::alignOf<Token>());
1038 Toks[0].startToken();
1039 Toks[0].setKind(tok::annot_pragma_pack);
1040 Toks[0].setLocation(PackLoc);
1041 Toks[0].setAnnotationEndLoc(RParenLoc);
1042 Toks[0].setAnnotationValue(static_cast<void*>(Info));
1043 PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
1044 /*OwnsTokens=*/false);
1047 // #pragma ms_struct on
1048 // #pragma ms_struct off
1049 void PragmaMSStructHandler::HandlePragma(Preprocessor &PP,
1050 PragmaIntroducerKind Introducer,
1051 Token &MSStructTok) {
1052 Sema::PragmaMSStructKind Kind = Sema::PMSST_OFF;
1056 if (Tok.isNot(tok::identifier)) {
1057 PP.Diag(Tok.getLocation(), diag::warn_pragma_ms_struct);
1060 SourceLocation EndLoc = Tok.getLocation();
1061 const IdentifierInfo *II = Tok.getIdentifierInfo();
1062 if (II->isStr("on")) {
1063 Kind = Sema::PMSST_ON;
1066 else if (II->isStr("off") || II->isStr("reset"))
1069 PP.Diag(Tok.getLocation(), diag::warn_pragma_ms_struct);
1073 if (Tok.isNot(tok::eod)) {
1074 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1080 (Token*) PP.getPreprocessorAllocator().Allocate(
1081 sizeof(Token) * 1, llvm::alignOf<Token>());
1083 Toks[0].startToken();
1084 Toks[0].setKind(tok::annot_pragma_msstruct);
1085 Toks[0].setLocation(MSStructTok.getLocation());
1086 Toks[0].setAnnotationEndLoc(EndLoc);
1087 Toks[0].setAnnotationValue(reinterpret_cast<void*>(
1088 static_cast<uintptr_t>(Kind)));
1089 PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
1090 /*OwnsTokens=*/false);
1093 // #pragma 'align' '=' {'native','natural','mac68k','power','reset'}
1094 // #pragma 'options 'align' '=' {'native','natural','mac68k','power','reset'}
1095 static void ParseAlignPragma(Preprocessor &PP, Token &FirstTok,
1101 if (Tok.isNot(tok::identifier) ||
1102 !Tok.getIdentifierInfo()->isStr("align")) {
1103 PP.Diag(Tok.getLocation(), diag::warn_pragma_options_expected_align);
1109 if (Tok.isNot(tok::equal)) {
1110 PP.Diag(Tok.getLocation(), diag::warn_pragma_align_expected_equal)
1116 if (Tok.isNot(tok::identifier)) {
1117 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
1118 << (IsOptions ? "options" : "align");
1122 Sema::PragmaOptionsAlignKind Kind = Sema::POAK_Natural;
1123 const IdentifierInfo *II = Tok.getIdentifierInfo();
1124 if (II->isStr("native"))
1125 Kind = Sema::POAK_Native;
1126 else if (II->isStr("natural"))
1127 Kind = Sema::POAK_Natural;
1128 else if (II->isStr("packed"))
1129 Kind = Sema::POAK_Packed;
1130 else if (II->isStr("power"))
1131 Kind = Sema::POAK_Power;
1132 else if (II->isStr("mac68k"))
1133 Kind = Sema::POAK_Mac68k;
1134 else if (II->isStr("reset"))
1135 Kind = Sema::POAK_Reset;
1137 PP.Diag(Tok.getLocation(), diag::warn_pragma_align_invalid_option)
1142 SourceLocation EndLoc = Tok.getLocation();
1144 if (Tok.isNot(tok::eod)) {
1145 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1146 << (IsOptions ? "options" : "align");
1151 (Token*) PP.getPreprocessorAllocator().Allocate(
1152 sizeof(Token) * 1, llvm::alignOf<Token>());
1154 Toks[0].startToken();
1155 Toks[0].setKind(tok::annot_pragma_align);
1156 Toks[0].setLocation(FirstTok.getLocation());
1157 Toks[0].setAnnotationEndLoc(EndLoc);
1158 Toks[0].setAnnotationValue(reinterpret_cast<void*>(
1159 static_cast<uintptr_t>(Kind)));
1160 PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
1161 /*OwnsTokens=*/false);
1164 void PragmaAlignHandler::HandlePragma(Preprocessor &PP,
1165 PragmaIntroducerKind Introducer,
1167 ParseAlignPragma(PP, AlignTok, /*IsOptions=*/false);
1170 void PragmaOptionsHandler::HandlePragma(Preprocessor &PP,
1171 PragmaIntroducerKind Introducer,
1172 Token &OptionsTok) {
1173 ParseAlignPragma(PP, OptionsTok, /*IsOptions=*/true);
1176 // #pragma unused(identifier)
1177 void PragmaUnusedHandler::HandlePragma(Preprocessor &PP,
1178 PragmaIntroducerKind Introducer,
1180 // FIXME: Should we be expanding macros here? My guess is no.
1181 SourceLocation UnusedLoc = UnusedTok.getLocation();
1183 // Lex the left '('.
1186 if (Tok.isNot(tok::l_paren)) {
1187 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "unused";
1191 // Lex the declaration reference(s).
1192 SmallVector<Token, 5> Identifiers;
1193 SourceLocation RParenLoc;
1200 if (Tok.is(tok::identifier)) {
1201 Identifiers.push_back(Tok);
1207 PP.Diag(Tok.getLocation(), diag::warn_pragma_unused_expected_var);
1211 // We are execting a ')' or a ','.
1212 if (Tok.is(tok::comma)) {
1217 if (Tok.is(tok::r_paren)) {
1218 RParenLoc = Tok.getLocation();
1223 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_punc) << "unused";
1228 if (Tok.isNot(tok::eod)) {
1229 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
1234 // Verify that we have a location for the right parenthesis.
1235 assert(RParenLoc.isValid() && "Valid '#pragma unused' must have ')'");
1236 assert(!Identifiers.empty() && "Valid '#pragma unused' must have arguments");
1238 // For each identifier token, insert into the token stream a
1239 // annot_pragma_unused token followed by the identifier token.
1240 // This allows us to cache a "#pragma unused" that occurs inside an inline
1241 // C++ member function.
1244 (Token*) PP.getPreprocessorAllocator().Allocate(
1245 sizeof(Token) * 2 * Identifiers.size(), llvm::alignOf<Token>());
1246 for (unsigned i=0; i != Identifiers.size(); i++) {
1247 Token &pragmaUnusedTok = Toks[2*i], &idTok = Toks[2*i+1];
1248 pragmaUnusedTok.startToken();
1249 pragmaUnusedTok.setKind(tok::annot_pragma_unused);
1250 pragmaUnusedTok.setLocation(UnusedLoc);
1251 idTok = Identifiers[i];
1253 PP.EnterTokenStream(Toks, 2*Identifiers.size(),
1254 /*DisableMacroExpansion=*/true, /*OwnsTokens=*/false);
1257 // #pragma weak identifier
1258 // #pragma weak identifier '=' identifier
1259 void PragmaWeakHandler::HandlePragma(Preprocessor &PP,
1260 PragmaIntroducerKind Introducer,
1262 SourceLocation WeakLoc = WeakTok.getLocation();
1266 if (Tok.isNot(tok::identifier)) {
1267 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) << "weak";
1271 Token WeakName = Tok;
1272 bool HasAlias = false;
1276 if (Tok.is(tok::equal)) {
1279 if (Tok.isNot(tok::identifier)) {
1280 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
1288 if (Tok.isNot(tok::eod)) {
1289 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "weak";
1295 (Token*) PP.getPreprocessorAllocator().Allocate(
1296 sizeof(Token) * 3, llvm::alignOf<Token>());
1297 Token &pragmaUnusedTok = Toks[0];
1298 pragmaUnusedTok.startToken();
1299 pragmaUnusedTok.setKind(tok::annot_pragma_weakalias);
1300 pragmaUnusedTok.setLocation(WeakLoc);
1301 pragmaUnusedTok.setAnnotationEndLoc(AliasName.getLocation());
1303 Toks[2] = AliasName;
1304 PP.EnterTokenStream(Toks, 3,
1305 /*DisableMacroExpansion=*/true, /*OwnsTokens=*/false);
1308 (Token*) PP.getPreprocessorAllocator().Allocate(
1309 sizeof(Token) * 2, llvm::alignOf<Token>());
1310 Token &pragmaUnusedTok = Toks[0];
1311 pragmaUnusedTok.startToken();
1312 pragmaUnusedTok.setKind(tok::annot_pragma_weak);
1313 pragmaUnusedTok.setLocation(WeakLoc);
1314 pragmaUnusedTok.setAnnotationEndLoc(WeakLoc);
1316 PP.EnterTokenStream(Toks, 2,
1317 /*DisableMacroExpansion=*/true, /*OwnsTokens=*/false);
1321 // #pragma redefine_extname identifier identifier
1322 void PragmaRedefineExtnameHandler::HandlePragma(Preprocessor &PP,
1323 PragmaIntroducerKind Introducer,
1324 Token &RedefToken) {
1325 SourceLocation RedefLoc = RedefToken.getLocation();
1329 if (Tok.isNot(tok::identifier)) {
1330 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) <<
1335 Token RedefName = Tok;
1338 if (Tok.isNot(tok::identifier)) {
1339 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
1340 << "redefine_extname";
1344 Token AliasName = Tok;
1347 if (Tok.isNot(tok::eod)) {
1348 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
1354 (Token*) PP.getPreprocessorAllocator().Allocate(
1355 sizeof(Token) * 3, llvm::alignOf<Token>());
1356 Token &pragmaRedefTok = Toks[0];
1357 pragmaRedefTok.startToken();
1358 pragmaRedefTok.setKind(tok::annot_pragma_redefine_extname);
1359 pragmaRedefTok.setLocation(RedefLoc);
1360 pragmaRedefTok.setAnnotationEndLoc(AliasName.getLocation());
1361 Toks[1] = RedefName;
1362 Toks[2] = AliasName;
1363 PP.EnterTokenStream(Toks, 3,
1364 /*DisableMacroExpansion=*/true, /*OwnsTokens=*/false);
1369 PragmaFPContractHandler::HandlePragma(Preprocessor &PP,
1370 PragmaIntroducerKind Introducer,
1372 tok::OnOffSwitch OOS;
1373 if (PP.LexOnOffSwitch(OOS))
1377 (Token*) PP.getPreprocessorAllocator().Allocate(
1378 sizeof(Token) * 1, llvm::alignOf<Token>());
1380 Toks[0].startToken();
1381 Toks[0].setKind(tok::annot_pragma_fp_contract);
1382 Toks[0].setLocation(Tok.getLocation());
1383 Toks[0].setAnnotationEndLoc(Tok.getLocation());
1384 Toks[0].setAnnotationValue(reinterpret_cast<void*>(
1385 static_cast<uintptr_t>(OOS)));
1386 PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
1387 /*OwnsTokens=*/false);
1391 PragmaOpenCLExtensionHandler::HandlePragma(Preprocessor &PP,
1392 PragmaIntroducerKind Introducer,
1394 PP.LexUnexpandedToken(Tok);
1395 if (Tok.isNot(tok::identifier)) {
1396 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) <<
1400 IdentifierInfo *ename = Tok.getIdentifierInfo();
1401 SourceLocation NameLoc = Tok.getLocation();
1404 if (Tok.isNot(tok::colon)) {
1405 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_colon) << ename;
1410 if (Tok.isNot(tok::identifier)) {
1411 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_enable_disable);
1414 IdentifierInfo *op = Tok.getIdentifierInfo();
1417 if (op->isStr("enable")) {
1419 } else if (op->isStr("disable")) {
1422 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_enable_disable);
1425 SourceLocation StateLoc = Tok.getLocation();
1428 if (Tok.isNot(tok::eod)) {
1429 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
1434 OpenCLExtData data(ename, state);
1436 (Token*) PP.getPreprocessorAllocator().Allocate(
1437 sizeof(Token) * 1, llvm::alignOf<Token>());
1439 Toks[0].startToken();
1440 Toks[0].setKind(tok::annot_pragma_opencl_extension);
1441 Toks[0].setLocation(NameLoc);
1442 Toks[0].setAnnotationValue(data.getOpaqueValue());
1443 Toks[0].setAnnotationEndLoc(StateLoc);
1444 PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
1445 /*OwnsTokens=*/false);
1447 if (PP.getPPCallbacks())
1448 PP.getPPCallbacks()->PragmaOpenCLExtension(NameLoc, ename,
1452 /// \brief Handle '#pragma omp ...' when OpenMP is disabled.
1455 PragmaNoOpenMPHandler::HandlePragma(Preprocessor &PP,
1456 PragmaIntroducerKind Introducer,
1458 if (!PP.getDiagnostics().isIgnored(diag::warn_pragma_omp_ignored,
1459 FirstTok.getLocation())) {
1460 PP.Diag(FirstTok, diag::warn_pragma_omp_ignored);
1461 PP.getDiagnostics().setSeverity(diag::warn_pragma_omp_ignored,
1462 diag::Severity::Ignored, SourceLocation());
1464 PP.DiscardUntilEndOfDirective();
1467 /// \brief Handle '#pragma omp ...' when OpenMP is enabled.
1470 PragmaOpenMPHandler::HandlePragma(Preprocessor &PP,
1471 PragmaIntroducerKind Introducer,
1473 SmallVector<Token, 16> Pragma;
1476 Tok.setKind(tok::annot_pragma_openmp);
1477 Tok.setLocation(FirstTok.getLocation());
1479 while (Tok.isNot(tok::eod)) {
1480 Pragma.push_back(Tok);
1483 SourceLocation EodLoc = Tok.getLocation();
1485 Tok.setKind(tok::annot_pragma_openmp_end);
1486 Tok.setLocation(EodLoc);
1487 Pragma.push_back(Tok);
1489 Token *Toks = new Token[Pragma.size()];
1490 std::copy(Pragma.begin(), Pragma.end(), Toks);
1491 PP.EnterTokenStream(Toks, Pragma.size(),
1492 /*DisableMacroExpansion=*/false, /*OwnsTokens=*/true);
1495 /// \brief Handle '#pragma pointers_to_members'
1496 // The grammar for this pragma is as follows:
1498 // <inheritance model> ::= ('single' | 'multiple' | 'virtual') '_inheritance'
1500 // #pragma pointers_to_members '(' 'best_case' ')'
1501 // #pragma pointers_to_members '(' 'full_generality' [',' inheritance-model] ')'
1502 // #pragma pointers_to_members '(' inheritance-model ')'
1503 void PragmaMSPointersToMembers::HandlePragma(Preprocessor &PP,
1504 PragmaIntroducerKind Introducer,
1506 SourceLocation PointersToMembersLoc = Tok.getLocation();
1508 if (Tok.isNot(tok::l_paren)) {
1509 PP.Diag(PointersToMembersLoc, diag::warn_pragma_expected_lparen)
1510 << "pointers_to_members";
1514 const IdentifierInfo *Arg = Tok.getIdentifierInfo();
1516 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
1517 << "pointers_to_members";
1522 LangOptions::PragmaMSPointersToMembersKind RepresentationMethod;
1523 if (Arg->isStr("best_case")) {
1524 RepresentationMethod = LangOptions::PPTMK_BestCase;
1526 if (Arg->isStr("full_generality")) {
1527 if (Tok.is(tok::comma)) {
1530 Arg = Tok.getIdentifierInfo();
1532 PP.Diag(Tok.getLocation(),
1533 diag::err_pragma_pointers_to_members_unknown_kind)
1534 << Tok.getKind() << /*OnlyInheritanceModels*/ 0;
1538 } else if (Tok.is(tok::r_paren)) {
1539 // #pragma pointers_to_members(full_generality) implicitly specifies
1540 // virtual_inheritance.
1542 RepresentationMethod = LangOptions::PPTMK_FullGeneralityVirtualInheritance;
1544 PP.Diag(Tok.getLocation(), diag::err_expected_punc)
1545 << "full_generality";
1551 if (Arg->isStr("single_inheritance")) {
1552 RepresentationMethod =
1553 LangOptions::PPTMK_FullGeneralitySingleInheritance;
1554 } else if (Arg->isStr("multiple_inheritance")) {
1555 RepresentationMethod =
1556 LangOptions::PPTMK_FullGeneralityMultipleInheritance;
1557 } else if (Arg->isStr("virtual_inheritance")) {
1558 RepresentationMethod =
1559 LangOptions::PPTMK_FullGeneralityVirtualInheritance;
1561 PP.Diag(Tok.getLocation(),
1562 diag::err_pragma_pointers_to_members_unknown_kind)
1563 << Arg << /*HasPointerDeclaration*/ 1;
1569 if (Tok.isNot(tok::r_paren)) {
1570 PP.Diag(Tok.getLocation(), diag::err_expected_rparen_after)
1571 << (Arg ? Arg->getName() : "full_generality");
1575 SourceLocation EndLoc = Tok.getLocation();
1577 if (Tok.isNot(tok::eod)) {
1578 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1579 << "pointers_to_members";
1584 AnnotTok.startToken();
1585 AnnotTok.setKind(tok::annot_pragma_ms_pointers_to_members);
1586 AnnotTok.setLocation(PointersToMembersLoc);
1587 AnnotTok.setAnnotationEndLoc(EndLoc);
1588 AnnotTok.setAnnotationValue(
1589 reinterpret_cast<void *>(static_cast<uintptr_t>(RepresentationMethod)));
1590 PP.EnterToken(AnnotTok);
1593 /// \brief Handle '#pragma vtordisp'
1594 // The grammar for this pragma is as follows:
1596 // <vtordisp-mode> ::= ('off' | 'on' | '0' | '1' | '2' )
1598 // #pragma vtordisp '(' ['push' ','] vtordisp-mode ')'
1599 // #pragma vtordisp '(' 'pop' ')'
1600 // #pragma vtordisp '(' ')'
1601 void PragmaMSVtorDisp::HandlePragma(Preprocessor &PP,
1602 PragmaIntroducerKind Introducer,
1604 SourceLocation VtorDispLoc = Tok.getLocation();
1606 if (Tok.isNot(tok::l_paren)) {
1607 PP.Diag(VtorDispLoc, diag::warn_pragma_expected_lparen) << "vtordisp";
1612 Sema::PragmaVtorDispKind Kind = Sema::PVDK_Set;
1613 const IdentifierInfo *II = Tok.getIdentifierInfo();
1615 if (II->isStr("push")) {
1616 // #pragma vtordisp(push, mode)
1618 if (Tok.isNot(tok::comma)) {
1619 PP.Diag(VtorDispLoc, diag::warn_pragma_expected_punc) << "vtordisp";
1623 Kind = Sema::PVDK_Push;
1624 // not push, could be on/off
1625 } else if (II->isStr("pop")) {
1626 // #pragma vtordisp(pop)
1628 Kind = Sema::PVDK_Pop;
1630 // not push or pop, could be on/off
1632 if (Tok.is(tok::r_paren)) {
1633 // #pragma vtordisp()
1634 Kind = Sema::PVDK_Reset;
1640 if (Kind == Sema::PVDK_Push || Kind == Sema::PVDK_Set) {
1641 const IdentifierInfo *II = Tok.getIdentifierInfo();
1642 if (II && II->isStr("off")) {
1645 } else if (II && II->isStr("on")) {
1648 } else if (Tok.is(tok::numeric_constant) &&
1649 PP.parseSimpleIntegerLiteral(Tok, Value)) {
1651 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_integer)
1652 << 0 << 2 << "vtordisp";
1656 PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_action)
1662 // Finish the pragma: ')' $
1663 if (Tok.isNot(tok::r_paren)) {
1664 PP.Diag(VtorDispLoc, diag::warn_pragma_expected_rparen) << "vtordisp";
1667 SourceLocation EndLoc = Tok.getLocation();
1669 if (Tok.isNot(tok::eod)) {
1670 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1675 // Enter the annotation.
1677 AnnotTok.startToken();
1678 AnnotTok.setKind(tok::annot_pragma_ms_vtordisp);
1679 AnnotTok.setLocation(VtorDispLoc);
1680 AnnotTok.setAnnotationEndLoc(EndLoc);
1681 AnnotTok.setAnnotationValue(reinterpret_cast<void *>(
1682 static_cast<uintptr_t>((Kind << 16) | (Value & 0xFFFF))));
1683 PP.EnterToken(AnnotTok);
1686 /// \brief Handle all MS pragmas. Simply forwards the tokens after inserting
1687 /// an annotation token.
1688 void PragmaMSPragma::HandlePragma(Preprocessor &PP,
1689 PragmaIntroducerKind Introducer,
1691 Token EoF, AnnotTok;
1693 EoF.setKind(tok::eof);
1694 AnnotTok.startToken();
1695 AnnotTok.setKind(tok::annot_pragma_ms_pragma);
1696 AnnotTok.setLocation(Tok.getLocation());
1697 AnnotTok.setAnnotationEndLoc(Tok.getLocation());
1698 SmallVector<Token, 8> TokenVector;
1699 // Suck up all of the tokens before the eod.
1700 for (; Tok.isNot(tok::eod); PP.Lex(Tok)) {
1701 TokenVector.push_back(Tok);
1702 AnnotTok.setAnnotationEndLoc(Tok.getLocation());
1704 // Add a sentinal EoF token to the end of the list.
1705 TokenVector.push_back(EoF);
1706 // We must allocate this array with new because EnterTokenStream is going to
1708 Token *TokenArray = new Token[TokenVector.size()];
1709 std::copy(TokenVector.begin(), TokenVector.end(), TokenArray);
1710 auto Value = new (PP.getPreprocessorAllocator())
1711 std::pair<Token*, size_t>(std::make_pair(TokenArray, TokenVector.size()));
1712 AnnotTok.setAnnotationValue(Value);
1713 PP.EnterToken(AnnotTok);
1716 /// \brief Handle the Microsoft \#pragma detect_mismatch extension.
1720 /// #pragma detect_mismatch("name", "value")
1722 /// Where 'name' and 'value' are quoted strings. The values are embedded in
1723 /// the object file and passed along to the linker. If the linker detects a
1724 /// mismatch in the object file's values for the given name, a LNK2038 error
1725 /// is emitted. See MSDN for more details.
1726 void PragmaDetectMismatchHandler::HandlePragma(Preprocessor &PP,
1727 PragmaIntroducerKind Introducer,
1729 SourceLocation CommentLoc = Tok.getLocation();
1731 if (Tok.isNot(tok::l_paren)) {
1732 PP.Diag(CommentLoc, diag::err_expected) << tok::l_paren;
1736 // Read the name to embed, which must be a string literal.
1737 std::string NameString;
1738 if (!PP.LexStringLiteral(Tok, NameString,
1739 "pragma detect_mismatch",
1740 /*MacroExpansion=*/true))
1743 // Read the comma followed by a second string literal.
1744 std::string ValueString;
1745 if (Tok.isNot(tok::comma)) {
1746 PP.Diag(Tok.getLocation(), diag::err_pragma_detect_mismatch_malformed);
1750 if (!PP.LexStringLiteral(Tok, ValueString, "pragma detect_mismatch",
1751 /*MacroExpansion=*/true))
1754 if (Tok.isNot(tok::r_paren)) {
1755 PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
1758 PP.Lex(Tok); // Eat the r_paren.
1760 if (Tok.isNot(tok::eod)) {
1761 PP.Diag(Tok.getLocation(), diag::err_pragma_detect_mismatch_malformed);
1765 // If the pragma is lexically sound, notify any interested PPCallbacks.
1766 if (PP.getPPCallbacks())
1767 PP.getPPCallbacks()->PragmaDetectMismatch(CommentLoc, NameString,
1770 Actions.ActOnPragmaDetectMismatch(NameString, ValueString);
1773 /// \brief Handle the microsoft \#pragma comment extension.
1777 /// #pragma comment(linker, "foo")
1779 /// 'linker' is one of five identifiers: compiler, exestr, lib, linker, user.
1780 /// "foo" is a string, which is fully macro expanded, and permits string
1781 /// concatenation, embedded escape characters etc. See MSDN for more details.
1782 void PragmaCommentHandler::HandlePragma(Preprocessor &PP,
1783 PragmaIntroducerKind Introducer,
1785 SourceLocation CommentLoc = Tok.getLocation();
1787 if (Tok.isNot(tok::l_paren)) {
1788 PP.Diag(CommentLoc, diag::err_pragma_comment_malformed);
1792 // Read the identifier.
1794 if (Tok.isNot(tok::identifier)) {
1795 PP.Diag(CommentLoc, diag::err_pragma_comment_malformed);
1799 // Verify that this is one of the 5 whitelisted options.
1800 IdentifierInfo *II = Tok.getIdentifierInfo();
1801 Sema::PragmaMSCommentKind Kind =
1802 llvm::StringSwitch<Sema::PragmaMSCommentKind>(II->getName())
1803 .Case("linker", Sema::PCK_Linker)
1804 .Case("lib", Sema::PCK_Lib)
1805 .Case("compiler", Sema::PCK_Compiler)
1806 .Case("exestr", Sema::PCK_ExeStr)
1807 .Case("user", Sema::PCK_User)
1808 .Default(Sema::PCK_Unknown);
1809 if (Kind == Sema::PCK_Unknown) {
1810 PP.Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind);
1814 // On PS4, issue a warning about any pragma comments other than
1815 // #pragma comment lib.
1816 if (PP.getTargetInfo().getTriple().isPS4() && Kind != Sema::PCK_Lib) {
1817 PP.Diag(Tok.getLocation(), diag::warn_pragma_comment_ignored)
1822 // Read the optional string if present.
1824 std::string ArgumentString;
1825 if (Tok.is(tok::comma) && !PP.LexStringLiteral(Tok, ArgumentString,
1827 /*MacroExpansion=*/true))
1830 // FIXME: warn that 'exestr' is deprecated.
1831 // FIXME: If the kind is "compiler" warn if the string is present (it is
1833 // The MSDN docs say that "lib" and "linker" require a string and have a short
1834 // whitelist of linker options they support, but in practice MSVC doesn't
1835 // issue a diagnostic. Therefore neither does clang.
1837 if (Tok.isNot(tok::r_paren)) {
1838 PP.Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
1841 PP.Lex(Tok); // eat the r_paren.
1843 if (Tok.isNot(tok::eod)) {
1844 PP.Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
1848 // If the pragma is lexically sound, notify any interested PPCallbacks.
1849 if (PP.getPPCallbacks())
1850 PP.getPPCallbacks()->PragmaComment(CommentLoc, II, ArgumentString);
1852 Actions.ActOnPragmaMSComment(Kind, ArgumentString);
1855 // #pragma clang optimize off
1856 // #pragma clang optimize on
1857 void PragmaOptimizeHandler::HandlePragma(Preprocessor &PP,
1858 PragmaIntroducerKind Introducer,
1859 Token &FirstToken) {
1862 if (Tok.is(tok::eod)) {
1863 PP.Diag(Tok.getLocation(), diag::err_pragma_missing_argument)
1864 << "clang optimize" << /*Expected=*/true << "'on' or 'off'";
1867 if (Tok.isNot(tok::identifier)) {
1868 PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_invalid_argument)
1869 << PP.getSpelling(Tok);
1872 const IdentifierInfo *II = Tok.getIdentifierInfo();
1873 // The only accepted values are 'on' or 'off'.
1875 if (II->isStr("on")) {
1877 } else if (!II->isStr("off")) {
1878 PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_invalid_argument)
1879 << PP.getSpelling(Tok);
1884 if (Tok.isNot(tok::eod)) {
1885 PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_extra_argument)
1886 << PP.getSpelling(Tok);
1890 Actions.ActOnPragmaOptimize(IsOn, FirstToken.getLocation());
1893 /// \brief Parses loop or unroll pragma hint value and fills in Info.
1894 static bool ParseLoopHintValue(Preprocessor &PP, Token &Tok, Token PragmaName,
1895 Token Option, bool ValueInParens,
1896 PragmaLoopHintInfo &Info) {
1897 SmallVector<Token, 1> ValueList;
1898 int OpenParens = ValueInParens ? 1 : 0;
1899 // Read constant expression.
1900 while (Tok.isNot(tok::eod)) {
1901 if (Tok.is(tok::l_paren))
1903 else if (Tok.is(tok::r_paren)) {
1905 if (OpenParens == 0 && ValueInParens)
1909 ValueList.push_back(Tok);
1913 if (ValueInParens) {
1915 if (Tok.isNot(tok::r_paren)) {
1916 PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
1923 EOFTok.startToken();
1924 EOFTok.setKind(tok::eof);
1925 EOFTok.setLocation(Tok.getLocation());
1926 ValueList.push_back(EOFTok); // Terminates expression for parsing.
1928 Token *TokenArray = (Token *)PP.getPreprocessorAllocator().Allocate(
1929 ValueList.size() * sizeof(Token), llvm::alignOf<Token>());
1930 std::copy(ValueList.begin(), ValueList.end(), TokenArray);
1931 Info.Toks = TokenArray;
1932 Info.TokSize = ValueList.size();
1934 Info.PragmaName = PragmaName;
1935 Info.Option = Option;
1939 /// \brief Handle the \#pragma clang loop directive.
1940 /// #pragma clang 'loop' loop-hints
1943 /// loop-hint loop-hints[opt]
1946 /// 'vectorize' '(' loop-hint-keyword ')'
1947 /// 'interleave' '(' loop-hint-keyword ')'
1948 /// 'unroll' '(' unroll-hint-keyword ')'
1949 /// 'vectorize_width' '(' loop-hint-value ')'
1950 /// 'interleave_count' '(' loop-hint-value ')'
1951 /// 'unroll_count' '(' loop-hint-value ')'
1953 /// loop-hint-keyword:
1957 /// unroll-hint-keyword:
1961 /// loop-hint-value:
1962 /// constant-expression
1964 /// Specifying vectorize(enable) or vectorize_width(_value_) instructs llvm to
1965 /// try vectorizing the instructions of the loop it precedes. Specifying
1966 /// interleave(enable) or interleave_count(_value_) instructs llvm to try
1967 /// interleaving multiple iterations of the loop it precedes. The width of the
1968 /// vector instructions is specified by vectorize_width() and the number of
1969 /// interleaved loop iterations is specified by interleave_count(). Specifying a
1970 /// value of 1 effectively disables vectorization/interleaving, even if it is
1971 /// possible and profitable, and 0 is invalid. The loop vectorizer currently
1972 /// only works on inner loops.
1974 /// The unroll and unroll_count directives control the concatenation
1975 /// unroller. Specifying unroll(full) instructs llvm to try to
1976 /// unroll the loop completely, and unroll(disable) disables unrolling
1977 /// for the loop. Specifying unroll_count(_value_) instructs llvm to
1978 /// try to unroll the loop the number of times indicated by the value.
1979 void PragmaLoopHintHandler::HandlePragma(Preprocessor &PP,
1980 PragmaIntroducerKind Introducer,
1982 // Incoming token is "loop" from "#pragma clang loop".
1983 Token PragmaName = Tok;
1984 SmallVector<Token, 1> TokenList;
1986 // Lex the optimization option and verify it is an identifier.
1988 if (Tok.isNot(tok::identifier)) {
1989 PP.Diag(Tok.getLocation(), diag::err_pragma_loop_invalid_option)
1990 << /*MissingOption=*/true << "";
1994 while (Tok.is(tok::identifier)) {
1996 IdentifierInfo *OptionInfo = Tok.getIdentifierInfo();
1998 bool OptionValid = llvm::StringSwitch<bool>(OptionInfo->getName())
1999 .Case("vectorize", true)
2000 .Case("interleave", true)
2001 .Case("unroll", true)
2002 .Case("vectorize_width", true)
2003 .Case("interleave_count", true)
2004 .Case("unroll_count", true)
2007 PP.Diag(Tok.getLocation(), diag::err_pragma_loop_invalid_option)
2008 << /*MissingOption=*/false << OptionInfo;
2014 if (Tok.isNot(tok::l_paren)) {
2015 PP.Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
2020 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
2021 if (ParseLoopHintValue(PP, Tok, PragmaName, Option, /*ValueInParens=*/true,
2025 // Generate the loop hint token.
2027 LoopHintTok.startToken();
2028 LoopHintTok.setKind(tok::annot_pragma_loop_hint);
2029 LoopHintTok.setLocation(PragmaName.getLocation());
2030 LoopHintTok.setAnnotationEndLoc(PragmaName.getLocation());
2031 LoopHintTok.setAnnotationValue(static_cast<void *>(Info));
2032 TokenList.push_back(LoopHintTok);
2035 if (Tok.isNot(tok::eod)) {
2036 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
2041 Token *TokenArray = new Token[TokenList.size()];
2042 std::copy(TokenList.begin(), TokenList.end(), TokenArray);
2044 PP.EnterTokenStream(TokenArray, TokenList.size(),
2045 /*DisableMacroExpansion=*/false,
2046 /*OwnsTokens=*/true);
2049 /// \brief Handle the loop unroll optimization pragmas.
2051 /// #pragma unroll unroll-hint-value
2052 /// #pragma unroll '(' unroll-hint-value ')'
2053 /// #pragma nounroll
2055 /// unroll-hint-value:
2056 /// constant-expression
2058 /// Loop unrolling hints can be specified with '#pragma unroll' or
2059 /// '#pragma nounroll'. '#pragma unroll' can take a numeric argument optionally
2060 /// contained in parentheses. With no argument the directive instructs llvm to
2061 /// try to unroll the loop completely. A positive integer argument can be
2062 /// specified to indicate the number of times the loop should be unrolled. To
2063 /// maximize compatibility with other compilers the unroll count argument can be
2064 /// specified with or without parentheses. Specifying, '#pragma nounroll'
2065 /// disables unrolling of the loop.
2066 void PragmaUnrollHintHandler::HandlePragma(Preprocessor &PP,
2067 PragmaIntroducerKind Introducer,
2069 // Incoming token is "unroll" for "#pragma unroll", or "nounroll" for
2070 // "#pragma nounroll".
2071 Token PragmaName = Tok;
2073 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
2074 if (Tok.is(tok::eod)) {
2075 // nounroll or unroll pragma without an argument.
2076 Info->PragmaName = PragmaName;
2077 Info->Option.startToken();
2078 } else if (PragmaName.getIdentifierInfo()->getName() == "nounroll") {
2079 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
2083 // Unroll pragma with an argument: "#pragma unroll N" or
2084 // "#pragma unroll(N)".
2085 // Read '(' if it exists.
2086 bool ValueInParens = Tok.is(tok::l_paren);
2091 Option.startToken();
2092 if (ParseLoopHintValue(PP, Tok, PragmaName, Option, ValueInParens, *Info))
2095 // In CUDA, the argument to '#pragma unroll' should not be contained in
2097 if (PP.getLangOpts().CUDA && ValueInParens)
2098 PP.Diag(Info->Toks[0].getLocation(),
2099 diag::warn_pragma_unroll_cuda_value_in_parens);
2101 if (Tok.isNot(tok::eod)) {
2102 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
2108 // Generate the hint token.
2109 Token *TokenArray = new Token[1];
2110 TokenArray[0].startToken();
2111 TokenArray[0].setKind(tok::annot_pragma_loop_hint);
2112 TokenArray[0].setLocation(PragmaName.getLocation());
2113 TokenArray[0].setAnnotationEndLoc(PragmaName.getLocation());
2114 TokenArray[0].setAnnotationValue(static_cast<void *>(Info));
2115 PP.EnterTokenStream(TokenArray, 1, /*DisableMacroExpansion=*/false,
2116 /*OwnsTokens=*/true);