DiagnosticIDs.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. //===--- DiagnosticIDs.cpp - Diagnostic IDs Handling ----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Diagnostic IDs-related interfaces.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Basic/DiagnosticIDs.h"
  14. #include "clang/Basic/AllDiagnostics.h"
  15. #include "clang/Basic/DiagnosticCategories.h"
  16. #include "clang/Basic/SourceManager.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/Support/ErrorHandling.h"
  20. #include <map>
  21. using namespace clang;
  22. //===----------------------------------------------------------------------===//
  23. // Builtin Diagnostic information
  24. //===----------------------------------------------------------------------===//
  25. namespace {
  26. // Diagnostic classes.
  27. enum {
  28. CLASS_NOTE = 0x01,
  29. CLASS_REMARK = 0x02,
  30. CLASS_WARNING = 0x03,
  31. CLASS_EXTENSION = 0x04,
  32. CLASS_ERROR = 0x05
  33. };
  34. struct StaticDiagInfoRec {
  35. uint16_t DiagID;
  36. unsigned DefaultSeverity : 3;
  37. unsigned Class : 3;
  38. unsigned SFINAE : 2;
  39. unsigned WarnNoWerror : 1;
  40. unsigned WarnShowInSystemHeader : 1;
  41. unsigned Category : 5;
  42. uint16_t OptionGroupIndex;
  43. uint16_t DescriptionLen;
  44. const char *DescriptionStr;
  45. unsigned getOptionGroupIndex() const {
  46. return OptionGroupIndex;
  47. }
  48. StringRef getDescription() const {
  49. return StringRef(DescriptionStr, DescriptionLen);
  50. }
  51. diag::Flavor getFlavor() const {
  52. return Class == CLASS_REMARK ? diag::Flavor::Remark
  53. : diag::Flavor::WarningOrError;
  54. }
  55. bool operator<(const StaticDiagInfoRec &RHS) const {
  56. return DiagID < RHS.DiagID;
  57. }
  58. };
  59. } // namespace anonymous
  60. static const StaticDiagInfoRec StaticDiagInfo[] = {
  61. #define DIAG(ENUM, CLASS, DEFAULT_SEVERITY, DESC, GROUP, SFINAE, NOWERROR, \
  62. SHOWINSYSHEADER, CATEGORY) \
  63. { \
  64. diag::ENUM, DEFAULT_SEVERITY, CLASS, DiagnosticIDs::SFINAE, NOWERROR, \
  65. SHOWINSYSHEADER, CATEGORY, GROUP, STR_SIZE(DESC, uint16_t), DESC \
  66. } \
  67. ,
  68. #include "clang/Basic/DiagnosticCommonKinds.inc"
  69. #include "clang/Basic/DiagnosticDriverKinds.inc"
  70. #include "clang/Basic/DiagnosticFrontendKinds.inc"
  71. #include "clang/Basic/DiagnosticSerializationKinds.inc"
  72. #include "clang/Basic/DiagnosticLexKinds.inc"
  73. #include "clang/Basic/DiagnosticParseKinds.inc"
  74. #include "clang/Basic/DiagnosticASTKinds.inc"
  75. #include "clang/Basic/DiagnosticCommentKinds.inc"
  76. #include "clang/Basic/DiagnosticSemaKinds.inc"
  77. #include "clang/Basic/DiagnosticAnalysisKinds.inc"
  78. #undef DIAG
  79. };
  80. static const unsigned StaticDiagInfoSize = _countof(StaticDiagInfo); // HLSL Change - SAL doesn't understand llvm::array_lengthof(StaticDiagInfo);
  81. /// GetDiagInfo - Return the StaticDiagInfoRec entry for the specified DiagID,
  82. /// or null if the ID is invalid.
  83. static const StaticDiagInfoRec *GetDiagInfo(unsigned DiagID) {
  84. // If assertions are enabled, verify that the StaticDiagInfo array is sorted.
  85. #ifndef NDEBUG
  86. static bool IsFirst = true; // So the check is only performed on first call.
  87. if (IsFirst) {
  88. for (unsigned i = 1; i != StaticDiagInfoSize; ++i) {
  89. assert(StaticDiagInfo[i-1].DiagID != StaticDiagInfo[i].DiagID &&
  90. "Diag ID conflict, the enums at the start of clang::diag (in "
  91. "DiagnosticIDs.h) probably need to be increased");
  92. assert(StaticDiagInfo[i-1] < StaticDiagInfo[i] &&
  93. "Improperly sorted diag info");
  94. }
  95. IsFirst = false;
  96. }
  97. #endif
  98. // Out of bounds diag. Can't be in the table.
  99. using namespace diag;
  100. if (DiagID >= DIAG_UPPER_LIMIT || DiagID <= DIAG_START_COMMON)
  101. return nullptr;
  102. // Compute the index of the requested diagnostic in the static table.
  103. // 1. Add the number of diagnostics in each category preceding the
  104. // diagnostic and of the category the diagnostic is in. This gives us
  105. // the offset of the category in the table.
  106. // 2. Subtract the number of IDs in each category from our ID. This gives us
  107. // the offset of the diagnostic in the category.
  108. // This is cheaper than a binary search on the table as it doesn't touch
  109. // memory at all.
  110. unsigned Offset = 0;
  111. unsigned ID = DiagID - DIAG_START_COMMON - 1;
  112. #define CATEGORY(NAME, PREV) \
  113. if (DiagID > DIAG_START_##NAME) { \
  114. Offset += NUM_BUILTIN_##PREV##_DIAGNOSTICS - DIAG_START_##PREV - 1; \
  115. ID -= DIAG_START_##NAME - DIAG_START_##PREV; \
  116. }
  117. CATEGORY(DRIVER, COMMON)
  118. CATEGORY(FRONTEND, DRIVER)
  119. CATEGORY(SERIALIZATION, FRONTEND)
  120. CATEGORY(LEX, SERIALIZATION)
  121. CATEGORY(PARSE, LEX)
  122. CATEGORY(AST, PARSE)
  123. CATEGORY(COMMENT, AST)
  124. CATEGORY(SEMA, COMMENT)
  125. CATEGORY(ANALYSIS, SEMA)
  126. #undef CATEGORY
  127. // Avoid out of bounds reads.
  128. if (ID + Offset >= StaticDiagInfoSize)
  129. return nullptr;
  130. assert(ID < StaticDiagInfoSize && Offset < StaticDiagInfoSize);
  131. const StaticDiagInfoRec *Found = &StaticDiagInfo[ID + Offset];
  132. // If the diag id doesn't match we found a different diag, abort. This can
  133. // happen when this function is called with an ID that points into a hole in
  134. // the diagID space.
  135. if (Found->DiagID != DiagID)
  136. return nullptr;
  137. return Found;
  138. }
  139. static DiagnosticMapping GetDefaultDiagMapping(unsigned DiagID) {
  140. DiagnosticMapping Info = DiagnosticMapping::Make(
  141. diag::Severity::Fatal, /*IsUser=*/false, /*IsPragma=*/false);
  142. if (const StaticDiagInfoRec *StaticInfo = GetDiagInfo(DiagID)) {
  143. Info.setSeverity((diag::Severity)StaticInfo->DefaultSeverity);
  144. if (StaticInfo->WarnNoWerror) {
  145. assert(Info.getSeverity() == diag::Severity::Warning &&
  146. "Unexpected mapping with no-Werror bit!");
  147. Info.setNoWarningAsError(true);
  148. }
  149. }
  150. return Info;
  151. }
  152. /// getCategoryNumberForDiag - Return the category number that a specified
  153. /// DiagID belongs to, or 0 if no category.
  154. unsigned DiagnosticIDs::getCategoryNumberForDiag(unsigned DiagID) {
  155. if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
  156. return Info->Category;
  157. return 0;
  158. }
  159. namespace {
  160. // The diagnostic category names.
  161. struct StaticDiagCategoryRec {
  162. const char *NameStr;
  163. uint8_t NameLen;
  164. StringRef getName() const {
  165. return StringRef(NameStr, NameLen);
  166. }
  167. };
  168. }
  169. // Unfortunately, the split between DiagnosticIDs and Diagnostic is not
  170. // particularly clean, but for now we just implement this method here so we can
  171. // access GetDefaultDiagMapping.
  172. DiagnosticMapping &
  173. DiagnosticsEngine::DiagState::getOrAddMapping(diag::kind Diag) {
  174. std::pair<iterator, bool> Result =
  175. DiagMap.insert(std::make_pair(Diag, DiagnosticMapping()));
  176. // Initialize the entry if we added it.
  177. if (Result.second)
  178. Result.first->second = GetDefaultDiagMapping(Diag);
  179. return Result.first->second;
  180. }
  181. static const StaticDiagCategoryRec CategoryNameTable[] = {
  182. #define GET_CATEGORY_TABLE
  183. #define CATEGORY(X, ENUM) { X, STR_SIZE(X, uint8_t) },
  184. #include "clang/Basic/DiagnosticGroups.inc"
  185. #undef GET_CATEGORY_TABLE
  186. { nullptr, 0 }
  187. };
  188. /// getNumberOfCategories - Return the number of categories
  189. unsigned DiagnosticIDs::getNumberOfCategories() {
  190. return llvm::array_lengthof(CategoryNameTable) - 1;
  191. }
  192. /// getCategoryNameFromID - Given a category ID, return the name of the
  193. /// category, an empty string if CategoryID is zero, or null if CategoryID is
  194. /// invalid.
  195. StringRef DiagnosticIDs::getCategoryNameFromID(unsigned CategoryID) {
  196. if (CategoryID >= getNumberOfCategories())
  197. return StringRef();
  198. return CategoryNameTable[CategoryID].getName();
  199. }
  200. DiagnosticIDs::SFINAEResponse
  201. DiagnosticIDs::getDiagnosticSFINAEResponse(unsigned DiagID) {
  202. if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
  203. return static_cast<DiagnosticIDs::SFINAEResponse>(Info->SFINAE);
  204. return SFINAE_Report;
  205. }
  206. /// getBuiltinDiagClass - Return the class field of the diagnostic.
  207. ///
  208. static unsigned getBuiltinDiagClass(unsigned DiagID) {
  209. if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
  210. return Info->Class;
  211. return ~0U;
  212. }
  213. //===----------------------------------------------------------------------===//
  214. // Custom Diagnostic information
  215. //===----------------------------------------------------------------------===//
  216. namespace clang {
  217. namespace diag {
  218. class CustomDiagInfo {
  219. typedef std::pair<DiagnosticIDs::Level, std::string> DiagDesc;
  220. std::vector<DiagDesc> DiagInfo;
  221. std::map<DiagDesc, unsigned> DiagIDs;
  222. public:
  223. /// getDescription - Return the description of the specified custom
  224. /// diagnostic.
  225. StringRef getDescription(unsigned DiagID) const {
  226. assert(DiagID - DIAG_UPPER_LIMIT < DiagInfo.size() &&
  227. "Invalid diagnostic ID");
  228. return DiagInfo[DiagID-DIAG_UPPER_LIMIT].second;
  229. }
  230. /// getLevel - Return the level of the specified custom diagnostic.
  231. DiagnosticIDs::Level getLevel(unsigned DiagID) const {
  232. assert(DiagID - DIAG_UPPER_LIMIT < DiagInfo.size() &&
  233. "Invalid diagnostic ID");
  234. return DiagInfo[DiagID-DIAG_UPPER_LIMIT].first;
  235. }
  236. unsigned getOrCreateDiagID(DiagnosticIDs::Level L, StringRef Message,
  237. DiagnosticIDs &Diags) {
  238. // HLSL Change Starts
  239. // ".str()" is a workaround for a bug in VC++'s STL where std::pair<T,U>::pair<T2,U2>(T2&&,U2&&)
  240. // may cause a conversion operator from U2 to U to be invoked within a noexcept function.
  241. // This would cause a call std::terminate if we ran out of memory and throw std::bad_alloc
  242. DiagDesc D(L, Message.str());
  243. // HLSL Change Ends
  244. // Check to see if it already exists.
  245. std::map<DiagDesc, unsigned>::iterator I = DiagIDs.lower_bound(D);
  246. if (I != DiagIDs.end() && I->first == D)
  247. return I->second;
  248. // If not, assign a new ID.
  249. unsigned ID = DiagInfo.size()+DIAG_UPPER_LIMIT;
  250. DiagIDs.insert(std::make_pair(D, ID));
  251. DiagInfo.push_back(D);
  252. return ID;
  253. }
  254. };
  255. } // end diag namespace
  256. } // end clang namespace
  257. //===----------------------------------------------------------------------===//
  258. // Common Diagnostic implementation
  259. //===----------------------------------------------------------------------===//
  260. DiagnosticIDs::DiagnosticIDs() { CustomDiagInfo = nullptr; }
  261. DiagnosticIDs::~DiagnosticIDs() {
  262. delete CustomDiagInfo;
  263. }
  264. /// getCustomDiagID - Return an ID for a diagnostic with the specified message
  265. /// and level. If this is the first request for this diagnostic, it is
  266. /// registered and created, otherwise the existing ID is returned.
  267. ///
  268. /// \param FormatString A fixed diagnostic format string that will be hashed and
  269. /// mapped to a unique DiagID.
  270. unsigned DiagnosticIDs::getCustomDiagID(Level L, StringRef FormatString) {
  271. if (!CustomDiagInfo)
  272. CustomDiagInfo = new diag::CustomDiagInfo();
  273. return CustomDiagInfo->getOrCreateDiagID(L, FormatString, *this);
  274. }
  275. /// isBuiltinWarningOrExtension - Return true if the unmapped diagnostic
  276. /// level of the specified diagnostic ID is a Warning or Extension.
  277. /// This only works on builtin diagnostics, not custom ones, and is not legal to
  278. /// call on NOTEs.
  279. bool DiagnosticIDs::isBuiltinWarningOrExtension(unsigned DiagID) {
  280. return DiagID < diag::DIAG_UPPER_LIMIT &&
  281. getBuiltinDiagClass(DiagID) != CLASS_ERROR;
  282. }
  283. /// \brief Determine whether the given built-in diagnostic ID is a
  284. /// Note.
  285. bool DiagnosticIDs::isBuiltinNote(unsigned DiagID) {
  286. return DiagID < diag::DIAG_UPPER_LIMIT &&
  287. getBuiltinDiagClass(DiagID) == CLASS_NOTE;
  288. }
  289. /// isBuiltinExtensionDiag - Determine whether the given built-in diagnostic
  290. /// ID is for an extension of some sort. This also returns EnabledByDefault,
  291. /// which is set to indicate whether the diagnostic is ignored by default (in
  292. /// which case -pedantic enables it) or treated as a warning/error by default.
  293. ///
  294. bool DiagnosticIDs::isBuiltinExtensionDiag(unsigned DiagID,
  295. bool &EnabledByDefault) {
  296. if (DiagID >= diag::DIAG_UPPER_LIMIT ||
  297. getBuiltinDiagClass(DiagID) != CLASS_EXTENSION)
  298. return false;
  299. EnabledByDefault =
  300. GetDefaultDiagMapping(DiagID).getSeverity() != diag::Severity::Ignored;
  301. return true;
  302. }
  303. bool DiagnosticIDs::isDefaultMappingAsError(unsigned DiagID) {
  304. if (DiagID >= diag::DIAG_UPPER_LIMIT)
  305. return false;
  306. return GetDefaultDiagMapping(DiagID).getSeverity() == diag::Severity::Error;
  307. }
  308. /// getDescription - Given a diagnostic ID, return a description of the
  309. /// issue.
  310. StringRef DiagnosticIDs::getDescription(unsigned DiagID) const {
  311. if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
  312. return Info->getDescription();
  313. assert(CustomDiagInfo && "Invalid CustomDiagInfo");
  314. return CustomDiagInfo->getDescription(DiagID);
  315. }
  316. static DiagnosticIDs::Level toLevel(diag::Severity SV) {
  317. switch (SV) {
  318. case diag::Severity::Ignored:
  319. return DiagnosticIDs::Ignored;
  320. case diag::Severity::Remark:
  321. return DiagnosticIDs::Remark;
  322. case diag::Severity::Warning:
  323. return DiagnosticIDs::Warning;
  324. case diag::Severity::Error:
  325. return DiagnosticIDs::Error;
  326. case diag::Severity::Fatal:
  327. return DiagnosticIDs::Fatal;
  328. }
  329. llvm_unreachable("unexpected severity");
  330. }
  331. /// getDiagnosticLevel - Based on the way the client configured the
  332. /// DiagnosticsEngine object, classify the specified diagnostic ID into a Level,
  333. /// by consumable the DiagnosticClient.
  334. DiagnosticIDs::Level
  335. DiagnosticIDs::getDiagnosticLevel(unsigned DiagID, SourceLocation Loc,
  336. const DiagnosticsEngine &Diag) const {
  337. // Handle custom diagnostics, which cannot be mapped.
  338. if (DiagID >= diag::DIAG_UPPER_LIMIT) {
  339. assert(CustomDiagInfo && "Invalid CustomDiagInfo");
  340. return CustomDiagInfo->getLevel(DiagID);
  341. }
  342. unsigned DiagClass = getBuiltinDiagClass(DiagID);
  343. if (DiagClass == CLASS_NOTE) return DiagnosticIDs::Note;
  344. return toLevel(getDiagnosticSeverity(DiagID, Loc, Diag));
  345. }
  346. /// \brief Based on the way the client configured the Diagnostic
  347. /// object, classify the specified diagnostic ID into a Level, consumable by
  348. /// the DiagnosticClient.
  349. ///
  350. /// \param Loc The source location we are interested in finding out the
  351. /// diagnostic state. Can be null in order to query the latest state.
  352. diag::Severity
  353. DiagnosticIDs::getDiagnosticSeverity(unsigned DiagID, SourceLocation Loc,
  354. const DiagnosticsEngine &Diag) const {
  355. assert(getBuiltinDiagClass(DiagID) != CLASS_NOTE);
  356. // Specific non-error diagnostics may be mapped to various levels from ignored
  357. // to error. Errors can only be mapped to fatal.
  358. diag::Severity Result = diag::Severity::Fatal;
  359. DiagnosticsEngine::DiagStatePointsTy::iterator
  360. Pos = Diag.GetDiagStatePointForLoc(Loc);
  361. DiagnosticsEngine::DiagState *State = Pos->State;
  362. // Get the mapping information, or compute it lazily.
  363. DiagnosticMapping &Mapping = State->getOrAddMapping((diag::kind)DiagID);
  364. // TODO: Can a null severity really get here?
  365. if (Mapping.getSeverity() != diag::Severity())
  366. Result = Mapping.getSeverity();
  367. // Upgrade ignored diagnostics if -Weverything is enabled.
  368. if (Diag.EnableAllWarnings && Result == diag::Severity::Ignored &&
  369. !Mapping.isUser() && getBuiltinDiagClass(DiagID) != CLASS_REMARK)
  370. Result = diag::Severity::Warning;
  371. // Ignore -pedantic diagnostics inside __extension__ blocks.
  372. // (The diagnostics controlled by -pedantic are the extension diagnostics
  373. // that are not enabled by default.)
  374. bool EnabledByDefault = false;
  375. bool IsExtensionDiag = isBuiltinExtensionDiag(DiagID, EnabledByDefault);
  376. if (Diag.AllExtensionsSilenced && IsExtensionDiag && !EnabledByDefault)
  377. return diag::Severity::Ignored;
  378. // For extension diagnostics that haven't been explicitly mapped, check if we
  379. // should upgrade the diagnostic.
  380. if (IsExtensionDiag && !Mapping.isUser())
  381. Result = std::max(Result, Diag.ExtBehavior);
  382. // At this point, ignored errors can no longer be upgraded.
  383. if (Result == diag::Severity::Ignored)
  384. return Result;
  385. // Honor -w, which is lower in priority than pedantic-errors, but higher than
  386. // -Werror.
  387. if (Result == diag::Severity::Warning && Diag.IgnoreAllWarnings)
  388. return diag::Severity::Ignored;
  389. // If -Werror is enabled, map warnings to errors unless explicitly disabled.
  390. if (Result == diag::Severity::Warning) {
  391. if (Diag.WarningsAsErrors && !Mapping.hasNoWarningAsError())
  392. Result = diag::Severity::Error;
  393. }
  394. // If -Wfatal-errors is enabled, map errors to fatal unless explicity
  395. // disabled.
  396. if (Result == diag::Severity::Error) {
  397. if (Diag.ErrorsAsFatal && !Mapping.hasNoErrorAsFatal())
  398. Result = diag::Severity::Fatal;
  399. }
  400. // Custom diagnostics always are emitted in system headers.
  401. bool ShowInSystemHeader =
  402. !GetDiagInfo(DiagID) || GetDiagInfo(DiagID)->WarnShowInSystemHeader;
  403. // If we are in a system header, we ignore it. We look at the diagnostic class
  404. // because we also want to ignore extensions and warnings in -Werror and
  405. // -pedantic-errors modes, which *map* warnings/extensions to errors.
  406. if (Diag.SuppressSystemWarnings && !ShowInSystemHeader && Loc.isValid() &&
  407. Diag.getSourceManager().isInSystemHeader(
  408. Diag.getSourceManager().getExpansionLoc(Loc)))
  409. return diag::Severity::Ignored;
  410. return Result;
  411. }
  412. #define GET_DIAG_ARRAYS
  413. #include "clang/Basic/DiagnosticGroups.inc"
  414. #undef GET_DIAG_ARRAYS
  415. namespace {
  416. struct WarningOption {
  417. uint16_t NameOffset;
  418. uint16_t Members;
  419. uint16_t SubGroups;
  420. // String is stored with a pascal-style length byte.
  421. StringRef getName() const {
  422. return StringRef(DiagGroupNames + NameOffset + 1,
  423. DiagGroupNames[NameOffset]);
  424. }
  425. };
  426. }
  427. // Second the table of options, sorted by name for fast binary lookup.
  428. static const WarningOption OptionTable[] = {
  429. #define GET_DIAG_TABLE
  430. #include "clang/Basic/DiagnosticGroups.inc"
  431. #undef GET_DIAG_TABLE
  432. };
  433. static const size_t OptionTableSize = llvm::array_lengthof(OptionTable);
  434. static bool WarningOptionCompare(const WarningOption &LHS, StringRef RHS) {
  435. return LHS.getName() < RHS;
  436. }
  437. /// getWarningOptionForDiag - Return the lowest-level warning option that
  438. /// enables the specified diagnostic. If there is no -Wfoo flag that controls
  439. /// the diagnostic, this returns null.
  440. StringRef DiagnosticIDs::getWarningOptionForDiag(unsigned DiagID) {
  441. if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
  442. return OptionTable[Info->getOptionGroupIndex()].getName();
  443. return StringRef();
  444. }
  445. /// Return \c true if any diagnostics were found in this group, even if they
  446. /// were filtered out due to having the wrong flavor.
  447. static bool getDiagnosticsInGroup(diag::Flavor Flavor,
  448. const WarningOption *Group,
  449. SmallVectorImpl<diag::kind> &Diags) {
  450. // An empty group is considered to be a warning group: we have empty groups
  451. // for GCC compatibility, and GCC does not have remarks.
  452. if (!Group->Members && !Group->SubGroups)
  453. return Flavor == diag::Flavor::Remark;
  454. bool NotFound = true;
  455. // Add the members of the option diagnostic set.
  456. const int16_t *Member = DiagArrays + Group->Members;
  457. for (; *Member != -1; ++Member) {
  458. if (GetDiagInfo(*Member)->getFlavor() == Flavor) {
  459. NotFound = false;
  460. Diags.push_back(*Member);
  461. }
  462. }
  463. // Add the members of the subgroups.
  464. const int16_t *SubGroups = DiagSubGroups + Group->SubGroups;
  465. for (; *SubGroups != (int16_t)-1; ++SubGroups)
  466. NotFound &= getDiagnosticsInGroup(Flavor, &OptionTable[(short)*SubGroups],
  467. Diags);
  468. return NotFound;
  469. }
  470. bool
  471. DiagnosticIDs::getDiagnosticsInGroup(diag::Flavor Flavor, StringRef Group,
  472. SmallVectorImpl<diag::kind> &Diags) const {
  473. const WarningOption *Found = std::lower_bound(
  474. OptionTable, OptionTable + OptionTableSize, Group, WarningOptionCompare);
  475. if (Found == OptionTable + OptionTableSize ||
  476. Found->getName() != Group)
  477. return true; // Option not found.
  478. return ::getDiagnosticsInGroup(Flavor, Found, Diags);
  479. }
  480. void DiagnosticIDs::getAllDiagnostics(diag::Flavor Flavor,
  481. SmallVectorImpl<diag::kind> &Diags) const {
  482. for (unsigned i = 0; i != StaticDiagInfoSize; ++i)
  483. if (StaticDiagInfo[i].getFlavor() == Flavor)
  484. Diags.push_back(StaticDiagInfo[i].DiagID);
  485. }
  486. StringRef DiagnosticIDs::getNearestOption(diag::Flavor Flavor,
  487. StringRef Group) {
  488. StringRef Best;
  489. unsigned BestDistance = Group.size() + 1; // Sanity threshold.
  490. for (const WarningOption *i = OptionTable, *e = OptionTable + OptionTableSize;
  491. i != e; ++i) {
  492. // Don't suggest ignored warning flags.
  493. if (!i->Members && !i->SubGroups)
  494. continue;
  495. unsigned Distance = i->getName().edit_distance(Group, true, BestDistance);
  496. if (Distance > BestDistance)
  497. continue;
  498. // Don't suggest groups that are not of this kind.
  499. llvm::SmallVector<diag::kind, 8> Diags;
  500. if (::getDiagnosticsInGroup(Flavor, i, Diags) || Diags.empty())
  501. continue;
  502. if (Distance == BestDistance) {
  503. // Two matches with the same distance, don't prefer one over the other.
  504. Best = "";
  505. } else if (Distance < BestDistance) {
  506. // This is a better match.
  507. Best = i->getName();
  508. BestDistance = Distance;
  509. }
  510. }
  511. return Best;
  512. }
  513. /// ProcessDiag - This is the method used to report a diagnostic that is
  514. /// finally fully formed.
  515. bool DiagnosticIDs::ProcessDiag(DiagnosticsEngine &Diag) const {
  516. Diagnostic Info(&Diag);
  517. assert(Diag.getClient() && "DiagnosticClient not set!");
  518. // Figure out the diagnostic level of this message.
  519. unsigned DiagID = Info.getID();
  520. DiagnosticIDs::Level DiagLevel
  521. = getDiagnosticLevel(DiagID, Info.getLocation(), Diag);
  522. // Update counts for DiagnosticErrorTrap even if a fatal error occurred
  523. // or diagnostics are suppressed.
  524. if (DiagLevel >= DiagnosticIDs::Error) {
  525. ++Diag.TrapNumErrorsOccurred;
  526. if (isUnrecoverable(DiagID))
  527. ++Diag.TrapNumUnrecoverableErrorsOccurred;
  528. }
  529. if (Diag.SuppressAllDiagnostics)
  530. return false;
  531. if (DiagLevel != DiagnosticIDs::Note) {
  532. // Record that a fatal error occurred only when we see a second
  533. // non-note diagnostic. This allows notes to be attached to the
  534. // fatal error, but suppresses any diagnostics that follow those
  535. // notes.
  536. if (Diag.LastDiagLevel == DiagnosticIDs::Fatal)
  537. Diag.FatalErrorOccurred = true;
  538. Diag.LastDiagLevel = DiagLevel;
  539. }
  540. // If a fatal error has already been emitted, silence all subsequent
  541. // diagnostics.
  542. if (Diag.FatalErrorOccurred) {
  543. if (DiagLevel >= DiagnosticIDs::Error &&
  544. Diag.Client->IncludeInDiagnosticCounts()) {
  545. ++Diag.NumErrors;
  546. }
  547. return false;
  548. }
  549. // If the client doesn't care about this message, don't issue it. If this is
  550. // a note and the last real diagnostic was ignored, ignore it too.
  551. if (DiagLevel == DiagnosticIDs::Ignored ||
  552. (DiagLevel == DiagnosticIDs::Note &&
  553. Diag.LastDiagLevel == DiagnosticIDs::Ignored))
  554. return false;
  555. if (DiagLevel >= DiagnosticIDs::Error) {
  556. if (isUnrecoverable(DiagID))
  557. Diag.UnrecoverableErrorOccurred = true;
  558. // Warnings which have been upgraded to errors do not prevent compilation.
  559. if (isDefaultMappingAsError(DiagID))
  560. Diag.UncompilableErrorOccurred = true;
  561. Diag.ErrorOccurred = true;
  562. if (Diag.Client->IncludeInDiagnosticCounts()) {
  563. ++Diag.NumErrors;
  564. }
  565. // If we've emitted a lot of errors, emit a fatal error instead of it to
  566. // stop a flood of bogus errors.
  567. if (Diag.ErrorLimit && Diag.NumErrors > Diag.ErrorLimit &&
  568. DiagLevel == DiagnosticIDs::Error) {
  569. Diag.SetDelayedDiagnostic(diag::fatal_too_many_errors);
  570. return false;
  571. }
  572. }
  573. // Finally, report it.
  574. // HLSL Change - guard bad_alloc with a fatal error report.
  575. try {
  576. EmitDiag(Diag, DiagLevel);
  577. }
  578. catch (const std::bad_alloc &) {
  579. Diag.FatalErrorOccurred = true;
  580. Diag.ErrorOccurred = true;
  581. Diag.UnrecoverableErrorOccurred = true;
  582. }
  583. return true;
  584. }
  585. void DiagnosticIDs::EmitDiag(DiagnosticsEngine &Diag, Level DiagLevel) const {
  586. Diagnostic Info(&Diag);
  587. assert(DiagLevel != DiagnosticIDs::Ignored && "Cannot emit ignored diagnostics!");
  588. Diag.Client->HandleDiagnostic((DiagnosticsEngine::Level)DiagLevel, Info);
  589. if (Diag.Client->IncludeInDiagnosticCounts()) {
  590. if (DiagLevel == DiagnosticIDs::Warning)
  591. ++Diag.NumWarnings;
  592. }
  593. Diag.CurDiagID = ~0U;
  594. }
  595. bool DiagnosticIDs::isUnrecoverable(unsigned DiagID) const {
  596. if (DiagID >= diag::DIAG_UPPER_LIMIT) {
  597. assert(CustomDiagInfo && "Invalid CustomDiagInfo");
  598. // Custom diagnostics.
  599. return CustomDiagInfo->getLevel(DiagID) >= DiagnosticIDs::Error;
  600. }
  601. // Only errors may be unrecoverable.
  602. if (getBuiltinDiagClass(DiagID) < CLASS_ERROR)
  603. return false;
  604. if (DiagID == diag::err_unavailable ||
  605. DiagID == diag::err_unavailable_message)
  606. return false;
  607. // Currently we consider all ARC errors as recoverable.
  608. if (isARCDiagnostic(DiagID))
  609. return false;
  610. return true;
  611. }
  612. bool DiagnosticIDs::isARCDiagnostic(unsigned DiagID) {
  613. unsigned cat = getCategoryNumberForDiag(DiagID);
  614. return DiagnosticIDs::getCategoryNameFromID(cat).startswith("ARC ");
  615. }
  616. // HLSL Change Starts
  617. static_assert(std::is_nothrow_constructible<clang::DiagnosticIDs::Level>::value == 1, "enum cannot nothrow");
  618. static_assert(std::is_nothrow_constructible<std::string, llvm::StringRef>::value == 0, "string from StringRef can throw");
  619. static_assert(std::is_nothrow_constructible<std::string, llvm::StringRef &>::value == 0, "string from StringRef & can throw");
  620. static_assert(std::is_nothrow_constructible<std::pair<clang::DiagnosticIDs::Level, std::string>, std::pair<clang::DiagnosticIDs::Level, std::string>&>::value == 0, "pair can throw");
  621. // HLSL Change Starts Ends