Coverage Report

Created: 2020-11-24 06:42

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