]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Parse/ParsePragma.cpp
Vendor import of clang trunk r290819:
[FreeBSD/FreeBSD.git] / lib / Parse / ParsePragma.cpp
1 //===--- ParsePragma.cpp - Language specific pragma parsing ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the language specific #pragma handlers.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "RAIIObjectsForParser.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/Basic/PragmaKinds.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Lex/Preprocessor.h"
19 #include "clang/Parse/ParseDiagnostic.h"
20 #include "clang/Parse/Parser.h"
21 #include "clang/Sema/LoopHint.h"
22 #include "clang/Sema/Scope.h"
23 #include "llvm/ADT/StringSwitch.h"
24 using namespace clang;
25
26 namespace {
27
28 struct PragmaAlignHandler : public PragmaHandler {
29   explicit PragmaAlignHandler() : PragmaHandler("align") {}
30   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
31                     Token &FirstToken) override;
32 };
33
34 struct PragmaGCCVisibilityHandler : public PragmaHandler {
35   explicit PragmaGCCVisibilityHandler() : PragmaHandler("visibility") {}
36   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
37                     Token &FirstToken) override;
38 };
39
40 struct PragmaOptionsHandler : public PragmaHandler {
41   explicit PragmaOptionsHandler() : PragmaHandler("options") {}
42   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
43                     Token &FirstToken) override;
44 };
45
46 struct PragmaPackHandler : public PragmaHandler {
47   explicit PragmaPackHandler() : PragmaHandler("pack") {}
48   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
49                     Token &FirstToken) override;
50 };
51
52 struct PragmaMSStructHandler : public PragmaHandler {
53   explicit PragmaMSStructHandler() : PragmaHandler("ms_struct") {}
54   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
55                     Token &FirstToken) override;
56 };
57
58 struct PragmaUnusedHandler : public PragmaHandler {
59   PragmaUnusedHandler() : PragmaHandler("unused") {}
60   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
61                     Token &FirstToken) override;
62 };
63
64 struct PragmaWeakHandler : public PragmaHandler {
65   explicit PragmaWeakHandler() : PragmaHandler("weak") {}
66   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
67                     Token &FirstToken) override;
68 };
69
70 struct PragmaRedefineExtnameHandler : public PragmaHandler {
71   explicit PragmaRedefineExtnameHandler() : PragmaHandler("redefine_extname") {}
72   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
73                     Token &FirstToken) override;
74 };
75
76 struct PragmaOpenCLExtensionHandler : public PragmaHandler {
77   PragmaOpenCLExtensionHandler() : PragmaHandler("EXTENSION") {}
78   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
79                     Token &FirstToken) override;
80 };
81
82
83 struct PragmaFPContractHandler : public PragmaHandler {
84   PragmaFPContractHandler() : PragmaHandler("FP_CONTRACT") {}
85   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
86                     Token &FirstToken) override;
87 };
88
89 struct PragmaNoOpenMPHandler : public PragmaHandler {
90   PragmaNoOpenMPHandler() : PragmaHandler("omp") { }
91   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
92                     Token &FirstToken) override;
93 };
94
95 struct PragmaOpenMPHandler : public PragmaHandler {
96   PragmaOpenMPHandler() : PragmaHandler("omp") { }
97   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
98                     Token &FirstToken) override;
99 };
100
101 /// PragmaCommentHandler - "\#pragma comment ...".
102 struct PragmaCommentHandler : public PragmaHandler {
103   PragmaCommentHandler(Sema &Actions)
104     : PragmaHandler("comment"), Actions(Actions) {}
105   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
106                     Token &FirstToken) override;
107 private:
108   Sema &Actions;
109 };
110
111 struct PragmaDetectMismatchHandler : public PragmaHandler {
112   PragmaDetectMismatchHandler(Sema &Actions)
113     : PragmaHandler("detect_mismatch"), Actions(Actions) {}
114   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
115                     Token &FirstToken) override;
116 private:
117   Sema &Actions;
118 };
119
120 struct PragmaMSPointersToMembers : public PragmaHandler {
121   explicit PragmaMSPointersToMembers() : PragmaHandler("pointers_to_members") {}
122   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
123                     Token &FirstToken) override;
124 };
125
126 struct PragmaMSVtorDisp : public PragmaHandler {
127   explicit PragmaMSVtorDisp() : PragmaHandler("vtordisp") {}
128   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
129                     Token &FirstToken) override;
130 };
131
132 struct PragmaMSPragma : public PragmaHandler {
133   explicit PragmaMSPragma(const char *name) : PragmaHandler(name) {}
134   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
135                     Token &FirstToken) override;
136 };
137
138 /// PragmaOptimizeHandler - "\#pragma clang optimize on/off".
139 struct PragmaOptimizeHandler : public PragmaHandler {
140   PragmaOptimizeHandler(Sema &S)
141     : PragmaHandler("optimize"), Actions(S) {}
142   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
143                     Token &FirstToken) override;
144 private:
145   Sema &Actions;
146 };
147
148 struct PragmaLoopHintHandler : public PragmaHandler {
149   PragmaLoopHintHandler() : PragmaHandler("loop") {}
150   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
151                     Token &FirstToken) override;
152 };
153
154 struct PragmaUnrollHintHandler : public PragmaHandler {
155   PragmaUnrollHintHandler(const char *name) : PragmaHandler(name) {}
156   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
157                     Token &FirstToken) override;
158 };
159
160 struct PragmaMSRuntimeChecksHandler : public EmptyPragmaHandler {
161   PragmaMSRuntimeChecksHandler() : EmptyPragmaHandler("runtime_checks") {}
162 };
163
164 struct PragmaMSIntrinsicHandler : public PragmaHandler {
165   PragmaMSIntrinsicHandler() : PragmaHandler("intrinsic") {}
166   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
167                     Token &FirstToken) override;
168 };
169
170 struct PragmaForceCUDAHostDeviceHandler : public PragmaHandler {
171   PragmaForceCUDAHostDeviceHandler(Sema &Actions)
172       : PragmaHandler("force_cuda_host_device"), Actions(Actions) {}
173   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
174                     Token &FirstToken) override;
175
176 private:
177   Sema &Actions;
178 };
179
180 }  // end namespace
181
182 void Parser::initializePragmaHandlers() {
183   AlignHandler.reset(new PragmaAlignHandler());
184   PP.AddPragmaHandler(AlignHandler.get());
185
186   GCCVisibilityHandler.reset(new PragmaGCCVisibilityHandler());
187   PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
188
189   OptionsHandler.reset(new PragmaOptionsHandler());
190   PP.AddPragmaHandler(OptionsHandler.get());
191
192   PackHandler.reset(new PragmaPackHandler());
193   PP.AddPragmaHandler(PackHandler.get());
194
195   MSStructHandler.reset(new PragmaMSStructHandler());
196   PP.AddPragmaHandler(MSStructHandler.get());
197
198   UnusedHandler.reset(new PragmaUnusedHandler());
199   PP.AddPragmaHandler(UnusedHandler.get());
200
201   WeakHandler.reset(new PragmaWeakHandler());
202   PP.AddPragmaHandler(WeakHandler.get());
203
204   RedefineExtnameHandler.reset(new PragmaRedefineExtnameHandler());
205   PP.AddPragmaHandler(RedefineExtnameHandler.get());
206
207   FPContractHandler.reset(new PragmaFPContractHandler());
208   PP.AddPragmaHandler("STDC", FPContractHandler.get());
209
210   if (getLangOpts().OpenCL) {
211     OpenCLExtensionHandler.reset(new PragmaOpenCLExtensionHandler());
212     PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
213
214     PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
215   }
216   if (getLangOpts().OpenMP)
217     OpenMPHandler.reset(new PragmaOpenMPHandler());
218   else
219     OpenMPHandler.reset(new PragmaNoOpenMPHandler());
220   PP.AddPragmaHandler(OpenMPHandler.get());
221
222   if (getLangOpts().MicrosoftExt || getTargetInfo().getTriple().isPS4()) {
223     MSCommentHandler.reset(new PragmaCommentHandler(Actions));
224     PP.AddPragmaHandler(MSCommentHandler.get());
225   }
226
227   if (getLangOpts().MicrosoftExt) {
228     MSDetectMismatchHandler.reset(new PragmaDetectMismatchHandler(Actions));
229     PP.AddPragmaHandler(MSDetectMismatchHandler.get());
230     MSPointersToMembers.reset(new PragmaMSPointersToMembers());
231     PP.AddPragmaHandler(MSPointersToMembers.get());
232     MSVtorDisp.reset(new PragmaMSVtorDisp());
233     PP.AddPragmaHandler(MSVtorDisp.get());
234     MSInitSeg.reset(new PragmaMSPragma("init_seg"));
235     PP.AddPragmaHandler(MSInitSeg.get());
236     MSDataSeg.reset(new PragmaMSPragma("data_seg"));
237     PP.AddPragmaHandler(MSDataSeg.get());
238     MSBSSSeg.reset(new PragmaMSPragma("bss_seg"));
239     PP.AddPragmaHandler(MSBSSSeg.get());
240     MSConstSeg.reset(new PragmaMSPragma("const_seg"));
241     PP.AddPragmaHandler(MSConstSeg.get());
242     MSCodeSeg.reset(new PragmaMSPragma("code_seg"));
243     PP.AddPragmaHandler(MSCodeSeg.get());
244     MSSection.reset(new PragmaMSPragma("section"));
245     PP.AddPragmaHandler(MSSection.get());
246     MSRuntimeChecks.reset(new PragmaMSRuntimeChecksHandler());
247     PP.AddPragmaHandler(MSRuntimeChecks.get());
248     MSIntrinsic.reset(new PragmaMSIntrinsicHandler());
249     PP.AddPragmaHandler(MSIntrinsic.get());
250   }
251
252   if (getLangOpts().CUDA) {
253     CUDAForceHostDeviceHandler.reset(
254         new PragmaForceCUDAHostDeviceHandler(Actions));
255     PP.AddPragmaHandler("clang", CUDAForceHostDeviceHandler.get());
256   }
257
258   OptimizeHandler.reset(new PragmaOptimizeHandler(Actions));
259   PP.AddPragmaHandler("clang", OptimizeHandler.get());
260
261   LoopHintHandler.reset(new PragmaLoopHintHandler());
262   PP.AddPragmaHandler("clang", LoopHintHandler.get());
263
264   UnrollHintHandler.reset(new PragmaUnrollHintHandler("unroll"));
265   PP.AddPragmaHandler(UnrollHintHandler.get());
266
267   NoUnrollHintHandler.reset(new PragmaUnrollHintHandler("nounroll"));
268   PP.AddPragmaHandler(NoUnrollHintHandler.get());
269 }
270
271 void Parser::resetPragmaHandlers() {
272   // Remove the pragma handlers we installed.
273   PP.RemovePragmaHandler(AlignHandler.get());
274   AlignHandler.reset();
275   PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
276   GCCVisibilityHandler.reset();
277   PP.RemovePragmaHandler(OptionsHandler.get());
278   OptionsHandler.reset();
279   PP.RemovePragmaHandler(PackHandler.get());
280   PackHandler.reset();
281   PP.RemovePragmaHandler(MSStructHandler.get());
282   MSStructHandler.reset();
283   PP.RemovePragmaHandler(UnusedHandler.get());
284   UnusedHandler.reset();
285   PP.RemovePragmaHandler(WeakHandler.get());
286   WeakHandler.reset();
287   PP.RemovePragmaHandler(RedefineExtnameHandler.get());
288   RedefineExtnameHandler.reset();
289
290   if (getLangOpts().OpenCL) {
291     PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
292     OpenCLExtensionHandler.reset();
293     PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
294   }
295   PP.RemovePragmaHandler(OpenMPHandler.get());
296   OpenMPHandler.reset();
297
298   if (getLangOpts().MicrosoftExt || getTargetInfo().getTriple().isPS4()) {
299     PP.RemovePragmaHandler(MSCommentHandler.get());
300     MSCommentHandler.reset();
301   }
302
303   if (getLangOpts().MicrosoftExt) {
304     PP.RemovePragmaHandler(MSDetectMismatchHandler.get());
305     MSDetectMismatchHandler.reset();
306     PP.RemovePragmaHandler(MSPointersToMembers.get());
307     MSPointersToMembers.reset();
308     PP.RemovePragmaHandler(MSVtorDisp.get());
309     MSVtorDisp.reset();
310     PP.RemovePragmaHandler(MSInitSeg.get());
311     MSInitSeg.reset();
312     PP.RemovePragmaHandler(MSDataSeg.get());
313     MSDataSeg.reset();
314     PP.RemovePragmaHandler(MSBSSSeg.get());
315     MSBSSSeg.reset();
316     PP.RemovePragmaHandler(MSConstSeg.get());
317     MSConstSeg.reset();
318     PP.RemovePragmaHandler(MSCodeSeg.get());
319     MSCodeSeg.reset();
320     PP.RemovePragmaHandler(MSSection.get());
321     MSSection.reset();
322     PP.RemovePragmaHandler(MSRuntimeChecks.get());
323     MSRuntimeChecks.reset();
324     PP.RemovePragmaHandler(MSIntrinsic.get());
325     MSIntrinsic.reset();
326   }
327
328   if (getLangOpts().CUDA) {
329     PP.RemovePragmaHandler("clang", CUDAForceHostDeviceHandler.get());
330     CUDAForceHostDeviceHandler.reset();
331   }
332
333   PP.RemovePragmaHandler("STDC", FPContractHandler.get());
334   FPContractHandler.reset();
335
336   PP.RemovePragmaHandler("clang", OptimizeHandler.get());
337   OptimizeHandler.reset();
338
339   PP.RemovePragmaHandler("clang", LoopHintHandler.get());
340   LoopHintHandler.reset();
341
342   PP.RemovePragmaHandler(UnrollHintHandler.get());
343   UnrollHintHandler.reset();
344
345   PP.RemovePragmaHandler(NoUnrollHintHandler.get());
346   NoUnrollHintHandler.reset();
347 }
348
349 /// \brief Handle the annotation token produced for #pragma unused(...)
350 ///
351 /// Each annot_pragma_unused is followed by the argument token so e.g.
352 /// "#pragma unused(x,y)" becomes:
353 /// annot_pragma_unused 'x' annot_pragma_unused 'y'
354 void Parser::HandlePragmaUnused() {
355   assert(Tok.is(tok::annot_pragma_unused));
356   SourceLocation UnusedLoc = ConsumeToken();
357   Actions.ActOnPragmaUnused(Tok, getCurScope(), UnusedLoc);
358   ConsumeToken(); // The argument token.
359 }
360
361 void Parser::HandlePragmaVisibility() {
362   assert(Tok.is(tok::annot_pragma_vis));
363   const IdentifierInfo *VisType =
364     static_cast<IdentifierInfo *>(Tok.getAnnotationValue());
365   SourceLocation VisLoc = ConsumeToken();
366   Actions.ActOnPragmaVisibility(VisType, VisLoc);
367 }
368
369 namespace {
370 struct PragmaPackInfo {
371   Sema::PragmaMsStackAction Action;
372   StringRef SlotLabel;
373   Token Alignment;
374 };
375 } // end anonymous namespace
376
377 void Parser::HandlePragmaPack() {
378   assert(Tok.is(tok::annot_pragma_pack));
379   PragmaPackInfo *Info =
380     static_cast<PragmaPackInfo *>(Tok.getAnnotationValue());
381   SourceLocation PragmaLoc = ConsumeToken();
382   ExprResult Alignment;
383   if (Info->Alignment.is(tok::numeric_constant)) {
384     Alignment = Actions.ActOnNumericConstant(Info->Alignment);
385     if (Alignment.isInvalid())
386       return;
387   }
388   Actions.ActOnPragmaPack(PragmaLoc, Info->Action, Info->SlotLabel,
389                           Alignment.get());
390 }
391
392 void Parser::HandlePragmaMSStruct() {
393   assert(Tok.is(tok::annot_pragma_msstruct));
394   PragmaMSStructKind Kind = static_cast<PragmaMSStructKind>(
395       reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
396   Actions.ActOnPragmaMSStruct(Kind);
397   ConsumeToken(); // The annotation token.
398 }
399
400 void Parser::HandlePragmaAlign() {
401   assert(Tok.is(tok::annot_pragma_align));
402   Sema::PragmaOptionsAlignKind Kind =
403     static_cast<Sema::PragmaOptionsAlignKind>(
404     reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
405   SourceLocation PragmaLoc = ConsumeToken();
406   Actions.ActOnPragmaOptionsAlign(Kind, PragmaLoc);
407 }
408
409 void Parser::HandlePragmaDump() {
410   assert(Tok.is(tok::annot_pragma_dump));
411   IdentifierInfo *II =
412       reinterpret_cast<IdentifierInfo *>(Tok.getAnnotationValue());
413   Actions.ActOnPragmaDump(getCurScope(), Tok.getLocation(), II);
414   ConsumeToken();
415 }
416
417 void Parser::HandlePragmaWeak() {
418   assert(Tok.is(tok::annot_pragma_weak));
419   SourceLocation PragmaLoc = ConsumeToken();
420   Actions.ActOnPragmaWeakID(Tok.getIdentifierInfo(), PragmaLoc,
421                             Tok.getLocation());
422   ConsumeToken(); // The weak name.
423 }
424
425 void Parser::HandlePragmaWeakAlias() {
426   assert(Tok.is(tok::annot_pragma_weakalias));
427   SourceLocation PragmaLoc = ConsumeToken();
428   IdentifierInfo *WeakName = Tok.getIdentifierInfo();
429   SourceLocation WeakNameLoc = Tok.getLocation();
430   ConsumeToken();
431   IdentifierInfo *AliasName = Tok.getIdentifierInfo();
432   SourceLocation AliasNameLoc = Tok.getLocation();
433   ConsumeToken();
434   Actions.ActOnPragmaWeakAlias(WeakName, AliasName, PragmaLoc,
435                                WeakNameLoc, AliasNameLoc);
436
437 }
438
439 void Parser::HandlePragmaRedefineExtname() {
440   assert(Tok.is(tok::annot_pragma_redefine_extname));
441   SourceLocation RedefLoc = ConsumeToken();
442   IdentifierInfo *RedefName = Tok.getIdentifierInfo();
443   SourceLocation RedefNameLoc = Tok.getLocation();
444   ConsumeToken();
445   IdentifierInfo *AliasName = Tok.getIdentifierInfo();
446   SourceLocation AliasNameLoc = Tok.getLocation();
447   ConsumeToken();
448   Actions.ActOnPragmaRedefineExtname(RedefName, AliasName, RedefLoc,
449                                      RedefNameLoc, AliasNameLoc);
450 }
451
452 void Parser::HandlePragmaFPContract() {
453   assert(Tok.is(tok::annot_pragma_fp_contract));
454   tok::OnOffSwitch OOS =
455     static_cast<tok::OnOffSwitch>(
456     reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
457   Actions.ActOnPragmaFPContract(OOS);
458   ConsumeToken(); // The annotation token.
459 }
460
461 StmtResult Parser::HandlePragmaCaptured()
462 {
463   assert(Tok.is(tok::annot_pragma_captured));
464   ConsumeToken();
465
466   if (Tok.isNot(tok::l_brace)) {
467     PP.Diag(Tok, diag::err_expected) << tok::l_brace;
468     return StmtError();
469   }
470
471   SourceLocation Loc = Tok.getLocation();
472
473   ParseScope CapturedRegionScope(this, Scope::FnScope | Scope::DeclScope);
474   Actions.ActOnCapturedRegionStart(Loc, getCurScope(), CR_Default,
475                                    /*NumParams=*/1);
476
477   StmtResult R = ParseCompoundStatement();
478   CapturedRegionScope.Exit();
479
480   if (R.isInvalid()) {
481     Actions.ActOnCapturedRegionError();
482     return StmtError();
483   }
484
485   return Actions.ActOnCapturedRegionEnd(R.get());
486 }
487
488 namespace {
489   enum OpenCLExtState : char {
490     Disable, Enable, Begin, End
491   };
492   typedef std::pair<const IdentifierInfo *, OpenCLExtState> OpenCLExtData;
493 }
494
495 void Parser::HandlePragmaOpenCLExtension() {
496   assert(Tok.is(tok::annot_pragma_opencl_extension));
497   OpenCLExtData *Data = static_cast<OpenCLExtData*>(Tok.getAnnotationValue());
498   auto State = Data->second;
499   auto Ident = Data->first;
500   SourceLocation NameLoc = Tok.getLocation();
501   ConsumeToken(); // The annotation token.
502
503   auto &Opt = Actions.getOpenCLOptions();
504   auto Name = Ident->getName();
505   // OpenCL 1.1 9.1: "The all variant sets the behavior for all extensions,
506   // overriding all previously issued extension directives, but only if the
507   // behavior is set to disable."
508   if (Name == "all") {
509     if (State == Disable)
510       Opt.disableAll();
511     else
512       PP.Diag(NameLoc, diag::warn_pragma_expected_predicate) << 1;
513   } else if (State == Begin) {
514     if (!Opt.isKnown(Name) ||
515         !Opt.isSupported(Name, getLangOpts().OpenCLVersion)) {
516       Opt.support(Name);
517     }
518     Actions.setCurrentOpenCLExtension(Name);
519   } else if (State == End) {
520     if (Name != Actions.getCurrentOpenCLExtension())
521       PP.Diag(NameLoc, diag::warn_pragma_begin_end_mismatch);
522     Actions.setCurrentOpenCLExtension("");
523   } else if (!Opt.isKnown(Name))
524     PP.Diag(NameLoc, diag::warn_pragma_unknown_extension) << Ident;
525   else if (Opt.isSupportedExtension(Name, getLangOpts().OpenCLVersion))
526     Opt.enable(Name, State == Enable);
527   else if (Opt.isSupportedCore(Name, getLangOpts().OpenCLVersion))
528     PP.Diag(NameLoc, diag::warn_pragma_extension_is_core) << Ident;
529   else
530     PP.Diag(NameLoc, diag::warn_pragma_unsupported_extension) << Ident;
531 }
532
533 void Parser::HandlePragmaMSPointersToMembers() {
534   assert(Tok.is(tok::annot_pragma_ms_pointers_to_members));
535   LangOptions::PragmaMSPointersToMembersKind RepresentationMethod =
536       static_cast<LangOptions::PragmaMSPointersToMembersKind>(
537           reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
538   SourceLocation PragmaLoc = ConsumeToken(); // The annotation token.
539   Actions.ActOnPragmaMSPointersToMembers(RepresentationMethod, PragmaLoc);
540 }
541
542 void Parser::HandlePragmaMSVtorDisp() {
543   assert(Tok.is(tok::annot_pragma_ms_vtordisp));
544   uintptr_t Value = reinterpret_cast<uintptr_t>(Tok.getAnnotationValue());
545   Sema::PragmaMsStackAction Action =
546       static_cast<Sema::PragmaMsStackAction>((Value >> 16) & 0xFFFF);
547   MSVtorDispAttr::Mode Mode = MSVtorDispAttr::Mode(Value & 0xFFFF);
548   SourceLocation PragmaLoc = ConsumeToken(); // The annotation token.
549   Actions.ActOnPragmaMSVtorDisp(Action, PragmaLoc, Mode);
550 }
551
552 void Parser::HandlePragmaMSPragma() {
553   assert(Tok.is(tok::annot_pragma_ms_pragma));
554   // Grab the tokens out of the annotation and enter them into the stream.
555   auto TheTokens =
556       (std::pair<std::unique_ptr<Token[]>, size_t> *)Tok.getAnnotationValue();
557   PP.EnterTokenStream(std::move(TheTokens->first), TheTokens->second, true);
558   SourceLocation PragmaLocation = ConsumeToken(); // The annotation token.
559   assert(Tok.isAnyIdentifier());
560   StringRef PragmaName = Tok.getIdentifierInfo()->getName();
561   PP.Lex(Tok); // pragma kind
562
563   // Figure out which #pragma we're dealing with.  The switch has no default
564   // because lex shouldn't emit the annotation token for unrecognized pragmas.
565   typedef bool (Parser::*PragmaHandler)(StringRef, SourceLocation);
566   PragmaHandler Handler = llvm::StringSwitch<PragmaHandler>(PragmaName)
567     .Case("data_seg", &Parser::HandlePragmaMSSegment)
568     .Case("bss_seg", &Parser::HandlePragmaMSSegment)
569     .Case("const_seg", &Parser::HandlePragmaMSSegment)
570     .Case("code_seg", &Parser::HandlePragmaMSSegment)
571     .Case("section", &Parser::HandlePragmaMSSection)
572     .Case("init_seg", &Parser::HandlePragmaMSInitSeg);
573
574   if (!(this->*Handler)(PragmaName, PragmaLocation)) {
575     // Pragma handling failed, and has been diagnosed.  Slurp up the tokens
576     // until eof (really end of line) to prevent follow-on errors.
577     while (Tok.isNot(tok::eof))
578       PP.Lex(Tok);
579     PP.Lex(Tok);
580   }
581 }
582
583 bool Parser::HandlePragmaMSSection(StringRef PragmaName,
584                                    SourceLocation PragmaLocation) {
585   if (Tok.isNot(tok::l_paren)) {
586     PP.Diag(PragmaLocation, diag::warn_pragma_expected_lparen) << PragmaName;
587     return false;
588   }
589   PP.Lex(Tok); // (
590   // Parsing code for pragma section
591   if (Tok.isNot(tok::string_literal)) {
592     PP.Diag(PragmaLocation, diag::warn_pragma_expected_section_name)
593         << PragmaName;
594     return false;
595   }
596   ExprResult StringResult = ParseStringLiteralExpression();
597   if (StringResult.isInvalid())
598     return false; // Already diagnosed.
599   StringLiteral *SegmentName = cast<StringLiteral>(StringResult.get());
600   if (SegmentName->getCharByteWidth() != 1) {
601     PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
602         << PragmaName;
603     return false;
604   }
605   int SectionFlags = ASTContext::PSF_Read;
606   bool SectionFlagsAreDefault = true;
607   while (Tok.is(tok::comma)) {
608     PP.Lex(Tok); // ,
609     // Ignore "long" and "short".
610     // They are undocumented, but widely used, section attributes which appear
611     // to do nothing.
612     if (Tok.is(tok::kw_long) || Tok.is(tok::kw_short)) {
613       PP.Lex(Tok); // long/short
614       continue;
615     }
616
617     if (!Tok.isAnyIdentifier()) {
618       PP.Diag(PragmaLocation, diag::warn_pragma_expected_action_or_r_paren)
619           << PragmaName;
620       return false;
621     }
622     ASTContext::PragmaSectionFlag Flag =
623       llvm::StringSwitch<ASTContext::PragmaSectionFlag>(
624       Tok.getIdentifierInfo()->getName())
625       .Case("read", ASTContext::PSF_Read)
626       .Case("write", ASTContext::PSF_Write)
627       .Case("execute", ASTContext::PSF_Execute)
628       .Case("shared", ASTContext::PSF_Invalid)
629       .Case("nopage", ASTContext::PSF_Invalid)
630       .Case("nocache", ASTContext::PSF_Invalid)
631       .Case("discard", ASTContext::PSF_Invalid)
632       .Case("remove", ASTContext::PSF_Invalid)
633       .Default(ASTContext::PSF_None);
634     if (Flag == ASTContext::PSF_None || Flag == ASTContext::PSF_Invalid) {
635       PP.Diag(PragmaLocation, Flag == ASTContext::PSF_None
636                                   ? diag::warn_pragma_invalid_specific_action
637                                   : diag::warn_pragma_unsupported_action)
638           << PragmaName << Tok.getIdentifierInfo()->getName();
639       return false;
640     }
641     SectionFlags |= Flag;
642     SectionFlagsAreDefault = false;
643     PP.Lex(Tok); // Identifier
644   }
645   // If no section attributes are specified, the section will be marked as
646   // read/write.
647   if (SectionFlagsAreDefault)
648     SectionFlags |= ASTContext::PSF_Write;
649   if (Tok.isNot(tok::r_paren)) {
650     PP.Diag(PragmaLocation, diag::warn_pragma_expected_rparen) << PragmaName;
651     return false;
652   }
653   PP.Lex(Tok); // )
654   if (Tok.isNot(tok::eof)) {
655     PP.Diag(PragmaLocation, diag::warn_pragma_extra_tokens_at_eol)
656         << PragmaName;
657     return false;
658   }
659   PP.Lex(Tok); // eof
660   Actions.ActOnPragmaMSSection(PragmaLocation, SectionFlags, SegmentName);
661   return true;
662 }
663
664 bool Parser::HandlePragmaMSSegment(StringRef PragmaName,
665                                    SourceLocation PragmaLocation) {
666   if (Tok.isNot(tok::l_paren)) {
667     PP.Diag(PragmaLocation, diag::warn_pragma_expected_lparen) << PragmaName;
668     return false;
669   }
670   PP.Lex(Tok); // (
671   Sema::PragmaMsStackAction Action = Sema::PSK_Reset;
672   StringRef SlotLabel;
673   if (Tok.isAnyIdentifier()) {
674     StringRef PushPop = Tok.getIdentifierInfo()->getName();
675     if (PushPop == "push")
676       Action = Sema::PSK_Push;
677     else if (PushPop == "pop")
678       Action = Sema::PSK_Pop;
679     else {
680       PP.Diag(PragmaLocation,
681               diag::warn_pragma_expected_section_push_pop_or_name)
682           << PragmaName;
683       return false;
684     }
685     if (Action != Sema::PSK_Reset) {
686       PP.Lex(Tok); // push | pop
687       if (Tok.is(tok::comma)) {
688         PP.Lex(Tok); // ,
689         // If we've got a comma, we either need a label or a string.
690         if (Tok.isAnyIdentifier()) {
691           SlotLabel = Tok.getIdentifierInfo()->getName();
692           PP.Lex(Tok); // identifier
693           if (Tok.is(tok::comma))
694             PP.Lex(Tok);
695           else if (Tok.isNot(tok::r_paren)) {
696             PP.Diag(PragmaLocation, diag::warn_pragma_expected_punc)
697                 << PragmaName;
698             return false;
699           }
700         }
701       } else if (Tok.isNot(tok::r_paren)) {
702         PP.Diag(PragmaLocation, diag::warn_pragma_expected_punc) << PragmaName;
703         return false;
704       }
705     }
706   }
707   // Grab the string literal for our section name.
708   StringLiteral *SegmentName = nullptr;
709   if (Tok.isNot(tok::r_paren)) {
710     if (Tok.isNot(tok::string_literal)) {
711       unsigned DiagID = Action != Sema::PSK_Reset ? !SlotLabel.empty() ?
712           diag::warn_pragma_expected_section_name :
713           diag::warn_pragma_expected_section_label_or_name :
714           diag::warn_pragma_expected_section_push_pop_or_name;
715       PP.Diag(PragmaLocation, DiagID) << PragmaName;
716       return false;
717     }
718     ExprResult StringResult = ParseStringLiteralExpression();
719     if (StringResult.isInvalid())
720       return false; // Already diagnosed.
721     SegmentName = cast<StringLiteral>(StringResult.get());
722     if (SegmentName->getCharByteWidth() != 1) {
723       PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
724           << PragmaName;
725       return false;
726     }
727     // Setting section "" has no effect
728     if (SegmentName->getLength())
729       Action = (Sema::PragmaMsStackAction)(Action | Sema::PSK_Set);
730   }
731   if (Tok.isNot(tok::r_paren)) {
732     PP.Diag(PragmaLocation, diag::warn_pragma_expected_rparen) << PragmaName;
733     return false;
734   }
735   PP.Lex(Tok); // )
736   if (Tok.isNot(tok::eof)) {
737     PP.Diag(PragmaLocation, diag::warn_pragma_extra_tokens_at_eol)
738         << PragmaName;
739     return false;
740   }
741   PP.Lex(Tok); // eof
742   Actions.ActOnPragmaMSSeg(PragmaLocation, Action, SlotLabel,
743                            SegmentName, PragmaName);
744   return true;
745 }
746
747 // #pragma init_seg({ compiler | lib | user | "section-name" [, func-name]} )
748 bool Parser::HandlePragmaMSInitSeg(StringRef PragmaName,
749                                    SourceLocation PragmaLocation) {
750   if (getTargetInfo().getTriple().getEnvironment() != llvm::Triple::MSVC) {
751     PP.Diag(PragmaLocation, diag::warn_pragma_init_seg_unsupported_target);
752     return false;
753   }
754
755   if (ExpectAndConsume(tok::l_paren, diag::warn_pragma_expected_lparen,
756                        PragmaName))
757     return false;
758
759   // Parse either the known section names or the string section name.
760   StringLiteral *SegmentName = nullptr;
761   if (Tok.isAnyIdentifier()) {
762     auto *II = Tok.getIdentifierInfo();
763     StringRef Section = llvm::StringSwitch<StringRef>(II->getName())
764                             .Case("compiler", "\".CRT$XCC\"")
765                             .Case("lib", "\".CRT$XCL\"")
766                             .Case("user", "\".CRT$XCU\"")
767                             .Default("");
768
769     if (!Section.empty()) {
770       // Pretend the user wrote the appropriate string literal here.
771       Token Toks[1];
772       Toks[0].startToken();
773       Toks[0].setKind(tok::string_literal);
774       Toks[0].setLocation(Tok.getLocation());
775       Toks[0].setLiteralData(Section.data());
776       Toks[0].setLength(Section.size());
777       SegmentName =
778           cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
779       PP.Lex(Tok);
780     }
781   } else if (Tok.is(tok::string_literal)) {
782     ExprResult StringResult = ParseStringLiteralExpression();
783     if (StringResult.isInvalid())
784       return false;
785     SegmentName = cast<StringLiteral>(StringResult.get());
786     if (SegmentName->getCharByteWidth() != 1) {
787       PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
788           << PragmaName;
789       return false;
790     }
791     // FIXME: Add support for the '[, func-name]' part of the pragma.
792   }
793
794   if (!SegmentName) {
795     PP.Diag(PragmaLocation, diag::warn_pragma_expected_init_seg) << PragmaName;
796     return false;
797   }
798
799   if (ExpectAndConsume(tok::r_paren, diag::warn_pragma_expected_rparen,
800                        PragmaName) ||
801       ExpectAndConsume(tok::eof, diag::warn_pragma_extra_tokens_at_eol,
802                        PragmaName))
803     return false;
804
805   Actions.ActOnPragmaMSInitSeg(PragmaLocation, SegmentName);
806   return true;
807 }
808
809 namespace {
810 struct PragmaLoopHintInfo {
811   Token PragmaName;
812   Token Option;
813   ArrayRef<Token> Toks;
814 };
815 } // end anonymous namespace
816
817 static std::string PragmaLoopHintString(Token PragmaName, Token Option) {
818   std::string PragmaString;
819   if (PragmaName.getIdentifierInfo()->getName() == "loop") {
820     PragmaString = "clang loop ";
821     PragmaString += Option.getIdentifierInfo()->getName();
822   } else {
823     assert(PragmaName.getIdentifierInfo()->getName() == "unroll" &&
824            "Unexpected pragma name");
825     PragmaString = "unroll";
826   }
827   return PragmaString;
828 }
829
830 bool Parser::HandlePragmaLoopHint(LoopHint &Hint) {
831   assert(Tok.is(tok::annot_pragma_loop_hint));
832   PragmaLoopHintInfo *Info =
833       static_cast<PragmaLoopHintInfo *>(Tok.getAnnotationValue());
834
835   IdentifierInfo *PragmaNameInfo = Info->PragmaName.getIdentifierInfo();
836   Hint.PragmaNameLoc = IdentifierLoc::create(
837       Actions.Context, Info->PragmaName.getLocation(), PragmaNameInfo);
838
839   // It is possible that the loop hint has no option identifier, such as
840   // #pragma unroll(4).
841   IdentifierInfo *OptionInfo = Info->Option.is(tok::identifier)
842                                    ? Info->Option.getIdentifierInfo()
843                                    : nullptr;
844   Hint.OptionLoc = IdentifierLoc::create(
845       Actions.Context, Info->Option.getLocation(), OptionInfo);
846
847   llvm::ArrayRef<Token> Toks = Info->Toks;
848
849   // Return a valid hint if pragma unroll or nounroll were specified
850   // without an argument.
851   bool PragmaUnroll = PragmaNameInfo->getName() == "unroll";
852   bool PragmaNoUnroll = PragmaNameInfo->getName() == "nounroll";
853   if (Toks.empty() && (PragmaUnroll || PragmaNoUnroll)) {
854     ConsumeToken(); // The annotation token.
855     Hint.Range = Info->PragmaName.getLocation();
856     return true;
857   }
858
859   // The constant expression is always followed by an eof token, which increases
860   // the TokSize by 1.
861   assert(!Toks.empty() &&
862          "PragmaLoopHintInfo::Toks must contain at least one token.");
863
864   // If no option is specified the argument is assumed to be a constant expr.
865   bool OptionUnroll = false;
866   bool OptionDistribute = false;
867   bool StateOption = false;
868   if (OptionInfo) { // Pragma Unroll does not specify an option.
869     OptionUnroll = OptionInfo->isStr("unroll");
870     OptionDistribute = OptionInfo->isStr("distribute");
871     StateOption = llvm::StringSwitch<bool>(OptionInfo->getName())
872                       .Case("vectorize", true)
873                       .Case("interleave", true)
874                       .Default(false) ||
875                   OptionUnroll || OptionDistribute;
876   }
877
878   bool AssumeSafetyArg = !OptionUnroll && !OptionDistribute;
879   // Verify loop hint has an argument.
880   if (Toks[0].is(tok::eof)) {
881     ConsumeToken(); // The annotation token.
882     Diag(Toks[0].getLocation(), diag::err_pragma_loop_missing_argument)
883         << /*StateArgument=*/StateOption << /*FullKeyword=*/OptionUnroll
884         << /*AssumeSafetyKeyword=*/AssumeSafetyArg;
885     return false;
886   }
887
888   // Validate the argument.
889   if (StateOption) {
890     ConsumeToken(); // The annotation token.
891     SourceLocation StateLoc = Toks[0].getLocation();
892     IdentifierInfo *StateInfo = Toks[0].getIdentifierInfo();
893
894     bool Valid = StateInfo &&
895                  llvm::StringSwitch<bool>(StateInfo->getName())
896                      .Cases("enable", "disable", true)
897                      .Case("full", OptionUnroll)
898                      .Case("assume_safety", AssumeSafetyArg)
899                      .Default(false);
900     if (!Valid) {
901       Diag(Toks[0].getLocation(), diag::err_pragma_invalid_keyword)
902           << /*FullKeyword=*/OptionUnroll
903           << /*AssumeSafetyKeyword=*/AssumeSafetyArg;
904       return false;
905     }
906     if (Toks.size() > 2)
907       Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
908           << PragmaLoopHintString(Info->PragmaName, Info->Option);
909     Hint.StateLoc = IdentifierLoc::create(Actions.Context, StateLoc, StateInfo);
910   } else {
911     // Enter constant expression including eof terminator into token stream.
912     PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/false);
913     ConsumeToken(); // The annotation token.
914
915     ExprResult R = ParseConstantExpression();
916
917     // Tokens following an error in an ill-formed constant expression will
918     // remain in the token stream and must be removed.
919     if (Tok.isNot(tok::eof)) {
920       Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
921           << PragmaLoopHintString(Info->PragmaName, Info->Option);
922       while (Tok.isNot(tok::eof))
923         ConsumeAnyToken();
924     }
925
926     ConsumeToken(); // Consume the constant expression eof terminator.
927
928     if (R.isInvalid() ||
929         Actions.CheckLoopHintExpr(R.get(), Toks[0].getLocation()))
930       return false;
931
932     // Argument is a constant expression with an integer type.
933     Hint.ValueExpr = R.get();
934   }
935
936   Hint.Range = SourceRange(Info->PragmaName.getLocation(),
937                            Info->Toks.back().getLocation());
938   return true;
939 }
940
941 // #pragma GCC visibility comes in two variants:
942 //   'push' '(' [visibility] ')'
943 //   'pop'
944 void PragmaGCCVisibilityHandler::HandlePragma(Preprocessor &PP, 
945                                               PragmaIntroducerKind Introducer,
946                                               Token &VisTok) {
947   SourceLocation VisLoc = VisTok.getLocation();
948
949   Token Tok;
950   PP.LexUnexpandedToken(Tok);
951
952   const IdentifierInfo *PushPop = Tok.getIdentifierInfo();
953
954   const IdentifierInfo *VisType;
955   if (PushPop && PushPop->isStr("pop")) {
956     VisType = nullptr;
957   } else if (PushPop && PushPop->isStr("push")) {
958     PP.LexUnexpandedToken(Tok);
959     if (Tok.isNot(tok::l_paren)) {
960       PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen)
961         << "visibility";
962       return;
963     }
964     PP.LexUnexpandedToken(Tok);
965     VisType = Tok.getIdentifierInfo();
966     if (!VisType) {
967       PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
968         << "visibility";
969       return;
970     }
971     PP.LexUnexpandedToken(Tok);
972     if (Tok.isNot(tok::r_paren)) {
973       PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen)
974         << "visibility";
975       return;
976     }
977   } else {
978     PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
979       << "visibility";
980     return;
981   }
982   SourceLocation EndLoc = Tok.getLocation();
983   PP.LexUnexpandedToken(Tok);
984   if (Tok.isNot(tok::eod)) {
985     PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
986       << "visibility";
987     return;
988   }
989
990   auto Toks = llvm::make_unique<Token[]>(1);
991   Toks[0].startToken();
992   Toks[0].setKind(tok::annot_pragma_vis);
993   Toks[0].setLocation(VisLoc);
994   Toks[0].setAnnotationEndLoc(EndLoc);
995   Toks[0].setAnnotationValue(
996                           const_cast<void*>(static_cast<const void*>(VisType)));
997   PP.EnterTokenStream(std::move(Toks), 1, /*DisableMacroExpansion=*/true);
998 }
999
1000 // #pragma pack(...) comes in the following delicious flavors:
1001 //   pack '(' [integer] ')'
1002 //   pack '(' 'show' ')'
1003 //   pack '(' ('push' | 'pop') [',' identifier] [, integer] ')'
1004 void PragmaPackHandler::HandlePragma(Preprocessor &PP, 
1005                                      PragmaIntroducerKind Introducer,
1006                                      Token &PackTok) {
1007   SourceLocation PackLoc = PackTok.getLocation();
1008
1009   Token Tok;
1010   PP.Lex(Tok);
1011   if (Tok.isNot(tok::l_paren)) {
1012     PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "pack";
1013     return;
1014   }
1015
1016   Sema::PragmaMsStackAction Action = Sema::PSK_Reset;
1017   StringRef SlotLabel;
1018   Token Alignment;
1019   Alignment.startToken();
1020   PP.Lex(Tok);
1021   if (Tok.is(tok::numeric_constant)) {
1022     Alignment = Tok;
1023
1024     PP.Lex(Tok);
1025
1026     // In MSVC/gcc, #pragma pack(4) sets the alignment without affecting
1027     // the push/pop stack.
1028     // In Apple gcc, #pragma pack(4) is equivalent to #pragma pack(push, 4)
1029     Action =
1030         PP.getLangOpts().ApplePragmaPack ? Sema::PSK_Push_Set : Sema::PSK_Set;
1031   } else if (Tok.is(tok::identifier)) {
1032     const IdentifierInfo *II = Tok.getIdentifierInfo();
1033     if (II->isStr("show")) {
1034       Action = Sema::PSK_Show;
1035       PP.Lex(Tok);
1036     } else {
1037       if (II->isStr("push")) {
1038         Action = Sema::PSK_Push;
1039       } else if (II->isStr("pop")) {
1040         Action = Sema::PSK_Pop;
1041       } else {
1042         PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_action) << "pack";
1043         return;
1044       }
1045       PP.Lex(Tok);
1046
1047       if (Tok.is(tok::comma)) {
1048         PP.Lex(Tok);
1049
1050         if (Tok.is(tok::numeric_constant)) {
1051           Action = (Sema::PragmaMsStackAction)(Action | Sema::PSK_Set);
1052           Alignment = Tok;
1053
1054           PP.Lex(Tok);
1055         } else if (Tok.is(tok::identifier)) {
1056           SlotLabel = Tok.getIdentifierInfo()->getName();
1057           PP.Lex(Tok);
1058
1059           if (Tok.is(tok::comma)) {
1060             PP.Lex(Tok);
1061
1062             if (Tok.isNot(tok::numeric_constant)) {
1063               PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_malformed);
1064               return;
1065             }
1066
1067             Action = (Sema::PragmaMsStackAction)(Action | Sema::PSK_Set);
1068             Alignment = Tok;
1069
1070             PP.Lex(Tok);
1071           }
1072         } else {
1073           PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_malformed);
1074           return;
1075         }
1076       }
1077     }
1078   } else if (PP.getLangOpts().ApplePragmaPack) {
1079     // In MSVC/gcc, #pragma pack() resets the alignment without affecting
1080     // the push/pop stack.
1081     // In Apple gcc #pragma pack() is equivalent to #pragma pack(pop).
1082     Action = Sema::PSK_Pop;
1083   }
1084
1085   if (Tok.isNot(tok::r_paren)) {
1086     PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen) << "pack";
1087     return;
1088   }
1089
1090   SourceLocation RParenLoc = Tok.getLocation();
1091   PP.Lex(Tok);
1092   if (Tok.isNot(tok::eod)) {
1093     PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "pack";
1094     return;
1095   }
1096
1097   PragmaPackInfo *Info =
1098       PP.getPreprocessorAllocator().Allocate<PragmaPackInfo>(1);
1099   Info->Action = Action;
1100   Info->SlotLabel = SlotLabel;
1101   Info->Alignment = Alignment;
1102
1103   MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
1104                               1);
1105   Toks[0].startToken();
1106   Toks[0].setKind(tok::annot_pragma_pack);
1107   Toks[0].setLocation(PackLoc);
1108   Toks[0].setAnnotationEndLoc(RParenLoc);
1109   Toks[0].setAnnotationValue(static_cast<void*>(Info));
1110   PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
1111 }
1112
1113 // #pragma ms_struct on
1114 // #pragma ms_struct off
1115 void PragmaMSStructHandler::HandlePragma(Preprocessor &PP, 
1116                                          PragmaIntroducerKind Introducer,
1117                                          Token &MSStructTok) {
1118   PragmaMSStructKind Kind = PMSST_OFF;
1119
1120   Token Tok;
1121   PP.Lex(Tok);
1122   if (Tok.isNot(tok::identifier)) {
1123     PP.Diag(Tok.getLocation(), diag::warn_pragma_ms_struct);
1124     return;
1125   }
1126   SourceLocation EndLoc = Tok.getLocation();
1127   const IdentifierInfo *II = Tok.getIdentifierInfo();
1128   if (II->isStr("on")) {
1129     Kind = PMSST_ON;
1130     PP.Lex(Tok);
1131   }
1132   else if (II->isStr("off") || II->isStr("reset"))
1133     PP.Lex(Tok);
1134   else {
1135     PP.Diag(Tok.getLocation(), diag::warn_pragma_ms_struct);
1136     return;
1137   }
1138   
1139   if (Tok.isNot(tok::eod)) {
1140     PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1141       << "ms_struct";
1142     return;
1143   }
1144
1145   MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
1146                               1);
1147   Toks[0].startToken();
1148   Toks[0].setKind(tok::annot_pragma_msstruct);
1149   Toks[0].setLocation(MSStructTok.getLocation());
1150   Toks[0].setAnnotationEndLoc(EndLoc);
1151   Toks[0].setAnnotationValue(reinterpret_cast<void*>(
1152                              static_cast<uintptr_t>(Kind)));
1153   PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
1154 }
1155
1156 // #pragma 'align' '=' {'native','natural','mac68k','power','reset'}
1157 // #pragma 'options 'align' '=' {'native','natural','mac68k','power','reset'}
1158 static void ParseAlignPragma(Preprocessor &PP, Token &FirstTok,
1159                              bool IsOptions) {
1160   Token Tok;
1161
1162   if (IsOptions) {
1163     PP.Lex(Tok);
1164     if (Tok.isNot(tok::identifier) ||
1165         !Tok.getIdentifierInfo()->isStr("align")) {
1166       PP.Diag(Tok.getLocation(), diag::warn_pragma_options_expected_align);
1167       return;
1168     }
1169   }
1170
1171   PP.Lex(Tok);
1172   if (Tok.isNot(tok::equal)) {
1173     PP.Diag(Tok.getLocation(), diag::warn_pragma_align_expected_equal)
1174       << IsOptions;
1175     return;
1176   }
1177
1178   PP.Lex(Tok);
1179   if (Tok.isNot(tok::identifier)) {
1180     PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
1181       << (IsOptions ? "options" : "align");
1182     return;
1183   }
1184
1185   Sema::PragmaOptionsAlignKind Kind = Sema::POAK_Natural;
1186   const IdentifierInfo *II = Tok.getIdentifierInfo();
1187   if (II->isStr("native"))
1188     Kind = Sema::POAK_Native;
1189   else if (II->isStr("natural"))
1190     Kind = Sema::POAK_Natural;
1191   else if (II->isStr("packed"))
1192     Kind = Sema::POAK_Packed;
1193   else if (II->isStr("power"))
1194     Kind = Sema::POAK_Power;
1195   else if (II->isStr("mac68k"))
1196     Kind = Sema::POAK_Mac68k;
1197   else if (II->isStr("reset"))
1198     Kind = Sema::POAK_Reset;
1199   else {
1200     PP.Diag(Tok.getLocation(), diag::warn_pragma_align_invalid_option)
1201       << IsOptions;
1202     return;
1203   }
1204
1205   SourceLocation EndLoc = Tok.getLocation();
1206   PP.Lex(Tok);
1207   if (Tok.isNot(tok::eod)) {
1208     PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1209       << (IsOptions ? "options" : "align");
1210     return;
1211   }
1212
1213   MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
1214                               1);
1215   Toks[0].startToken();
1216   Toks[0].setKind(tok::annot_pragma_align);
1217   Toks[0].setLocation(FirstTok.getLocation());
1218   Toks[0].setAnnotationEndLoc(EndLoc);
1219   Toks[0].setAnnotationValue(reinterpret_cast<void*>(
1220                              static_cast<uintptr_t>(Kind)));
1221   PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
1222 }
1223
1224 void PragmaAlignHandler::HandlePragma(Preprocessor &PP, 
1225                                       PragmaIntroducerKind Introducer,
1226                                       Token &AlignTok) {
1227   ParseAlignPragma(PP, AlignTok, /*IsOptions=*/false);
1228 }
1229
1230 void PragmaOptionsHandler::HandlePragma(Preprocessor &PP, 
1231                                         PragmaIntroducerKind Introducer,
1232                                         Token &OptionsTok) {
1233   ParseAlignPragma(PP, OptionsTok, /*IsOptions=*/true);
1234 }
1235
1236 // #pragma unused(identifier)
1237 void PragmaUnusedHandler::HandlePragma(Preprocessor &PP, 
1238                                        PragmaIntroducerKind Introducer,
1239                                        Token &UnusedTok) {
1240   // FIXME: Should we be expanding macros here? My guess is no.
1241   SourceLocation UnusedLoc = UnusedTok.getLocation();
1242
1243   // Lex the left '('.
1244   Token Tok;
1245   PP.Lex(Tok);
1246   if (Tok.isNot(tok::l_paren)) {
1247     PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "unused";
1248     return;
1249   }
1250
1251   // Lex the declaration reference(s).
1252   SmallVector<Token, 5> Identifiers;
1253   SourceLocation RParenLoc;
1254   bool LexID = true;
1255
1256   while (true) {
1257     PP.Lex(Tok);
1258
1259     if (LexID) {
1260       if (Tok.is(tok::identifier)) {
1261         Identifiers.push_back(Tok);
1262         LexID = false;
1263         continue;
1264       }
1265
1266       // Illegal token!
1267       PP.Diag(Tok.getLocation(), diag::warn_pragma_unused_expected_var);
1268       return;
1269     }
1270
1271     // We are execting a ')' or a ','.
1272     if (Tok.is(tok::comma)) {
1273       LexID = true;
1274       continue;
1275     }
1276
1277     if (Tok.is(tok::r_paren)) {
1278       RParenLoc = Tok.getLocation();
1279       break;
1280     }
1281
1282     // Illegal token!
1283     PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_punc) << "unused";
1284     return;
1285   }
1286
1287   PP.Lex(Tok);
1288   if (Tok.isNot(tok::eod)) {
1289     PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
1290         "unused";
1291     return;
1292   }
1293
1294   // Verify that we have a location for the right parenthesis.
1295   assert(RParenLoc.isValid() && "Valid '#pragma unused' must have ')'");
1296   assert(!Identifiers.empty() && "Valid '#pragma unused' must have arguments");
1297
1298   // For each identifier token, insert into the token stream a
1299   // annot_pragma_unused token followed by the identifier token.
1300   // This allows us to cache a "#pragma unused" that occurs inside an inline
1301   // C++ member function.
1302
1303   MutableArrayRef<Token> Toks(
1304       PP.getPreprocessorAllocator().Allocate<Token>(2 * Identifiers.size()),
1305       2 * Identifiers.size());
1306   for (unsigned i=0; i != Identifiers.size(); i++) {
1307     Token &pragmaUnusedTok = Toks[2*i], &idTok = Toks[2*i+1];
1308     pragmaUnusedTok.startToken();
1309     pragmaUnusedTok.setKind(tok::annot_pragma_unused);
1310     pragmaUnusedTok.setLocation(UnusedLoc);
1311     idTok = Identifiers[i];
1312   }
1313   PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
1314 }
1315
1316 // #pragma weak identifier
1317 // #pragma weak identifier '=' identifier
1318 void PragmaWeakHandler::HandlePragma(Preprocessor &PP, 
1319                                      PragmaIntroducerKind Introducer,
1320                                      Token &WeakTok) {
1321   SourceLocation WeakLoc = WeakTok.getLocation();
1322
1323   Token Tok;
1324   PP.Lex(Tok);
1325   if (Tok.isNot(tok::identifier)) {
1326     PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) << "weak";
1327     return;
1328   }
1329
1330   Token WeakName = Tok;
1331   bool HasAlias = false;
1332   Token AliasName;
1333
1334   PP.Lex(Tok);
1335   if (Tok.is(tok::equal)) {
1336     HasAlias = true;
1337     PP.Lex(Tok);
1338     if (Tok.isNot(tok::identifier)) {
1339       PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
1340           << "weak";
1341       return;
1342     }
1343     AliasName = Tok;
1344     PP.Lex(Tok);
1345   }
1346
1347   if (Tok.isNot(tok::eod)) {
1348     PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "weak";
1349     return;
1350   }
1351
1352   if (HasAlias) {
1353     MutableArrayRef<Token> Toks(
1354         PP.getPreprocessorAllocator().Allocate<Token>(3), 3);
1355     Token &pragmaUnusedTok = Toks[0];
1356     pragmaUnusedTok.startToken();
1357     pragmaUnusedTok.setKind(tok::annot_pragma_weakalias);
1358     pragmaUnusedTok.setLocation(WeakLoc);
1359     pragmaUnusedTok.setAnnotationEndLoc(AliasName.getLocation());
1360     Toks[1] = WeakName;
1361     Toks[2] = AliasName;
1362     PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
1363   } else {
1364     MutableArrayRef<Token> Toks(
1365         PP.getPreprocessorAllocator().Allocate<Token>(2), 2);
1366     Token &pragmaUnusedTok = Toks[0];
1367     pragmaUnusedTok.startToken();
1368     pragmaUnusedTok.setKind(tok::annot_pragma_weak);
1369     pragmaUnusedTok.setLocation(WeakLoc);
1370     pragmaUnusedTok.setAnnotationEndLoc(WeakLoc);
1371     Toks[1] = WeakName;
1372     PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
1373   }
1374 }
1375
1376 // #pragma redefine_extname identifier identifier
1377 void PragmaRedefineExtnameHandler::HandlePragma(Preprocessor &PP, 
1378                                                PragmaIntroducerKind Introducer,
1379                                                 Token &RedefToken) {
1380   SourceLocation RedefLoc = RedefToken.getLocation();
1381
1382   Token Tok;
1383   PP.Lex(Tok);
1384   if (Tok.isNot(tok::identifier)) {
1385     PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) <<
1386       "redefine_extname";
1387     return;
1388   }
1389
1390   Token RedefName = Tok;
1391   PP.Lex(Tok);
1392
1393   if (Tok.isNot(tok::identifier)) {
1394     PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
1395         << "redefine_extname";
1396     return;
1397   }
1398
1399   Token AliasName = Tok;
1400   PP.Lex(Tok);
1401
1402   if (Tok.isNot(tok::eod)) {
1403     PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
1404       "redefine_extname";
1405     return;
1406   }
1407
1408   MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(3),
1409                               3);
1410   Token &pragmaRedefTok = Toks[0];
1411   pragmaRedefTok.startToken();
1412   pragmaRedefTok.setKind(tok::annot_pragma_redefine_extname);
1413   pragmaRedefTok.setLocation(RedefLoc);
1414   pragmaRedefTok.setAnnotationEndLoc(AliasName.getLocation());
1415   Toks[1] = RedefName;
1416   Toks[2] = AliasName;
1417   PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
1418 }
1419
1420
1421 void
1422 PragmaFPContractHandler::HandlePragma(Preprocessor &PP, 
1423                                       PragmaIntroducerKind Introducer,
1424                                       Token &Tok) {
1425   tok::OnOffSwitch OOS;
1426   if (PP.LexOnOffSwitch(OOS))
1427     return;
1428
1429   MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
1430                               1);
1431   Toks[0].startToken();
1432   Toks[0].setKind(tok::annot_pragma_fp_contract);
1433   Toks[0].setLocation(Tok.getLocation());
1434   Toks[0].setAnnotationEndLoc(Tok.getLocation());
1435   Toks[0].setAnnotationValue(reinterpret_cast<void*>(
1436                              static_cast<uintptr_t>(OOS)));
1437   PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
1438 }
1439
1440 void 
1441 PragmaOpenCLExtensionHandler::HandlePragma(Preprocessor &PP, 
1442                                            PragmaIntroducerKind Introducer,
1443                                            Token &Tok) {
1444   PP.LexUnexpandedToken(Tok);
1445   if (Tok.isNot(tok::identifier)) {
1446     PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) <<
1447       "OPENCL";
1448     return;
1449   }
1450   IdentifierInfo *Ext = Tok.getIdentifierInfo();
1451   SourceLocation NameLoc = Tok.getLocation();
1452
1453   PP.Lex(Tok);
1454   if (Tok.isNot(tok::colon)) {
1455     PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_colon) << Ext;
1456     return;
1457   }
1458
1459   PP.Lex(Tok);
1460   if (Tok.isNot(tok::identifier)) {
1461     PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_predicate) << 0;
1462     return;
1463   }
1464   IdentifierInfo *Pred = Tok.getIdentifierInfo();
1465
1466   OpenCLExtState State;
1467   if (Pred->isStr("enable")) {
1468     State = Enable;
1469   } else if (Pred->isStr("disable")) {
1470     State = Disable;
1471   } else if (Pred->isStr("begin"))
1472     State = Begin;
1473   else if (Pred->isStr("end"))
1474     State = End;
1475   else {
1476     PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_predicate)
1477       << Ext->isStr("all");
1478     return;
1479   }
1480   SourceLocation StateLoc = Tok.getLocation();
1481
1482   PP.Lex(Tok);
1483   if (Tok.isNot(tok::eod)) {
1484     PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
1485       "OPENCL EXTENSION";
1486     return;
1487   }
1488
1489   auto Info = PP.getPreprocessorAllocator().Allocate<OpenCLExtData>(1);
1490   Info->first = Ext;
1491   Info->second = State;
1492   MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
1493                               1);
1494   Toks[0].startToken();
1495   Toks[0].setKind(tok::annot_pragma_opencl_extension);
1496   Toks[0].setLocation(NameLoc);
1497   Toks[0].setAnnotationValue(static_cast<void*>(Info));
1498   Toks[0].setAnnotationEndLoc(StateLoc);
1499   PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
1500
1501   if (PP.getPPCallbacks())
1502     PP.getPPCallbacks()->PragmaOpenCLExtension(NameLoc, Ext, 
1503                                                StateLoc, State);
1504 }
1505
1506 /// \brief Handle '#pragma omp ...' when OpenMP is disabled.
1507 ///
1508 void
1509 PragmaNoOpenMPHandler::HandlePragma(Preprocessor &PP,
1510                                     PragmaIntroducerKind Introducer,
1511                                     Token &FirstTok) {
1512   if (!PP.getDiagnostics().isIgnored(diag::warn_pragma_omp_ignored,
1513                                      FirstTok.getLocation())) {
1514     PP.Diag(FirstTok, diag::warn_pragma_omp_ignored);
1515     PP.getDiagnostics().setSeverity(diag::warn_pragma_omp_ignored,
1516                                     diag::Severity::Ignored, SourceLocation());
1517   }
1518   PP.DiscardUntilEndOfDirective();
1519 }
1520
1521 /// \brief Handle '#pragma omp ...' when OpenMP is enabled.
1522 ///
1523 void
1524 PragmaOpenMPHandler::HandlePragma(Preprocessor &PP,
1525                                   PragmaIntroducerKind Introducer,
1526                                   Token &FirstTok) {
1527   SmallVector<Token, 16> Pragma;
1528   Token Tok;
1529   Tok.startToken();
1530   Tok.setKind(tok::annot_pragma_openmp);
1531   Tok.setLocation(FirstTok.getLocation());
1532
1533   while (Tok.isNot(tok::eod)) {
1534     Pragma.push_back(Tok);
1535     PP.Lex(Tok);
1536   }
1537   SourceLocation EodLoc = Tok.getLocation();
1538   Tok.startToken();
1539   Tok.setKind(tok::annot_pragma_openmp_end);
1540   Tok.setLocation(EodLoc);
1541   Pragma.push_back(Tok);
1542
1543   auto Toks = llvm::make_unique<Token[]>(Pragma.size());
1544   std::copy(Pragma.begin(), Pragma.end(), Toks.get());
1545   PP.EnterTokenStream(std::move(Toks), Pragma.size(),
1546                       /*DisableMacroExpansion=*/false);
1547 }
1548
1549 /// \brief Handle '#pragma pointers_to_members'
1550 // The grammar for this pragma is as follows:
1551 //
1552 // <inheritance model> ::= ('single' | 'multiple' | 'virtual') '_inheritance'
1553 //
1554 // #pragma pointers_to_members '(' 'best_case' ')'
1555 // #pragma pointers_to_members '(' 'full_generality' [',' inheritance-model] ')'
1556 // #pragma pointers_to_members '(' inheritance-model ')'
1557 void PragmaMSPointersToMembers::HandlePragma(Preprocessor &PP,
1558                                              PragmaIntroducerKind Introducer,
1559                                              Token &Tok) {
1560   SourceLocation PointersToMembersLoc = Tok.getLocation();
1561   PP.Lex(Tok);
1562   if (Tok.isNot(tok::l_paren)) {
1563     PP.Diag(PointersToMembersLoc, diag::warn_pragma_expected_lparen)
1564       << "pointers_to_members";
1565     return;
1566   }
1567   PP.Lex(Tok);
1568   const IdentifierInfo *Arg = Tok.getIdentifierInfo();
1569   if (!Arg) {
1570     PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
1571       << "pointers_to_members";
1572     return;
1573   }
1574   PP.Lex(Tok);
1575
1576   LangOptions::PragmaMSPointersToMembersKind RepresentationMethod;
1577   if (Arg->isStr("best_case")) {
1578     RepresentationMethod = LangOptions::PPTMK_BestCase;
1579   } else {
1580     if (Arg->isStr("full_generality")) {
1581       if (Tok.is(tok::comma)) {
1582         PP.Lex(Tok);
1583
1584         Arg = Tok.getIdentifierInfo();
1585         if (!Arg) {
1586           PP.Diag(Tok.getLocation(),
1587                   diag::err_pragma_pointers_to_members_unknown_kind)
1588               << Tok.getKind() << /*OnlyInheritanceModels*/ 0;
1589           return;
1590         }
1591         PP.Lex(Tok);
1592       } else if (Tok.is(tok::r_paren)) {
1593         // #pragma pointers_to_members(full_generality) implicitly specifies
1594         // virtual_inheritance.
1595         Arg = nullptr;
1596         RepresentationMethod = LangOptions::PPTMK_FullGeneralityVirtualInheritance;
1597       } else {
1598         PP.Diag(Tok.getLocation(), diag::err_expected_punc)
1599             << "full_generality";
1600         return;
1601       }
1602     }
1603
1604     if (Arg) {
1605       if (Arg->isStr("single_inheritance")) {
1606         RepresentationMethod =
1607             LangOptions::PPTMK_FullGeneralitySingleInheritance;
1608       } else if (Arg->isStr("multiple_inheritance")) {
1609         RepresentationMethod =
1610             LangOptions::PPTMK_FullGeneralityMultipleInheritance;
1611       } else if (Arg->isStr("virtual_inheritance")) {
1612         RepresentationMethod =
1613             LangOptions::PPTMK_FullGeneralityVirtualInheritance;
1614       } else {
1615         PP.Diag(Tok.getLocation(),
1616                 diag::err_pragma_pointers_to_members_unknown_kind)
1617             << Arg << /*HasPointerDeclaration*/ 1;
1618         return;
1619       }
1620     }
1621   }
1622
1623   if (Tok.isNot(tok::r_paren)) {
1624     PP.Diag(Tok.getLocation(), diag::err_expected_rparen_after)
1625         << (Arg ? Arg->getName() : "full_generality");
1626     return;
1627   }
1628
1629   SourceLocation EndLoc = Tok.getLocation();
1630   PP.Lex(Tok);
1631   if (Tok.isNot(tok::eod)) {
1632     PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1633       << "pointers_to_members";
1634     return;
1635   }
1636
1637   Token AnnotTok;
1638   AnnotTok.startToken();
1639   AnnotTok.setKind(tok::annot_pragma_ms_pointers_to_members);
1640   AnnotTok.setLocation(PointersToMembersLoc);
1641   AnnotTok.setAnnotationEndLoc(EndLoc);
1642   AnnotTok.setAnnotationValue(
1643       reinterpret_cast<void *>(static_cast<uintptr_t>(RepresentationMethod)));
1644   PP.EnterToken(AnnotTok);
1645 }
1646
1647 /// \brief Handle '#pragma vtordisp'
1648 // The grammar for this pragma is as follows:
1649 //
1650 // <vtordisp-mode> ::= ('off' | 'on' | '0' | '1' | '2' )
1651 //
1652 // #pragma vtordisp '(' ['push' ','] vtordisp-mode ')'
1653 // #pragma vtordisp '(' 'pop' ')'
1654 // #pragma vtordisp '(' ')'
1655 void PragmaMSVtorDisp::HandlePragma(Preprocessor &PP,
1656                                     PragmaIntroducerKind Introducer,
1657                                     Token &Tok) {
1658   SourceLocation VtorDispLoc = Tok.getLocation();
1659   PP.Lex(Tok);
1660   if (Tok.isNot(tok::l_paren)) {
1661     PP.Diag(VtorDispLoc, diag::warn_pragma_expected_lparen) << "vtordisp";
1662     return;
1663   }
1664   PP.Lex(Tok);
1665
1666   Sema::PragmaMsStackAction Action = Sema::PSK_Set;
1667   const IdentifierInfo *II = Tok.getIdentifierInfo();
1668   if (II) {
1669     if (II->isStr("push")) {
1670       // #pragma vtordisp(push, mode)
1671       PP.Lex(Tok);
1672       if (Tok.isNot(tok::comma)) {
1673         PP.Diag(VtorDispLoc, diag::warn_pragma_expected_punc) << "vtordisp";
1674         return;
1675       }
1676       PP.Lex(Tok);
1677       Action = Sema::PSK_Push_Set;
1678       // not push, could be on/off
1679     } else if (II->isStr("pop")) {
1680       // #pragma vtordisp(pop)
1681       PP.Lex(Tok);
1682       Action = Sema::PSK_Pop;
1683     }
1684     // not push or pop, could be on/off
1685   } else {
1686     if (Tok.is(tok::r_paren)) {
1687       // #pragma vtordisp()
1688       Action = Sema::PSK_Reset;
1689     }
1690   }
1691
1692
1693   uint64_t Value = 0;
1694   if (Action & Sema::PSK_Push || Action & Sema::PSK_Set) {
1695     const IdentifierInfo *II = Tok.getIdentifierInfo();
1696     if (II && II->isStr("off")) {
1697       PP.Lex(Tok);
1698       Value = 0;
1699     } else if (II && II->isStr("on")) {
1700       PP.Lex(Tok);
1701       Value = 1;
1702     } else if (Tok.is(tok::numeric_constant) &&
1703                PP.parseSimpleIntegerLiteral(Tok, Value)) {
1704       if (Value > 2) {
1705         PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_integer)
1706             << 0 << 2 << "vtordisp";
1707         return;
1708       }
1709     } else {
1710       PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_action)
1711           << "vtordisp";
1712       return;
1713     }
1714   }
1715
1716   // Finish the pragma: ')' $
1717   if (Tok.isNot(tok::r_paren)) {
1718     PP.Diag(VtorDispLoc, diag::warn_pragma_expected_rparen) << "vtordisp";
1719     return;
1720   }
1721   SourceLocation EndLoc = Tok.getLocation();
1722   PP.Lex(Tok);
1723   if (Tok.isNot(tok::eod)) {
1724     PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1725         << "vtordisp";
1726     return;
1727   }
1728
1729   // Enter the annotation.
1730   Token AnnotTok;
1731   AnnotTok.startToken();
1732   AnnotTok.setKind(tok::annot_pragma_ms_vtordisp);
1733   AnnotTok.setLocation(VtorDispLoc);
1734   AnnotTok.setAnnotationEndLoc(EndLoc);
1735   AnnotTok.setAnnotationValue(reinterpret_cast<void *>(
1736       static_cast<uintptr_t>((Action << 16) | (Value & 0xFFFF))));
1737   PP.EnterToken(AnnotTok);
1738 }
1739
1740 /// \brief Handle all MS pragmas.  Simply forwards the tokens after inserting
1741 /// an annotation token.
1742 void PragmaMSPragma::HandlePragma(Preprocessor &PP,
1743                                   PragmaIntroducerKind Introducer,
1744                                   Token &Tok) {
1745   Token EoF, AnnotTok;
1746   EoF.startToken();
1747   EoF.setKind(tok::eof);
1748   AnnotTok.startToken();
1749   AnnotTok.setKind(tok::annot_pragma_ms_pragma);
1750   AnnotTok.setLocation(Tok.getLocation());
1751   AnnotTok.setAnnotationEndLoc(Tok.getLocation());
1752   SmallVector<Token, 8> TokenVector;
1753   // Suck up all of the tokens before the eod.
1754   for (; Tok.isNot(tok::eod); PP.Lex(Tok)) {
1755     TokenVector.push_back(Tok);
1756     AnnotTok.setAnnotationEndLoc(Tok.getLocation());
1757   }
1758   // Add a sentinal EoF token to the end of the list.
1759   TokenVector.push_back(EoF);
1760   // We must allocate this array with new because EnterTokenStream is going to
1761   // delete it later.
1762   auto TokenArray = llvm::make_unique<Token[]>(TokenVector.size());
1763   std::copy(TokenVector.begin(), TokenVector.end(), TokenArray.get());
1764   auto Value = new (PP.getPreprocessorAllocator())
1765       std::pair<std::unique_ptr<Token[]>, size_t>(std::move(TokenArray),
1766                                                   TokenVector.size());
1767   AnnotTok.setAnnotationValue(Value);
1768   PP.EnterToken(AnnotTok);
1769 }
1770
1771 /// \brief Handle the Microsoft \#pragma detect_mismatch extension.
1772 ///
1773 /// The syntax is:
1774 /// \code
1775 ///   #pragma detect_mismatch("name", "value")
1776 /// \endcode
1777 /// Where 'name' and 'value' are quoted strings.  The values are embedded in
1778 /// the object file and passed along to the linker.  If the linker detects a
1779 /// mismatch in the object file's values for the given name, a LNK2038 error
1780 /// is emitted.  See MSDN for more details.
1781 void PragmaDetectMismatchHandler::HandlePragma(Preprocessor &PP,
1782                                                PragmaIntroducerKind Introducer,
1783                                                Token &Tok) {
1784   SourceLocation DetectMismatchLoc = Tok.getLocation();
1785   PP.Lex(Tok);
1786   if (Tok.isNot(tok::l_paren)) {
1787     PP.Diag(DetectMismatchLoc, diag::err_expected) << tok::l_paren;
1788     return;
1789   }
1790
1791   // Read the name to embed, which must be a string literal.
1792   std::string NameString;
1793   if (!PP.LexStringLiteral(Tok, NameString,
1794                            "pragma detect_mismatch",
1795                            /*MacroExpansion=*/true))
1796     return;
1797
1798   // Read the comma followed by a second string literal.
1799   std::string ValueString;
1800   if (Tok.isNot(tok::comma)) {
1801     PP.Diag(Tok.getLocation(), diag::err_pragma_detect_mismatch_malformed);
1802     return;
1803   }
1804
1805   if (!PP.LexStringLiteral(Tok, ValueString, "pragma detect_mismatch",
1806                            /*MacroExpansion=*/true))
1807     return;
1808
1809   if (Tok.isNot(tok::r_paren)) {
1810     PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
1811     return;
1812   }
1813   PP.Lex(Tok);  // Eat the r_paren.
1814
1815   if (Tok.isNot(tok::eod)) {
1816     PP.Diag(Tok.getLocation(), diag::err_pragma_detect_mismatch_malformed);
1817     return;
1818   }
1819
1820   // If the pragma is lexically sound, notify any interested PPCallbacks.
1821   if (PP.getPPCallbacks())
1822     PP.getPPCallbacks()->PragmaDetectMismatch(DetectMismatchLoc, NameString,
1823                                               ValueString);
1824
1825   Actions.ActOnPragmaDetectMismatch(DetectMismatchLoc, NameString, ValueString);
1826 }
1827
1828 /// \brief Handle the microsoft \#pragma comment extension.
1829 ///
1830 /// The syntax is:
1831 /// \code
1832 ///   #pragma comment(linker, "foo")
1833 /// \endcode
1834 /// 'linker' is one of five identifiers: compiler, exestr, lib, linker, user.
1835 /// "foo" is a string, which is fully macro expanded, and permits string
1836 /// concatenation, embedded escape characters etc.  See MSDN for more details.
1837 void PragmaCommentHandler::HandlePragma(Preprocessor &PP,
1838                                         PragmaIntroducerKind Introducer,
1839                                         Token &Tok) {
1840   SourceLocation CommentLoc = Tok.getLocation();
1841   PP.Lex(Tok);
1842   if (Tok.isNot(tok::l_paren)) {
1843     PP.Diag(CommentLoc, diag::err_pragma_comment_malformed);
1844     return;
1845   }
1846
1847   // Read the identifier.
1848   PP.Lex(Tok);
1849   if (Tok.isNot(tok::identifier)) {
1850     PP.Diag(CommentLoc, diag::err_pragma_comment_malformed);
1851     return;
1852   }
1853
1854   // Verify that this is one of the 5 whitelisted options.
1855   IdentifierInfo *II = Tok.getIdentifierInfo();
1856   PragmaMSCommentKind Kind =
1857     llvm::StringSwitch<PragmaMSCommentKind>(II->getName())
1858     .Case("linker",   PCK_Linker)
1859     .Case("lib",      PCK_Lib)
1860     .Case("compiler", PCK_Compiler)
1861     .Case("exestr",   PCK_ExeStr)
1862     .Case("user",     PCK_User)
1863     .Default(PCK_Unknown);
1864   if (Kind == PCK_Unknown) {
1865     PP.Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind);
1866     return;
1867   }
1868
1869   // On PS4, issue a warning about any pragma comments other than
1870   // #pragma comment lib.
1871   if (PP.getTargetInfo().getTriple().isPS4() && Kind != PCK_Lib) {
1872     PP.Diag(Tok.getLocation(), diag::warn_pragma_comment_ignored)
1873       << II->getName();
1874     return;
1875   }
1876
1877   // Read the optional string if present.
1878   PP.Lex(Tok);
1879   std::string ArgumentString;
1880   if (Tok.is(tok::comma) && !PP.LexStringLiteral(Tok, ArgumentString,
1881                                                  "pragma comment",
1882                                                  /*MacroExpansion=*/true))
1883     return;
1884
1885   // FIXME: warn that 'exestr' is deprecated.
1886   // FIXME: If the kind is "compiler" warn if the string is present (it is
1887   // ignored).
1888   // The MSDN docs say that "lib" and "linker" require a string and have a short
1889   // whitelist of linker options they support, but in practice MSVC doesn't
1890   // issue a diagnostic.  Therefore neither does clang.
1891
1892   if (Tok.isNot(tok::r_paren)) {
1893     PP.Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
1894     return;
1895   }
1896   PP.Lex(Tok);  // eat the r_paren.
1897
1898   if (Tok.isNot(tok::eod)) {
1899     PP.Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
1900     return;
1901   }
1902
1903   // If the pragma is lexically sound, notify any interested PPCallbacks.
1904   if (PP.getPPCallbacks())
1905     PP.getPPCallbacks()->PragmaComment(CommentLoc, II, ArgumentString);
1906
1907   Actions.ActOnPragmaMSComment(CommentLoc, Kind, ArgumentString);
1908 }
1909
1910 // #pragma clang optimize off
1911 // #pragma clang optimize on
1912 void PragmaOptimizeHandler::HandlePragma(Preprocessor &PP, 
1913                                         PragmaIntroducerKind Introducer,
1914                                         Token &FirstToken) {
1915   Token Tok;
1916   PP.Lex(Tok);
1917   if (Tok.is(tok::eod)) {
1918     PP.Diag(Tok.getLocation(), diag::err_pragma_missing_argument)
1919         << "clang optimize" << /*Expected=*/true << "'on' or 'off'";
1920     return;
1921   }
1922   if (Tok.isNot(tok::identifier)) {
1923     PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_invalid_argument)
1924       << PP.getSpelling(Tok);
1925     return;
1926   }
1927   const IdentifierInfo *II = Tok.getIdentifierInfo();
1928   // The only accepted values are 'on' or 'off'.
1929   bool IsOn = false;
1930   if (II->isStr("on")) {
1931     IsOn = true;
1932   } else if (!II->isStr("off")) {
1933     PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_invalid_argument)
1934       << PP.getSpelling(Tok);
1935     return;
1936   }
1937   PP.Lex(Tok);
1938   
1939   if (Tok.isNot(tok::eod)) {
1940     PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_extra_argument)
1941       << PP.getSpelling(Tok);
1942     return;
1943   }
1944
1945   Actions.ActOnPragmaOptimize(IsOn, FirstToken.getLocation());
1946 }
1947
1948 /// \brief Parses loop or unroll pragma hint value and fills in Info.
1949 static bool ParseLoopHintValue(Preprocessor &PP, Token &Tok, Token PragmaName,
1950                                Token Option, bool ValueInParens,
1951                                PragmaLoopHintInfo &Info) {
1952   SmallVector<Token, 1> ValueList;
1953   int OpenParens = ValueInParens ? 1 : 0;
1954   // Read constant expression.
1955   while (Tok.isNot(tok::eod)) {
1956     if (Tok.is(tok::l_paren))
1957       OpenParens++;
1958     else if (Tok.is(tok::r_paren)) {
1959       OpenParens--;
1960       if (OpenParens == 0 && ValueInParens)
1961         break;
1962     }
1963
1964     ValueList.push_back(Tok);
1965     PP.Lex(Tok);
1966   }
1967
1968   if (ValueInParens) {
1969     // Read ')'
1970     if (Tok.isNot(tok::r_paren)) {
1971       PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
1972       return true;
1973     }
1974     PP.Lex(Tok);
1975   }
1976
1977   Token EOFTok;
1978   EOFTok.startToken();
1979   EOFTok.setKind(tok::eof);
1980   EOFTok.setLocation(Tok.getLocation());
1981   ValueList.push_back(EOFTok); // Terminates expression for parsing.
1982
1983   Info.Toks = llvm::makeArrayRef(ValueList).copy(PP.getPreprocessorAllocator());
1984
1985   Info.PragmaName = PragmaName;
1986   Info.Option = Option;
1987   return false;
1988 }
1989
1990 /// \brief Handle the \#pragma clang loop directive.
1991 ///  #pragma clang 'loop' loop-hints
1992 ///
1993 ///  loop-hints:
1994 ///    loop-hint loop-hints[opt]
1995 ///
1996 ///  loop-hint:
1997 ///    'vectorize' '(' loop-hint-keyword ')'
1998 ///    'interleave' '(' loop-hint-keyword ')'
1999 ///    'unroll' '(' unroll-hint-keyword ')'
2000 ///    'vectorize_width' '(' loop-hint-value ')'
2001 ///    'interleave_count' '(' loop-hint-value ')'
2002 ///    'unroll_count' '(' loop-hint-value ')'
2003 ///
2004 ///  loop-hint-keyword:
2005 ///    'enable'
2006 ///    'disable'
2007 ///    'assume_safety'
2008 ///
2009 ///  unroll-hint-keyword:
2010 ///    'enable'
2011 ///    'disable'
2012 ///    'full'
2013 ///
2014 ///  loop-hint-value:
2015 ///    constant-expression
2016 ///
2017 /// Specifying vectorize(enable) or vectorize_width(_value_) instructs llvm to
2018 /// try vectorizing the instructions of the loop it precedes. Specifying
2019 /// interleave(enable) or interleave_count(_value_) instructs llvm to try
2020 /// interleaving multiple iterations of the loop it precedes. The width of the
2021 /// vector instructions is specified by vectorize_width() and the number of
2022 /// interleaved loop iterations is specified by interleave_count(). Specifying a
2023 /// value of 1 effectively disables vectorization/interleaving, even if it is
2024 /// possible and profitable, and 0 is invalid. The loop vectorizer currently
2025 /// only works on inner loops.
2026 ///
2027 /// The unroll and unroll_count directives control the concatenation
2028 /// unroller. Specifying unroll(enable) instructs llvm to unroll the loop
2029 /// completely if the trip count is known at compile time and unroll partially
2030 /// if the trip count is not known.  Specifying unroll(full) is similar to
2031 /// unroll(enable) but will unroll the loop only if the trip count is known at
2032 /// compile time.  Specifying unroll(disable) disables unrolling for the
2033 /// loop. Specifying unroll_count(_value_) instructs llvm to try to unroll the
2034 /// loop the number of times indicated by the value.
2035 void PragmaLoopHintHandler::HandlePragma(Preprocessor &PP,
2036                                          PragmaIntroducerKind Introducer,
2037                                          Token &Tok) {
2038   // Incoming token is "loop" from "#pragma clang loop".
2039   Token PragmaName = Tok;
2040   SmallVector<Token, 1> TokenList;
2041
2042   // Lex the optimization option and verify it is an identifier.
2043   PP.Lex(Tok);
2044   if (Tok.isNot(tok::identifier)) {
2045     PP.Diag(Tok.getLocation(), diag::err_pragma_loop_invalid_option)
2046         << /*MissingOption=*/true << "";
2047     return;
2048   }
2049
2050   while (Tok.is(tok::identifier)) {
2051     Token Option = Tok;
2052     IdentifierInfo *OptionInfo = Tok.getIdentifierInfo();
2053
2054     bool OptionValid = llvm::StringSwitch<bool>(OptionInfo->getName())
2055                            .Case("vectorize", true)
2056                            .Case("interleave", true)
2057                            .Case("unroll", true)
2058                            .Case("distribute", true)
2059                            .Case("vectorize_width", true)
2060                            .Case("interleave_count", true)
2061                            .Case("unroll_count", true)
2062                            .Default(false);
2063     if (!OptionValid) {
2064       PP.Diag(Tok.getLocation(), diag::err_pragma_loop_invalid_option)
2065           << /*MissingOption=*/false << OptionInfo;
2066       return;
2067     }
2068     PP.Lex(Tok);
2069
2070     // Read '('
2071     if (Tok.isNot(tok::l_paren)) {
2072       PP.Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
2073       return;
2074     }
2075     PP.Lex(Tok);
2076
2077     auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
2078     if (ParseLoopHintValue(PP, Tok, PragmaName, Option, /*ValueInParens=*/true,
2079                            *Info))
2080       return;
2081
2082     // Generate the loop hint token.
2083     Token LoopHintTok;
2084     LoopHintTok.startToken();
2085     LoopHintTok.setKind(tok::annot_pragma_loop_hint);
2086     LoopHintTok.setLocation(PragmaName.getLocation());
2087     LoopHintTok.setAnnotationEndLoc(PragmaName.getLocation());
2088     LoopHintTok.setAnnotationValue(static_cast<void *>(Info));
2089     TokenList.push_back(LoopHintTok);
2090   }
2091
2092   if (Tok.isNot(tok::eod)) {
2093     PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
2094         << "clang loop";
2095     return;
2096   }
2097
2098   auto TokenArray = llvm::make_unique<Token[]>(TokenList.size());
2099   std::copy(TokenList.begin(), TokenList.end(), TokenArray.get());
2100
2101   PP.EnterTokenStream(std::move(TokenArray), TokenList.size(),
2102                       /*DisableMacroExpansion=*/false);
2103 }
2104
2105 /// \brief Handle the loop unroll optimization pragmas.
2106 ///  #pragma unroll
2107 ///  #pragma unroll unroll-hint-value
2108 ///  #pragma unroll '(' unroll-hint-value ')'
2109 ///  #pragma nounroll
2110 ///
2111 ///  unroll-hint-value:
2112 ///    constant-expression
2113 ///
2114 /// Loop unrolling hints can be specified with '#pragma unroll' or
2115 /// '#pragma nounroll'. '#pragma unroll' can take a numeric argument optionally
2116 /// contained in parentheses. With no argument the directive instructs llvm to
2117 /// try to unroll the loop completely. A positive integer argument can be
2118 /// specified to indicate the number of times the loop should be unrolled.  To
2119 /// maximize compatibility with other compilers the unroll count argument can be
2120 /// specified with or without parentheses.  Specifying, '#pragma nounroll'
2121 /// disables unrolling of the loop.
2122 void PragmaUnrollHintHandler::HandlePragma(Preprocessor &PP,
2123                                            PragmaIntroducerKind Introducer,
2124                                            Token &Tok) {
2125   // Incoming token is "unroll" for "#pragma unroll", or "nounroll" for
2126   // "#pragma nounroll".
2127   Token PragmaName = Tok;
2128   PP.Lex(Tok);
2129   auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
2130   if (Tok.is(tok::eod)) {
2131     // nounroll or unroll pragma without an argument.
2132     Info->PragmaName = PragmaName;
2133     Info->Option.startToken();
2134   } else if (PragmaName.getIdentifierInfo()->getName() == "nounroll") {
2135     PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
2136         << "nounroll";
2137     return;
2138   } else {
2139     // Unroll pragma with an argument: "#pragma unroll N" or
2140     // "#pragma unroll(N)".
2141     // Read '(' if it exists.
2142     bool ValueInParens = Tok.is(tok::l_paren);
2143     if (ValueInParens)
2144       PP.Lex(Tok);
2145
2146     Token Option;
2147     Option.startToken();
2148     if (ParseLoopHintValue(PP, Tok, PragmaName, Option, ValueInParens, *Info))
2149       return;
2150
2151     // In CUDA, the argument to '#pragma unroll' should not be contained in
2152     // parentheses.
2153     if (PP.getLangOpts().CUDA && ValueInParens)
2154       PP.Diag(Info->Toks[0].getLocation(),
2155               diag::warn_pragma_unroll_cuda_value_in_parens);
2156
2157     if (Tok.isNot(tok::eod)) {
2158       PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
2159           << "unroll";
2160       return;
2161     }
2162   }
2163
2164   // Generate the hint token.
2165   auto TokenArray = llvm::make_unique<Token[]>(1);
2166   TokenArray[0].startToken();
2167   TokenArray[0].setKind(tok::annot_pragma_loop_hint);
2168   TokenArray[0].setLocation(PragmaName.getLocation());
2169   TokenArray[0].setAnnotationEndLoc(PragmaName.getLocation());
2170   TokenArray[0].setAnnotationValue(static_cast<void *>(Info));
2171   PP.EnterTokenStream(std::move(TokenArray), 1,
2172                       /*DisableMacroExpansion=*/false);
2173 }
2174
2175 /// \brief Handle the Microsoft \#pragma intrinsic extension.
2176 ///
2177 /// The syntax is:
2178 /// \code
2179 ///  #pragma intrinsic(memset)
2180 ///  #pragma intrinsic(strlen, memcpy)
2181 /// \endcode
2182 ///
2183 /// Pragma intrisic tells the compiler to use a builtin version of the
2184 /// function. Clang does it anyway, so the pragma doesn't really do anything.
2185 /// Anyway, we emit a warning if the function specified in \#pragma intrinsic
2186 /// isn't an intrinsic in clang and suggest to include intrin.h.
2187 void PragmaMSIntrinsicHandler::HandlePragma(Preprocessor &PP,
2188                                             PragmaIntroducerKind Introducer,
2189                                             Token &Tok) {
2190   PP.Lex(Tok);
2191
2192   if (Tok.isNot(tok::l_paren)) {
2193     PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen)
2194         << "intrinsic";
2195     return;
2196   }
2197   PP.Lex(Tok);
2198
2199   bool SuggestIntrinH = !PP.isMacroDefined("__INTRIN_H");
2200
2201   while (Tok.is(tok::identifier)) {
2202     IdentifierInfo *II = Tok.getIdentifierInfo();
2203     if (!II->getBuiltinID())
2204       PP.Diag(Tok.getLocation(), diag::warn_pragma_intrinsic_builtin)
2205           << II << SuggestIntrinH;
2206
2207     PP.Lex(Tok);
2208     if (Tok.isNot(tok::comma))
2209       break;
2210     PP.Lex(Tok);
2211   }
2212
2213   if (Tok.isNot(tok::r_paren)) {
2214     PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen)
2215         << "intrinsic";
2216     return;
2217   }
2218   PP.Lex(Tok);
2219
2220   if (Tok.isNot(tok::eod))
2221     PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
2222         << "intrinsic";
2223 }
2224 void PragmaForceCUDAHostDeviceHandler::HandlePragma(
2225     Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) {
2226   Token FirstTok = Tok;
2227
2228   PP.Lex(Tok);
2229   IdentifierInfo *Info = Tok.getIdentifierInfo();
2230   if (!Info || (!Info->isStr("begin") && !Info->isStr("end"))) {
2231     PP.Diag(FirstTok.getLocation(),
2232             diag::warn_pragma_force_cuda_host_device_bad_arg);
2233     return;
2234   }
2235
2236   if (Info->isStr("begin"))
2237     Actions.PushForceCUDAHostDevice();
2238   else if (!Actions.PopForceCUDAHostDevice())
2239     PP.Diag(FirstTok.getLocation(),
2240             diag::err_pragma_cannot_end_force_cuda_host_device);
2241
2242   PP.Lex(Tok);
2243   if (!Tok.is(tok::eod))
2244     PP.Diag(FirstTok.getLocation(),
2245             diag::warn_pragma_force_cuda_host_device_bad_arg);
2246 }