xref: /llvm-project-15.0.7/clang/lib/Sema/Sema.cpp (revision 28331ae6)
1 //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the actions class which performs semantic analysis and
11 // builds an AST out of a parse stream.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/Sema/SemaInternal.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTDiagnostic.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/StmtCXX.h"
24 #include "clang/Basic/FileManager.h"
25 #include "clang/Basic/PartialDiagnostic.h"
26 #include "clang/Basic/TargetInfo.h"
27 #include "clang/Lex/HeaderSearch.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Sema/CXXFieldCollector.h"
30 #include "clang/Sema/DelayedDiagnostic.h"
31 #include "clang/Sema/ExternalSemaSource.h"
32 #include "clang/Sema/MultiplexExternalSemaSource.h"
33 #include "clang/Sema/ObjCMethodList.h"
34 #include "clang/Sema/PrettyDeclStackTrace.h"
35 #include "clang/Sema/Scope.h"
36 #include "clang/Sema/ScopeInfo.h"
37 #include "clang/Sema/SemaConsumer.h"
38 #include "clang/Sema/TemplateDeduction.h"
39 #include "llvm/ADT/APFloat.h"
40 #include "llvm/ADT/DenseMap.h"
41 #include "llvm/ADT/SmallSet.h"
42 #include "llvm/Support/CrashRecoveryContext.h"
43 using namespace clang;
44 using namespace sema;
45 
46 PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
47                                        const Preprocessor &PP) {
48   PrintingPolicy Policy = Context.getPrintingPolicy();
49   Policy.Bool = Context.getLangOpts().Bool;
50   if (!Policy.Bool) {
51     if (const MacroInfo *
52           BoolMacro = PP.getMacroInfo(&Context.Idents.get("bool"))) {
53       Policy.Bool = BoolMacro->isObjectLike() &&
54         BoolMacro->getNumTokens() == 1 &&
55         BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
56     }
57   }
58 
59   return Policy;
60 }
61 
62 void Sema::ActOnTranslationUnitScope(Scope *S) {
63   TUScope = S;
64   PushDeclContext(S, Context.getTranslationUnitDecl());
65 
66   VAListTagName = PP.getIdentifierInfo("__va_list_tag");
67 }
68 
69 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
70            TranslationUnitKind TUKind,
71            CodeCompleteConsumer *CodeCompleter)
72   : ExternalSource(0),
73     isMultiplexExternalSource(false), FPFeatures(pp.getLangOpts()),
74     LangOpts(pp.getLangOpts()), PP(pp), Context(ctxt), Consumer(consumer),
75     Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
76     CollectStats(false), CodeCompleter(CodeCompleter),
77     CurContext(0), OriginalLexicalContext(0),
78     PackContext(0), MSStructPragmaOn(false),
79     MSPointerToMemberRepresentationMethod(
80         LangOpts.getMSPointerToMemberRepresentationMethod()),
81     VtorDispModeStack(1, MSVtorDispAttr::Mode(LangOpts.VtorDispMode)),
82     DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
83     CodeSegStack(nullptr), VisContext(0),
84     IsBuildingRecoveryCallExpr(false),
85     ExprNeedsCleanups(false), LateTemplateParser(0), OpaqueParser(0),
86     IdResolver(pp), StdInitializerList(0), CXXTypeInfoDecl(0), MSVCGuidDecl(0),
87     NSNumberDecl(0),
88     NSStringDecl(0), StringWithUTF8StringMethod(0),
89     NSArrayDecl(0), ArrayWithObjectsMethod(0),
90     NSDictionaryDecl(0), DictionaryWithObjectsMethod(0),
91     GlobalNewDeleteDeclared(false),
92     TUKind(TUKind),
93     NumSFINAEErrors(0),
94     AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
95     NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
96     CurrentInstantiationScope(0), DisableTypoCorrection(false),
97     TyposCorrected(0), AnalysisWarnings(*this),
98     VarDataSharingAttributesStack(0), CurScope(0),
99     Ident_super(0), Ident___float128(0)
100 {
101   TUScope = 0;
102 
103   LoadedExternalKnownNamespaces = false;
104   for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
105     NSNumberLiteralMethods[I] = 0;
106 
107   if (getLangOpts().ObjC1)
108     NSAPIObj.reset(new NSAPI(Context));
109 
110   if (getLangOpts().CPlusPlus)
111     FieldCollector.reset(new CXXFieldCollector());
112 
113   // Tell diagnostics how to render things from the AST library.
114   PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
115                                        &Context);
116 
117   ExprEvalContexts.push_back(
118         ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0,
119                                           false, 0, false));
120 
121   FunctionScopes.push_back(new FunctionScopeInfo(Diags));
122 
123   // Initilization of data sharing attributes stack for OpenMP
124   InitDataSharingAttributesStack();
125 }
126 
127 void Sema::addImplicitTypedef(StringRef Name, QualType T) {
128   DeclarationName DN = &Context.Idents.get(Name);
129   if (IdResolver.begin(DN) == IdResolver.end())
130     PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
131 }
132 
133 void Sema::Initialize() {
134   // Tell the AST consumer about this Sema object.
135   Consumer.Initialize(Context);
136 
137   // FIXME: Isn't this redundant with the initialization above?
138   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
139     SC->InitializeSema(*this);
140 
141   // Tell the external Sema source about this Sema object.
142   if (ExternalSemaSource *ExternalSema
143       = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
144     ExternalSema->InitializeSema(*this);
145 
146   // Initialize predefined 128-bit integer types, if needed.
147   if (PP.getTargetInfo().hasInt128Type()) {
148     // If either of the 128-bit integer types are unavailable to name lookup,
149     // define them now.
150     DeclarationName Int128 = &Context.Idents.get("__int128_t");
151     if (IdResolver.begin(Int128) == IdResolver.end())
152       PushOnScopeChains(Context.getInt128Decl(), TUScope);
153 
154     DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
155     if (IdResolver.begin(UInt128) == IdResolver.end())
156       PushOnScopeChains(Context.getUInt128Decl(), TUScope);
157   }
158 
159 
160   // Initialize predefined Objective-C types:
161   if (PP.getLangOpts().ObjC1) {
162     // If 'SEL' does not yet refer to any declarations, make it refer to the
163     // predefined 'SEL'.
164     DeclarationName SEL = &Context.Idents.get("SEL");
165     if (IdResolver.begin(SEL) == IdResolver.end())
166       PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
167 
168     // If 'id' does not yet refer to any declarations, make it refer to the
169     // predefined 'id'.
170     DeclarationName Id = &Context.Idents.get("id");
171     if (IdResolver.begin(Id) == IdResolver.end())
172       PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
173 
174     // Create the built-in typedef for 'Class'.
175     DeclarationName Class = &Context.Idents.get("Class");
176     if (IdResolver.begin(Class) == IdResolver.end())
177       PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
178 
179     // Create the built-in forward declaratino for 'Protocol'.
180     DeclarationName Protocol = &Context.Idents.get("Protocol");
181     if (IdResolver.begin(Protocol) == IdResolver.end())
182       PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
183   }
184 
185   // Initialize Microsoft "predefined C++ types".
186   if (PP.getLangOpts().MSVCCompat && PP.getLangOpts().CPlusPlus) {
187     if (IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
188       PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
189                         TUScope);
190 
191     addImplicitTypedef("size_t", Context.getSizeType());
192   }
193 
194   // Initialize predefined OpenCL types.
195   if (PP.getLangOpts().OpenCL) {
196     addImplicitTypedef("image1d_t", Context.OCLImage1dTy);
197     addImplicitTypedef("image1d_array_t", Context.OCLImage1dArrayTy);
198     addImplicitTypedef("image1d_buffer_t", Context.OCLImage1dBufferTy);
199     addImplicitTypedef("image2d_t", Context.OCLImage2dTy);
200     addImplicitTypedef("image2d_array_t", Context.OCLImage2dArrayTy);
201     addImplicitTypedef("image3d_t", Context.OCLImage3dTy);
202     addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
203     addImplicitTypedef("event_t", Context.OCLEventTy);
204   }
205 
206   DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
207   if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
208     PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
209 }
210 
211 Sema::~Sema() {
212   llvm::DeleteContainerSeconds(LateParsedTemplateMap);
213   if (PackContext) FreePackedContext();
214   if (VisContext) FreeVisContext();
215   // Kill all the active scopes.
216   for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
217     delete FunctionScopes[I];
218   if (FunctionScopes.size() == 1)
219     delete FunctionScopes[0];
220 
221   // Tell the SemaConsumer to forget about us; we're going out of scope.
222   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
223     SC->ForgetSema();
224 
225   // Detach from the external Sema source.
226   if (ExternalSemaSource *ExternalSema
227         = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
228     ExternalSema->ForgetSema();
229 
230   // If Sema's ExternalSource is the multiplexer - we own it.
231   if (isMultiplexExternalSource)
232     delete ExternalSource;
233 
234   // Destroys data sharing attributes stack for OpenMP
235   DestroyDataSharingAttributesStack();
236 }
237 
238 /// makeUnavailableInSystemHeader - There is an error in the current
239 /// context.  If we're still in a system header, and we can plausibly
240 /// make the relevant declaration unavailable instead of erroring, do
241 /// so and return true.
242 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
243                                          StringRef msg) {
244   // If we're not in a function, it's an error.
245   FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
246   if (!fn) return false;
247 
248   // If we're in template instantiation, it's an error.
249   if (!ActiveTemplateInstantiations.empty())
250     return false;
251 
252   // If that function's not in a system header, it's an error.
253   if (!Context.getSourceManager().isInSystemHeader(loc))
254     return false;
255 
256   // If the function is already unavailable, it's not an error.
257   if (fn->hasAttr<UnavailableAttr>()) return true;
258 
259   fn->addAttr(UnavailableAttr::CreateImplicit(Context, msg, loc));
260   return true;
261 }
262 
263 ASTMutationListener *Sema::getASTMutationListener() const {
264   return getASTConsumer().GetASTMutationListener();
265 }
266 
267 ///\brief Registers an external source. If an external source already exists,
268 /// creates a multiplex external source and appends to it.
269 ///
270 ///\param[in] E - A non-null external sema source.
271 ///
272 void Sema::addExternalSource(ExternalSemaSource *E) {
273   assert(E && "Cannot use with NULL ptr");
274 
275   if (!ExternalSource) {
276     ExternalSource = E;
277     return;
278   }
279 
280   if (isMultiplexExternalSource)
281     static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
282   else {
283     ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
284     isMultiplexExternalSource = true;
285   }
286 }
287 
288 /// \brief Print out statistics about the semantic analysis.
289 void Sema::PrintStats() const {
290   llvm::errs() << "\n*** Semantic Analysis Stats:\n";
291   llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
292 
293   BumpAlloc.PrintStats();
294   AnalysisWarnings.PrintStats();
295 }
296 
297 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
298 /// If there is already an implicit cast, merge into the existing one.
299 /// The result is of the given category.
300 ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
301                                    CastKind Kind, ExprValueKind VK,
302                                    const CXXCastPath *BasePath,
303                                    CheckedConversionKind CCK) {
304 #ifndef NDEBUG
305   if (VK == VK_RValue && !E->isRValue()) {
306     switch (Kind) {
307     default:
308       assert(0 && "can't implicitly cast lvalue to rvalue with this cast kind");
309     case CK_LValueToRValue:
310     case CK_ArrayToPointerDecay:
311     case CK_FunctionToPointerDecay:
312     case CK_ToVoid:
313       break;
314     }
315   }
316   assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue");
317 #endif
318 
319   QualType ExprTy = Context.getCanonicalType(E->getType());
320   QualType TypeTy = Context.getCanonicalType(Ty);
321 
322   if (ExprTy == TypeTy)
323     return Owned(E);
324 
325   // If this is a derived-to-base cast to a through a virtual base, we
326   // need a vtable.
327   if (Kind == CK_DerivedToBase &&
328       BasePathInvolvesVirtualBase(*BasePath)) {
329     QualType T = E->getType();
330     if (const PointerType *Pointer = T->getAs<PointerType>())
331       T = Pointer->getPointeeType();
332     if (const RecordType *RecordTy = T->getAs<RecordType>())
333       MarkVTableUsed(E->getLocStart(),
334                      cast<CXXRecordDecl>(RecordTy->getDecl()));
335   }
336 
337   if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
338     if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
339       ImpCast->setType(Ty);
340       ImpCast->setValueKind(VK);
341       return Owned(E);
342     }
343   }
344 
345   return Owned(ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK));
346 }
347 
348 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
349 /// to the conversion from scalar type ScalarTy to the Boolean type.
350 CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
351   switch (ScalarTy->getScalarTypeKind()) {
352   case Type::STK_Bool: return CK_NoOp;
353   case Type::STK_CPointer: return CK_PointerToBoolean;
354   case Type::STK_BlockPointer: return CK_PointerToBoolean;
355   case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
356   case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
357   case Type::STK_Integral: return CK_IntegralToBoolean;
358   case Type::STK_Floating: return CK_FloatingToBoolean;
359   case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
360   case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
361   }
362   return CK_Invalid;
363 }
364 
365 /// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
366 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
367   if (D->getMostRecentDecl()->isUsed())
368     return true;
369 
370   if (D->isExternallyVisible())
371     return true;
372 
373   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
374     // UnusedFileScopedDecls stores the first declaration.
375     // The declaration may have become definition so check again.
376     const FunctionDecl *DeclToCheck;
377     if (FD->hasBody(DeclToCheck))
378       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
379 
380     // Later redecls may add new information resulting in not having to warn,
381     // so check again.
382     DeclToCheck = FD->getMostRecentDecl();
383     if (DeclToCheck != FD)
384       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
385   }
386 
387   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
388     // If a variable usable in constant expressions is referenced,
389     // don't warn if it isn't used: if the value of a variable is required
390     // for the computation of a constant expression, it doesn't make sense to
391     // warn even if the variable isn't odr-used.  (isReferenced doesn't
392     // precisely reflect that, but it's a decent approximation.)
393     if (VD->isReferenced() &&
394         VD->isUsableInConstantExpressions(SemaRef->Context))
395       return true;
396 
397     // UnusedFileScopedDecls stores the first declaration.
398     // The declaration may have become definition so check again.
399     const VarDecl *DeclToCheck = VD->getDefinition();
400     if (DeclToCheck)
401       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
402 
403     // Later redecls may add new information resulting in not having to warn,
404     // so check again.
405     DeclToCheck = VD->getMostRecentDecl();
406     if (DeclToCheck != VD)
407       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
408   }
409 
410   return false;
411 }
412 
413 /// Obtains a sorted list of functions that are undefined but ODR-used.
414 void Sema::getUndefinedButUsed(
415     SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
416   for (llvm::DenseMap<NamedDecl *, SourceLocation>::iterator
417          I = UndefinedButUsed.begin(), E = UndefinedButUsed.end();
418        I != E; ++I) {
419     NamedDecl *ND = I->first;
420 
421     // Ignore attributes that have become invalid.
422     if (ND->isInvalidDecl()) continue;
423 
424     // __attribute__((weakref)) is basically a definition.
425     if (ND->hasAttr<WeakRefAttr>()) continue;
426 
427     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
428       if (FD->isDefined())
429         continue;
430       if (FD->isExternallyVisible() &&
431           !FD->getMostRecentDecl()->isInlined())
432         continue;
433     } else {
434       if (cast<VarDecl>(ND)->hasDefinition() != VarDecl::DeclarationOnly)
435         continue;
436       if (ND->isExternallyVisible())
437         continue;
438     }
439 
440     Undefined.push_back(std::make_pair(ND, I->second));
441   }
442 
443   // Sort (in order of use site) so that we're not dependent on the iteration
444   // order through an llvm::DenseMap.
445   SourceManager &SM = Context.getSourceManager();
446   std::sort(Undefined.begin(), Undefined.end(),
447             [&SM](const std::pair<NamedDecl *, SourceLocation> &l,
448                   const std::pair<NamedDecl *, SourceLocation> &r) {
449     if (l.second.isValid() && !r.second.isValid())
450       return true;
451     if (!l.second.isValid() && r.second.isValid())
452       return false;
453     if (l.second != r.second)
454       return SM.isBeforeInTranslationUnit(l.second, r.second);
455     return SM.isBeforeInTranslationUnit(l.first->getLocation(),
456                                         r.first->getLocation());
457   });
458 }
459 
460 /// checkUndefinedButUsed - Check for undefined objects with internal linkage
461 /// or that are inline.
462 static void checkUndefinedButUsed(Sema &S) {
463   if (S.UndefinedButUsed.empty()) return;
464 
465   // Collect all the still-undefined entities with internal linkage.
466   SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
467   S.getUndefinedButUsed(Undefined);
468   if (Undefined.empty()) return;
469 
470   for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
471          I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
472     NamedDecl *ND = I->first;
473 
474     if (!ND->isExternallyVisible()) {
475       S.Diag(ND->getLocation(), diag::warn_undefined_internal)
476         << isa<VarDecl>(ND) << ND;
477     } else {
478       assert(cast<FunctionDecl>(ND)->getMostRecentDecl()->isInlined() &&
479              "used object requires definition but isn't inline or internal?");
480       S.Diag(ND->getLocation(), diag::warn_undefined_inline) << ND;
481     }
482     if (I->second.isValid())
483       S.Diag(I->second, diag::note_used_here);
484   }
485 }
486 
487 void Sema::LoadExternalWeakUndeclaredIdentifiers() {
488   if (!ExternalSource)
489     return;
490 
491   SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
492   ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
493   for (unsigned I = 0, N = WeakIDs.size(); I != N; ++I) {
494     llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator Pos
495       = WeakUndeclaredIdentifiers.find(WeakIDs[I].first);
496     if (Pos != WeakUndeclaredIdentifiers.end())
497       continue;
498 
499     WeakUndeclaredIdentifiers.insert(WeakIDs[I]);
500   }
501 }
502 
503 
504 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
505 
506 /// \brief Returns true, if all methods and nested classes of the given
507 /// CXXRecordDecl are defined in this translation unit.
508 ///
509 /// Should only be called from ActOnEndOfTranslationUnit so that all
510 /// definitions are actually read.
511 static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
512                                             RecordCompleteMap &MNCComplete) {
513   RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
514   if (Cache != MNCComplete.end())
515     return Cache->second;
516   if (!RD->isCompleteDefinition())
517     return false;
518   bool Complete = true;
519   for (DeclContext::decl_iterator I = RD->decls_begin(),
520                                   E = RD->decls_end();
521        I != E && Complete; ++I) {
522     if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
523       Complete = M->isDefined() || (M->isPure() && !isa<CXXDestructorDecl>(M));
524     else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
525       Complete = F->getTemplatedDecl()->isDefined();
526     else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
527       if (R->isInjectedClassName())
528         continue;
529       if (R->hasDefinition())
530         Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
531                                                    MNCComplete);
532       else
533         Complete = false;
534     }
535   }
536   MNCComplete[RD] = Complete;
537   return Complete;
538 }
539 
540 /// \brief Returns true, if the given CXXRecordDecl is fully defined in this
541 /// translation unit, i.e. all methods are defined or pure virtual and all
542 /// friends, friend functions and nested classes are fully defined in this
543 /// translation unit.
544 ///
545 /// Should only be called from ActOnEndOfTranslationUnit so that all
546 /// definitions are actually read.
547 static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
548                                  RecordCompleteMap &RecordsComplete,
549                                  RecordCompleteMap &MNCComplete) {
550   RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
551   if (Cache != RecordsComplete.end())
552     return Cache->second;
553   bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
554   for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
555                                       E = RD->friend_end();
556        I != E && Complete; ++I) {
557     // Check if friend classes and methods are complete.
558     if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
559       // Friend classes are available as the TypeSourceInfo of the FriendDecl.
560       if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
561         Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
562       else
563         Complete = false;
564     } else {
565       // Friend functions are available through the NamedDecl of FriendDecl.
566       if (const FunctionDecl *FD =
567           dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
568         Complete = FD->isDefined();
569       else
570         // This is a template friend, give up.
571         Complete = false;
572     }
573   }
574   RecordsComplete[RD] = Complete;
575   return Complete;
576 }
577 
578 /// ActOnEndOfTranslationUnit - This is called at the very end of the
579 /// translation unit when EOF is reached and all but the top-level scope is
580 /// popped.
581 void Sema::ActOnEndOfTranslationUnit() {
582   assert(DelayedDiagnostics.getCurrentPool() == NULL
583          && "reached end of translation unit with a pool attached?");
584 
585   // If code completion is enabled, don't perform any end-of-translation-unit
586   // work.
587   if (PP.isCodeCompletionEnabled())
588     return;
589 
590   // Complete translation units and modules define vtables and perform implicit
591   // instantiations. PCH files do not.
592   if (TUKind != TU_Prefix) {
593     DiagnoseUseOfUnimplementedSelectors();
594 
595     // If any dynamic classes have their key function defined within
596     // this translation unit, then those vtables are considered "used" and must
597     // be emitted.
598     for (DynamicClassesType::iterator I = DynamicClasses.begin(ExternalSource),
599                                       E = DynamicClasses.end();
600          I != E; ++I) {
601       assert(!(*I)->isDependentType() &&
602              "Should not see dependent types here!");
603       if (const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(*I)) {
604         const FunctionDecl *Definition = 0;
605         if (KeyFunction->hasBody(Definition))
606           MarkVTableUsed(Definition->getLocation(), *I, true);
607       }
608     }
609 
610     // If DefinedUsedVTables ends up marking any virtual member functions it
611     // might lead to more pending template instantiations, which we then need
612     // to instantiate.
613     DefineUsedVTables();
614 
615     // C++: Perform implicit template instantiations.
616     //
617     // FIXME: When we perform these implicit instantiations, we do not
618     // carefully keep track of the point of instantiation (C++ [temp.point]).
619     // This means that name lookup that occurs within the template
620     // instantiation will always happen at the end of the translation unit,
621     // so it will find some names that are not required to be found. This is
622     // valid, but we could do better by diagnosing if an instantiation uses a
623     // name that was not visible at its first point of instantiation.
624     if (ExternalSource) {
625       // Load pending instantiations from the external source.
626       SmallVector<PendingImplicitInstantiation, 4> Pending;
627       ExternalSource->ReadPendingInstantiations(Pending);
628       PendingInstantiations.insert(PendingInstantiations.begin(),
629                                    Pending.begin(), Pending.end());
630     }
631     PerformPendingInstantiations();
632 
633     CheckDelayedMemberExceptionSpecs();
634   }
635 
636   // All delayed member exception specs should be checked or we end up accepting
637   // incompatible declarations.
638   assert(DelayedDefaultedMemberExceptionSpecs.empty());
639   assert(DelayedDestructorExceptionSpecChecks.empty());
640 
641   // Remove file scoped decls that turned out to be used.
642   UnusedFileScopedDecls.erase(
643       std::remove_if(UnusedFileScopedDecls.begin(0, true),
644                      UnusedFileScopedDecls.end(),
645                      std::bind1st(std::ptr_fun(ShouldRemoveFromUnused), this)),
646       UnusedFileScopedDecls.end());
647 
648   if (TUKind == TU_Prefix) {
649     // Translation unit prefixes don't need any of the checking below.
650     TUScope = 0;
651     return;
652   }
653 
654   // Check for #pragma weak identifiers that were never declared
655   // FIXME: This will cause diagnostics to be emitted in a non-determinstic
656   // order!  Iterating over a densemap like this is bad.
657   LoadExternalWeakUndeclaredIdentifiers();
658   for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
659        I = WeakUndeclaredIdentifiers.begin(),
660        E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
661     if (I->second.getUsed()) continue;
662 
663     Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
664       << I->first;
665   }
666 
667   if (LangOpts.CPlusPlus11 &&
668       Diags.getDiagnosticLevel(diag::warn_delegating_ctor_cycle,
669                                SourceLocation())
670         != DiagnosticsEngine::Ignored)
671     CheckDelegatingCtorCycles();
672 
673   if (TUKind == TU_Module) {
674     // If we are building a module, resolve all of the exported declarations
675     // now.
676     if (Module *CurrentModule = PP.getCurrentModule()) {
677       ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
678 
679       SmallVector<Module *, 2> Stack;
680       Stack.push_back(CurrentModule);
681       while (!Stack.empty()) {
682         Module *Mod = Stack.pop_back_val();
683 
684         // Resolve the exported declarations and conflicts.
685         // FIXME: Actually complain, once we figure out how to teach the
686         // diagnostic client to deal with complaints in the module map at this
687         // point.
688         ModMap.resolveExports(Mod, /*Complain=*/false);
689         ModMap.resolveUses(Mod, /*Complain=*/false);
690         ModMap.resolveConflicts(Mod, /*Complain=*/false);
691 
692         // Queue the submodules, so their exports will also be resolved.
693         for (Module::submodule_iterator Sub = Mod->submodule_begin(),
694                                      SubEnd = Mod->submodule_end();
695              Sub != SubEnd; ++Sub) {
696           Stack.push_back(*Sub);
697         }
698       }
699     }
700 
701     // Modules don't need any of the checking below.
702     TUScope = 0;
703     return;
704   }
705 
706   // C99 6.9.2p2:
707   //   A declaration of an identifier for an object that has file
708   //   scope without an initializer, and without a storage-class
709   //   specifier or with the storage-class specifier static,
710   //   constitutes a tentative definition. If a translation unit
711   //   contains one or more tentative definitions for an identifier,
712   //   and the translation unit contains no external definition for
713   //   that identifier, then the behavior is exactly as if the
714   //   translation unit contains a file scope declaration of that
715   //   identifier, with the composite type as of the end of the
716   //   translation unit, with an initializer equal to 0.
717   llvm::SmallSet<VarDecl *, 32> Seen;
718   for (TentativeDefinitionsType::iterator
719             T = TentativeDefinitions.begin(ExternalSource),
720          TEnd = TentativeDefinitions.end();
721        T != TEnd; ++T)
722   {
723     VarDecl *VD = (*T)->getActingDefinition();
724 
725     // If the tentative definition was completed, getActingDefinition() returns
726     // null. If we've already seen this variable before, insert()'s second
727     // return value is false.
728     if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
729       continue;
730 
731     if (const IncompleteArrayType *ArrayT
732         = Context.getAsIncompleteArrayType(VD->getType())) {
733       // Set the length of the array to 1 (C99 6.9.2p5).
734       Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
735       llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
736       QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
737                                                 One, ArrayType::Normal, 0);
738       VD->setType(T);
739     } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
740                                    diag::err_tentative_def_incomplete_type))
741       VD->setInvalidDecl();
742 
743     CheckCompleteVariableDeclaration(VD);
744 
745     // Notify the consumer that we've completed a tentative definition.
746     if (!VD->isInvalidDecl())
747       Consumer.CompleteTentativeDefinition(VD);
748 
749   }
750 
751   // If there were errors, disable 'unused' warnings since they will mostly be
752   // noise.
753   if (!Diags.hasErrorOccurred()) {
754     // Output warning for unused file scoped decls.
755     for (UnusedFileScopedDeclsType::iterator
756            I = UnusedFileScopedDecls.begin(ExternalSource),
757            E = UnusedFileScopedDecls.end(); I != E; ++I) {
758       if (ShouldRemoveFromUnused(this, *I))
759         continue;
760 
761       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
762         const FunctionDecl *DiagD;
763         if (!FD->hasBody(DiagD))
764           DiagD = FD;
765         if (DiagD->isDeleted())
766           continue; // Deleted functions are supposed to be unused.
767         if (DiagD->isReferenced()) {
768           if (isa<CXXMethodDecl>(DiagD))
769             Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
770                   << DiagD->getDeclName();
771           else {
772             if (FD->getStorageClass() == SC_Static &&
773                 !FD->isInlineSpecified() &&
774                 !SourceMgr.isInMainFile(
775                    SourceMgr.getExpansionLoc(FD->getLocation())))
776               Diag(DiagD->getLocation(), diag::warn_unneeded_static_internal_decl)
777                 << DiagD->getDeclName();
778             else
779               Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
780                    << /*function*/0 << DiagD->getDeclName();
781           }
782         } else {
783           Diag(DiagD->getLocation(),
784                isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
785                                          : diag::warn_unused_function)
786                 << DiagD->getDeclName();
787         }
788       } else {
789         const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
790         if (!DiagD)
791           DiagD = cast<VarDecl>(*I);
792         if (DiagD->isReferenced()) {
793           Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
794                 << /*variable*/1 << DiagD->getDeclName();
795         } else if (DiagD->getType().isConstQualified()) {
796           Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
797               << DiagD->getDeclName();
798         } else {
799           Diag(DiagD->getLocation(), diag::warn_unused_variable)
800               << DiagD->getDeclName();
801         }
802       }
803     }
804 
805     if (ExternalSource)
806       ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
807     checkUndefinedButUsed(*this);
808   }
809 
810   if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
811                                SourceLocation())
812         != DiagnosticsEngine::Ignored) {
813     RecordCompleteMap RecordsComplete;
814     RecordCompleteMap MNCComplete;
815     for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
816          E = UnusedPrivateFields.end(); I != E; ++I) {
817       const NamedDecl *D = *I;
818       const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
819       if (RD && !RD->isUnion() &&
820           IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
821         Diag(D->getLocation(), diag::warn_unused_private_field)
822               << D->getDeclName();
823       }
824     }
825   }
826 
827   // Check we've noticed that we're no longer parsing the initializer for every
828   // variable. If we miss cases, then at best we have a performance issue and
829   // at worst a rejects-valid bug.
830   assert(ParsingInitForAutoVars.empty() &&
831          "Didn't unmark var as having its initializer parsed");
832 
833   TUScope = 0;
834 }
835 
836 
837 //===----------------------------------------------------------------------===//
838 // Helper functions.
839 //===----------------------------------------------------------------------===//
840 
841 DeclContext *Sema::getFunctionLevelDeclContext() {
842   DeclContext *DC = CurContext;
843 
844   while (true) {
845     if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) {
846       DC = DC->getParent();
847     } else if (isa<CXXMethodDecl>(DC) &&
848                cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
849                cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
850       DC = DC->getParent()->getParent();
851     }
852     else break;
853   }
854 
855   return DC;
856 }
857 
858 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
859 /// to the function decl for the function being parsed.  If we're currently
860 /// in a 'block', this returns the containing context.
861 FunctionDecl *Sema::getCurFunctionDecl() {
862   DeclContext *DC = getFunctionLevelDeclContext();
863   return dyn_cast<FunctionDecl>(DC);
864 }
865 
866 ObjCMethodDecl *Sema::getCurMethodDecl() {
867   DeclContext *DC = getFunctionLevelDeclContext();
868   while (isa<RecordDecl>(DC))
869     DC = DC->getParent();
870   return dyn_cast<ObjCMethodDecl>(DC);
871 }
872 
873 NamedDecl *Sema::getCurFunctionOrMethodDecl() {
874   DeclContext *DC = getFunctionLevelDeclContext();
875   if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
876     return cast<NamedDecl>(DC);
877   return 0;
878 }
879 
880 void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
881   // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
882   // and yet we also use the current diag ID on the DiagnosticsEngine. This has
883   // been made more painfully obvious by the refactor that introduced this
884   // function, but it is possible that the incoming argument can be
885   // eliminnated. If it truly cannot be (for example, there is some reentrancy
886   // issue I am not seeing yet), then there should at least be a clarifying
887   // comment somewhere.
888   if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
889     switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
890               Diags.getCurrentDiagID())) {
891     case DiagnosticIDs::SFINAE_Report:
892       // We'll report the diagnostic below.
893       break;
894 
895     case DiagnosticIDs::SFINAE_SubstitutionFailure:
896       // Count this failure so that we know that template argument deduction
897       // has failed.
898       ++NumSFINAEErrors;
899 
900       // Make a copy of this suppressed diagnostic and store it with the
901       // template-deduction information.
902       if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
903         Diagnostic DiagInfo(&Diags);
904         (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
905                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
906       }
907 
908       Diags.setLastDiagnosticIgnored();
909       Diags.Clear();
910       return;
911 
912     case DiagnosticIDs::SFINAE_AccessControl: {
913       // Per C++ Core Issue 1170, access control is part of SFINAE.
914       // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
915       // make access control a part of SFINAE for the purposes of checking
916       // type traits.
917       if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
918         break;
919 
920       SourceLocation Loc = Diags.getCurrentDiagLoc();
921 
922       // Suppress this diagnostic.
923       ++NumSFINAEErrors;
924 
925       // Make a copy of this suppressed diagnostic and store it with the
926       // template-deduction information.
927       if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
928         Diagnostic DiagInfo(&Diags);
929         (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
930                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
931       }
932 
933       Diags.setLastDiagnosticIgnored();
934       Diags.Clear();
935 
936       // Now the diagnostic state is clear, produce a C++98 compatibility
937       // warning.
938       Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
939 
940       // The last diagnostic which Sema produced was ignored. Suppress any
941       // notes attached to it.
942       Diags.setLastDiagnosticIgnored();
943       return;
944     }
945 
946     case DiagnosticIDs::SFINAE_Suppress:
947       // Make a copy of this suppressed diagnostic and store it with the
948       // template-deduction information;
949       if (*Info) {
950         Diagnostic DiagInfo(&Diags);
951         (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
952                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
953       }
954 
955       // Suppress this diagnostic.
956       Diags.setLastDiagnosticIgnored();
957       Diags.Clear();
958       return;
959     }
960   }
961 
962   // Set up the context's printing policy based on our current state.
963   Context.setPrintingPolicy(getPrintingPolicy());
964 
965   // Emit the diagnostic.
966   if (!Diags.EmitCurrentDiagnostic())
967     return;
968 
969   // If this is not a note, and we're in a template instantiation
970   // that is different from the last template instantiation where
971   // we emitted an error, print a template instantiation
972   // backtrace.
973   if (!DiagnosticIDs::isBuiltinNote(DiagID) &&
974       !ActiveTemplateInstantiations.empty() &&
975       ActiveTemplateInstantiations.back()
976         != LastTemplateInstantiationErrorContext) {
977     PrintInstantiationStack();
978     LastTemplateInstantiationErrorContext = ActiveTemplateInstantiations.back();
979   }
980 }
981 
982 Sema::SemaDiagnosticBuilder
983 Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
984   SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
985   PD.Emit(Builder);
986 
987   return Builder;
988 }
989 
990 /// \brief Looks through the macro-expansion chain for the given
991 /// location, looking for a macro expansion with the given name.
992 /// If one is found, returns true and sets the location to that
993 /// expansion loc.
994 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
995   SourceLocation loc = locref;
996   if (!loc.isMacroID()) return false;
997 
998   // There's no good way right now to look at the intermediate
999   // expansions, so just jump to the expansion location.
1000   loc = getSourceManager().getExpansionLoc(loc);
1001 
1002   // If that's written with the name, stop here.
1003   SmallVector<char, 16> buffer;
1004   if (getPreprocessor().getSpelling(loc, buffer) == name) {
1005     locref = loc;
1006     return true;
1007   }
1008   return false;
1009 }
1010 
1011 /// \brief Determines the active Scope associated with the given declaration
1012 /// context.
1013 ///
1014 /// This routine maps a declaration context to the active Scope object that
1015 /// represents that declaration context in the parser. It is typically used
1016 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1017 /// declarations) that injects a name for name-lookup purposes and, therefore,
1018 /// must update the Scope.
1019 ///
1020 /// \returns The scope corresponding to the given declaraion context, or NULL
1021 /// if no such scope is open.
1022 Scope *Sema::getScopeForContext(DeclContext *Ctx) {
1023 
1024   if (!Ctx)
1025     return 0;
1026 
1027   Ctx = Ctx->getPrimaryContext();
1028   for (Scope *S = getCurScope(); S; S = S->getParent()) {
1029     // Ignore scopes that cannot have declarations. This is important for
1030     // out-of-line definitions of static class members.
1031     if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
1032       if (DeclContext *Entity = S->getEntity())
1033         if (Ctx == Entity->getPrimaryContext())
1034           return S;
1035   }
1036 
1037   return 0;
1038 }
1039 
1040 /// \brief Enter a new function scope
1041 void Sema::PushFunctionScope() {
1042   if (FunctionScopes.size() == 1) {
1043     // Use the "top" function scope rather than having to allocate
1044     // memory for a new scope.
1045     FunctionScopes.back()->Clear();
1046     FunctionScopes.push_back(FunctionScopes.back());
1047     return;
1048   }
1049 
1050   FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
1051 }
1052 
1053 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
1054   FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
1055                                               BlockScope, Block));
1056 }
1057 
1058 LambdaScopeInfo *Sema::PushLambdaScope() {
1059   LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
1060   FunctionScopes.push_back(LSI);
1061   return LSI;
1062 }
1063 
1064 void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
1065   if (LambdaScopeInfo *const LSI = getCurLambda()) {
1066     LSI->AutoTemplateParameterDepth = Depth;
1067     return;
1068   }
1069   llvm_unreachable(
1070       "Remove assertion if intentionally called in a non-lambda context.");
1071 }
1072 
1073 void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
1074                                 const Decl *D, const BlockExpr *blkExpr) {
1075   FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
1076   assert(!FunctionScopes.empty() && "mismatched push/pop!");
1077 
1078   // Issue any analysis-based warnings.
1079   if (WP && D)
1080     AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
1081   else {
1082     for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
1083          i = Scope->PossiblyUnreachableDiags.begin(),
1084          e = Scope->PossiblyUnreachableDiags.end();
1085          i != e; ++i) {
1086       const sema::PossiblyUnreachableDiag &D = *i;
1087       Diag(D.Loc, D.PD);
1088     }
1089   }
1090 
1091   if (FunctionScopes.back() != Scope) {
1092     delete Scope;
1093   }
1094 }
1095 
1096 void Sema::PushCompoundScope() {
1097   getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo());
1098 }
1099 
1100 void Sema::PopCompoundScope() {
1101   FunctionScopeInfo *CurFunction = getCurFunction();
1102   assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
1103 
1104   CurFunction->CompoundScopes.pop_back();
1105 }
1106 
1107 /// \brief Determine whether any errors occurred within this function/method/
1108 /// block.
1109 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
1110   return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
1111 }
1112 
1113 BlockScopeInfo *Sema::getCurBlock() {
1114   if (FunctionScopes.empty())
1115     return 0;
1116 
1117   return dyn_cast<BlockScopeInfo>(FunctionScopes.back());
1118 }
1119 
1120 LambdaScopeInfo *Sema::getCurLambda() {
1121   if (FunctionScopes.empty())
1122     return 0;
1123 
1124   return dyn_cast<LambdaScopeInfo>(FunctionScopes.back());
1125 }
1126 // We have a generic lambda if we parsed auto parameters, or we have
1127 // an associated template parameter list.
1128 LambdaScopeInfo *Sema::getCurGenericLambda() {
1129   if (LambdaScopeInfo *LSI =  getCurLambda()) {
1130     return (LSI->AutoTemplateParams.size() ||
1131                     LSI->GLTemplateParameterList) ? LSI : 0;
1132   }
1133   return 0;
1134 }
1135 
1136 
1137 void Sema::ActOnComment(SourceRange Comment) {
1138   if (!LangOpts.RetainCommentsFromSystemHeaders &&
1139       SourceMgr.isInSystemHeader(Comment.getBegin()))
1140     return;
1141   RawComment RC(SourceMgr, Comment, false,
1142                 LangOpts.CommentOpts.ParseAllComments);
1143   if (RC.isAlmostTrailingComment()) {
1144     SourceRange MagicMarkerRange(Comment.getBegin(),
1145                                  Comment.getBegin().getLocWithOffset(3));
1146     StringRef MagicMarkerText;
1147     switch (RC.getKind()) {
1148     case RawComment::RCK_OrdinaryBCPL:
1149       MagicMarkerText = "///<";
1150       break;
1151     case RawComment::RCK_OrdinaryC:
1152       MagicMarkerText = "/**<";
1153       break;
1154     default:
1155       llvm_unreachable("if this is an almost Doxygen comment, "
1156                        "it should be ordinary");
1157     }
1158     Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
1159       FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
1160   }
1161   Context.addComment(RC);
1162 }
1163 
1164 // Pin this vtable to this file.
1165 ExternalSemaSource::~ExternalSemaSource() {}
1166 
1167 void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
1168 
1169 void ExternalSemaSource::ReadKnownNamespaces(
1170                            SmallVectorImpl<NamespaceDecl *> &Namespaces) {
1171 }
1172 
1173 void ExternalSemaSource::ReadUndefinedButUsed(
1174                        llvm::DenseMap<NamedDecl *, SourceLocation> &Undefined) {
1175 }
1176 
1177 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
1178   SourceLocation Loc = this->Loc;
1179   if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
1180   if (Loc.isValid()) {
1181     Loc.print(OS, S.getSourceManager());
1182     OS << ": ";
1183   }
1184   OS << Message;
1185 
1186   if (TheDecl && isa<NamedDecl>(TheDecl)) {
1187     std::string Name = cast<NamedDecl>(TheDecl)->getNameAsString();
1188     if (!Name.empty())
1189       OS << " '" << Name << '\'';
1190   }
1191 
1192   OS << '\n';
1193 }
1194 
1195 /// \brief Figure out if an expression could be turned into a call.
1196 ///
1197 /// Use this when trying to recover from an error where the programmer may have
1198 /// written just the name of a function instead of actually calling it.
1199 ///
1200 /// \param E - The expression to examine.
1201 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1202 ///  with no arguments, this parameter is set to the type returned by such a
1203 ///  call; otherwise, it is set to an empty QualType.
1204 /// \param OverloadSet - If the expression is an overloaded function
1205 ///  name, this parameter is populated with the decls of the various overloads.
1206 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1207                          UnresolvedSetImpl &OverloadSet) {
1208   ZeroArgCallReturnTy = QualType();
1209   OverloadSet.clear();
1210 
1211   const OverloadExpr *Overloads = NULL;
1212   bool IsMemExpr = false;
1213   if (E.getType() == Context.OverloadTy) {
1214     OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
1215 
1216     // Ignore overloads that are pointer-to-member constants.
1217     if (FR.HasFormOfMemberPointer)
1218       return false;
1219 
1220     Overloads = FR.Expression;
1221   } else if (E.getType() == Context.BoundMemberTy) {
1222     Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
1223     IsMemExpr = true;
1224   }
1225 
1226   bool Ambiguous = false;
1227 
1228   if (Overloads) {
1229     for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
1230          DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
1231       OverloadSet.addDecl(*it);
1232 
1233       // Check whether the function is a non-template, non-member which takes no
1234       // arguments.
1235       if (IsMemExpr)
1236         continue;
1237       if (const FunctionDecl *OverloadDecl
1238             = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
1239         if (OverloadDecl->getMinRequiredArguments() == 0) {
1240           if (!ZeroArgCallReturnTy.isNull() && !Ambiguous) {
1241             ZeroArgCallReturnTy = QualType();
1242             Ambiguous = true;
1243           } else
1244             ZeroArgCallReturnTy = OverloadDecl->getReturnType();
1245         }
1246       }
1247     }
1248 
1249     // If it's not a member, use better machinery to try to resolve the call
1250     if (!IsMemExpr)
1251       return !ZeroArgCallReturnTy.isNull();
1252   }
1253 
1254   // Attempt to call the member with no arguments - this will correctly handle
1255   // member templates with defaults/deduction of template arguments, overloads
1256   // with default arguments, etc.
1257   if (IsMemExpr && !E.isTypeDependent()) {
1258     bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
1259     getDiagnostics().setSuppressAllDiagnostics(true);
1260     ExprResult R = BuildCallToMemberFunction(NULL, &E, SourceLocation(), None,
1261                                              SourceLocation());
1262     getDiagnostics().setSuppressAllDiagnostics(Suppress);
1263     if (R.isUsable()) {
1264       ZeroArgCallReturnTy = R.get()->getType();
1265       return true;
1266     }
1267     return false;
1268   }
1269 
1270   if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
1271     if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
1272       if (Fun->getMinRequiredArguments() == 0)
1273         ZeroArgCallReturnTy = Fun->getReturnType();
1274       return true;
1275     }
1276   }
1277 
1278   // We don't have an expression that's convenient to get a FunctionDecl from,
1279   // but we can at least check if the type is "function of 0 arguments".
1280   QualType ExprTy = E.getType();
1281   const FunctionType *FunTy = NULL;
1282   QualType PointeeTy = ExprTy->getPointeeType();
1283   if (!PointeeTy.isNull())
1284     FunTy = PointeeTy->getAs<FunctionType>();
1285   if (!FunTy)
1286     FunTy = ExprTy->getAs<FunctionType>();
1287 
1288   if (const FunctionProtoType *FPT =
1289       dyn_cast_or_null<FunctionProtoType>(FunTy)) {
1290     if (FPT->getNumParams() == 0)
1291       ZeroArgCallReturnTy = FunTy->getReturnType();
1292     return true;
1293   }
1294   return false;
1295 }
1296 
1297 /// \brief Give notes for a set of overloads.
1298 ///
1299 /// A companion to tryExprAsCall. In cases when the name that the programmer
1300 /// wrote was an overloaded function, we may be able to make some guesses about
1301 /// plausible overloads based on their return types; such guesses can be handed
1302 /// off to this method to be emitted as notes.
1303 ///
1304 /// \param Overloads - The overloads to note.
1305 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
1306 ///  -fshow-overloads=best, this is the location to attach to the note about too
1307 ///  many candidates. Typically this will be the location of the original
1308 ///  ill-formed expression.
1309 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
1310                           const SourceLocation FinalNoteLoc) {
1311   int ShownOverloads = 0;
1312   int SuppressedOverloads = 0;
1313   for (UnresolvedSetImpl::iterator It = Overloads.begin(),
1314        DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1315     // FIXME: Magic number for max shown overloads stolen from
1316     // OverloadCandidateSet::NoteCandidates.
1317     if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) {
1318       ++SuppressedOverloads;
1319       continue;
1320     }
1321 
1322     NamedDecl *Fn = (*It)->getUnderlyingDecl();
1323     S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
1324     ++ShownOverloads;
1325   }
1326 
1327   if (SuppressedOverloads)
1328     S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
1329       << SuppressedOverloads;
1330 }
1331 
1332 static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
1333                                    const UnresolvedSetImpl &Overloads,
1334                                    bool (*IsPlausibleResult)(QualType)) {
1335   if (!IsPlausibleResult)
1336     return noteOverloads(S, Overloads, Loc);
1337 
1338   UnresolvedSet<2> PlausibleOverloads;
1339   for (OverloadExpr::decls_iterator It = Overloads.begin(),
1340          DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1341     const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
1342     QualType OverloadResultTy = OverloadDecl->getReturnType();
1343     if (IsPlausibleResult(OverloadResultTy))
1344       PlausibleOverloads.addDecl(It.getDecl());
1345   }
1346   noteOverloads(S, PlausibleOverloads, Loc);
1347 }
1348 
1349 /// Determine whether the given expression can be called by just
1350 /// putting parentheses after it.  Notably, expressions with unary
1351 /// operators can't be because the unary operator will start parsing
1352 /// outside the call.
1353 static bool IsCallableWithAppend(Expr *E) {
1354   E = E->IgnoreImplicit();
1355   return (!isa<CStyleCastExpr>(E) &&
1356           !isa<UnaryOperator>(E) &&
1357           !isa<BinaryOperator>(E) &&
1358           !isa<CXXOperatorCallExpr>(E));
1359 }
1360 
1361 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1362                                 bool ForceComplain,
1363                                 bool (*IsPlausibleResult)(QualType)) {
1364   SourceLocation Loc = E.get()->getExprLoc();
1365   SourceRange Range = E.get()->getSourceRange();
1366 
1367   QualType ZeroArgCallTy;
1368   UnresolvedSet<4> Overloads;
1369   if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
1370       !ZeroArgCallTy.isNull() &&
1371       (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
1372     // At this point, we know E is potentially callable with 0
1373     // arguments and that it returns something of a reasonable type,
1374     // so we can emit a fixit and carry on pretending that E was
1375     // actually a CallExpr.
1376     SourceLocation ParenInsertionLoc = PP.getLocForEndOfToken(Range.getEnd());
1377     Diag(Loc, PD)
1378       << /*zero-arg*/ 1 << Range
1379       << (IsCallableWithAppend(E.get())
1380           ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
1381           : FixItHint());
1382     notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1383 
1384     // FIXME: Try this before emitting the fixit, and suppress diagnostics
1385     // while doing so.
1386     E = ActOnCallExpr(0, E.take(), Range.getEnd(), None,
1387                       Range.getEnd().getLocWithOffset(1));
1388     return true;
1389   }
1390 
1391   if (!ForceComplain) return false;
1392 
1393   Diag(Loc, PD) << /*not zero-arg*/ 0 << Range;
1394   notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1395   E = ExprError();
1396   return true;
1397 }
1398 
1399 IdentifierInfo *Sema::getSuperIdentifier() const {
1400   if (!Ident_super)
1401     Ident_super = &Context.Idents.get("super");
1402   return Ident_super;
1403 }
1404 
1405 IdentifierInfo *Sema::getFloat128Identifier() const {
1406   if (!Ident___float128)
1407     Ident___float128 = &Context.Idents.get("__float128");
1408   return Ident___float128;
1409 }
1410 
1411 void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
1412                                    CapturedRegionKind K) {
1413   CapturingScopeInfo *CSI = new CapturedRegionScopeInfo(getDiagnostics(), S, CD, RD,
1414                                                         CD->getContextParam(), K);
1415   CSI->ReturnType = Context.VoidTy;
1416   FunctionScopes.push_back(CSI);
1417 }
1418 
1419 CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
1420   if (FunctionScopes.empty())
1421     return 0;
1422 
1423   return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
1424 }
1425