Coverage Report

Created: 2022-01-18 06:27

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