Coverage Report

Created: 2022-07-16 07:03

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/Sema.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
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 actions class which performs semantic analysis and
10
// builds an AST out of a parse stream.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "UsedDeclVisitor.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/ASTDiagnostic.h"
17
#include "clang/AST/Decl.h"
18
#include "clang/AST/DeclCXX.h"
19
#include "clang/AST/DeclFriend.h"
20
#include "clang/AST/DeclObjC.h"
21
#include "clang/AST/Expr.h"
22
#include "clang/AST/ExprCXX.h"
23
#include "clang/AST/PrettyDeclStackTrace.h"
24
#include "clang/AST/StmtCXX.h"
25
#include "clang/Basic/DarwinSDKInfo.h"
26
#include "clang/Basic/DiagnosticOptions.h"
27
#include "clang/Basic/PartialDiagnostic.h"
28
#include "clang/Basic/SourceManager.h"
29
#include "clang/Basic/Stack.h"
30
#include "clang/Basic/TargetInfo.h"
31
#include "clang/Lex/HeaderSearch.h"
32
#include "clang/Lex/HeaderSearchOptions.h"
33
#include "clang/Lex/Preprocessor.h"
34
#include "clang/Sema/CXXFieldCollector.h"
35
#include "clang/Sema/DelayedDiagnostic.h"
36
#include "clang/Sema/ExternalSemaSource.h"
37
#include "clang/Sema/Initialization.h"
38
#include "clang/Sema/MultiplexExternalSemaSource.h"
39
#include "clang/Sema/ObjCMethodList.h"
40
#include "clang/Sema/Scope.h"
41
#include "clang/Sema/ScopeInfo.h"
42
#include "clang/Sema/SemaConsumer.h"
43
#include "clang/Sema/SemaInternal.h"
44
#include "clang/Sema/TemplateDeduction.h"
45
#include "clang/Sema/TemplateInstCallback.h"
46
#include "clang/Sema/TypoCorrection.h"
47
#include "llvm/ADT/DenseMap.h"
48
#include "llvm/ADT/SmallPtrSet.h"
49
#include "llvm/Support/TimeProfiler.h"
50
51
using namespace clang;
52
using namespace sema;
53
54
107k
SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
55
107k
  return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
56
107k
}
57
58
144k
ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
59
60
DarwinSDKInfo *
61
Sema::getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
62
46
                                              StringRef Platform) {
63
46
  auto *SDKInfo = getDarwinSDKInfoForAvailabilityChecking();
64
46
  if (!SDKInfo && 
!WarnedDarwinSDKInfoMissing2
) {
65
1
    Diag(Loc, diag::warn_missing_sdksettings_for_availability_checking)
66
1
        << Platform;
67
1
    WarnedDarwinSDKInfoMissing = true;
68
1
  }
69
46
  return SDKInfo;
70
46
}
71
72
112
DarwinSDKInfo *Sema::getDarwinSDKInfoForAvailabilityChecking() {
73
112
  if (CachedDarwinSDKInfo)
74
100
    return CachedDarwinSDKInfo->get();
75
12
  auto SDKInfo = parseDarwinSDKInfo(
76
12
      PP.getFileManager().getVirtualFileSystem(),
77
12
      PP.getHeaderSearchInfo().getHeaderSearchOpts().Sysroot);
78
12
  if (SDKInfo && *SDKInfo) {
79
4
    CachedDarwinSDKInfo = std::make_unique<DarwinSDKInfo>(std::move(**SDKInfo));
80
4
    return CachedDarwinSDKInfo->get();
81
4
  }
82
8
  if (!SDKInfo)
83
0
    llvm::consumeError(SDKInfo.takeError());
84
8
  CachedDarwinSDKInfo = std::unique_ptr<DarwinSDKInfo>();
85
8
  return nullptr;
86
12
}
87
88
IdentifierInfo *
89
Sema::InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
90
2.63k
                                                 unsigned int Index) {
91
2.63k
  std::string InventedName;
92
2.63k
  llvm::raw_string_ostream OS(InventedName);
93
94
2.63k
  if (!ParamName)
95
144
    OS << "auto:" << Index + 1;
96
2.48k
  else
97
2.48k
    OS << ParamName->getName() << ":auto";
98
99
2.63k
  OS.flush();
100
2.63k
  return &Context.Idents.get(OS.str());
101
2.63k
}
102
103
PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
104
116M
                                       const Preprocessor &PP) {
105
116M
  PrintingPolicy Policy = Context.getPrintingPolicy();
106
  // In diagnostics, we print _Bool as bool if the latter is defined as the
107
  // former.
108
116M
  Policy.Bool = Context.getLangOpts().Bool;
109
116M
  if (!Policy.Bool) {
110
62.6M
    if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
111
46.8M
      Policy.Bool = BoolMacro->isObjectLike() &&
112
46.8M
                    BoolMacro->getNumTokens() == 1 &&
113
46.8M
                    BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
114
46.8M
    }
115
62.6M
  }
116
117
  // Shorten the data output if needed
118
116M
  Policy.EntireContentsOfLargeArray = false;
119
120
116M
  return Policy;
121
116M
}
122
123
88.2k
void Sema::ActOnTranslationUnitScope(Scope *S) {
124
88.2k
  TUScope = S;
125
88.2k
  PushDeclContext(S, Context.getTranslationUnitDecl());
126
88.2k
}
127
128
namespace clang {
129
namespace sema {
130
131
class SemaPPCallbacks : public PPCallbacks {
132
  Sema *S = nullptr;
133
  llvm::SmallVector<SourceLocation, 8> IncludeStack;
134
135
public:
136
88.2k
  void set(Sema &S) { this->S = &S; }
137
138
83.4k
  void reset() { S = nullptr; }
139
140
  virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
141
                           SrcMgr::CharacteristicKind FileType,
142
2.24M
                           FileID PrevFID) override {
143
2.24M
    if (!S)
144
0
      return;
145
2.24M
    switch (Reason) {
146
988k
    case EnterFile: {
147
988k
      SourceManager &SM = S->getSourceManager();
148
988k
      SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc));
149
988k
      if (IncludeLoc.isValid()) {
150
727k
        if (llvm::timeTraceProfilerEnabled()) {
151
0
          const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc));
152
0
          llvm::timeTraceProfilerBegin(
153
0
              "Source", FE != nullptr ? FE->getName() : StringRef("<unknown>"));
154
0
        }
155
156
727k
        IncludeStack.push_back(IncludeLoc);
157
727k
        S->DiagnoseNonDefaultPragmaAlignPack(
158
727k
            Sema::PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude,
159
727k
            IncludeLoc);
160
727k
      }
161
988k
      break;
162
0
    }
163
900k
    case ExitFile:
164
900k
      if (!IncludeStack.empty()) {
165
727k
        if (llvm::timeTraceProfilerEnabled())
166
0
          llvm::timeTraceProfilerEnd();
167
168
727k
        S->DiagnoseNonDefaultPragmaAlignPack(
169
727k
            Sema::PragmaAlignPackDiagnoseKind::ChangedStateAtExit,
170
727k
            IncludeStack.pop_back_val());
171
727k
      }
172
900k
      break;
173
357k
    default:
174
357k
      break;
175
2.24M
    }
176
2.24M
  }
177
};
178
179
} // end namespace sema
180
} // end namespace clang
181
182
const unsigned Sema::MaxAlignmentExponent;
183
const uint64_t Sema::MaximumAlignment;
184
185
Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
186
           TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
187
    : ExternalSource(nullptr), isMultiplexExternalSource(false),
188
      CurFPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp),
189
      Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
190
      SourceMgr(PP.getSourceManager()), CollectStats(false),
191
      CodeCompleter(CodeCompleter), CurContext(nullptr),
192
      OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
193
      MSPointerToMemberRepresentationMethod(
194
          LangOpts.getMSPointerToMemberRepresentationMethod()),
195
      VtorDispStack(LangOpts.getVtorDispMode()),
196
      AlignPackStack(AlignPackInfo(getLangOpts().XLPragmaPack)),
197
      DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
198
      CodeSegStack(nullptr), FpPragmaStack(FPOptionsOverride()),
199
      CurInitSeg(nullptr), VisContext(nullptr),
200
      PragmaAttributeCurrentTargetDecl(nullptr),
201
      IsBuildingRecoveryCallExpr(false), LateTemplateParser(nullptr),
202
      LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
203
      StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr),
204
      StdCoroutineTraitsCache(nullptr), CXXTypeInfoDecl(nullptr),
205
      MSVCGuidDecl(nullptr), StdSourceLocationImplDecl(nullptr),
206
      NSNumberDecl(nullptr), NSValueDecl(nullptr), NSStringDecl(nullptr),
207
      StringWithUTF8StringMethod(nullptr),
208
      ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
209
      ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
210
      DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
211
      TUKind(TUKind), NumSFINAEErrors(0),
212
      FullyCheckedComparisonCategories(
213
          static_cast<unsigned>(ComparisonCategoryType::Last) + 1),
214
      SatisfactionCache(Context), AccessCheckingSFINAE(false),
215
      InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0),
216
      ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr),
217
      DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this),
218
      ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
219
88.2k
      CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) {
220
88.2k
  assert(pp.TUKind == TUKind);
221
0
  TUScope = nullptr;
222
88.2k
  isConstantEvaluatedOverride = false;
223
224
88.2k
  LoadedExternalKnownNamespaces = false;
225
1.41M
  for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; 
++I1.32M
)
226
1.32M
    NSNumberLiteralMethods[I] = nullptr;
227
228
88.2k
  if (getLangOpts().ObjC)
229
23.1k
    NSAPIObj.reset(new NSAPI(Context));
230
231
88.2k
  if (getLangOpts().CPlusPlus)
232
69.1k
    FieldCollector.reset(new CXXFieldCollector());
233
234
  // Tell diagnostics how to render things from the AST library.
235
88.2k
  Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
236
237
  // This evaluation context exists to ensure that there's always at least one
238
  // valid evaluation context available. It is never removed from the
239
  // evaluation stack.
240
88.2k
  ExprEvalContexts.emplace_back(
241
88.2k
      ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
242
88.2k
      nullptr, ExpressionEvaluationContextRecord::EK_Other);
243
244
  // Initialization of data sharing attributes stack for OpenMP
245
88.2k
  InitDataSharingAttributesStack();
246
247
88.2k
  std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
248
88.2k
      std::make_unique<sema::SemaPPCallbacks>();
249
88.2k
  SemaPPCallbackHandler = Callbacks.get();
250
88.2k
  PP.addPPCallbacks(std::move(Callbacks));
251
88.2k
  SemaPPCallbackHandler->set(*this);
252
253
88.2k
  CurFPFeatures.setFPEvalMethod(PP.getCurrentFPEvalMethod());
254
88.2k
}
255
256
// Anchor Sema's type info to this TU.
257
0
void Sema::anchor() {}
258
259
176k
void Sema::addImplicitTypedef(StringRef Name, QualType T) {
260
176k
  DeclarationName DN = &Context.Idents.get(Name);
261
176k
  if (IdResolver.begin(DN) == IdResolver.end())
262
172k
    PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
263
176k
}
264
265
88.2k
void Sema::Initialize() {
266
88.2k
  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
267
21.6k
    SC->InitializeSema(*this);
268
269
  // Tell the external Sema source about this Sema object.
270
88.2k
  if (ExternalSemaSource *ExternalSema
271
88.2k
      = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
272
14.0k
    ExternalSema->InitializeSema(*this);
273
274
  // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
275
  // will not be able to merge any duplicate __va_list_tag decls correctly.
276
88.2k
  VAListTagName = PP.getIdentifierInfo("__va_list_tag");
277
278
88.2k
  if (!TUScope)
279
163
    return;
280
281
  // Initialize predefined 128-bit integer types, if needed.
282
88.1k
  if (Context.getTargetInfo().hasInt128Type() ||
283
88.1k
      
(16.3k
Context.getAuxTargetInfo()16.3k
&&
284
71.7k
       
Context.getAuxTargetInfo()->hasInt128Type()9
)) {
285
    // If either of the 128-bit integer types are unavailable to name lookup,
286
    // define them now.
287
71.7k
    DeclarationName Int128 = &Context.Idents.get("__int128_t");
288
71.7k
    if (IdResolver.begin(Int128) == IdResolver.end())
289
68.9k
      PushOnScopeChains(Context.getInt128Decl(), TUScope);
290
291
71.7k
    DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
292
71.7k
    if (IdResolver.begin(UInt128) == IdResolver.end())
293
68.9k
      PushOnScopeChains(Context.getUInt128Decl(), TUScope);
294
71.7k
  }
295
296
297
  // Initialize predefined Objective-C types:
298
88.1k
  if (getLangOpts().ObjC) {
299
    // If 'SEL' does not yet refer to any declarations, make it refer to the
300
    // predefined 'SEL'.
301
23.1k
    DeclarationName SEL = &Context.Idents.get("SEL");
302
23.1k
    if (IdResolver.begin(SEL) == IdResolver.end())
303
22.9k
      PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
304
305
    // If 'id' does not yet refer to any declarations, make it refer to the
306
    // predefined 'id'.
307
23.1k
    DeclarationName Id = &Context.Idents.get("id");
308
23.1k
    if (IdResolver.begin(Id) == IdResolver.end())
309
22.9k
      PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
310
311
    // Create the built-in typedef for 'Class'.
312
23.1k
    DeclarationName Class = &Context.Idents.get("Class");
313
23.1k
    if (IdResolver.begin(Class) == IdResolver.end())
314
22.9k
      PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
315
316
    // Create the built-in forward declaratino for 'Protocol'.
317
23.1k
    DeclarationName Protocol = &Context.Idents.get("Protocol");
318
23.1k
    if (IdResolver.begin(Protocol) == IdResolver.end())
319
22.9k
      PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
320
23.1k
  }
321
322
  // Create the internal type for the *StringMakeConstantString builtins.
323
88.1k
  DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
324
88.1k
  if (IdResolver.begin(ConstantString) == IdResolver.end())
325
84.3k
    PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
326
327
  // Initialize Microsoft "predefined C++ types".
328
88.1k
  if (getLangOpts().MSVCCompat) {
329
10.4k
    if (getLangOpts().CPlusPlus &&
330
10.4k
        
IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end()9.35k
)
331
9.34k
      PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
332
9.34k
                        TUScope);
333
334
10.4k
    addImplicitTypedef("size_t", Context.getSizeType());
335
10.4k
  }
336
337
  // Initialize predefined OpenCL types and supported extensions and (optional)
338
  // core features.
339
88.1k
  if (getLangOpts().OpenCL) {
340
791
    getOpenCLOptions().addSupport(
341
791
        Context.getTargetInfo().getSupportedOpenCLOpts(), getLangOpts());
342
791
    addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
343
791
    addImplicitTypedef("event_t", Context.OCLEventTy);
344
791
    auto OCLCompatibleVersion = getLangOpts().getOpenCLCompatibleVersion();
345
791
    if (OCLCompatibleVersion >= 200) {
346
408
      if (getLangOpts().OpenCLCPlusPlus || 
getLangOpts().Blocks266
) {
347
371
        addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
348
371
        addImplicitTypedef("queue_t", Context.OCLQueueTy);
349
371
      }
350
408
      if (getLangOpts().OpenCLPipes)
351
359
        addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
352
408
      addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
353
408
      addImplicitTypedef("atomic_uint",
354
408
                         Context.getAtomicType(Context.UnsignedIntTy));
355
408
      addImplicitTypedef("atomic_float",
356
408
                         Context.getAtomicType(Context.FloatTy));
357
      // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
358
      // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
359
408
      addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
360
361
362
      // OpenCL v2.0 s6.13.11.6:
363
      // - The atomic_long and atomic_ulong types are supported if the
364
      //   cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
365
      //   extensions are supported.
366
      // - The atomic_double type is only supported if double precision
367
      //   is supported and the cl_khr_int64_base_atomics and
368
      //   cl_khr_int64_extended_atomics extensions are supported.
369
      // - If the device address space is 64-bits, the data types
370
      //   atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
371
      //   atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
372
      //   cl_khr_int64_extended_atomics extensions are supported.
373
374
408
      auto AddPointerSizeDependentTypes = [&]() {
375
384
        auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
376
384
        auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
377
384
        auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
378
384
        auto AtomicPtrDiffT =
379
384
            Context.getAtomicType(Context.getPointerDiffType());
380
384
        addImplicitTypedef("atomic_size_t", AtomicSizeT);
381
384
        addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
382
384
        addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
383
384
        addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
384
384
      };
385
386
408
      if (Context.getTypeSize(Context.getSizeType()) == 32) {
387
155
        AddPointerSizeDependentTypes();
388
155
      }
389
390
408
      if (getOpenCLOptions().isSupported("cl_khr_fp16", getLangOpts())) {
391
367
        auto AtomicHalfT = Context.getAtomicType(Context.HalfTy);
392
367
        addImplicitTypedef("atomic_half", AtomicHalfT);
393
367
      }
394
395
408
      std::vector<QualType> Atomic64BitTypes;
396
408
      if (getOpenCLOptions().isSupported("cl_khr_int64_base_atomics",
397
408
                                         getLangOpts()) &&
398
408
          getOpenCLOptions().isSupported("cl_khr_int64_extended_atomics",
399
365
                                         getLangOpts())) {
400
365
        if (getOpenCLOptions().isSupported("cl_khr_fp64", getLangOpts())) {
401
358
          auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
402
358
          addImplicitTypedef("atomic_double", AtomicDoubleT);
403
358
          Atomic64BitTypes.push_back(AtomicDoubleT);
404
358
        }
405
365
        auto AtomicLongT = Context.getAtomicType(Context.LongTy);
406
365
        auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
407
365
        addImplicitTypedef("atomic_long", AtomicLongT);
408
365
        addImplicitTypedef("atomic_ulong", AtomicULongT);
409
410
411
365
        if (Context.getTypeSize(Context.getSizeType()) == 64) {
412
229
          AddPointerSizeDependentTypes();
413
229
        }
414
365
      }
415
408
    }
416
417
791
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext)                                      \
418
9.49k
  if (getOpenCLOptions().isSupported(#Ext, getLangOpts())) {                   \
419
5.76k
    addImplicitTypedef(#ExtType, Context.Id##Ty);                              \
420
5.76k
  }
421
791
#include "clang/Basic/OpenCLExtensionTypes.def"
422
791
  }
423
424
88.1k
  if (Context.getTargetInfo().hasAArch64SVETypes()) {
425
2.77k
#define SVE_TYPE(Name, Id, SingletonId) \
426
136k
    addImplicitTypedef(Name, Context.SingletonId);
427
2.77k
#include "clang/Basic/AArch64SVEACLETypes.def"
428
2.77k
  }
429
430
88.1k
  if (Context.getTargetInfo().getTriple().isPPC64()) {
431
3.75k
#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
432
3.75k
      addImplicitTypedef(#Name, Context.Id##Ty);
433
3.75k
#include "clang/Basic/PPCTypes.def"
434
3.75k
#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
435
3.75k
    addImplicitTypedef(#Name, Context.Id##Ty);
436
3.75k
#include "clang/Basic/PPCTypes.def"
437
3.75k
  }
438
439
88.1k
  if (Context.getTargetInfo().hasRISCVVTypes()) {
440
142
#define RVV_TYPE(Name, Id, SingletonId)                                        \
441
9.37k
  addImplicitTypedef(Name, Context.SingletonId);
442
142
#include "clang/Basic/RISCVVTypes.def"
443
142
  }
444
445
88.1k
  if (Context.getTargetInfo().hasBuiltinMSVaList()) {
446
67.1k
    DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
447
67.1k
    if (IdResolver.begin(MSVaList) == IdResolver.end())
448
65.3k
      PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
449
67.1k
  }
450
451
88.1k
  DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
452
88.1k
  if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
453
84.3k
    PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
454
88.1k
}
455
456
83.4k
Sema::~Sema() {
457
83.4k
  assert(InstantiatingSpecializations.empty() &&
458
83.4k
         "failed to clean up an InstantiatingTemplate?");
459
460
83.4k
  if (VisContext) 
FreeVisContext()4
;
461
462
  // Kill all the active scopes.
463
83.4k
  for (sema::FunctionScopeInfo *FSI : FunctionScopes)
464
0
    delete FSI;
465
466
  // Tell the SemaConsumer to forget about us; we're going out of scope.
467
83.4k
  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
468
21.6k
    SC->ForgetSema();
469
470
  // Detach from the external Sema source.
471
83.4k
  if (ExternalSemaSource *ExternalSema
472
83.4k
        = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
473
13.0k
    ExternalSema->ForgetSema();
474
475
  // If Sema's ExternalSource is the multiplexer - we own it.
476
83.4k
  if (isMultiplexExternalSource)
477
155
    delete ExternalSource;
478
479
  // Delete cached satisfactions.
480
83.4k
  std::vector<ConstraintSatisfaction *> Satisfactions;
481
83.4k
  Satisfactions.reserve(Satisfactions.size());
482
83.4k
  for (auto &Node : SatisfactionCache)
483
2.66k
    Satisfactions.push_back(&Node);
484
83.4k
  for (auto *Node : Satisfactions)
485
2.66k
    delete Node;
486
487
83.4k
  threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
488
489
  // Destroys data sharing attributes stack for OpenMP
490
83.4k
  DestroyDataSharingAttributesStack();
491
492
  // Detach from the PP callback handler which outlives Sema since it's owned
493
  // by the preprocessor.
494
83.4k
  SemaPPCallbackHandler->reset();
495
83.4k
}
496
497
11
void Sema::warnStackExhausted(SourceLocation Loc) {
498
  // Only warn about this once.
499
11
  if (!WarnedStackExhausted) {
500
2
    Diag(Loc, diag::warn_stack_exhausted);
501
2
    WarnedStackExhausted = true;
502
2
  }
503
11
}
504
505
void Sema::runWithSufficientStackSpace(SourceLocation Loc,
506
132M
                                       llvm::function_ref<void()> Fn) {
507
132M
  clang::runWithSufficientStackSpace([&] 
{ warnStackExhausted(Loc); }11
, Fn);
508
132M
}
509
510
/// makeUnavailableInSystemHeader - There is an error in the current
511
/// context.  If we're still in a system header, and we can plausibly
512
/// make the relevant declaration unavailable instead of erroring, do
513
/// so and return true.
514
bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
515
338
                                      UnavailableAttr::ImplicitReason reason) {
516
  // If we're not in a function, it's an error.
517
338
  FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
518
338
  if (!fn) 
return false24
;
519
520
  // If we're in template instantiation, it's an error.
521
314
  if (inTemplateInstantiation())
522
0
    return false;
523
524
  // If that function's not in a system header, it's an error.
525
314
  if (!Context.getSourceManager().isInSystemHeader(loc))
526
310
    return false;
527
528
  // If the function is already unavailable, it's not an error.
529
4
  if (fn->hasAttr<UnavailableAttr>()) 
return true0
;
530
531
4
  fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
532
4
  return true;
533
4
}
534
535
960k
ASTMutationListener *Sema::getASTMutationListener() const {
536
960k
  return getASTConsumer().GetASTMutationListener();
537
960k
}
538
539
///Registers an external source. If an external source already exists,
540
/// creates a multiplex external source and appends to it.
541
///
542
///\param[in] E - A non-null external sema source.
543
///
544
14.2k
void Sema::addExternalSource(ExternalSemaSource *E) {
545
14.2k
  assert(E && "Cannot use with NULL ptr");
546
547
14.2k
  if (!ExternalSource) {
548
14.0k
    ExternalSource = E;
549
14.0k
    return;
550
14.0k
  }
551
552
168
  if (isMultiplexExternalSource)
553
2
    static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
554
166
  else {
555
166
    ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
556
166
    isMultiplexExternalSource = true;
557
166
  }
558
168
}
559
560
/// Print out statistics about the semantic analysis.
561
4
void Sema::PrintStats() const {
562
4
  llvm::errs() << "\n*** Semantic Analysis Stats:\n";
563
4
  llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
564
565
4
  BumpAlloc.PrintStats();
566
4
  AnalysisWarnings.PrintStats();
567
4
}
568
569
void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
570
                                               QualType SrcType,
571
23.3M
                                               SourceLocation Loc) {
572
23.3M
  Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context);
573
23.3M
  if (!ExprNullability || 
(9.47k
*ExprNullability != NullabilityKind::Nullable9.47k
&&
574
9.47k
                           
*ExprNullability != NullabilityKind::NullableResult4.72k
))
575
23.3M
    return;
576
577
4.75k
  Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context);
578
4.75k
  if (!TypeNullability || 
*TypeNullability != NullabilityKind::NonNull428
)
579
4.58k
    return;
580
581
171
  Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
582
171
}
583
584
11.7M
void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr* E) {
585
11.7M
  if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
586
11.7M
                      E->getBeginLoc()))
587
11.7M
    return;
588
  // nullptr only exists from C++11 on, so don't warn on its absence earlier.
589
740
  if (!getLangOpts().CPlusPlus11)
590
307
    return;
591
592
433
  if (Kind != CK_NullToPointer && 
Kind != CK_NullToMemberPointer373
)
593
366
    return;
594
67
  if (E->IgnoreParenImpCasts()->getType()->isNullPtrType())
595
16
    return;
596
597
  // Don't diagnose the conversion from a 0 literal to a null pointer argument
598
  // in a synthesized call to operator<=>.
599
51
  if (!CodeSynthesisContexts.empty() &&
600
51
      CodeSynthesisContexts.back().Kind ==
601
10
          CodeSynthesisContext::RewritingOperatorAsSpaceship)
602
2
    return;
603
604
  // If it is a macro from system header, and if the macro name is not "NULL",
605
  // do not warn.
606
49
  SourceLocation MaybeMacroLoc = E->getBeginLoc();
607
49
  if (Diags.getSuppressSystemWarnings() &&
608
49
      
SourceMgr.isInSystemMacro(MaybeMacroLoc)25
&&
609
49
      
!findMacroSpelling(MaybeMacroLoc, "NULL")3
)
610
2
    return;
611
612
47
  Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant)
613
47
      << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");
614
47
}
615
616
/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
617
/// If there is already an implicit cast, merge into the existing one.
618
/// The result is of the given category.
619
ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
620
                                   CastKind Kind, ExprValueKind VK,
621
                                   const CXXCastPath *BasePath,
622
11.7M
                                   CheckedConversionKind CCK) {
623
11.7M
#ifndef NDEBUG
624
11.7M
  if (VK == VK_PRValue && 
!E->isPRValue()11.5M
) {
625
1.70M
    switch (Kind) {
626
0
    default:
627
0
      llvm_unreachable(
628
0
          ("can't implicitly cast glvalue to prvalue with this cast "
629
0
           "kind: " +
630
0
           std::string(CastExpr::getCastKindName(Kind)))
631
0
              .c_str());
632
406k
    case CK_Dependent:
633
406k
    case CK_LValueToRValue:
634
666k
    case CK_ArrayToPointerDecay:
635
1.70M
    case CK_FunctionToPointerDecay:
636
1.70M
    case CK_ToVoid:
637
1.70M
    case CK_NonAtomicToAtomic:
638
1.70M
      break;
639
1.70M
    }
640
1.70M
  }
641
11.7M
  assert((VK == VK_PRValue || Kind == CK_Dependent || !E->isPRValue()) &&
642
11.7M
         "can't cast prvalue to glvalue");
643
0
#endif
644
645
0
  diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getBeginLoc());
646
11.7M
  diagnoseZeroToNullptrConversion(Kind, E);
647
648
11.7M
  QualType ExprTy = Context.getCanonicalType(E->getType());
649
11.7M
  QualType TypeTy = Context.getCanonicalType(Ty);
650
651
11.7M
  if (ExprTy == TypeTy)
652
3.50M
    return E;
653
654
8.24M
  if (Kind == CK_ArrayToPointerDecay) {
655
    // C++1z [conv.array]: The temporary materialization conversion is applied.
656
    // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
657
259k
    if (getLangOpts().CPlusPlus && 
E->isPRValue()198k
) {
658
      // The temporary is an lvalue in C++98 and an xvalue otherwise.
659
56
      ExprResult Materialized = CreateMaterializeTemporaryExpr(
660
56
          E->getType(), E, !getLangOpts().CPlusPlus11);
661
56
      if (Materialized.isInvalid())
662
0
        return ExprError();
663
56
      E = Materialized.get();
664
56
    }
665
    // C17 6.7.1p6 footnote 124: The implementation can treat any register
666
    // declaration simply as an auto declaration. However, whether or not
667
    // addressable storage is actually used, the address of any part of an
668
    // object declared with storage-class specifier register cannot be
669
    // computed, either explicitly(by use of the unary & operator as discussed
670
    // in 6.5.3.2) or implicitly(by converting an array name to a pointer as
671
    // discussed in 6.3.2.1).Thus, the only operator that can be applied to an
672
    // array declared with storage-class specifier register is sizeof.
673
259k
    if (VK == VK_PRValue && !getLangOpts().CPlusPlus && 
!E->isPRValue()60.9k
) {
674
60.9k
      if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
675
9.62k
        if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
676
9.62k
          if (VD->getStorageClass() == SC_Register) {
677
24
            Diag(E->getExprLoc(), diag::err_typecheck_address_of)
678
24
                << /*register variable*/ 3 << E->getSourceRange();
679
24
            return ExprError();
680
24
          }
681
9.62k
        }
682
9.62k
      }
683
60.9k
    }
684
259k
  }
685
686
8.24M
  if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
687
779k
    if (ImpCast->getCastKind() == Kind && 
(24.1k
!BasePath24.1k
||
BasePath->empty()486
)) {
688
24.0k
      ImpCast->setType(Ty);
689
24.0k
      ImpCast->setValueKind(VK);
690
24.0k
      return E;
691
24.0k
    }
692
779k
  }
693
694
8.22M
  return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK,
695
8.22M
                                  CurFPFeatureOverrides());
696
8.24M
}
697
698
/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
699
/// to the conversion from scalar type ScalarTy to the Boolean type.
700
410k
CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
701
410k
  switch (ScalarTy->getScalarTypeKind()) {
702
254k
  case Type::STK_Bool: return CK_NoOp;
703
22.1k
  case Type::STK_CPointer: return CK_PointerToBoolean;
704
7
  case Type::STK_BlockPointer: return CK_PointerToBoolean;
705
163
  case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
706
111
  case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
707
132k
  case Type::STK_Integral: return CK_IntegralToBoolean;
708
1.72k
  case Type::STK_Floating: return CK_FloatingToBoolean;
709
15
  case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
710
1
  case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
711
0
  case Type::STK_FixedPoint: return CK_FixedPointToBoolean;
712
410k
  }
713
0
  llvm_unreachable("unknown scalar type kind");
714
0
}
715
716
/// Used to prune the decls of Sema's UnusedFileScopedDecls vector.
717
36.2k
static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
718
36.2k
  if (D->getMostRecentDecl()->isUsed())
719
6.74k
    return true;
720
721
29.4k
  if (D->isExternallyVisible())
722
51
    return true;
723
724
29.4k
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
725
    // If this is a function template and none of its specializations is used,
726
    // we should warn.
727
23.1k
    if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
728
2.09k
      for (const auto *Spec : Template->specializations())
729
86
        if (ShouldRemoveFromUnused(SemaRef, Spec))
730
56
          return true;
731
732
    // UnusedFileScopedDecls stores the first declaration.
733
    // The declaration may have become definition so check again.
734
23.0k
    const FunctionDecl *DeclToCheck;
735
23.0k
    if (FD->hasBody(DeclToCheck))
736
13.4k
      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
737
738
    // Later redecls may add new information resulting in not having to warn,
739
    // so check again.
740
9.62k
    DeclToCheck = FD->getMostRecentDecl();
741
9.62k
    if (DeclToCheck != FD)
742
62
      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
743
9.62k
  }
744
745
15.8k
  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
746
    // If a variable usable in constant expressions is referenced,
747
    // don't warn if it isn't used: if the value of a variable is required
748
    // for the computation of a constant expression, it doesn't make sense to
749
    // warn even if the variable isn't odr-used.  (isReferenced doesn't
750
    // precisely reflect that, but it's a decent approximation.)
751
6.29k
    if (VD->isReferenced() &&
752
6.29k
        
VD->mightBeUsableInConstantExpressions(SemaRef->Context)1.12k
)
753
1.01k
      return true;
754
755
5.27k
    if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
756
      // If this is a variable template and none of its specializations is used,
757
      // we should warn.
758
233
      for (const auto *Spec : Template->specializations())
759
26
        if (ShouldRemoveFromUnused(SemaRef, Spec))
760
10
          return true;
761
762
    // UnusedFileScopedDecls stores the first declaration.
763
    // The declaration may have become definition so check again.
764
5.26k
    const VarDecl *DeclToCheck = VD->getDefinition();
765
5.26k
    if (DeclToCheck)
766
4.55k
      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
767
768
    // Later redecls may add new information resulting in not having to warn,
769
    // so check again.
770
711
    DeclToCheck = VD->getMostRecentDecl();
771
711
    if (DeclToCheck != VD)
772
43
      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
773
711
  }
774
775
10.2k
  return false;
776
15.8k
}
777
778
53
static bool isFunctionOrVarDeclExternC(NamedDecl *ND) {
779
53
  if (auto *FD = dyn_cast<FunctionDecl>(ND))
780
18
    return FD->isExternC();
781
35
  return cast<VarDecl>(ND)->isExternC();
782
53
}
783
784
/// Determine whether ND is an external-linkage function or variable whose
785
/// type has no linkage.
786
1.08M
bool Sema::isExternalWithNoLinkageType(ValueDecl *VD) {
787
  // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
788
  // because we also want to catch the case where its type has VisibleNoLinkage,
789
  // which does not affect the linkage of VD.
790
1.08M
  return getLangOpts().CPlusPlus && 
VD->hasExternalFormalLinkage()450k
&&
791
1.08M
         
!isExternalFormalLinkage(VD->getType()->getLinkage())449k
&&
792
1.08M
         
!isFunctionOrVarDeclExternC(VD)53
;
793
1.08M
}
794
795
/// Obtains a sorted list of functions and variables that are undefined but
796
/// ODR-used.
797
void Sema::getUndefinedButUsed(
798
11.6k
    SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
799
156k
  for (const auto &UndefinedUse : UndefinedButUsed) {
800
156k
    NamedDecl *ND = UndefinedUse.first;
801
802
    // Ignore attributes that have become invalid.
803
156k
    if (ND->isInvalidDecl()) 
continue0
;
804
805
    // __attribute__((weakref)) is basically a definition.
806
156k
    if (ND->hasAttr<WeakRefAttr>()) 
continue0
;
807
808
156k
    if (isa<CXXDeductionGuideDecl>(ND))
809
6
      continue;
810
811
156k
    if (ND->hasAttr<DLLImportAttr>() || 
ND->hasAttr<DLLExportAttr>()156k
) {
812
      // An exported function will always be emitted when defined, so even if
813
      // the function is inline, it doesn't have to be emitted in this TU. An
814
      // imported function implies that it has been exported somewhere else.
815
247
      continue;
816
247
    }
817
818
156k
    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
819
155k
      if (FD->isDefined())
820
105k
        continue;
821
50.8k
      if (FD->isExternallyVisible() &&
822
50.8k
          
!isExternalWithNoLinkageType(FD)18.7k
&&
823
50.8k
          
!FD->getMostRecentDecl()->isInlined()18.7k
&&
824
50.8k
          
!FD->hasAttr<ExcludeFromExplicitInstantiationAttr>()6
)
825
6
        continue;
826
50.8k
      if (FD->getBuiltinID())
827
47.6k
        continue;
828
50.8k
    } else {
829
81
      auto *VD = cast<VarDecl>(ND);
830
81
      if (VD->hasDefinition() != VarDecl::DeclarationOnly)
831
62
        continue;
832
19
      if (VD->isExternallyVisible() &&
833
19
          
!isExternalWithNoLinkageType(VD)2
&&
834
19
          
!VD->getMostRecentDecl()->isInline()2
&&
835
19
          
!VD->hasAttr<ExcludeFromExplicitInstantiationAttr>()0
)
836
0
        continue;
837
838
      // Skip VarDecls that lack formal definitions but which we know are in
839
      // fact defined somewhere.
840
19
      if (VD->isKnownToBeDefined())
841
0
        continue;
842
19
    }
843
844
3.24k
    Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
845
3.24k
  }
846
11.6k
}
847
848
/// checkUndefinedButUsed - Check for undefined objects with internal linkage
849
/// or that are inline.
850
72.9k
static void checkUndefinedButUsed(Sema &S) {
851
72.9k
  if (S.UndefinedButUsed.empty()) 
return66.8k
;
852
853
  // Collect all the still-undefined entities with internal linkage.
854
6.03k
  SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
855
6.03k
  S.getUndefinedButUsed(Undefined);
856
6.03k
  if (Undefined.empty()) 
return5.74k
;
857
858
948
  
for (auto Undef : Undefined)293
{
859
948
    ValueDecl *VD = cast<ValueDecl>(Undef.first);
860
948
    SourceLocation UseLoc = Undef.second;
861
862
948
    if (S.isExternalWithNoLinkageType(VD)) {
863
      // C++ [basic.link]p8:
864
      //   A type without linkage shall not be used as the type of a variable
865
      //   or function with external linkage unless
866
      //    -- the entity has C language linkage
867
      //    -- the entity is not odr-used or is defined in the same TU
868
      //
869
      // As an extension, accept this in cases where the type is externally
870
      // visible, since the function or variable actually can be defined in
871
      // another translation unit in that case.
872
7
      S.Diag(VD->getLocation(), isExternallyVisible(VD->getType()->getLinkage())
873
7
                                    ? 
diag::ext_undefined_internal_type3
874
7
                                    : 
diag::err_undefined_internal_type4
)
875
7
        << isa<VarDecl>(VD) << VD;
876
941
    } else if (!VD->isExternallyVisible()) {
877
      // FIXME: We can promote this to an error. The function or variable can't
878
      // be defined anywhere else, so the program must necessarily violate the
879
      // one definition rule.
880
616
      bool IsImplicitBase = false;
881
616
      if (const auto *BaseD = dyn_cast<FunctionDecl>(VD)) {
882
599
        auto *DVAttr = BaseD->getAttr<OMPDeclareVariantAttr>();
883
599
        if (DVAttr && !DVAttr->getTraitInfo().isExtensionActive(
884
399
                          llvm::omp::TraitProperty::
885
399
                              implementation_extension_disable_implicit_base)) {
886
399
          const auto *Func = cast<FunctionDecl>(
887
399
              cast<DeclRefExpr>(DVAttr->getVariantFuncRef())->getDecl());
888
399
          IsImplicitBase = BaseD->isImplicit() &&
889
399
                           
Func->getIdentifier()->isMangledOpenMPVariantName()398
;
890
399
        }
891
599
      }
892
616
      if (!S.getLangOpts().OpenMP || 
!IsImplicitBase400
)
893
218
        S.Diag(VD->getLocation(), diag::warn_undefined_internal)
894
218
            << isa<VarDecl>(VD) << VD;
895
616
    } else 
if (auto *325
FD325
= dyn_cast<FunctionDecl>(VD)) {
896
323
      (void)FD;
897
323
      assert(FD->getMostRecentDecl()->isInlined() &&
898
323
             "used object requires definition but isn't inline or internal?");
899
      // FIXME: This is ill-formed; we should reject.
900
0
      S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD;
901
323
    } else {
902
2
      assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
903
2
             "used var requires definition but isn't inline or internal?");
904
0
      S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD;
905
2
    }
906
948
    if (UseLoc.isValid())
907
947
      S.Diag(UseLoc, diag::note_used_here);
908
948
  }
909
910
293
  S.UndefinedButUsed.clear();
911
293
}
912
913
27.7M
void Sema::LoadExternalWeakUndeclaredIdentifiers() {
914
27.7M
  if (!ExternalSource)
915
27.1M
    return;
916
917
535k
  SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
918
535k
  ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
919
535k
  for (auto &WeakID : WeakIDs)
920
8
    (void)WeakUndeclaredIdentifiers[WeakID.first].insert(WeakID.second);
921
535k
}
922
923
924
typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
925
926
/// Returns true, if all methods and nested classes of the given
927
/// CXXRecordDecl are defined in this translation unit.
928
///
929
/// Should only be called from ActOnEndOfTranslationUnit so that all
930
/// definitions are actually read.
931
static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
932
104
                                            RecordCompleteMap &MNCComplete) {
933
104
  RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
934
104
  if (Cache != MNCComplete.end())
935
12
    return Cache->second;
936
92
  if (!RD->isCompleteDefinition())
937
6
    return false;
938
86
  bool Complete = true;
939
86
  for (DeclContext::decl_iterator I = RD->decls_begin(),
940
86
                                  E = RD->decls_end();
941
479
       I != E && 
Complete410
;
++I393
) {
942
393
    if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
943
79
      Complete = M->isDefined() || 
M->isDefaulted()11
||
944
79
                 
(11
M->isPure()11
&&
!isa<CXXDestructorDecl>(M)3
);
945
314
    else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
946
      // If the template function is marked as late template parsed at this
947
      // point, it has not been instantiated and therefore we have not
948
      // performed semantic analysis on it yet, so we cannot know if the type
949
      // can be considered complete.
950
4
      Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
951
4
                  
F->getTemplatedDecl()->isDefined()3
;
952
310
    else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
953
98
      if (R->isInjectedClassName())
954
86
        continue;
955
12
      if (R->hasDefinition())
956
6
        Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
957
6
                                                   MNCComplete);
958
6
      else
959
6
        Complete = false;
960
12
    }
961
393
  }
962
86
  MNCComplete[RD] = Complete;
963
86
  return Complete;
964
92
}
965
966
/// Returns true, if the given CXXRecordDecl is fully defined in this
967
/// translation unit, i.e. all methods are defined or pure virtual and all
968
/// friends, friend functions and nested classes are fully defined in this
969
/// translation unit.
970
///
971
/// Should only be called from ActOnEndOfTranslationUnit so that all
972
/// definitions are actually read.
973
static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
974
                                 RecordCompleteMap &RecordsComplete,
975
110
                                 RecordCompleteMap &MNCComplete) {
976
110
  RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
977
110
  if (Cache != RecordsComplete.end())
978
33
    return Cache->second;
979
77
  bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
980
77
  for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
981
77
                                      E = RD->friend_end();
982
107
       I != E && 
Complete39
;
++I30
) {
983
    // Check if friend classes and methods are complete.
984
30
    if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
985
      // Friend classes are available as the TypeSourceInfo of the FriendDecl.
986
21
      if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
987
21
        Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
988
0
      else
989
0
        Complete = false;
990
21
    } else {
991
      // Friend functions are available through the NamedDecl of FriendDecl.
992
9
      if (const FunctionDecl *FD =
993
9
          dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
994
6
        Complete = FD->isDefined();
995
3
      else
996
        // This is a template friend, give up.
997
3
        Complete = false;
998
9
    }
999
30
  }
1000
77
  RecordsComplete[RD] = Complete;
1001
77
  return Complete;
1002
110
}
1003
1004
73.0k
void Sema::emitAndClearUnusedLocalTypedefWarnings() {
1005
73.0k
  if (ExternalSource)
1006
11.3k
    ExternalSource->ReadUnusedLocalTypedefNameCandidates(
1007
11.3k
        UnusedLocalTypedefNameCandidates);
1008
73.0k
  for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
1009
254
    if (TD->isReferenced())
1010
16
      continue;
1011
238
    Diag(TD->getLocation(), diag::warn_unused_local_typedef)
1012
238
        << isa<TypeAliasDecl>(TD) << TD->getDeclName();
1013
238
  }
1014
73.0k
  UnusedLocalTypedefNameCandidates.clear();
1015
73.0k
}
1016
1017
/// This is called before the very first declaration in the translation unit
1018
/// is parsed. Note that the ASTContext may have already injected some
1019
/// declarations.
1020
86.7k
void Sema::ActOnStartOfTranslationUnit() {
1021
86.7k
  if (getLangOpts().CPlusPlusModules &&
1022
86.7k
      
getLangOpts().getCompilingModule() == LangOptions::CMK_HeaderUnit3.94k
)
1023
20
    HandleStartOfHeaderUnit();
1024
86.7k
  else if (getLangOpts().ModulesTS &&
1025
86.7k
           
(139
getLangOpts().getCompilingModule() ==
1026
139
                LangOptions::CMK_ModuleInterface ||
1027
139
            
getLangOpts().getCompilingModule() == LangOptions::CMK_None96
)) {
1028
    // We start in an implied global module fragment.
1029
125
    SourceLocation StartOfTU =
1030
125
        SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1031
125
    ActOnGlobalModuleFragmentDecl(StartOfTU);
1032
125
    ModuleScopes.back().ImplicitGlobalModuleFragment = true;
1033
125
  }
1034
86.7k
}
1035
1036
81.9k
void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) {
1037
  // No explicit actions are required at the end of the global module fragment.
1038
81.9k
  if (Kind == TUFragmentKind::Global)
1039
133
    return;
1040
1041
  // Transfer late parsed template instantiations over to the pending template
1042
  // instantiation list. During normal compilation, the late template parser
1043
  // will be installed and instantiating these templates will succeed.
1044
  //
1045
  // If we are building a TU prefix for serialization, it is also safe to
1046
  // transfer these over, even though they are not parsed. The end of the TU
1047
  // should be outside of any eager template instantiation scope, so when this
1048
  // AST is deserialized, these templates will not be parsed until the end of
1049
  // the combined TU.
1050
81.8k
  PendingInstantiations.insert(PendingInstantiations.end(),
1051
81.8k
                               LateParsedInstantiations.begin(),
1052
81.8k
                               LateParsedInstantiations.end());
1053
81.8k
  LateParsedInstantiations.clear();
1054
1055
  // If DefinedUsedVTables ends up marking any virtual member functions it
1056
  // might lead to more pending template instantiations, which we then need
1057
  // to instantiate.
1058
81.8k
  DefineUsedVTables();
1059
1060
  // C++: Perform implicit template instantiations.
1061
  //
1062
  // FIXME: When we perform these implicit instantiations, we do not
1063
  // carefully keep track of the point of instantiation (C++ [temp.point]).
1064
  // This means that name lookup that occurs within the template
1065
  // instantiation will always happen at the end of the translation unit,
1066
  // so it will find some names that are not required to be found. This is
1067
  // valid, but we could do better by diagnosing if an instantiation uses a
1068
  // name that was not visible at its first point of instantiation.
1069
81.8k
  if (ExternalSource) {
1070
    // Load pending instantiations from the external source.
1071
12.1k
    SmallVector<PendingImplicitInstantiation, 4> Pending;
1072
12.1k
    ExternalSource->ReadPendingInstantiations(Pending);
1073
12.1k
    for (auto PII : Pending)
1074
3.73k
      if (auto Func = dyn_cast<FunctionDecl>(PII.first))
1075
3.67k
        Func->setInstantiationIsPending(true);
1076
12.1k
    PendingInstantiations.insert(PendingInstantiations.begin(),
1077
12.1k
                                 Pending.begin(), Pending.end());
1078
12.1k
  }
1079
1080
81.8k
  {
1081
81.8k
    llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1082
81.8k
    PerformPendingInstantiations();
1083
81.8k
  }
1084
1085
81.8k
  emitDeferredDiags();
1086
1087
81.8k
  assert(LateParsedInstantiations.empty() &&
1088
81.8k
         "end of TU template instantiation should not create more "
1089
81.8k
         "late-parsed templates");
1090
1091
  // Report diagnostics for uncorrected delayed typos. Ideally all of them
1092
  // should have been corrected by that time, but it is very hard to cover all
1093
  // cases in practice.
1094
3
  for (const auto &Typo : DelayedTypos) {
1095
    // We pass an empty TypoCorrection to indicate no correction was performed.
1096
3
    Typo.second.DiagHandler(TypoCorrection());
1097
3
  }
1098
81.8k
  DelayedTypos.clear();
1099
81.8k
}
1100
1101
/// ActOnEndOfTranslationUnit - This is called at the very end of the
1102
/// translation unit when EOF is reached and all but the top-level scope is
1103
/// popped.
1104
86.6k
void Sema::ActOnEndOfTranslationUnit() {
1105
86.6k
  assert(DelayedDiagnostics.getCurrentPool() == nullptr
1106
86.6k
         && "reached end of translation unit with a pool attached?");
1107
1108
  // If code completion is enabled, don't perform any end-of-translation-unit
1109
  // work.
1110
86.6k
  if (PP.isCodeCompletionEnabled())
1111
1.28k
    return;
1112
1113
  // Complete translation units and modules define vtables and perform implicit
1114
  // instantiations. PCH files do not.
1115
85.3k
  if (TUKind != TU_Prefix) {
1116
81.8k
    DiagnoseUseOfUnimplementedSelectors();
1117
1118
81.8k
    ActOnEndOfTranslationUnitFragment(
1119
81.8k
        !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1120
346
                                     Module::PrivateModuleFragment
1121
81.8k
            ? 
TUFragmentKind::Private11
1122
81.8k
            : 
TUFragmentKind::Normal81.8k
);
1123
1124
81.8k
    if (LateTemplateParserCleanup)
1125
0
      LateTemplateParserCleanup(OpaqueParser);
1126
1127
81.8k
    CheckDelayedMemberExceptionSpecs();
1128
81.8k
  } else {
1129
    // If we are building a TU prefix for serialization, it is safe to transfer
1130
    // these over, even though they are not parsed. The end of the TU should be
1131
    // outside of any eager template instantiation scope, so when this AST is
1132
    // deserialized, these templates will not be parsed until the end of the
1133
    // combined TU.
1134
3.53k
    PendingInstantiations.insert(PendingInstantiations.end(),
1135
3.53k
                                 LateParsedInstantiations.begin(),
1136
3.53k
                                 LateParsedInstantiations.end());
1137
3.53k
    LateParsedInstantiations.clear();
1138
1139
3.53k
    if (LangOpts.PCHInstantiateTemplates) {
1140
56
      llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1141
56
      PerformPendingInstantiations();
1142
56
    }
1143
3.53k
  }
1144
1145
85.3k
  DiagnoseUnterminatedPragmaAlignPack();
1146
85.3k
  DiagnoseUnterminatedPragmaAttribute();
1147
85.3k
  DiagnoseUnterminatedOpenMPDeclareTarget();
1148
1149
  // All delayed member exception specs should be checked or we end up accepting
1150
  // incompatible declarations.
1151
85.3k
  assert(DelayedOverridingExceptionSpecChecks.empty());
1152
0
  assert(DelayedEquivalentExceptionSpecChecks.empty());
1153
1154
  // All dllexport classes should have been processed already.
1155
0
  assert(DelayedDllExportClasses.empty());
1156
0
  assert(DelayedDllExportMemberFunctions.empty());
1157
1158
  // Remove file scoped decls that turned out to be used.
1159
0
  UnusedFileScopedDecls.erase(
1160
85.3k
      std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
1161
85.3k
                     UnusedFileScopedDecls.end(),
1162
85.3k
                     [this](const DeclaratorDecl *DD) {
1163
24.7k
                       return ShouldRemoveFromUnused(this, DD);
1164
24.7k
                     }),
1165
85.3k
      UnusedFileScopedDecls.end());
1166
1167
85.3k
  if (TUKind == TU_Prefix) {
1168
    // Translation unit prefixes don't need any of the checking below.
1169
3.53k
    if (!PP.isIncrementalProcessingEnabled())
1170
3.53k
      TUScope = nullptr;
1171
3.53k
    return;
1172
3.53k
  }
1173
1174
  // Check for #pragma weak identifiers that were never declared
1175
81.8k
  LoadExternalWeakUndeclaredIdentifiers();
1176
81.8k
  for (const auto &WeakIDs : WeakUndeclaredIdentifiers) {
1177
90
    if (WeakIDs.second.empty())
1178
72
      continue;
1179
1180
18
    Decl *PrevDecl = LookupSingleName(TUScope, WeakIDs.first, SourceLocation(),
1181
18
                                      LookupOrdinaryName);
1182
18
    if (PrevDecl != nullptr &&
1183
18
        
!(6
isa<FunctionDecl>(PrevDecl)6
||
isa<VarDecl>(PrevDecl)4
))
1184
3
      for (const auto &WI : WeakIDs.second)
1185
3
        Diag(WI.getLocation(), diag::warn_attribute_wrong_decl_type)
1186
3
            << "'weak'" << ExpectedVariableOrFunction;
1187
15
    else
1188
15
      for (const auto &WI : WeakIDs.second)
1189
15
        Diag(WI.getLocation(), diag::warn_weak_identifier_undeclared)
1190
15
            << WeakIDs.first;
1191
18
  }
1192
1193
81.8k
  if (LangOpts.CPlusPlus11 &&
1194
81.8k
      
!Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation())56.7k
)
1195
56.7k
    CheckDelegatingCtorCycles();
1196
1197
81.8k
  if (!Diags.hasErrorOccurred()) {
1198
72.9k
    if (ExternalSource)
1199
11.2k
      ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
1200
72.9k
    checkUndefinedButUsed(*this);
1201
72.9k
  }
1202
1203
  // A global-module-fragment is only permitted within a module unit.
1204
81.8k
  bool DiagnosedMissingModuleDeclaration = false;
1205
81.8k
  if (!ModuleScopes.empty() &&
1206
81.8k
      
ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment346
&&
1207
81.8k
      
!ModuleScopes.back().ImplicitGlobalModuleFragment51
) {
1208
3
    Diag(ModuleScopes.back().BeginLoc,
1209
3
         diag::err_module_declaration_missing_after_global_module_introducer);
1210
3
    DiagnosedMissingModuleDeclaration = true;
1211
3
  }
1212
1213
81.8k
  if (TUKind == TU_Module) {
1214
    // If we are building a module interface unit, we need to have seen the
1215
    // module declaration by now.
1216
2.28k
    if (getLangOpts().getCompilingModule() ==
1217
2.28k
            LangOptions::CMK_ModuleInterface &&
1218
2.28k
        
(157
ModuleScopes.empty()157
||
1219
157
         !ModuleScopes.back().Module->isModulePurview()) &&
1220
2.28k
        
!DiagnosedMissingModuleDeclaration1
) {
1221
      // FIXME: Make a better guess as to where to put the module declaration.
1222
1
      Diag(getSourceManager().getLocForStartOfFile(
1223
1
               getSourceManager().getMainFileID()),
1224
1
           diag::err_module_declaration_missing);
1225
1
    }
1226
1227
    // If we are building a module, resolve all of the exported declarations
1228
    // now.
1229
2.28k
    if (Module *CurrentModule = PP.getCurrentModule()) {
1230
2.21k
      ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
1231
1232
2.21k
      SmallVector<Module *, 2> Stack;
1233
2.21k
      Stack.push_back(CurrentModule);
1234
30.9k
      while (!Stack.empty()) {
1235
28.7k
        Module *Mod = Stack.pop_back_val();
1236
1237
        // Resolve the exported declarations and conflicts.
1238
        // FIXME: Actually complain, once we figure out how to teach the
1239
        // diagnostic client to deal with complaints in the module map at this
1240
        // point.
1241
28.7k
        ModMap.resolveExports(Mod, /*Complain=*/false);
1242
28.7k
        ModMap.resolveUses(Mod, /*Complain=*/false);
1243
28.7k
        ModMap.resolveConflicts(Mod, /*Complain=*/false);
1244
1245
        // Queue the submodules, so their exports will also be resolved.
1246
28.7k
        Stack.append(Mod->submodule_begin(), Mod->submodule_end());
1247
28.7k
      }
1248
2.21k
    }
1249
1250
    // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
1251
    // modules when they are built, not every time they are used.
1252
2.28k
    emitAndClearUnusedLocalTypedefWarnings();
1253
2.28k
  }
1254
1255
  // C99 6.9.2p2:
1256
  //   A declaration of an identifier for an object that has file
1257
  //   scope without an initializer, and without a storage-class
1258
  //   specifier or with the storage-class specifier static,
1259
  //   constitutes a tentative definition. If a translation unit
1260
  //   contains one or more tentative definitions for an identifier,
1261
  //   and the translation unit contains no external definition for
1262
  //   that identifier, then the behavior is exactly as if the
1263
  //   translation unit contains a file scope declaration of that
1264
  //   identifier, with the composite type as of the end of the
1265
  //   translation unit, with an initializer equal to 0.
1266
81.8k
  llvm::SmallSet<VarDecl *, 32> Seen;
1267
81.8k
  for (TentativeDefinitionsType::iterator
1268
81.8k
            T = TentativeDefinitions.begin(ExternalSource),
1269
81.8k
         TEnd = TentativeDefinitions.end();
1270
92.2k
       T != TEnd; 
++T10.3k
) {
1271
10.3k
    VarDecl *VD = (*T)->getActingDefinition();
1272
1273
    // If the tentative definition was completed, getActingDefinition() returns
1274
    // null. If we've already seen this variable before, insert()'s second
1275
    // return value is false.
1276
10.3k
    if (!VD || 
VD->isInvalidDecl()10.3k
||
!Seen.insert(VD).second10.3k
)
1277
238
      continue;
1278
1279
10.1k
    if (const IncompleteArrayType *ArrayT
1280
10.1k
        = Context.getAsIncompleteArrayType(VD->getType())) {
1281
      // Set the length of the array to 1 (C99 6.9.2p5).
1282
39
      Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
1283
39
      llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
1284
39
      QualType T = Context.getConstantArrayType(ArrayT->getElementType(), One,
1285
39
                                                nullptr, ArrayType::Normal, 0);
1286
39
      VD->setType(T);
1287
10.0k
    } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
1288
10.0k
                                   diag::err_tentative_def_incomplete_type))
1289
15
      VD->setInvalidDecl();
1290
1291
    // No initialization is performed for a tentative definition.
1292
10.1k
    CheckCompleteVariableDeclaration(VD);
1293
1294
    // Notify the consumer that we've completed a tentative definition.
1295
10.1k
    if (!VD->isInvalidDecl())
1296
10.1k
      Consumer.CompleteTentativeDefinition(VD);
1297
10.1k
  }
1298
1299
81.8k
  for (auto D : ExternalDeclarations) {
1300
12
    if (!D || D->isInvalidDecl() || D->getPreviousDecl() || 
!D->isUsed()11
)
1301
5
      continue;
1302
1303
7
    Consumer.CompleteExternalDeclaration(D);
1304
7
  }
1305
1306
  // If there were errors, disable 'unused' warnings since they will mostly be
1307
  // noise. Don't warn for a use from a module: either we should warn on all
1308
  // file-scope declarations in modules or not at all, but whether the
1309
  // declaration is used is immaterial.
1310
81.8k
  if (!Diags.hasErrorOccurred() && 
TUKind != TU_Module72.9k
) {
1311
    // Output warning for unused file scoped decls.
1312
70.7k
    for (UnusedFileScopedDeclsType::iterator
1313
70.7k
           I = UnusedFileScopedDecls.begin(ExternalSource),
1314
82.0k
           E = UnusedFileScopedDecls.end(); I != E; 
++I11.3k
) {
1315
11.3k
      if (ShouldRemoveFromUnused(this, *I))
1316
10
        continue;
1317
1318
11.2k
      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1319
9.68k
        const FunctionDecl *DiagD;
1320
9.68k
        if (!FD->hasBody(DiagD))
1321
4.62k
          DiagD = FD;
1322
9.68k
        if (DiagD->isDeleted())
1323
1
          continue; // Deleted functions are supposed to be unused.
1324
9.67k
        if (DiagD->isReferenced()) {
1325
421
          if (isa<CXXMethodDecl>(DiagD))
1326
6
            Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
1327
6
                << DiagD;
1328
415
          else {
1329
415
            if (FD->getStorageClass() == SC_Static &&
1330
415
                
!FD->isInlineSpecified()412
&&
1331
415
                !SourceMgr.isInMainFile(
1332
404
                   SourceMgr.getExpansionLoc(FD->getLocation())))
1333
169
              Diag(DiagD->getLocation(),
1334
169
                   diag::warn_unneeded_static_internal_decl)
1335
169
                  << DiagD;
1336
246
            else
1337
246
              Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1338
246
                  << /*function*/ 0 << DiagD;
1339
415
          }
1340
9.25k
        } else {
1341
9.25k
          if (FD->getDescribedFunctionTemplate())
1342
999
            Diag(DiagD->getLocation(), diag::warn_unused_template)
1343
999
                << /*function*/ 0 << DiagD;
1344
8.25k
          else
1345
8.25k
            Diag(DiagD->getLocation(), isa<CXXMethodDecl>(DiagD)
1346
8.25k
                                           ? 
diag::warn_unused_member_function166
1347
8.25k
                                           : 
diag::warn_unused_function8.09k
)
1348
8.25k
                << DiagD;
1349
9.25k
        }
1350
9.67k
      } else {
1351
1.61k
        const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
1352
1.61k
        if (!DiagD)
1353
307
          DiagD = cast<VarDecl>(*I);
1354
1.61k
        if (DiagD->isReferenced()) {
1355
26
          Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1356
26
              << /*variable*/ 1 << DiagD;
1357
1.58k
        } else if (DiagD->getType().isConstQualified()) {
1358
536
          const SourceManager &SM = SourceMgr;
1359
536
          if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
1360
536
              !PP.getLangOpts().IsHeaderFile)
1361
534
            Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
1362
534
                << DiagD;
1363
1.05k
        } else {
1364
1.05k
          if (DiagD->getDescribedVarTemplate())
1365
103
            Diag(DiagD->getLocation(), diag::warn_unused_template)
1366
103
                << /*variable*/ 1 << DiagD;
1367
950
          else
1368
950
            Diag(DiagD->getLocation(), diag::warn_unused_variable) << DiagD;
1369
1.05k
        }
1370
1.61k
      }
1371
11.2k
    }
1372
1373
70.7k
    emitAndClearUnusedLocalTypedefWarnings();
1374
70.7k
  }
1375
1376
81.8k
  if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
1377
    // FIXME: Load additional unused private field candidates from the external
1378
    // source.
1379
2.21k
    RecordCompleteMap RecordsComplete;
1380
2.21k
    RecordCompleteMap MNCComplete;
1381
2.21k
    for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
1382
2.33k
         E = UnusedPrivateFields.end(); I != E; 
++I116
) {
1383
116
      const NamedDecl *D = *I;
1384
116
      const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1385
116
      if (RD && !RD->isUnion() &&
1386
116
          
IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)110
) {
1387
71
        Diag(D->getLocation(), diag::warn_unused_private_field)
1388
71
              << D->getDeclName();
1389
71
      }
1390
116
    }
1391
2.21k
  }
1392
1393
81.8k
  if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
1394
81.2k
    if (ExternalSource)
1395
12.1k
      ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
1396
81.2k
    for (const auto &DeletedFieldInfo : DeleteExprs) {
1397
647
      for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
1398
647
        AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
1399
647
                                  DeleteExprLoc.second);
1400
647
      }
1401
418
    }
1402
81.2k
  }
1403
1404
  // Check we've noticed that we're no longer parsing the initializer for every
1405
  // variable. If we miss cases, then at best we have a performance issue and
1406
  // at worst a rejects-valid bug.
1407
81.8k
  assert(ParsingInitForAutoVars.empty() &&
1408
81.8k
         "Didn't unmark var as having its initializer parsed");
1409
1410
81.8k
  if (!PP.isIncrementalProcessingEnabled())
1411
81.8k
    TUScope = nullptr;
1412
81.8k
}
1413
1414
1415
//===----------------------------------------------------------------------===//
1416
// Helper functions.
1417
//===----------------------------------------------------------------------===//
1418
1419
130M
DeclContext *Sema::getFunctionLevelDeclContext(bool AllowLambda) {
1420
130M
  DeclContext *DC = CurContext;
1421
1422
134M
  while (true) {
1423
134M
    if (isa<BlockDecl>(DC) || 
isa<EnumDecl>(DC)134M
||
isa<CapturedDecl>(DC)133M
||
1424
134M
        
isa<RequiresExprBodyDecl>(DC)130M
) {
1425
3.59M
      DC = DC->getParent();
1426
130M
    } else if (!AllowLambda && 
isa<CXXMethodDecl>(DC)130M
&&
1427
130M
               
cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call14.7M
&&
1428
130M
               
cast<CXXRecordDecl>(DC->getParent())->isLambda()865k
) {
1429
79.4k
      DC = DC->getParent()->getParent();
1430
130M
    } else break;
1431
134M
  }
1432
1433
130M
  return DC;
1434
130M
}
1435
1436
/// getCurFunctionDecl - If inside of a function body, this returns a pointer
1437
/// to the function decl for the function being parsed.  If we're currently
1438
/// in a 'block', this returns the containing context.
1439
88.0M
FunctionDecl *Sema::getCurFunctionDecl(bool AllowLambda) {
1440
88.0M
  DeclContext *DC = getFunctionLevelDeclContext(AllowLambda);
1441
88.0M
  return dyn_cast<FunctionDecl>(DC);
1442
88.0M
}
1443
1444
34.0M
ObjCMethodDecl *Sema::getCurMethodDecl() {
1445
34.0M
  DeclContext *DC = getFunctionLevelDeclContext();
1446
35.6M
  while (isa<RecordDecl>(DC))
1447
1.59M
    DC = DC->getParent();
1448
34.0M
  return dyn_cast<ObjCMethodDecl>(DC);
1449
34.0M
}
1450
1451
1.97M
NamedDecl *Sema::getCurFunctionOrMethodDecl() {
1452
1.97M
  DeclContext *DC = getFunctionLevelDeclContext();
1453
1.97M
  if (isa<ObjCMethodDecl>(DC) || 
isa<FunctionDecl>(DC)1.96M
)
1454
1.89M
    return cast<NamedDecl>(DC);
1455
79.6k
  return nullptr;
1456
1.97M
}
1457
1458
776k
LangAS Sema::getDefaultCXXMethodAddrSpace() const {
1459
776k
  if (getLangOpts().OpenCL)
1460
401
    return getASTContext().getDefaultOpenCLPointeeAddrSpace();
1461
775k
  return LangAS::Default;
1462
776k
}
1463
1464
3.24M
void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
1465
  // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1466
  // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1467
  // been made more painfully obvious by the refactor that introduced this
1468
  // function, but it is possible that the incoming argument can be
1469
  // eliminated. If it truly cannot be (for example, there is some reentrancy
1470
  // issue I am not seeing yet), then there should at least be a clarifying
1471
  // comment somewhere.
1472
3.24M
  if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
1473
224k
    switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
1474
224k
              Diags.getCurrentDiagID())) {
1475
98
    case DiagnosticIDs::SFINAE_Report:
1476
      // We'll report the diagnostic below.
1477
98
      break;
1478
1479
163k
    case DiagnosticIDs::SFINAE_SubstitutionFailure:
1480
      // Count this failure so that we know that template argument deduction
1481
      // has failed.
1482
163k
      ++NumSFINAEErrors;
1483
1484
      // Make a copy of this suppressed diagnostic and store it with the
1485
      // template-deduction information.
1486
163k
      if (*Info && 
!(*Info)->hasSFINAEDiagnostic()151k
) {
1487
149k
        Diagnostic DiagInfo(&Diags);
1488
149k
        (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1489
149k
                       PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1490
149k
      }
1491
1492
163k
      Diags.setLastDiagnosticIgnored(true);
1493
163k
      Diags.Clear();
1494
163k
      return;
1495
1496
93
    case DiagnosticIDs::SFINAE_AccessControl: {
1497
      // Per C++ Core Issue 1170, access control is part of SFINAE.
1498
      // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
1499
      // make access control a part of SFINAE for the purposes of checking
1500
      // type traits.
1501
93
      if (!AccessCheckingSFINAE && 
!getLangOpts().CPlusPlus1117
)
1502
1
        break;
1503
1504
92
      SourceLocation Loc = Diags.getCurrentDiagLoc();
1505
1506
      // Suppress this diagnostic.
1507
92
      ++NumSFINAEErrors;
1508
1509
      // Make a copy of this suppressed diagnostic and store it with the
1510
      // template-deduction information.
1511
92
      if (*Info && 
!(*Info)->hasSFINAEDiagnostic()15
) {
1512
14
        Diagnostic DiagInfo(&Diags);
1513
14
        (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1514
14
                       PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1515
14
      }
1516
1517
92
      Diags.setLastDiagnosticIgnored(true);
1518
92
      Diags.Clear();
1519
1520
      // Now the diagnostic state is clear, produce a C++98 compatibility
1521
      // warning.
1522
92
      Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
1523
1524
      // The last diagnostic which Sema produced was ignored. Suppress any
1525
      // notes attached to it.
1526
92
      Diags.setLastDiagnosticIgnored(true);
1527
92
      return;
1528
93
    }
1529
1530
60.1k
    case DiagnosticIDs::SFINAE_Suppress:
1531
      // Make a copy of this suppressed diagnostic and store it with the
1532
      // template-deduction information;
1533
60.1k
      if (*Info) {
1534
55.0k
        Diagnostic DiagInfo(&Diags);
1535
55.0k
        (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
1536
55.0k
                       PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1537
55.0k
      }
1538
1539
      // Suppress this diagnostic.
1540
60.1k
      Diags.setLastDiagnosticIgnored(true);
1541
60.1k
      Diags.Clear();
1542
60.1k
      return;
1543
224k
    }
1544
224k
  }
1545
1546
  // Copy the diagnostic printing policy over the ASTContext printing policy.
1547
  // TODO: Stop doing that.  See: https://reviews.llvm.org/D45093#1090292
1548
3.02M
  Context.setPrintingPolicy(getPrintingPolicy());
1549
1550
  // Emit the diagnostic.
1551
3.02M
  if (!Diags.EmitCurrentDiagnostic())
1552
2.72M
    return;
1553
1554
  // If this is not a note, and we're in a template instantiation
1555
  // that is different from the last template instantiation where
1556
  // we emitted an error, print a template instantiation
1557
  // backtrace.
1558
294k
  if (!DiagnosticIDs::isBuiltinNote(DiagID))
1559
195k
    PrintContextStack();
1560
294k
}
1561
1562
Sema::SemaDiagnosticBuilder
1563
107k
Sema::Diag(SourceLocation Loc, const PartialDiagnostic &PD, bool DeferHint) {
1564
107k
  return Diag(Loc, PD.getDiagID(), DeferHint) << PD;
1565
107k
}
1566
1567
12.5M
bool Sema::hasUncompilableErrorOccurred() const {
1568
12.5M
  if (getDiagnostics().hasUncompilableErrorOccurred())
1569
230k
    return true;
1570
12.3M
  auto *FD = dyn_cast<FunctionDecl>(CurContext);
1571
12.3M
  if (!FD)
1572
4.08M
    return false;
1573
8.23M
  auto Loc = DeviceDeferredDiags.find(FD);
1574
8.23M
  if (Loc == DeviceDeferredDiags.end())
1575
8.23M
    return false;
1576
195
  for (auto PDAt : Loc->second) {
1577
195
    if (DiagnosticIDs::isDefaultMappingAsError(PDAt.second.getDiagID()))
1578
195
      return true;
1579
195
  }
1580
0
  return false;
1581
195
}
1582
1583
// Print notes showing how we can reach FD starting from an a priori
1584
// known-callable function.
1585
150
static void emitCallStackNotes(Sema &S, FunctionDecl *FD) {
1586
150
  auto FnIt = S.DeviceKnownEmittedFns.find(FD);
1587
268
  while (FnIt != S.DeviceKnownEmittedFns.end()) {
1588
    // Respect error limit.
1589
119
    if (S.Diags.hasFatalErrorOccurred())
1590
1
      return;
1591
118
    DiagnosticBuilder Builder(
1592
118
        S.Diags.Report(FnIt->second.Loc, diag::note_called_by));
1593
118
    Builder << FnIt->second.FD;
1594
118
    FnIt = S.DeviceKnownEmittedFns.find(FnIt->second.FD);
1595
118
  }
1596
150
}
1597
1598
namespace {
1599
1600
/// Helper class that emits deferred diagnostic messages if an entity directly
1601
/// or indirectly using the function that causes the deferred diagnostic
1602
/// messages is known to be emitted.
1603
///
1604
/// During parsing of AST, certain diagnostic messages are recorded as deferred
1605
/// diagnostics since it is unknown whether the functions containing such
1606
/// diagnostics will be emitted. A list of potentially emitted functions and
1607
/// variables that may potentially trigger emission of functions are also
1608
/// recorded. DeferredDiagnosticsEmitter recursively visits used functions
1609
/// by each function to emit deferred diagnostics.
1610
///
1611
/// During the visit, certain OpenMP directives or initializer of variables
1612
/// with certain OpenMP attributes will cause subsequent visiting of any
1613
/// functions enter a state which is called OpenMP device context in this
1614
/// implementation. The state is exited when the directive or initializer is
1615
/// exited. This state can change the emission states of subsequent uses
1616
/// of functions.
1617
///
1618
/// Conceptually the functions or variables to be visited form a use graph
1619
/// where the parent node uses the child node. At any point of the visit,
1620
/// the tree nodes traversed from the tree root to the current node form a use
1621
/// stack. The emission state of the current node depends on two factors:
1622
///    1. the emission state of the root node
1623
///    2. whether the current node is in OpenMP device context
1624
/// If the function is decided to be emitted, its contained deferred diagnostics
1625
/// are emitted, together with the information about the use stack.
1626
///
1627
class DeferredDiagnosticsEmitter
1628
    : public UsedDeclVisitor<DeferredDiagnosticsEmitter> {
1629
public:
1630
  typedef UsedDeclVisitor<DeferredDiagnosticsEmitter> Inherited;
1631
1632
  // Whether the function is already in the current use-path.
1633
  llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> InUsePath;
1634
1635
  // The current use-path.
1636
  llvm::SmallVector<CanonicalDeclPtr<FunctionDecl>, 4> UsePath;
1637
1638
  // Whether the visiting of the function has been done. Done[0] is for the
1639
  // case not in OpenMP device context. Done[1] is for the case in OpenMP
1640
  // device context. We need two sets because diagnostics emission may be
1641
  // different depending on whether it is in OpenMP device context.
1642
  llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> DoneMap[2];
1643
1644
  // Emission state of the root node of the current use graph.
1645
  bool ShouldEmitRootNode;
1646
1647
  // Current OpenMP device context level. It is initialized to 0 and each
1648
  // entering of device context increases it by 1 and each exit decreases
1649
  // it by 1. Non-zero value indicates it is currently in device context.
1650
  unsigned InOMPDeviceContext;
1651
1652
  DeferredDiagnosticsEmitter(Sema &S)
1653
4.66k
      : Inherited(S), ShouldEmitRootNode(false), InOMPDeviceContext(0) {}
1654
1655
557
  bool shouldVisitDiscardedStmt() const { return false; }
1656
1657
8.91k
  void VisitOMPTargetDirective(OMPTargetDirective *Node) {
1658
8.91k
    ++InOMPDeviceContext;
1659
8.91k
    Inherited::VisitOMPTargetDirective(Node);
1660
8.91k
    --InOMPDeviceContext;
1661
8.91k
  }
1662
1663
309k
  void visitUsedDecl(SourceLocation Loc, Decl *D) {
1664
309k
    if (isa<VarDecl>(D))
1665
213k
      return;
1666
96.4k
    if (auto *FD = dyn_cast<FunctionDecl>(D))
1667
35.2k
      checkFunc(Loc, FD);
1668
61.1k
    else
1669
61.1k
      Inherited::visitUsedDecl(Loc, D);
1670
96.4k
  }
1671
1672
1.83k
  void checkVar(VarDecl *VD) {
1673
1.83k
    assert(VD->isFileVarDecl() &&
1674
1.83k
           "Should only check file-scope variables");
1675
1.83k
    if (auto *Init = VD->getInit()) {
1676
1.83k
      auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD);
1677
1.83k
      bool IsDev = DevTy && 
(169
*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost169
||
1678
169
                             *DevTy == OMPDeclareTargetDeclAttr::DT_Any);
1679
1.83k
      if (IsDev)
1680
169
        ++InOMPDeviceContext;
1681
1.83k
      this->Visit(Init);
1682
1.83k
      if (IsDev)
1683
169
        --InOMPDeviceContext;
1684
1.83k
    }
1685
1.83k
  }
1686
1687
66.9k
  void checkFunc(SourceLocation Loc, FunctionDecl *FD) {
1688
66.9k
    auto &Done = DoneMap[InOMPDeviceContext > 0 ? 
13.88k
:
063.0k
];
1689
66.9k
    FunctionDecl *Caller = UsePath.empty() ? 
nullptr35.7k
:
UsePath.back()31.2k
;
1690
66.9k
    if ((!ShouldEmitRootNode && 
!S.getLangOpts().OpenMP25.1k
&&
!Caller307
) ||
1691
66.9k
        
S.shouldIgnoreInHostDeviceCheck(FD)66.6k
||
InUsePath.count(FD)66.6k
)
1692
455
      return;
1693
    // Finalize analysis of OpenMP-specific constructs.
1694
66.5k
    if (Caller && 
S.LangOpts.OpenMP31.1k
&&
UsePath.size() == 130.7k
&&
1695
66.5k
        
(26.2k
ShouldEmitRootNode26.2k
||
InOMPDeviceContext11.8k
))
1696
14.5k
      S.finalizeOpenMPDelayedAnalysis(Caller, FD, Loc);
1697
66.5k
    if (Caller)
1698
31.1k
      S.DeviceKnownEmittedFns[FD] = {Caller, Loc};
1699
    // Always emit deferred diagnostics for the direct users. This does not
1700
    // lead to explosion of diagnostics since each user is visited at most
1701
    // twice.
1702
66.5k
    if (ShouldEmitRootNode || 
InOMPDeviceContext24.8k
)
1703
43.4k
      emitDeferredDiags(FD, Caller);
1704
    // Do not revisit a function if the function body has been completely
1705
    // visited before.
1706
66.5k
    if (!Done.insert(FD).second)
1707
23.8k
      return;
1708
42.6k
    InUsePath.insert(FD);
1709
42.6k
    UsePath.push_back(FD);
1710
42.6k
    if (auto *S = FD->getBody()) {
1711
35.5k
      this->Visit(S);
1712
35.5k
    }
1713
42.6k
    UsePath.pop_back();
1714
42.6k
    InUsePath.erase(FD);
1715
42.6k
  }
1716
1717
33.5k
  void checkRecordedDecl(Decl *D) {
1718
33.5k
    if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1719
31.7k
      ShouldEmitRootNode = S.getEmissionStatus(FD, /*Final=*/true) ==
1720
31.7k
                           Sema::FunctionEmissionStatus::Emitted;
1721
31.7k
      checkFunc(SourceLocation(), FD);
1722
31.7k
    } else
1723
1.83k
      checkVar(cast<VarDecl>(D));
1724
33.5k
  }
1725
1726
  // Emit any deferred diagnostics for FD
1727
43.4k
  void emitDeferredDiags(FunctionDecl *FD, bool ShowCallStack) {
1728
43.4k
    auto It = S.DeviceDeferredDiags.find(FD);
1729
43.4k
    if (It == S.DeviceDeferredDiags.end())
1730
43.3k
      return;
1731
92
    bool HasWarningOrError = false;
1732
92
    bool FirstDiag = true;
1733
225
    for (PartialDiagnosticAt &PDAt : It->second) {
1734
      // Respect error limit.
1735
225
      if (S.Diags.hasFatalErrorOccurred())
1736
1
        return;
1737
224
      const SourceLocation &Loc = PDAt.first;
1738
224
      const PartialDiagnostic &PD = PDAt.second;
1739
224
      HasWarningOrError |=
1740
224
          S.getDiagnostics().getDiagnosticLevel(PD.getDiagID(), Loc) >=
1741
224
          DiagnosticsEngine::Warning;
1742
224
      {
1743
224
        DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
1744
224
        PD.Emit(Builder);
1745
224
      }
1746
      // Emit the note on the first diagnostic in case too many diagnostics
1747
      // cause the note not emitted.
1748
224
      if (FirstDiag && 
HasWarningOrError91
&&
ShowCallStack86
) {
1749
83
        emitCallStackNotes(S, FD);
1750
83
        FirstDiag = false;
1751
83
      }
1752
224
    }
1753
92
  }
1754
};
1755
} // namespace
1756
1757
81.8k
void Sema::emitDeferredDiags() {
1758
81.8k
  if (ExternalSource)
1759
12.1k
    ExternalSource->ReadDeclsToCheckForDeferredDiags(
1760
12.1k
        DeclsToCheckForDeferredDiags);
1761
1762
81.8k
  if ((DeviceDeferredDiags.empty() && 
!LangOpts.OpenMP81.7k
) ||
1763
81.8k
      
DeclsToCheckForDeferredDiags.empty()9.67k
)
1764
77.1k
    return;
1765
1766
4.66k
  DeferredDiagnosticsEmitter DDE(*this);
1767
4.66k
  for (auto D : DeclsToCheckForDeferredDiags)
1768
33.5k
    DDE.checkRecordedDecl(D);
1769
4.66k
}
1770
1771
// In CUDA, there are some constructs which may appear in semantically-valid
1772
// code, but trigger errors if we ever generate code for the function in which
1773
// they appear.  Essentially every construct you're not allowed to use on the
1774
// device falls into this category, because you are allowed to use these
1775
// constructs in a __host__ __device__ function, but only if that function is
1776
// never codegen'ed on the device.
1777
//
1778
// To handle semantic checking for these constructs, we keep track of the set of
1779
// functions we know will be emitted, either because we could tell a priori that
1780
// they would be emitted, or because they were transitively called by a
1781
// known-emitted function.
1782
//
1783
// We also keep a partial call graph of which not-known-emitted functions call
1784
// which other not-known-emitted functions.
1785
//
1786
// When we see something which is illegal if the current function is emitted
1787
// (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or
1788
// CheckCUDACall), we first check if the current function is known-emitted.  If
1789
// so, we immediately output the diagnostic.
1790
//
1791
// Otherwise, we "defer" the diagnostic.  It sits in Sema::DeviceDeferredDiags
1792
// until we discover that the function is known-emitted, at which point we take
1793
// it out of this map and emit the diagnostic.
1794
1795
Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(Kind K, SourceLocation Loc,
1796
                                                   unsigned DiagID,
1797
                                                   FunctionDecl *Fn, Sema &S)
1798
    : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
1799
3.24M
      ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
1800
3.24M
  switch (K) {
1801
125
  case K_Nop:
1802
125
    break;
1803
3.24M
  case K_Immediate:
1804
3.24M
  case K_ImmediateWithCallStack:
1805
3.24M
    ImmediateDiag.emplace(
1806
3.24M
        ImmediateDiagBuilder(S.Diags.Report(Loc, DiagID), S, DiagID));
1807
3.24M
    break;
1808
571
  case K_Deferred:
1809
571
    assert(Fn && "Must have a function to attach the deferred diag to.");
1810
0
    auto &Diags = S.DeviceDeferredDiags[Fn];
1811
571
    PartialDiagId.emplace(Diags.size());
1812
571
    Diags.emplace_back(Loc, S.PDiag(DiagID));
1813
571
    break;
1814
3.24M
  }
1815
3.24M
}
1816
1817
Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D)
1818
    : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn),
1819
      ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),
1820
18
      PartialDiagId(D.PartialDiagId) {
1821
  // Clean the previous diagnostics.
1822
18
  D.ShowCallStack = false;
1823
18
  D.ImmediateDiag.reset();
1824
18
  D.PartialDiagId.reset();
1825
18
}
1826
1827
3.36M
Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
1828
3.36M
  if (ImmediateDiag) {
1829
    // Emit our diagnostic and, if it was a warning or error, output a callstack
1830
    // if Fn isn't a priori known-emitted.
1831
3.36M
    bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
1832
3.36M
                                DiagID, Loc) >= DiagnosticsEngine::Warning;
1833
3.36M
    ImmediateDiag.reset(); // Emit the immediate diag.
1834
3.36M
    if (IsWarningOrError && 
ShowCallStack391k
)
1835
67
      emitCallStackNotes(S, Fn);
1836
3.36M
  } else {
1837
907
    assert((!PartialDiagId || ShowCallStack) &&
1838
907
           "Must always show call stack for deferred diags.");
1839
907
  }
1840
3.36M
}
1841
1842
Sema::SemaDiagnosticBuilder
1843
845
Sema::targetDiag(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD) {
1844
845
  FD = FD ? 
FD372
:
getCurFunctionDecl()473
;
1845
845
  if (LangOpts.OpenMP)
1846
355
    return LangOpts.OpenMPIsDevice ? 
diagIfOpenMPDeviceCode(Loc, DiagID, FD)348
1847
355
                                   : 
diagIfOpenMPHostCode(Loc, DiagID, FD)7
;
1848
490
  if (getLangOpts().CUDA)
1849
72
    return getLangOpts().CUDAIsDevice ? 
CUDADiagIfDeviceCode(Loc, DiagID)71
1850
72
                                      : 
CUDADiagIfHostCode(Loc, DiagID)1
;
1851
1852
418
  if (getLangOpts().SYCLIsDevice)
1853
122
    return SYCLDiagIfDeviceCode(Loc, DiagID);
1854
1855
296
  return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc, DiagID,
1856
296
                               FD, *this);
1857
418
}
1858
1859
Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID,
1860
3.24M
                                       bool DeferHint) {
1861
3.24M
  bool IsError = Diags.getDiagnosticIDs()->isDefaultMappingAsError(DiagID);
1862
3.24M
  bool ShouldDefer = getLangOpts().CUDA && 
LangOpts.GPUDeferDiag7.22k
&&
1863
3.24M
                     
DiagnosticIDs::isDeferrable(DiagID)135
&&
1864
3.24M
                     
(60
DeferHint60
||
DeferDiags48
||
!IsError42
);
1865
3.24M
  auto SetIsLastErrorImmediate = [&](bool Flag) {
1866
3.24M
    if (IsError)
1867
724k
      IsLastErrorImmediate = Flag;
1868
3.24M
  };
1869
3.24M
  if (!ShouldDefer) {
1870
3.24M
    SetIsLastErrorImmediate(true);
1871
3.24M
    return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc,
1872
3.24M
                                 DiagID, getCurFunctionDecl(), *this);
1873
3.24M
  }
1874
1875
18
  SemaDiagnosticBuilder DB = getLangOpts().CUDAIsDevice
1876
18
                                 ? 
CUDADiagIfDeviceCode(Loc, DiagID)6
1877
18
                                 : 
CUDADiagIfHostCode(Loc, DiagID)12
;
1878
18
  SetIsLastErrorImmediate(DB.isImmediate());
1879
18
  return DB;
1880
3.24M
}
1881
1882
39.8M
void Sema::checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D) {
1883
39.8M
  if (isUnevaluatedContext() || 
Ty.isNull()39.6M
)
1884
268k
    return;
1885
1886
  // The original idea behind checkTypeSupport function is that unused
1887
  // declarations can be replaced with an array of bytes of the same size during
1888
  // codegen, such replacement doesn't seem to be possible for types without
1889
  // constant byte size like zero length arrays. So, do a deep check for SYCL.
1890
39.6M
  if (D && 
LangOpts.SYCLIsDevice26.1M
) {
1891
1.22k
    llvm::DenseSet<QualType> Visited;
1892
1.22k
    deepTypeCheckForSYCLDevice(Loc, Visited, D);
1893
1.22k
  }
1894
1895
39.6M
  Decl *C = cast<Decl>(getCurLexicalContext());
1896
1897
  // Memcpy operations for structs containing a member with unsupported type
1898
  // are ok, though.
1899
39.6M
  if (const auto *MD = dyn_cast<CXXMethodDecl>(C)) {
1900
6.36M
    if ((MD->isCopyAssignmentOperator() || 
MD->isMoveAssignmentOperator()6.30M
) &&
1901
6.36M
        
MD->isTrivial()106k
)
1902
26.5k
      return;
1903
1904
6.33M
    if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(MD))
1905
1.33M
      if (Ctor->isCopyOrMoveConstructor() && 
Ctor->isTrivial()158k
)
1906
40.5k
        return;
1907
6.33M
  }
1908
1909
  // Try to associate errors with the lexical context, if that is a function, or
1910
  // the value declaration otherwise.
1911
39.5M
  FunctionDecl *FD = isa<FunctionDecl>(C) ? 
cast<FunctionDecl>(C)27.4M
1912
39.5M
                                          : 
dyn_cast_or_null<FunctionDecl>(D)12.0M
;
1913
1914
39.5M
  auto CheckDeviceType = [&](QualType Ty) {
1915
312k
    if (Ty->isDependentType())
1916
5.35k
      return;
1917
1918
306k
    if (Ty->isBitIntType()) {
1919
4
      if (!Context.getTargetInfo().hasBitIntType()) {
1920
0
        PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
1921
0
        if (D)
1922
0
          PD << D;
1923
0
        else
1924
0
          PD << "expression";
1925
0
        targetDiag(Loc, PD, FD)
1926
0
            << false /*show bit size*/ << 0 /*bitsize*/ << false /*return*/
1927
0
            << Ty << Context.getTargetInfo().getTriple().str();
1928
0
      }
1929
4
      return;
1930
4
    }
1931
1932
    // Check if we are dealing with two 'long double' but with different
1933
    // semantics.
1934
306k
    bool LongDoubleMismatched = false;
1935
306k
    if (Ty->isRealFloatingType() && 
Context.getTypeSize(Ty) == 12842.9k
) {
1936
217
      const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(Ty);
1937
217
      if ((&Sem != &llvm::APFloat::PPCDoubleDouble() &&
1938
217
           
!Context.getTargetInfo().hasFloat128Type()129
) ||
1939
217
          
(124
&Sem == &llvm::APFloat::PPCDoubleDouble()124
&&
1940
124
           
!Context.getTargetInfo().hasIbm128Type()88
))
1941
178
        LongDoubleMismatched = true;
1942
217
    }
1943
1944
306k
    if ((Ty->isFloat16Type() && 
!Context.getTargetInfo().hasFloat16Type()292
) ||
1945
306k
        (Ty->isFloat128Type() && 
!Context.getTargetInfo().hasFloat128Type()82
) ||
1946
306k
        
(306k
Ty->isIbm128Type()306k
&&
!Context.getTargetInfo().hasIbm128Type()1
) ||
1947
306k
        
(306k
Ty->isIntegerType()306k
&&
Context.getTypeSize(Ty) == 128191k
&&
1948
306k
         
!Context.getTargetInfo().hasInt128Type()115
) ||
1949
306k
        
LongDoubleMismatched306k
) {
1950
217
      PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
1951
217
      if (D)
1952
171
        PD << D;
1953
46
      else
1954
46
        PD << "expression";
1955
1956
217
      if (targetDiag(Loc, PD, FD)
1957
217
          << true /*show bit size*/
1958
217
          << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1959
217
          << false /*return*/ << Context.getTargetInfo().getTriple().str()) {
1960
30
        if (D)
1961
30
          D->setInvalidDecl();
1962
30
      }
1963
217
      if (D)
1964
171
        targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
1965
217
    }
1966
306k
  };
1967
1968
61.9M
  auto CheckType = [&](QualType Ty, bool IsRetTy = false) {
1969
61.9M
    if (LangOpts.SYCLIsDevice || 
(61.9M
LangOpts.OpenMP61.9M
&&
LangOpts.OpenMPIsDevice10.7M
) ||
1970
61.9M
        
LangOpts.CUDAIsDevice61.6M
)
1971
312k
      CheckDeviceType(Ty);
1972
1973
61.9M
    QualType UnqualTy = Ty.getCanonicalType().getUnqualifiedType();
1974
61.9M
    const TargetInfo &TI = Context.getTargetInfo();
1975
61.9M
    if (!TI.hasLongDoubleType() && 
UnqualTy == Context.LongDoubleTy430
) {
1976
28
      PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
1977
28
      if (D)
1978
16
        PD << D;
1979
12
      else
1980
12
        PD << "expression";
1981
1982
28
      if (Diag(Loc, PD, FD)
1983
28
          << false /*show bit size*/ << 0 << Ty << false /*return*/
1984
28
          << Context.getTargetInfo().getTriple().str()) {
1985
28
        if (D)
1986
16
          D->setInvalidDecl();
1987
28
      }
1988
28
      if (D)
1989
16
        targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
1990
28
    }
1991
1992
61.9M
    bool IsDouble = UnqualTy == Context.DoubleTy;
1993
61.9M
    bool IsFloat = UnqualTy == Context.FloatTy;
1994
61.9M
    if (IsRetTy && 
!TI.hasFPReturn()8.93M
&&
(0
IsDouble0
||
IsFloat0
)) {
1995
0
      PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
1996
0
      if (D)
1997
0
        PD << D;
1998
0
      else
1999
0
        PD << "expression";
2000
2001
0
      if (Diag(Loc, PD, FD)
2002
0
          << false /*show bit size*/ << 0 << Ty << true /*return*/
2003
0
          << Context.getTargetInfo().getTriple().str()) {
2004
0
        if (D)
2005
0
          D->setInvalidDecl();
2006
0
      }
2007
0
      if (D)
2008
0
        targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2009
0
    }
2010
61.9M
  };
2011
2012
39.5M
  CheckType(Ty);
2013
39.5M
  if (const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) {
2014
8.75M
    for (const auto &ParamTy : FPTy->param_types())
2015
13.4M
      CheckType(ParamTy);
2016
8.75M
    CheckType(FPTy->getReturnType(), /*IsRetTy=*/true);
2017
8.75M
  }
2018
39.5M
  if (const auto *FNPTy = dyn_cast<FunctionNoProtoType>(Ty))
2019
178k
    CheckType(FNPTy->getReturnType(), /*IsRetTy=*/true);
2020
39.5M
}
2021
2022
/// Looks through the macro-expansion chain for the given
2023
/// location, looking for a macro expansion with the given name.
2024
/// If one is found, returns true and sets the location to that
2025
/// expansion loc.
2026
184
bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
2027
184
  SourceLocation loc = locref;
2028
184
  if (!loc.isMacroID()) 
return false5
;
2029
2030
  // There's no good way right now to look at the intermediate
2031
  // expansions, so just jump to the expansion location.
2032
179
  loc = getSourceManager().getExpansionLoc(loc);
2033
2034
  // If that's written with the name, stop here.
2035
179
  SmallString<16> buffer;
2036
179
  if (getPreprocessor().getSpelling(loc, buffer) == name) {
2037
13
    locref = loc;
2038
13
    return true;
2039
13
  }
2040
166
  return false;
2041
179
}
2042
2043
/// Determines the active Scope associated with the given declaration
2044
/// context.
2045
///
2046
/// This routine maps a declaration context to the active Scope object that
2047
/// represents that declaration context in the parser. It is typically used
2048
/// from "scope-less" code (e.g., template instantiation, lazy creation of
2049
/// declarations) that injects a name for name-lookup purposes and, therefore,
2050
/// must update the Scope.
2051
///
2052
/// \returns The scope corresponding to the given declaraion context, or NULL
2053
/// if no such scope is open.
2054
468k
Scope *Sema::getScopeForContext(DeclContext *Ctx) {
2055
2056
468k
  if (!Ctx)
2057
0
    return nullptr;
2058
2059
468k
  Ctx = Ctx->getPrimaryContext();
2060
1.69M
  for (Scope *S = getCurScope(); S; 
S = S->getParent()1.23M
) {
2061
    // Ignore scopes that cannot have declarations. This is important for
2062
    // out-of-line definitions of static class members.
2063
1.29M
    if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
2064
1.29M
      if (DeclContext *Entity = S->getEntity())
2065
1.14M
        if (Ctx == Entity->getPrimaryContext())
2066
64.5k
          return S;
2067
1.29M
  }
2068
2069
404k
  return nullptr;
2070
468k
}
2071
2072
/// Enter a new function scope
2073
4.17M
void Sema::PushFunctionScope() {
2074
4.17M
  if (FunctionScopes.empty() && 
CachedFunctionScope4.02M
) {
2075
    // Use CachedFunctionScope to avoid allocating memory when possible.
2076
3.96M
    CachedFunctionScope->Clear();
2077
3.96M
    FunctionScopes.push_back(CachedFunctionScope.release());
2078
3.96M
  } else {
2079
209k
    FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
2080
209k
  }
2081
4.17M
  if (LangOpts.OpenMP)
2082
94.4k
    pushOpenMPFunctionRegion();
2083
4.17M
}
2084
2085
3.38k
void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
2086
3.38k
  FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
2087
3.38k
                                              BlockScope, Block));
2088
3.38k
}
2089
2090
13.7k
LambdaScopeInfo *Sema::PushLambdaScope() {
2091
13.7k
  LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
2092
13.7k
  FunctionScopes.push_back(LSI);
2093
13.7k
  return LSI;
2094
13.7k
}
2095
2096
3.84k
void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
2097
3.84k
  if (LambdaScopeInfo *const LSI = getCurLambda()) {
2098
3.84k
    LSI->AutoTemplateParameterDepth = Depth;
2099
3.84k
    return;
2100
3.84k
  }
2101
0
  llvm_unreachable(
2102
0
      "Remove assertion if intentionally called in a non-lambda context.");
2103
0
}
2104
2105
// Check that the type of the VarDecl has an accessible copy constructor and
2106
// resolve its destructor's exception specification.
2107
// This also performs initialization of block variables when they are moved
2108
// to the heap. It uses the same rules as applicable for implicit moves
2109
// according to the C++ standard in effect ([class.copy.elision]p3).
2110
102
static void checkEscapingByref(VarDecl *VD, Sema &S) {
2111
102
  QualType T = VD->getType();
2112
102
  EnterExpressionEvaluationContext scope(
2113
102
      S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2114
102
  SourceLocation Loc = VD->getLocation();
2115
102
  Expr *VarRef =
2116
102
      new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
2117
102
  ExprResult Result;
2118
102
  auto IE = InitializedEntity::InitializeBlock(Loc, T);
2119
102
  if (S.getLangOpts().CPlusPlus2b) {
2120
9
    auto *E = ImplicitCastExpr::Create(S.Context, T, CK_NoOp, VarRef, nullptr,
2121
9
                                       VK_XValue, FPOptionsOverride());
2122
9
    Result = S.PerformCopyInitialization(IE, SourceLocation(), E);
2123
93
  } else {
2124
93
    Result = S.PerformMoveOrCopyInitialization(
2125
93
        IE, Sema::NamedReturnInfo{VD, Sema::NamedReturnInfo::MoveEligible},
2126
93
        VarRef);
2127
93
  }
2128
2129
102
  if (!Result.isInvalid()) {
2130
61
    Result = S.MaybeCreateExprWithCleanups(Result);
2131
61
    Expr *Init = Result.getAs<Expr>();
2132
61
    S.Context.setBlockVarCopyInit(VD, Init, S.canThrow(Init));
2133
61
  }
2134
2135
  // The destructor's exception specification is needed when IRGen generates
2136
  // block copy/destroy functions. Resolve it here.
2137
102
  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2138
83
    if (CXXDestructorDecl *DD = RD->getDestructor()) {
2139
15
      auto *FPT = DD->getType()->getAs<FunctionProtoType>();
2140
15
      S.ResolveExceptionSpec(Loc, FPT);
2141
15
    }
2142
102
}
2143
2144
4.80M
static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) {
2145
  // Set the EscapingByref flag of __block variables captured by
2146
  // escaping blocks.
2147
4.80M
  for (const BlockDecl *BD : FSI.Blocks) {
2148
3.21k
    for (const BlockDecl::Capture &BC : BD->captures()) {
2149
3.21k
      VarDecl *VD = BC.getVariable();
2150
3.21k
      if (VD->hasAttr<BlocksAttr>()) {
2151
        // Nothing to do if this is a __block variable captured by a
2152
        // non-escaping block.
2153
550
        if (BD->doesNotEscape())
2154
26
          continue;
2155
524
        VD->setEscapingByref();
2156
524
      }
2157
      // Check whether the captured variable is or contains an object of
2158
      // non-trivial C union type.
2159
3.18k
      QualType CapType = BC.getVariable()->getType();
2160
3.18k
      if (CapType.hasNonTrivialToPrimitiveDestructCUnion() ||
2161
3.18k
          
CapType.hasNonTrivialToPrimitiveCopyCUnion()3.17k
)
2162
6
        S.checkNonTrivialCUnion(BC.getVariable()->getType(),
2163
6
                                BD->getCaretLocation(),
2164
6
                                Sema::NTCUC_BlockCapture,
2165
6
                                Sema::NTCUK_Destruct|Sema::NTCUK_Copy);
2166
3.18k
    }
2167
3.11k
  }
2168
2169
4.80M
  for (VarDecl *VD : FSI.ByrefBlockVars) {
2170
    // __block variables might require us to capture a copy-initializer.
2171
498
    if (!VD->isEscapingByref())
2172
81
      continue;
2173
    // It's currently invalid to ever have a __block variable with an
2174
    // array type; should we diagnose that here?
2175
    // Regardless, we don't want to ignore array nesting when
2176
    // constructing this copy.
2177
417
    if (VD->getType()->isStructureOrClassType())
2178
102
      checkEscapingByref(VD, S);
2179
417
  }
2180
4.80M
}
2181
2182
/// Pop a function (or block or lambda or captured region) scope from the stack.
2183
///
2184
/// \param WP The warning policy to use for CFG-based warnings, or null if such
2185
///        warnings should not be produced.
2186
/// \param D The declaration corresponding to this function scope, if producing
2187
///        CFG-based warnings.
2188
/// \param BlockType The type of the block expression, if D is a BlockDecl.
2189
Sema::PoppedFunctionScopePtr
2190
Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
2191
4.80M
                           const Decl *D, QualType BlockType) {
2192
4.80M
  assert(!FunctionScopes.empty() && "mismatched push/pop!");
2193
2194
0
  markEscapingByrefs(*FunctionScopes.back(), *this);
2195
2196
4.80M
  PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(),
2197
4.80M
                               PoppedFunctionScopeDeleter(this));
2198
2199
4.80M
  if (LangOpts.OpenMP)
2200
712k
    popOpenMPFunctionRegion(Scope.get());
2201
2202
  // Issue any analysis-based warnings.
2203
4.80M
  if (WP && 
D3.44M
)
2204
3.44M
    AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType);
2205
1.35M
  else
2206
1.35M
    for (const auto &PUD : Scope->PossiblyUnreachableDiags)
2207
33.8k
      Diag(PUD.Loc, PUD.PD);
2208
2209
4.80M
  return Scope;
2210
4.80M
}
2211
2212
void Sema::PoppedFunctionScopeDeleter::
2213
4.80M
operator()(sema::FunctionScopeInfo *Scope) const {
2214
  // Stash the function scope for later reuse if it's for a normal function.
2215
4.80M
  if (Scope->isPlainFunction() && 
!Self->CachedFunctionScope4.17M
)
2216
4.02M
    Self->CachedFunctionScope.reset(Scope);
2217
781k
  else
2218
781k
    delete Scope;
2219
4.80M
}
2220
2221
5.12M
void Sema::PushCompoundScope(bool IsStmtExpr) {
2222
5.12M
  getCurFunction()->CompoundScopes.push_back(
2223
5.12M
      CompoundScopeInfo(IsStmtExpr, getCurFPFeatures()));
2224
5.12M
}
2225
2226
5.12M
void Sema::PopCompoundScope() {
2227
5.12M
  FunctionScopeInfo *CurFunction = getCurFunction();
2228
5.12M
  assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
2229
2230
0
  CurFunction->CompoundScopes.pop_back();
2231
5.12M
}
2232
2233
/// Determine whether any errors occurred within this function/method/
2234
/// block.
2235
18.5k
bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
2236
18.5k
  return getCurFunction()->hasUnrecoverableErrorOccurred();
2237
18.5k
}
2238
2239
13.2k
void Sema::setFunctionHasBranchIntoScope() {
2240
13.2k
  if (!FunctionScopes.empty())
2241
13.2k
    FunctionScopes.back()->setHasBranchIntoScope();
2242
13.2k
}
2243
2244
1.84M
void Sema::setFunctionHasBranchProtectedScope() {
2245
1.84M
  if (!FunctionScopes.empty())
2246
1.84M
    FunctionScopes.back()->setHasBranchProtectedScope();
2247
1.84M
}
2248
2249
130
void Sema::setFunctionHasIndirectGoto() {
2250
130
  if (!FunctionScopes.empty())
2251
130
    FunctionScopes.back()->setHasIndirectGoto();
2252
130
}
2253
2254
70
void Sema::setFunctionHasMustTail() {
2255
70
  if (!FunctionScopes.empty())
2256
70
    FunctionScopes.back()->setHasMustTail();
2257
70
}
2258
2259
177k
BlockScopeInfo *Sema::getCurBlock() {
2260
177k
  if (FunctionScopes.empty())
2261
1.23k
    return nullptr;
2262
2263
176k
  auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
2264
176k
  if (CurBSI && 
CurBSI->TheDecl7.91k
&&
2265
176k
      
!CurBSI->TheDecl->Encloses(CurContext)7.91k
) {
2266
    // We have switched contexts due to template instantiation.
2267
0
    assert(!CodeSynthesisContexts.empty());
2268
0
    return nullptr;
2269
0
  }
2270
2271
176k
  return CurBSI;
2272
176k
}
2273
2274
3.50k
FunctionScopeInfo *Sema::getEnclosingFunction() const {
2275
3.50k
  if (FunctionScopes.empty())
2276
596
    return nullptr;
2277
2278
2.91k
  
for (int e = FunctionScopes.size() - 1; 2.90k
e >= 0;
--e4
) {
2279
2.91k
    if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
2280
4
      continue;
2281
2.90k
    return FunctionScopes[e];
2282
2.91k
  }
2283
0
  return nullptr;
2284
2.90k
}
2285
2286
302k
LambdaScopeInfo *Sema::getEnclosingLambda() const {
2287
302k
  for (auto *Scope : llvm::reverse(FunctionScopes)) {
2288
15.4k
    if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope)) {
2289
1.00k
      if (LSI->Lambda && 
!LSI->Lambda->Encloses(CurContext)177
) {
2290
        // We have switched contexts due to template instantiation.
2291
        // FIXME: We should swap out the FunctionScopes during code synthesis
2292
        // so that we don't need to check for this.
2293
6
        assert(!CodeSynthesisContexts.empty());
2294
0
        return nullptr;
2295
6
      }
2296
1.00k
      return LSI;
2297
1.00k
    }
2298
15.4k
  }
2299
301k
  return nullptr;
2300
302k
}
2301
2302
15.3M
LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
2303
15.3M
  if (FunctionScopes.empty())
2304
1.81M
    return nullptr;
2305
2306
13.5M
  auto I = FunctionScopes.rbegin();
2307
13.5M
  if (IgnoreNonLambdaCapturingScope) {
2308
11.9M
    auto E = FunctionScopes.rend();
2309
15.5M
    while (I != E && 
isa<CapturingScopeInfo>(*I)15.5M
&&
!isa<LambdaScopeInfo>(*I)3.62M
)
2310
3.59M
      ++I;
2311
11.9M
    if (I == E)
2312
130
      return nullptr;
2313
11.9M
  }
2314
13.5M
  auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
2315
13.5M
  if (CurLSI && 
CurLSI->Lambda99.4k
&&
2316
13.5M
      
!CurLSI->Lambda->Encloses(CurContext)58.2k
) {
2317
    // We have switched contexts due to template instantiation.
2318
383
    assert(!CodeSynthesisContexts.empty());
2319
0
    return nullptr;
2320
383
  }
2321
2322
13.5M
  return CurLSI;
2323
13.5M
}
2324
2325
// We have a generic lambda if we parsed auto parameters, or we have
2326
// an associated template parameter list.
2327
4.14k
LambdaScopeInfo *Sema::getCurGenericLambda() {
2328
4.14k
  if (LambdaScopeInfo *LSI =  getCurLambda()) {
2329
4.14k
    return (LSI->TemplateParams.size() ||
2330
4.14k
                    
LSI->GLTemplateParameterList1.77k
) ?
LSI2.58k
:
nullptr1.56k
;
2331
4.14k
  }
2332
0
  return nullptr;
2333
4.14k
}
2334
2335
2336
58.1M
void Sema::ActOnComment(SourceRange Comment) {
2337
58.1M
  if (!LangOpts.RetainCommentsFromSystemHeaders &&
2338
58.1M
      
SourceMgr.isInSystemHeader(Comment.getBegin())58.1M
)
2339
19.7M
    return;
2340
38.3M
  RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);
2341
38.3M
  if (RC.isAlmostTrailingComment()) {
2342
69
    SourceRange MagicMarkerRange(Comment.getBegin(),
2343
69
                                 Comment.getBegin().getLocWithOffset(3));
2344
69
    StringRef MagicMarkerText;
2345
69
    switch (RC.getKind()) {
2346
18
    case RawComment::RCK_OrdinaryBCPL:
2347
18
      MagicMarkerText = "///<";
2348
18
      break;
2349
51
    case RawComment::RCK_OrdinaryC:
2350
51
      MagicMarkerText = "/**<";
2351
51
      break;
2352
0
    default:
2353
0
      llvm_unreachable("if this is an almost Doxygen comment, "
2354
69
                       "it should be ordinary");
2355
69
    }
2356
69
    Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
2357
69
      FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
2358
69
  }
2359
38.3M
  Context.addComment(RC);
2360
38.3M
}
2361
2362
// Pin this vtable to this file.
2363
14.2k
ExternalSemaSource::~ExternalSemaSource() {}
2364
char ExternalSemaSource::ID;
2365
2366
0
void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
2367
0
void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
2368
2369
void ExternalSemaSource::ReadKnownNamespaces(
2370
1
                           SmallVectorImpl<NamespaceDecl *> &Namespaces) {
2371
1
}
2372
2373
void ExternalSemaSource::ReadUndefinedButUsed(
2374
1
    llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
2375
2376
void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
2377
10
    FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
2378
2379
/// Figure out if an expression could be turned into a call.
2380
///
2381
/// Use this when trying to recover from an error where the programmer may have
2382
/// written just the name of a function instead of actually calling it.
2383
///
2384
/// \param E - The expression to examine.
2385
/// \param ZeroArgCallReturnTy - If the expression can be turned into a call
2386
///  with no arguments, this parameter is set to the type returned by such a
2387
///  call; otherwise, it is set to an empty QualType.
2388
/// \param OverloadSet - If the expression is an overloaded function
2389
///  name, this parameter is populated with the decls of the various overloads.
2390
bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
2391
343
                         UnresolvedSetImpl &OverloadSet) {
2392
343
  ZeroArgCallReturnTy = QualType();
2393
343
  OverloadSet.clear();
2394
2395
343
  const OverloadExpr *Overloads = nullptr;
2396
343
  bool IsMemExpr = false;
2397
343
  if (E.getType() == Context.OverloadTy) {
2398
100
    OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
2399
2400
    // Ignore overloads that are pointer-to-member constants.
2401
100
    if (FR.HasFormOfMemberPointer)
2402
19
      return false;
2403
2404
81
    Overloads = FR.Expression;
2405
243
  } else if (E.getType() == Context.BoundMemberTy) {
2406
78
    Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
2407
78
    IsMemExpr = true;
2408
78
  }
2409
2410
324
  bool Ambiguous = false;
2411
324
  bool IsMV = false;
2412
2413
324
  if (Overloads) {
2414
110
    for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
2415
290
         DeclsEnd = Overloads->decls_end(); it != DeclsEnd; 
++it180
) {
2416
180
      OverloadSet.addDecl(*it);
2417
2418
      // Check whether the function is a non-template, non-member which takes no
2419
      // arguments.
2420
180
      if (IsMemExpr)
2421
36
        continue;
2422
144
      if (const FunctionDecl *OverloadDecl
2423
144
            = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
2424
92
        if (OverloadDecl->getMinRequiredArguments() == 0) {
2425
43
          if (!ZeroArgCallReturnTy.isNull() && 
!Ambiguous4
&&
2426
43
              
(4
!IsMV4
||
!(2
OverloadDecl->isCPUDispatchMultiVersion()2
||
2427
2
                          OverloadDecl->isCPUSpecificMultiVersion()))) {
2428
2
            ZeroArgCallReturnTy = QualType();
2429
2
            Ambiguous = true;
2430
41
          } else {
2431
41
            ZeroArgCallReturnTy = OverloadDecl->getReturnType();
2432
41
            IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||
2433
41
                   OverloadDecl->isCPUSpecificMultiVersion();
2434
41
          }
2435
43
        }
2436
92
      }
2437
144
    }
2438
2439
    // If it's not a member, use better machinery to try to resolve the call
2440
110
    if (!IsMemExpr)
2441
81
      return !ZeroArgCallReturnTy.isNull();
2442
110
  }
2443
2444
  // Attempt to call the member with no arguments - this will correctly handle
2445
  // member templates with defaults/deduction of template arguments, overloads
2446
  // with default arguments, etc.
2447
243
  if (IsMemExpr && 
!E.isTypeDependent()78
) {
2448
75
    Sema::TentativeAnalysisScope Trap(*this);
2449
75
    ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
2450
75
                                             None, SourceLocation());
2451
75
    if (R.isUsable()) {
2452
56
      ZeroArgCallReturnTy = R.get()->getType();
2453
56
      return true;
2454
56
    }
2455
19
    return false;
2456
75
  }
2457
2458
168
  if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
2459
111
    if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
2460
90
      if (Fun->getMinRequiredArguments() == 0)
2461
74
        ZeroArgCallReturnTy = Fun->getReturnType();
2462
90
      return true;
2463
90
    }
2464
111
  }
2465
2466
  // We don't have an expression that's convenient to get a FunctionDecl from,
2467
  // but we can at least check if the type is "function of 0 arguments".
2468
78
  QualType ExprTy = E.getType();
2469
78
  const FunctionType *FunTy = nullptr;
2470
78
  QualType PointeeTy = ExprTy->getPointeeType();
2471
78
  if (!PointeeTy.isNull())
2472
23
    FunTy = PointeeTy->getAs<FunctionType>();
2473
78
  if (!FunTy)
2474
78
    FunTy = ExprTy->getAs<FunctionType>();
2475
2476
78
  if (const FunctionProtoType *FPT =
2477
78
      dyn_cast_or_null<FunctionProtoType>(FunTy)) {
2478
6
    if (FPT->getNumParams() == 0)
2479
0
      ZeroArgCallReturnTy = FunTy->getReturnType();
2480
6
    return true;
2481
6
  }
2482
72
  return false;
2483
78
}
2484
2485
/// Give notes for a set of overloads.
2486
///
2487
/// A companion to tryExprAsCall. In cases when the name that the programmer
2488
/// wrote was an overloaded function, we may be able to make some guesses about
2489
/// plausible overloads based on their return types; such guesses can be handed
2490
/// off to this method to be emitted as notes.
2491
///
2492
/// \param Overloads - The overloads to note.
2493
/// \param FinalNoteLoc - If we've suppressed printing some overloads due to
2494
///  -fshow-overloads=best, this is the location to attach to the note about too
2495
///  many candidates. Typically this will be the location of the original
2496
///  ill-formed expression.
2497
static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
2498
211
                          const SourceLocation FinalNoteLoc) {
2499
211
  unsigned ShownOverloads = 0;
2500
211
  unsigned SuppressedOverloads = 0;
2501
211
  for (UnresolvedSetImpl::iterator It = Overloads.begin(),
2502
385
       DeclsEnd = Overloads.end(); It != DeclsEnd; 
++It174
) {
2503
174
    if (ShownOverloads >= S.Diags.getNumOverloadCandidatesToShow()) {
2504
0
      ++SuppressedOverloads;
2505
0
      continue;
2506
0
    }
2507
2508
174
    NamedDecl *Fn = (*It)->getUnderlyingDecl();
2509
    // Don't print overloads for non-default multiversioned functions.
2510
174
    if (const auto *FD = Fn->getAsFunction()) {
2511
174
      if (FD->isMultiVersion() && 
FD->hasAttr<TargetAttr>()2
&&
2512
174
          
!FD->getAttr<TargetAttr>()->isDefaultVersion()2
)
2513
1
        continue;
2514
174
    }
2515
173
    S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
2516
173
    ++ShownOverloads;
2517
173
  }
2518
2519
211
  S.Diags.overloadCandidatesShown(ShownOverloads);
2520
2521
211
  if (SuppressedOverloads)
2522
0
    S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
2523
0
      << SuppressedOverloads;
2524
211
}
2525
2526
static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
2527
                                   const UnresolvedSetImpl &Overloads,
2528
211
                                   bool (*IsPlausibleResult)(QualType)) {
2529
211
  if (!IsPlausibleResult)
2530
200
    return noteOverloads(S, Overloads, Loc);
2531
2532
11
  UnresolvedSet<2> PlausibleOverloads;
2533
11
  for (OverloadExpr::decls_iterator It = Overloads.begin(),
2534
11
         DeclsEnd = Overloads.end(); It != DeclsEnd; 
++It0
) {
2535
0
    const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
2536
0
    QualType OverloadResultTy = OverloadDecl->getReturnType();
2537
0
    if (IsPlausibleResult(OverloadResultTy))
2538
0
      PlausibleOverloads.addDecl(It.getDecl());
2539
0
  }
2540
11
  noteOverloads(S, PlausibleOverloads, Loc);
2541
11
}
2542
2543
/// Determine whether the given expression can be called by just
2544
/// putting parentheses after it.  Notably, expressions with unary
2545
/// operators can't be because the unary operator will start parsing
2546
/// outside the call.
2547
104
static bool IsCallableWithAppend(Expr *E) {
2548
104
  E = E->IgnoreImplicit();
2549
104
  return (!isa<CStyleCastExpr>(E) &&
2550
104
          !isa<UnaryOperator>(E) &&
2551
104
          
!isa<BinaryOperator>(E)101
&&
2552
104
          
!isa<CXXOperatorCallExpr>(E)95
);
2553
104
}
2554
2555
217
static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E) {
2556
217
  if (const auto *UO = dyn_cast<UnaryOperator>(E))
2557
25
    E = UO->getSubExpr();
2558
2559
217
  if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2560
81
    if (ULE->getNumDecls() == 0)
2561
1
      return false;
2562
2563
80
    const NamedDecl *ND = *ULE->decls_begin();
2564
80
    if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2565
50
      return FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion();
2566
80
  }
2567
166
  return false;
2568
217
}
2569
2570
bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
2571
                                bool ForceComplain,
2572
317
                                bool (*IsPlausibleResult)(QualType)) {
2573
317
  SourceLocation Loc = E.get()->getExprLoc();
2574
317
  SourceRange Range = E.get()->getSourceRange();
2575
317
  UnresolvedSet<4> Overloads;
2576
2577
  // If this is a SFINAE context, don't try anything that might trigger ADL
2578
  // prematurely.
2579
317
  if (!isSFINAEContext()) {
2580
258
    QualType ZeroArgCallTy;
2581
258
    if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
2582
258
        
!ZeroArgCallTy.isNull()104
&&
2583
258
        
(104
!IsPlausibleResult104
||
IsPlausibleResult(ZeroArgCallTy)11
)) {
2584
      // At this point, we know E is potentially callable with 0
2585
      // arguments and that it returns something of a reasonable type,
2586
      // so we can emit a fixit and carry on pretending that E was
2587
      // actually a CallExpr.
2588
104
      SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
2589
104
      bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
2590
104
      Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range
2591
104
                    << (IsCallableWithAppend(E.get())
2592
104
                            ? FixItHint::CreateInsertion(ParenInsertionLoc,
2593
95
                                                         "()")
2594
104
                            : 
FixItHint()9
);
2595
104
      if (!IsMV)
2596
100
        notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2597
2598
      // FIXME: Try this before emitting the fixit, and suppress diagnostics
2599
      // while doing so.
2600
104
      E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), None,
2601
104
                        Range.getEnd().getLocWithOffset(1));
2602
104
      return true;
2603
104
    }
2604
258
  }
2605
213
  if (!ForceComplain) 
return false100
;
2606
2607
113
  bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
2608
113
  Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;
2609
113
  if (!IsMV)
2610
111
    notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2611
113
  E = ExprError();
2612
113
  return true;
2613
213
}
2614
2615
79
IdentifierInfo *Sema::getSuperIdentifier() const {
2616
79
  if (!Ident_super)
2617
34
    Ident_super = &Context.Idents.get("super");
2618
79
  return Ident_super;
2619
79
}
2620
2621
0
IdentifierInfo *Sema::getFloat128Identifier() const {
2622
0
  if (!Ident___float128)
2623
0
    Ident___float128 = &Context.Idents.get("__float128");
2624
0
  return Ident___float128;
2625
0
}
2626
2627
void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
2628
                                   CapturedRegionKind K,
2629
616k
                                   unsigned OpenMPCaptureLevel) {
2630
616k
  auto *CSI = new CapturedRegionScopeInfo(
2631
616k
      getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
2632
616k
      (getLangOpts().OpenMP && 
K == CR_OpenMP616k
) ?
getOpenMPNestingLevel()616k
:
0260
,
2633
616k
      OpenMPCaptureLevel);
2634
616k
  CSI->ReturnType = Context.VoidTy;
2635
616k
  FunctionScopes.push_back(CSI);
2636
616k
}
2637
2638
581k
CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
2639
581k
  if (FunctionScopes.empty())
2640
653
    return nullptr;
2641
2642
581k
  return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
2643
581k
}
2644
2645
const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
2646
3.47k
Sema::getMismatchingDeleteExpressions() const {
2647
3.47k
  return DeleteExprs;
2648
3.47k
}
2649
2650
Sema::FPFeaturesStateRAII::FPFeaturesStateRAII(Sema &S)
2651
    : S(S), OldFPFeaturesState(S.CurFPFeatures),
2652
      OldOverrides(S.FpPragmaStack.CurrentValue),
2653
      OldEvalMethod(S.PP.getCurrentFPEvalMethod()),
2654
5.94M
      OldFPPragmaLocation(S.PP.getLastFPEvalPragmaLocation()) {}
2655
2656
5.94M
Sema::FPFeaturesStateRAII::~FPFeaturesStateRAII() {
2657
5.94M
  S.CurFPFeatures = OldFPFeaturesState;
2658
5.94M
  S.FpPragmaStack.CurrentValue = OldOverrides;
2659
5.94M
  S.PP.setCurrentFPEvalMethod(OldFPPragmaLocation, OldEvalMethod);
2660
5.94M
}