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