clang API Documentation

Sema.cpp
Go to the documentation of this file.
00001 //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the actions class which performs semantic analysis and
00011 // builds an AST out of a parse stream.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/Sema/SemaInternal.h"
00016 #include "clang/AST/ASTContext.h"
00017 #include "clang/AST/ASTDiagnostic.h"
00018 #include "clang/AST/DeclCXX.h"
00019 #include "clang/AST/DeclFriend.h"
00020 #include "clang/AST/DeclObjC.h"
00021 #include "clang/AST/Expr.h"
00022 #include "clang/AST/ExprCXX.h"
00023 #include "clang/AST/StmtCXX.h"
00024 #include "clang/Basic/DiagnosticOptions.h"
00025 #include "clang/Basic/FileManager.h"
00026 #include "clang/Basic/PartialDiagnostic.h"
00027 #include "clang/Basic/TargetInfo.h"
00028 #include "clang/Lex/HeaderSearch.h"
00029 #include "clang/Lex/Preprocessor.h"
00030 #include "clang/Sema/CXXFieldCollector.h"
00031 #include "clang/Sema/DelayedDiagnostic.h"
00032 #include "clang/Sema/ExternalSemaSource.h"
00033 #include "clang/Sema/MultiplexExternalSemaSource.h"
00034 #include "clang/Sema/ObjCMethodList.h"
00035 #include "clang/Sema/PrettyDeclStackTrace.h"
00036 #include "clang/Sema/Scope.h"
00037 #include "clang/Sema/ScopeInfo.h"
00038 #include "clang/Sema/SemaConsumer.h"
00039 #include "clang/Sema/TemplateDeduction.h"
00040 #include "llvm/ADT/APFloat.h"
00041 #include "llvm/ADT/DenseMap.h"
00042 #include "llvm/ADT/SmallSet.h"
00043 #include "llvm/Support/CrashRecoveryContext.h"
00044 using namespace clang;
00045 using namespace sema;
00046 
00047 SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
00048   return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
00049 }
00050 
00051 ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
00052 
00053 PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
00054                                        const Preprocessor &PP) {
00055   PrintingPolicy Policy = Context.getPrintingPolicy();
00056   Policy.Bool = Context.getLangOpts().Bool;
00057   if (!Policy.Bool) {
00058     if (const MacroInfo *
00059           BoolMacro = PP.getMacroInfo(&Context.Idents.get("bool"))) {
00060       Policy.Bool = BoolMacro->isObjectLike() &&
00061         BoolMacro->getNumTokens() == 1 &&
00062         BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
00063     }
00064   }
00065 
00066   return Policy;
00067 }
00068 
00069 void Sema::ActOnTranslationUnitScope(Scope *S) {
00070   TUScope = S;
00071   PushDeclContext(S, Context.getTranslationUnitDecl());
00072 }
00073 
00074 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
00075            TranslationUnitKind TUKind,
00076            CodeCompleteConsumer *CodeCompleter)
00077   : ExternalSource(nullptr),
00078     isMultiplexExternalSource(false), FPFeatures(pp.getLangOpts()),
00079     LangOpts(pp.getLangOpts()), PP(pp), Context(ctxt), Consumer(consumer),
00080     Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
00081     CollectStats(false), CodeCompleter(CodeCompleter),
00082     CurContext(nullptr), OriginalLexicalContext(nullptr),
00083     PackContext(nullptr), MSStructPragmaOn(false),
00084     MSPointerToMemberRepresentationMethod(
00085         LangOpts.getMSPointerToMemberRepresentationMethod()),
00086     VtorDispModeStack(1, MSVtorDispAttr::Mode(LangOpts.VtorDispMode)),
00087     DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
00088     CodeSegStack(nullptr), CurInitSeg(nullptr), VisContext(nullptr),
00089     IsBuildingRecoveryCallExpr(false),
00090     ExprNeedsCleanups(false), LateTemplateParser(nullptr),
00091     LateTemplateParserCleanup(nullptr),
00092     OpaqueParser(nullptr), IdResolver(pp), StdInitializerList(nullptr),
00093     CXXTypeInfoDecl(nullptr), MSVCGuidDecl(nullptr),
00094     NSNumberDecl(nullptr),
00095     NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr),
00096     NSArrayDecl(nullptr), ArrayWithObjectsMethod(nullptr),
00097     NSDictionaryDecl(nullptr), DictionaryWithObjectsMethod(nullptr),
00098     MSAsmLabelNameCounter(0),
00099     GlobalNewDeleteDeclared(false),
00100     TUKind(TUKind),
00101     NumSFINAEErrors(0),
00102     AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
00103     NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
00104     CurrentInstantiationScope(nullptr), DisableTypoCorrection(false),
00105     TyposCorrected(0), AnalysisWarnings(*this),
00106     VarDataSharingAttributesStack(nullptr), CurScope(nullptr),
00107     Ident_super(nullptr), Ident___float128(nullptr)
00108 {
00109   TUScope = nullptr;
00110 
00111   LoadedExternalKnownNamespaces = false;
00112   for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
00113     NSNumberLiteralMethods[I] = nullptr;
00114 
00115   if (getLangOpts().ObjC1)
00116     NSAPIObj.reset(new NSAPI(Context));
00117 
00118   if (getLangOpts().CPlusPlus)
00119     FieldCollector.reset(new CXXFieldCollector());
00120 
00121   // Tell diagnostics how to render things from the AST library.
00122   PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
00123                                        &Context);
00124 
00125   ExprEvalContexts.push_back(
00126         ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0,
00127                                           false, nullptr, false));
00128 
00129   FunctionScopes.push_back(new FunctionScopeInfo(Diags));
00130 
00131   // Initilization of data sharing attributes stack for OpenMP
00132   InitDataSharingAttributesStack();
00133 }
00134 
00135 void Sema::addImplicitTypedef(StringRef Name, QualType T) {
00136   DeclarationName DN = &Context.Idents.get(Name);
00137   if (IdResolver.begin(DN) == IdResolver.end())
00138     PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
00139 }
00140 
00141 void Sema::Initialize() {
00142   // Tell the AST consumer about this Sema object.
00143   Consumer.Initialize(Context);
00144 
00145   // FIXME: Isn't this redundant with the initialization above?
00146   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
00147     SC->InitializeSema(*this);
00148 
00149   // Tell the external Sema source about this Sema object.
00150   if (ExternalSemaSource *ExternalSema
00151       = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
00152     ExternalSema->InitializeSema(*this);
00153 
00154   // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
00155   // will not be able to merge any duplicate __va_list_tag decls correctly.
00156   VAListTagName = PP.getIdentifierInfo("__va_list_tag");
00157 
00158   // Initialize predefined 128-bit integer types, if needed.
00159   if (Context.getTargetInfo().hasInt128Type()) {
00160     // If either of the 128-bit integer types are unavailable to name lookup,
00161     // define them now.
00162     DeclarationName Int128 = &Context.Idents.get("__int128_t");
00163     if (IdResolver.begin(Int128) == IdResolver.end())
00164       PushOnScopeChains(Context.getInt128Decl(), TUScope);
00165 
00166     DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
00167     if (IdResolver.begin(UInt128) == IdResolver.end())
00168       PushOnScopeChains(Context.getUInt128Decl(), TUScope);
00169   }
00170 
00171 
00172   // Initialize predefined Objective-C types:
00173   if (PP.getLangOpts().ObjC1) {
00174     // If 'SEL' does not yet refer to any declarations, make it refer to the
00175     // predefined 'SEL'.
00176     DeclarationName SEL = &Context.Idents.get("SEL");
00177     if (IdResolver.begin(SEL) == IdResolver.end())
00178       PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
00179 
00180     // If 'id' does not yet refer to any declarations, make it refer to the
00181     // predefined 'id'.
00182     DeclarationName Id = &Context.Idents.get("id");
00183     if (IdResolver.begin(Id) == IdResolver.end())
00184       PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
00185 
00186     // Create the built-in typedef for 'Class'.
00187     DeclarationName Class = &Context.Idents.get("Class");
00188     if (IdResolver.begin(Class) == IdResolver.end())
00189       PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
00190 
00191     // Create the built-in forward declaratino for 'Protocol'.
00192     DeclarationName Protocol = &Context.Idents.get("Protocol");
00193     if (IdResolver.begin(Protocol) == IdResolver.end())
00194       PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
00195   }
00196 
00197   // Initialize Microsoft "predefined C++ types".
00198   if (PP.getLangOpts().MSVCCompat && PP.getLangOpts().CPlusPlus) {
00199     if (IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
00200       PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
00201                         TUScope);
00202 
00203     addImplicitTypedef("size_t", Context.getSizeType());
00204   }
00205 
00206   // Initialize predefined OpenCL types.
00207   if (PP.getLangOpts().OpenCL) {
00208     addImplicitTypedef("image1d_t", Context.OCLImage1dTy);
00209     addImplicitTypedef("image1d_array_t", Context.OCLImage1dArrayTy);
00210     addImplicitTypedef("image1d_buffer_t", Context.OCLImage1dBufferTy);
00211     addImplicitTypedef("image2d_t", Context.OCLImage2dTy);
00212     addImplicitTypedef("image2d_array_t", Context.OCLImage2dArrayTy);
00213     addImplicitTypedef("image3d_t", Context.OCLImage3dTy);
00214     addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
00215     addImplicitTypedef("event_t", Context.OCLEventTy);
00216   }
00217 
00218   DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
00219   if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
00220     PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
00221 }
00222 
00223 Sema::~Sema() {
00224   llvm::DeleteContainerSeconds(LateParsedTemplateMap);
00225   if (PackContext) FreePackedContext();
00226   if (VisContext) FreeVisContext();
00227   // Kill all the active scopes.
00228   for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
00229     delete FunctionScopes[I];
00230   if (FunctionScopes.size() == 1)
00231     delete FunctionScopes[0];
00232 
00233   // Tell the SemaConsumer to forget about us; we're going out of scope.
00234   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
00235     SC->ForgetSema();
00236 
00237   // Detach from the external Sema source.
00238   if (ExternalSemaSource *ExternalSema
00239         = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
00240     ExternalSema->ForgetSema();
00241 
00242   // If Sema's ExternalSource is the multiplexer - we own it.
00243   if (isMultiplexExternalSource)
00244     delete ExternalSource;
00245 
00246   // Destroys data sharing attributes stack for OpenMP
00247   DestroyDataSharingAttributesStack();
00248 }
00249 
00250 /// makeUnavailableInSystemHeader - There is an error in the current
00251 /// context.  If we're still in a system header, and we can plausibly
00252 /// make the relevant declaration unavailable instead of erroring, do
00253 /// so and return true.
00254 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
00255                                          StringRef msg) {
00256   // If we're not in a function, it's an error.
00257   FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
00258   if (!fn) return false;
00259 
00260   // If we're in template instantiation, it's an error.
00261   if (!ActiveTemplateInstantiations.empty())
00262     return false;
00263 
00264   // If that function's not in a system header, it's an error.
00265   if (!Context.getSourceManager().isInSystemHeader(loc))
00266     return false;
00267 
00268   // If the function is already unavailable, it's not an error.
00269   if (fn->hasAttr<UnavailableAttr>()) return true;
00270 
00271   fn->addAttr(UnavailableAttr::CreateImplicit(Context, msg, loc));
00272   return true;
00273 }
00274 
00275 ASTMutationListener *Sema::getASTMutationListener() const {
00276   return getASTConsumer().GetASTMutationListener();
00277 }
00278 
00279 ///\brief Registers an external source. If an external source already exists,
00280 /// creates a multiplex external source and appends to it.
00281 ///
00282 ///\param[in] E - A non-null external sema source.
00283 ///
00284 void Sema::addExternalSource(ExternalSemaSource *E) {
00285   assert(E && "Cannot use with NULL ptr");
00286 
00287   if (!ExternalSource) {
00288     ExternalSource = E;
00289     return;
00290   }
00291 
00292   if (isMultiplexExternalSource)
00293     static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
00294   else {
00295     ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
00296     isMultiplexExternalSource = true;
00297   }
00298 }
00299 
00300 /// \brief Print out statistics about the semantic analysis.
00301 void Sema::PrintStats() const {
00302   llvm::errs() << "\n*** Semantic Analysis Stats:\n";
00303   llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
00304 
00305   BumpAlloc.PrintStats();
00306   AnalysisWarnings.PrintStats();
00307 }
00308 
00309 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
00310 /// If there is already an implicit cast, merge into the existing one.
00311 /// The result is of the given category.
00312 ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
00313                                    CastKind Kind, ExprValueKind VK,
00314                                    const CXXCastPath *BasePath,
00315                                    CheckedConversionKind CCK) {
00316 #ifndef NDEBUG
00317   if (VK == VK_RValue && !E->isRValue()) {
00318     switch (Kind) {
00319     default:
00320       llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast "
00321                        "kind");
00322     case CK_LValueToRValue:
00323     case CK_ArrayToPointerDecay:
00324     case CK_FunctionToPointerDecay:
00325     case CK_ToVoid:
00326       break;
00327     }
00328   }
00329   assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue");
00330 #endif
00331 
00332   QualType ExprTy = Context.getCanonicalType(E->getType());
00333   QualType TypeTy = Context.getCanonicalType(Ty);
00334 
00335   if (ExprTy == TypeTy)
00336     return E;
00337 
00338   // If this is a derived-to-base cast to a through a virtual base, we
00339   // need a vtable.
00340   if (Kind == CK_DerivedToBase &&
00341       BasePathInvolvesVirtualBase(*BasePath)) {
00342     QualType T = E->getType();
00343     if (const PointerType *Pointer = T->getAs<PointerType>())
00344       T = Pointer->getPointeeType();
00345     if (const RecordType *RecordTy = T->getAs<RecordType>())
00346       MarkVTableUsed(E->getLocStart(),
00347                      cast<CXXRecordDecl>(RecordTy->getDecl()));
00348   }
00349 
00350   if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
00351     if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
00352       ImpCast->setType(Ty);
00353       ImpCast->setValueKind(VK);
00354       return E;
00355     }
00356   }
00357 
00358   return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK);
00359 }
00360 
00361 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
00362 /// to the conversion from scalar type ScalarTy to the Boolean type.
00363 CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
00364   switch (ScalarTy->getScalarTypeKind()) {
00365   case Type::STK_Bool: return CK_NoOp;
00366   case Type::STK_CPointer: return CK_PointerToBoolean;
00367   case Type::STK_BlockPointer: return CK_PointerToBoolean;
00368   case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
00369   case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
00370   case Type::STK_Integral: return CK_IntegralToBoolean;
00371   case Type::STK_Floating: return CK_FloatingToBoolean;
00372   case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
00373   case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
00374   }
00375   return CK_Invalid;
00376 }
00377 
00378 /// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
00379 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
00380   if (D->getMostRecentDecl()->isUsed())
00381     return true;
00382 
00383   if (D->isExternallyVisible())
00384     return true;
00385 
00386   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
00387     // UnusedFileScopedDecls stores the first declaration.
00388     // The declaration may have become definition so check again.
00389     const FunctionDecl *DeclToCheck;
00390     if (FD->hasBody(DeclToCheck))
00391       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
00392 
00393     // Later redecls may add new information resulting in not having to warn,
00394     // so check again.
00395     DeclToCheck = FD->getMostRecentDecl();
00396     if (DeclToCheck != FD)
00397       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
00398   }
00399 
00400   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
00401     // If a variable usable in constant expressions is referenced,
00402     // don't warn if it isn't used: if the value of a variable is required
00403     // for the computation of a constant expression, it doesn't make sense to
00404     // warn even if the variable isn't odr-used.  (isReferenced doesn't
00405     // precisely reflect that, but it's a decent approximation.)
00406     if (VD->isReferenced() &&
00407         VD->isUsableInConstantExpressions(SemaRef->Context))
00408       return true;
00409 
00410     // UnusedFileScopedDecls stores the first declaration.
00411     // The declaration may have become definition so check again.
00412     const VarDecl *DeclToCheck = VD->getDefinition();
00413     if (DeclToCheck)
00414       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
00415 
00416     // Later redecls may add new information resulting in not having to warn,
00417     // so check again.
00418     DeclToCheck = VD->getMostRecentDecl();
00419     if (DeclToCheck != VD)
00420       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
00421   }
00422 
00423   return false;
00424 }
00425 
00426 /// Obtains a sorted list of functions that are undefined but ODR-used.
00427 void Sema::getUndefinedButUsed(
00428     SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
00429   for (llvm::DenseMap<NamedDecl *, SourceLocation>::iterator
00430          I = UndefinedButUsed.begin(), E = UndefinedButUsed.end();
00431        I != E; ++I) {
00432     NamedDecl *ND = I->first;
00433 
00434     // Ignore attributes that have become invalid.
00435     if (ND->isInvalidDecl()) continue;
00436 
00437     // __attribute__((weakref)) is basically a definition.
00438     if (ND->hasAttr<WeakRefAttr>()) continue;
00439 
00440     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
00441       if (FD->isDefined())
00442         continue;
00443       if (FD->isExternallyVisible() &&
00444           !FD->getMostRecentDecl()->isInlined())
00445         continue;
00446     } else {
00447       if (cast<VarDecl>(ND)->hasDefinition() != VarDecl::DeclarationOnly)
00448         continue;
00449       if (ND->isExternallyVisible())
00450         continue;
00451     }
00452 
00453     Undefined.push_back(std::make_pair(ND, I->second));
00454   }
00455 
00456   // Sort (in order of use site) so that we're not dependent on the iteration
00457   // order through an llvm::DenseMap.
00458   SourceManager &SM = Context.getSourceManager();
00459   std::sort(Undefined.begin(), Undefined.end(),
00460             [&SM](const std::pair<NamedDecl *, SourceLocation> &l,
00461                   const std::pair<NamedDecl *, SourceLocation> &r) {
00462     if (l.second.isValid() && !r.second.isValid())
00463       return true;
00464     if (!l.second.isValid() && r.second.isValid())
00465       return false;
00466     if (l.second != r.second)
00467       return SM.isBeforeInTranslationUnit(l.second, r.second);
00468     return SM.isBeforeInTranslationUnit(l.first->getLocation(),
00469                                         r.first->getLocation());
00470   });
00471 }
00472 
00473 /// checkUndefinedButUsed - Check for undefined objects with internal linkage
00474 /// or that are inline.
00475 static void checkUndefinedButUsed(Sema &S) {
00476   if (S.UndefinedButUsed.empty()) return;
00477 
00478   // Collect all the still-undefined entities with internal linkage.
00479   SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
00480   S.getUndefinedButUsed(Undefined);
00481   if (Undefined.empty()) return;
00482 
00483   for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
00484          I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
00485     NamedDecl *ND = I->first;
00486 
00487     if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
00488       // An exported function will always be emitted when defined, so even if
00489       // the function is inline, it doesn't have to be emitted in this TU. An
00490       // imported function implies that it has been exported somewhere else.
00491       continue;
00492     }
00493 
00494     if (!ND->isExternallyVisible()) {
00495       S.Diag(ND->getLocation(), diag::warn_undefined_internal)
00496         << isa<VarDecl>(ND) << ND;
00497     } else {
00498       assert(cast<FunctionDecl>(ND)->getMostRecentDecl()->isInlined() &&
00499              "used object requires definition but isn't inline or internal?");
00500       S.Diag(ND->getLocation(), diag::warn_undefined_inline) << ND;
00501     }
00502     if (I->second.isValid())
00503       S.Diag(I->second, diag::note_used_here);
00504   }
00505 }
00506 
00507 void Sema::LoadExternalWeakUndeclaredIdentifiers() {
00508   if (!ExternalSource)
00509     return;
00510 
00511   SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
00512   ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
00513   for (unsigned I = 0, N = WeakIDs.size(); I != N; ++I) {
00514     llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator Pos
00515       = WeakUndeclaredIdentifiers.find(WeakIDs[I].first);
00516     if (Pos != WeakUndeclaredIdentifiers.end())
00517       continue;
00518 
00519     WeakUndeclaredIdentifiers.insert(WeakIDs[I]);
00520   }
00521 }
00522 
00523 
00524 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
00525 
00526 /// \brief Returns true, if all methods and nested classes of the given
00527 /// CXXRecordDecl are defined in this translation unit.
00528 ///
00529 /// Should only be called from ActOnEndOfTranslationUnit so that all
00530 /// definitions are actually read.
00531 static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
00532                                             RecordCompleteMap &MNCComplete) {
00533   RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
00534   if (Cache != MNCComplete.end())
00535     return Cache->second;
00536   if (!RD->isCompleteDefinition())
00537     return false;
00538   bool Complete = true;
00539   for (DeclContext::decl_iterator I = RD->decls_begin(),
00540                                   E = RD->decls_end();
00541        I != E && Complete; ++I) {
00542     if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
00543       Complete = M->isDefined() || (M->isPure() && !isa<CXXDestructorDecl>(M));
00544     else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
00545       // If the template function is marked as late template parsed at this point,
00546       // it has not been instantiated and therefore we have not performed semantic
00547       // analysis on it yet, so we cannot know if the type can be considered
00548       // complete.
00549       Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
00550                   F->getTemplatedDecl()->isDefined();
00551     else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
00552       if (R->isInjectedClassName())
00553         continue;
00554       if (R->hasDefinition())
00555         Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
00556                                                    MNCComplete);
00557       else
00558         Complete = false;
00559     }
00560   }
00561   MNCComplete[RD] = Complete;
00562   return Complete;
00563 }
00564 
00565 /// \brief Returns true, if the given CXXRecordDecl is fully defined in this
00566 /// translation unit, i.e. all methods are defined or pure virtual and all
00567 /// friends, friend functions and nested classes are fully defined in this
00568 /// translation unit.
00569 ///
00570 /// Should only be called from ActOnEndOfTranslationUnit so that all
00571 /// definitions are actually read.
00572 static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
00573                                  RecordCompleteMap &RecordsComplete,
00574                                  RecordCompleteMap &MNCComplete) {
00575   RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
00576   if (Cache != RecordsComplete.end())
00577     return Cache->second;
00578   bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
00579   for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
00580                                       E = RD->friend_end();
00581        I != E && Complete; ++I) {
00582     // Check if friend classes and methods are complete.
00583     if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
00584       // Friend classes are available as the TypeSourceInfo of the FriendDecl.
00585       if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
00586         Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
00587       else
00588         Complete = false;
00589     } else {
00590       // Friend functions are available through the NamedDecl of FriendDecl.
00591       if (const FunctionDecl *FD =
00592           dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
00593         Complete = FD->isDefined();
00594       else
00595         // This is a template friend, give up.
00596         Complete = false;
00597     }
00598   }
00599   RecordsComplete[RD] = Complete;
00600   return Complete;
00601 }
00602 
00603 void Sema::emitAndClearUnusedLocalTypedefWarnings() {
00604   if (ExternalSource)
00605     ExternalSource->ReadUnusedLocalTypedefNameCandidates(
00606         UnusedLocalTypedefNameCandidates);
00607   for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
00608     if (TD->isReferenced())
00609       continue;
00610     Diag(TD->getLocation(), diag::warn_unused_local_typedef)
00611         << isa<TypeAliasDecl>(TD) << TD->getDeclName();
00612   }
00613   UnusedLocalTypedefNameCandidates.clear();
00614 }
00615 
00616 /// ActOnEndOfTranslationUnit - This is called at the very end of the
00617 /// translation unit when EOF is reached and all but the top-level scope is
00618 /// popped.
00619 void Sema::ActOnEndOfTranslationUnit() {
00620   assert(DelayedDiagnostics.getCurrentPool() == nullptr
00621          && "reached end of translation unit with a pool attached?");
00622 
00623   // If code completion is enabled, don't perform any end-of-translation-unit
00624   // work.
00625   if (PP.isCodeCompletionEnabled())
00626     return;
00627 
00628   // Complete translation units and modules define vtables and perform implicit
00629   // instantiations. PCH files do not.
00630   if (TUKind != TU_Prefix) {
00631     DiagnoseUseOfUnimplementedSelectors();
00632 
00633     // If any dynamic classes have their key function defined within
00634     // this translation unit, then those vtables are considered "used" and must
00635     // be emitted.
00636     for (DynamicClassesType::iterator I = DynamicClasses.begin(ExternalSource),
00637                                       E = DynamicClasses.end();
00638          I != E; ++I) {
00639       assert(!(*I)->isDependentType() &&
00640              "Should not see dependent types here!");
00641       if (const CXXMethodDecl *KeyFunction =
00642               Context.getCurrentKeyFunction(*I)) {
00643         const FunctionDecl *Definition = nullptr;
00644         if (KeyFunction->hasBody(Definition))
00645           MarkVTableUsed(Definition->getLocation(), *I, true);
00646       }
00647     }
00648 
00649     // If DefinedUsedVTables ends up marking any virtual member functions it
00650     // might lead to more pending template instantiations, which we then need
00651     // to instantiate.
00652     DefineUsedVTables();
00653 
00654     // C++: Perform implicit template instantiations.
00655     //
00656     // FIXME: When we perform these implicit instantiations, we do not
00657     // carefully keep track of the point of instantiation (C++ [temp.point]).
00658     // This means that name lookup that occurs within the template
00659     // instantiation will always happen at the end of the translation unit,
00660     // so it will find some names that are not required to be found. This is
00661     // valid, but we could do better by diagnosing if an instantiation uses a
00662     // name that was not visible at its first point of instantiation.
00663     if (ExternalSource) {
00664       // Load pending instantiations from the external source.
00665       SmallVector<PendingImplicitInstantiation, 4> Pending;
00666       ExternalSource->ReadPendingInstantiations(Pending);
00667       PendingInstantiations.insert(PendingInstantiations.begin(),
00668                                    Pending.begin(), Pending.end());
00669     }
00670     PerformPendingInstantiations();
00671 
00672     if (LateTemplateParserCleanup)
00673       LateTemplateParserCleanup(OpaqueParser);
00674 
00675     CheckDelayedMemberExceptionSpecs();
00676   }
00677 
00678   // All delayed member exception specs should be checked or we end up accepting
00679   // incompatible declarations.
00680   assert(DelayedDefaultedMemberExceptionSpecs.empty());
00681   assert(DelayedDestructorExceptionSpecChecks.empty());
00682 
00683   // Remove file scoped decls that turned out to be used.
00684   UnusedFileScopedDecls.erase(
00685       std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
00686                      UnusedFileScopedDecls.end(),
00687                      std::bind1st(std::ptr_fun(ShouldRemoveFromUnused), this)),
00688       UnusedFileScopedDecls.end());
00689 
00690   if (TUKind == TU_Prefix) {
00691     // Translation unit prefixes don't need any of the checking below.
00692     TUScope = nullptr;
00693     return;
00694   }
00695 
00696   // Check for #pragma weak identifiers that were never declared
00697   // FIXME: This will cause diagnostics to be emitted in a non-determinstic
00698   // order!  Iterating over a densemap like this is bad.
00699   LoadExternalWeakUndeclaredIdentifiers();
00700   for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
00701        I = WeakUndeclaredIdentifiers.begin(),
00702        E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
00703     if (I->second.getUsed()) continue;
00704 
00705     Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
00706       << I->first;
00707   }
00708 
00709   if (LangOpts.CPlusPlus11 &&
00710       !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
00711     CheckDelegatingCtorCycles();
00712 
00713   if (TUKind == TU_Module) {
00714     // If we are building a module, resolve all of the exported declarations
00715     // now.
00716     if (Module *CurrentModule = PP.getCurrentModule()) {
00717       ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
00718 
00719       SmallVector<Module *, 2> Stack;
00720       Stack.push_back(CurrentModule);
00721       while (!Stack.empty()) {
00722         Module *Mod = Stack.pop_back_val();
00723 
00724         // Resolve the exported declarations and conflicts.
00725         // FIXME: Actually complain, once we figure out how to teach the
00726         // diagnostic client to deal with complaints in the module map at this
00727         // point.
00728         ModMap.resolveExports(Mod, /*Complain=*/false);
00729         ModMap.resolveUses(Mod, /*Complain=*/false);
00730         ModMap.resolveConflicts(Mod, /*Complain=*/false);
00731 
00732         // Queue the submodules, so their exports will also be resolved.
00733         for (Module::submodule_iterator Sub = Mod->submodule_begin(),
00734                                      SubEnd = Mod->submodule_end();
00735              Sub != SubEnd; ++Sub) {
00736           Stack.push_back(*Sub);
00737         }
00738       }
00739     }
00740 
00741     // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
00742     // modules when they are built, not every time they are used.
00743     emitAndClearUnusedLocalTypedefWarnings();
00744 
00745     // Modules don't need any of the checking below.
00746     TUScope = nullptr;
00747     return;
00748   }
00749 
00750   // C99 6.9.2p2:
00751   //   A declaration of an identifier for an object that has file
00752   //   scope without an initializer, and without a storage-class
00753   //   specifier or with the storage-class specifier static,
00754   //   constitutes a tentative definition. If a translation unit
00755   //   contains one or more tentative definitions for an identifier,
00756   //   and the translation unit contains no external definition for
00757   //   that identifier, then the behavior is exactly as if the
00758   //   translation unit contains a file scope declaration of that
00759   //   identifier, with the composite type as of the end of the
00760   //   translation unit, with an initializer equal to 0.
00761   llvm::SmallSet<VarDecl *, 32> Seen;
00762   for (TentativeDefinitionsType::iterator
00763             T = TentativeDefinitions.begin(ExternalSource),
00764          TEnd = TentativeDefinitions.end();
00765        T != TEnd; ++T)
00766   {
00767     VarDecl *VD = (*T)->getActingDefinition();
00768 
00769     // If the tentative definition was completed, getActingDefinition() returns
00770     // null. If we've already seen this variable before, insert()'s second
00771     // return value is false.
00772     if (!VD || VD->isInvalidDecl() || !Seen.insert(VD))
00773       continue;
00774 
00775     if (const IncompleteArrayType *ArrayT
00776         = Context.getAsIncompleteArrayType(VD->getType())) {
00777       // Set the length of the array to 1 (C99 6.9.2p5).
00778       Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
00779       llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
00780       QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
00781                                                 One, ArrayType::Normal, 0);
00782       VD->setType(T);
00783     } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
00784                                    diag::err_tentative_def_incomplete_type))
00785       VD->setInvalidDecl();
00786 
00787     CheckCompleteVariableDeclaration(VD);
00788 
00789     // Notify the consumer that we've completed a tentative definition.
00790     if (!VD->isInvalidDecl())
00791       Consumer.CompleteTentativeDefinition(VD);
00792 
00793   }
00794 
00795   // If there were errors, disable 'unused' warnings since they will mostly be
00796   // noise.
00797   if (!Diags.hasErrorOccurred()) {
00798     // Output warning for unused file scoped decls.
00799     for (UnusedFileScopedDeclsType::iterator
00800            I = UnusedFileScopedDecls.begin(ExternalSource),
00801            E = UnusedFileScopedDecls.end(); I != E; ++I) {
00802       if (ShouldRemoveFromUnused(this, *I))
00803         continue;
00804 
00805       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
00806         const FunctionDecl *DiagD;
00807         if (!FD->hasBody(DiagD))
00808           DiagD = FD;
00809         if (DiagD->isDeleted())
00810           continue; // Deleted functions are supposed to be unused.
00811         if (DiagD->isReferenced()) {
00812           if (isa<CXXMethodDecl>(DiagD))
00813             Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
00814                   << DiagD->getDeclName();
00815           else {
00816             if (FD->getStorageClass() == SC_Static &&
00817                 !FD->isInlineSpecified() &&
00818                 !SourceMgr.isInMainFile(
00819                    SourceMgr.getExpansionLoc(FD->getLocation())))
00820               Diag(DiagD->getLocation(),
00821                    diag::warn_unneeded_static_internal_decl)
00822                   << DiagD->getDeclName();
00823             else
00824               Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
00825                    << /*function*/0 << DiagD->getDeclName();
00826           }
00827         } else {
00828           Diag(DiagD->getLocation(),
00829                isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
00830                                          : diag::warn_unused_function)
00831                 << DiagD->getDeclName();
00832         }
00833       } else {
00834         const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
00835         if (!DiagD)
00836           DiagD = cast<VarDecl>(*I);
00837         if (DiagD->isReferenced()) {
00838           Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
00839                 << /*variable*/1 << DiagD->getDeclName();
00840         } else if (DiagD->getType().isConstQualified()) {
00841           Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
00842               << DiagD->getDeclName();
00843         } else {
00844           Diag(DiagD->getLocation(), diag::warn_unused_variable)
00845               << DiagD->getDeclName();
00846         }
00847       }
00848     }
00849 
00850     if (ExternalSource)
00851       ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
00852     checkUndefinedButUsed(*this);
00853 
00854     emitAndClearUnusedLocalTypedefWarnings();
00855   }
00856 
00857   if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
00858     RecordCompleteMap RecordsComplete;
00859     RecordCompleteMap MNCComplete;
00860     for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
00861          E = UnusedPrivateFields.end(); I != E; ++I) {
00862       const NamedDecl *D = *I;
00863       const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
00864       if (RD && !RD->isUnion() &&
00865           IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
00866         Diag(D->getLocation(), diag::warn_unused_private_field)
00867               << D->getDeclName();
00868       }
00869     }
00870   }
00871 
00872   // Check we've noticed that we're no longer parsing the initializer for every
00873   // variable. If we miss cases, then at best we have a performance issue and
00874   // at worst a rejects-valid bug.
00875   assert(ParsingInitForAutoVars.empty() &&
00876          "Didn't unmark var as having its initializer parsed");
00877 
00878   TUScope = nullptr;
00879 }
00880 
00881 
00882 //===----------------------------------------------------------------------===//
00883 // Helper functions.
00884 //===----------------------------------------------------------------------===//
00885 
00886 DeclContext *Sema::getFunctionLevelDeclContext() {
00887   DeclContext *DC = CurContext;
00888 
00889   while (true) {
00890     if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) {
00891       DC = DC->getParent();
00892     } else if (isa<CXXMethodDecl>(DC) &&
00893                cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
00894                cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
00895       DC = DC->getParent()->getParent();
00896     }
00897     else break;
00898   }
00899 
00900   return DC;
00901 }
00902 
00903 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
00904 /// to the function decl for the function being parsed.  If we're currently
00905 /// in a 'block', this returns the containing context.
00906 FunctionDecl *Sema::getCurFunctionDecl() {
00907   DeclContext *DC = getFunctionLevelDeclContext();
00908   return dyn_cast<FunctionDecl>(DC);
00909 }
00910 
00911 ObjCMethodDecl *Sema::getCurMethodDecl() {
00912   DeclContext *DC = getFunctionLevelDeclContext();
00913   while (isa<RecordDecl>(DC))
00914     DC = DC->getParent();
00915   return dyn_cast<ObjCMethodDecl>(DC);
00916 }
00917 
00918 NamedDecl *Sema::getCurFunctionOrMethodDecl() {
00919   DeclContext *DC = getFunctionLevelDeclContext();
00920   if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
00921     return cast<NamedDecl>(DC);
00922   return nullptr;
00923 }
00924 
00925 void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
00926   // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
00927   // and yet we also use the current diag ID on the DiagnosticsEngine. This has
00928   // been made more painfully obvious by the refactor that introduced this
00929   // function, but it is possible that the incoming argument can be
00930   // eliminnated. If it truly cannot be (for example, there is some reentrancy
00931   // issue I am not seeing yet), then there should at least be a clarifying
00932   // comment somewhere.
00933   if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
00934     switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
00935               Diags.getCurrentDiagID())) {
00936     case DiagnosticIDs::SFINAE_Report:
00937       // We'll report the diagnostic below.
00938       break;
00939 
00940     case DiagnosticIDs::SFINAE_SubstitutionFailure:
00941       // Count this failure so that we know that template argument deduction
00942       // has failed.
00943       ++NumSFINAEErrors;
00944 
00945       // Make a copy of this suppressed diagnostic and store it with the
00946       // template-deduction information.
00947       if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
00948         Diagnostic DiagInfo(&Diags);
00949         (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
00950                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
00951       }
00952 
00953       Diags.setLastDiagnosticIgnored();
00954       Diags.Clear();
00955       return;
00956 
00957     case DiagnosticIDs::SFINAE_AccessControl: {
00958       // Per C++ Core Issue 1170, access control is part of SFINAE.
00959       // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
00960       // make access control a part of SFINAE for the purposes of checking
00961       // type traits.
00962       if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
00963         break;
00964 
00965       SourceLocation Loc = Diags.getCurrentDiagLoc();
00966 
00967       // Suppress this diagnostic.
00968       ++NumSFINAEErrors;
00969 
00970       // Make a copy of this suppressed diagnostic and store it with the
00971       // template-deduction information.
00972       if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
00973         Diagnostic DiagInfo(&Diags);
00974         (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
00975                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
00976       }
00977 
00978       Diags.setLastDiagnosticIgnored();
00979       Diags.Clear();
00980 
00981       // Now the diagnostic state is clear, produce a C++98 compatibility
00982       // warning.
00983       Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
00984 
00985       // The last diagnostic which Sema produced was ignored. Suppress any
00986       // notes attached to it.
00987       Diags.setLastDiagnosticIgnored();
00988       return;
00989     }
00990 
00991     case DiagnosticIDs::SFINAE_Suppress:
00992       // Make a copy of this suppressed diagnostic and store it with the
00993       // template-deduction information;
00994       if (*Info) {
00995         Diagnostic DiagInfo(&Diags);
00996         (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
00997                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
00998       }
00999 
01000       // Suppress this diagnostic.
01001       Diags.setLastDiagnosticIgnored();
01002       Diags.Clear();
01003       return;
01004     }
01005   }
01006 
01007   // Set up the context's printing policy based on our current state.
01008   Context.setPrintingPolicy(getPrintingPolicy());
01009 
01010   // Emit the diagnostic.
01011   if (!Diags.EmitCurrentDiagnostic())
01012     return;
01013 
01014   // If this is not a note, and we're in a template instantiation
01015   // that is different from the last template instantiation where
01016   // we emitted an error, print a template instantiation
01017   // backtrace.
01018   if (!DiagnosticIDs::isBuiltinNote(DiagID) &&
01019       !ActiveTemplateInstantiations.empty() &&
01020       ActiveTemplateInstantiations.back()
01021         != LastTemplateInstantiationErrorContext) {
01022     PrintInstantiationStack();
01023     LastTemplateInstantiationErrorContext = ActiveTemplateInstantiations.back();
01024   }
01025 }
01026 
01027 Sema::SemaDiagnosticBuilder
01028 Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
01029   SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
01030   PD.Emit(Builder);
01031 
01032   return Builder;
01033 }
01034 
01035 /// \brief Looks through the macro-expansion chain for the given
01036 /// location, looking for a macro expansion with the given name.
01037 /// If one is found, returns true and sets the location to that
01038 /// expansion loc.
01039 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
01040   SourceLocation loc = locref;
01041   if (!loc.isMacroID()) return false;
01042 
01043   // There's no good way right now to look at the intermediate
01044   // expansions, so just jump to the expansion location.
01045   loc = getSourceManager().getExpansionLoc(loc);
01046 
01047   // If that's written with the name, stop here.
01048   SmallVector<char, 16> buffer;
01049   if (getPreprocessor().getSpelling(loc, buffer) == name) {
01050     locref = loc;
01051     return true;
01052   }
01053   return false;
01054 }
01055 
01056 /// \brief Determines the active Scope associated with the given declaration
01057 /// context.
01058 ///
01059 /// This routine maps a declaration context to the active Scope object that
01060 /// represents that declaration context in the parser. It is typically used
01061 /// from "scope-less" code (e.g., template instantiation, lazy creation of
01062 /// declarations) that injects a name for name-lookup purposes and, therefore,
01063 /// must update the Scope.
01064 ///
01065 /// \returns The scope corresponding to the given declaraion context, or NULL
01066 /// if no such scope is open.
01067 Scope *Sema::getScopeForContext(DeclContext *Ctx) {
01068 
01069   if (!Ctx)
01070     return nullptr;
01071 
01072   Ctx = Ctx->getPrimaryContext();
01073   for (Scope *S = getCurScope(); S; S = S->getParent()) {
01074     // Ignore scopes that cannot have declarations. This is important for
01075     // out-of-line definitions of static class members.
01076     if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
01077       if (DeclContext *Entity = S->getEntity())
01078         if (Ctx == Entity->getPrimaryContext())
01079           return S;
01080   }
01081 
01082   return nullptr;
01083 }
01084 
01085 /// \brief Enter a new function scope
01086 void Sema::PushFunctionScope() {
01087   if (FunctionScopes.size() == 1) {
01088     // Use the "top" function scope rather than having to allocate
01089     // memory for a new scope.
01090     FunctionScopes.back()->Clear();
01091     FunctionScopes.push_back(FunctionScopes.back());
01092     return;
01093   }
01094 
01095   FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
01096 }
01097 
01098 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
01099   FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
01100                                               BlockScope, Block));
01101 }
01102 
01103 LambdaScopeInfo *Sema::PushLambdaScope() {
01104   LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
01105   FunctionScopes.push_back(LSI);
01106   return LSI;
01107 }
01108 
01109 void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
01110   if (LambdaScopeInfo *const LSI = getCurLambda()) {
01111     LSI->AutoTemplateParameterDepth = Depth;
01112     return;
01113   } 
01114   llvm_unreachable( 
01115       "Remove assertion if intentionally called in a non-lambda context.");
01116 }
01117 
01118 void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
01119                                 const Decl *D, const BlockExpr *blkExpr) {
01120   FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
01121   assert(!FunctionScopes.empty() && "mismatched push/pop!");
01122 
01123   // Issue any analysis-based warnings.
01124   if (WP && D)
01125     AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
01126   else
01127     for (const auto &PUD : Scope->PossiblyUnreachableDiags)
01128       Diag(PUD.Loc, PUD.PD);
01129 
01130   if (FunctionScopes.back() != Scope)
01131     delete Scope;
01132 }
01133 
01134 void Sema::PushCompoundScope() {
01135   getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo());
01136 }
01137 
01138 void Sema::PopCompoundScope() {
01139   FunctionScopeInfo *CurFunction = getCurFunction();
01140   assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
01141 
01142   CurFunction->CompoundScopes.pop_back();
01143 }
01144 
01145 /// \brief Determine whether any errors occurred within this function/method/
01146 /// block.
01147 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
01148   return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
01149 }
01150 
01151 BlockScopeInfo *Sema::getCurBlock() {
01152   if (FunctionScopes.empty())
01153     return nullptr;
01154 
01155   auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
01156   if (CurBSI && CurBSI->TheDecl &&
01157       !CurBSI->TheDecl->Encloses(CurContext)) {
01158     // We have switched contexts due to template instantiation.
01159     assert(!ActiveTemplateInstantiations.empty());
01160     return nullptr;
01161   }
01162 
01163   return CurBSI;
01164 }
01165 
01166 LambdaScopeInfo *Sema::getCurLambda() {
01167   if (FunctionScopes.empty())
01168     return nullptr;
01169 
01170   auto CurLSI = dyn_cast<LambdaScopeInfo>(FunctionScopes.back());
01171   if (CurLSI && CurLSI->Lambda &&
01172       !CurLSI->Lambda->Encloses(CurContext)) {
01173     // We have switched contexts due to template instantiation.
01174     assert(!ActiveTemplateInstantiations.empty());
01175     return nullptr;
01176   }
01177 
01178   return CurLSI;
01179 }
01180 // We have a generic lambda if we parsed auto parameters, or we have 
01181 // an associated template parameter list.
01182 LambdaScopeInfo *Sema::getCurGenericLambda() {
01183   if (LambdaScopeInfo *LSI =  getCurLambda()) {
01184     return (LSI->AutoTemplateParams.size() ||
01185                     LSI->GLTemplateParameterList) ? LSI : nullptr;
01186   }
01187   return nullptr;
01188 }
01189 
01190 
01191 void Sema::ActOnComment(SourceRange Comment) {
01192   if (!LangOpts.RetainCommentsFromSystemHeaders &&
01193       SourceMgr.isInSystemHeader(Comment.getBegin()))
01194     return;
01195   RawComment RC(SourceMgr, Comment, false,
01196                 LangOpts.CommentOpts.ParseAllComments);
01197   if (RC.isAlmostTrailingComment()) {
01198     SourceRange MagicMarkerRange(Comment.getBegin(),
01199                                  Comment.getBegin().getLocWithOffset(3));
01200     StringRef MagicMarkerText;
01201     switch (RC.getKind()) {
01202     case RawComment::RCK_OrdinaryBCPL:
01203       MagicMarkerText = "///<";
01204       break;
01205     case RawComment::RCK_OrdinaryC:
01206       MagicMarkerText = "/**<";
01207       break;
01208     default:
01209       llvm_unreachable("if this is an almost Doxygen comment, "
01210                        "it should be ordinary");
01211     }
01212     Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
01213       FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
01214   }
01215   Context.addComment(RC);
01216 }
01217 
01218 // Pin this vtable to this file.
01219 ExternalSemaSource::~ExternalSemaSource() {}
01220 
01221 void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
01222 
01223 void ExternalSemaSource::ReadKnownNamespaces(
01224                            SmallVectorImpl<NamespaceDecl *> &Namespaces) {
01225 }
01226 
01227 void ExternalSemaSource::ReadUndefinedButUsed(
01228                        llvm::DenseMap<NamedDecl *, SourceLocation> &Undefined) {
01229 }
01230 
01231 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
01232   SourceLocation Loc = this->Loc;
01233   if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
01234   if (Loc.isValid()) {
01235     Loc.print(OS, S.getSourceManager());
01236     OS << ": ";
01237   }
01238   OS << Message;
01239 
01240   if (TheDecl && isa<NamedDecl>(TheDecl)) {
01241     std::string Name = cast<NamedDecl>(TheDecl)->getNameAsString();
01242     if (!Name.empty())
01243       OS << " '" << Name << '\'';
01244   }
01245 
01246   OS << '\n';
01247 }
01248 
01249 /// \brief Figure out if an expression could be turned into a call.
01250 ///
01251 /// Use this when trying to recover from an error where the programmer may have
01252 /// written just the name of a function instead of actually calling it.
01253 ///
01254 /// \param E - The expression to examine.
01255 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
01256 ///  with no arguments, this parameter is set to the type returned by such a
01257 ///  call; otherwise, it is set to an empty QualType.
01258 /// \param OverloadSet - If the expression is an overloaded function
01259 ///  name, this parameter is populated with the decls of the various overloads.
01260 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
01261                          UnresolvedSetImpl &OverloadSet) {
01262   ZeroArgCallReturnTy = QualType();
01263   OverloadSet.clear();
01264 
01265   const OverloadExpr *Overloads = nullptr;
01266   bool IsMemExpr = false;
01267   if (E.getType() == Context.OverloadTy) {
01268     OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
01269 
01270     // Ignore overloads that are pointer-to-member constants.
01271     if (FR.HasFormOfMemberPointer)
01272       return false;
01273 
01274     Overloads = FR.Expression;
01275   } else if (E.getType() == Context.BoundMemberTy) {
01276     Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
01277     IsMemExpr = true;
01278   }
01279 
01280   bool Ambiguous = false;
01281 
01282   if (Overloads) {
01283     for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
01284          DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
01285       OverloadSet.addDecl(*it);
01286 
01287       // Check whether the function is a non-template, non-member which takes no
01288       // arguments.
01289       if (IsMemExpr)
01290         continue;
01291       if (const FunctionDecl *OverloadDecl
01292             = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
01293         if (OverloadDecl->getMinRequiredArguments() == 0) {
01294           if (!ZeroArgCallReturnTy.isNull() && !Ambiguous) {
01295             ZeroArgCallReturnTy = QualType();
01296             Ambiguous = true;
01297           } else
01298             ZeroArgCallReturnTy = OverloadDecl->getReturnType();
01299         }
01300       }
01301     }
01302 
01303     // If it's not a member, use better machinery to try to resolve the call
01304     if (!IsMemExpr)
01305       return !ZeroArgCallReturnTy.isNull();
01306   }
01307 
01308   // Attempt to call the member with no arguments - this will correctly handle
01309   // member templates with defaults/deduction of template arguments, overloads
01310   // with default arguments, etc.
01311   if (IsMemExpr && !E.isTypeDependent()) {
01312     bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
01313     getDiagnostics().setSuppressAllDiagnostics(true);
01314     ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
01315                                              None, SourceLocation());
01316     getDiagnostics().setSuppressAllDiagnostics(Suppress);
01317     if (R.isUsable()) {
01318       ZeroArgCallReturnTy = R.get()->getType();
01319       return true;
01320     }
01321     return false;
01322   }
01323 
01324   if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
01325     if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
01326       if (Fun->getMinRequiredArguments() == 0)
01327         ZeroArgCallReturnTy = Fun->getReturnType();
01328       return true;
01329     }
01330   }
01331 
01332   // We don't have an expression that's convenient to get a FunctionDecl from,
01333   // but we can at least check if the type is "function of 0 arguments".
01334   QualType ExprTy = E.getType();
01335   const FunctionType *FunTy = nullptr;
01336   QualType PointeeTy = ExprTy->getPointeeType();
01337   if (!PointeeTy.isNull())
01338     FunTy = PointeeTy->getAs<FunctionType>();
01339   if (!FunTy)
01340     FunTy = ExprTy->getAs<FunctionType>();
01341 
01342   if (const FunctionProtoType *FPT =
01343       dyn_cast_or_null<FunctionProtoType>(FunTy)) {
01344     if (FPT->getNumParams() == 0)
01345       ZeroArgCallReturnTy = FunTy->getReturnType();
01346     return true;
01347   }
01348   return false;
01349 }
01350 
01351 /// \brief Give notes for a set of overloads.
01352 ///
01353 /// A companion to tryExprAsCall. In cases when the name that the programmer
01354 /// wrote was an overloaded function, we may be able to make some guesses about
01355 /// plausible overloads based on their return types; such guesses can be handed
01356 /// off to this method to be emitted as notes.
01357 ///
01358 /// \param Overloads - The overloads to note.
01359 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
01360 ///  -fshow-overloads=best, this is the location to attach to the note about too
01361 ///  many candidates. Typically this will be the location of the original
01362 ///  ill-formed expression.
01363 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
01364                           const SourceLocation FinalNoteLoc) {
01365   int ShownOverloads = 0;
01366   int SuppressedOverloads = 0;
01367   for (UnresolvedSetImpl::iterator It = Overloads.begin(),
01368        DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
01369     // FIXME: Magic number for max shown overloads stolen from
01370     // OverloadCandidateSet::NoteCandidates.
01371     if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) {
01372       ++SuppressedOverloads;
01373       continue;
01374     }
01375 
01376     NamedDecl *Fn = (*It)->getUnderlyingDecl();
01377     S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
01378     ++ShownOverloads;
01379   }
01380 
01381   if (SuppressedOverloads)
01382     S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
01383       << SuppressedOverloads;
01384 }
01385 
01386 static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
01387                                    const UnresolvedSetImpl &Overloads,
01388                                    bool (*IsPlausibleResult)(QualType)) {
01389   if (!IsPlausibleResult)
01390     return noteOverloads(S, Overloads, Loc);
01391 
01392   UnresolvedSet<2> PlausibleOverloads;
01393   for (OverloadExpr::decls_iterator It = Overloads.begin(),
01394          DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
01395     const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
01396     QualType OverloadResultTy = OverloadDecl->getReturnType();
01397     if (IsPlausibleResult(OverloadResultTy))
01398       PlausibleOverloads.addDecl(It.getDecl());
01399   }
01400   noteOverloads(S, PlausibleOverloads, Loc);
01401 }
01402 
01403 /// Determine whether the given expression can be called by just
01404 /// putting parentheses after it.  Notably, expressions with unary
01405 /// operators can't be because the unary operator will start parsing
01406 /// outside the call.
01407 static bool IsCallableWithAppend(Expr *E) {
01408   E = E->IgnoreImplicit();
01409   return (!isa<CStyleCastExpr>(E) &&
01410           !isa<UnaryOperator>(E) &&
01411           !isa<BinaryOperator>(E) &&
01412           !isa<CXXOperatorCallExpr>(E));
01413 }
01414 
01415 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
01416                                 bool ForceComplain,
01417                                 bool (*IsPlausibleResult)(QualType)) {
01418   SourceLocation Loc = E.get()->getExprLoc();
01419   SourceRange Range = E.get()->getSourceRange();
01420 
01421   QualType ZeroArgCallTy;
01422   UnresolvedSet<4> Overloads;
01423   if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
01424       !ZeroArgCallTy.isNull() &&
01425       (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
01426     // At this point, we know E is potentially callable with 0
01427     // arguments and that it returns something of a reasonable type,
01428     // so we can emit a fixit and carry on pretending that E was
01429     // actually a CallExpr.
01430     SourceLocation ParenInsertionLoc = PP.getLocForEndOfToken(Range.getEnd());
01431     Diag(Loc, PD)
01432       << /*zero-arg*/ 1 << Range
01433       << (IsCallableWithAppend(E.get())
01434           ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
01435           : FixItHint());
01436     notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
01437 
01438     // FIXME: Try this before emitting the fixit, and suppress diagnostics
01439     // while doing so.
01440     E = ActOnCallExpr(nullptr, E.get(), Range.getEnd(), None,
01441                       Range.getEnd().getLocWithOffset(1));
01442     return true;
01443   }
01444 
01445   if (!ForceComplain) return false;
01446 
01447   Diag(Loc, PD) << /*not zero-arg*/ 0 << Range;
01448   notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
01449   E = ExprError();
01450   return true;
01451 }
01452 
01453 IdentifierInfo *Sema::getSuperIdentifier() const {
01454   if (!Ident_super)
01455     Ident_super = &Context.Idents.get("super");
01456   return Ident_super;
01457 }
01458 
01459 IdentifierInfo *Sema::getFloat128Identifier() const {
01460   if (!Ident___float128)
01461     Ident___float128 = &Context.Idents.get("__float128");
01462   return Ident___float128;
01463 }
01464 
01465 void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
01466                                    CapturedRegionKind K) {
01467   CapturingScopeInfo *CSI = new CapturedRegionScopeInfo(
01468       getDiagnostics(), S, CD, RD, CD->getContextParam(), K);
01469   CSI->ReturnType = Context.VoidTy;
01470   FunctionScopes.push_back(CSI);
01471 }
01472 
01473 CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
01474   if (FunctionScopes.empty())
01475     return nullptr;
01476 
01477   return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
01478 }