1//===--- DiagnosticIDs.cpp - Diagnostic IDs Handling ----------------------===//
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 Diagnostic IDs-related interfaces.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Basic/DiagnosticIDs.h"
14#include "clang/Basic/AllDiagnostics.h"
15#include "clang/Basic/DiagnosticCategories.h"
16#include "clang/Basic/LangOptions.h"
17#include "clang/Basic/SourceManager.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/StringTable.h"
21#include "llvm/Support/Compiler.h"
22#include "llvm/Support/ErrorHandling.h"
23#include <map>
24#include <optional>
25using namespace clang;
26
27//===----------------------------------------------------------------------===//
28// Builtin Diagnostic information
29//===----------------------------------------------------------------------===//
30
31namespace {
32
33struct StaticDiagInfoRec;
34
35// Store the descriptions in a separate table to avoid pointers that need to
36// be relocated, and also decrease the amount of data needed on 64-bit
37// platforms. See "How To Write Shared Libraries" by Ulrich Drepper.
38struct StaticDiagInfoDescriptionStringTable {
39#define DIAG(ENUM, CLASS, DEFAULT_SEVERITY, DESC, GROUP, SFINAE, NOWERROR, \
40 SHOWINSYSHEADER, SHOWINSYSMACRO, DEFERRABLE, CATEGORY) \
41 char ENUM##_desc[sizeof(DESC)];
42#include "clang/Basic/AllDiagnosticKinds.inc"
43#undef DIAG
44};
45
46const StaticDiagInfoDescriptionStringTable StaticDiagInfoDescriptions = {
47#define DIAG(ENUM, CLASS, DEFAULT_SEVERITY, DESC, GROUP, SFINAE, NOWERROR, \
48 SHOWINSYSHEADER, SHOWINSYSMACRO, DEFERRABLE, CATEGORY) \
49 DESC,
50#include "clang/Basic/AllDiagnosticKinds.inc"
51#undef DIAG
52};
53
54extern const StaticDiagInfoRec StaticDiagInfo[];
55
56// Stored separately from StaticDiagInfoRec to pack better. Otherwise,
57// StaticDiagInfoRec would have extra padding on 64-bit platforms.
58const uint32_t StaticDiagInfoDescriptionOffsets[] = {
59#define DIAG(ENUM, CLASS, DEFAULT_SEVERITY, DESC, GROUP, SFINAE, NOWERROR, \
60 SHOWINSYSHEADER, SHOWINSYSMACRO, DEFERRABLE, CATEGORY) \
61 offsetof(StaticDiagInfoDescriptionStringTable, ENUM##_desc),
62#include "clang/Basic/AllDiagnosticKinds.inc"
63#undef DIAG
64};
65
66enum DiagnosticClass {
67 CLASS_NOTE = DiagnosticIDs::CLASS_NOTE,
68 CLASS_REMARK = DiagnosticIDs::CLASS_REMARK,
69 CLASS_WARNING = DiagnosticIDs::CLASS_WARNING,
70 CLASS_EXTENSION = DiagnosticIDs::CLASS_EXTENSION,
71 CLASS_ERROR = DiagnosticIDs::CLASS_ERROR,
72 CLASS_TRAP = DiagnosticIDs::CLASS_TRAP,
73};
74
75struct StaticDiagInfoRec {
76 uint16_t DiagID;
77 LLVM_PREFERRED_TYPE(diag::Severity)
78 uint16_t DefaultSeverity : 3;
79 LLVM_PREFERRED_TYPE(DiagnosticClass)
80 uint16_t Class : 3;
81 LLVM_PREFERRED_TYPE(DiagnosticIDs::SFINAEResponse)
82 uint16_t SFINAE : 2;
83 LLVM_PREFERRED_TYPE(diag::DiagCategory)
84 uint16_t Category : 6;
85 LLVM_PREFERRED_TYPE(bool)
86 uint16_t WarnNoWerror : 1;
87 LLVM_PREFERRED_TYPE(bool)
88 uint16_t WarnShowInSystemHeader : 1;
89 LLVM_PREFERRED_TYPE(bool)
90 uint16_t WarnShowInSystemMacro : 1;
91
92 LLVM_PREFERRED_TYPE(diag::Group)
93 uint16_t OptionGroupIndex : 15;
94 LLVM_PREFERRED_TYPE(bool)
95 uint16_t Deferrable : 1;
96
97 uint16_t DescriptionLen;
98
99 unsigned getOptionGroupIndex() const {
100 return OptionGroupIndex;
101 }
102
103 StringRef getDescription() const {
104 size_t MyIndex = this - &StaticDiagInfo[0];
105 uint32_t StringOffset = StaticDiagInfoDescriptionOffsets[MyIndex];
106 const char* Table = reinterpret_cast<const char*>(&StaticDiagInfoDescriptions);
107 return StringRef(&Table[StringOffset], DescriptionLen);
108 }
109
110 diag::Flavor getFlavor() const {
111 return Class == CLASS_REMARK ? diag::Flavor::Remark
112 : diag::Flavor::WarningOrError;
113 }
114
115 bool operator<(const StaticDiagInfoRec &RHS) const {
116 return DiagID < RHS.DiagID;
117 }
118};
119
120#define STRINGIFY_NAME(NAME) #NAME
121#define VALIDATE_DIAG_SIZE(NAME) \
122 static_assert( \
123 static_cast<unsigned>(diag::NUM_BUILTIN_##NAME##_DIAGNOSTICS) < \
124 static_cast<unsigned>(diag::DIAG_START_##NAME) + \
125 static_cast<unsigned>(diag::DIAG_SIZE_##NAME), \
126 STRINGIFY_NAME( \
127 DIAG_SIZE_##NAME) " is insufficient to contain all " \
128 "diagnostics, it may need to be made larger in " \
129 "DiagnosticIDs.h.");
130VALIDATE_DIAG_SIZE(COMMON)
131VALIDATE_DIAG_SIZE(DRIVER)
132VALIDATE_DIAG_SIZE(FRONTEND)
133VALIDATE_DIAG_SIZE(SERIALIZATION)
134VALIDATE_DIAG_SIZE(LEX)
135VALIDATE_DIAG_SIZE(PARSE)
136VALIDATE_DIAG_SIZE(AST)
137VALIDATE_DIAG_SIZE(COMMENT)
138VALIDATE_DIAG_SIZE(CROSSTU)
139VALIDATE_DIAG_SIZE(SEMA)
140VALIDATE_DIAG_SIZE(ANALYSIS)
141VALIDATE_DIAG_SIZE(REFACTORING)
142VALIDATE_DIAG_SIZE(INSTALLAPI)
143VALIDATE_DIAG_SIZE(TRAP)
144#undef VALIDATE_DIAG_SIZE
145#undef STRINGIFY_NAME
146
147const StaticDiagInfoRec StaticDiagInfo[] = {
148// clang-format off
149#define DIAG(ENUM, CLASS, DEFAULT_SEVERITY, DESC, GROUP, SFINAE, NOWERROR, \
150 SHOWINSYSHEADER, SHOWINSYSMACRO, DEFERRABLE, CATEGORY) \
151 { \
152 diag::ENUM, \
153 DEFAULT_SEVERITY, \
154 CLASS, \
155 DiagnosticIDs::SFINAE, \
156 CATEGORY, \
157 NOWERROR, \
158 SHOWINSYSHEADER, \
159 SHOWINSYSMACRO, \
160 GROUP, \
161 DEFERRABLE, \
162 STR_SIZE(DESC, uint16_t)},
163#include "clang/Basic/DiagnosticCommonKinds.inc"
164#include "clang/Basic/DiagnosticDriverKinds.inc"
165#include "clang/Basic/DiagnosticFrontendKinds.inc"
166#include "clang/Basic/DiagnosticSerializationKinds.inc"
167#include "clang/Basic/DiagnosticLexKinds.inc"
168#include "clang/Basic/DiagnosticParseKinds.inc"
169#include "clang/Basic/DiagnosticASTKinds.inc"
170#include "clang/Basic/DiagnosticCommentKinds.inc"
171#include "clang/Basic/DiagnosticCrossTUKinds.inc"
172#include "clang/Basic/DiagnosticSemaKinds.inc"
173#include "clang/Basic/DiagnosticAnalysisKinds.inc"
174#include "clang/Basic/DiagnosticRefactoringKinds.inc"
175#include "clang/Basic/DiagnosticInstallAPIKinds.inc"
176#include "clang/Basic/DiagnosticTrapKinds.inc"
177// clang-format on
178#undef DIAG
179};
180
181} // namespace
182
183static const unsigned StaticDiagInfoSize = std::size(StaticDiagInfo);
184
185/// GetDiagInfo - Return the StaticDiagInfoRec entry for the specified DiagID,
186/// or null if the ID is invalid.
187static const StaticDiagInfoRec *GetDiagInfo(unsigned DiagID) {
188 // Out of bounds diag. Can't be in the table.
189 using namespace diag;
190 if (DiagID >= DIAG_UPPER_LIMIT || DiagID <= DIAG_START_COMMON)
191 return nullptr;
192
193 // Compute the index of the requested diagnostic in the static table.
194 // 1. Add the number of diagnostics in each category preceding the
195 // diagnostic and of the category the diagnostic is in. This gives us
196 // the offset of the category in the table.
197 // 2. Subtract the number of IDs in each category from our ID. This gives us
198 // the offset of the diagnostic in the category.
199 // This is cheaper than a binary search on the table as it doesn't touch
200 // memory at all.
201 unsigned Offset = 0;
202 unsigned ID = DiagID - DIAG_START_COMMON - 1;
203#define CATEGORY(NAME, PREV) \
204 if (DiagID > DIAG_START_##NAME) { \
205 Offset += NUM_BUILTIN_##PREV##_DIAGNOSTICS - DIAG_START_##PREV - 1; \
206 ID -= DIAG_START_##NAME - DIAG_START_##PREV; \
207 }
208CATEGORY(DRIVER, COMMON)
209CATEGORY(FRONTEND, DRIVER)
210CATEGORY(SERIALIZATION, FRONTEND)
211CATEGORY(LEX, SERIALIZATION)
212CATEGORY(PARSE, LEX)
213CATEGORY(AST, PARSE)
214CATEGORY(COMMENT, AST)
215CATEGORY(CROSSTU, COMMENT)
216CATEGORY(SEMA, CROSSTU)
217CATEGORY(ANALYSIS, SEMA)
218CATEGORY(REFACTORING, ANALYSIS)
219CATEGORY(INSTALLAPI, REFACTORING)
220CATEGORY(TRAP, INSTALLAPI)
221#undef CATEGORY
222
223 // Avoid out of bounds reads.
224 if (ID + Offset >= StaticDiagInfoSize)
225 return nullptr;
226
227 assert(ID < StaticDiagInfoSize && Offset < StaticDiagInfoSize);
228
229 const StaticDiagInfoRec *Found = &StaticDiagInfo[ID + Offset];
230 // If the diag id doesn't match we found a different diag, abort. This can
231 // happen when this function is called with an ID that points into a hole in
232 // the diagID space.
233 if (Found->DiagID != DiagID)
234 return nullptr;
235 return Found;
236}
237
238//===----------------------------------------------------------------------===//
239// Custom Diagnostic information
240//===----------------------------------------------------------------------===//
241
242namespace clang {
243namespace diag {
244using CustomDiagDesc = DiagnosticIDs::CustomDiagDesc;
245class CustomDiagInfo {
246 std::vector<CustomDiagDesc> DiagInfo;
247 std::map<CustomDiagDesc, unsigned> DiagIDs;
248 std::map<diag::Group, std::vector<unsigned>> GroupToDiags;
249
250public:
251 /// getDescription - Return the description of the specified custom
252 /// diagnostic.
253 const CustomDiagDesc &getDescription(unsigned DiagID) const {
254 assert(DiagID - DIAG_UPPER_LIMIT < DiagInfo.size() &&
255 "Invalid diagnostic ID");
256 return DiagInfo[DiagID - DIAG_UPPER_LIMIT];
257 }
258
259 unsigned getOrCreateDiagID(DiagnosticIDs::CustomDiagDesc D) {
260 // Check to see if it already exists.
261 std::map<CustomDiagDesc, unsigned>::iterator I = DiagIDs.lower_bound(x: D);
262 if (I != DiagIDs.end() && I->first == D)
263 return I->second;
264
265 // If not, assign a new ID.
266 unsigned ID = DiagInfo.size() + DIAG_UPPER_LIMIT;
267 DiagIDs.insert(x: std::make_pair(x&: D, y&: ID));
268 DiagInfo.push_back(x: D);
269 if (auto Group = D.GetGroup())
270 GroupToDiags[*Group].emplace_back(args&: ID);
271 return ID;
272 }
273
274 ArrayRef<unsigned> getDiagsInGroup(diag::Group G) const {
275 if (auto Diags = GroupToDiags.find(x: G); Diags != GroupToDiags.end())
276 return Diags->second;
277 return {};
278 }
279};
280
281} // namespace diag
282} // namespace clang
283
284DiagnosticMapping DiagnosticIDs::getDefaultMapping(unsigned DiagID) const {
285 DiagnosticMapping Info = DiagnosticMapping::Make(
286 Severity: diag::Severity::Fatal, /*IsUser=*/false, /*IsPragma=*/false);
287
288 if (IsCustomDiag(Diag: DiagID)) {
289 Info.setSeverity(
290 CustomDiagInfo->getDescription(DiagID).GetDefaultSeverity());
291 } else if (const StaticDiagInfoRec *StaticInfo = GetDiagInfo(DiagID)) {
292 Info.setSeverity((diag::Severity)StaticInfo->DefaultSeverity);
293
294 if (StaticInfo->WarnNoWerror) {
295 assert(Info.getSeverity() == diag::Severity::Warning &&
296 "Unexpected mapping with no-Werror bit!");
297 Info.setNoWarningAsError(true);
298 }
299 }
300
301 return Info;
302}
303
304void DiagnosticIDs::initCustomDiagMapping(DiagnosticMapping &Mapping,
305 unsigned DiagID) {
306 assert(IsCustomDiag(DiagID));
307 const auto &Diag = CustomDiagInfo->getDescription(DiagID);
308 if (auto Group = Diag.GetGroup()) {
309 GroupInfo GroupInfo = GroupInfos[static_cast<size_t>(*Group)];
310 if (static_cast<diag::Severity>(GroupInfo.Severity) != diag::Severity())
311 Mapping.setSeverity(static_cast<diag::Severity>(GroupInfo.Severity));
312 Mapping.setNoWarningAsError(GroupInfo.HasNoWarningAsError);
313 } else {
314 Mapping.setSeverity(Diag.GetDefaultSeverity());
315 Mapping.setNoWarningAsError(true);
316 Mapping.setNoErrorAsFatal(true);
317 }
318}
319
320/// getCategoryNumberForDiag - Return the category number that a specified
321/// DiagID belongs to, or 0 if no category.
322unsigned DiagnosticIDs::getCategoryNumberForDiag(unsigned DiagID) {
323 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
324 return Info->Category;
325 return 0;
326}
327
328namespace {
329 // The diagnostic category names.
330 struct StaticDiagCategoryRec {
331 const char *NameStr;
332 uint8_t NameLen;
333
334 StringRef getName() const {
335 return StringRef(NameStr, NameLen);
336 }
337 };
338}
339
340static const StaticDiagCategoryRec CategoryNameTable[] = {
341#define GET_CATEGORY_TABLE
342#define CATEGORY(X, ENUM) { X, STR_SIZE(X, uint8_t) },
343#include "clang/Basic/DiagnosticGroups.inc"
344#undef GET_CATEGORY_TABLE
345 { .NameStr: nullptr, .NameLen: 0 }
346};
347
348/// getNumberOfCategories - Return the number of categories
349unsigned DiagnosticIDs::getNumberOfCategories() {
350 return std::size(CategoryNameTable) - 1;
351}
352
353/// getCategoryNameFromID - Given a category ID, return the name of the
354/// category, an empty string if CategoryID is zero, or null if CategoryID is
355/// invalid.
356StringRef DiagnosticIDs::getCategoryNameFromID(unsigned CategoryID) {
357 if (CategoryID >= getNumberOfCategories())
358 return StringRef();
359 return CategoryNameTable[CategoryID].getName();
360}
361
362
363
364DiagnosticIDs::SFINAEResponse
365DiagnosticIDs::getDiagnosticSFINAEResponse(unsigned DiagID) {
366 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
367 return static_cast<DiagnosticIDs::SFINAEResponse>(Info->SFINAE);
368 return SFINAE_Report;
369}
370
371bool DiagnosticIDs::isDeferrable(unsigned DiagID) {
372 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
373 return Info->Deferrable;
374 return false;
375}
376
377//===----------------------------------------------------------------------===//
378// Common Diagnostic implementation
379//===----------------------------------------------------------------------===//
380
381DiagnosticIDs::DiagnosticIDs() {}
382
383DiagnosticIDs::~DiagnosticIDs() {}
384
385/// getCustomDiagID - Return an ID for a diagnostic with the specified message
386/// and level. If this is the first request for this diagnostic, it is
387/// registered and created, otherwise the existing ID is returned.
388///
389/// \param FormatString A fixed diagnostic format string that will be hashed and
390/// mapped to a unique DiagID.
391unsigned DiagnosticIDs::getCustomDiagID(CustomDiagDesc Diag) {
392 if (!CustomDiagInfo)
393 CustomDiagInfo.reset(p: new diag::CustomDiagInfo());
394 return CustomDiagInfo->getOrCreateDiagID(D: Diag);
395}
396
397bool DiagnosticIDs::isWarningOrExtension(unsigned DiagID) const {
398 return DiagID < diag::DIAG_UPPER_LIMIT
399 ? getDiagClass(DiagID) != CLASS_ERROR
400 : CustomDiagInfo->getDescription(DiagID).GetClass() != CLASS_ERROR;
401}
402
403/// Determine whether the given built-in diagnostic ID is a
404/// Note.
405bool DiagnosticIDs::isNote(unsigned DiagID) const {
406 return DiagID < diag::DIAG_UPPER_LIMIT && getDiagClass(DiagID) == CLASS_NOTE;
407}
408
409/// isExtensionDiag - Determine whether the given built-in diagnostic
410/// ID is for an extension of some sort. This also returns EnabledByDefault,
411/// which is set to indicate whether the diagnostic is ignored by default (in
412/// which case -pedantic enables it) or treated as a warning/error by default.
413///
414bool DiagnosticIDs::isExtensionDiag(unsigned DiagID,
415 bool &EnabledByDefault) const {
416 if (IsCustomDiag(Diag: DiagID) || getDiagClass(DiagID) != CLASS_EXTENSION)
417 return false;
418
419 EnabledByDefault =
420 getDefaultMapping(DiagID).getSeverity() != diag::Severity::Ignored;
421 return true;
422}
423
424bool DiagnosticIDs::isDefaultMappingAsError(unsigned DiagID) const {
425 return getDefaultMapping(DiagID).getSeverity() >= diag::Severity::Error;
426}
427
428/// getDescription - Given a diagnostic ID, return a description of the
429/// issue.
430StringRef DiagnosticIDs::getDescription(unsigned DiagID) const {
431 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
432 return Info->getDescription();
433 assert(CustomDiagInfo && "Invalid CustomDiagInfo");
434 return CustomDiagInfo->getDescription(DiagID).GetDescription();
435}
436
437static DiagnosticIDs::Level toLevel(diag::Severity SV) {
438 switch (SV) {
439 case diag::Severity::Ignored:
440 return DiagnosticIDs::Ignored;
441 case diag::Severity::Remark:
442 return DiagnosticIDs::Remark;
443 case diag::Severity::Warning:
444 return DiagnosticIDs::Warning;
445 case diag::Severity::Error:
446 return DiagnosticIDs::Error;
447 case diag::Severity::Fatal:
448 return DiagnosticIDs::Fatal;
449 }
450 llvm_unreachable("unexpected severity");
451}
452
453/// getDiagnosticLevel - Based on the way the client configured the
454/// DiagnosticsEngine object, classify the specified diagnostic ID into a Level,
455/// by consumable the DiagnosticClient.
456DiagnosticIDs::Level
457DiagnosticIDs::getDiagnosticLevel(unsigned DiagID, SourceLocation Loc,
458 const DiagnosticsEngine &Diag) const {
459 unsigned DiagClass = getDiagClass(DiagID);
460 if (DiagClass == CLASS_NOTE) return DiagnosticIDs::Note;
461 return toLevel(SV: getDiagnosticSeverity(DiagID, Loc, Diag));
462}
463
464/// Based on the way the client configured the Diagnostic
465/// object, classify the specified diagnostic ID into a Level, consumable by
466/// the DiagnosticClient.
467///
468/// \param Loc The source location we are interested in finding out the
469/// diagnostic state. Can be null in order to query the latest state.
470diag::Severity
471DiagnosticIDs::getDiagnosticSeverity(unsigned DiagID, SourceLocation Loc,
472 const DiagnosticsEngine &Diag) const {
473 bool IsCustomDiag = DiagnosticIDs::IsCustomDiag(Diag: DiagID);
474 assert(getDiagClass(DiagID) != CLASS_NOTE);
475
476 // Specific non-error diagnostics may be mapped to various levels from ignored
477 // to error. Errors can only be mapped to fatal.
478 diag::Severity Result = diag::Severity::Fatal;
479
480 // Get the mapping information, or compute it lazily.
481 DiagnosticsEngine::DiagState *State = Diag.GetDiagStateForLoc(Loc);
482 DiagnosticMapping Mapping = State->getOrAddMapping(Diag: (diag::kind)DiagID);
483
484 // TODO: Can a null severity really get here?
485 if (Mapping.getSeverity() != diag::Severity())
486 Result = Mapping.getSeverity();
487
488 // Upgrade ignored diagnostics if -Weverything is enabled.
489 if (State->EnableAllWarnings && Result == diag::Severity::Ignored &&
490 !Mapping.isUser() &&
491 (IsCustomDiag || getDiagClass(DiagID) != CLASS_REMARK))
492 Result = diag::Severity::Warning;
493
494 // Ignore -pedantic diagnostics inside __extension__ blocks.
495 // (The diagnostics controlled by -pedantic are the extension diagnostics
496 // that are not enabled by default.)
497 bool EnabledByDefault = false;
498 bool IsExtensionDiag = isExtensionDiag(DiagID, EnabledByDefault);
499 if (Diag.AllExtensionsSilenced && IsExtensionDiag && !EnabledByDefault)
500 return diag::Severity::Ignored;
501
502 // For extension diagnostics that haven't been explicitly mapped, check if we
503 // should upgrade the diagnostic.
504 if (IsExtensionDiag && !Mapping.isUser())
505 Result = std::max(a: Result, b: State->ExtBehavior);
506
507 // At this point, ignored errors can no longer be upgraded.
508 if (Result == diag::Severity::Ignored)
509 return Result;
510
511 // Honor -w: this disables all messages which are not Error/Fatal by
512 // default (disregarding attempts to upgrade severity from Warning to Error),
513 // as well as disabling all messages which are currently mapped to Warning
514 // (whether by default or downgraded from Error via e.g. -Wno-error or #pragma
515 // diagnostic.)
516 // FIXME: Should -w be ignored for custom warnings without a group?
517 if (State->IgnoreAllWarnings) {
518 if ((!IsCustomDiag || CustomDiagInfo->getDescription(DiagID).GetGroup()) &&
519 (Result == diag::Severity::Warning ||
520 (Result >= diag::Severity::Error &&
521 !isDefaultMappingAsError(DiagID: (diag::kind)DiagID))))
522 return diag::Severity::Ignored;
523 }
524
525 // If -Werror is enabled, map warnings to errors unless explicitly disabled.
526 if (Result == diag::Severity::Warning) {
527 if (State->WarningsAsErrors && !Mapping.hasNoWarningAsError())
528 Result = diag::Severity::Error;
529 }
530
531 // If -Wfatal-errors is enabled, map errors to fatal unless explicitly
532 // disabled.
533 if (Result == diag::Severity::Error) {
534 if (State->ErrorsAsFatal && !Mapping.hasNoErrorAsFatal())
535 Result = diag::Severity::Fatal;
536 }
537
538 // If explicitly requested, map fatal errors to errors.
539 if (Result == diag::Severity::Fatal &&
540 DiagID != diag::fatal_too_many_errors && Diag.FatalsAsError)
541 Result = diag::Severity::Error;
542
543 // Rest of the mappings are only applicable for diagnostics associated with a
544 // SourceLocation, bail out early for others.
545 if (!Diag.hasSourceManager())
546 return Result;
547
548 const auto &SM = Diag.getSourceManager();
549 // If we are in a system header, we ignore it. We look at the diagnostic class
550 // because we also want to ignore extensions and warnings in -Werror and
551 // -pedantic-errors modes, which *map* warnings/extensions to errors.
552 //
553 // We check both the location-specific state and the ForceSystemWarnings
554 // override. In some cases (like template instantiations from system modules),
555 // the location-specific state might have suppression enabled, but the
556 // engine might have an override (e.g. AllowWarningInSystemHeaders) to show
557 // the warning.
558 if (State->SuppressSystemWarnings && !Diag.getForceSystemWarnings() &&
559 Loc.isValid() && SM.isInSystemHeader(Loc: SM.getExpansionLoc(Loc))) {
560 bool ShowInSystemHeader = true;
561 if (IsCustomDiag)
562 ShowInSystemHeader =
563 CustomDiagInfo->getDescription(DiagID).ShouldShowInSystemHeader();
564 else if (const StaticDiagInfoRec *Rec = GetDiagInfo(DiagID))
565 ShowInSystemHeader = Rec->WarnShowInSystemHeader;
566
567 if (!ShowInSystemHeader)
568 return diag::Severity::Ignored;
569 }
570 // We also ignore warnings due to system macros. As above, we respect the
571 // ForceSystemWarnings override.
572 if (State->SuppressSystemWarnings && !Diag.getForceSystemWarnings() &&
573 Loc.isValid()) {
574
575 bool ShowInSystemMacro = true;
576 if (const StaticDiagInfoRec *Rec = GetDiagInfo(DiagID))
577 ShowInSystemMacro = Rec->WarnShowInSystemMacro;
578
579 if (!ShowInSystemMacro && SM.isInSystemMacro(loc: Loc))
580 return diag::Severity::Ignored;
581 }
582 // Clang-diagnostics pragmas always take precedence over suppression mapping.
583 if (!Mapping.isPragma() && Diag.isSuppressedViaMapping(DiagId: DiagID, DiagLoc: Loc))
584 return diag::Severity::Ignored;
585
586 return Result;
587}
588
589DiagnosticIDs::Class DiagnosticIDs::getDiagClass(unsigned DiagID) const {
590 if (IsCustomDiag(Diag: DiagID))
591 return Class(CustomDiagInfo->getDescription(DiagID).GetClass());
592
593 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
594 return Class(Info->Class);
595 return CLASS_INVALID;
596}
597
598#define GET_DIAG_ARRAYS
599#include "clang/Basic/DiagnosticGroups.inc"
600#undef GET_DIAG_ARRAYS
601
602namespace {
603 struct WarningOption {
604 uint16_t NameOffset;
605 uint16_t Members;
606 uint16_t SubGroups;
607 StringRef Documentation;
608
609 StringRef getName() const { return DiagGroupNames[NameOffset]; }
610 };
611}
612
613// Second the table of options, sorted by name for fast binary lookup.
614static const WarningOption OptionTable[] = {
615#define DIAG_ENTRY(GroupName, FlagNameOffset, Members, SubGroups, Docs) \
616 {FlagNameOffset, Members, SubGroups, Docs},
617#include "clang/Basic/DiagnosticGroups.inc"
618#undef DIAG_ENTRY
619};
620
621/// Given a diagnostic group ID, return its documentation.
622StringRef DiagnosticIDs::getWarningOptionDocumentation(diag::Group Group) {
623 return OptionTable[static_cast<int>(Group)].Documentation;
624}
625
626StringRef DiagnosticIDs::getWarningOptionForGroup(diag::Group Group) {
627 return OptionTable[static_cast<int>(Group)].getName();
628}
629
630std::optional<diag::Group>
631DiagnosticIDs::getGroupForWarningOption(StringRef Name) {
632 const auto *Found = llvm::partition_point(
633 Range: OptionTable, P: [=](const WarningOption &O) { return O.getName() < Name; });
634 if (Found == std::end(arr: OptionTable) || Found->getName() != Name)
635 return std::nullopt;
636 return static_cast<diag::Group>(Found - OptionTable);
637}
638
639std::optional<diag::Group>
640DiagnosticIDs::getGroupForDiag(unsigned DiagID) const {
641 if (IsCustomDiag(Diag: DiagID)) {
642 assert(CustomDiagInfo);
643 return CustomDiagInfo->getDescription(DiagID).GetGroup();
644 }
645 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
646 return static_cast<diag::Group>(Info->getOptionGroupIndex());
647 return std::nullopt;
648}
649
650/// getWarningOptionForDiag - Return the lowest-level warning option that
651/// enables the specified diagnostic. If there is no -Wfoo flag that controls
652/// the diagnostic, this returns null.
653StringRef DiagnosticIDs::getWarningOptionForDiag(unsigned DiagID) {
654 if (auto G = getGroupForDiag(DiagID))
655 return getWarningOptionForGroup(Group: *G);
656 return StringRef();
657}
658
659std::vector<std::string> DiagnosticIDs::getDiagnosticFlags() {
660 std::vector<std::string> Res{"-W", "-Wno-"};
661 for (StringRef Name : DiagGroupNames) {
662 if (Name.empty())
663 continue;
664
665 Res.push_back(x: (Twine("-W") + Name).str());
666 Res.push_back(x: (Twine("-Wno-") + Name).str());
667 }
668
669 return Res;
670}
671
672/// Return \c true if any diagnostics were found in this group, even if they
673/// were filtered out due to having the wrong flavor.
674static bool getDiagnosticsInGroup(diag::Flavor Flavor,
675 const WarningOption *Group,
676 SmallVectorImpl<diag::kind> &Diags,
677 diag::CustomDiagInfo *CustomDiagInfo) {
678 // An empty group is considered to be a warning group: we have empty groups
679 // for GCC compatibility, and GCC does not have remarks.
680 if (!Group->Members && !Group->SubGroups)
681 return Flavor == diag::Flavor::Remark;
682
683 bool NotFound = true;
684
685 // Add the members of the option diagnostic set.
686 const int16_t *Member = DiagArrays + Group->Members;
687 for (; *Member != -1; ++Member) {
688 if (GetDiagInfo(DiagID: *Member)->getFlavor() == Flavor) {
689 NotFound = false;
690 Diags.push_back(Elt: *Member);
691 }
692 }
693
694 // Add the members of the subgroups.
695 const int16_t *SubGroups = DiagSubGroups + Group->SubGroups;
696 for (; *SubGroups != (int16_t)-1; ++SubGroups) {
697 if (CustomDiagInfo)
698 llvm::copy(
699 Range: CustomDiagInfo->getDiagsInGroup(G: static_cast<diag::Group>(*SubGroups)),
700 Out: std::back_inserter(x&: Diags));
701 NotFound &= getDiagnosticsInGroup(Flavor, Group: &OptionTable[(short)*SubGroups],
702 Diags, CustomDiagInfo);
703 }
704
705 return NotFound;
706}
707
708bool
709DiagnosticIDs::getDiagnosticsInGroup(diag::Flavor Flavor, StringRef Group,
710 SmallVectorImpl<diag::kind> &Diags) const {
711 if (std::optional<diag::Group> G = getGroupForWarningOption(Name: Group)) {
712 if (CustomDiagInfo)
713 llvm::copy(Range: CustomDiagInfo->getDiagsInGroup(G: *G),
714 Out: std::back_inserter(x&: Diags));
715 return ::getDiagnosticsInGroup(Flavor,
716 Group: &OptionTable[static_cast<unsigned>(*G)],
717 Diags, CustomDiagInfo: CustomDiagInfo.get());
718 }
719 return true;
720}
721
722template <class Func>
723static void forEachSubGroupImpl(const WarningOption *Group, Func func) {
724 for (const int16_t *SubGroups = DiagSubGroups + Group->SubGroups;
725 *SubGroups != -1; ++SubGroups) {
726 func(static_cast<size_t>(*SubGroups));
727 forEachSubGroupImpl(&OptionTable[*SubGroups], func);
728 }
729}
730
731template <class Func>
732static void forEachSubGroup(diag::Group Group, Func func) {
733 const WarningOption *WarningOpt = &OptionTable[static_cast<size_t>(Group)];
734 func(static_cast<size_t>(Group));
735 ::forEachSubGroupImpl(WarningOpt, std::move(func));
736}
737
738void DiagnosticIDs::setGroupSeverity(StringRef Group, diag::Severity Sev) {
739 if (std::optional<diag::Group> G = getGroupForWarningOption(Name: Group)) {
740 ::forEachSubGroup(Group: *G, func: [&](size_t SubGroup) {
741 GroupInfos[SubGroup].Severity = static_cast<unsigned>(Sev);
742 });
743 }
744}
745
746void DiagnosticIDs::setGroupNoWarningsAsError(StringRef Group, bool Val) {
747 if (std::optional<diag::Group> G = getGroupForWarningOption(Name: Group)) {
748 ::forEachSubGroup(Group: *G, func: [&](size_t SubGroup) {
749 GroupInfos[static_cast<size_t>(*G)].HasNoWarningAsError = Val;
750 });
751 }
752}
753
754void DiagnosticIDs::getAllDiagnostics(diag::Flavor Flavor,
755 std::vector<diag::kind> &Diags) {
756 for (unsigned i = 0; i != StaticDiagInfoSize; ++i)
757 if (StaticDiagInfo[i].getFlavor() == Flavor)
758 Diags.push_back(x: StaticDiagInfo[i].DiagID);
759}
760
761StringRef DiagnosticIDs::getNearestOption(diag::Flavor Flavor,
762 StringRef Group) {
763 StringRef Best;
764 unsigned BestDistance = Group.size() + 1; // Maximum threshold.
765 for (const WarningOption &O : OptionTable) {
766 // Don't suggest ignored warning flags.
767 if (!O.Members && !O.SubGroups)
768 continue;
769
770 unsigned Distance = O.getName().edit_distance(Other: Group, AllowReplacements: true, MaxEditDistance: BestDistance);
771 if (Distance > BestDistance)
772 continue;
773
774 // Don't suggest groups that are not of this kind.
775 llvm::SmallVector<diag::kind, 8> Diags;
776 if (::getDiagnosticsInGroup(Flavor, Group: &O, Diags, CustomDiagInfo: nullptr) || Diags.empty())
777 continue;
778
779 if (Distance == BestDistance) {
780 // Two matches with the same distance, don't prefer one over the other.
781 Best = "";
782 } else if (Distance < BestDistance) {
783 // This is a better match.
784 Best = O.getName();
785 BestDistance = Distance;
786 }
787 }
788
789 return Best;
790}
791
792unsigned DiagnosticIDs::getCXXCompatDiagId(const LangOptions &LangOpts,
793 unsigned CompatDiagId) {
794 struct CompatDiag {
795 unsigned StdVer;
796 unsigned DiagId;
797 unsigned PreDiagId;
798 };
799
800 // We encode the standard version such that C++98 < C++11 < C++14 etc. The
801 // actual numbers don't really matter for this, but the definitions of the
802 // compat diags in the Tablegen file use the standard version number (i.e.
803 // 98, 11, 14, etc.), so we base the encoding here on that.
804#define DIAG_COMPAT_IDS_BEGIN()
805#define DIAG_COMPAT_IDS_END()
806#define DIAG_COMPAT_ID(Value, Name, Std, Diag, DiagPre) \
807 {Std == 98 ? 1998 : 2000 + Std, diag::Diag, diag::DiagPre},
808 static constexpr CompatDiag Diags[]{
809#include "clang/Basic/DiagnosticAllCompatIDs.inc"
810 };
811#undef DIAG_COMPAT_ID
812#undef DIAG_COMPAT_IDS_BEGIN
813#undef DIAG_COMPAT_IDS_END
814
815 assert(CompatDiagId < std::size(Diags) && "Invalid compat diag id");
816
817 unsigned StdVer = [&] {
818 if (LangOpts.CPlusPlus26)
819 return 2026;
820 if (LangOpts.CPlusPlus23)
821 return 2023;
822 if (LangOpts.CPlusPlus20)
823 return 2020;
824 if (LangOpts.CPlusPlus17)
825 return 2017;
826 if (LangOpts.CPlusPlus14)
827 return 2014;
828 if (LangOpts.CPlusPlus11)
829 return 2011;
830 return 1998;
831 }();
832
833 const CompatDiag &D = Diags[CompatDiagId];
834 return StdVer >= D.StdVer ? D.DiagId : D.PreDiagId;
835}
836
837bool DiagnosticIDs::isUnrecoverable(unsigned DiagID) const {
838 // Only errors may be unrecoverable.
839 if (getDiagClass(DiagID) < CLASS_ERROR)
840 return false;
841
842 if (DiagID == diag::err_unavailable ||
843 DiagID == diag::err_unavailable_message)
844 return false;
845
846 // All ARC errors are currently considered recoverable, with the exception of
847 // err_arc_may_not_respond. This specific error is treated as unrecoverable
848 // because sending a message with an unknown selector could lead to crashes
849 // within CodeGen if the resulting expression is used to initialize a C++
850 // auto variable, where type deduction is required.
851 if (isARCDiagnostic(DiagID) && DiagID != diag::err_arc_may_not_respond)
852 return false;
853
854 if (isCodegenABICheckDiagnostic(DiagID))
855 return false;
856
857 return true;
858}
859
860bool DiagnosticIDs::isARCDiagnostic(unsigned DiagID) {
861 unsigned cat = getCategoryNumberForDiag(DiagID);
862 return DiagnosticIDs::getCategoryNameFromID(CategoryID: cat).starts_with(Prefix: "ARC ");
863}
864
865bool DiagnosticIDs::isCodegenABICheckDiagnostic(unsigned DiagID) {
866 unsigned cat = getCategoryNumberForDiag(DiagID);
867 return DiagnosticIDs::getCategoryNameFromID(CategoryID: cat) == "Codegen ABI Check";
868}
869