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