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