Coverage Report

Created: 2020-09-15 12:33

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Basic/Diagnostic.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- Diagnostic.cpp - C Language Family Diagnostic 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-related interfaces.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Basic/Diagnostic.h"
14
#include "clang/Basic/CharInfo.h"
15
#include "clang/Basic/DiagnosticError.h"
16
#include "clang/Basic/DiagnosticIDs.h"
17
#include "clang/Basic/DiagnosticOptions.h"
18
#include "clang/Basic/IdentifierTable.h"
19
#include "clang/Basic/PartialDiagnostic.h"
20
#include "clang/Basic/SourceLocation.h"
21
#include "clang/Basic/SourceManager.h"
22
#include "clang/Basic/Specifiers.h"
23
#include "clang/Basic/TokenKinds.h"
24
#include "llvm/ADT/SmallString.h"
25
#include "llvm/ADT/SmallVector.h"
26
#include "llvm/ADT/StringExtras.h"
27
#include "llvm/ADT/StringRef.h"
28
#include "llvm/Support/CrashRecoveryContext.h"
29
#include "llvm/Support/Locale.h"
30
#include "llvm/Support/raw_ostream.h"
31
#include <algorithm>
32
#include <cassert>
33
#include <cstddef>
34
#include <cstdint>
35
#include <cstring>
36
#include <limits>
37
#include <string>
38
#include <utility>
39
#include <vector>
40
41
using namespace clang;
42
43
const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
44
133
                                           DiagNullabilityKind nullability) {
45
133
  StringRef string;
46
133
  switch (nullability.first) {
47
85
  case NullabilityKind::NonNull:
48
74
    string = nullability.second ? 
"'nonnull'"11
: "'_Nonnull'";
49
85
    break;
50
0
51
41
  case NullabilityKind::Nullable:
52
21
    string = nullability.second ? 
"'nullable'"20
: "'_Nullable'";
53
41
    break;
54
0
55
7
  case NullabilityKind::Unspecified:
56
4
    string = nullability.second ? "'null_unspecified'" : 
"'_Null_unspecified'"3
;
57
7
    break;
58
133
  }
59
133
60
133
  DB.AddString(string);
61
133
  return DB;
62
133
}
63
64
const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
65
6
                                           llvm::Error &&E) {
66
6
  DB.AddString(toString(std::move(E)));
67
6
  return DB;
68
6
}
69
70
static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT,
71
                            StringRef Modifier, StringRef Argument,
72
                            ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs,
73
                            SmallVectorImpl<char> &Output,
74
                            void *Cookie,
75
0
                            ArrayRef<intptr_t> QualTypeVals) {
76
0
  StringRef Str = "<can't format argument>";
77
0
  Output.append(Str.begin(), Str.end());
78
0
}
79
80
DiagnosticsEngine::DiagnosticsEngine(
81
    IntrusiveRefCntPtr<DiagnosticIDs> diags,
82
    IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, DiagnosticConsumer *client,
83
    bool ShouldOwnClient)
84
249k
    : Diags(std::move(diags)), DiagOpts(std::move(DiagOpts)) {
85
249k
  setClient(client, ShouldOwnClient);
86
249k
  ArgToStringFn = DummyArgToStringFn;
87
249k
88
249k
  Reset();
89
249k
}
90
91
240k
DiagnosticsEngine::~DiagnosticsEngine() {
92
  // If we own the diagnostic client, destroy it first so that it can access the
93
  // engine from its destructor.
94
240k
  setClient(nullptr);
95
240k
}
96
97
0
void DiagnosticsEngine::dump() const {
98
0
  DiagStatesByLoc.dump(*SourceMgr);
99
0
}
100
101
0
void DiagnosticsEngine::dump(StringRef DiagName) const {
102
0
  DiagStatesByLoc.dump(*SourceMgr, DiagName);
103
0
}
104
105
void DiagnosticsEngine::setClient(DiagnosticConsumer *client,
106
677k
                                  bool ShouldOwnClient) {
107
593k
  Owner.reset(ShouldOwnClient ? client : 
nullptr83.8k
);
108
677k
  Client = client;
109
677k
}
110
111
22.3k
void DiagnosticsEngine::pushMappings(SourceLocation Loc) {
112
22.3k
  DiagStateOnPushStack.push_back(GetCurDiagState());
113
22.3k
}
114
115
22.3k
bool DiagnosticsEngine::popMappings(SourceLocation Loc) {
116
22.3k
  if (DiagStateOnPushStack.empty())
117
2
    return false;
118
22.3k
119
22.3k
  if (DiagStateOnPushStack.back() != GetCurDiagState()) {
120
    // State changed at some point between push/pop.
121
22.3k
    PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
122
22.3k
  }
123
22.3k
  DiagStateOnPushStack.pop_back();
124
22.3k
  return true;
125
22.3k
}
126
127
257k
void DiagnosticsEngine::Reset() {
128
257k
  ErrorOccurred = false;
129
257k
  UncompilableErrorOccurred = false;
130
257k
  FatalErrorOccurred = false;
131
257k
  UnrecoverableErrorOccurred = false;
132
257k
133
257k
  NumWarnings = 0;
134
257k
  NumErrors = 0;
135
257k
  TrapNumErrorsOccurred = 0;
136
257k
  TrapNumUnrecoverableErrorsOccurred = 0;
137
257k
138
257k
  CurDiagID = std::numeric_limits<unsigned>::max();
139
257k
  LastDiagLevel = DiagnosticIDs::Ignored;
140
257k
  DelayedDiagID = 0;
141
257k
142
  // Clear state related to #pragma diagnostic.
143
257k
  DiagStates.clear();
144
257k
  DiagStatesByLoc.clear();
145
257k
  DiagStateOnPushStack.clear();
146
257k
147
  // Create a DiagState and DiagStatePoint representing diagnostic changes
148
  // through command-line.
149
257k
  DiagStates.emplace_back();
150
257k
  DiagStatesByLoc.appendFirst(&DiagStates.back());
151
257k
}
152
153
void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,
154
8
                                             StringRef Arg2, StringRef Arg3) {
155
8
  if (DelayedDiagID)
156
0
    return;
157
8
158
8
  DelayedDiagID = DiagID;
159
8
  DelayedDiagArg1 = Arg1.str();
160
8
  DelayedDiagArg2 = Arg2.str();
161
8
  DelayedDiagArg3 = Arg3.str();
162
8
}
163
164
8
void DiagnosticsEngine::ReportDelayed() {
165
8
  unsigned ID = DelayedDiagID;
166
8
  DelayedDiagID = 0;
167
8
  Report(ID) << DelayedDiagArg1 << DelayedDiagArg2 << DelayedDiagArg3;
168
8
}
169
170
257k
void DiagnosticsEngine::DiagStateMap::appendFirst(DiagState *State) {
171
257k
  assert(Files.empty() && "not first");
172
257k
  FirstDiagState = CurDiagState = State;
173
257k
  CurDiagStateLoc = SourceLocation();
174
257k
}
175
176
void DiagnosticsEngine::DiagStateMap::append(SourceManager &SrcMgr,
177
                                             SourceLocation Loc,
178
46.6k
                                             DiagState *State) {
179
46.6k
  CurDiagState = State;
180
46.6k
  CurDiagStateLoc = Loc;
181
46.6k
182
46.6k
  std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);
183
46.6k
  unsigned Offset = Decomp.second;
184
424k
  for (File *F = getFile(SrcMgr, Decomp.first); F;
185
377k
       Offset = F->ParentOffset, F = F->Parent) {
186
377k
    F->HasLocalTransitions = true;
187
377k
    auto &Last = F->StateTransitions.back();
188
377k
    assert(Last.Offset <= Offset && "state transitions added out of order");
189
377k
190
377k
    if (Last.Offset == Offset) {
191
290k
      if (Last.State == State)
192
0
        break;
193
290k
      Last.State = State;
194
290k
      continue;
195
290k
    }
196
87.1k
197
87.1k
    F->StateTransitions.push_back({State, Offset});
198
87.1k
  }
199
46.6k
}
200
201
DiagnosticsEngine::DiagState *
202
DiagnosticsEngine::DiagStateMap::lookup(SourceManager &SrcMgr,
203
147M
                                        SourceLocation Loc) const {
204
  // Common case: we have not seen any diagnostic pragmas.
205
147M
  if (Files.empty())
206
96.1M
    return FirstDiagState;
207
51.1M
208
51.1M
  std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);
209
51.1M
  const File *F = getFile(SrcMgr, Decomp.first);
210
51.1M
  return F->lookup(Decomp.second);
211
51.1M
}
212
213
DiagnosticsEngine::DiagState *
214
54.1M
DiagnosticsEngine::DiagStateMap::File::lookup(unsigned Offset) const {
215
54.1M
  auto OnePastIt =
216
62.9M
      llvm::partition_point(StateTransitions, [=](const DiagStatePoint &P) {
217
62.9M
        return P.Offset <= Offset;
218
62.9M
      });
219
54.1M
  assert(OnePastIt != StateTransitions.begin() && "missing initial state");
220
54.1M
  return OnePastIt[-1].State;
221
54.1M
}
222
223
DiagnosticsEngine::DiagStateMap::File *
224
DiagnosticsEngine::DiagStateMap::getFile(SourceManager &SrcMgr,
225
54.1M
                                         FileID ID) const {
226
  // Get or insert the File for this ID.
227
54.1M
  auto Range = Files.equal_range(ID);
228
54.1M
  if (Range.first != Range.second)
229
51.1M
    return &Range.first->second;
230
2.99M
  auto &F = Files.insert(Range.first, std::make_pair(ID, File()))->second;
231
2.99M
232
  // We created a new File; look up the diagnostic state at the start of it and
233
  // initialize it.
234
2.99M
  if (ID.isValid()) {
235
2.98M
    std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedIncludedLoc(ID);
236
2.98M
    F.Parent = getFile(SrcMgr, Decomp.first);
237
2.98M
    F.ParentOffset = Decomp.second;
238
2.98M
    F.StateTransitions.push_back({F.Parent->lookup(Decomp.second), 0});
239
3.29k
  } else {
240
    // This is the (imaginary) root file into which we pretend all top-level
241
    // files are included; it descends from the initial state.
242
    //
243
    // FIXME: This doesn't guarantee that we use the same ordering as
244
    // isBeforeInTranslationUnit in the cases where someone invented another
245
    // top-level file and added diagnostic pragmas to it. See the code at the
246
    // end of isBeforeInTranslationUnit for the quirks it deals with.
247
3.29k
    F.StateTransitions.push_back({FirstDiagState, 0});
248
3.29k
  }
249
2.99M
  return &F;
250
2.99M
}
251
252
void DiagnosticsEngine::DiagStateMap::dump(SourceManager &SrcMgr,
253
0
                                           StringRef DiagName) const {
254
0
  llvm::errs() << "diagnostic state at ";
255
0
  CurDiagStateLoc.print(llvm::errs(), SrcMgr);
256
0
  llvm::errs() << ": " << CurDiagState << "\n";
257
0
258
0
  for (auto &F : Files) {
259
0
    FileID ID = F.first;
260
0
    File &File = F.second;
261
0
262
0
    bool PrintedOuterHeading = false;
263
0
    auto PrintOuterHeading = [&] {
264
0
      if (PrintedOuterHeading) return;
265
0
      PrintedOuterHeading = true;
266
0
267
0
      llvm::errs() << "File " << &File << " <FileID " << ID.getHashValue()
268
0
                   << ">: " << SrcMgr.getBuffer(ID)->getBufferIdentifier();
269
0
      if (F.second.Parent) {
270
0
        std::pair<FileID, unsigned> Decomp =
271
0
            SrcMgr.getDecomposedIncludedLoc(ID);
272
0
        assert(File.ParentOffset == Decomp.second);
273
0
        llvm::errs() << " parent " << File.Parent << " <FileID "
274
0
                     << Decomp.first.getHashValue() << "> ";
275
0
        SrcMgr.getLocForStartOfFile(Decomp.first)
276
0
              .getLocWithOffset(Decomp.second)
277
0
              .print(llvm::errs(), SrcMgr);
278
0
      }
279
0
      if (File.HasLocalTransitions)
280
0
        llvm::errs() << " has_local_transitions";
281
0
      llvm::errs() << "\n";
282
0
    };
283
0
284
0
    if (DiagName.empty())
285
0
      PrintOuterHeading();
286
0
287
0
    for (DiagStatePoint &Transition : File.StateTransitions) {
288
0
      bool PrintedInnerHeading = false;
289
0
      auto PrintInnerHeading = [&] {
290
0
        if (PrintedInnerHeading) return;
291
0
        PrintedInnerHeading = true;
292
0
293
0
        PrintOuterHeading();
294
0
        llvm::errs() << "  ";
295
0
        SrcMgr.getLocForStartOfFile(ID)
296
0
              .getLocWithOffset(Transition.Offset)
297
0
              .print(llvm::errs(), SrcMgr);
298
0
        llvm::errs() << ": state " << Transition.State << ":\n";
299
0
      };
300
0
301
0
      if (DiagName.empty())
302
0
        PrintInnerHeading();
303
0
304
0
      for (auto &Mapping : *Transition.State) {
305
0
        StringRef Option =
306
0
            DiagnosticIDs::getWarningOptionForDiag(Mapping.first);
307
0
        if (!DiagName.empty() && DiagName != Option)
308
0
          continue;
309
0
310
0
        PrintInnerHeading();
311
0
        llvm::errs() << "    ";
312
0
        if (Option.empty())
313
0
          llvm::errs() << "<unknown " << Mapping.first << ">";
314
0
        else
315
0
          llvm::errs() << Option;
316
0
        llvm::errs() << ": ";
317
0
318
0
        switch (Mapping.second.getSeverity()) {
319
0
        case diag::Severity::Ignored: llvm::errs() << "ignored"; break;
320
0
        case diag::Severity::Remark: llvm::errs() << "remark"; break;
321
0
        case diag::Severity::Warning: llvm::errs() << "warning"; break;
322
0
        case diag::Severity::Error: llvm::errs() << "error"; break;
323
0
        case diag::Severity::Fatal: llvm::errs() << "fatal"; break;
324
0
        }
325
0
326
0
        if (!Mapping.second.isUser())
327
0
          llvm::errs() << " default";
328
0
        if (Mapping.second.isPragma())
329
0
          llvm::errs() << " pragma";
330
0
        if (Mapping.second.hasNoWarningAsError())
331
0
          llvm::errs() << " no-error";
332
0
        if (Mapping.second.hasNoErrorAsFatal())
333
0
          llvm::errs() << " no-fatal";
334
0
        if (Mapping.second.wasUpgradedFromWarning())
335
0
          llvm::errs() << " overruled";
336
0
        llvm::errs() << "\n";
337
0
      }
338
0
    }
339
0
  }
340
0
}
341
342
void DiagnosticsEngine::PushDiagStatePoint(DiagState *State,
343
46.6k
                                           SourceLocation Loc) {
344
46.6k
  assert(Loc.isValid() && "Adding invalid loc point");
345
46.6k
  DiagStatesByLoc.append(*SourceMgr, Loc, State);
346
46.6k
}
347
348
void DiagnosticsEngine::setSeverity(diag::kind Diag, diag::Severity Map,
349
2.01M
                                    SourceLocation L) {
350
2.01M
  assert(Diag < diag::DIAG_UPPER_LIMIT &&
351
2.01M
         "Can only map builtin diagnostics");
352
2.01M
  assert((Diags->isBuiltinWarningOrExtension(Diag) ||
353
2.01M
          (Map == diag::Severity::Fatal || Map == diag::Severity::Error)) &&
354
2.01M
         "Cannot map errors into warnings!");
355
2.01M
  assert((L.isInvalid() || SourceMgr) && "No SourceMgr for valid location");
356
2.01M
357
  // Don't allow a mapping to a warning override an error/fatal mapping.
358
2.01M
  bool WasUpgradedFromWarning = false;
359
2.01M
  if (Map == diag::Severity::Warning) {
360
380k
    DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
361
380k
    if (Info.getSeverity() == diag::Severity::Error ||
362
369k
        Info.getSeverity() == diag::Severity::Fatal) {
363
14.5k
      Map = Info.getSeverity();
364
14.5k
      WasUpgradedFromWarning = true;
365
14.5k
    }
366
380k
  }
367
2.01M
  DiagnosticMapping Mapping = makeUserMapping(Map, L);
368
2.01M
  Mapping.setUpgradedFromWarning(WasUpgradedFromWarning);
369
2.01M
370
  // Common case; setting all the diagnostics of a group in one place.
371
2.01M
  if ((L.isInvalid() || 
L == DiagStatesByLoc.getCurDiagStateLoc()518k
) &&
372
1.99M
      
DiagStatesByLoc.getCurDiagState()1.99M
) {
373
    // FIXME: This is theoretically wrong: if the current state is shared with
374
    // some other location (via push/pop) we will change the state for that
375
    // other location as well. This cannot currently happen, as we can't update
376
    // the diagnostic state at the same location at which we pop.
377
1.99M
    DiagStatesByLoc.getCurDiagState()->setMapping(Diag, Mapping);
378
1.99M
    return;
379
1.99M
  }
380
24.3k
381
  // A diagnostic pragma occurred, create a new DiagState initialized with
382
  // the current one and a new DiagStatePoint to record at which location
383
  // the new state became active.
384
24.3k
  DiagStates.push_back(*GetCurDiagState());
385
24.3k
  DiagStates.back().setMapping(Diag, Mapping);
386
24.3k
  PushDiagStatePoint(&DiagStates.back(), L);
387
24.3k
}
388
389
bool DiagnosticsEngine::setSeverityForGroup(diag::Flavor Flavor,
390
                                            StringRef Group, diag::Severity Map,
391
203k
                                            SourceLocation Loc) {
392
  // Get the diagnostics in this group.
393
203k
  SmallVector<diag::kind, 256> GroupDiags;
394
203k
  if (Diags->getDiagnosticsInGroup(Flavor, Group, GroupDiags))
395
42
    return true;
396
202k
397
  // Set the mapping.
398
202k
  for (diag::kind Diag : GroupDiags)
399
1.92M
    setSeverity(Diag, Map, Loc);
400
202k
401
202k
  return false;
402
202k
}
403
404
bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group,
405
92.7k
                                                         bool Enabled) {
406
  // If we are enabling this feature, just set the diagnostic mappings to map to
407
  // errors.
408
92.7k
  if (Enabled)
409
92.6k
    return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
410
92.6k
                               diag::Severity::Error);
411
58
412
  // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
413
  // potentially downgrade anything already mapped to be a warning.
414
58
415
  // Get the diagnostics in this group.
416
58
  SmallVector<diag::kind, 8> GroupDiags;
417
58
  if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
418
58
                                   GroupDiags))
419
0
    return true;
420
58
421
  // Perform the mapping change.
422
249
  
for (diag::kind Diag : GroupDiags)58
{
423
249
    DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
424
249
425
249
    if (Info.getSeverity() == diag::Severity::Error ||
426
131
        Info.getSeverity() == diag::Severity::Fatal)
427
118
      Info.setSeverity(diag::Severity::Warning);
428
249
429
249
    Info.setNoWarningAsError(true);
430
249
  }
431
58
432
58
  return false;
433
58
}
434
435
bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group,
436
1
                                                       bool Enabled) {
437
  // If we are enabling this feature, just set the diagnostic mappings to map to
438
  // fatal errors.
439
1
  if (Enabled)
440
1
    return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
441
1
                               diag::Severity::Fatal);
442
0
443
  // Otherwise, we want to set the diagnostic mapping's "no Wfatal-errors" bit,
444
  // and potentially downgrade anything already mapped to be a fatal error.
445
0
446
  // Get the diagnostics in this group.
447
0
  SmallVector<diag::kind, 8> GroupDiags;
448
0
  if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
449
0
                                   GroupDiags))
450
0
    return true;
451
0
452
  // Perform the mapping change.
453
0
  for (diag::kind Diag : GroupDiags) {
454
0
    DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
455
0
456
0
    if (Info.getSeverity() == diag::Severity::Fatal)
457
0
      Info.setSeverity(diag::Severity::Error);
458
0
459
0
    Info.setNoErrorAsFatal(true);
460
0
  }
461
0
462
0
  return false;
463
0
}
464
465
void DiagnosticsEngine::setSeverityForAll(diag::Flavor Flavor,
466
                                          diag::Severity Map,
467
44
                                          SourceLocation Loc) {
468
  // Get all the diagnostics.
469
44
  std::vector<diag::kind> AllDiags;
470
44
  DiagnosticIDs::getAllDiagnostics(Flavor, AllDiags);
471
44
472
  // Set the mapping.
473
44
  for (diag::kind Diag : AllDiags)
474
194k
    if (Diags->isBuiltinWarningOrExtension(Diag))
475
88.7k
      setSeverity(Diag, Map, Loc);
476
44
}
477
478
150
void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) {
479
150
  assert(CurDiagID == std::numeric_limits<unsigned>::max() &&
480
150
         "Multiple diagnostics in flight at once!");
481
150
482
150
  CurDiagLoc = storedDiag.getLocation();
483
150
  CurDiagID = storedDiag.getID();
484
150
  NumDiagArgs = 0;
485
150
486
150
  DiagRanges.clear();
487
150
  DiagRanges.append(storedDiag.range_begin(), storedDiag.range_end());
488
150
489
150
  DiagFixItHints.clear();
490
150
  DiagFixItHints.append(storedDiag.fixit_begin(), storedDiag.fixit_end());
491
150
492
150
  assert(Client && "DiagnosticConsumer not set!");
493
150
  Level DiagLevel = storedDiag.getLevel();
494
150
  Diagnostic Info(this, storedDiag.getMessage());
495
150
  Client->HandleDiagnostic(DiagLevel, Info);
496
150
  if (Client->IncludeInDiagnosticCounts()) {
497
150
    if (DiagLevel == DiagnosticsEngine::Warning)
498
1
      ++NumWarnings;
499
150
  }
500
150
501
150
  CurDiagID = std::numeric_limits<unsigned>::max();
502
150
}
503
504
6.50M
bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) {
505
6.50M
  assert(getClient() && "DiagnosticClient not set!");
506
6.50M
507
6.50M
  bool Emitted;
508
6.50M
  if (Force) {
509
125
    Diagnostic Info(this);
510
125
511
    // Figure out the diagnostic level of this message.
512
125
    DiagnosticIDs::Level DiagLevel
513
125
      = Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this);
514
125
515
125
    Emitted = (DiagLevel != DiagnosticIDs::Ignored);
516
125
    if (Emitted) {
517
      // Emit the diagnostic regardless of suppression level.
518
125
      Diags->EmitDiag(*this, DiagLevel);
519
125
    }
520
6.50M
  } else {
521
    // Process the diagnostic, sending the accumulated information to the
522
    // DiagnosticConsumer.
523
6.50M
    Emitted = ProcessDiag();
524
6.50M
  }
525
6.50M
526
  // Clear out the current diagnostic object.
527
6.50M
  Clear();
528
6.50M
529
  // If there was a delayed diagnostic, emit it now.
530
6.50M
  if (!Force && 
DelayedDiagID6.50M
)
531
8
    ReportDelayed();
532
6.50M
533
6.50M
  return Emitted;
534
6.50M
}
535
536
254k
DiagnosticConsumer::~DiagnosticConsumer() = default;
537
538
void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
539
392k
                                        const Diagnostic &Info) {
540
392k
  if (!IncludeInDiagnosticCounts())
541
4
    return;
542
392k
543
392k
  if (DiagLevel == DiagnosticsEngine::Warning)
544
75.3k
    ++NumWarnings;
545
317k
  else if (DiagLevel >= DiagnosticsEngine::Error)
546
193k
    ++NumErrors;
547
392k
}
548
549
/// ModifierIs - Return true if the specified modifier matches specified string.
550
template <std::size_t StrLen>
551
static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
552
804k
                       const char (&Str)[StrLen]) {
553
804k
  return StrLen-1 == ModifierLen && 
memcmp(Modifier, Str, StrLen-1) == 0215k
;
554
804k
}
Diagnostic.cpp:bool ModifierIs<5ul>(char const*, unsigned int, char const (&) [5ul])
Line
Count
Source
552
530k
                       const char (&Str)[StrLen]) {
553
530k
  return StrLen-1 == ModifierLen && 
memcmp(Modifier, Str, StrLen-1) == 016.7k
;
554
530k
}
Diagnostic.cpp:bool ModifierIs<7ul>(char const*, unsigned int, char const (&) [7ul])
Line
Count
Source
552
230k
                       const char (&Str)[StrLen]) {
553
230k
  return StrLen-1 == ModifierLen && 
memcmp(Modifier, Str, StrLen-1) == 0189k
;
554
230k
}
Diagnostic.cpp:bool ModifierIs<2ul>(char const*, unsigned int, char const (&) [2ul])
Line
Count
Source
552
23.7k
                       const char (&Str)[StrLen]) {
553
23.7k
  return StrLen-1 == ModifierLen && 
memcmp(Modifier, Str, StrLen-1) == 01.43k
;
554
23.7k
}
Diagnostic.cpp:bool ModifierIs<8ul>(char const*, unsigned int, char const (&) [8ul])
Line
Count
Source
552
19.8k
                       const char (&Str)[StrLen]) {
553
19.8k
  return StrLen-1 == ModifierLen && 
memcmp(Modifier, Str, StrLen-1) == 07.77k
;
554
19.8k
}
555
556
/// ScanForward - Scans forward, looking for the given character, skipping
557
/// nested clauses and escaped characters.
558
574k
static const char *ScanFormat(const char *I, const char *E, char Target) {
559
574k
  unsigned Depth = 0;
560
574k
561
30.7M
  for ( ; I != E; 
++I30.1M
) {
562
30.7M
    if (Depth == 0 && 
*I == Target23.8M
)
return I527k
;
563
30.1M
    if (Depth != 0 && 
*I == '}'6.84M
)
Depth--122k
;
564
30.1M
565
30.1M
    if (*I == '%') {
566
315k
      I++;
567
315k
      if (I == E) 
break0
;
568
315k
569
      // Escaped characters get implicitly skipped here.
570
315k
571
      // Format specifier.
572
315k
      if (!isDigit(*I) && 
!isPunctuation(*I)152k
) {
573
747k
        for (I++; I != E && !isDigit(*I) && 
*I != '{'718k
;
I++595k
)
;595k
574
151k
        if (I == E) 
break0
;
575
151k
        if (*I == '{')
576
122k
          Depth++;
577
151k
      }
578
315k
    }
579
30.1M
  }
580
46.9k
  return E;
581
574k
}
582
583
/// HandleSelectModifier - Handle the integer 'select' modifier.  This is used
584
/// like this:  %select{foo|bar|baz}2.  This means that the integer argument
585
/// "%2" has a value from 0-2.  If the value is 0, the diagnostic prints 'foo'.
586
/// If the value is 1, it prints 'bar'.  If it has the value 2, it prints 'baz'.
587
/// This is very useful for certain classes of variant diagnostics.
588
static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo,
589
                                 const char *Argument, unsigned ArgumentLen,
590
184k
                                 SmallVectorImpl<char> &OutStr) {
591
184k
  const char *ArgumentEnd = Argument+ArgumentLen;
592
184k
593
  // Skip over 'ValNo' |'s.
594
317k
  while (ValNo) {
595
132k
    const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
596
132k
    assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
597
132k
           " larger than the number of options in the diagnostic string!");
598
132k
    Argument = NextVal+1;  // Skip this string.
599
132k
    --ValNo;
600
132k
  }
601
184k
602
  // Get the end of the value.  This is either the } or the |.
603
184k
  const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
604
184k
605
  // Recursively format the result of the select clause into the output string.
606
184k
  DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
607
184k
}
608
609
/// HandleIntegerSModifier - Handle the integer 's' modifier.  This adds the
610
/// letter 's' to the string if the value is not 1.  This is used in cases like
611
/// this:  "you idiot, you have %4 parameter%s4!".
612
static void HandleIntegerSModifier(unsigned ValNo,
613
1.43k
                                   SmallVectorImpl<char> &OutStr) {
614
1.43k
  if (ValNo != 1)
615
808
    OutStr.push_back('s');
616
1.43k
}
617
618
/// HandleOrdinalModifier - Handle the integer 'ord' modifier.  This
619
/// prints the ordinal form of the given integer, with 1 corresponding
620
/// to the first ordinal.  Currently this is hard-coded to use the
621
/// English form.
622
static void HandleOrdinalModifier(unsigned ValNo,
623
7.77k
                                  SmallVectorImpl<char> &OutStr) {
624
7.77k
  assert(ValNo != 0 && "ValNo must be strictly positive!");
625
7.77k
626
7.77k
  llvm::raw_svector_ostream Out(OutStr);
627
7.77k
628
  // We could use text forms for the first N ordinals, but the numeric
629
  // forms are actually nicer in diagnostics because they stand out.
630
7.77k
  Out << ValNo << llvm::getOrdinalSuffix(ValNo);
631
7.77k
}
632
633
/// PluralNumber - Parse an unsigned integer and advance Start.
634
3.06k
static unsigned PluralNumber(const char *&Start, const char *End) {
635
  // Programming 101: Parse a decimal number :-)
636
3.06k
  unsigned Val = 0;
637
6.12k
  while (Start != End && 
*Start >= '0'3.07k
&&
*Start <= '9'3.07k
) {
638
3.06k
    Val *= 10;
639
3.06k
    Val += *Start - '0';
640
3.06k
    ++Start;
641
3.06k
  }
642
3.06k
  return Val;
643
3.06k
}
644
645
/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
646
3.05k
static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
647
3.05k
  if (*Start != '[') {
648
3.05k
    unsigned Ref = PluralNumber(Start, End);
649
3.05k
    return Ref == Val;
650
3.05k
  }
651
7
652
7
  ++Start;
653
7
  unsigned Low = PluralNumber(Start, End);
654
7
  assert(*Start == ',' && "Bad plural expression syntax: expected ,");
655
7
  ++Start;
656
7
  unsigned High = PluralNumber(Start, End);
657
7
  assert(*Start == ']' && "Bad plural expression syntax: expected )");
658
7
  ++Start;
659
7
  return Low <= Val && Val <= High;
660
7
}
661
662
/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
663
4.41k
static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
664
  // Empty condition?
665
4.41k
  if (*Start == ':')
666
1.36k
    return true;
667
3.05k
668
3.05k
  while (true) {
669
3.05k
    char C = *Start;
670
3.05k
    if (C == '%') {
671
      // Modulo expression
672
0
      ++Start;
673
0
      unsigned Arg = PluralNumber(Start, End);
674
0
      assert(*Start == '=' && "Bad plural expression syntax: expected =");
675
0
      ++Start;
676
0
      unsigned ValMod = ValNo % Arg;
677
0
      if (TestPluralRange(ValMod, Start, End))
678
0
        return true;
679
3.05k
    } else {
680
3.05k
      assert((C == '[' || (C >= '0' && C <= '9')) &&
681
3.05k
             "Bad plural expression syntax: unexpected character");
682
      // Range expression
683
3.05k
      if (TestPluralRange(ValNo, Start, End))
684
1.16k
        return true;
685
1.89k
    }
686
1.89k
687
    // Scan for next or-expr part.
688
1.89k
    Start = std::find(Start, End, ',');
689
1.89k
    if (Start == End)
690
1.89k
      break;
691
0
    ++Start;
692
0
  }
693
1.89k
  return false;
694
3.05k
}
695
696
/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
697
/// for complex plural forms, or in languages where all plurals are complex.
698
/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
699
/// conditions that are tested in order, the form corresponding to the first
700
/// that applies being emitted. The empty condition is always true, making the
701
/// last form a default case.
702
/// Conditions are simple boolean expressions, where n is the number argument.
703
/// Here are the rules.
704
/// condition  := expression | empty
705
/// empty      :=                             -> always true
706
/// expression := numeric [',' expression]    -> logical or
707
/// numeric    := range                       -> true if n in range
708
///             | '%' number '=' range        -> true if n % number in range
709
/// range      := number
710
///             | '[' number ',' number ']'   -> ranges are inclusive both ends
711
///
712
/// Here are some examples from the GNU gettext manual written in this form:
713
/// English:
714
/// {1:form0|:form1}
715
/// Latvian:
716
/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
717
/// Gaeilge:
718
/// {1:form0|2:form1|:form2}
719
/// Romanian:
720
/// {1:form0|0,%100=[1,19]:form1|:form2}
721
/// Lithuanian:
722
/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
723
/// Russian (requires repeated form):
724
/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
725
/// Slovak
726
/// {1:form0|[2,4]:form1|:form2}
727
/// Polish (requires repeated form):
728
/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
729
static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo,
730
                                 const char *Argument, unsigned ArgumentLen,
731
2.52k
                                 SmallVectorImpl<char> &OutStr) {
732
2.52k
  const char *ArgumentEnd = Argument + ArgumentLen;
733
4.41k
  while (true) {
734
4.41k
    assert(Argument < ArgumentEnd && "Plural expression didn't match.");
735
4.41k
    const char *ExprEnd = Argument;
736
7.50k
    while (*ExprEnd != ':') {
737
3.08k
      assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
738
3.08k
      ++ExprEnd;
739
3.08k
    }
740
4.41k
    if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
741
2.52k
      Argument = ExprEnd + 1;
742
2.52k
      ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
743
2.52k
744
      // Recursively format the result of the plural clause into the
745
      // output string.
746
2.52k
      DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
747
2.52k
      return;
748
2.52k
    }
749
1.89k
    Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
750
1.89k
  }
751
2.52k
}
752
753
/// Returns the friendly description for a token kind that will appear
754
/// without quotes in diagnostic messages. These strings may be translatable in
755
/// future.
756
301
static const char *getTokenDescForDiagnostic(tok::TokenKind Kind) {
757
301
  switch (Kind) {
758
299
  case tok::identifier:
759
299
    return "identifier";
760
2
  default:
761
2
    return nullptr;
762
301
  }
763
301
}
764
765
/// FormatDiagnostic - Format this diagnostic into a string, substituting the
766
/// formal arguments into the %0 slots.  The result is appended onto the Str
767
/// array.
768
void Diagnostic::
769
394k
FormatDiagnostic(SmallVectorImpl<char> &OutStr) const {
770
394k
  if (!StoredDiagMessage.empty()) {
771
153
    OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
772
153
    return;
773
153
  }
774
393k
775
393k
  StringRef Diag =
776
393k
    getDiags()->getDiagnosticIDs()->getDescription(getID());
777
393k
778
393k
  FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
779
393k
}
780
781
void Diagnostic::
782
FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
783
630k
                 SmallVectorImpl<char> &OutStr) const {
784
  // When the diagnostic string is only "%0", the entire string is being given
785
  // by an outside source.  Remove unprintable characters from this string
786
  // and skip all the other string processing.
787
630k
  if (DiagEnd - DiagStr == 2 &&
788
23.0k
      StringRef(DiagStr, DiagEnd - DiagStr).equals("%0") &&
789
20.2k
      getArgKind(0) == DiagnosticsEngine::ak_std_string) {
790
20.1k
    const std::string &S = getArgStdStr(0);
791
1.02M
    for (char c : S) {
792
1.02M
      if (llvm::sys::locale::isPrint(c) || 
c == '\t'376
) {
793
1.02M
        OutStr.push_back(c);
794
1.02M
      }
795
1.02M
    }
796
20.1k
    return;
797
20.1k
  }
798
610k
799
  /// FormattedArgs - Keep track of all of the arguments formatted by
800
  /// ConvertArgToString and pass them into subsequent calls to
801
  /// ConvertArgToString, allowing the implementation to avoid redundancies in
802
  /// obvious cases.
803
610k
  SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs;
804
610k
805
  /// QualTypeVals - Pass a vector of arrays so that QualType names can be
806
  /// compared to see if more information is needed to be printed.
807
610k
  SmallVector<intptr_t, 2> QualTypeVals;
808
610k
  SmallVector<char, 64> Tree;
809
610k
810
2.21M
  for (unsigned i = 0, e = getNumArgs(); i < e; 
++i1.60M
)
811
1.60M
    if (getArgKind(i) == DiagnosticsEngine::ak_qualtype)
812
318k
      QualTypeVals.push_back(getRawArg(i));
813
610k
814
1.90M
  while (DiagStr != DiagEnd) {
815
1.29M
    if (DiagStr[0] != '%') {
816
      // Append non-%0 substrings to Str if we have one.
817
768k
      const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
818
768k
      OutStr.append(DiagStr, StrEnd);
819
768k
      DiagStr = StrEnd;
820
768k
      continue;
821
530k
    } else if (isPunctuation(DiagStr[1])) {
822
113
      OutStr.push_back(DiagStr[1]);  // %% -> %.
823
113
      DiagStr += 2;
824
113
      continue;
825
113
    }
826
530k
827
    // Skip the %.
828
530k
    ++DiagStr;
829
530k
830
    // This must be a placeholder for a diagnostic argument.  The format for a
831
    // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
832
    // The digit is a number from 0-9 indicating which argument this comes from.
833
    // The modifier is a string of digits from the set [-a-z]+, arguments is a
834
    // brace enclosed string.
835
530k
    const char *Modifier = nullptr, *Argument = nullptr;
836
530k
    unsigned ModifierLen = 0, ArgumentLen = 0;
837
530k
838
    // Check to see if we have a modifier.  If so eat it.
839
530k
    if (!isDigit(DiagStr[0])) {
840
221k
      Modifier = DiagStr;
841
1.48M
      while (DiagStr[0] == '-' ||
842
1.48M
             (DiagStr[0] >= 'a' && 
DiagStr[0] <= 'z'1.46M
))
843
1.26M
        ++DiagStr;
844
221k
      ModifierLen = DiagStr-Modifier;
845
221k
846
      // If we have an argument, get it next.
847
221k
      if (DiagStr[0] == '{') {
848
203k
        ++DiagStr; // Skip {.
849
203k
        Argument = DiagStr;
850
203k
851
203k
        DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
852
203k
        assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
853
203k
        ArgumentLen = DiagStr-Argument;
854
203k
        ++DiagStr;  // Skip }.
855
203k
      }
856
221k
    }
857
530k
858
530k
    assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic");
859
530k
    unsigned ArgNo = *DiagStr++ - '0';
860
530k
861
    // Only used for type diffing.
862
530k
    unsigned ArgNo2 = ArgNo;
863
530k
864
530k
    DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo);
865
530k
    if (ModifierIs(Modifier, ModifierLen, "diff")) {
866
16.7k
      assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) &&
867
16.7k
             "Invalid format for diff modifier");
868
16.7k
      ++DiagStr;  // Comma.
869
16.7k
      ArgNo2 = *DiagStr++ - '0';
870
16.7k
      DiagnosticsEngine::ArgumentKind Kind2 = getArgKind(ArgNo2);
871
16.7k
      if (Kind == DiagnosticsEngine::ak_qualtype &&
872
16.6k
          Kind2 == DiagnosticsEngine::ak_qualtype)
873
16.6k
        Kind = DiagnosticsEngine::ak_qualtype_pair;
874
80
      else {
875
        // %diff only supports QualTypes.  For other kinds of arguments,
876
        // use the default printing.  For example, if the modifier is:
877
        //   "%diff{compare $ to $|other text}1,2"
878
        // treat it as:
879
        //   "compare %1 to %2"
880
80
        const char *ArgumentEnd = Argument + ArgumentLen;
881
80
        const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
882
80
        assert(ScanFormat(Pipe + 1, ArgumentEnd, '|') == ArgumentEnd &&
883
80
               "Found too many '|'s in a %diff modifier!");
884
80
        const char *FirstDollar = ScanFormat(Argument, Pipe, '$');
885
80
        const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$');
886
80
        const char ArgStr1[] = { '%', static_cast<char>('0' + ArgNo) };
887
80
        const char ArgStr2[] = { '%', static_cast<char>('0' + ArgNo2) };
888
80
        FormatDiagnostic(Argument, FirstDollar, OutStr);
889
80
        FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr);
890
80
        FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
891
80
        FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr);
892
80
        FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
893
80
        continue;
894
80
      }
895
530k
    }
896
530k
897
530k
    switch (Kind) {
898
    // ---- STRINGS ----
899
110k
    case DiagnosticsEngine::ak_std_string: {
900
110k
      const std::string &S = getArgStdStr(ArgNo);
901
110k
      assert(ModifierLen == 0 && "No modifiers for strings yet");
902
110k
      OutStr.append(S.begin(), S.end());
903
110k
      break;
904
0
    }
905
15.2k
    case DiagnosticsEngine::ak_c_string: {
906
15.2k
      const char *S = getArgCStr(ArgNo);
907
15.2k
      assert(ModifierLen == 0 && "No modifiers for strings yet");
908
15.2k
909
      // Don't crash if get passed a null pointer by accident.
910
15.2k
      if (!S)
911
0
        S = "(null)";
912
15.2k
913
15.2k
      OutStr.append(S, S + strlen(S));
914
15.2k
      break;
915
0
    }
916
    // ---- INTEGERS ----
917
119k
    case DiagnosticsEngine::ak_sint: {
918
119k
      int Val = getArgSInt(ArgNo);
919
119k
920
119k
      if (ModifierIs(Modifier, ModifierLen, "select")) {
921
114k
        HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
922
114k
                             OutStr);
923
5.69k
      } else if (ModifierIs(Modifier, ModifierLen, "s")) {
924
37
        HandleIntegerSModifier(Val, OutStr);
925
5.65k
      } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
926
599
        HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
927
599
                             OutStr);
928
5.05k
      } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
929
38
        HandleOrdinalModifier((unsigned)Val, OutStr);
930
5.01k
      } else {
931
5.01k
        assert(ModifierLen == 0 && "Unknown integer modifier");
932
5.01k
        llvm::raw_svector_ostream(OutStr) << Val;
933
5.01k
      }
934
119k
      break;
935
0
    }
936
88.3k
    case DiagnosticsEngine::ak_uint: {
937
88.3k
      unsigned Val = getArgUInt(ArgNo);
938
88.3k
939
88.3k
      if (ModifierIs(Modifier, ModifierLen, "select")) {
940
70.2k
        HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
941
18.0k
      } else if (ModifierIs(Modifier, ModifierLen, "s")) {
942
1.40k
        HandleIntegerSModifier(Val, OutStr);
943
16.6k
      } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
944
1.92k
        HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
945
1.92k
                             OutStr);
946
14.7k
      } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
947
7.73k
        HandleOrdinalModifier(Val, OutStr);
948
7.01k
      } else {
949
7.01k
        assert(ModifierLen == 0 && "Unknown integer modifier");
950
7.01k
        llvm::raw_svector_ostream(OutStr) << Val;
951
7.01k
      }
952
88.3k
      break;
953
0
    }
954
    // ---- TOKEN SPELLINGS ----
955
37.8k
    case DiagnosticsEngine::ak_tokenkind: {
956
37.8k
      tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo));
957
37.8k
      assert(ModifierLen == 0 && "No modifiers for token kinds yet");
958
37.8k
959
37.8k
      llvm::raw_svector_ostream Out(OutStr);
960
37.8k
      if (const char *S = tok::getPunctuatorSpelling(Kind))
961
        // Quoted token spelling for punctuators.
962
37.5k
        Out << '\'' << S << '\'';
963
325
      else if (const char *S = tok::getKeywordSpelling(Kind))
964
        // Unquoted token spelling for keywords.
965
24
        Out << S;
966
301
      else if (const char *S = getTokenDescForDiagnostic(Kind))
967
        // Unquoted translatable token name.
968
299
        Out << S;
969
2
      else if (const char *S = tok::getTokenName(Kind))
970
        // Debug name, shouldn't appear in user-facing diagnostics.
971
2
        Out << '<' << S << '>';
972
0
      else
973
0
        Out << "(null)";
974
37.8k
      break;
975
0
    }
976
    // ---- NAMES and TYPES ----
977
14.2k
    case DiagnosticsEngine::ak_identifierinfo: {
978
14.2k
      const IdentifierInfo *II = getArgIdentifier(ArgNo);
979
14.2k
      assert(ModifierLen == 0 && "No modifiers for strings yet");
980
14.2k
981
      // Don't crash if get passed a null pointer by accident.
982
14.2k
      if (!II) {
983
8
        const char *S = "(null)";
984
8
        OutStr.append(S, S + strlen(S));
985
8
        continue;
986
8
      }
987
14.2k
988
14.2k
      llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
989
14.2k
      break;
990
14.2k
    }
991
127k
    case DiagnosticsEngine::ak_addrspace:
992
127k
    case DiagnosticsEngine::ak_qual:
993
127k
    case DiagnosticsEngine::ak_qualtype:
994
127k
    case DiagnosticsEngine::ak_declarationname:
995
127k
    case DiagnosticsEngine::ak_nameddecl:
996
127k
    case DiagnosticsEngine::ak_nestednamespec:
997
127k
    case DiagnosticsEngine::ak_declcontext:
998
127k
    case DiagnosticsEngine::ak_attr:
999
127k
      getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
1000
127k
                                     StringRef(Modifier, ModifierLen),
1001
127k
                                     StringRef(Argument, ArgumentLen),
1002
127k
                                     FormattedArgs,
1003
127k
                                     OutStr, QualTypeVals);
1004
127k
      break;
1005
16.6k
    case DiagnosticsEngine::ak_qualtype_pair: {
1006
      // Create a struct with all the info needed for printing.
1007
16.6k
      TemplateDiffTypes TDT;
1008
16.6k
      TDT.FromType = getRawArg(ArgNo);
1009
16.6k
      TDT.ToType = getRawArg(ArgNo2);
1010
16.6k
      TDT.ElideType = getDiags()->ElideType;
1011
16.6k
      TDT.ShowColors = getDiags()->ShowColors;
1012
16.6k
      TDT.TemplateDiffUsed = false;
1013
16.6k
      intptr_t val = reinterpret_cast<intptr_t>(&TDT);
1014
16.6k
1015
16.6k
      const char *ArgumentEnd = Argument + ArgumentLen;
1016
16.6k
      const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
1017
16.6k
1018
      // Print the tree.  If this diagnostic already has a tree, skip the
1019
      // second tree.
1020
16.6k
      if (getDiags()->PrintTemplateTree && 
Tree.empty()577
) {
1021
577
        TDT.PrintFromType = true;
1022
577
        TDT.PrintTree = true;
1023
577
        getDiags()->ConvertArgToString(Kind, val,
1024
577
                                       StringRef(Modifier, ModifierLen),
1025
577
                                       StringRef(Argument, ArgumentLen),
1026
577
                                       FormattedArgs,
1027
577
                                       Tree, QualTypeVals);
1028
        // If there is no tree information, fall back to regular printing.
1029
577
        if (!Tree.empty()) {
1030
347
          FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr);
1031
347
          break;
1032
347
        }
1033
16.2k
      }
1034
16.2k
1035
      // Non-tree printing, also the fall-back when tree printing fails.
1036
      // The fall-back is triggered when the types compared are not templates.
1037
16.2k
      const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$');
1038
16.2k
      const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$');
1039
16.2k
1040
      // Append before text
1041
16.2k
      FormatDiagnostic(Argument, FirstDollar, OutStr);
1042
16.2k
1043
      // Append first type
1044
16.2k
      TDT.PrintTree = false;
1045
16.2k
      TDT.PrintFromType = true;
1046
16.2k
      getDiags()->ConvertArgToString(Kind, val,
1047
16.2k
                                     StringRef(Modifier, ModifierLen),
1048
16.2k
                                     StringRef(Argument, ArgumentLen),
1049
16.2k
                                     FormattedArgs,
1050
16.2k
                                     OutStr, QualTypeVals);
1051
16.2k
      if (!TDT.TemplateDiffUsed)
1052
15.8k
        FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
1053
15.8k
                                               TDT.FromType));
1054
16.2k
1055
      // Append middle text
1056
16.2k
      FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
1057
16.2k
1058
      // Append second type
1059
16.2k
      TDT.PrintFromType = false;
1060
16.2k
      getDiags()->ConvertArgToString(Kind, val,
1061
16.2k
                                     StringRef(Modifier, ModifierLen),
1062
16.2k
                                     StringRef(Argument, ArgumentLen),
1063
16.2k
                                     FormattedArgs,
1064
16.2k
                                     OutStr, QualTypeVals);
1065
16.2k
      if (!TDT.TemplateDiffUsed)
1066
15.8k
        FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
1067
15.8k
                                               TDT.ToType));
1068
16.2k
1069
      // Append end text
1070
16.2k
      FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
1071
16.2k
      break;
1072
16.2k
    }
1073
530k
    }
1074
530k
1075
    // Remember this argument info for subsequent formatting operations.  Turn
1076
    // std::strings into a null terminated string to make it be the same case as
1077
    // all the other ones.
1078
530k
    if (Kind == DiagnosticsEngine::ak_qualtype_pair)
1079
16.6k
      continue;
1080
513k
    else if (Kind != DiagnosticsEngine::ak_std_string)
1081
403k
      FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
1082
110k
    else
1083
110k
      FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string,
1084
110k
                                        (intptr_t)getArgStdStr(ArgNo).c_str()));
1085
530k
  }
1086
610k
1087
  // Append the type tree to the end of the diagnostics.
1088
610k
  OutStr.append(Tree.begin(), Tree.end());
1089
610k
}
1090
1091
StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1092
                                   StringRef Message)
1093
0
    : ID(ID), Level(Level), Message(Message) {}
1094
1095
StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level,
1096
                                   const Diagnostic &Info)
1097
10.9k
    : ID(Info.getID()), Level(Level) {
1098
10.9k
  assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
1099
10.9k
       "Valid source location without setting a source manager for diagnostic");
1100
10.9k
  if (Info.getLocation().isValid())
1101
10.9k
    Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
1102
10.9k
  SmallString<64> Message;
1103
10.9k
  Info.FormatDiagnostic(Message);
1104
10.9k
  this->Message.assign(Message.begin(), Message.end());
1105
10.9k
  this->Ranges.assign(Info.getRanges().begin(), Info.getRanges().end());
1106
10.9k
  this->FixIts.assign(Info.getFixItHints().begin(), Info.getFixItHints().end());
1107
10.9k
}
1108
1109
StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1110
                                   StringRef Message, FullSourceLoc Loc,
1111
                                   ArrayRef<CharSourceRange> Ranges,
1112
                                   ArrayRef<FixItHint> FixIts)
1113
    : ID(ID), Level(Level), Loc(Loc), Message(Message),
1114
      Ranges(Ranges.begin(), Ranges.end()), FixIts(FixIts.begin(), FixIts.end())
1115
85
{
1116
85
}
1117
1118
/// IncludeInDiagnosticCounts - This method (whose default implementation
1119
///  returns true) indicates whether the diagnostics handled by this
1120
///  DiagnosticConsumer should be included in the number of diagnostics
1121
///  reported by DiagnosticsEngine.
1122
978k
bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; }
1123
1124
0
void IgnoringDiagConsumer::anchor() {}
1125
1126
1.72k
ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer() = default;
1127
1128
void ForwardingDiagnosticConsumer::HandleDiagnostic(
1129
       DiagnosticsEngine::Level DiagLevel,
1130
600
       const Diagnostic &Info) {
1131
600
  Target.HandleDiagnostic(DiagLevel, Info);
1132
600
}
1133
1134
0
void ForwardingDiagnosticConsumer::clear() {
1135
0
  DiagnosticConsumer::clear();
1136
0
  Target.clear();
1137
0
}
1138
1139
653
bool ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts() const {
1140
653
  return Target.IncludeInDiagnosticCounts();
1141
653
}
1142
1143
83.7k
PartialDiagnostic::StorageAllocator::StorageAllocator() {
1144
1.42M
  for (unsigned I = 0; I != NumCached; 
++I1.33M
)
1145
1.33M
    FreeList[I] = Cached + I;
1146
83.7k
  NumFreeListEntries = NumCached;
1147
83.7k
}
1148
1149
78.6k
PartialDiagnostic::StorageAllocator::~StorageAllocator() {
1150
  // Don't assert if we are in a CrashRecovery context, as this invariant may
1151
  // be invalidated during a crash.
1152
78.6k
  assert((NumFreeListEntries == NumCached ||
1153
78.6k
          llvm::CrashRecoveryContext::isRecoveringFromCrash()) &&
1154
78.6k
         "A partial is on the lam");
1155
78.6k
}
1156
1157
char DiagnosticError::ID;