Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/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 "clang/AST/ASTContext.h"
15
#include "clang/AST/ASTDiagnostic.h"
16
#include "clang/AST/DeclCXX.h"
17
#include "clang/AST/DeclFriend.h"
18
#include "clang/AST/DeclObjC.h"
19
#include "clang/AST/Expr.h"
20
#include "clang/AST/ExprCXX.h"
21
#include "clang/AST/PrettyDeclStackTrace.h"
22
#include "clang/AST/StmtCXX.h"
23
#include "clang/Basic/DiagnosticOptions.h"
24
#include "clang/Basic/PartialDiagnostic.h"
25
#include "clang/Basic/TargetInfo.h"
26
#include "clang/Lex/HeaderSearch.h"
27
#include "clang/Lex/Preprocessor.h"
28
#include "clang/Sema/CXXFieldCollector.h"
29
#include "clang/Sema/DelayedDiagnostic.h"
30
#include "clang/Sema/ExternalSemaSource.h"
31
#include "clang/Sema/Initialization.h"
32
#include "clang/Sema/MultiplexExternalSemaSource.h"
33
#include "clang/Sema/ObjCMethodList.h"
34
#include "clang/Sema/Scope.h"
35
#include "clang/Sema/ScopeInfo.h"
36
#include "clang/Sema/SemaConsumer.h"
37
#include "clang/Sema/SemaInternal.h"
38
#include "clang/Sema/TemplateDeduction.h"
39
#include "clang/Sema/TemplateInstCallback.h"
40
#include "llvm/ADT/DenseMap.h"
41
#include "llvm/ADT/SmallSet.h"
42
#include "llvm/Support/TimeProfiler.h"
43
44
using namespace clang;
45
using namespace sema;
46
47
680k
SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
48
680k
  return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
49
680k
}
50
51
5.27k
ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
52
53
PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
54
34.7M
                                       const Preprocessor &PP) {
55
34.7M
  PrintingPolicy Policy = Context.getPrintingPolicy();
56
34.7M
  // In diagnostics, we print _Bool as bool if the latter is defined as the
57
34.7M
  // former.
58
34.7M
  Policy.Bool = Context.getLangOpts().Bool;
59
34.7M
  if (!Policy.Bool) {
60
11.5M
    if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
61
844k
      Policy.Bool = BoolMacro->isObjectLike() &&
62
844k
                    
BoolMacro->getNumTokens() == 1764k
&&
63
844k
                    
BoolMacro->getReplacementToken(0).is(tok::kw__Bool)764k
;
64
844k
    }
65
11.5M
  }
66
34.7M
67
34.7M
  return Policy;
68
34.7M
}
69
70
41.4k
void Sema::ActOnTranslationUnitScope(Scope *S) {
71
41.4k
  TUScope = S;
72
41.4k
  PushDeclContext(S, Context.getTranslationUnitDecl());
73
41.4k
}
74
75
namespace clang {
76
namespace sema {
77
78
class SemaPPCallbacks : public PPCallbacks {
79
  Sema *S = nullptr;
80
  llvm::SmallVector<SourceLocation, 8> IncludeStack;
81
82
public:
83
41.5k
  void set(Sema &S) { this->S = &S; }
84
85
32.9k
  void reset() { S = nullptr; }
86
87
  virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
88
                           SrcMgr::CharacteristicKind FileType,
89
1.22M
                           FileID PrevFID) override {
90
1.22M
    if (!S)
91
0
      return;
92
1.22M
    switch (Reason) {
93
1.22M
    case EnterFile: {
94
599k
      SourceManager &SM = S->getSourceManager();
95
599k
      SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc));
96
599k
      if (IncludeLoc.isValid()) {
97
477k
        if (llvm::timeTraceProfilerEnabled()) {
98
0
          const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc));
99
0
          llvm::timeTraceProfilerBegin(
100
0
              "Source", FE != nullptr ? FE->getName() : StringRef("<unknown>"));
101
0
        }
102
477k
103
477k
        IncludeStack.push_back(IncludeLoc);
104
477k
        S->DiagnoseNonDefaultPragmaPack(
105
477k
            Sema::PragmaPackDiagnoseKind::NonDefaultStateAtInclude, IncludeLoc);
106
477k
      }
107
599k
      break;
108
1.22M
    }
109
1.22M
    case ExitFile:
110
557k
      if (!IncludeStack.empty()) {
111
477k
        if (llvm::timeTraceProfilerEnabled())
112
0
          llvm::timeTraceProfilerEnd();
113
477k
114
477k
        S->DiagnoseNonDefaultPragmaPack(
115
477k
            Sema::PragmaPackDiagnoseKind::ChangedStateAtExit,
116
477k
            IncludeStack.pop_back_val());
117
477k
      }
118
557k
      break;
119
1.22M
    default:
120
69.5k
      break;
121
1.22M
    }
122
1.22M
  }
123
};
124
125
} // end namespace sema
126
} // end namespace clang
127
128
Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
129
           TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
130
    : ExternalSource(nullptr), isMultiplexExternalSource(false),
131
      FPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp),
132
      Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
133
      SourceMgr(PP.getSourceManager()), CollectStats(false),
134
      CodeCompleter(CodeCompleter), CurContext(nullptr),
135
      OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
136
      MSPointerToMemberRepresentationMethod(
137
          LangOpts.getMSPointerToMemberRepresentationMethod()),
138
      VtorDispStack(MSVtorDispAttr::Mode(LangOpts.VtorDispMode)), PackStack(0),
139
      DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
140
      CodeSegStack(nullptr), CurInitSeg(nullptr), VisContext(nullptr),
141
      PragmaAttributeCurrentTargetDecl(nullptr),
142
      IsBuildingRecoveryCallExpr(false), Cleanup{}, LateTemplateParser(nullptr),
143
      LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
144
      StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr),
145
      StdCoroutineTraitsCache(nullptr), CXXTypeInfoDecl(nullptr),
146
      MSVCGuidDecl(nullptr), NSNumberDecl(nullptr), NSValueDecl(nullptr),
147
      NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr),
148
      ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
149
      ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
150
      DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
151
      TUKind(TUKind), NumSFINAEErrors(0),
152
      FullyCheckedComparisonCategories(
153
          static_cast<unsigned>(ComparisonCategoryType::Last) + 1),
154
      AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
155
      NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
156
      CurrentInstantiationScope(nullptr), DisableTypoCorrection(false),
157
      TyposCorrected(0), AnalysisWarnings(*this),
158
      ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
159
41.5k
      CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) {
160
41.5k
  TUScope = nullptr;
161
41.5k
  isConstantEvaluatedOverride = false;
162
41.5k
163
41.5k
  LoadedExternalKnownNamespaces = false;
164
665k
  for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; 
++I623k
)
165
623k
    NSNumberLiteralMethods[I] = nullptr;
166
41.5k
167
41.5k
  if (getLangOpts().ObjC)
168
4.88k
    NSAPIObj.reset(new NSAPI(Context));
169
41.5k
170
41.5k
  if (getLangOpts().CPlusPlus)
171
26.0k
    FieldCollector.reset(new CXXFieldCollector());
172
41.5k
173
41.5k
  // Tell diagnostics how to render things from the AST library.
174
41.5k
  Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
175
41.5k
176
41.5k
  ExprEvalContexts.emplace_back(
177
41.5k
      ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
178
41.5k
      nullptr, ExpressionEvaluationContextRecord::EK_Other);
179
41.5k
180
41.5k
  // Initialization of data sharing attributes stack for OpenMP
181
41.5k
  InitDataSharingAttributesStack();
182
41.5k
183
41.5k
  std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
184
41.5k
      llvm::make_unique<sema::SemaPPCallbacks>();
185
41.5k
  SemaPPCallbackHandler = Callbacks.get();
186
41.5k
  PP.addPPCallbacks(std::move(Callbacks));
187
41.5k
  SemaPPCallbackHandler->set(*this);
188
41.5k
}
189
190
12.0k
void Sema::addImplicitTypedef(StringRef Name, QualType T) {
191
12.0k
  DeclarationName DN = &Context.Idents.get(Name);
192
12.0k
  if (IdResolver.begin(DN) == IdResolver.end())
193
11.9k
    PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
194
12.0k
}
195
196
41.5k
void Sema::Initialize() {
197
41.5k
  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
198
5.62k
    SC->InitializeSema(*this);
199
41.5k
200
41.5k
  // Tell the external Sema source about this Sema object.
201
41.5k
  if (ExternalSemaSource *ExternalSema
202
5.23k
      = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
203
5.23k
    ExternalSema->InitializeSema(*this);
204
41.5k
205
41.5k
  // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
206
41.5k
  // will not be able to merge any duplicate __va_list_tag decls correctly.
207
41.5k
  VAListTagName = PP.getIdentifierInfo("__va_list_tag");
208
41.5k
209
41.5k
  if (!TUScope)
210
116
    return;
211
41.4k
212
41.4k
  // Initialize predefined 128-bit integer types, if needed.
213
41.4k
  if (Context.getTargetInfo().hasInt128Type()) {
214
32.5k
    // If either of the 128-bit integer types are unavailable to name lookup,
215
32.5k
    // define them now.
216
32.5k
    DeclarationName Int128 = &Context.Idents.get("__int128_t");
217
32.5k
    if (IdResolver.begin(Int128) == IdResolver.end())
218
30.7k
      PushOnScopeChains(Context.getInt128Decl(), TUScope);
219
32.5k
220
32.5k
    DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
221
32.5k
    if (IdResolver.begin(UInt128) == IdResolver.end())
222
30.7k
      PushOnScopeChains(Context.getUInt128Decl(), TUScope);
223
32.5k
  }
224
41.4k
225
41.4k
226
41.4k
  // Initialize predefined Objective-C types:
227
41.4k
  if (getLangOpts().ObjC) {
228
4.85k
    // If 'SEL' does not yet refer to any declarations, make it refer to the
229
4.85k
    // predefined 'SEL'.
230
4.85k
    DeclarationName SEL = &Context.Idents.get("SEL");
231
4.85k
    if (IdResolver.begin(SEL) == IdResolver.end())
232
4.66k
      PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
233
4.85k
234
4.85k
    // If 'id' does not yet refer to any declarations, make it refer to the
235
4.85k
    // predefined 'id'.
236
4.85k
    DeclarationName Id = &Context.Idents.get("id");
237
4.85k
    if (IdResolver.begin(Id) == IdResolver.end())
238
4.66k
      PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
239
4.85k
240
4.85k
    // Create the built-in typedef for 'Class'.
241
4.85k
    DeclarationName Class = &Context.Idents.get("Class");
242
4.85k
    if (IdResolver.begin(Class) == IdResolver.end())
243
4.66k
      PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
244
4.85k
245
4.85k
    // Create the built-in forward declaratino for 'Protocol'.
246
4.85k
    DeclarationName Protocol = &Context.Idents.get("Protocol");
247
4.85k
    if (IdResolver.begin(Protocol) == IdResolver.end())
248
4.66k
      PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
249
4.85k
  }
250
41.4k
251
41.4k
  // Create the internal type for the *StringMakeConstantString builtins.
252
41.4k
  DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
253
41.4k
  if (IdResolver.begin(ConstantString) == IdResolver.end())
254
39.0k
    PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
255
41.4k
256
41.4k
  // Initialize Microsoft "predefined C++ types".
257
41.4k
  if (getLangOpts().MSVCCompat) {
258
1.68k
    if (getLangOpts().CPlusPlus &&
259
1.68k
        
IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end()1.47k
)
260
1.46k
      PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
261
1.46k
                        TUScope);
262
1.68k
263
1.68k
    addImplicitTypedef("size_t", Context.getSizeType());
264
1.68k
  }
265
41.4k
266
41.4k
  // Initialize predefined OpenCL types and supported extensions and (optional)
267
41.4k
  // core features.
268
41.4k
  if (getLangOpts().OpenCL) {
269
535
    getOpenCLOptions().addSupport(
270
535
        Context.getTargetInfo().getSupportedOpenCLOpts());
271
535
    getOpenCLOptions().enableSupportedCore(getLangOpts());
272
535
    addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
273
535
    addImplicitTypedef("event_t", Context.OCLEventTy);
274
535
    if (getLangOpts().OpenCLCPlusPlus || 
getLangOpts().OpenCLVersion >= 200481
) {
275
204
      addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
276
204
      addImplicitTypedef("queue_t", Context.OCLQueueTy);
277
204
      addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
278
204
      addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
279
204
      addImplicitTypedef("atomic_uint",
280
204
                         Context.getAtomicType(Context.UnsignedIntTy));
281
204
      auto AtomicLongT = Context.getAtomicType(Context.LongTy);
282
204
      addImplicitTypedef("atomic_long", AtomicLongT);
283
204
      auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
284
204
      addImplicitTypedef("atomic_ulong", AtomicULongT);
285
204
      addImplicitTypedef("atomic_float",
286
204
                         Context.getAtomicType(Context.FloatTy));
287
204
      auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
288
204
      addImplicitTypedef("atomic_double", AtomicDoubleT);
289
204
      // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
290
204
      // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
291
204
      addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
292
204
      auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
293
204
      addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
294
204
      auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
295
204
      addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
296
204
      auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
297
204
      addImplicitTypedef("atomic_size_t", AtomicSizeT);
298
204
      auto AtomicPtrDiffT = Context.getAtomicType(Context.getPointerDiffType());
299
204
      addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
300
204
301
204
      // OpenCL v2.0 s6.13.11.6:
302
204
      // - The atomic_long and atomic_ulong types are supported if the
303
204
      //   cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
304
204
      //   extensions are supported.
305
204
      // - The atomic_double type is only supported if double precision
306
204
      //   is supported and the cl_khr_int64_base_atomics and
307
204
      //   cl_khr_int64_extended_atomics extensions are supported.
308
204
      // - If the device address space is 64-bits, the data types
309
204
      //   atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
310
204
      //   atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
311
204
      //   cl_khr_int64_extended_atomics extensions are supported.
312
204
      std::vector<QualType> Atomic64BitTypes;
313
204
      Atomic64BitTypes.push_back(AtomicLongT);
314
204
      Atomic64BitTypes.push_back(AtomicULongT);
315
204
      Atomic64BitTypes.push_back(AtomicDoubleT);
316
204
      if (Context.getTypeSize(AtomicSizeT) == 64) {
317
128
        Atomic64BitTypes.push_back(AtomicSizeT);
318
128
        Atomic64BitTypes.push_back(AtomicIntPtrT);
319
128
        Atomic64BitTypes.push_back(AtomicUIntPtrT);
320
128
        Atomic64BitTypes.push_back(AtomicPtrDiffT);
321
128
      }
322
204
      for (auto &I : Atomic64BitTypes)
323
1.12k
        setOpenCLExtensionForType(I,
324
1.12k
            "cl_khr_int64_base_atomics cl_khr_int64_extended_atomics");
325
204
326
204
      setOpenCLExtensionForType(AtomicDoubleT, "cl_khr_fp64");
327
204
    }
328
535
329
535
    setOpenCLExtensionForType(Context.DoubleTy, "cl_khr_fp64");
330
535
331
535
#define GENERIC_IMAGE_TYPE_EXT(Type, Id, Ext) \
332
19.2k
    setOpenCLExtensionForType(Context.Id, Ext);
333
535
#include "clang/Basic/OpenCLImageTypes.def"
334
535
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
335
6.42k
    addImplicitTypedef(#ExtType, Context.Id##Ty); \
336
6.42k
    setOpenCLExtensionForType(Context.Id##Ty, #Ext);
337
535
#include "clang/Basic/OpenCLExtensionTypes.def"
338
535
    };
339
41.4k
340
41.4k
  if (Context.getTargetInfo().hasBuiltinMSVaList()) {
341
29.6k
    DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
342
29.6k
    if (IdResolver.begin(MSVaList) == IdResolver.end())
343
28.5k
      PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
344
29.6k
  }
345
41.4k
346
41.4k
  DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
347
41.4k
  if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
348
39.0k
    PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
349
41.4k
}
350
351
32.9k
Sema::~Sema() {
352
32.9k
  if (VisContext) 
FreeVisContext()4
;
353
32.9k
354
32.9k
  // Kill all the active scopes.
355
32.9k
  for (sema::FunctionScopeInfo *FSI : FunctionScopes)
356
0
    delete FSI;
357
32.9k
358
32.9k
  // Tell the SemaConsumer to forget about us; we're going out of scope.
359
32.9k
  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
360
5.59k
    SC->ForgetSema();
361
32.9k
362
32.9k
  // Detach from the external Sema source.
363
32.9k
  if (ExternalSemaSource *ExternalSema
364
5.17k
        = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
365
5.17k
    ExternalSema->ForgetSema();
366
32.9k
367
32.9k
  // If Sema's ExternalSource is the multiplexer - we own it.
368
32.9k
  if (isMultiplexExternalSource)
369
111
    delete ExternalSource;
370
32.9k
371
32.9k
  threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
372
32.9k
373
32.9k
  // Destroys data sharing attributes stack for OpenMP
374
32.9k
  DestroyDataSharingAttributesStack();
375
32.9k
376
32.9k
  // Detach from the PP callback handler which outlives Sema since it's owned
377
32.9k
  // by the preprocessor.
378
32.9k
  SemaPPCallbackHandler->reset();
379
32.9k
380
32.9k
  assert(DelayedTypos.empty() && "Uncorrected typos!");
381
32.9k
}
382
383
/// makeUnavailableInSystemHeader - There is an error in the current
384
/// context.  If we're still in a system header, and we can plausibly
385
/// make the relevant declaration unavailable instead of erroring, do
386
/// so and return true.
387
bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
388
331
                                      UnavailableAttr::ImplicitReason reason) {
389
331
  // If we're not in a function, it's an error.
390
331
  FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
391
331
  if (!fn) 
return false24
;
392
307
393
307
  // If we're in template instantiation, it's an error.
394
307
  if (inTemplateInstantiation())
395
0
    return false;
396
307
397
307
  // If that function's not in a system header, it's an error.
398
307
  if (!Context.getSourceManager().isInSystemHeader(loc))
399
303
    return false;
400
4
401
4
  // If the function is already unavailable, it's not an error.
402
4
  if (fn->hasAttr<UnavailableAttr>()) 
return true0
;
403
4
404
4
  fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
405
4
  return true;
406
4
}
407
408
1.08M
ASTMutationListener *Sema::getASTMutationListener() const {
409
1.08M
  return getASTConsumer().GetASTMutationListener();
410
1.08M
}
411
412
///Registers an external source. If an external source already exists,
413
/// creates a multiplex external source and appends to it.
414
///
415
///\param[in] E - A non-null external sema source.
416
///
417
5.37k
void Sema::addExternalSource(ExternalSemaSource *E) {
418
5.37k
  assert(E && "Cannot use with NULL ptr");
419
5.37k
420
5.37k
  if (!ExternalSource) {
421
5.25k
    ExternalSource = E;
422
5.25k
    return;
423
5.25k
  }
424
120
425
120
  if (isMultiplexExternalSource)
426
2
    static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
427
118
  else {
428
118
    ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
429
118
    isMultiplexExternalSource = true;
430
118
  }
431
120
}
432
433
/// Print out statistics about the semantic analysis.
434
3
void Sema::PrintStats() const {
435
3
  llvm::errs() << "\n*** Semantic Analysis Stats:\n";
436
3
  llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
437
3
438
3
  BumpAlloc.PrintStats();
439
3
  AnalysisWarnings.PrintStats();
440
3
}
441
442
void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
443
                                               QualType SrcType,
444
24.4M
                                               SourceLocation Loc) {
445
24.4M
  Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context);
446
24.4M
  if (!ExprNullability || 
*ExprNullability != NullabilityKind::Nullable1.19k
)
447
24.4M
    return;
448
512
449
512
  Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context);
450
512
  if (!TypeNullability || 
*TypeNullability != NullabilityKind::NonNull131
)
451
446
    return;
452
66
453
66
  Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
454
66
}
455
456
12.5M
void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr* E) {
457
12.5M
  if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
458
12.5M
                      E->getBeginLoc()))
459
12.5M
    return;
460
704
  // nullptr only exists from C++11 on, so don't warn on its absence earlier.
461
704
  if (!getLangOpts().CPlusPlus11)
462
307
    return;
463
397
464
397
  if (Kind != CK_NullToPointer && 
Kind != CK_NullToMemberPointer337
)
465
331
    return;
466
66
  if (E->IgnoreParenImpCasts()->getType()->isNullPtrType())
467
18
    return;
468
48
469
48
  // If it is a macro from system header, and if the macro name is not "NULL",
470
48
  // do not warn.
471
48
  SourceLocation MaybeMacroLoc = E->getBeginLoc();
472
48
  if (Diags.getSuppressSystemWarnings() &&
473
48
      
SourceMgr.isInSystemMacro(MaybeMacroLoc)24
&&
474
48
      
!findMacroSpelling(MaybeMacroLoc, "NULL")3
)
475
2
    return;
476
46
477
46
  Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant)
478
46
      << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");
479
46
}
480
481
/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
482
/// If there is already an implicit cast, merge into the existing one.
483
/// The result is of the given category.
484
ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
485
                                   CastKind Kind, ExprValueKind VK,
486
                                   const CXXCastPath *BasePath,
487
12.5M
                                   CheckedConversionKind CCK) {
488
#ifndef NDEBUG
489
  if (VK == VK_RValue && !E->isRValue()) {
490
    switch (Kind) {
491
    default:
492
      llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast "
493
                       "kind");
494
    case CK_Dependent:
495
    case CK_LValueToRValue:
496
    case CK_ArrayToPointerDecay:
497
    case CK_FunctionToPointerDecay:
498
    case CK_ToVoid:
499
    case CK_NonAtomicToAtomic:
500
      break;
501
    }
502
  }
503
  assert((VK == VK_RValue || Kind == CK_Dependent || !E->isRValue()) &&
504
         "can't cast rvalue to lvalue");
505
#endif
506
507
12.5M
  diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getBeginLoc());
508
12.5M
  diagnoseZeroToNullptrConversion(Kind, E);
509
12.5M
510
12.5M
  QualType ExprTy = Context.getCanonicalType(E->getType());
511
12.5M
  QualType TypeTy = Context.getCanonicalType(Ty);
512
12.5M
513
12.5M
  if (ExprTy == TypeTy)
514
2.75M
    return E;
515
9.83M
516
9.83M
  // C++1z [conv.array]: The temporary materialization conversion is applied.
517
9.83M
  // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
518
9.83M
  if (Kind == CK_ArrayToPointerDecay && 
getLangOpts().CPlusPlus812k
&&
519
9.83M
      
E->getValueKind() == VK_RValue551k
) {
520
44
    // The temporary is an lvalue in C++98 and an xvalue otherwise.
521
44
    ExprResult Materialized = CreateMaterializeTemporaryExpr(
522
44
        E->getType(), E, !getLangOpts().CPlusPlus11);
523
44
    if (Materialized.isInvalid())
524
0
      return ExprError();
525
44
    E = Materialized.get();
526
44
  }
527
9.83M
528
9.83M
  if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
529
959k
    if (ImpCast->getCastKind() == Kind && 
(27.9k
!BasePath27.9k
||
BasePath->empty()1.09k
)) {
530
27.6k
      ImpCast->setType(Ty);
531
27.6k
      ImpCast->setValueKind(VK);
532
27.6k
      return E;
533
27.6k
    }
534
9.80M
  }
535
9.80M
536
9.80M
  return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK);
537
9.80M
}
538
539
/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
540
/// to the conversion from scalar type ScalarTy to the Boolean type.
541
963k
CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
542
963k
  switch (ScalarTy->getScalarTypeKind()) {
543
963k
  
case Type::STK_Bool: return CK_NoOp650k
;
544
963k
  
case Type::STK_CPointer: return CK_PointerToBoolean39.6k
;
545
963k
  
case Type::STK_BlockPointer: return CK_PointerToBoolean20
;
546
963k
  
case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean139
;
547
963k
  
case Type::STK_MemberPointer: return CK_MemberPointerToBoolean416
;
548
963k
  
case Type::STK_Integral: return CK_IntegralToBoolean272k
;
549
963k
  
case Type::STK_Floating: return CK_FloatingToBoolean739
;
550
963k
  
case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean12
;
551
963k
  
case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean1
;
552
963k
  
case Type::STK_FixedPoint: return CK_FixedPointToBoolean0
;
553
0
  }
554
0
  llvm_unreachable("unknown scalar type kind");
555
0
}
556
557
/// Used to prune the decls of Sema's UnusedFileScopedDecls vector.
558
36.9k
static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
559
36.9k
  if (D->getMostRecentDecl()->isUsed())
560
22.4k
    return true;
561
14.5k
562
14.5k
  if (D->isExternallyVisible())
563
39
    return true;
564
14.4k
565
14.4k
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
566
10.0k
    // If this is a function template and none of its specializations is used,
567
10.0k
    // we should warn.
568
10.0k
    if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
569
1.41k
      for (const auto *Spec : Template->specializations())
570
407
        if (ShouldRemoveFromUnused(SemaRef, Spec))
571
395
          return true;
572
10.0k
573
10.0k
    // UnusedFileScopedDecls stores the first declaration.
574
10.0k
    // The declaration may have become definition so check again.
575
10.0k
    const FunctionDecl *DeclToCheck;
576
9.69k
    if (FD->hasBody(DeclToCheck))
577
9.18k
      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
578
511
579
511
    // Later redecls may add new information resulting in not having to warn,
580
511
    // so check again.
581
511
    DeclToCheck = FD->getMostRecentDecl();
582
511
    if (DeclToCheck != FD)
583
46
      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
584
4.84k
  }
585
4.84k
586
4.84k
  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
587
4.38k
    // If a variable usable in constant expressions is referenced,
588
4.38k
    // don't warn if it isn't used: if the value of a variable is required
589
4.38k
    // for the computation of a constant expression, it doesn't make sense to
590
4.38k
    // warn even if the variable isn't odr-used.  (isReferenced doesn't
591
4.38k
    // precisely reflect that, but it's a decent approximation.)
592
4.38k
    if (VD->isReferenced() &&
593
4.38k
        
VD->mightBeUsableInConstantExpressions(SemaRef->Context)1.52k
)
594
1.47k
      return true;
595
2.91k
596
2.91k
    if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
597
15
      // If this is a variable template and none of its specializations is used,
598
15
      // we should warn.
599
15
      for (const auto *Spec : Template->specializations())
600
12
        if (ShouldRemoveFromUnused(SemaRef, Spec))
601
8
          return true;
602
2.91k
603
2.91k
    // UnusedFileScopedDecls stores the first declaration.
604
2.91k
    // The declaration may have become definition so check again.
605
2.91k
    const VarDecl *DeclToCheck = VD->getDefinition();
606
2.90k
    if (DeclToCheck)
607
2.43k
      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
608
464
609
464
    // Later redecls may add new information resulting in not having to warn,
610
464
    // so check again.
611
464
    DeclToCheck = VD->getMostRecentDecl();
612
464
    if (DeclToCheck != VD)
613
27
      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
614
902
  }
615
902
616
902
  return false;
617
902
}
618
619
125
static bool isFunctionOrVarDeclExternC(NamedDecl *ND) {
620
125
  if (auto *FD = dyn_cast<FunctionDecl>(ND))
621
94
    return FD->isExternC();
622
31
  return cast<VarDecl>(ND)->isExternC();
623
31
}
624
625
/// Determine whether ND is an external-linkage function or variable whose
626
/// type has no linkage.
627
852k
bool Sema::isExternalWithNoLinkageType(ValueDecl *VD) {
628
852k
  // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
629
852k
  // because we also want to catch the case where its type has VisibleNoLinkage,
630
852k
  // which does not affect the linkage of VD.
631
852k
  return getLangOpts().CPlusPlus && 
VD->hasExternalFormalLinkage()443k
&&
632
852k
         
!isExternalFormalLinkage(VD->getType()->getLinkage())443k
&&
633
852k
         
!isFunctionOrVarDeclExternC(VD)125
;
634
852k
}
635
636
/// Obtains a sorted list of functions and variables that are undefined but
637
/// ODR-used.
638
void Sema::getUndefinedButUsed(
639
7.58k
    SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
640
223k
  for (const auto &UndefinedUse : UndefinedButUsed) {
641
223k
    NamedDecl *ND = UndefinedUse.first;
642
223k
643
223k
    // Ignore attributes that have become invalid.
644
223k
    if (ND->isInvalidDecl()) 
continue0
;
645
223k
646
223k
    // __attribute__((weakref)) is basically a definition.
647
223k
    if (ND->hasAttr<WeakRefAttr>()) 
continue0
;
648
223k
649
223k
    if (isa<CXXDeductionGuideDecl>(ND))
650
4
      continue;
651
223k
652
223k
    if (ND->hasAttr<DLLImportAttr>() || 
ND->hasAttr<DLLExportAttr>()223k
) {
653
241
      // An exported function will always be emitted when defined, so even if
654
241
      // the function is inline, it doesn't have to be emitted in this TU. An
655
241
      // imported function implies that it has been exported somewhere else.
656
241
      continue;
657
241
    }
658
223k
659
223k
    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
660
223k
      if (FD->isDefined())
661
221k
        continue;
662
1.94k
      if (FD->isExternallyVisible() &&
663
1.94k
          
!isExternalWithNoLinkageType(FD)1.68k
&&
664
1.94k
          
!FD->getMostRecentDecl()->isInlined()1.67k
&&
665
1.94k
          
!FD->hasAttr<ExcludeFromExplicitInstantiationAttr>()6
)
666
6
        continue;
667
1.93k
      if (FD->getBuiltinID())
668
52
        continue;
669
49
    } else {
670
49
      auto *VD = cast<VarDecl>(ND);
671
49
      if (VD->hasDefinition() != VarDecl::DeclarationOnly)
672
30
        continue;
673
19
      if (VD->isExternallyVisible() &&
674
19
          
!isExternalWithNoLinkageType(VD)2
&&
675
19
          
!VD->getMostRecentDecl()->isInline()2
&&
676
19
          
!VD->hasAttr<ExcludeFromExplicitInstantiationAttr>()0
)
677
0
        continue;
678
19
679
19
      // Skip VarDecls that lack formal definitions but which we know are in
680
19
      // fact defined somewhere.
681
19
      if (VD->isKnownToBeDefined())
682
0
        continue;
683
1.90k
    }
684
1.90k
685
1.90k
    Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
686
1.90k
  }
687
7.58k
}
688
689
/// checkUndefinedButUsed - Check for undefined objects with internal linkage
690
/// or that are inline.
691
31.9k
static void checkUndefinedButUsed(Sema &S) {
692
31.9k
  if (S.UndefinedButUsed.empty()) 
return27.9k
;
693
3.96k
694
3.96k
  // Collect all the still-undefined entities with internal linkage.
695
3.96k
  SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
696
3.96k
  S.getUndefinedButUsed(Undefined);
697
3.96k
  if (Undefined.empty()) 
return3.90k
;
698
61
699
256
  
for (auto Undef : Undefined)61
{
700
256
    ValueDecl *VD = cast<ValueDecl>(Undef.first);
701
256
    SourceLocation UseLoc = Undef.second;
702
256
703
256
    if (S.isExternalWithNoLinkageType(VD)) {
704
7
      // C++ [basic.link]p8:
705
7
      //   A type without linkage shall not be used as the type of a variable
706
7
      //   or function with external linkage unless
707
7
      //    -- the entity has C language linkage
708
7
      //    -- the entity is not odr-used or is defined in the same TU
709
7
      //
710
7
      // As an extension, accept this in cases where the type is externally
711
7
      // visible, since the function or variable actually can be defined in
712
7
      // another translation unit in that case.
713
7
      S.Diag(VD->getLocation(), isExternallyVisible(VD->getType()->getLinkage())
714
7
                                    ? 
diag::ext_undefined_internal_type3
715
7
                                    : 
diag::err_undefined_internal_type4
)
716
7
        << isa<VarDecl>(VD) << VD;
717
249
    } else if (!VD->isExternallyVisible()) {
718
216
      // FIXME: We can promote this to an error. The function or variable can't
719
216
      // be defined anywhere else, so the program must necessarily violate the
720
216
      // one definition rule.
721
216
      S.Diag(VD->getLocation(), diag::warn_undefined_internal)
722
216
        << isa<VarDecl>(VD) << VD;
723
216
    } else 
if (auto *33
FD33
= dyn_cast<FunctionDecl>(VD)) {
724
31
      (void)FD;
725
31
      assert(FD->getMostRecentDecl()->isInlined() &&
726
31
             "used object requires definition but isn't inline or internal?");
727
31
      // FIXME: This is ill-formed; we should reject.
728
31
      S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD;
729
31
    } else {
730
2
      assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
731
2
             "used var requires definition but isn't inline or internal?");
732
2
      S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD;
733
2
    }
734
256
    if (UseLoc.isValid())
735
255
      S.Diag(UseLoc, diag::note_used_here);
736
256
  }
737
61
738
61
  S.UndefinedButUsed.clear();
739
61
}
740
741
8.60M
void Sema::LoadExternalWeakUndeclaredIdentifiers() {
742
8.60M
  if (!ExternalSource)
743
8.50M
    return;
744
102k
745
102k
  SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
746
102k
  ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
747
102k
  for (auto &WeakID : WeakIDs)
748
40
    WeakUndeclaredIdentifiers.insert(WeakID);
749
102k
}
750
751
752
typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
753
754
/// Returns true, if all methods and nested classes of the given
755
/// CXXRecordDecl are defined in this translation unit.
756
///
757
/// Should only be called from ActOnEndOfTranslationUnit so that all
758
/// definitions are actually read.
759
static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
760
12.4k
                                            RecordCompleteMap &MNCComplete) {
761
12.4k
  RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
762
12.4k
  if (Cache != MNCComplete.end())
763
20
    return Cache->second;
764
12.4k
  if (!RD->isCompleteDefinition())
765
4
    return false;
766
12.4k
  bool Complete = true;
767
12.4k
  for (DeclContext::decl_iterator I = RD->decls_begin(),
768
12.4k
                                  E = RD->decls_end();
769
66.7k
       I != E && 
Complete66.1k
;
++I54.3k
) {
770
54.3k
    if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
771
21.9k
      Complete = M->isDefined() || 
M->isDefaulted()11.7k
||
772
21.9k
                 
(11.7k
M->isPure()11.7k
&&
!isa<CXXDestructorDecl>(M)2
);
773
32.3k
    else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
774
3
      // If the template function is marked as late template parsed at this
775
3
      // point, it has not been instantiated and therefore we have not
776
3
      // performed semantic analysis on it yet, so we cannot know if the type
777
3
      // can be considered complete.
778
3
      Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
779
3
                  
F->getTemplatedDecl()->isDefined()2
;
780
32.3k
    else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
781
13.0k
      if (R->isInjectedClassName())
782
12.4k
        continue;
783
691
      if (R->hasDefinition())
784
687
        Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
785
687
                                                   MNCComplete);
786
4
      else
787
4
        Complete = false;
788
691
    }
789
54.3k
  }
790
12.4k
  MNCComplete[RD] = Complete;
791
12.4k
  return Complete;
792
12.4k
}
793
794
/// Returns true, if the given CXXRecordDecl is fully defined in this
795
/// translation unit, i.e. all methods are defined or pure virtual and all
796
/// friends, friend functions and nested classes are fully defined in this
797
/// translation unit.
798
///
799
/// Should only be called from ActOnEndOfTranslationUnit so that all
800
/// definitions are actually read.
801
static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
802
                                 RecordCompleteMap &RecordsComplete,
803
29.0k
                                 RecordCompleteMap &MNCComplete) {
804
29.0k
  RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
805
29.0k
  if (Cache != RecordsComplete.end())
806
17.3k
    return Cache->second;
807
11.7k
  bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
808
11.7k
  for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
809
11.7k
                                      E = RD->friend_end();
810
11.8k
       I != E && 
Complete1.21k
;
++I28
) {
811
28
    // Check if friend classes and methods are complete.
812
28
    if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
813
20
      // Friend classes are available as the TypeSourceInfo of the FriendDecl.
814
20
      if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
815
20
        Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
816
0
      else
817
0
        Complete = false;
818
20
    } else {
819
8
      // Friend functions are available through the NamedDecl of FriendDecl.
820
8
      if (const FunctionDecl *FD =
821
5
          dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
822
5
        Complete = FD->isDefined();
823
3
      else
824
3
        // This is a template friend, give up.
825
3
        Complete = false;
826
8
    }
827
28
  }
828
11.7k
  RecordsComplete[RD] = Complete;
829
11.7k
  return Complete;
830
11.7k
}
831
832
31.9k
void Sema::emitAndClearUnusedLocalTypedefWarnings() {
833
31.9k
  if (ExternalSource)
834
4.37k
    ExternalSource->ReadUnusedLocalTypedefNameCandidates(
835
4.37k
        UnusedLocalTypedefNameCandidates);
836
31.9k
  for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
837
207
    if (TD->isReferenced())
838
16
      continue;
839
191
    Diag(TD->getLocation(), diag::warn_unused_local_typedef)
840
191
        << isa<TypeAliasDecl>(TD) << TD->getDeclName();
841
191
  }
842
31.9k
  UnusedLocalTypedefNameCandidates.clear();
843
31.9k
}
844
845
/// This is called before the very first declaration in the translation unit
846
/// is parsed. Note that the ASTContext may have already injected some
847
/// declarations.
848
41.4k
void Sema::ActOnStartOfTranslationUnit() {
849
41.4k
  if (getLangOpts().ModulesTS &&
850
41.4k
      
(136
getLangOpts().getCompilingModule() == LangOptions::CMK_ModuleInterface136
||
851
136
       
getLangOpts().getCompilingModule() == LangOptions::CMK_None93
)) {
852
122
    // We start in an implied global module fragment.
853
122
    SourceLocation StartOfTU =
854
122
        SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
855
122
    ActOnGlobalModuleFragmentDecl(StartOfTU);
856
122
    ModuleScopes.back().ImplicitGlobalModuleFragment = true;
857
122
  }
858
41.4k
}
859
860
38.2k
void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) {
861
38.2k
  // No explicit actions are required at the end of the global module fragment.
862
38.2k
  if (Kind == TUFragmentKind::Global)
863
85
    return;
864
38.1k
865
38.1k
  // Transfer late parsed template instantiations over to the pending template
866
38.1k
  // instantiation list. During normal compilation, the late template parser
867
38.1k
  // will be installed and instantiating these templates will succeed.
868
38.1k
  //
869
38.1k
  // If we are building a TU prefix for serialization, it is also safe to
870
38.1k
  // transfer these over, even though they are not parsed. The end of the TU
871
38.1k
  // should be outside of any eager template instantiation scope, so when this
872
38.1k
  // AST is deserialized, these templates will not be parsed until the end of
873
38.1k
  // the combined TU.
874
38.1k
  PendingInstantiations.insert(PendingInstantiations.end(),
875
38.1k
                               LateParsedInstantiations.begin(),
876
38.1k
                               LateParsedInstantiations.end());
877
38.1k
  LateParsedInstantiations.clear();
878
38.1k
879
38.1k
  // If DefinedUsedVTables ends up marking any virtual member functions it
880
38.1k
  // might lead to more pending template instantiations, which we then need
881
38.1k
  // to instantiate.
882
38.1k
  DefineUsedVTables();
883
38.1k
884
38.1k
  // C++: Perform implicit template instantiations.
885
38.1k
  //
886
38.1k
  // FIXME: When we perform these implicit instantiations, we do not
887
38.1k
  // carefully keep track of the point of instantiation (C++ [temp.point]).
888
38.1k
  // This means that name lookup that occurs within the template
889
38.1k
  // instantiation will always happen at the end of the translation unit,
890
38.1k
  // so it will find some names that are not required to be found. This is
891
38.1k
  // valid, but we could do better by diagnosing if an instantiation uses a
892
38.1k
  // name that was not visible at its first point of instantiation.
893
38.1k
  if (ExternalSource) {
894
4.89k
    // Load pending instantiations from the external source.
895
4.89k
    SmallVector<PendingImplicitInstantiation, 4> Pending;
896
4.89k
    ExternalSource->ReadPendingInstantiations(Pending);
897
4.89k
    for (auto PII : Pending)
898
2.57k
      if (auto Func = dyn_cast<FunctionDecl>(PII.first))
899
2.52k
        Func->setInstantiationIsPending(true);
900
4.89k
    PendingInstantiations.insert(PendingInstantiations.begin(),
901
4.89k
                                 Pending.begin(), Pending.end());
902
4.89k
  }
903
38.1k
904
38.1k
  {
905
38.1k
    llvm::TimeTraceScope TimeScope("PerformPendingInstantiations",
906
38.1k
                                   StringRef(""));
907
38.1k
    PerformPendingInstantiations();
908
38.1k
  }
909
38.1k
910
38.1k
  assert(LateParsedInstantiations.empty() &&
911
38.1k
         "end of TU template instantiation should not create more "
912
38.1k
         "late-parsed templates");
913
38.1k
}
914
915
/// ActOnEndOfTranslationUnit - This is called at the very end of the
916
/// translation unit when EOF is reached and all but the top-level scope is
917
/// popped.
918
41.4k
void Sema::ActOnEndOfTranslationUnit() {
919
41.4k
  assert(DelayedDiagnostics.getCurrentPool() == nullptr
920
41.4k
         && "reached end of translation unit with a pool attached?");
921
41.4k
922
41.4k
  // If code completion is enabled, don't perform any end-of-translation-unit
923
41.4k
  // work.
924
41.4k
  if (PP.isCodeCompletionEnabled())
925
1.10k
    return;
926
40.3k
927
40.3k
  // Complete translation units and modules define vtables and perform implicit
928
40.3k
  // instantiations. PCH files do not.
929
40.3k
  if (TUKind != TU_Prefix) {
930
38.1k
    DiagnoseUseOfUnimplementedSelectors();
931
38.1k
932
38.1k
    ActOnEndOfTranslationUnitFragment(
933
38.1k
        !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
934
157
                                     Module::PrivateModuleFragment
935
38.1k
            ? 
TUFragmentKind::Private7
936
38.1k
            : 
TUFragmentKind::Normal38.1k
);
937
38.1k
938
38.1k
    if (LateTemplateParserCleanup)
939
1
      LateTemplateParserCleanup(OpaqueParser);
940
38.1k
941
38.1k
    CheckDelayedMemberExceptionSpecs();
942
38.1k
  } else {
943
2.18k
    // If we are building a TU prefix for serialization, it is safe to transfer
944
2.18k
    // these over, even though they are not parsed. The end of the TU should be
945
2.18k
    // outside of any eager template instantiation scope, so when this AST is
946
2.18k
    // deserialized, these templates will not be parsed until the end of the
947
2.18k
    // combined TU.
948
2.18k
    PendingInstantiations.insert(PendingInstantiations.end(),
949
2.18k
                                 LateParsedInstantiations.begin(),
950
2.18k
                                 LateParsedInstantiations.end());
951
2.18k
    LateParsedInstantiations.clear();
952
2.18k
  }
953
40.3k
954
40.3k
  DiagnoseUnterminatedPragmaPack();
955
40.3k
  DiagnoseUnterminatedPragmaAttribute();
956
40.3k
957
40.3k
  // All delayed member exception specs should be checked or we end up accepting
958
40.3k
  // incompatible declarations.
959
40.3k
  assert(DelayedOverridingExceptionSpecChecks.empty());
960
40.3k
  assert(DelayedEquivalentExceptionSpecChecks.empty());
961
40.3k
962
40.3k
  // All dllexport classes should have been processed already.
963
40.3k
  assert(DelayedDllExportClasses.empty());
964
40.3k
965
40.3k
  // Remove file scoped decls that turned out to be used.
966
40.3k
  UnusedFileScopedDecls.erase(
967
40.3k
      std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
968
40.3k
                     UnusedFileScopedDecls.end(),
969
40.3k
                     [this](const DeclaratorDecl *DD) {
970
31.0k
                       return ShouldRemoveFromUnused(this, DD);
971
31.0k
                     }),
972
40.3k
      UnusedFileScopedDecls.end());
973
40.3k
974
40.3k
  if (TUKind == TU_Prefix) {
975
2.18k
    // Translation unit prefixes don't need any of the checking below.
976
2.18k
    if (!PP.isIncrementalProcessingEnabled())
977
2.18k
      TUScope = nullptr;
978
2.18k
    return;
979
2.18k
  }
980
38.1k
981
38.1k
  // Check for #pragma weak identifiers that were never declared
982
38.1k
  LoadExternalWeakUndeclaredIdentifiers();
983
38.1k
  for (auto WeakID : WeakUndeclaredIdentifiers) {
984
102
    if (WeakID.second.getUsed())
985
84
      continue;
986
18
987
18
    Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(),
988
18
                                      LookupOrdinaryName);
989
18
    if (PrevDecl != nullptr &&
990
18
        
!(6
isa<FunctionDecl>(PrevDecl)6
||
isa<VarDecl>(PrevDecl)4
))
991
3
      Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type)
992
3
          << "'weak'" << ExpectedVariableOrFunction;
993
15
    else
994
15
      Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared)
995
15
          << WeakID.first;
996
18
  }
997
38.1k
998
38.1k
  if (LangOpts.CPlusPlus11 &&
999
38.1k
      
!Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation())20.2k
)
1000
20.2k
    CheckDelegatingCtorCycles();
1001
38.1k
1002
38.1k
  if (!Diags.hasErrorOccurred()) {
1003
31.9k
    if (ExternalSource)
1004
4.34k
      ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
1005
31.9k
    checkUndefinedButUsed(*this);
1006
31.9k
  }
1007
38.1k
1008
38.1k
  // A global-module-fragment is only permitted within a module unit.
1009
38.1k
  bool DiagnosedMissingModuleDeclaration = false;
1010
38.1k
  if (!ModuleScopes.empty() &&
1011
38.1k
      
ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment157
&&
1012
38.1k
      
!ModuleScopes.back().ImplicitGlobalModuleFragment50
) {
1013
2
    Diag(ModuleScopes.back().BeginLoc,
1014
2
         diag::err_module_declaration_missing_after_global_module_introducer);
1015
2
    DiagnosedMissingModuleDeclaration = true;
1016
2
  }
1017
38.1k
1018
38.1k
  if (TUKind == TU_Module) {
1019
1.54k
    // If we are building a module interface unit, we need to have seen the
1020
1.54k
    // module declaration by now.
1021
1.54k
    if (getLangOpts().getCompilingModule() ==
1022
1.54k
            LangOptions::CMK_ModuleInterface &&
1023
1.54k
        
(49
ModuleScopes.empty()49
||
1024
49
         !ModuleScopes.back().Module->isModulePurview()) &&
1025
1.54k
        
!DiagnosedMissingModuleDeclaration1
) {
1026
1
      // FIXME: Make a better guess as to where to put the module declaration.
1027
1
      Diag(getSourceManager().getLocForStartOfFile(
1028
1
               getSourceManager().getMainFileID()),
1029
1
           diag::err_module_declaration_missing);
1030
1
    }
1031
1.54k
1032
1.54k
    // If we are building a module, resolve all of the exported declarations
1033
1.54k
    // now.
1034
1.54k
    if (Module *CurrentModule = PP.getCurrentModule()) {
1035
1.51k
      ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
1036
1.51k
1037
1.51k
      SmallVector<Module *, 2> Stack;
1038
1.51k
      Stack.push_back(CurrentModule);
1039
5.07k
      while (!Stack.empty()) {
1040
3.56k
        Module *Mod = Stack.pop_back_val();
1041
3.56k
1042
3.56k
        // Resolve the exported declarations and conflicts.
1043
3.56k
        // FIXME: Actually complain, once we figure out how to teach the
1044
3.56k
        // diagnostic client to deal with complaints in the module map at this
1045
3.56k
        // point.
1046
3.56k
        ModMap.resolveExports(Mod, /*Complain=*/false);
1047
3.56k
        ModMap.resolveUses(Mod, /*Complain=*/false);
1048
3.56k
        ModMap.resolveConflicts(Mod, /*Complain=*/false);
1049
3.56k
1050
3.56k
        // Queue the submodules, so their exports will also be resolved.
1051
3.56k
        Stack.append(Mod->submodule_begin(), Mod->submodule_end());
1052
3.56k
      }
1053
1.51k
    }
1054
1.54k
1055
1.54k
    // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
1056
1.54k
    // modules when they are built, not every time they are used.
1057
1.54k
    emitAndClearUnusedLocalTypedefWarnings();
1058
1.54k
  }
1059
38.1k
1060
38.1k
  // C99 6.9.2p2:
1061
38.1k
  //   A declaration of an identifier for an object that has file
1062
38.1k
  //   scope without an initializer, and without a storage-class
1063
38.1k
  //   specifier or with the storage-class specifier static,
1064
38.1k
  //   constitutes a tentative definition. If a translation unit
1065
38.1k
  //   contains one or more tentative definitions for an identifier,
1066
38.1k
  //   and the translation unit contains no external definition for
1067
38.1k
  //   that identifier, then the behavior is exactly as if the
1068
38.1k
  //   translation unit contains a file scope declaration of that
1069
38.1k
  //   identifier, with the composite type as of the end of the
1070
38.1k
  //   translation unit, with an initializer equal to 0.
1071
38.1k
  llvm::SmallSet<VarDecl *, 32> Seen;
1072
38.1k
  for (TentativeDefinitionsType::iterator
1073
38.1k
            T = TentativeDefinitions.begin(ExternalSource),
1074
38.1k
         TEnd = TentativeDefinitions.end();
1075
57.1k
       T != TEnd; 
++T18.9k
) {
1076
18.9k
    VarDecl *VD = (*T)->getActingDefinition();
1077
18.9k
1078
18.9k
    // If the tentative definition was completed, getActingDefinition() returns
1079
18.9k
    // null. If we've already seen this variable before, insert()'s second
1080
18.9k
    // return value is false.
1081
18.9k
    if (!VD || 
VD->isInvalidDecl()18.9k
||
!Seen.insert(VD).second18.9k
)
1082
190
      continue;
1083
18.7k
1084
18.7k
    if (const IncompleteArrayType *ArrayT
1085
17
        = Context.getAsIncompleteArrayType(VD->getType())) {
1086
17
      // Set the length of the array to 1 (C99 6.9.2p5).
1087
17
      Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
1088
17
      llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
1089
17
      QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
1090
17
                                                One, ArrayType::Normal, 0);
1091
17
      VD->setType(T);
1092
18.7k
    } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
1093
18.7k
                                   diag::err_tentative_def_incomplete_type))
1094
14
      VD->setInvalidDecl();
1095
18.7k
1096
18.7k
    // No initialization is performed for a tentative definition.
1097
18.7k
    CheckCompleteVariableDeclaration(VD);
1098
18.7k
1099
18.7k
    // Notify the consumer that we've completed a tentative definition.
1100
18.7k
    if (!VD->isInvalidDecl())
1101
18.7k
      Consumer.CompleteTentativeDefinition(VD);
1102
18.7k
  }
1103
38.1k
1104
38.1k
  // If there were errors, disable 'unused' warnings since they will mostly be
1105
38.1k
  // noise. Don't warn for a use from a module: either we should warn on all
1106
38.1k
  // file-scope declarations in modules or not at all, but whether the
1107
38.1k
  // declaration is used is immaterial.
1108
38.1k
  if (!Diags.hasErrorOccurred() && 
TUKind != TU_Module31.9k
) {
1109
30.4k
    // Output warning for unused file scoped decls.
1110
30.4k
    for (UnusedFileScopedDeclsType::iterator
1111
30.4k
           I = UnusedFileScopedDecls.begin(ExternalSource),
1112
35.8k
           E = UnusedFileScopedDecls.end(); I != E; 
++I5.44k
) {
1113
5.44k
      if (ShouldRemoveFromUnused(this, *I))
1114
10
        continue;
1115
5.43k
1116
5.43k
      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1117
4.54k
        const FunctionDecl *DiagD;
1118
4.54k
        if (!FD->hasBody(DiagD))
1119
178
          DiagD = FD;
1120
4.54k
        if (DiagD->isDeleted())
1121
1
          continue; // Deleted functions are supposed to be unused.
1122
4.54k
        if (DiagD->isReferenced()) {
1123
60
          if (isa<CXXMethodDecl>(DiagD))
1124
3
            Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
1125
3
                  << DiagD->getDeclName();
1126
57
          else {
1127
57
            if (FD->getStorageClass() == SC_Static &&
1128
57
                
!FD->isInlineSpecified()54
&&
1129
57
                !SourceMgr.isInMainFile(
1130
46
                   SourceMgr.getExpansionLoc(FD->getLocation())))
1131
22
              Diag(DiagD->getLocation(),
1132
22
                   diag::warn_unneeded_static_internal_decl)
1133
22
                  << DiagD->getDeclName();
1134
35
            else
1135
35
              Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1136
35
                   << /*function*/0 << DiagD->getDeclName();
1137
57
          }
1138
4.48k
        } else {
1139
4.48k
          if (FD->getDescribedFunctionTemplate())
1140
507
            Diag(DiagD->getLocation(), diag::warn_unused_template)
1141
507
              << /*function*/0 << DiagD->getDeclName();
1142
3.98k
          else
1143
3.98k
            Diag(DiagD->getLocation(),
1144
3.98k
                 isa<CXXMethodDecl>(DiagD) ? 
diag::warn_unused_member_function150
1145
3.98k
                                           : 
diag::warn_unused_function3.83k
)
1146
3.98k
              << DiagD->getDeclName();
1147
4.48k
        }
1148
4.54k
      } else {
1149
889
        const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
1150
889
        if (!DiagD)
1151
207
          DiagD = cast<VarDecl>(*I);
1152
889
        if (DiagD->isReferenced()) {
1153
10
          Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1154
10
                << /*variable*/1 << DiagD->getDeclName();
1155
879
        } else if (DiagD->getType().isConstQualified()) {
1156
223
          const SourceManager &SM = SourceMgr;
1157
223
          if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
1158
223
              !PP.getLangOpts().IsHeaderFile)
1159
221
            Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
1160
221
                << DiagD->getDeclName();
1161
656
        } else {
1162
656
          if (DiagD->getDescribedVarTemplate())
1163
0
            Diag(DiagD->getLocation(), diag::warn_unused_template)
1164
0
              << /*variable*/1 << DiagD->getDeclName();
1165
656
          else
1166
656
            Diag(DiagD->getLocation(), diag::warn_unused_variable)
1167
656
              << DiagD->getDeclName();
1168
656
        }
1169
889
      }
1170
5.43k
    }
1171
30.4k
1172
30.4k
    emitAndClearUnusedLocalTypedefWarnings();
1173
30.4k
  }
1174
38.1k
1175
38.1k
  if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
1176
5.55k
    // FIXME: Load additional unused private field candidates from the external
1177
5.55k
    // source.
1178
5.55k
    RecordCompleteMap RecordsComplete;
1179
5.55k
    RecordCompleteMap MNCComplete;
1180
5.55k
    for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
1181
34.6k
         E = UnusedPrivateFields.end(); I != E; 
++I29.0k
) {
1182
29.0k
      const NamedDecl *D = *I;
1183
29.0k
      const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1184
29.0k
      if (RD && !RD->isUnion() &&
1185
29.0k
          
IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)29.0k
) {
1186
50
        Diag(D->getLocation(), diag::warn_unused_private_field)
1187
50
              << D->getDeclName();
1188
50
      }
1189
29.0k
    }
1190
5.55k
  }
1191
38.1k
1192
38.1k
  if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
1193
35.3k
    if (ExternalSource)
1194
4.86k
      ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
1195
35.3k
    for (const auto &DeletedFieldInfo : DeleteExprs) {
1196
453
      for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
1197
453
        AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
1198
453
                                  DeleteExprLoc.second);
1199
453
      }
1200
287
    }
1201
35.3k
  }
1202
38.1k
1203
38.1k
  // Check we've noticed that we're no longer parsing the initializer for every
1204
38.1k
  // variable. If we miss cases, then at best we have a performance issue and
1205
38.1k
  // at worst a rejects-valid bug.
1206
38.1k
  assert(ParsingInitForAutoVars.empty() &&
1207
38.1k
         "Didn't unmark var as having its initializer parsed");
1208
38.1k
1209
38.1k
  if (!PP.isIncrementalProcessingEnabled())
1210
38.1k
    TUScope = nullptr;
1211
38.1k
}
1212
1213
1214
//===----------------------------------------------------------------------===//
1215
// Helper functions.
1216
//===----------------------------------------------------------------------===//
1217
1218
58.9M
DeclContext *Sema::getFunctionLevelDeclContext() {
1219
58.9M
  DeclContext *DC = CurContext;
1220
58.9M
1221
60.1M
  while (true) {
1222
60.1M
    if (isa<BlockDecl>(DC) || 
isa<EnumDecl>(DC)60.1M
||
isa<CapturedDecl>(DC)60.1M
) {
1223
1.18M
      DC = DC->getParent();
1224
58.9M
    } else if (isa<CXXMethodDecl>(DC) &&
1225
58.9M
               
cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call19.3M
&&
1226
58.9M
               
cast<CXXRecordDecl>(DC->getParent())->isLambda()453k
) {
1227
30.5k
      DC = DC->getParent()->getParent();
1228
30.5k
    }
1229
58.9M
    else break;
1230
60.1M
  }
1231
58.9M
1232
58.9M
  return DC;
1233
58.9M
}
1234
1235
/// getCurFunctionDecl - If inside of a function body, this returns a pointer
1236
/// to the function decl for the function being parsed.  If we're currently
1237
/// in a 'block', this returns the containing context.
1238
26.4M
FunctionDecl *Sema::getCurFunctionDecl() {
1239
26.4M
  DeclContext *DC = getFunctionLevelDeclContext();
1240
26.4M
  return dyn_cast<FunctionDecl>(DC);
1241
26.4M
}
1242
1243
23.6M
ObjCMethodDecl *Sema::getCurMethodDecl() {
1244
23.6M
  DeclContext *DC = getFunctionLevelDeclContext();
1245
24.8M
  while (isa<RecordDecl>(DC))
1246
1.22M
    DC = DC->getParent();
1247
23.6M
  return dyn_cast<ObjCMethodDecl>(DC);
1248
23.6M
}
1249
1250
81.9k
NamedDecl *Sema::getCurFunctionOrMethodDecl() {
1251
81.9k
  DeclContext *DC = getFunctionLevelDeclContext();
1252
81.9k
  if (isa<ObjCMethodDecl>(DC) || 
isa<FunctionDecl>(DC)81.7k
)
1253
80.3k
    return cast<NamedDecl>(DC);
1254
1.52k
  return nullptr;
1255
1.52k
}
1256
1257
2.39M
void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
1258
2.39M
  // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1259
2.39M
  // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1260
2.39M
  // been made more painfully obvious by the refactor that introduced this
1261
2.39M
  // function, but it is possible that the incoming argument can be
1262
2.39M
  // eliminated. If it truly cannot be (for example, there is some reentrancy
1263
2.39M
  // issue I am not seeing yet), then there should at least be a clarifying
1264
2.39M
  // comment somewhere.
1265
2.39M
  if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
1266
164k
    switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
1267
164k
              Diags.getCurrentDiagID())) {
1268
164k
    case DiagnosticIDs::SFINAE_Report:
1269
31
      // We'll report the diagnostic below.
1270
31
      break;
1271
164k
1272
164k
    case DiagnosticIDs::SFINAE_SubstitutionFailure:
1273
152k
      // Count this failure so that we know that template argument deduction
1274
152k
      // has failed.
1275
152k
      ++NumSFINAEErrors;
1276
152k
1277
152k
      // Make a copy of this suppressed diagnostic and store it with the
1278
152k
      // template-deduction information.
1279
152k
      if (*Info && 
!(*Info)->hasSFINAEDiagnostic()151k
) {
1280
150k
        Diagnostic DiagInfo(&Diags);
1281
150k
        (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1282
150k
                       PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1283
150k
      }
1284
152k
1285
152k
      Diags.setLastDiagnosticIgnored();
1286
152k
      Diags.Clear();
1287
152k
      return;
1288
164k
1289
164k
    case DiagnosticIDs::SFINAE_AccessControl: {
1290
30
      // Per C++ Core Issue 1170, access control is part of SFINAE.
1291
30
      // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
1292
30
      // make access control a part of SFINAE for the purposes of checking
1293
30
      // type traits.
1294
30
      if (!AccessCheckingSFINAE && 
!getLangOpts().CPlusPlus1114
)
1295
1
        break;
1296
29
1297
29
      SourceLocation Loc = Diags.getCurrentDiagLoc();
1298
29
1299
29
      // Suppress this diagnostic.
1300
29
      ++NumSFINAEErrors;
1301
29
1302
29
      // Make a copy of this suppressed diagnostic and store it with the
1303
29
      // template-deduction information.
1304
29
      if (*Info && 
!(*Info)->hasSFINAEDiagnostic()12
) {
1305
11
        Diagnostic DiagInfo(&Diags);
1306
11
        (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1307
11
                       PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1308
11
      }
1309
29
1310
29
      Diags.setLastDiagnosticIgnored();
1311
29
      Diags.Clear();
1312
29
1313
29
      // Now the diagnostic state is clear, produce a C++98 compatibility
1314
29
      // warning.
1315
29
      Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
1316
29
1317
29
      // The last diagnostic which Sema produced was ignored. Suppress any
1318
29
      // notes attached to it.
1319
29
      Diags.setLastDiagnosticIgnored();
1320
29
      return;
1321
29
    }
1322
29
1323
11.9k
    case DiagnosticIDs::SFINAE_Suppress:
1324
11.9k
      // Make a copy of this suppressed diagnostic and store it with the
1325
11.9k
      // template-deduction information;
1326
11.9k
      if (*Info) {
1327
9.25k
        Diagnostic DiagInfo(&Diags);
1328
9.25k
        (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
1329
9.25k
                       PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1330
9.25k
      }
1331
11.9k
1332
11.9k
      // Suppress this diagnostic.
1333
11.9k
      Diags.setLastDiagnosticIgnored();
1334
11.9k
      Diags.Clear();
1335
11.9k
      return;
1336
2.23M
    }
1337
2.23M
  }
1338
2.23M
1339
2.23M
  // Copy the diagnostic printing policy over the ASTContext printing policy.
1340
2.23M
  // TODO: Stop doing that.  See: https://reviews.llvm.org/D45093#1090292
1341
2.23M
  Context.setPrintingPolicy(getPrintingPolicy());
1342
2.23M
1343
2.23M
  // Emit the diagnostic.
1344
2.23M
  if (!Diags.EmitCurrentDiagnostic())
1345
2.06M
    return;
1346
169k
1347
169k
  // If this is not a note, and we're in a template instantiation
1348
169k
  // that is different from the last template instantiation where
1349
169k
  // we emitted an error, print a template instantiation
1350
169k
  // backtrace.
1351
169k
  if (!DiagnosticIDs::isBuiltinNote(DiagID))
1352
107k
    PrintContextStack();
1353
169k
}
1354
1355
Sema::SemaDiagnosticBuilder
1356
92.6k
Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
1357
92.6k
  SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
1358
92.6k
  PD.Emit(Builder);
1359
92.6k
1360
92.6k
  return Builder;
1361
92.6k
}
1362
1363
// Print notes showing how we can reach FD starting from an a priori
1364
// known-callable function.
1365
85
static void emitCallStackNotes(Sema &S, FunctionDecl *FD) {
1366
85
  auto FnIt = S.DeviceKnownEmittedFns.find(FD);
1367
126
  while (FnIt != S.DeviceKnownEmittedFns.end()) {
1368
41
    DiagnosticBuilder Builder(
1369
41
        S.Diags.Report(FnIt->second.Loc, diag::note_called_by));
1370
41
    Builder << FnIt->second.FD;
1371
41
    Builder.setForceEmit();
1372
41
1373
41
    FnIt = S.DeviceKnownEmittedFns.find(FnIt->second.FD);
1374
41
  }
1375
85
}
1376
1377
// Emit any deferred diagnostics for FD and erase them from the map in which
1378
// they're stored.
1379
2.04k
static void emitDeferredDiags(Sema &S, FunctionDecl *FD) {
1380
2.04k
  auto It = S.DeviceDeferredDiags.find(FD);
1381
2.04k
  if (It == S.DeviceDeferredDiags.end())
1382
2.01k
    return;
1383
31
  bool HasWarningOrError = false;
1384
39
  for (PartialDiagnosticAt &PDAt : It->second) {
1385
39
    const SourceLocation &Loc = PDAt.first;
1386
39
    const PartialDiagnostic &PD = PDAt.second;
1387
39
    HasWarningOrError |= S.getDiagnostics().getDiagnosticLevel(
1388
39
                             PD.getDiagID(), Loc) >= DiagnosticsEngine::Warning;
1389
39
    DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
1390
39
    Builder.setForceEmit();
1391
39
    PD.Emit(Builder);
1392
39
  }
1393
31
  S.DeviceDeferredDiags.erase(It);
1394
31
1395
31
  // FIXME: Should this be called after every warning/error emitted in the loop
1396
31
  // above, instead of just once per function?  That would be consistent with
1397
31
  // how we handle immediate errors, but it also seems like a bit much.
1398
31
  if (HasWarningOrError)
1399
31
    emitCallStackNotes(S, FD);
1400
31
}
1401
1402
// In CUDA, there are some constructs which may appear in semantically-valid
1403
// code, but trigger errors if we ever generate code for the function in which
1404
// they appear.  Essentially every construct you're not allowed to use on the
1405
// device falls into this category, because you are allowed to use these
1406
// constructs in a __host__ __device__ function, but only if that function is
1407
// never codegen'ed on the device.
1408
//
1409
// To handle semantic checking for these constructs, we keep track of the set of
1410
// functions we know will be emitted, either because we could tell a priori that
1411
// they would be emitted, or because they were transitively called by a
1412
// known-emitted function.
1413
//
1414
// We also keep a partial call graph of which not-known-emitted functions call
1415
// which other not-known-emitted functions.
1416
//
1417
// When we see something which is illegal if the current function is emitted
1418
// (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or
1419
// CheckCUDACall), we first check if the current function is known-emitted.  If
1420
// so, we immediately output the diagnostic.
1421
//
1422
// Otherwise, we "defer" the diagnostic.  It sits in Sema::DeviceDeferredDiags
1423
// until we discover that the function is known-emitted, at which point we take
1424
// it out of this map and emit the diagnostic.
1425
1426
Sema::DeviceDiagBuilder::DeviceDiagBuilder(Kind K, SourceLocation Loc,
1427
                                           unsigned DiagID, FunctionDecl *Fn,
1428
                                           Sema &S)
1429
    : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
1430
569
      ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
1431
569
  switch (K) {
1432
569
  case K_Nop:
1433
29
    break;
1434
569
  case K_Immediate:
1435
433
  case K_ImmediateWithCallStack:
1436
433
    ImmediateDiag.emplace(S.Diag(Loc, DiagID));
1437
433
    break;
1438
433
  case K_Deferred:
1439
107
    assert(Fn && "Must have a function to attach the deferred diag to.");
1440
107
    auto &Diags = S.DeviceDeferredDiags[Fn];
1441
107
    PartialDiagId.emplace(Diags.size());
1442
107
    Diags.emplace_back(Loc, S.PDiag(DiagID));
1443
107
    break;
1444
569
  }
1445
569
}
1446
1447
Sema::DeviceDiagBuilder::DeviceDiagBuilder(DeviceDiagBuilder &&D)
1448
    : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn),
1449
      ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),
1450
0
      PartialDiagId(D.PartialDiagId) {
1451
0
  // Clean the previous diagnostics.
1452
0
  D.ShowCallStack = false;
1453
0
  D.ImmediateDiag.reset();
1454
0
  D.PartialDiagId.reset();
1455
0
}
1456
1457
580
Sema::DeviceDiagBuilder::~DeviceDiagBuilder() {
1458
580
  if (ImmediateDiag) {
1459
444
    // Emit our diagnostic and, if it was a warning or error, output a callstack
1460
444
    // if Fn isn't a priori known-emitted.
1461
444
    bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
1462
444
                                DiagID, Loc) >= DiagnosticsEngine::Warning;
1463
444
    ImmediateDiag.reset(); // Emit the immediate diag.
1464
444
    if (IsWarningOrError && 
ShowCallStack330
)
1465
54
      emitCallStackNotes(S, Fn);
1466
444
  } else {
1467
136
    assert((!PartialDiagId || ShowCallStack) &&
1468
136
           "Must always show call stack for deferred diags.");
1469
136
  }
1470
580
}
1471
1472
// Indicate that this function (and thus everything it transtively calls) will
1473
// be codegen'ed, and emit any deferred diagnostics on this function and its
1474
// (transitive) callees.
1475
void Sema::markKnownEmitted(
1476
    Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee,
1477
    SourceLocation OrigLoc,
1478
6.20k
    const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted) {
1479
6.20k
  // Nothing to do if we already know that FD is emitted.
1480
6.20k
  if (IsKnownEmitted(S, OrigCallee)) {
1481
4.32k
    assert(!S.DeviceCallGraph.count(OrigCallee));
1482
4.32k
    return;
1483
4.32k
  }
1484
1.88k
1485
1.88k
  // We've just discovered that OrigCallee is known-emitted.  Walk our call
1486
1.88k
  // graph to see what else we can now discover also must be emitted.
1487
1.88k
1488
1.88k
  struct CallInfo {
1489
1.88k
    FunctionDecl *Caller;
1490
1.88k
    FunctionDecl *Callee;
1491
1.88k
    SourceLocation Loc;
1492
1.88k
  };
1493
1.88k
  llvm::SmallVector<CallInfo, 4> Worklist = {{OrigCaller, OrigCallee, OrigLoc}};
1494
1.88k
  llvm::SmallSet<CanonicalDeclPtr<FunctionDecl>, 4> Seen;
1495
1.88k
  Seen.insert(OrigCallee);
1496
3.93k
  while (!Worklist.empty()) {
1497
2.04k
    CallInfo C = Worklist.pop_back_val();
1498
2.04k
    assert(!IsKnownEmitted(S, C.Callee) &&
1499
2.04k
           "Worklist should not contain known-emitted functions.");
1500
2.04k
    S.DeviceKnownEmittedFns[C.Callee] = {C.Caller, C.Loc};
1501
2.04k
    emitDeferredDiags(S, C.Callee);
1502
2.04k
1503
2.04k
    // If this is a template instantiation, explore its callgraph as well:
1504
2.04k
    // Non-dependent calls are part of the template's callgraph, while dependent
1505
2.04k
    // calls are part of to the instantiation's call graph.
1506
2.04k
    if (auto *Templ = C.Callee->getPrimaryTemplate()) {
1507
107
      FunctionDecl *TemplFD = Templ->getAsFunction();
1508
107
      if (!Seen.count(TemplFD) && !S.DeviceKnownEmittedFns.count(TemplFD)) {
1509
38
        Seen.insert(TemplFD);
1510
38
        Worklist.push_back(
1511
38
            {/* Caller = */ C.Caller, /* Callee = */ TemplFD, C.Loc});
1512
38
      }
1513
107
    }
1514
2.04k
1515
2.04k
    // Add all functions called by Callee to our worklist.
1516
2.04k
    auto CGIt = S.DeviceCallGraph.find(C.Callee);
1517
2.04k
    if (CGIt == S.DeviceCallGraph.end())
1518
1.84k
      continue;
1519
203
1520
203
    for (std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation> FDLoc :
1521
256
         CGIt->second) {
1522
256
      FunctionDecl *NewCallee = FDLoc.first;
1523
256
      SourceLocation CallLoc = FDLoc.second;
1524
256
      if (Seen.count(NewCallee) || IsKnownEmitted(S, NewCallee))
1525
131
        continue;
1526
125
      Seen.insert(NewCallee);
1527
125
      Worklist.push_back(
1528
125
          {/* Caller = */ C.Callee, /* Callee = */ NewCallee, CallLoc});
1529
125
    }
1530
203
1531
203
    // C.Callee is now known-emitted, so we no longer need to maintain its list
1532
203
    // of callees in DeviceCallGraph.
1533
203
    S.DeviceCallGraph.erase(CGIt);
1534
203
  }
1535
1.88k
}
1536
1537
311
Sema::DeviceDiagBuilder Sema::targetDiag(SourceLocation Loc, unsigned DiagID) {
1538
311
  if (LangOpts.OpenMP && 
LangOpts.OpenMPIsDevice80
)
1539
80
    return diagIfOpenMPDeviceCode(Loc, DiagID);
1540
231
  if (getLangOpts().CUDA)
1541
30
    return getLangOpts().CUDAIsDevice ? 
CUDADiagIfDeviceCode(Loc, DiagID)27
1542
30
                                      : 
CUDADiagIfHostCode(Loc, DiagID)3
;
1543
201
  return DeviceDiagBuilder(DeviceDiagBuilder::K_Immediate, Loc, DiagID,
1544
201
                           getCurFunctionDecl(), *this);
1545
201
}
1546
1547
/// Looks through the macro-expansion chain for the given
1548
/// location, looking for a macro expansion with the given name.
1549
/// If one is found, returns true and sets the location to that
1550
/// expansion loc.
1551
306
bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
1552
306
  SourceLocation loc = locref;
1553
306
  if (!loc.isMacroID()) 
return false5
;
1554
301
1555
301
  // There's no good way right now to look at the intermediate
1556
301
  // expansions, so just jump to the expansion location.
1557
301
  loc = getSourceManager().getExpansionLoc(loc);
1558
301
1559
301
  // If that's written with the name, stop here.
1560
301
  SmallVector<char, 16> buffer;
1561
301
  if (getPreprocessor().getSpelling(loc, buffer) == name) {
1562
13
    locref = loc;
1563
13
    return true;
1564
13
  }
1565
288
  return false;
1566
288
}
1567
1568
/// Determines the active Scope associated with the given declaration
1569
/// context.
1570
///
1571
/// This routine maps a declaration context to the active Scope object that
1572
/// represents that declaration context in the parser. It is typically used
1573
/// from "scope-less" code (e.g., template instantiation, lazy creation of
1574
/// declarations) that injects a name for name-lookup purposes and, therefore,
1575
/// must update the Scope.
1576
///
1577
/// \returns The scope corresponding to the given declaraion context, or NULL
1578
/// if no such scope is open.
1579
642k
Scope *Sema::getScopeForContext(DeclContext *Ctx) {
1580
642k
1581
642k
  if (!Ctx)
1582
0
    return nullptr;
1583
642k
1584
642k
  Ctx = Ctx->getPrimaryContext();
1585
2.12M
  for (Scope *S = getCurScope(); S; 
S = S->getParent()1.48M
) {
1586
1.61M
    // Ignore scopes that cannot have declarations. This is important for
1587
1.61M
    // out-of-line definitions of static class members.
1588
1.61M
    if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
1589
1.58M
      if (DeclContext *Entity = S->getEntity())
1590
1.49M
        if (Ctx == Entity->getPrimaryContext())
1591
135k
          return S;
1592
1.61M
  }
1593
642k
1594
642k
  
return nullptr506k
;
1595
642k
}
1596
1597
/// Enter a new function scope
1598
3.63M
void Sema::PushFunctionScope() {
1599
3.63M
  if (FunctionScopes.empty() && 
CachedFunctionScope3.50M
) {
1600
3.47M
    // Use CachedFunctionScope to avoid allocating memory when possible.
1601
3.47M
    CachedFunctionScope->Clear();
1602
3.47M
    FunctionScopes.push_back(CachedFunctionScope.release());
1603
3.47M
  } else {
1604
159k
    FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
1605
159k
  }
1606
3.63M
  if (LangOpts.OpenMP)
1607
51.3k
    pushOpenMPFunctionRegion();
1608
3.63M
}
1609
1610
2.75k
void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
1611
2.75k
  FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
1612
2.75k
                                              BlockScope, Block));
1613
2.75k
}
1614
1615
7.99k
LambdaScopeInfo *Sema::PushLambdaScope() {
1616
7.99k
  LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
1617
7.99k
  FunctionScopes.push_back(LSI);
1618
7.99k
  return LSI;
1619
7.99k
}
1620
1621
2.14k
void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
1622
2.14k
  if (LambdaScopeInfo *const LSI = getCurLambda()) {
1623
2.14k
    LSI->AutoTemplateParameterDepth = Depth;
1624
2.14k
    return;
1625
2.14k
  }
1626
0
  llvm_unreachable(
1627
0
      "Remove assertion if intentionally called in a non-lambda context.");
1628
0
}
1629
1630
// Check that the type of the VarDecl has an accessible copy constructor and
1631
// resolve its destructor's exception specification.
1632
117
static void checkEscapingByref(VarDecl *VD, Sema &S) {
1633
117
  QualType T = VD->getType();
1634
117
  EnterExpressionEvaluationContext scope(
1635
117
      S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
1636
117
  SourceLocation Loc = VD->getLocation();
1637
117
  Expr *VarRef =
1638
117
      new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
1639
117
  ExprResult Result = S.PerformMoveOrCopyInitialization(
1640
117
      InitializedEntity::InitializeBlock(Loc, T, false), VD, VD->getType(),
1641
117
      VarRef, /*AllowNRVO=*/true);
1642
117
  if (!Result.isInvalid()) {
1643
111
    Result = S.MaybeCreateExprWithCleanups(Result);
1644
111
    Expr *Init = Result.getAs<Expr>();
1645
111
    S.Context.setBlockVarCopyInit(VD, Init, S.canThrow(Init));
1646
111
  }
1647
117
1648
117
  // The destructor's exception specification is needed when IRGen generates
1649
117
  // block copy/destroy functions. Resolve it here.
1650
117
  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1651
117
    if (CXXDestructorDecl *DD = RD->getDestructor()) {
1652
15
      auto *FPT = DD->getType()->getAs<FunctionProtoType>();
1653
15
      S.ResolveExceptionSpec(Loc, FPT);
1654
15
    }
1655
117
}
1656
1657
3.94M
static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) {
1658
3.94M
  // Set the EscapingByref flag of __block variables captured by
1659
3.94M
  // escaping blocks.
1660
3.94M
  for (const BlockDecl *BD : FSI.Blocks) {
1661
2.87k
    for (const BlockDecl::Capture &BC : BD->captures()) {
1662
2.87k
      VarDecl *VD = BC.getVariable();
1663
2.87k
      if (VD->hasAttr<BlocksAttr>()) {
1664
711
        // Nothing to do if this is a __block variable captured by a
1665
711
        // non-escaping block.
1666
711
        if (BD->doesNotEscape())
1667
20
          continue;
1668
691
        VD->setEscapingByref();
1669
691
      }
1670
2.87k
      // Check whether the captured variable is or contains an object of
1671
2.87k
      // non-trivial C union type.
1672
2.87k
      QualType CapType = BC.getVariable()->getType();
1673
2.85k
      if (CapType.hasNonTrivialToPrimitiveDestructCUnion() ||
1674
2.85k
          
CapType.hasNonTrivialToPrimitiveCopyCUnion()2.84k
)
1675
6
        S.checkNonTrivialCUnion(BC.getVariable()->getType(),
1676
6
                                BD->getCaretLocation(),
1677
6
                                Sema::NTCUC_BlockCapture,
1678
6
                                Sema::NTCUK_Destruct|Sema::NTCUK_Copy);
1679
2.85k
    }
1680
2.62k
  }
1681
3.94M
1682
3.94M
  for (VarDecl *VD : FSI.ByrefBlockVars) {
1683
255
    // __block variables might require us to capture a copy-initializer.
1684
255
    if (!VD->isEscapingByref())
1685
48
      continue;
1686
207
    // It's currently invalid to ever have a __block variable with an
1687
207
    // array type; should we diagnose that here?
1688
207
    // Regardless, we don't want to ignore array nesting when
1689
207
    // constructing this copy.
1690
207
    if (VD->getType()->isStructureOrClassType())
1691
117
      checkEscapingByref(VD, S);
1692
207
  }
1693
3.94M
}
1694
1695
/// Pop a function (or block or lambda or captured region) scope from the stack.
1696
///
1697
/// \param WP The warning policy to use for CFG-based warnings, or null if such
1698
///        warnings should not be produced.
1699
/// \param D The declaration corresponding to this function scope, if producing
1700
///        CFG-based warnings.
1701
/// \param BlockType The type of the block expression, if D is a BlockDecl.
1702
Sema::PoppedFunctionScopePtr
1703
Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
1704
3.94M
                           const Decl *D, QualType BlockType) {
1705
3.94M
  assert(!FunctionScopes.empty() && "mismatched push/pop!");
1706
3.94M
1707
3.94M
  markEscapingByrefs(*FunctionScopes.back(), *this);
1708
3.94M
1709
3.94M
  PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(),
1710
3.94M
                               PoppedFunctionScopeDeleter(this));
1711
3.94M
1712
3.94M
  if (LangOpts.OpenMP)
1713
347k
    popOpenMPFunctionRegion(Scope.get());
1714
3.94M
1715
3.94M
  // Issue any analysis-based warnings.
1716
3.94M
  if (WP && 
D3.02M
)
1717
3.02M
    AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType);
1718
920k
  else
1719
920k
    for (const auto &PUD : Scope->PossiblyUnreachableDiags)
1720
32.2k
      Diag(PUD.Loc, PUD.PD);
1721
3.94M
1722
3.94M
  return Scope;
1723
3.94M
}
1724
1725
void Sema::PoppedFunctionScopeDeleter::
1726
3.94M
operator()(sema::FunctionScopeInfo *Scope) const {
1727
3.94M
  // Stash the function scope for later reuse if it's for a normal function.
1728
3.94M
  if (Scope->isPlainFunction() && 
!Self->CachedFunctionScope3.63M
)
1729
3.50M
    Self->CachedFunctionScope.reset(Scope);
1730
435k
  else
1731
435k
    delete Scope;
1732
3.94M
}
1733
1734
4.70M
void Sema::PushCompoundScope(bool IsStmtExpr) {
1735
4.70M
  getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo(IsStmtExpr));
1736
4.70M
}
1737
1738
4.70M
void Sema::PopCompoundScope() {
1739
4.70M
  FunctionScopeInfo *CurFunction = getCurFunction();
1740
4.70M
  assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
1741
4.70M
1742
4.70M
  CurFunction->CompoundScopes.pop_back();
1743
4.70M
}
1744
1745
/// Determine whether any errors occurred within this function/method/
1746
/// block.
1747
22.8k
bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
1748
22.8k
  return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
1749
22.8k
}
1750
1751
23.5k
void Sema::setFunctionHasBranchIntoScope() {
1752
23.5k
  if (!FunctionScopes.empty())
1753
23.5k
    FunctionScopes.back()->setHasBranchIntoScope();
1754
23.5k
}
1755
1756
1.75M
void Sema::setFunctionHasBranchProtectedScope() {
1757
1.75M
  if (!FunctionScopes.empty())
1758
1.75M
    FunctionScopes.back()->setHasBranchProtectedScope();
1759
1.75M
}
1760
1761
143
void Sema::setFunctionHasIndirectGoto() {
1762
143
  if (!FunctionScopes.empty())
1763
143
    FunctionScopes.back()->setHasIndirectGoto();
1764
143
}
1765
1766
91.4k
BlockScopeInfo *Sema::getCurBlock() {
1767
91.4k
  if (FunctionScopes.empty())
1768
919
    return nullptr;
1769
90.4k
1770
90.4k
  auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
1771
90.4k
  if (CurBSI && 
CurBSI->TheDecl6.88k
&&
1772
90.4k
      
!CurBSI->TheDecl->Encloses(CurContext)6.88k
) {
1773
0
    // We have switched contexts due to template instantiation.
1774
0
    assert(!CodeSynthesisContexts.empty());
1775
0
    return nullptr;
1776
0
  }
1777
90.4k
1778
90.4k
  return CurBSI;
1779
90.4k
}
1780
1781
2.27k
FunctionScopeInfo *Sema::getEnclosingFunction() const {
1782
2.27k
  if (FunctionScopes.empty())
1783
436
    return nullptr;
1784
1.84k
1785
1.84k
  
for (int e = FunctionScopes.size() - 1; 1.84k
e >= 0;
--e7
) {
1786
1.84k
    if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1787
7
      continue;
1788
1.84k
    return FunctionScopes[e];
1789
1.84k
  }
1790
1.84k
  
return nullptr0
;
1791
1.84k
}
1792
1793
12.8M
LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
1794
12.8M
  if (FunctionScopes.empty())
1795
720k
    return nullptr;
1796
12.1M
1797
12.1M
  auto I = FunctionScopes.rbegin();
1798
12.1M
  if (IgnoreNonLambdaCapturingScope) {
1799
10.6M
    auto E = FunctionScopes.rend();
1800
12.4M
    while (I != E && 
isa<CapturingScopeInfo>(*I)12.4M
&&
!isa<LambdaScopeInfo>(*I)1.85M
)
1801
1.83M
      ++I;
1802
10.6M
    if (I == E)
1803
126
      return nullptr;
1804
12.1M
  }
1805
12.1M
  auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
1806
12.1M
  if (CurLSI && 
CurLSI->Lambda59.0k
&&
1807
12.1M
      
!CurLSI->Lambda->Encloses(CurContext)34.9k
) {
1808
952
    // We have switched contexts due to template instantiation.
1809
952
    assert(!CodeSynthesisContexts.empty());
1810
952
    return nullptr;
1811
952
  }
1812
12.1M
1813
12.1M
  return CurLSI;
1814
12.1M
}
1815
// We have a generic lambda if we parsed auto parameters, or we have
1816
// an associated template parameter list.
1817
2.14k
LambdaScopeInfo *Sema::getCurGenericLambda() {
1818
2.14k
  if (LambdaScopeInfo *LSI =  getCurLambda()) {
1819
2.14k
    return (LSI->TemplateParams.size() ||
1820
2.14k
                    
LSI->GLTemplateParameterList1.14k
) ?
LSI1.00k
:
nullptr1.14k
;
1821
2.14k
  }
1822
0
  return nullptr;
1823
0
}
1824
1825
1826
13.4M
void Sema::ActOnComment(SourceRange Comment) {
1827
13.4M
  if (!LangOpts.RetainCommentsFromSystemHeaders &&
1828
13.4M
      
SourceMgr.isInSystemHeader(Comment.getBegin())13.4M
)
1829
8.53M
    return;
1830
4.89M
  RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);
1831
4.89M
  if (RC.isAlmostTrailingComment()) {
1832
138
    SourceRange MagicMarkerRange(Comment.getBegin(),
1833
138
                                 Comment.getBegin().getLocWithOffset(3));
1834
138
    StringRef MagicMarkerText;
1835
138
    switch (RC.getKind()) {
1836
138
    case RawComment::RCK_OrdinaryBCPL:
1837
80
      MagicMarkerText = "///<";
1838
80
      break;
1839
138
    case RawComment::RCK_OrdinaryC:
1840
58
      MagicMarkerText = "/**<";
1841
58
      break;
1842
138
    default:
1843
0
      llvm_unreachable("if this is an almost Doxygen comment, "
1844
138
                       "it should be ordinary");
1845
138
    }
1846
138
    Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
1847
138
      FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
1848
138
  }
1849
4.89M
  Context.addComment(RC);
1850
4.89M
}
1851
1852
// Pin this vtable to this file.
1853
7.36k
ExternalSemaSource::~ExternalSemaSource() {}
1854
1855
0
void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
1856
0
void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
1857
1858
void ExternalSemaSource::ReadKnownNamespaces(
1859
1
                           SmallVectorImpl<NamespaceDecl *> &Namespaces) {
1860
1
}
1861
1862
void ExternalSemaSource::ReadUndefinedButUsed(
1863
1
    llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
1864
1865
void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
1866
10
    FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
1867
1868
/// Figure out if an expression could be turned into a call.
1869
///
1870
/// Use this when trying to recover from an error where the programmer may have
1871
/// written just the name of a function instead of actually calling it.
1872
///
1873
/// \param E - The expression to examine.
1874
/// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1875
///  with no arguments, this parameter is set to the type returned by such a
1876
///  call; otherwise, it is set to an empty QualType.
1877
/// \param OverloadSet - If the expression is an overloaded function
1878
///  name, this parameter is populated with the decls of the various overloads.
1879
bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1880
306
                         UnresolvedSetImpl &OverloadSet) {
1881
306
  ZeroArgCallReturnTy = QualType();
1882
306
  OverloadSet.clear();
1883
306
1884
306
  const OverloadExpr *Overloads = nullptr;
1885
306
  bool IsMemExpr = false;
1886
306
  if (E.getType() == Context.OverloadTy) {
1887
88
    OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
1888
88
1889
88
    // Ignore overloads that are pointer-to-member constants.
1890
88
    if (FR.HasFormOfMemberPointer)
1891
18
      return false;
1892
70
1893
70
    Overloads = FR.Expression;
1894
218
  } else if (E.getType() == Context.BoundMemberTy) {
1895
82
    Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
1896
82
    IsMemExpr = true;
1897
82
  }
1898
306
1899
306
  bool Ambiguous = false;
1900
288
  bool IsMV = false;
1901
288
1902
288
  if (Overloads) {
1903
99
    for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
1904
259
         DeclsEnd = Overloads->decls_end(); it != DeclsEnd; 
++it160
) {
1905
160
      OverloadSet.addDecl(*it);
1906
160
1907
160
      // Check whether the function is a non-template, non-member which takes no
1908
160
      // arguments.
1909
160
      if (IsMemExpr)
1910
36
        continue;
1911
124
      if (const FunctionDecl *OverloadDecl
1912
76
            = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
1913
76
        if (OverloadDecl->getMinRequiredArguments() == 0) {
1914
35
          if (!ZeroArgCallReturnTy.isNull() && 
!Ambiguous4
&&
1915
35
              
(4
!IsMV4
||
!(2
OverloadDecl->isCPUDispatchMultiVersion()2
||
1916
2
                          OverloadDecl->isCPUSpecificMultiVersion()))) {
1917
2
            ZeroArgCallReturnTy = QualType();
1918
2
            Ambiguous = true;
1919
33
          } else {
1920
33
            ZeroArgCallReturnTy = OverloadDecl->getReturnType();
1921
33
            IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||
1922
33
                   OverloadDecl->isCPUSpecificMultiVersion();
1923
33
          }
1924
35
        }
1925
76
      }
1926
124
    }
1927
99
1928
99
    // If it's not a member, use better machinery to try to resolve the call
1929
99
    if (!IsMemExpr)
1930
70
      return !ZeroArgCallReturnTy.isNull();
1931
218
  }
1932
218
1933
218
  // Attempt to call the member with no arguments - this will correctly handle
1934
218
  // member templates with defaults/deduction of template arguments, overloads
1935
218
  // with default arguments, etc.
1936
218
  if (IsMemExpr && 
!E.isTypeDependent()82
) {
1937
79
    bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
1938
79
    getDiagnostics().setSuppressAllDiagnostics(true);
1939
79
    ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
1940
79
                                             None, SourceLocation());
1941
79
    getDiagnostics().setSuppressAllDiagnostics(Suppress);
1942
79
    if (R.isUsable()) {
1943
62
      ZeroArgCallReturnTy = R.get()->getType();
1944
62
      return true;
1945
62
    }
1946
17
    return false;
1947
17
  }
1948
139
1949
139
  if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
1950
97
    if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
1951
80
      if (Fun->getMinRequiredArguments() == 0)
1952
64
        ZeroArgCallReturnTy = Fun->getReturnType();
1953
80
      return true;
1954
80
    }
1955
59
  }
1956
59
1957
59
  // We don't have an expression that's convenient to get a FunctionDecl from,
1958
59
  // but we can at least check if the type is "function of 0 arguments".
1959
59
  QualType ExprTy = E.getType();
1960
59
  const FunctionType *FunTy = nullptr;
1961
59
  QualType PointeeTy = ExprTy->getPointeeType();
1962
59
  if (!PointeeTy.isNull())
1963
22
    FunTy = PointeeTy->getAs<FunctionType>();
1964
59
  if (!FunTy)
1965
59
    FunTy = ExprTy->getAs<FunctionType>();
1966
59
1967
59
  if (const FunctionProtoType *FPT =
1968
6
      dyn_cast_or_null<FunctionProtoType>(FunTy)) {
1969
6
    if (FPT->getNumParams() == 0)
1970
0
      ZeroArgCallReturnTy = FunTy->getReturnType();
1971
6
    return true;
1972
6
  }
1973
53
  return false;
1974
53
}
1975
1976
/// Give notes for a set of overloads.
1977
///
1978
/// A companion to tryExprAsCall. In cases when the name that the programmer
1979
/// wrote was an overloaded function, we may be able to make some guesses about
1980
/// plausible overloads based on their return types; such guesses can be handed
1981
/// off to this method to be emitted as notes.
1982
///
1983
/// \param Overloads - The overloads to note.
1984
/// \param FinalNoteLoc - If we've suppressed printing some overloads due to
1985
///  -fshow-overloads=best, this is the location to attach to the note about too
1986
///  many candidates. Typically this will be the location of the original
1987
///  ill-formed expression.
1988
static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
1989
175
                          const SourceLocation FinalNoteLoc) {
1990
175
  int ShownOverloads = 0;
1991
175
  int SuppressedOverloads = 0;
1992
175
  for (UnresolvedSetImpl::iterator It = Overloads.begin(),
1993
329
       DeclsEnd = Overloads.end(); It != DeclsEnd; 
++It154
) {
1994
154
    // FIXME: Magic number for max shown overloads stolen from
1995
154
    // OverloadCandidateSet::NoteCandidates.
1996
154
    if (ShownOverloads >= 4 && 
S.Diags.getShowOverloads() == Ovl_Best0
) {
1997
0
      ++SuppressedOverloads;
1998
0
      continue;
1999
0
    }
2000
154
2001
154
    NamedDecl *Fn = (*It)->getUnderlyingDecl();
2002
154
    // Don't print overloads for non-default multiversioned functions.
2003
154
    if (const auto *FD = Fn->getAsFunction()) {
2004
154
      if (FD->isMultiVersion() && 
FD->hasAttr<TargetAttr>()2
&&
2005
154
          
!FD->getAttr<TargetAttr>()->isDefaultVersion()2
)
2006
1
        continue;
2007
153
    }
2008
153
    S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
2009
153
    ++ShownOverloads;
2010
153
  }
2011
175
2012
175
  if (SuppressedOverloads)
2013
0
    S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
2014
0
      << SuppressedOverloads;
2015
175
}
2016
2017
static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
2018
                                   const UnresolvedSetImpl &Overloads,
2019
175
                                   bool (*IsPlausibleResult)(QualType)) {
2020
175
  if (!IsPlausibleResult)
2021
164
    return noteOverloads(S, Overloads, Loc);
2022
11
2023
11
  UnresolvedSet<2> PlausibleOverloads;
2024
11
  for (OverloadExpr::decls_iterator It = Overloads.begin(),
2025
11
         DeclsEnd = Overloads.end(); It != DeclsEnd; 
++It0
) {
2026
0
    const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
2027
0
    QualType OverloadResultTy = OverloadDecl->getReturnType();
2028
0
    if (IsPlausibleResult(OverloadResultTy))
2029
0
      PlausibleOverloads.addDecl(It.getDecl());
2030
0
  }
2031
11
  noteOverloads(S, PlausibleOverloads, Loc);
2032
11
}
2033
2034
/// Determine whether the given expression can be called by just
2035
/// putting parentheses after it.  Notably, expressions with unary
2036
/// operators can't be because the unary operator will start parsing
2037
/// outside the call.
2038
102
static bool IsCallableWithAppend(Expr *E) {
2039
102
  E = E->IgnoreImplicit();
2040
102
  return (!isa<CStyleCastExpr>(E) &&
2041
102
          !isa<UnaryOperator>(E) &&
2042
102
          
!isa<BinaryOperator>(E)99
&&
2043
102
          
!isa<CXXOperatorCallExpr>(E)93
);
2044
102
}
2045
2046
181
static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E) {
2047
181
  if (const auto *UO = dyn_cast<UnaryOperator>(E))
2048
20
    E = UO->getSubExpr();
2049
181
2050
181
  if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2051
64
    if (ULE->getNumDecls() == 0)
2052
1
      return false;
2053
63
2054
63
    const NamedDecl *ND = *ULE->decls_begin();
2055
63
    if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2056
37
      return FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion();
2057
143
  }
2058
143
  return false;
2059
143
}
2060
2061
bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
2062
                                bool ForceComplain,
2063
231
                                bool (*IsPlausibleResult)(QualType)) {
2064
231
  SourceLocation Loc = E.get()->getExprLoc();
2065
231
  SourceRange Range = E.get()->getSourceRange();
2066
231
2067
231
  QualType ZeroArgCallTy;
2068
231
  UnresolvedSet<4> Overloads;
2069
231
  if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
2070
231
      
!ZeroArgCallTy.isNull()102
&&
2071
231
      
(102
!IsPlausibleResult102
||
IsPlausibleResult(ZeroArgCallTy)11
)) {
2072
102
    // At this point, we know E is potentially callable with 0
2073
102
    // arguments and that it returns something of a reasonable type,
2074
102
    // so we can emit a fixit and carry on pretending that E was
2075
102
    // actually a CallExpr.
2076
102
    SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
2077
102
    bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
2078
102
    Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range
2079
102
                  << (IsCallableWithAppend(E.get())
2080
102
                          ? 
FixItHint::CreateInsertion(ParenInsertionLoc, "()")93
2081
102
                          : 
FixItHint()9
);
2082
102
    if (!IsMV)
2083
98
      notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2084
102
2085
102
    // FIXME: Try this before emitting the fixit, and suppress diagnostics
2086
102
    // while doing so.
2087
102
    E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), None,
2088
102
                      Range.getEnd().getLocWithOffset(1));
2089
102
    return true;
2090
102
  }
2091
129
2092
129
  if (!ForceComplain) 
return false50
;
2093
79
2094
79
  bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
2095
79
  Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;
2096
79
  if (!IsMV)
2097
77
    notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2098
79
  E = ExprError();
2099
79
  return true;
2100
79
}
2101
2102
79
IdentifierInfo *Sema::getSuperIdentifier() const {
2103
79
  if (!Ident_super)
2104
34
    Ident_super = &Context.Idents.get("super");
2105
79
  return Ident_super;
2106
79
}
2107
2108
0
IdentifierInfo *Sema::getFloat128Identifier() const {
2109
0
  if (!Ident___float128)
2110
0
    Ident___float128 = &Context.Idents.get("__float128");
2111
0
  return Ident___float128;
2112
0
}
2113
2114
void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
2115
295k
                                   CapturedRegionKind K) {
2116
295k
  CapturingScopeInfo *CSI = new CapturedRegionScopeInfo(
2117
295k
      getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
2118
295k
      (getLangOpts().OpenMP && 
K == CR_OpenMP295k
) ?
getOpenMPNestingLevel()295k
:
074
);
2119
295k
  CSI->ReturnType = Context.VoidTy;
2120
295k
  FunctionScopes.push_back(CSI);
2121
295k
}
2122
2123
301k
CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
2124
301k
  if (FunctionScopes.empty())
2125
355
    return nullptr;
2126
301k
2127
301k
  return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
2128
301k
}
2129
2130
const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
2131
2.13k
Sema::getMismatchingDeleteExpressions() const {
2132
2.13k
  return DeleteExprs;
2133
2.13k
}
2134
2135
27.5k
void Sema::setOpenCLExtensionForType(QualType T, llvm::StringRef ExtStr) {
2136
27.5k
  if (ExtStr.empty())
2137
12.3k
    return;
2138
15.2k
  llvm::SmallVector<StringRef, 1> Exts;
2139
15.2k
  ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
2140
15.2k
  auto CanT = T.getCanonicalType().getTypePtr();
2141
15.2k
  for (auto &I : Exts)
2142
16.3k
    OpenCLTypeExtMap[CanT].insert(I.str());
2143
15.2k
}
2144
2145
1.58k
void Sema::setOpenCLExtensionForDecl(Decl *FD, StringRef ExtStr) {
2146
1.58k
  llvm::SmallVector<StringRef, 1> Exts;
2147
1.58k
  ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
2148
1.58k
  if (Exts.empty())
2149
0
    return;
2150
1.58k
  for (auto &I : Exts)
2151
1.58k
    OpenCLDeclExtMap[FD].insert(I.str());
2152
1.58k
}
2153
2154
0
void Sema::setCurrentOpenCLExtensionForType(QualType T) {
2155
0
  if (CurrOpenCLExtension.empty())
2156
0
    return;
2157
0
  setOpenCLExtensionForType(T, CurrOpenCLExtension);
2158
0
}
2159
2160
252k
void Sema::setCurrentOpenCLExtensionForDecl(Decl *D) {
2161
252k
  if (CurrOpenCLExtension.empty())
2162
251k
    return;
2163
1.58k
  setOpenCLExtensionForDecl(D, CurrOpenCLExtension);
2164
1.58k
}
2165
2166
12
std::string Sema::getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD) {
2167
12
  if (!OpenCLDeclExtMap.empty())
2168
12
    return getOpenCLExtensionsFromExtMap(FD, OpenCLDeclExtMap);
2169
0
2170
0
  return "";
2171
0
}
2172
2173
0
std::string Sema::getOpenCLExtensionsFromTypeExtMap(FunctionType *FT) {
2174
0
  if (!OpenCLTypeExtMap.empty())
2175
0
    return getOpenCLExtensionsFromExtMap(FT, OpenCLTypeExtMap);
2176
0
2177
0
  return "";
2178
0
}
2179
2180
template <typename T, typename MapT>
2181
12
std::string Sema::getOpenCLExtensionsFromExtMap(T *FDT, MapT &Map) {
2182
12
  std::string ExtensionNames = "";
2183
12
  auto Loc = Map.find(FDT);
2184
12
2185
12
  for (auto const& I : Loc->second) {
2186
12
    ExtensionNames += I;
2187
12
    ExtensionNames += " ";
2188
12
  }
2189
12
  ExtensionNames.pop_back();
2190
12
2191
12
  return ExtensionNames;
2192
12
}
std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > clang::Sema::getOpenCLExtensionsFromExtMap<clang::FunctionDecl, llvm::DenseMap<clang::Decl const*, std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >, llvm::DenseMapInfo<clang::Decl const*>, llvm::detail::DenseMapPair<clang::Decl const*, std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > > > >(clang::FunctionDecl*, llvm::DenseMap<clang::Decl const*, std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >, llvm::DenseMapInfo<clang::Decl const*>, llvm::detail::DenseMapPair<clang::Decl const*, std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > > >&)
Line
Count
Source
2181
12
std::string Sema::getOpenCLExtensionsFromExtMap(T *FDT, MapT &Map) {
2182
12
  std::string ExtensionNames = "";
2183
12
  auto Loc = Map.find(FDT);
2184
12
2185
12
  for (auto const& I : Loc->second) {
2186
12
    ExtensionNames += I;
2187
12
    ExtensionNames += " ";
2188
12
  }
2189
12
  ExtensionNames.pop_back();
2190
12
2191
12
  return ExtensionNames;
2192
12
}
Unexecuted instantiation: std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > clang::Sema::getOpenCLExtensionsFromExtMap<clang::FunctionType, llvm::DenseMap<clang::Type const*, std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >, llvm::DenseMapInfo<clang::Type const*>, llvm::detail::DenseMapPair<clang::Type const*, std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > > > >(clang::FunctionType*, llvm::DenseMap<clang::Type const*, std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >, llvm::DenseMapInfo<clang::Type const*>, llvm::detail::DenseMapPair<clang::Type const*, std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > > >&)
2193
2194
600
bool Sema::isOpenCLDisabledDecl(Decl *FD) {
2195
600
  auto Loc = OpenCLDeclExtMap.find(FD);
2196
600
  if (Loc == OpenCLDeclExtMap.end())
2197
574
    return false;
2198
26
  for (auto &I : Loc->second) {
2199
26
    if (!getOpenCLOptions().isEnabled(I))
2200
13
      return true;
2201
26
  }
2202
26
  
return false13
;
2203
26
}
2204
2205
template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
2206
bool Sema::checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc,
2207
                                         DiagInfoT DiagInfo, MapT &Map,
2208
                                         unsigned Selector,
2209
841k
                                         SourceRange SrcRange) {
2210
841k
  auto Loc = Map.find(D);
2211
841k
  if (Loc == Map.end())
2212
777k
    return false;
2213
63.9k
  bool Disabled = false;
2214
65.7k
  for (auto &I : Loc->second) {
2215
65.7k
    if (I != CurrOpenCLExtension && 
!getOpenCLOptions().isEnabled(I)63.5k
) {
2216
94
      Diag(DiagLoc, diag::err_opencl_requires_extension) << Selector << DiagInfo
2217
94
                                                         << I << SrcRange;
2218
94
      Disabled = true;
2219
94
    }
2220
65.7k
  }
2221
63.9k
  return Disabled;
2222
63.9k
}
bool clang::Sema::checkOpenCLDisabledTypeOrDecl<clang::Type const*, clang::SourceLocation, clang::QualType, llvm::DenseMap<clang::Type const*, std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >, llvm::DenseMapInfo<clang::Type const*>, llvm::detail::DenseMapPair<clang::Type const*, std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > > > >(clang::Type const*, clang::SourceLocation, clang::QualType, llvm::DenseMap<clang::Type const*, std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >, llvm::DenseMapInfo<clang::Type const*>, llvm::detail::DenseMapPair<clang::Type const*, std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > > >&, unsigned int, clang::SourceRange)
Line
Count
Source
2209
639k
                                         SourceRange SrcRange) {
2210
639k
  auto Loc = Map.find(D);
2211
639k
  if (Loc == Map.end())
2212
575k
    return false;
2213
63.8k
  bool Disabled = false;
2214
65.6k
  for (auto &I : Loc->second) {
2215
65.6k
    if (I != CurrOpenCLExtension && 
!getOpenCLOptions().isEnabled(I)63.4k
) {
2216
72
      Diag(DiagLoc, diag::err_opencl_requires_extension) << Selector << DiagInfo
2217
72
                                                         << I << SrcRange;
2218
72
      Disabled = true;
2219
72
    }
2220
65.6k
  }
2221
63.8k
  return Disabled;
2222
63.8k
}
bool clang::Sema::checkOpenCLDisabledTypeOrDecl<clang::Decl*, clang::SourceLocation, clang::QualType, llvm::DenseMap<clang::Decl const*, std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >, llvm::DenseMapInfo<clang::Decl const*>, llvm::detail::DenseMapPair<clang::Decl const*, std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > > > >(clang::Decl*, clang::SourceLocation, clang::QualType, llvm::DenseMap<clang::Decl const*, std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >, llvm::DenseMapInfo<clang::Decl const*>, llvm::detail::DenseMapPair<clang::Decl const*, std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > > >&, unsigned int, clang::SourceRange)
Line
Count
Source
2209
199k
                                         SourceRange SrcRange) {
2210
199k
  auto Loc = Map.find(D);
2211
199k
  if (Loc == Map.end())
2212
199k
    return false;
2213
28
  bool Disabled = false;
2214
28
  for (auto &I : Loc->second) {
2215
28
    if (I != CurrOpenCLExtension && 
!getOpenCLOptions().isEnabled(I)20
) {
2216
16
      Diag(DiagLoc, diag::err_opencl_requires_extension) << Selector << DiagInfo
2217
16
                                                         << I << SrcRange;
2218
16
      Disabled = true;
2219
16
    }
2220
28
  }
2221
28
  return Disabled;
2222
28
}
bool clang::Sema::checkOpenCLDisabledTypeOrDecl<clang::NamedDecl const*, clang::SourceLocation, clang::IdentifierInfo*, llvm::DenseMap<clang::Decl const*, std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >, llvm::DenseMapInfo<clang::Decl const*>, llvm::detail::DenseMapPair<clang::Decl const*, std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > > > >(clang::NamedDecl const*, clang::SourceLocation, clang::IdentifierInfo*, llvm::DenseMap<clang::Decl const*, std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >, llvm::DenseMapInfo<clang::Decl const*>, llvm::detail::DenseMapPair<clang::Decl const*, std::__1::set<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > > >&, unsigned int, clang::SourceRange)
Line
Count
Source
2209
2.09k
                                         SourceRange SrcRange) {
2210
2.09k
  auto Loc = Map.find(D);
2211
2.09k
  if (Loc == Map.end())
2212
2.08k
    return false;
2213
12
  bool Disabled = false;
2214
12
  for (auto &I : Loc->second) {
2215
12
    if (I != CurrOpenCLExtension && !getOpenCLOptions().isEnabled(I)) {
2216
6
      Diag(DiagLoc, diag::err_opencl_requires_extension) << Selector << DiagInfo
2217
6
                                                         << I << SrcRange;
2218
6
      Disabled = true;
2219
6
    }
2220
12
  }
2221
12
  return Disabled;
2222
12
}
2223
2224
639k
bool Sema::checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType QT) {
2225
639k
  // Check extensions for declared types.
2226
639k
  Decl *Decl = nullptr;
2227
639k
  if (auto TypedefT = dyn_cast<TypedefType>(QT.getTypePtr()))
2228
522k
    Decl = TypedefT->getDecl();
2229
639k
  if (auto TagT = dyn_cast<TagType>(QT.getCanonicalType().getTypePtr()))
2230
4.23k
    Decl = TagT->getDecl();
2231
639k
  auto Loc = DS.getTypeSpecTypeLoc();
2232
639k
2233
639k
  // Check extensions for vector types.
2234
639k
  // e.g. double4 is not allowed when cl_khr_fp64 is absent.
2235
639k
  if (QT->isExtVectorType()) {
2236
440k
    auto TypePtr = QT->castAs<ExtVectorType>()->getElementType().getTypePtr();
2237
440k
    return checkOpenCLDisabledTypeOrDecl(TypePtr, Loc, QT, OpenCLTypeExtMap);
2238
440k
  }
2239
199k
2240
199k
  if (checkOpenCLDisabledTypeOrDecl(Decl, Loc, QT, OpenCLDeclExtMap))
2241
16
    return true;
2242
199k
2243
199k
  // Check extensions for builtin types.
2244
199k
  return checkOpenCLDisabledTypeOrDecl(QT.getCanonicalType().getTypePtr(), Loc,
2245
199k
                                       QT, OpenCLTypeExtMap);
2246
199k
}
2247
2248
2.09k
bool Sema::checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E) {
2249
2.09k
  IdentifierInfo *FnName = D.getIdentifier();
2250
2.09k
  return checkOpenCLDisabledTypeOrDecl(&D, E.getBeginLoc(), FnName,
2251
2.09k
                                       OpenCLDeclExtMap, 1, D.getSourceRange());
2252
2.09k
}