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