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