Bug Summary

File:clang/include/clang/Basic/Diagnostic.h
Warning:line 1144, column 5
Use of memory after it is freed

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ParsePragma.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/tools/clang/lib/Parse -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/lib/Parse -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/tools/clang/lib/Parse -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-11-29-190409-37574-1 -x c++ /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/lib/Parse/ParsePragma.cpp

/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/lib/Parse/ParsePragma.cpp

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

/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h

1//===- Diagnostic.h - C Language Family Diagnostic Handling -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// Defines the Diagnostic-related interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_BASIC_DIAGNOSTIC_H
15#define LLVM_CLANG_BASIC_DIAGNOSTIC_H
16
17#include "clang/Basic/DiagnosticIDs.h"
18#include "clang/Basic/DiagnosticOptions.h"
19#include "clang/Basic/SourceLocation.h"
20#include "clang/Basic/Specifiers.h"
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/IntrusiveRefCntPtr.h"
24#include "llvm/ADT/Optional.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/ADT/iterator_range.h"
28#include "llvm/Support/Compiler.h"
29#include <cassert>
30#include <cstdint>
31#include <limits>
32#include <list>
33#include <map>
34#include <memory>
35#include <string>
36#include <type_traits>
37#include <utility>
38#include <vector>
39
40namespace llvm {
41class Error;
42}
43
44namespace clang {
45
46class DeclContext;
47class DiagnosticBuilder;
48class DiagnosticConsumer;
49class IdentifierInfo;
50class LangOptions;
51class Preprocessor;
52class SourceManager;
53class StoredDiagnostic;
54
55namespace tok {
56
57enum TokenKind : unsigned short;
58
59} // namespace tok
60
61/// Annotates a diagnostic with some code that should be
62/// inserted, removed, or replaced to fix the problem.
63///
64/// This kind of hint should be used when we are certain that the
65/// introduction, removal, or modification of a particular (small!)
66/// amount of code will correct a compilation error. The compiler
67/// should also provide full recovery from such errors, such that
68/// suppressing the diagnostic output can still result in successful
69/// compilation.
70class FixItHint {
71public:
72 /// Code that should be replaced to correct the error. Empty for an
73 /// insertion hint.
74 CharSourceRange RemoveRange;
75
76 /// Code in the specific range that should be inserted in the insertion
77 /// location.
78 CharSourceRange InsertFromRange;
79
80 /// The actual code to insert at the insertion location, as a
81 /// string.
82 std::string CodeToInsert;
83
84 bool BeforePreviousInsertions = false;
85
86 /// Empty code modification hint, indicating that no code
87 /// modification is known.
88 FixItHint() = default;
89
90 bool isNull() const {
91 return !RemoveRange.isValid();
92 }
93
94 /// Create a code modification hint that inserts the given
95 /// code string at a specific location.
96 static FixItHint CreateInsertion(SourceLocation InsertionLoc,
97 StringRef Code,
98 bool BeforePreviousInsertions = false) {
99 FixItHint Hint;
100 Hint.RemoveRange =
101 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
102 Hint.CodeToInsert = std::string(Code);
103 Hint.BeforePreviousInsertions = BeforePreviousInsertions;
104 return Hint;
105 }
106
107 /// Create a code modification hint that inserts the given
108 /// code from \p FromRange at a specific location.
109 static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc,
110 CharSourceRange FromRange,
111 bool BeforePreviousInsertions = false) {
112 FixItHint Hint;
113 Hint.RemoveRange =
114 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
115 Hint.InsertFromRange = FromRange;
116 Hint.BeforePreviousInsertions = BeforePreviousInsertions;
117 return Hint;
118 }
119
120 /// Create a code modification hint that removes the given
121 /// source range.
122 static FixItHint CreateRemoval(CharSourceRange RemoveRange) {
123 FixItHint Hint;
124 Hint.RemoveRange = RemoveRange;
125 return Hint;
126 }
127 static FixItHint CreateRemoval(SourceRange RemoveRange) {
128 return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange));
129 }
130
131 /// Create a code modification hint that replaces the given
132 /// source range with the given code string.
133 static FixItHint CreateReplacement(CharSourceRange RemoveRange,
134 StringRef Code) {
135 FixItHint Hint;
136 Hint.RemoveRange = RemoveRange;
137 Hint.CodeToInsert = std::string(Code);
138 return Hint;
139 }
140
141 static FixItHint CreateReplacement(SourceRange RemoveRange,
142 StringRef Code) {
143 return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code);
144 }
145};
146
147struct DiagnosticStorage {
148 enum {
149 /// The maximum number of arguments we can hold. We
150 /// currently only support up to 10 arguments (%0-%9).
151 ///
152 /// A single diagnostic with more than that almost certainly has to
153 /// be simplified anyway.
154 MaxArguments = 10
155 };
156
157 /// The number of entries in Arguments.
158 unsigned char NumDiagArgs = 0;
159
160 /// Specifies for each argument whether it is in DiagArgumentsStr
161 /// or in DiagArguments.
162 unsigned char DiagArgumentsKind[MaxArguments];
163
164 /// The values for the various substitution positions.
165 ///
166 /// This is used when the argument is not an std::string. The specific value
167 /// is mangled into an intptr_t and the interpretation depends on exactly
168 /// what sort of argument kind it is.
169 intptr_t DiagArgumentsVal[MaxArguments];
170
171 /// The values for the various substitution positions that have
172 /// string arguments.
173 std::string DiagArgumentsStr[MaxArguments];
174
175 /// The list of ranges added to this diagnostic.
176 SmallVector<CharSourceRange, 8> DiagRanges;
177
178 /// If valid, provides a hint with some code to insert, remove, or
179 /// modify at a particular position.
180 SmallVector<FixItHint, 6> FixItHints;
181
182 DiagnosticStorage() = default;
183};
184
185/// Concrete class used by the front-end to report problems and issues.
186///
187/// This massages the diagnostics (e.g. handling things like "report warnings
188/// as errors" and passes them off to the DiagnosticConsumer for reporting to
189/// the user. DiagnosticsEngine is tied to one translation unit and one
190/// SourceManager.
191class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> {
192public:
193 /// The level of the diagnostic, after it has been through mapping.
194 enum Level {
195 Ignored = DiagnosticIDs::Ignored,
196 Note = DiagnosticIDs::Note,
197 Remark = DiagnosticIDs::Remark,
198 Warning = DiagnosticIDs::Warning,
199 Error = DiagnosticIDs::Error,
200 Fatal = DiagnosticIDs::Fatal
201 };
202
203 enum ArgumentKind {
204 /// std::string
205 ak_std_string,
206
207 /// const char *
208 ak_c_string,
209
210 /// int
211 ak_sint,
212
213 /// unsigned
214 ak_uint,
215
216 /// enum TokenKind : unsigned
217 ak_tokenkind,
218
219 /// IdentifierInfo
220 ak_identifierinfo,
221
222 /// address space
223 ak_addrspace,
224
225 /// Qualifiers
226 ak_qual,
227
228 /// QualType
229 ak_qualtype,
230
231 /// DeclarationName
232 ak_declarationname,
233
234 /// NamedDecl *
235 ak_nameddecl,
236
237 /// NestedNameSpecifier *
238 ak_nestednamespec,
239
240 /// DeclContext *
241 ak_declcontext,
242
243 /// pair<QualType, QualType>
244 ak_qualtype_pair,
245
246 /// Attr *
247 ak_attr
248 };
249
250 /// Represents on argument value, which is a union discriminated
251 /// by ArgumentKind, with a value.
252 using ArgumentValue = std::pair<ArgumentKind, intptr_t>;
253
254private:
255 // Used by __extension__
256 unsigned char AllExtensionsSilenced = 0;
257
258 // Treat fatal errors like errors.
259 bool FatalsAsError = false;
260
261 // Suppress all diagnostics.
262 bool SuppressAllDiagnostics = false;
263
264 // Elide common types of templates.
265 bool ElideType = true;
266
267 // Print a tree when comparing templates.
268 bool PrintTemplateTree = false;
269
270 // Color printing is enabled.
271 bool ShowColors = false;
272
273 // Which overload candidates to show.
274 OverloadsShown ShowOverloads = Ovl_All;
275
276 // Cap of # errors emitted, 0 -> no limit.
277 unsigned ErrorLimit = 0;
278
279 // Cap on depth of template backtrace stack, 0 -> no limit.
280 unsigned TemplateBacktraceLimit = 0;
281
282 // Cap on depth of constexpr evaluation backtrace stack, 0 -> no limit.
283 unsigned ConstexprBacktraceLimit = 0;
284
285 IntrusiveRefCntPtr<DiagnosticIDs> Diags;
286 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
287 DiagnosticConsumer *Client = nullptr;
288 std::unique_ptr<DiagnosticConsumer> Owner;
289 SourceManager *SourceMgr = nullptr;
290
291 /// Mapping information for diagnostics.
292 ///
293 /// Mapping info is packed into four bits per diagnostic. The low three
294 /// bits are the mapping (an instance of diag::Severity), or zero if unset.
295 /// The high bit is set when the mapping was established as a user mapping.
296 /// If the high bit is clear, then the low bits are set to the default
297 /// value, and should be mapped with -pedantic, -Werror, etc.
298 ///
299 /// A new DiagState is created and kept around when diagnostic pragmas modify
300 /// the state so that we know what is the diagnostic state at any given
301 /// source location.
302 class DiagState {
303 llvm::DenseMap<unsigned, DiagnosticMapping> DiagMap;
304
305 public:
306 // "Global" configuration state that can actually vary between modules.
307
308 // Ignore all warnings: -w
309 unsigned IgnoreAllWarnings : 1;
310
311 // Enable all warnings.
312 unsigned EnableAllWarnings : 1;
313
314 // Treat warnings like errors.
315 unsigned WarningsAsErrors : 1;
316
317 // Treat errors like fatal errors.
318 unsigned ErrorsAsFatal : 1;
319
320 // Suppress warnings in system headers.
321 unsigned SuppressSystemWarnings : 1;
322
323 // Map extensions to warnings or errors?
324 diag::Severity ExtBehavior = diag::Severity::Ignored;
325
326 DiagState()
327 : IgnoreAllWarnings(false), EnableAllWarnings(false),
328 WarningsAsErrors(false), ErrorsAsFatal(false),
329 SuppressSystemWarnings(false) {}
330
331 using iterator = llvm::DenseMap<unsigned, DiagnosticMapping>::iterator;
332 using const_iterator =
333 llvm::DenseMap<unsigned, DiagnosticMapping>::const_iterator;
334
335 void setMapping(diag::kind Diag, DiagnosticMapping Info) {
336 DiagMap[Diag] = Info;
337 }
338
339 DiagnosticMapping lookupMapping(diag::kind Diag) const {
340 return DiagMap.lookup(Diag);
341 }
342
343 DiagnosticMapping &getOrAddMapping(diag::kind Diag);
344
345 const_iterator begin() const { return DiagMap.begin(); }
346 const_iterator end() const { return DiagMap.end(); }
347 };
348
349 /// Keeps and automatically disposes all DiagStates that we create.
350 std::list<DiagState> DiagStates;
351
352 /// A mapping from files to the diagnostic states for those files. Lazily
353 /// built on demand for files in which the diagnostic state has not changed.
354 class DiagStateMap {
355 public:
356 /// Add an initial diagnostic state.
357 void appendFirst(DiagState *State);
358
359 /// Add a new latest state point.
360 void append(SourceManager &SrcMgr, SourceLocation Loc, DiagState *State);
361
362 /// Look up the diagnostic state at a given source location.
363 DiagState *lookup(SourceManager &SrcMgr, SourceLocation Loc) const;
364
365 /// Determine whether this map is empty.
366 bool empty() const { return Files.empty(); }
367
368 /// Clear out this map.
369 void clear() {
370 Files.clear();
371 FirstDiagState = CurDiagState = nullptr;
372 CurDiagStateLoc = SourceLocation();
373 }
374
375 /// Produce a debugging dump of the diagnostic state.
376 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void dump(SourceManager &SrcMgr,
377 StringRef DiagName = StringRef()) const;
378
379 /// Grab the most-recently-added state point.
380 DiagState *getCurDiagState() const { return CurDiagState; }
381
382 /// Get the location at which a diagnostic state was last added.
383 SourceLocation getCurDiagStateLoc() const { return CurDiagStateLoc; }
384
385 private:
386 friend class ASTReader;
387 friend class ASTWriter;
388
389 /// Represents a point in source where the diagnostic state was
390 /// modified because of a pragma.
391 ///
392 /// 'Loc' can be null if the point represents the diagnostic state
393 /// modifications done through the command-line.
394 struct DiagStatePoint {
395 DiagState *State;
396 unsigned Offset;
397
398 DiagStatePoint(DiagState *State, unsigned Offset)
399 : State(State), Offset(Offset) {}
400 };
401
402 /// Description of the diagnostic states and state transitions for a
403 /// particular FileID.
404 struct File {
405 /// The diagnostic state for the parent file. This is strictly redundant,
406 /// as looking up the DecomposedIncludedLoc for the FileID in the Files
407 /// map would give us this, but we cache it here for performance.
408 File *Parent = nullptr;
409
410 /// The offset of this file within its parent.
411 unsigned ParentOffset = 0;
412
413 /// Whether this file has any local (not imported from an AST file)
414 /// diagnostic state transitions.
415 bool HasLocalTransitions = false;
416
417 /// The points within the file where the state changes. There will always
418 /// be at least one of these (the state on entry to the file).
419 llvm::SmallVector<DiagStatePoint, 4> StateTransitions;
420
421 DiagState *lookup(unsigned Offset) const;
422 };
423
424 /// The diagnostic states for each file.
425 mutable std::map<FileID, File> Files;
426
427 /// The initial diagnostic state.
428 DiagState *FirstDiagState;
429
430 /// The current diagnostic state.
431 DiagState *CurDiagState;
432
433 /// The location at which the current diagnostic state was established.
434 SourceLocation CurDiagStateLoc;
435
436 /// Get the diagnostic state information for a file.
437 File *getFile(SourceManager &SrcMgr, FileID ID) const;
438 };
439
440 DiagStateMap DiagStatesByLoc;
441
442 /// Keeps the DiagState that was active during each diagnostic 'push'
443 /// so we can get back at it when we 'pop'.
444 std::vector<DiagState *> DiagStateOnPushStack;
445
446 DiagState *GetCurDiagState() const {
447 return DiagStatesByLoc.getCurDiagState();
448 }
449
450 void PushDiagStatePoint(DiagState *State, SourceLocation L);
451
452 /// Finds the DiagStatePoint that contains the diagnostic state of
453 /// the given source location.
454 DiagState *GetDiagStateForLoc(SourceLocation Loc) const {
455 return SourceMgr ? DiagStatesByLoc.lookup(*SourceMgr, Loc)
456 : DiagStatesByLoc.getCurDiagState();
457 }
458
459 /// Sticky flag set to \c true when an error is emitted.
460 bool ErrorOccurred;
461
462 /// Sticky flag set to \c true when an "uncompilable error" occurs.
463 /// I.e. an error that was not upgraded from a warning by -Werror.
464 bool UncompilableErrorOccurred;
465
466 /// Sticky flag set to \c true when a fatal error is emitted.
467 bool FatalErrorOccurred;
468
469 /// Indicates that an unrecoverable error has occurred.
470 bool UnrecoverableErrorOccurred;
471
472 /// Counts for DiagnosticErrorTrap to check whether an error occurred
473 /// during a parsing section, e.g. during parsing a function.
474 unsigned TrapNumErrorsOccurred;
475 unsigned TrapNumUnrecoverableErrorsOccurred;
476
477 /// The level of the last diagnostic emitted.
478 ///
479 /// This is used to emit continuation diagnostics with the same level as the
480 /// diagnostic that they follow.
481 DiagnosticIDs::Level LastDiagLevel;
482
483 /// Number of warnings reported
484 unsigned NumWarnings;
485
486 /// Number of errors reported
487 unsigned NumErrors;
488
489 /// A function pointer that converts an opaque diagnostic
490 /// argument to a strings.
491 ///
492 /// This takes the modifiers and argument that was present in the diagnostic.
493 ///
494 /// The PrevArgs array indicates the previous arguments formatted for this
495 /// diagnostic. Implementations of this function can use this information to
496 /// avoid redundancy across arguments.
497 ///
498 /// This is a hack to avoid a layering violation between libbasic and libsema.
499 using ArgToStringFnTy = void (*)(
500 ArgumentKind Kind, intptr_t Val,
501 StringRef Modifier, StringRef Argument,
502 ArrayRef<ArgumentValue> PrevArgs,
503 SmallVectorImpl<char> &Output,
504 void *Cookie,
505 ArrayRef<intptr_t> QualTypeVals);
506
507 void *ArgToStringCookie = nullptr;
508 ArgToStringFnTy ArgToStringFn;
509
510 /// ID of the "delayed" diagnostic, which is a (typically
511 /// fatal) diagnostic that had to be delayed because it was found
512 /// while emitting another diagnostic.
513 unsigned DelayedDiagID;
514
515 /// First string argument for the delayed diagnostic.
516 std::string DelayedDiagArg1;
517
518 /// Second string argument for the delayed diagnostic.
519 std::string DelayedDiagArg2;
520
521 /// Third string argument for the delayed diagnostic.
522 std::string DelayedDiagArg3;
523
524 /// Optional flag value.
525 ///
526 /// Some flags accept values, for instance: -Wframe-larger-than=<value> and
527 /// -Rpass=<value>. The content of this string is emitted after the flag name
528 /// and '='.
529 std::string FlagValue;
530
531public:
532 explicit DiagnosticsEngine(IntrusiveRefCntPtr<DiagnosticIDs> Diags,
533 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
534 DiagnosticConsumer *client = nullptr,
535 bool ShouldOwnClient = true);
536 DiagnosticsEngine(const DiagnosticsEngine &) = delete;
537 DiagnosticsEngine &operator=(const DiagnosticsEngine &) = delete;
538 ~DiagnosticsEngine();
539
540 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void dump() const;
541 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void dump(StringRef DiagName) const;
542
543 const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
544 return Diags;
545 }
546
547 /// Retrieve the diagnostic options.
548 DiagnosticOptions &getDiagnosticOptions() const { return *DiagOpts; }
549
550 using diag_mapping_range = llvm::iterator_range<DiagState::const_iterator>;
551
552 /// Get the current set of diagnostic mappings.
553 diag_mapping_range getDiagnosticMappings() const {
554 const DiagState &DS = *GetCurDiagState();
555 return diag_mapping_range(DS.begin(), DS.end());
556 }
557
558 DiagnosticConsumer *getClient() { return Client; }
559 const DiagnosticConsumer *getClient() const { return Client; }
560
561 /// Determine whether this \c DiagnosticsEngine object own its client.
562 bool ownsClient() const { return Owner != nullptr; }
563
564 /// Return the current diagnostic client along with ownership of that
565 /// client.
566 std::unique_ptr<DiagnosticConsumer> takeClient() { return std::move(Owner); }
567
568 bool hasSourceManager() const { return SourceMgr != nullptr; }
569
570 SourceManager &getSourceManager() const {
571 assert(SourceMgr && "SourceManager not set!")((SourceMgr && "SourceManager not set!") ? static_cast
<void> (0) : __assert_fail ("SourceMgr && \"SourceManager not set!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 571, __PRETTY_FUNCTION__))
;
572 return *SourceMgr;
573 }
574
575 void setSourceManager(SourceManager *SrcMgr) {
576 assert(DiagStatesByLoc.empty() &&((DiagStatesByLoc.empty() && "Leftover diag state from a different SourceManager."
) ? static_cast<void> (0) : __assert_fail ("DiagStatesByLoc.empty() && \"Leftover diag state from a different SourceManager.\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 577, __PRETTY_FUNCTION__))
577 "Leftover diag state from a different SourceManager.")((DiagStatesByLoc.empty() && "Leftover diag state from a different SourceManager."
) ? static_cast<void> (0) : __assert_fail ("DiagStatesByLoc.empty() && \"Leftover diag state from a different SourceManager.\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 577, __PRETTY_FUNCTION__))
;
578 SourceMgr = SrcMgr;
579 }
580
581 //===--------------------------------------------------------------------===//
582 // DiagnosticsEngine characterization methods, used by a client to customize
583 // how diagnostics are emitted.
584 //
585
586 /// Copies the current DiagMappings and pushes the new copy
587 /// onto the top of the stack.
588 void pushMappings(SourceLocation Loc);
589
590 /// Pops the current DiagMappings off the top of the stack,
591 /// causing the new top of the stack to be the active mappings.
592 ///
593 /// \returns \c true if the pop happens, \c false if there is only one
594 /// DiagMapping on the stack.
595 bool popMappings(SourceLocation Loc);
596
597 /// Set the diagnostic client associated with this diagnostic object.
598 ///
599 /// \param ShouldOwnClient true if the diagnostic object should take
600 /// ownership of \c client.
601 void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true);
602
603 /// Specify a limit for the number of errors we should
604 /// emit before giving up.
605 ///
606 /// Zero disables the limit.
607 void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
608
609 /// Specify the maximum number of template instantiation
610 /// notes to emit along with a given diagnostic.
611 void setTemplateBacktraceLimit(unsigned Limit) {
612 TemplateBacktraceLimit = Limit;
613 }
614
615 /// Retrieve the maximum number of template instantiation
616 /// notes to emit along with a given diagnostic.
617 unsigned getTemplateBacktraceLimit() const {
618 return TemplateBacktraceLimit;
619 }
620
621 /// Specify the maximum number of constexpr evaluation
622 /// notes to emit along with a given diagnostic.
623 void setConstexprBacktraceLimit(unsigned Limit) {
624 ConstexprBacktraceLimit = Limit;
625 }
626
627 /// Retrieve the maximum number of constexpr evaluation
628 /// notes to emit along with a given diagnostic.
629 unsigned getConstexprBacktraceLimit() const {
630 return ConstexprBacktraceLimit;
631 }
632
633 /// When set to true, any unmapped warnings are ignored.
634 ///
635 /// If this and WarningsAsErrors are both set, then this one wins.
636 void setIgnoreAllWarnings(bool Val) {
637 GetCurDiagState()->IgnoreAllWarnings = Val;
638 }
639 bool getIgnoreAllWarnings() const {
640 return GetCurDiagState()->IgnoreAllWarnings;
641 }
642
643 /// When set to true, any unmapped ignored warnings are no longer
644 /// ignored.
645 ///
646 /// If this and IgnoreAllWarnings are both set, then that one wins.
647 void setEnableAllWarnings(bool Val) {
648 GetCurDiagState()->EnableAllWarnings = Val;
649 }
650 bool getEnableAllWarnings() const {
651 return GetCurDiagState()->EnableAllWarnings;
652 }
653
654 /// When set to true, any warnings reported are issued as errors.
655 void setWarningsAsErrors(bool Val) {
656 GetCurDiagState()->WarningsAsErrors = Val;
657 }
658 bool getWarningsAsErrors() const {
659 return GetCurDiagState()->WarningsAsErrors;
660 }
661
662 /// When set to true, any error reported is made a fatal error.
663 void setErrorsAsFatal(bool Val) { GetCurDiagState()->ErrorsAsFatal = Val; }
664 bool getErrorsAsFatal() const { return GetCurDiagState()->ErrorsAsFatal; }
665
666 /// \brief When set to true, any fatal error reported is made an error.
667 ///
668 /// This setting takes precedence over the setErrorsAsFatal setting above.
669 void setFatalsAsError(bool Val) { FatalsAsError = Val; }
670 bool getFatalsAsError() const { return FatalsAsError; }
671
672 /// When set to true mask warnings that come from system headers.
673 void setSuppressSystemWarnings(bool Val) {
674 GetCurDiagState()->SuppressSystemWarnings = Val;
675 }
676 bool getSuppressSystemWarnings() const {
677 return GetCurDiagState()->SuppressSystemWarnings;
678 }
679
680 /// Suppress all diagnostics, to silence the front end when we
681 /// know that we don't want any more diagnostics to be passed along to the
682 /// client
683 void setSuppressAllDiagnostics(bool Val) { SuppressAllDiagnostics = Val; }
684 bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
685
686 /// Set type eliding, to skip outputting same types occurring in
687 /// template types.
688 void setElideType(bool Val) { ElideType = Val; }
689 bool getElideType() { return ElideType; }
690
691 /// Set tree printing, to outputting the template difference in a
692 /// tree format.
693 void setPrintTemplateTree(bool Val) { PrintTemplateTree = Val; }
694 bool getPrintTemplateTree() { return PrintTemplateTree; }
695
696 /// Set color printing, so the type diffing will inject color markers
697 /// into the output.
698 void setShowColors(bool Val) { ShowColors = Val; }
699 bool getShowColors() { return ShowColors; }
700
701 /// Specify which overload candidates to show when overload resolution
702 /// fails.
703 ///
704 /// By default, we show all candidates.
705 void setShowOverloads(OverloadsShown Val) {
706 ShowOverloads = Val;
707 }
708 OverloadsShown getShowOverloads() const { return ShowOverloads; }
709
710 /// Pretend that the last diagnostic issued was ignored, so any
711 /// subsequent notes will be suppressed, or restore a prior ignoring
712 /// state after ignoring some diagnostics and their notes, possibly in
713 /// the middle of another diagnostic.
714 ///
715 /// This can be used by clients who suppress diagnostics themselves.
716 void setLastDiagnosticIgnored(bool Ignored) {
717 if (LastDiagLevel == DiagnosticIDs::Fatal)
718 FatalErrorOccurred = true;
719 LastDiagLevel = Ignored ? DiagnosticIDs::Ignored : DiagnosticIDs::Warning;
720 }
721
722 /// Determine whether the previous diagnostic was ignored. This can
723 /// be used by clients that want to determine whether notes attached to a
724 /// diagnostic will be suppressed.
725 bool isLastDiagnosticIgnored() const {
726 return LastDiagLevel == DiagnosticIDs::Ignored;
727 }
728
729 /// Controls whether otherwise-unmapped extension diagnostics are
730 /// mapped onto ignore/warning/error.
731 ///
732 /// This corresponds to the GCC -pedantic and -pedantic-errors option.
733 void setExtensionHandlingBehavior(diag::Severity H) {
734 GetCurDiagState()->ExtBehavior = H;
735 }
736 diag::Severity getExtensionHandlingBehavior() const {
737 return GetCurDiagState()->ExtBehavior;
738 }
739
740 /// Counter bumped when an __extension__ block is/ encountered.
741 ///
742 /// When non-zero, all extension diagnostics are entirely silenced, no
743 /// matter how they are mapped.
744 void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
745 void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
746 bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
747
748 /// This allows the client to specify that certain warnings are
749 /// ignored.
750 ///
751 /// Notes can never be mapped, errors can only be mapped to fatal, and
752 /// WARNINGs and EXTENSIONs can be mapped arbitrarily.
753 ///
754 /// \param Loc The source location that this change of diagnostic state should
755 /// take affect. It can be null if we are setting the latest state.
756 void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc);
757
758 /// Change an entire diagnostic group (e.g. "unknown-pragmas") to
759 /// have the specified mapping.
760 ///
761 /// \returns true (and ignores the request) if "Group" was unknown, false
762 /// otherwise.
763 ///
764 /// \param Flavor The flavor of group to affect. -Rfoo does not affect the
765 /// state of the -Wfoo group and vice versa.
766 ///
767 /// \param Loc The source location that this change of diagnostic state should
768 /// take affect. It can be null if we are setting the state from command-line.
769 bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group,
770 diag::Severity Map,
771 SourceLocation Loc = SourceLocation());
772
773 /// Set the warning-as-error flag for the given diagnostic group.
774 ///
775 /// This function always only operates on the current diagnostic state.
776 ///
777 /// \returns True if the given group is unknown, false otherwise.
778 bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled);
779
780 /// Set the error-as-fatal flag for the given diagnostic group.
781 ///
782 /// This function always only operates on the current diagnostic state.
783 ///
784 /// \returns True if the given group is unknown, false otherwise.
785 bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled);
786
787 /// Add the specified mapping to all diagnostics of the specified
788 /// flavor.
789 ///
790 /// Mainly to be used by -Wno-everything to disable all warnings but allow
791 /// subsequent -W options to enable specific warnings.
792 void setSeverityForAll(diag::Flavor Flavor, diag::Severity Map,
793 SourceLocation Loc = SourceLocation());
794
795 bool hasErrorOccurred() const { return ErrorOccurred; }
796
797 /// Errors that actually prevent compilation, not those that are
798 /// upgraded from a warning by -Werror.
799 bool hasUncompilableErrorOccurred() const {
800 return UncompilableErrorOccurred;
801 }
802 bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
803
804 /// Determine whether any kind of unrecoverable error has occurred.
805 bool hasUnrecoverableErrorOccurred() const {
806 return FatalErrorOccurred || UnrecoverableErrorOccurred;
807 }
808
809 unsigned getNumWarnings() const { return NumWarnings; }
810
811 void setNumWarnings(unsigned NumWarnings) {
812 this->NumWarnings = NumWarnings;
813 }
814
815 /// Return an ID for a diagnostic with the specified format string and
816 /// level.
817 ///
818 /// If this is the first request for this diagnostic, it is registered and
819 /// created, otherwise the existing ID is returned.
820 ///
821 /// \param FormatString A fixed diagnostic format string that will be hashed
822 /// and mapped to a unique DiagID.
823 template <unsigned N>
824 unsigned getCustomDiagID(Level L, const char (&FormatString)[N]) {
825 return Diags->getCustomDiagID((DiagnosticIDs::Level)L,
826 StringRef(FormatString, N - 1));
827 }
828
829 /// Converts a diagnostic argument (as an intptr_t) into the string
830 /// that represents it.
831 void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
832 StringRef Modifier, StringRef Argument,
833 ArrayRef<ArgumentValue> PrevArgs,
834 SmallVectorImpl<char> &Output,
835 ArrayRef<intptr_t> QualTypeVals) const {
836 ArgToStringFn(Kind, Val, Modifier, Argument, PrevArgs, Output,
837 ArgToStringCookie, QualTypeVals);
838 }
839
840 void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
841 ArgToStringFn = Fn;
842 ArgToStringCookie = Cookie;
843 }
844
845 /// Note that the prior diagnostic was emitted by some other
846 /// \c DiagnosticsEngine, and we may be attaching a note to that diagnostic.
847 void notePriorDiagnosticFrom(const DiagnosticsEngine &Other) {
848 LastDiagLevel = Other.LastDiagLevel;
849 }
850
851 /// Reset the state of the diagnostic object to its initial
852 /// configuration.
853 void Reset();
854
855 //===--------------------------------------------------------------------===//
856 // DiagnosticsEngine classification and reporting interfaces.
857 //
858
859 /// Determine whether the diagnostic is known to be ignored.
860 ///
861 /// This can be used to opportunistically avoid expensive checks when it's
862 /// known for certain that the diagnostic has been suppressed at the
863 /// specified location \p Loc.
864 ///
865 /// \param Loc The source location we are interested in finding out the
866 /// diagnostic state. Can be null in order to query the latest state.
867 bool isIgnored(unsigned DiagID, SourceLocation Loc) const {
868 return Diags->getDiagnosticSeverity(DiagID, Loc, *this) ==
869 diag::Severity::Ignored;
870 }
871
872 /// Based on the way the client configured the DiagnosticsEngine
873 /// object, classify the specified diagnostic ID into a Level, consumable by
874 /// the DiagnosticConsumer.
875 ///
876 /// To preserve invariant assumptions, this function should not be used to
877 /// influence parse or semantic analysis actions. Instead consider using
878 /// \c isIgnored().
879 ///
880 /// \param Loc The source location we are interested in finding out the
881 /// diagnostic state. Can be null in order to query the latest state.
882 Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const {
883 return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this);
884 }
885
886 /// Issue the message to the client.
887 ///
888 /// This actually returns an instance of DiagnosticBuilder which emits the
889 /// diagnostics (through @c ProcessDiag) when it is destroyed.
890 ///
891 /// \param DiagID A member of the @c diag::kind enum.
892 /// \param Loc Represents the source location associated with the diagnostic,
893 /// which can be an invalid location if no position information is available.
894 inline DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID);
895 inline DiagnosticBuilder Report(unsigned DiagID);
896
897 void Report(const StoredDiagnostic &storedDiag);
898
899 /// Determine whethere there is already a diagnostic in flight.
900 bool isDiagnosticInFlight() const {
901 return CurDiagID != std::numeric_limits<unsigned>::max();
902 }
903
904 /// Set the "delayed" diagnostic that will be emitted once
905 /// the current diagnostic completes.
906 ///
907 /// If a diagnostic is already in-flight but the front end must
908 /// report a problem (e.g., with an inconsistent file system
909 /// state), this routine sets a "delayed" diagnostic that will be
910 /// emitted after the current diagnostic completes. This should
911 /// only be used for fatal errors detected at inconvenient
912 /// times. If emitting a delayed diagnostic causes a second delayed
913 /// diagnostic to be introduced, that second delayed diagnostic
914 /// will be ignored.
915 ///
916 /// \param DiagID The ID of the diagnostic being delayed.
917 ///
918 /// \param Arg1 A string argument that will be provided to the
919 /// diagnostic. A copy of this string will be stored in the
920 /// DiagnosticsEngine object itself.
921 ///
922 /// \param Arg2 A string argument that will be provided to the
923 /// diagnostic. A copy of this string will be stored in the
924 /// DiagnosticsEngine object itself.
925 ///
926 /// \param Arg3 A string argument that will be provided to the
927 /// diagnostic. A copy of this string will be stored in the
928 /// DiagnosticsEngine object itself.
929 void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "",
930 StringRef Arg2 = "", StringRef Arg3 = "");
931
932 /// Clear out the current diagnostic.
933 void Clear() { CurDiagID = std::numeric_limits<unsigned>::max(); }
934
935 /// Return the value associated with this diagnostic flag.
936 StringRef getFlagValue() const { return FlagValue; }
937
938private:
939 // This is private state used by DiagnosticBuilder. We put it here instead of
940 // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
941 // object. This implementation choice means that we can only have one
942 // diagnostic "in flight" at a time, but this seems to be a reasonable
943 // tradeoff to keep these objects small. Assertions verify that only one
944 // diagnostic is in flight at a time.
945 friend class Diagnostic;
946 friend class DiagnosticBuilder;
947 friend class DiagnosticErrorTrap;
948 friend class DiagnosticIDs;
949 friend class PartialDiagnostic;
950
951 /// Report the delayed diagnostic.
952 void ReportDelayed();
953
954 /// The location of the current diagnostic that is in flight.
955 SourceLocation CurDiagLoc;
956
957 /// The ID of the current diagnostic that is in flight.
958 ///
959 /// This is set to std::numeric_limits<unsigned>::max() when there is no
960 /// diagnostic in flight.
961 unsigned CurDiagID;
962
963 enum {
964 /// The maximum number of arguments we can hold.
965 ///
966 /// We currently only support up to 10 arguments (%0-%9). A single
967 /// diagnostic with more than that almost certainly has to be simplified
968 /// anyway.
969 MaxArguments = DiagnosticStorage::MaxArguments,
970 };
971
972 DiagnosticStorage DiagStorage;
973
974 DiagnosticMapping makeUserMapping(diag::Severity Map, SourceLocation L) {
975 bool isPragma = L.isValid();
976 DiagnosticMapping Mapping =
977 DiagnosticMapping::Make(Map, /*IsUser=*/true, isPragma);
978
979 // If this is a pragma mapping, then set the diagnostic mapping flags so
980 // that we override command line options.
981 if (isPragma) {
982 Mapping.setNoWarningAsError(true);
983 Mapping.setNoErrorAsFatal(true);
984 }
985
986 return Mapping;
987 }
988
989 /// Used to report a diagnostic that is finally fully formed.
990 ///
991 /// \returns true if the diagnostic was emitted, false if it was suppressed.
992 bool ProcessDiag() {
993 return Diags->ProcessDiag(*this);
994 }
995
996 /// @name Diagnostic Emission
997 /// @{
998protected:
999 friend class ASTReader;
1000 friend class ASTWriter;
1001
1002 // Sema requires access to the following functions because the current design
1003 // of SFINAE requires it to use its own SemaDiagnosticBuilder, which needs to
1004 // access us directly to ensure we minimize the emitted code for the common
1005 // Sema::Diag() patterns.
1006 friend class Sema;
1007
1008 /// Emit the current diagnostic and clear the diagnostic state.
1009 ///
1010 /// \param Force Emit the diagnostic regardless of suppression settings.
1011 bool EmitCurrentDiagnostic(bool Force = false);
1012
1013 unsigned getCurrentDiagID() const { return CurDiagID; }
1014
1015 SourceLocation getCurrentDiagLoc() const { return CurDiagLoc; }
1016
1017 /// @}
1018};
1019
1020/// RAII class that determines when any errors have occurred
1021/// between the time the instance was created and the time it was
1022/// queried.
1023///
1024/// Note that you almost certainly do not want to use this. It's usually
1025/// meaningless to ask whether a particular scope triggered an error message,
1026/// because error messages outside that scope can mark things invalid (or cause
1027/// us to reach an error limit), which can suppress errors within that scope.
1028class DiagnosticErrorTrap {
1029 DiagnosticsEngine &Diag;
1030 unsigned NumErrors;
1031 unsigned NumUnrecoverableErrors;
1032
1033public:
1034 explicit DiagnosticErrorTrap(DiagnosticsEngine &Diag)
1035 : Diag(Diag) { reset(); }
1036
1037 /// Determine whether any errors have occurred since this
1038 /// object instance was created.
1039 bool hasErrorOccurred() const {
1040 return Diag.TrapNumErrorsOccurred > NumErrors;
1041 }
1042
1043 /// Determine whether any unrecoverable errors have occurred since this
1044 /// object instance was created.
1045 bool hasUnrecoverableErrorOccurred() const {
1046 return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors;
1047 }
1048
1049 /// Set to initial state of "no errors occurred".
1050 void reset() {
1051 NumErrors = Diag.TrapNumErrorsOccurred;
1052 NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred;
1053 }
1054};
1055
1056/// The streaming interface shared between DiagnosticBuilder and
1057/// PartialDiagnostic. This class is not intended to be constructed directly
1058/// but only as base class of DiagnosticBuilder and PartialDiagnostic builder.
1059///
1060/// Any new type of argument accepted by DiagnosticBuilder and PartialDiagnostic
1061/// should be implemented as a '<<' operator of StreamingDiagnostic, e.g.
1062///
1063/// const StreamingDiagnostic&
1064/// operator<<(const StreamingDiagnostic&, NewArgType);
1065///
1066class StreamingDiagnostic {
1067public:
1068 /// An allocator for DiagnosticStorage objects, which uses a small cache to
1069 /// objects, used to reduce malloc()/free() traffic for partial diagnostics.
1070 class DiagStorageAllocator {
1071 static const unsigned NumCached = 16;
1072 DiagnosticStorage Cached[NumCached];
1073 DiagnosticStorage *FreeList[NumCached];
1074 unsigned NumFreeListEntries;
1075
1076 public:
1077 DiagStorageAllocator();
1078 ~DiagStorageAllocator();
1079
1080 /// Allocate new storage.
1081 DiagnosticStorage *Allocate() {
1082 if (NumFreeListEntries == 0)
1083 return new DiagnosticStorage;
1084
1085 DiagnosticStorage *Result = FreeList[--NumFreeListEntries];
1086 Result->NumDiagArgs = 0;
1087 Result->DiagRanges.clear();
1088 Result->FixItHints.clear();
1089 return Result;
1090 }
1091
1092 /// Free the given storage object.
1093 void Deallocate(DiagnosticStorage *S) {
1094 if (S >= Cached && S <= Cached + NumCached) {
33
Assuming 'S' is < field 'Cached'
1095 FreeList[NumFreeListEntries++] = S;
1096 return;
1097 }
1098
1099 delete S;
34
Memory is released
1100 }
1101 };
1102
1103protected:
1104 mutable DiagnosticStorage *DiagStorage = nullptr;
1105
1106 /// Allocator used to allocate storage for this diagnostic.
1107 DiagStorageAllocator *Allocator = nullptr;
1108
1109public:
1110 /// Retrieve storage for this particular diagnostic.
1111 DiagnosticStorage *getStorage() const {
1112 if (DiagStorage)
1113 return DiagStorage;
1114
1115 assert(Allocator)((Allocator) ? static_cast<void> (0) : __assert_fail ("Allocator"
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1115, __PRETTY_FUNCTION__))
;
1116 DiagStorage = Allocator->Allocate();
1117 return DiagStorage;
1118 }
1119
1120 void freeStorage() {
1121 if (!DiagStorage)
27
Assuming field 'DiagStorage' is non-null
28
Taking false branch
1122 return;
1123
1124 // The hot path for PartialDiagnostic is when we just used it to wrap an ID
1125 // (typically so we have the flexibility of passing a more complex
1126 // diagnostic into the callee, but that does not commonly occur).
1127 //
1128 // Split this out into a slow function for silly compilers (*cough*) which
1129 // can't do decent partial inlining.
1130 freeStorageSlow();
29
Calling 'StreamingDiagnostic::freeStorageSlow'
36
Returning; memory was released
1131 }
1132
1133 void freeStorageSlow() {
1134 if (!Allocator)
30
Assuming field 'Allocator' is non-null
31
Taking false branch
1135 return;
1136 Allocator->Deallocate(DiagStorage);
32
Calling 'DiagStorageAllocator::Deallocate'
35
Returning; memory was released via 1st parameter
1137 DiagStorage = nullptr;
1138 }
1139
1140 void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
1141 if (!DiagStorage
45.1
Field 'DiagStorage' is non-null
45.1
Field 'DiagStorage' is non-null
)
46
Taking false branch
1142 DiagStorage = getStorage();
1143
1144 assert(DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments &&((DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments
&& "Too many arguments to diagnostic!") ? static_cast
<void> (0) : __assert_fail ("DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1145, __PRETTY_FUNCTION__))
47
Use of memory after it is freed
1145 "Too many arguments to diagnostic!")((DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments
&& "Too many arguments to diagnostic!") ? static_cast
<void> (0) : __assert_fail ("DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1145, __PRETTY_FUNCTION__))
;
1146 DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] = Kind;
1147 DiagStorage->DiagArgumentsVal[DiagStorage->NumDiagArgs++] = V;
1148 }
1149
1150 void AddString(StringRef V) const {
1151 if (!DiagStorage)
1152 DiagStorage = getStorage();
1153
1154 assert(DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments &&((DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments
&& "Too many arguments to diagnostic!") ? static_cast
<void> (0) : __assert_fail ("DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1155, __PRETTY_FUNCTION__))
1155 "Too many arguments to diagnostic!")((DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments
&& "Too many arguments to diagnostic!") ? static_cast
<void> (0) : __assert_fail ("DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1155, __PRETTY_FUNCTION__))
;
1156 DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] =
1157 DiagnosticsEngine::ak_std_string;
1158 DiagStorage->DiagArgumentsStr[DiagStorage->NumDiagArgs++] = std::string(V);
1159 }
1160
1161 void AddSourceRange(const CharSourceRange &R) const {
1162 if (!DiagStorage)
1163 DiagStorage = getStorage();
1164
1165 DiagStorage->DiagRanges.push_back(R);
1166 }
1167
1168 void AddFixItHint(const FixItHint &Hint) const {
1169 if (Hint.isNull())
1170 return;
1171
1172 if (!DiagStorage)
1173 DiagStorage = getStorage();
1174
1175 DiagStorage->FixItHints.push_back(Hint);
1176 }
1177
1178 /// Conversion of StreamingDiagnostic to bool always returns \c true.
1179 ///
1180 /// This allows is to be used in boolean error contexts (where \c true is
1181 /// used to indicate that an error has occurred), like:
1182 /// \code
1183 /// return Diag(...);
1184 /// \endcode
1185 operator bool() const { return true; }
1186
1187protected:
1188 StreamingDiagnostic() = default;
1189
1190 /// Construct with an external storage not owned by itself. The allocator
1191 /// is a null pointer in this case.
1192 explicit StreamingDiagnostic(DiagnosticStorage *Storage)
1193 : DiagStorage(Storage) {}
1194
1195 /// Construct with a storage allocator which will manage the storage. The
1196 /// allocator is not a null pointer in this case.
1197 explicit StreamingDiagnostic(DiagStorageAllocator &Alloc)
1198 : Allocator(&Alloc) {}
1199
1200 StreamingDiagnostic(const StreamingDiagnostic &Diag) = default;
1201 StreamingDiagnostic(StreamingDiagnostic &&Diag) = default;
1202
1203 ~StreamingDiagnostic() { freeStorage(); }
26
Calling 'StreamingDiagnostic::freeStorage'
37
Returning; memory was released
1204};
1205
1206//===----------------------------------------------------------------------===//
1207// DiagnosticBuilder
1208//===----------------------------------------------------------------------===//
1209
1210/// A little helper class used to produce diagnostics.
1211///
1212/// This is constructed by the DiagnosticsEngine::Report method, and
1213/// allows insertion of extra information (arguments and source ranges) into
1214/// the currently "in flight" diagnostic. When the temporary for the builder
1215/// is destroyed, the diagnostic is issued.
1216///
1217/// Note that many of these will be created as temporary objects (many call
1218/// sites), so we want them to be small and we never want their address taken.
1219/// This ensures that compilers with somewhat reasonable optimizers will promote
1220/// the common fields to registers, eliminating increments of the NumArgs field,
1221/// for example.
1222class DiagnosticBuilder : public StreamingDiagnostic {
1223 friend class DiagnosticsEngine;
1224 friend class PartialDiagnostic;
1225
1226 mutable DiagnosticsEngine *DiagObj = nullptr;
1227
1228 /// Status variable indicating if this diagnostic is still active.
1229 ///
1230 // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj == 0)),
1231 // but LLVM is not currently smart enough to eliminate the null check that
1232 // Emit() would end up with if we used that as our status variable.
1233 mutable bool IsActive = false;
1234
1235 /// Flag indicating that this diagnostic is being emitted via a
1236 /// call to ForceEmit.
1237 mutable bool IsForceEmit = false;
1238
1239 DiagnosticBuilder() = default;
1240
1241 explicit DiagnosticBuilder(DiagnosticsEngine *diagObj)
1242 : StreamingDiagnostic(&diagObj->DiagStorage), DiagObj(diagObj),
1243 IsActive(true) {
1244 assert(diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!")((diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!"
) ? static_cast<void> (0) : __assert_fail ("diagObj && \"DiagnosticBuilder requires a valid DiagnosticsEngine!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1244, __PRETTY_FUNCTION__))
;
1245 assert(DiagStorage &&((DiagStorage && "DiagnosticBuilder requires a valid DiagnosticStorage!"
) ? static_cast<void> (0) : __assert_fail ("DiagStorage && \"DiagnosticBuilder requires a valid DiagnosticStorage!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1246, __PRETTY_FUNCTION__))
1246 "DiagnosticBuilder requires a valid DiagnosticStorage!")((DiagStorage && "DiagnosticBuilder requires a valid DiagnosticStorage!"
) ? static_cast<void> (0) : __assert_fail ("DiagStorage && \"DiagnosticBuilder requires a valid DiagnosticStorage!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1246, __PRETTY_FUNCTION__))
;
1247 DiagStorage->NumDiagArgs = 0;
1248 DiagStorage->DiagRanges.clear();
1249 DiagStorage->FixItHints.clear();
1250 }
1251
1252protected:
1253 /// Clear out the current diagnostic.
1254 void Clear() const {
1255 DiagObj = nullptr;
1256 IsActive = false;
1257 IsForceEmit = false;
1258 }
1259
1260 /// Determine whether this diagnostic is still active.
1261 bool isActive() const { return IsActive; }
1262
1263 /// Force the diagnostic builder to emit the diagnostic now.
1264 ///
1265 /// Once this function has been called, the DiagnosticBuilder object
1266 /// should not be used again before it is destroyed.
1267 ///
1268 /// \returns true if a diagnostic was emitted, false if the
1269 /// diagnostic was suppressed.
1270 bool Emit() {
1271 // If this diagnostic is inactive, then its soul was stolen by the copy ctor
1272 // (or by a subclass, as in SemaDiagnosticBuilder).
1273 if (!isActive()) return false;
1274
1275 // Process the diagnostic.
1276 bool Result = DiagObj->EmitCurrentDiagnostic(IsForceEmit);
1277
1278 // This diagnostic is dead.
1279 Clear();
1280
1281 return Result;
1282 }
1283
1284public:
1285 /// Copy constructor. When copied, this "takes" the diagnostic info from the
1286 /// input and neuters it.
1287 DiagnosticBuilder(const DiagnosticBuilder &D) : StreamingDiagnostic() {
1288 DiagObj = D.DiagObj;
1289 DiagStorage = D.DiagStorage;
1290 IsActive = D.IsActive;
1291 IsForceEmit = D.IsForceEmit;
1292 D.Clear();
1293 }
1294
1295 template <typename T> const DiagnosticBuilder &operator<<(const T &V) const {
1296 assert(isActive() && "Clients must not add to cleared diagnostic!")((isActive() && "Clients must not add to cleared diagnostic!"
) ? static_cast<void> (0) : __assert_fail ("isActive() && \"Clients must not add to cleared diagnostic!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1296, __PRETTY_FUNCTION__))
;
1297 const StreamingDiagnostic &DB = *this;
1298 DB << V;
1299 return *this;
1300 }
1301
1302 // It is necessary to limit this to rvalue reference to avoid calling this
1303 // function with a bitfield lvalue argument since non-const reference to
1304 // bitfield is not allowed.
1305 template <typename T, typename = typename std::enable_if<
1306 !std::is_lvalue_reference<T>::value>::type>
1307 const DiagnosticBuilder &operator<<(T &&V) const {
1308 assert(isActive() && "Clients must not add to cleared diagnostic!")((isActive() && "Clients must not add to cleared diagnostic!"
) ? static_cast<void> (0) : __assert_fail ("isActive() && \"Clients must not add to cleared diagnostic!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1308, __PRETTY_FUNCTION__))
;
42
Assuming the condition is true
43
'?' condition is true
1309 const StreamingDiagnostic &DB = *this;
1310 DB << std::move(V);
44
Calling 'operator<<'
1311 return *this;
1312 }
1313
1314 DiagnosticBuilder &operator=(const DiagnosticBuilder &) = delete;
1315
1316 /// Emits the diagnostic.
1317 ~DiagnosticBuilder() { Emit(); }
25
Calling '~StreamingDiagnostic'
38
Returning from '~StreamingDiagnostic'
1318
1319 /// Forces the diagnostic to be emitted.
1320 const DiagnosticBuilder &setForceEmit() const {
1321 IsForceEmit = true;
1322 return *this;
1323 }
1324
1325 void addFlagValue(StringRef V) const { DiagObj->FlagValue = std::string(V); }
1326};
1327
1328struct AddFlagValue {
1329 StringRef Val;
1330
1331 explicit AddFlagValue(StringRef V) : Val(V) {}
1332};
1333
1334/// Register a value for the flag in the current diagnostic. This
1335/// value will be shown as the suffix "=value" after the flag name. It is
1336/// useful in cases where the diagnostic flag accepts values (e.g.,
1337/// -Rpass or -Wframe-larger-than).
1338inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1339 const AddFlagValue V) {
1340 DB.addFlagValue(V.Val);
1341 return DB;
1342}
1343
1344inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1345 StringRef S) {
1346 DB.AddString(S);
1347 return DB;
1348}
1349
1350inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1351 const char *Str) {
1352 DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
1353 DiagnosticsEngine::ak_c_string);
1354 return DB;
1355}
1356
1357inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1358 int I) {
1359 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1360 return DB;
1361}
1362
1363// We use enable_if here to prevent that this overload is selected for
1364// pointers or other arguments that are implicitly convertible to bool.
1365template <typename T>
1366inline std::enable_if_t<std::is_same<T, bool>::value,
1367 const StreamingDiagnostic &>
1368operator<<(const StreamingDiagnostic &DB, T I) {
1369 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1370 return DB;
1371}
1372
1373inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1374 unsigned I) {
1375 DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
1376 return DB;
1377}
1378
1379inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1380 tok::TokenKind I) {
1381 DB.AddTaggedVal(static_cast<unsigned>(I), DiagnosticsEngine::ak_tokenkind);
45
Calling 'StreamingDiagnostic::AddTaggedVal'
1382 return DB;
1383}
1384
1385inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1386 const IdentifierInfo *II) {
1387 DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
1388 DiagnosticsEngine::ak_identifierinfo);
1389 return DB;
1390}
1391
1392// Adds a DeclContext to the diagnostic. The enable_if template magic is here
1393// so that we only match those arguments that are (statically) DeclContexts;
1394// other arguments that derive from DeclContext (e.g., RecordDecls) will not
1395// match.
1396template <typename T>
1397inline std::enable_if_t<
1398 std::is_same<std::remove_const_t<T>, DeclContext>::value,
1399 const StreamingDiagnostic &>
1400operator<<(const StreamingDiagnostic &DB, T *DC) {
1401 DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
1402 DiagnosticsEngine::ak_declcontext);
1403 return DB;
1404}
1405
1406inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1407 SourceRange R) {
1408 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1409 return DB;
1410}
1411
1412inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1413 ArrayRef<SourceRange> Ranges) {
1414 for (SourceRange R : Ranges)
1415 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1416 return DB;
1417}
1418
1419inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1420 const CharSourceRange &R) {
1421 DB.AddSourceRange(R);
1422 return DB;
1423}
1424
1425inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1426 const FixItHint &Hint) {
1427 DB.AddFixItHint(Hint);
1428 return DB;
1429}
1430
1431inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1432 ArrayRef<FixItHint> Hints) {
1433 for (const FixItHint &Hint : Hints)
1434 DB.AddFixItHint(Hint);
1435 return DB;
1436}
1437
1438inline const StreamingDiagnostic &
1439operator<<(const StreamingDiagnostic &DB,
1440 const llvm::Optional<SourceRange> &Opt) {
1441 if (Opt)
1442 DB << *Opt;
1443 return DB;
1444}
1445
1446inline const StreamingDiagnostic &
1447operator<<(const StreamingDiagnostic &DB,
1448 const llvm::Optional<CharSourceRange> &Opt) {
1449 if (Opt)
1450 DB << *Opt;
1451 return DB;
1452}
1453
1454inline const StreamingDiagnostic &
1455operator<<(const StreamingDiagnostic &DB,
1456 const llvm::Optional<FixItHint> &Opt) {
1457 if (Opt)
1458 DB << *Opt;
1459 return DB;
1460}
1461
1462/// A nullability kind paired with a bit indicating whether it used a
1463/// context-sensitive keyword.
1464using DiagNullabilityKind = std::pair<NullabilityKind, bool>;
1465
1466const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1467 DiagNullabilityKind nullability);
1468
1469inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
1470 unsigned DiagID) {
1471 assert(CurDiagID == std::numeric_limits<unsigned>::max() &&((CurDiagID == std::numeric_limits<unsigned>::max() &&
"Multiple diagnostics in flight at once!") ? static_cast<
void> (0) : __assert_fail ("CurDiagID == std::numeric_limits<unsigned>::max() && \"Multiple diagnostics in flight at once!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1472, __PRETTY_FUNCTION__))
1472 "Multiple diagnostics in flight at once!")((CurDiagID == std::numeric_limits<unsigned>::max() &&
"Multiple diagnostics in flight at once!") ? static_cast<
void> (0) : __assert_fail ("CurDiagID == std::numeric_limits<unsigned>::max() && \"Multiple diagnostics in flight at once!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1472, __PRETTY_FUNCTION__))
;
1473 CurDiagLoc = Loc;
1474 CurDiagID = DiagID;
1475 FlagValue.clear();
1476 return DiagnosticBuilder(this);
1477}
1478
1479const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1480 llvm::Error &&E);
1481
1482inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
1483 return Report(SourceLocation(), DiagID);
1484}
1485
1486//===----------------------------------------------------------------------===//
1487// Diagnostic
1488//===----------------------------------------------------------------------===//
1489
1490/// A little helper class (which is basically a smart pointer that forwards
1491/// info from DiagnosticsEngine) that allows clients to enquire about the
1492/// currently in-flight diagnostic.
1493class Diagnostic {
1494 const DiagnosticsEngine *DiagObj;
1495 StringRef StoredDiagMessage;
1496
1497public:
1498 explicit Diagnostic(const DiagnosticsEngine *DO) : DiagObj(DO) {}
1499 Diagnostic(const DiagnosticsEngine *DO, StringRef storedDiagMessage)
1500 : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {}
1501
1502 const DiagnosticsEngine *getDiags() const { return DiagObj; }
1503 unsigned getID() const { return DiagObj->CurDiagID; }
1504 const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
1505 bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
1506 SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
1507
1508 unsigned getNumArgs() const { return DiagObj->DiagStorage.NumDiagArgs; }
1509
1510 /// Return the kind of the specified index.
1511 ///
1512 /// Based on the kind of argument, the accessors below can be used to get
1513 /// the value.
1514 ///
1515 /// \pre Idx < getNumArgs()
1516 DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const {
1517 assert(Idx < getNumArgs() && "Argument index out of range!")((Idx < getNumArgs() && "Argument index out of range!"
) ? static_cast<void> (0) : __assert_fail ("Idx < getNumArgs() && \"Argument index out of range!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1517, __PRETTY_FUNCTION__))
;
1518 return (DiagnosticsEngine::ArgumentKind)
1519 DiagObj->DiagStorage.DiagArgumentsKind[Idx];
1520 }
1521
1522 /// Return the provided argument string specified by \p Idx.
1523 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string
1524 const std::string &getArgStdStr(unsigned Idx) const {
1525 assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&((getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&
"invalid argument accessor!") ? static_cast<void> (0) :
__assert_fail ("getArgKind(Idx) == DiagnosticsEngine::ak_std_string && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1526, __PRETTY_FUNCTION__))
1526 "invalid argument accessor!")((getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&
"invalid argument accessor!") ? static_cast<void> (0) :
__assert_fail ("getArgKind(Idx) == DiagnosticsEngine::ak_std_string && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1526, __PRETTY_FUNCTION__))
;
1527 return DiagObj->DiagStorage.DiagArgumentsStr[Idx];
1528 }
1529
1530 /// Return the specified C string argument.
1531 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string
1532 const char *getArgCStr(unsigned Idx) const {
1533 assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&((getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&
"invalid argument accessor!") ? static_cast<void> (0) :
__assert_fail ("getArgKind(Idx) == DiagnosticsEngine::ak_c_string && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1534, __PRETTY_FUNCTION__))
1534 "invalid argument accessor!")((getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&
"invalid argument accessor!") ? static_cast<void> (0) :
__assert_fail ("getArgKind(Idx) == DiagnosticsEngine::ak_c_string && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1534, __PRETTY_FUNCTION__))
;
1535 return reinterpret_cast<const char *>(
1536 DiagObj->DiagStorage.DiagArgumentsVal[Idx]);
1537 }
1538
1539 /// Return the specified signed integer argument.
1540 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint
1541 int getArgSInt(unsigned Idx) const {
1542 assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&((getArgKind(Idx) == DiagnosticsEngine::ak_sint && "invalid argument accessor!"
) ? static_cast<void> (0) : __assert_fail ("getArgKind(Idx) == DiagnosticsEngine::ak_sint && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1543, __PRETTY_FUNCTION__))
1543 "invalid argument accessor!")((getArgKind(Idx) == DiagnosticsEngine::ak_sint && "invalid argument accessor!"
) ? static_cast<void> (0) : __assert_fail ("getArgKind(Idx) == DiagnosticsEngine::ak_sint && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1543, __PRETTY_FUNCTION__))
;
1544 return (int)DiagObj->DiagStorage.DiagArgumentsVal[Idx];
1545 }
1546
1547 /// Return the specified unsigned integer argument.
1548 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint
1549 unsigned getArgUInt(unsigned Idx) const {
1550 assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&((getArgKind(Idx) == DiagnosticsEngine::ak_uint && "invalid argument accessor!"
) ? static_cast<void> (0) : __assert_fail ("getArgKind(Idx) == DiagnosticsEngine::ak_uint && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1551, __PRETTY_FUNCTION__))
1551 "invalid argument accessor!")((getArgKind(Idx) == DiagnosticsEngine::ak_uint && "invalid argument accessor!"
) ? static_cast<void> (0) : __assert_fail ("getArgKind(Idx) == DiagnosticsEngine::ak_uint && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1551, __PRETTY_FUNCTION__))
;
1552 return (unsigned)DiagObj->DiagStorage.DiagArgumentsVal[Idx];
1553 }
1554
1555 /// Return the specified IdentifierInfo argument.
1556 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo
1557 const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
1558 assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&((getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&
"invalid argument accessor!") ? static_cast<void> (0) :
__assert_fail ("getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1559, __PRETTY_FUNCTION__))
1559 "invalid argument accessor!")((getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&
"invalid argument accessor!") ? static_cast<void> (0) :
__assert_fail ("getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1559, __PRETTY_FUNCTION__))
;
1560 return reinterpret_cast<IdentifierInfo *>(
1561 DiagObj->DiagStorage.DiagArgumentsVal[Idx]);
1562 }
1563
1564 /// Return the specified non-string argument in an opaque form.
1565 /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string
1566 intptr_t getRawArg(unsigned Idx) const {
1567 assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&((getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&
"invalid argument accessor!") ? static_cast<void> (0) :
__assert_fail ("getArgKind(Idx) != DiagnosticsEngine::ak_std_string && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1568, __PRETTY_FUNCTION__))
1568 "invalid argument accessor!")((getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&
"invalid argument accessor!") ? static_cast<void> (0) :
__assert_fail ("getArgKind(Idx) != DiagnosticsEngine::ak_std_string && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1568, __PRETTY_FUNCTION__))
;
1569 return DiagObj->DiagStorage.DiagArgumentsVal[Idx];
1570 }
1571
1572 /// Return the number of source ranges associated with this diagnostic.
1573 unsigned getNumRanges() const {
1574 return DiagObj->DiagStorage.DiagRanges.size();
1575 }
1576
1577 /// \pre Idx < getNumRanges()
1578 const CharSourceRange &getRange(unsigned Idx) const {
1579 assert(Idx < getNumRanges() && "Invalid diagnostic range index!")((Idx < getNumRanges() && "Invalid diagnostic range index!"
) ? static_cast<void> (0) : __assert_fail ("Idx < getNumRanges() && \"Invalid diagnostic range index!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1579, __PRETTY_FUNCTION__))
;
1580 return DiagObj->DiagStorage.DiagRanges[Idx];
1581 }
1582
1583 /// Return an array reference for this diagnostic's ranges.
1584 ArrayRef<CharSourceRange> getRanges() const {
1585 return DiagObj->DiagStorage.DiagRanges;
1586 }
1587
1588 unsigned getNumFixItHints() const {
1589 return DiagObj->DiagStorage.FixItHints.size();
1590 }
1591
1592 const FixItHint &getFixItHint(unsigned Idx) const {
1593 assert(Idx < getNumFixItHints() && "Invalid index!")((Idx < getNumFixItHints() && "Invalid index!") ? static_cast
<void> (0) : __assert_fail ("Idx < getNumFixItHints() && \"Invalid index!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Basic/Diagnostic.h"
, 1593, __PRETTY_FUNCTION__))
;
1594 return DiagObj->DiagStorage.FixItHints[Idx];
1595 }
1596
1597 ArrayRef<FixItHint> getFixItHints() const {
1598 return DiagObj->DiagStorage.FixItHints;
1599 }
1600
1601 /// Format this diagnostic into a string, substituting the
1602 /// formal arguments into the %0 slots.
1603 ///
1604 /// The result is appended onto the \p OutStr array.
1605 void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
1606
1607 /// Format the given format-string into the output buffer using the
1608 /// arguments stored in this diagnostic.
1609 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
1610 SmallVectorImpl<char> &OutStr) const;
1611};
1612
1613/**
1614 * Represents a diagnostic in a form that can be retained until its
1615 * corresponding source manager is destroyed.
1616 */
1617class StoredDiagnostic {
1618 unsigned ID;
1619 DiagnosticsEngine::Level Level;
1620 FullSourceLoc Loc;
1621 std::string Message;
1622 std::vector<CharSourceRange> Ranges;
1623 std::vector<FixItHint> FixIts;
1624
1625public:
1626 StoredDiagnostic() = default;
1627 StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info);
1628 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1629 StringRef Message);
1630 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1631 StringRef Message, FullSourceLoc Loc,
1632 ArrayRef<CharSourceRange> Ranges,
1633 ArrayRef<FixItHint> Fixits);
1634
1635 /// Evaluates true when this object stores a diagnostic.
1636 explicit operator bool() const { return !Message.empty(); }
1637
1638 unsigned getID() const { return ID; }
1639 DiagnosticsEngine::Level getLevel() const { return Level; }
1640 const FullSourceLoc &getLocation() const { return Loc; }
1641 StringRef getMessage() const { return Message; }
1642
1643 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
1644
1645 using range_iterator = std::vector<CharSourceRange>::const_iterator;
1646
1647 range_iterator range_begin() const { return Ranges.begin(); }
1648 range_iterator range_end() const { return Ranges.end(); }
1649 unsigned range_size() const { return Ranges.size(); }
1650
1651 ArrayRef<CharSourceRange> getRanges() const {
1652 return llvm::makeArrayRef(Ranges);
1653 }
1654
1655 using fixit_iterator = std::vector<FixItHint>::const_iterator;
1656
1657 fixit_iterator fixit_begin() const { return FixIts.begin(); }
1658 fixit_iterator fixit_end() const { return FixIts.end(); }
1659 unsigned fixit_size() const { return FixIts.size(); }
1660
1661 ArrayRef<FixItHint> getFixIts() const {
1662 return llvm::makeArrayRef(FixIts);
1663 }
1664};
1665
1666/// Abstract interface, implemented by clients of the front-end, which
1667/// formats and prints fully processed diagnostics.
1668class DiagnosticConsumer {
1669protected:
1670 unsigned NumWarnings = 0; ///< Number of warnings reported
1671 unsigned NumErrors = 0; ///< Number of errors reported
1672
1673public:
1674 DiagnosticConsumer() = default;
1675 virtual ~DiagnosticConsumer();
1676
1677 unsigned getNumErrors() const { return NumErrors; }
1678 unsigned getNumWarnings() const { return NumWarnings; }
1679 virtual void clear() { NumWarnings = NumErrors = 0; }
1680
1681 /// Callback to inform the diagnostic client that processing
1682 /// of a source file is beginning.
1683 ///
1684 /// Note that diagnostics may be emitted outside the processing of a source
1685 /// file, for example during the parsing of command line options. However,
1686 /// diagnostics with source range information are required to only be emitted
1687 /// in between BeginSourceFile() and EndSourceFile().
1688 ///
1689 /// \param LangOpts The language options for the source file being processed.
1690 /// \param PP The preprocessor object being used for the source; this is
1691 /// optional, e.g., it may not be present when processing AST source files.
1692 virtual void BeginSourceFile(const LangOptions &LangOpts,
1693 const Preprocessor *PP = nullptr) {}
1694
1695 /// Callback to inform the diagnostic client that processing
1696 /// of a source file has ended.
1697 ///
1698 /// The diagnostic client should assume that any objects made available via
1699 /// BeginSourceFile() are inaccessible.
1700 virtual void EndSourceFile() {}
1701
1702 /// Callback to inform the diagnostic client that processing of all
1703 /// source files has ended.
1704 virtual void finish() {}
1705
1706 /// Indicates whether the diagnostics handled by this
1707 /// DiagnosticConsumer should be included in the number of diagnostics
1708 /// reported by DiagnosticsEngine.
1709 ///
1710 /// The default implementation returns true.
1711 virtual bool IncludeInDiagnosticCounts() const;
1712
1713 /// Handle this diagnostic, reporting it to the user or
1714 /// capturing it to a log as needed.
1715 ///
1716 /// The default implementation just keeps track of the total number of
1717 /// warnings and errors.
1718 virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1719 const Diagnostic &Info);
1720};
1721
1722/// A diagnostic client that ignores all diagnostics.
1723class IgnoringDiagConsumer : public DiagnosticConsumer {
1724 virtual void anchor();
1725
1726 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1727 const Diagnostic &Info) override {
1728 // Just ignore it.
1729 }
1730};
1731
1732/// Diagnostic consumer that forwards diagnostics along to an
1733/// existing, already-initialized diagnostic consumer.
1734///
1735class ForwardingDiagnosticConsumer : public DiagnosticConsumer {
1736 DiagnosticConsumer &Target;
1737
1738public:
1739 ForwardingDiagnosticConsumer(DiagnosticConsumer &Target) : Target(Target) {}
1740 ~ForwardingDiagnosticConsumer() override;
1741
1742 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1743 const Diagnostic &Info) override;
1744 void clear() override;
1745
1746 bool IncludeInDiagnosticCounts() const override;
1747};
1748
1749// Struct used for sending info about how a type should be printed.
1750struct TemplateDiffTypes {
1751 intptr_t FromType;
1752 intptr_t ToType;
1753 unsigned PrintTree : 1;
1754 unsigned PrintFromType : 1;
1755 unsigned ElideType : 1;
1756 unsigned ShowColors : 1;
1757
1758 // The printer sets this variable to true if the template diff was used.
1759 unsigned TemplateDiffUsed : 1;
1760};
1761
1762/// Special character that the diagnostic printer will use to toggle the bold
1763/// attribute. The character itself will be not be printed.
1764const char ToggleHighlight = 127;
1765
1766/// ProcessWarningOptions - Initialize the diagnostic client and process the
1767/// warning options specified on the command line.
1768void ProcessWarningOptions(DiagnosticsEngine &Diags,
1769 const DiagnosticOptions &Opts,
1770 bool ReportDiags = true);
1771
1772} // namespace clang
1773
1774#endif // LLVM_CLANG_BASIC_DIAGNOSTIC_H