1193326Sed//===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed// This file implements the actions class which performs semantic analysis and
11193326Sed// builds an AST out of a parse stream.
12193326Sed//
13193326Sed//===----------------------------------------------------------------------===//
14193326Sed
15212904Sdim#include "clang/Sema/SemaInternal.h"
16202379Srdivacky#include "TargetAttributesSema.h"
17193326Sed#include "clang/AST/ASTContext.h"
18203955Srdivacky#include "clang/AST/ASTDiagnostic.h"
19212904Sdim#include "clang/AST/DeclCXX.h"
20239462Sdim#include "clang/AST/DeclFriend.h"
21193326Sed#include "clang/AST/DeclObjC.h"
22193326Sed#include "clang/AST/Expr.h"
23223017Sdim#include "clang/AST/ExprCXX.h"
24218893Sdim#include "clang/AST/StmtCXX.h"
25226633Sdim#include "clang/Basic/FileManager.h"
26198092Srdivacky#include "clang/Basic/PartialDiagnostic.h"
27193326Sed#include "clang/Basic/TargetInfo.h"
28249423Sdim#include "clang/Lex/HeaderSearch.h"
29249423Sdim#include "clang/Lex/Preprocessor.h"
30249423Sdim#include "clang/Sema/CXXFieldCollector.h"
31249423Sdim#include "clang/Sema/DelayedDiagnostic.h"
32249423Sdim#include "clang/Sema/ExternalSemaSource.h"
33249423Sdim#include "clang/Sema/MultiplexExternalSemaSource.h"
34249423Sdim#include "clang/Sema/ObjCMethodList.h"
35249423Sdim#include "clang/Sema/PrettyDeclStackTrace.h"
36249423Sdim#include "clang/Sema/Scope.h"
37249423Sdim#include "clang/Sema/ScopeInfo.h"
38249423Sdim#include "clang/Sema/SemaConsumer.h"
39249423Sdim#include "clang/Sema/TemplateDeduction.h"
40249423Sdim#include "llvm/ADT/APFloat.h"
41249423Sdim#include "llvm/ADT/DenseMap.h"
42249423Sdim#include "llvm/ADT/SmallSet.h"
43249423Sdim#include "llvm/Support/CrashRecoveryContext.h"
44193326Sedusing namespace clang;
45212904Sdimusing namespace sema;
46204643Srdivacky
47234353SdimPrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
48234353Sdim                                       const Preprocessor &PP) {
49226633Sdim  PrintingPolicy Policy = Context.getPrintingPolicy();
50234353Sdim  Policy.Bool = Context.getLangOpts().Bool;
51226633Sdim  if (!Policy.Bool) {
52249423Sdim    if (const MacroInfo *
53249423Sdim          BoolMacro = PP.getMacroInfo(&Context.Idents.get("bool"))) {
54249423Sdim      Policy.Bool = BoolMacro->isObjectLike() &&
55226633Sdim        BoolMacro->getNumTokens() == 1 &&
56226633Sdim        BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
57226633Sdim    }
58226633Sdim  }
59249423Sdim
60226633Sdim  return Policy;
61226633Sdim}
62226633Sdim
63212904Sdimvoid Sema::ActOnTranslationUnitScope(Scope *S) {
64193326Sed  TUScope = S;
65193326Sed  PushDeclContext(S, Context.getTranslationUnitDecl());
66198092Srdivacky
67210299Sed  VAListTagName = PP.getIdentifierInfo("__va_list_tag");
68193326Sed}
69193326Sed
70193326SedSema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
71226633Sdim           TranslationUnitKind TUKind,
72199482Srdivacky           CodeCompleteConsumer *CodeCompleter)
73249423Sdim  : TheTargetAttributesSema(0), ExternalSource(0),
74243830Sdim    isMultiplexExternalSource(false), FPFeatures(pp.getLangOpts()),
75234353Sdim    LangOpts(pp.getLangOpts()), PP(pp), Context(ctxt), Consumer(consumer),
76198092Srdivacky    Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
77243830Sdim    CollectStats(false), CodeCompleter(CodeCompleter),
78226633Sdim    CurContext(0), OriginalLexicalContext(0),
79226633Sdim    PackContext(0), MSStructPragmaOn(false), VisContext(0),
80243830Sdim    IsBuildingRecoveryCallExpr(false),
81234353Sdim    ExprNeedsCleanups(false), LateTemplateParser(0), OpaqueParser(0),
82234353Sdim    IdResolver(pp), StdInitializerList(0), CXXTypeInfoDecl(0), MSVCGuidDecl(0),
83239462Sdim    NSNumberDecl(0),
84239462Sdim    NSStringDecl(0), StringWithUTF8StringMethod(0),
85239462Sdim    NSArrayDecl(0), ArrayWithObjectsMethod(0),
86234353Sdim    NSDictionaryDecl(0), DictionaryWithObjectsMethod(0),
87249423Sdim    GlobalNewDeleteDeclared(false),
88226633Sdim    TUKind(TUKind),
89239462Sdim    NumSFINAEErrors(0), InFunctionDeclarator(0),
90218893Sdim    AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
91218893Sdim    NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
92263508Sdim    CurrentInstantiationScope(0), DisableTypoCorrection(false),
93263508Sdim    TyposCorrected(0), AnalysisWarnings(*this),
94263508Sdim    VarDataSharingAttributesStack(0), CurScope(0),
95263508Sdim    Ident_super(0), Ident___float128(0)
96199482Srdivacky{
97193326Sed  TUScope = 0;
98249423Sdim
99224145Sdim  LoadedExternalKnownNamespaces = false;
100234353Sdim  for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
101234353Sdim    NSNumberLiteralMethods[I] = 0;
102234353Sdim
103234353Sdim  if (getLangOpts().ObjC1)
104234353Sdim    NSAPIObj.reset(new NSAPI(Context));
105234353Sdim
106234353Sdim  if (getLangOpts().CPlusPlus)
107193326Sed    FieldCollector.reset(new CXXFieldCollector());
108198092Srdivacky
109193326Sed  // Tell diagnostics how to render things from the AST library.
110249423Sdim  PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
111203955Srdivacky                                       &Context);
112199990Srdivacky
113199990Srdivacky  ExprEvalContexts.push_back(
114234353Sdim        ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0,
115234353Sdim                                          false, 0, false));
116212904Sdim
117218893Sdim  FunctionScopes.push_back(new FunctionScopeInfo(Diags));
118263508Sdim
119263508Sdim  // Initilization of data sharing attributes stack for OpenMP
120263508Sdim  InitDataSharingAttributesStack();
121193326Sed}
122193326Sed
123212904Sdimvoid Sema::Initialize() {
124212904Sdim  // Tell the AST consumer about this Sema object.
125212904Sdim  Consumer.Initialize(Context);
126249423Sdim
127212904Sdim  // FIXME: Isn't this redundant with the initialization above?
128212904Sdim  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
129212904Sdim    SC->InitializeSema(*this);
130249423Sdim
131212904Sdim  // Tell the external Sema source about this Sema object.
132212904Sdim  if (ExternalSemaSource *ExternalSema
133212904Sdim      = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
134212904Sdim    ExternalSema->InitializeSema(*this);
135226633Sdim
136226633Sdim  // Initialize predefined 128-bit integer types, if needed.
137249423Sdim  if (PP.getTargetInfo().hasInt128Type()) {
138226633Sdim    // If either of the 128-bit integer types are unavailable to name lookup,
139226633Sdim    // define them now.
140226633Sdim    DeclarationName Int128 = &Context.Idents.get("__int128_t");
141234353Sdim    if (IdResolver.begin(Int128) == IdResolver.end())
142226633Sdim      PushOnScopeChains(Context.getInt128Decl(), TUScope);
143226633Sdim
144226633Sdim    DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
145234353Sdim    if (IdResolver.begin(UInt128) == IdResolver.end())
146226633Sdim      PushOnScopeChains(Context.getUInt128Decl(), TUScope);
147226633Sdim  }
148226633Sdim
149249423Sdim
150226633Sdim  // Initialize predefined Objective-C types:
151234353Sdim  if (PP.getLangOpts().ObjC1) {
152226633Sdim    // If 'SEL' does not yet refer to any declarations, make it refer to the
153226633Sdim    // predefined 'SEL'.
154226633Sdim    DeclarationName SEL = &Context.Idents.get("SEL");
155234353Sdim    if (IdResolver.begin(SEL) == IdResolver.end())
156226633Sdim      PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
157226633Sdim
158226633Sdim    // If 'id' does not yet refer to any declarations, make it refer to the
159226633Sdim    // predefined 'id'.
160226633Sdim    DeclarationName Id = &Context.Idents.get("id");
161234353Sdim    if (IdResolver.begin(Id) == IdResolver.end())
162226633Sdim      PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
163249423Sdim
164226633Sdim    // Create the built-in typedef for 'Class'.
165226633Sdim    DeclarationName Class = &Context.Idents.get("Class");
166234353Sdim    if (IdResolver.begin(Class) == IdResolver.end())
167226633Sdim      PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
168234353Sdim
169234353Sdim    // Create the built-in forward declaratino for 'Protocol'.
170234353Sdim    DeclarationName Protocol = &Context.Idents.get("Protocol");
171234353Sdim    if (IdResolver.begin(Protocol) == IdResolver.end())
172234353Sdim      PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
173226633Sdim  }
174239462Sdim
175239462Sdim  DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
176239462Sdim  if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
177239462Sdim    PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
178212904Sdim}
179212904Sdim
180202379SrdivackySema::~Sema() {
181263508Sdim  for (LateParsedTemplateMapT::iterator I = LateParsedTemplateMap.begin(),
182263508Sdim                                        E = LateParsedTemplateMap.end();
183263508Sdim       I != E; ++I)
184263508Sdim    delete I->second;
185202379Srdivacky  if (PackContext) FreePackedContext();
186212904Sdim  if (VisContext) FreeVisContext();
187202379Srdivacky  delete TheTargetAttributesSema;
188221345Sdim  MSStructPragmaOn = false;
189212904Sdim  // Kill all the active scopes.
190212904Sdim  for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
191212904Sdim    delete FunctionScopes[I];
192212904Sdim  if (FunctionScopes.size() == 1)
193212904Sdim    delete FunctionScopes[0];
194249423Sdim
195212904Sdim  // Tell the SemaConsumer to forget about us; we're going out of scope.
196212904Sdim  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
197212904Sdim    SC->ForgetSema();
198212904Sdim
199212904Sdim  // Detach from the external Sema source.
200212904Sdim  if (ExternalSemaSource *ExternalSema
201212904Sdim        = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
202212904Sdim    ExternalSema->ForgetSema();
203243830Sdim
204243830Sdim  // If Sema's ExternalSource is the multiplexer - we own it.
205243830Sdim  if (isMultiplexExternalSource)
206243830Sdim    delete ExternalSource;
207263508Sdim
208263508Sdim  // Destroys data sharing attributes stack for OpenMP
209263508Sdim  DestroyDataSharingAttributesStack();
210199482Srdivacky}
211199482Srdivacky
212224145Sdim/// makeUnavailableInSystemHeader - There is an error in the current
213224145Sdim/// context.  If we're still in a system header, and we can plausibly
214224145Sdim/// make the relevant declaration unavailable instead of erroring, do
215224145Sdim/// so and return true.
216224145Sdimbool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
217226633Sdim                                         StringRef msg) {
218224145Sdim  // If we're not in a function, it's an error.
219224145Sdim  FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
220224145Sdim  if (!fn) return false;
221224145Sdim
222224145Sdim  // If we're in template instantiation, it's an error.
223224145Sdim  if (!ActiveTemplateInstantiations.empty())
224224145Sdim    return false;
225249423Sdim
226224145Sdim  // If that function's not in a system header, it's an error.
227224145Sdim  if (!Context.getSourceManager().isInSystemHeader(loc))
228224145Sdim    return false;
229224145Sdim
230224145Sdim  // If the function is already unavailable, it's not an error.
231224145Sdim  if (fn->hasAttr<UnavailableAttr>()) return true;
232224145Sdim
233224145Sdim  fn->addAttr(new (Context) UnavailableAttr(loc, Context, msg));
234224145Sdim  return true;
235224145Sdim}
236224145Sdim
237221345SdimASTMutationListener *Sema::getASTMutationListener() const {
238221345Sdim  return getASTConsumer().GetASTMutationListener();
239221345Sdim}
240221345Sdim
241243830Sdim///\brief Registers an external source. If an external source already exists,
242243830Sdim/// creates a multiplex external source and appends to it.
243243830Sdim///
244243830Sdim///\param[in] E - A non-null external sema source.
245243830Sdim///
246243830Sdimvoid Sema::addExternalSource(ExternalSemaSource *E) {
247243830Sdim  assert(E && "Cannot use with NULL ptr");
248243830Sdim
249243830Sdim  if (!ExternalSource) {
250243830Sdim    ExternalSource = E;
251243830Sdim    return;
252243830Sdim  }
253243830Sdim
254243830Sdim  if (isMultiplexExternalSource)
255243830Sdim    static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
256243830Sdim  else {
257243830Sdim    ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
258243830Sdim    isMultiplexExternalSource = true;
259243830Sdim  }
260243830Sdim}
261243830Sdim
262224145Sdim/// \brief Print out statistics about the semantic analysis.
263224145Sdimvoid Sema::PrintStats() const {
264224145Sdim  llvm::errs() << "\n*** Semantic Analysis Stats:\n";
265224145Sdim  llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
266224145Sdim
267224145Sdim  BumpAlloc.PrintStats();
268224145Sdim  AnalysisWarnings.PrintStats();
269224145Sdim}
270224145Sdim
271198092Srdivacky/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
272193326Sed/// If there is already an implicit cast, merge into the existing one.
273212904Sdim/// The result is of the given category.
274221345SdimExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
275221345Sdim                                   CastKind Kind, ExprValueKind VK,
276224145Sdim                                   const CXXCastPath *BasePath,
277224145Sdim                                   CheckedConversionKind CCK) {
278234353Sdim#ifndef NDEBUG
279234353Sdim  if (VK == VK_RValue && !E->isRValue()) {
280234353Sdim    switch (Kind) {
281234353Sdim    default:
282234353Sdim      assert(0 && "can't implicitly cast lvalue to rvalue with this cast kind");
283234353Sdim    case CK_LValueToRValue:
284234353Sdim    case CK_ArrayToPointerDecay:
285234353Sdim    case CK_FunctionToPointerDecay:
286234353Sdim    case CK_ToVoid:
287234353Sdim      break;
288234353Sdim    }
289234353Sdim  }
290234353Sdim  assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue");
291234353Sdim#endif
292234353Sdim
293221345Sdim  QualType ExprTy = Context.getCanonicalType(E->getType());
294193326Sed  QualType TypeTy = Context.getCanonicalType(Ty);
295198092Srdivacky
296193326Sed  if (ExprTy == TypeTy)
297221345Sdim    return Owned(E);
298198092Srdivacky
299208600Srdivacky  // If this is a derived-to-base cast to a through a virtual base, we
300208600Srdivacky  // need a vtable.
301249423Sdim  if (Kind == CK_DerivedToBase &&
302212904Sdim      BasePathInvolvesVirtualBase(*BasePath)) {
303221345Sdim    QualType T = E->getType();
304208600Srdivacky    if (const PointerType *Pointer = T->getAs<PointerType>())
305208600Srdivacky      T = Pointer->getPointeeType();
306208600Srdivacky    if (const RecordType *RecordTy = T->getAs<RecordType>())
307249423Sdim      MarkVTableUsed(E->getLocStart(),
308208600Srdivacky                     cast<CXXRecordDecl>(RecordTy->getDecl()));
309208600Srdivacky  }
310199482Srdivacky
311221345Sdim  if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
312212904Sdim    if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
313198092Srdivacky      ImpCast->setType(Ty);
314212904Sdim      ImpCast->setValueKind(VK);
315221345Sdim      return Owned(E);
316198092Srdivacky    }
317198092Srdivacky  }
318198092Srdivacky
319221345Sdim  return Owned(ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK));
320193326Sed}
321193326Sed
322221345Sdim/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
323221345Sdim/// to the conversion from scalar type ScalarTy to the Boolean type.
324221345SdimCastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
325221345Sdim  switch (ScalarTy->getScalarTypeKind()) {
326221345Sdim  case Type::STK_Bool: return CK_NoOp;
327226633Sdim  case Type::STK_CPointer: return CK_PointerToBoolean;
328226633Sdim  case Type::STK_BlockPointer: return CK_PointerToBoolean;
329226633Sdim  case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
330221345Sdim  case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
331221345Sdim  case Type::STK_Integral: return CK_IntegralToBoolean;
332221345Sdim  case Type::STK_Floating: return CK_FloatingToBoolean;
333221345Sdim  case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
334221345Sdim  case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
335221345Sdim  }
336221345Sdim  return CK_Invalid;
337221345Sdim}
338221345Sdim
339212904Sdim/// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
340212904Sdimstatic bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
341249423Sdim  if (D->getMostRecentDecl()->isUsed())
342212904Sdim    return true;
343212904Sdim
344263508Sdim  if (D->isExternallyVisible())
345249423Sdim    return true;
346249423Sdim
347212904Sdim  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
348212904Sdim    // UnusedFileScopedDecls stores the first declaration.
349212904Sdim    // The declaration may have become definition so check again.
350212904Sdim    const FunctionDecl *DeclToCheck;
351212904Sdim    if (FD->hasBody(DeclToCheck))
352212904Sdim      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
353212904Sdim
354212904Sdim    // Later redecls may add new information resulting in not having to warn,
355212904Sdim    // so check again.
356234353Sdim    DeclToCheck = FD->getMostRecentDecl();
357212904Sdim    if (DeclToCheck != FD)
358212904Sdim      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
359212904Sdim  }
360212904Sdim
361212904Sdim  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
362263508Sdim    // If a variable usable in constant expressions is referenced,
363263508Sdim    // don't warn if it isn't used: if the value of a variable is required
364263508Sdim    // for the computation of a constant expression, it doesn't make sense to
365263508Sdim    // warn even if the variable isn't odr-used.  (isReferenced doesn't
366263508Sdim    // precisely reflect that, but it's a decent approximation.)
367263508Sdim    if (VD->isReferenced() &&
368263508Sdim        VD->isUsableInConstantExpressions(SemaRef->Context))
369263508Sdim      return true;
370263508Sdim
371212904Sdim    // UnusedFileScopedDecls stores the first declaration.
372212904Sdim    // The declaration may have become definition so check again.
373249423Sdim    const VarDecl *DeclToCheck = VD->getDefinition();
374212904Sdim    if (DeclToCheck)
375212904Sdim      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
376212904Sdim
377212904Sdim    // Later redecls may add new information resulting in not having to warn,
378212904Sdim    // so check again.
379234353Sdim    DeclToCheck = VD->getMostRecentDecl();
380212904Sdim    if (DeclToCheck != VD)
381212904Sdim      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
382212904Sdim  }
383212904Sdim
384212904Sdim  return false;
385193326Sed}
386193326Sed
387218893Sdimnamespace {
388249423Sdim  struct SortUndefinedButUsed {
389249423Sdim    const SourceManager &SM;
390249423Sdim    explicit SortUndefinedButUsed(SourceManager &SM) : SM(SM) {}
391218893Sdim
392249423Sdim    bool operator()(const std::pair<NamedDecl *, SourceLocation> &l,
393249423Sdim                    const std::pair<NamedDecl *, SourceLocation> &r) const {
394249423Sdim      if (l.second.isValid() && !r.second.isValid())
395249423Sdim        return true;
396249423Sdim      if (!l.second.isValid() && r.second.isValid())
397249423Sdim        return false;
398249423Sdim      if (l.second != r.second)
399249423Sdim        return SM.isBeforeInTranslationUnit(l.second, r.second);
400249423Sdim      return SM.isBeforeInTranslationUnit(l.first->getLocation(),
401249423Sdim                                          r.first->getLocation());
402249423Sdim    }
403218893Sdim  };
404218893Sdim}
405218893Sdim
406249423Sdim/// Obtains a sorted list of functions that are undefined but ODR-used.
407249423Sdimvoid Sema::getUndefinedButUsed(
408249423Sdim    SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
409249423Sdim  for (llvm::DenseMap<NamedDecl *, SourceLocation>::iterator
410249423Sdim         I = UndefinedButUsed.begin(), E = UndefinedButUsed.end();
411249423Sdim       I != E; ++I) {
412249423Sdim    NamedDecl *ND = I->first;
413218893Sdim
414218893Sdim    // Ignore attributes that have become invalid.
415249423Sdim    if (ND->isInvalidDecl()) continue;
416218893Sdim
417218893Sdim    // __attribute__((weakref)) is basically a definition.
418249423Sdim    if (ND->hasAttr<WeakRefAttr>()) continue;
419218893Sdim
420249423Sdim    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
421249423Sdim      if (FD->isDefined())
422218893Sdim        continue;
423263508Sdim      if (FD->isExternallyVisible() &&
424249423Sdim          !FD->getMostRecentDecl()->isInlined())
425249423Sdim        continue;
426218893Sdim    } else {
427249423Sdim      if (cast<VarDecl>(ND)->hasDefinition() != VarDecl::DeclarationOnly)
428218893Sdim        continue;
429263508Sdim      if (ND->isExternallyVisible())
430249423Sdim        continue;
431218893Sdim    }
432218893Sdim
433249423Sdim    Undefined.push_back(std::make_pair(ND, I->second));
434218893Sdim  }
435218893Sdim
436249423Sdim  // Sort (in order of use site) so that we're not dependent on the iteration
437249423Sdim  // order through an llvm::DenseMap.
438249423Sdim  std::sort(Undefined.begin(), Undefined.end(),
439249423Sdim            SortUndefinedButUsed(Context.getSourceManager()));
440249423Sdim}
441218893Sdim
442249423Sdim/// checkUndefinedButUsed - Check for undefined objects with internal linkage
443249423Sdim/// or that are inline.
444249423Sdimstatic void checkUndefinedButUsed(Sema &S) {
445249423Sdim  if (S.UndefinedButUsed.empty()) return;
446218893Sdim
447249423Sdim  // Collect all the still-undefined entities with internal linkage.
448249423Sdim  SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
449249423Sdim  S.getUndefinedButUsed(Undefined);
450249423Sdim  if (Undefined.empty()) return;
451249423Sdim
452249423Sdim  for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
453249423Sdim         I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
454249423Sdim    NamedDecl *ND = I->first;
455249423Sdim
456263508Sdim    if (!ND->isExternallyVisible()) {
457249423Sdim      S.Diag(ND->getLocation(), diag::warn_undefined_internal)
458249423Sdim        << isa<VarDecl>(ND) << ND;
459249423Sdim    } else {
460249423Sdim      assert(cast<FunctionDecl>(ND)->getMostRecentDecl()->isInlined() &&
461249423Sdim             "used object requires definition but isn't inline or internal?");
462249423Sdim      S.Diag(ND->getLocation(), diag::warn_undefined_inline) << ND;
463249423Sdim    }
464249423Sdim    if (I->second.isValid())
465249423Sdim      S.Diag(I->second, diag::note_used_here);
466218893Sdim  }
467218893Sdim}
468218893Sdim
469226633Sdimvoid Sema::LoadExternalWeakUndeclaredIdentifiers() {
470226633Sdim  if (!ExternalSource)
471226633Sdim    return;
472249423Sdim
473226633Sdim  SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
474226633Sdim  ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
475226633Sdim  for (unsigned I = 0, N = WeakIDs.size(); I != N; ++I) {
476226633Sdim    llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator Pos
477226633Sdim      = WeakUndeclaredIdentifiers.find(WeakIDs[I].first);
478226633Sdim    if (Pos != WeakUndeclaredIdentifiers.end())
479226633Sdim      continue;
480249423Sdim
481226633Sdim    WeakUndeclaredIdentifiers.insert(WeakIDs[I]);
482226633Sdim  }
483226633Sdim}
484226633Sdim
485239462Sdim
486239462Sdimtypedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
487239462Sdim
488239462Sdim/// \brief Returns true, if all methods and nested classes of the given
489239462Sdim/// CXXRecordDecl are defined in this translation unit.
490239462Sdim///
491239462Sdim/// Should only be called from ActOnEndOfTranslationUnit so that all
492239462Sdim/// definitions are actually read.
493239462Sdimstatic bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
494239462Sdim                                            RecordCompleteMap &MNCComplete) {
495239462Sdim  RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
496239462Sdim  if (Cache != MNCComplete.end())
497239462Sdim    return Cache->second;
498239462Sdim  if (!RD->isCompleteDefinition())
499239462Sdim    return false;
500239462Sdim  bool Complete = true;
501239462Sdim  for (DeclContext::decl_iterator I = RD->decls_begin(),
502239462Sdim                                  E = RD->decls_end();
503239462Sdim       I != E && Complete; ++I) {
504239462Sdim    if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
505239462Sdim      Complete = M->isDefined() || (M->isPure() && !isa<CXXDestructorDecl>(M));
506239462Sdim    else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
507239462Sdim      Complete = F->getTemplatedDecl()->isDefined();
508239462Sdim    else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
509239462Sdim      if (R->isInjectedClassName())
510239462Sdim        continue;
511239462Sdim      if (R->hasDefinition())
512239462Sdim        Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
513239462Sdim                                                   MNCComplete);
514239462Sdim      else
515239462Sdim        Complete = false;
516239462Sdim    }
517239462Sdim  }
518239462Sdim  MNCComplete[RD] = Complete;
519239462Sdim  return Complete;
520239462Sdim}
521239462Sdim
522239462Sdim/// \brief Returns true, if the given CXXRecordDecl is fully defined in this
523239462Sdim/// translation unit, i.e. all methods are defined or pure virtual and all
524239462Sdim/// friends, friend functions and nested classes are fully defined in this
525239462Sdim/// translation unit.
526239462Sdim///
527239462Sdim/// Should only be called from ActOnEndOfTranslationUnit so that all
528239462Sdim/// definitions are actually read.
529239462Sdimstatic bool IsRecordFullyDefined(const CXXRecordDecl *RD,
530239462Sdim                                 RecordCompleteMap &RecordsComplete,
531239462Sdim                                 RecordCompleteMap &MNCComplete) {
532239462Sdim  RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
533239462Sdim  if (Cache != RecordsComplete.end())
534239462Sdim    return Cache->second;
535239462Sdim  bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
536239462Sdim  for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
537239462Sdim                                      E = RD->friend_end();
538239462Sdim       I != E && Complete; ++I) {
539239462Sdim    // Check if friend classes and methods are complete.
540239462Sdim    if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
541239462Sdim      // Friend classes are available as the TypeSourceInfo of the FriendDecl.
542239462Sdim      if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
543239462Sdim        Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
544239462Sdim      else
545239462Sdim        Complete = false;
546239462Sdim    } else {
547239462Sdim      // Friend functions are available through the NamedDecl of FriendDecl.
548239462Sdim      if (const FunctionDecl *FD =
549239462Sdim          dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
550239462Sdim        Complete = FD->isDefined();
551239462Sdim      else
552239462Sdim        // This is a template friend, give up.
553239462Sdim        Complete = false;
554239462Sdim    }
555239462Sdim  }
556239462Sdim  RecordsComplete[RD] = Complete;
557239462Sdim  return Complete;
558239462Sdim}
559239462Sdim
560193326Sed/// ActOnEndOfTranslationUnit - This is called at the very end of the
561193326Sed/// translation unit when EOF is reached and all but the top-level scope is
562193326Sed/// popped.
563212904Sdimvoid Sema::ActOnEndOfTranslationUnit() {
564239462Sdim  assert(DelayedDiagnostics.getCurrentPool() == NULL
565239462Sdim         && "reached end of translation unit with a pool attached?");
566239462Sdim
567243830Sdim  // If code completion is enabled, don't perform any end-of-translation-unit
568243830Sdim  // work.
569243830Sdim  if (PP.isCodeCompletionEnabled())
570243830Sdim    return;
571243830Sdim
572263508Sdim  // Complete translation units and modules define vtables and perform implicit
573263508Sdim  // instantiations. PCH files do not.
574263508Sdim  if (TUKind != TU_Prefix) {
575234353Sdim    DiagnoseUseOfUnimplementedSelectors();
576234353Sdim
577218893Sdim    // If any dynamic classes have their key function defined within
578218893Sdim    // this translation unit, then those vtables are considered "used" and must
579218893Sdim    // be emitted.
580226633Sdim    for (DynamicClassesType::iterator I = DynamicClasses.begin(ExternalSource),
581226633Sdim                                      E = DynamicClasses.end();
582226633Sdim         I != E; ++I) {
583226633Sdim      assert(!(*I)->isDependentType() &&
584218893Sdim             "Should not see dependent types here!");
585249423Sdim      if (const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(*I)) {
586218893Sdim        const FunctionDecl *Definition = 0;
587218893Sdim        if (KeyFunction->hasBody(Definition))
588226633Sdim          MarkVTableUsed(Definition->getLocation(), *I, true);
589218893Sdim      }
590218893Sdim    }
591212904Sdim
592223017Sdim    // If DefinedUsedVTables ends up marking any virtual member functions it
593223017Sdim    // might lead to more pending template instantiations, which we then need
594223017Sdim    // to instantiate.
595223017Sdim    DefineUsedVTables();
596218893Sdim
597223017Sdim    // C++: Perform implicit template instantiations.
598223017Sdim    //
599223017Sdim    // FIXME: When we perform these implicit instantiations, we do not
600223017Sdim    // carefully keep track of the point of instantiation (C++ [temp.point]).
601223017Sdim    // This means that name lookup that occurs within the template
602223017Sdim    // instantiation will always happen at the end of the translation unit,
603263508Sdim    // so it will find some names that are not required to be found. This is
604263508Sdim    // valid, but we could do better by diagnosing if an instantiation uses a
605263508Sdim    // name that was not visible at its first point of instantiation.
606223017Sdim    PerformPendingInstantiations();
607263508Sdim    CheckDelayedMemberExceptionSpecs();
608218893Sdim  }
609249423Sdim
610263508Sdim  // All delayed member exception specs should be checked or we end up accepting
611263508Sdim  // incompatible declarations.
612263508Sdim  assert(DelayedDefaultedMemberExceptionSpecs.empty());
613263508Sdim  assert(DelayedDestructorExceptionSpecChecks.empty());
614263508Sdim
615212904Sdim  // Remove file scoped decls that turned out to be used.
616251662Sdim  UnusedFileScopedDecls.erase(
617251662Sdim      std::remove_if(UnusedFileScopedDecls.begin(0, true),
618251662Sdim                     UnusedFileScopedDecls.end(),
619251662Sdim                     std::bind1st(std::ptr_fun(ShouldRemoveFromUnused), this)),
620251662Sdim      UnusedFileScopedDecls.end());
621207619Srdivacky
622226633Sdim  if (TUKind == TU_Prefix) {
623226633Sdim    // Translation unit prefixes don't need any of the checking below.
624212904Sdim    TUScope = 0;
625212904Sdim    return;
626212904Sdim  }
627212904Sdim
628198092Srdivacky  // Check for #pragma weak identifiers that were never declared
629198092Srdivacky  // FIXME: This will cause diagnostics to be emitted in a non-determinstic
630198092Srdivacky  // order!  Iterating over a densemap like this is bad.
631226633Sdim  LoadExternalWeakUndeclaredIdentifiers();
632198092Srdivacky  for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
633198092Srdivacky       I = WeakUndeclaredIdentifiers.begin(),
634198092Srdivacky       E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
635198092Srdivacky    if (I->second.getUsed()) continue;
636198092Srdivacky
637198092Srdivacky    Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
638198092Srdivacky      << I->first;
639198092Srdivacky  }
640198092Srdivacky
641249423Sdim  if (LangOpts.CPlusPlus11 &&
642249423Sdim      Diags.getDiagnosticLevel(diag::warn_delegating_ctor_cycle,
643249423Sdim                               SourceLocation())
644249423Sdim        != DiagnosticsEngine::Ignored)
645249423Sdim    CheckDelegatingCtorCycles();
646249423Sdim
647226633Sdim  if (TUKind == TU_Module) {
648234353Sdim    // If we are building a module, resolve all of the exported declarations
649234353Sdim    // now.
650234353Sdim    if (Module *CurrentModule = PP.getCurrentModule()) {
651234353Sdim      ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
652249423Sdim
653249423Sdim      SmallVector<Module *, 2> Stack;
654234353Sdim      Stack.push_back(CurrentModule);
655234353Sdim      while (!Stack.empty()) {
656263508Sdim        Module *Mod = Stack.pop_back_val();
657249423Sdim
658249423Sdim        // Resolve the exported declarations and conflicts.
659234353Sdim        // FIXME: Actually complain, once we figure out how to teach the
660249423Sdim        // diagnostic client to deal with complaints in the module map at this
661234353Sdim        // point.
662234353Sdim        ModMap.resolveExports(Mod, /*Complain=*/false);
663263508Sdim        ModMap.resolveUses(Mod, /*Complain=*/false);
664249423Sdim        ModMap.resolveConflicts(Mod, /*Complain=*/false);
665249423Sdim
666234353Sdim        // Queue the submodules, so their exports will also be resolved.
667234353Sdim        for (Module::submodule_iterator Sub = Mod->submodule_begin(),
668234353Sdim                                     SubEnd = Mod->submodule_end();
669234353Sdim             Sub != SubEnd; ++Sub) {
670234353Sdim          Stack.push_back(*Sub);
671226633Sdim        }
672226633Sdim      }
673226633Sdim    }
674249423Sdim
675226633Sdim    // Modules don't need any of the checking below.
676226633Sdim    TUScope = 0;
677226633Sdim    return;
678226633Sdim  }
679249423Sdim
680193326Sed  // C99 6.9.2p2:
681193326Sed  //   A declaration of an identifier for an object that has file
682193326Sed  //   scope without an initializer, and without a storage-class
683193326Sed  //   specifier or with the storage-class specifier static,
684193326Sed  //   constitutes a tentative definition. If a translation unit
685193326Sed  //   contains one or more tentative definitions for an identifier,
686193326Sed  //   and the translation unit contains no external definition for
687193326Sed  //   that identifier, then the behavior is exactly as if the
688193326Sed  //   translation unit contains a file scope declaration of that
689193326Sed  //   identifier, with the composite type as of the end of the
690193326Sed  //   translation unit, with an initializer equal to 0.
691203955Srdivacky  llvm::SmallSet<VarDecl *, 32> Seen;
692249423Sdim  for (TentativeDefinitionsType::iterator
693226633Sdim            T = TentativeDefinitions.begin(ExternalSource),
694226633Sdim         TEnd = TentativeDefinitions.end();
695249423Sdim       T != TEnd; ++T)
696226633Sdim  {
697226633Sdim    VarDecl *VD = (*T)->getActingDefinition();
698193326Sed
699203955Srdivacky    // If the tentative definition was completed, getActingDefinition() returns
700203955Srdivacky    // null. If we've already seen this variable before, insert()'s second
701203955Srdivacky    // return value is false.
702203955Srdivacky    if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
703193326Sed      continue;
704193326Sed
705198092Srdivacky    if (const IncompleteArrayType *ArrayT
706193326Sed        = Context.getAsIncompleteArrayType(VD->getType())) {
707198092Srdivacky      // Set the length of the array to 1 (C99 6.9.2p5).
708198092Srdivacky      Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
709198092Srdivacky      llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
710198398Srdivacky      QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
711198398Srdivacky                                                One, ArrayType::Normal, 0);
712198092Srdivacky      VD->setType(T);
713198092Srdivacky    } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
714193326Sed                                   diag::err_tentative_def_incomplete_type))
715193326Sed      VD->setInvalidDecl();
716193326Sed
717242080Sed    CheckCompleteVariableDeclaration(VD);
718242080Sed
719193326Sed    // Notify the consumer that we've completed a tentative definition.
720193326Sed    if (!VD->isInvalidDecl())
721193326Sed      Consumer.CompleteTentativeDefinition(VD);
722193326Sed
723193326Sed  }
724218893Sdim
725218893Sdim  // If there were errors, disable 'unused' warnings since they will mostly be
726218893Sdim  // noise.
727218893Sdim  if (!Diags.hasErrorOccurred()) {
728218893Sdim    // Output warning for unused file scoped decls.
729226633Sdim    for (UnusedFileScopedDeclsType::iterator
730226633Sdim           I = UnusedFileScopedDecls.begin(ExternalSource),
731218893Sdim           E = UnusedFileScopedDecls.end(); I != E; ++I) {
732226633Sdim      if (ShouldRemoveFromUnused(this, *I))
733226633Sdim        continue;
734249423Sdim
735218893Sdim      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
736218893Sdim        const FunctionDecl *DiagD;
737218893Sdim        if (!FD->hasBody(DiagD))
738218893Sdim          DiagD = FD;
739221345Sdim        if (DiagD->isDeleted())
740221345Sdim          continue; // Deleted functions are supposed to be unused.
741221345Sdim        if (DiagD->isReferenced()) {
742221345Sdim          if (isa<CXXMethodDecl>(DiagD))
743221345Sdim            Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
744221345Sdim                  << DiagD->getDeclName();
745239462Sdim          else {
746249423Sdim            if (FD->getStorageClass() == SC_Static &&
747239462Sdim                !FD->isInlineSpecified() &&
748263508Sdim                !SourceMgr.isInMainFile(
749239462Sdim                   SourceMgr.getExpansionLoc(FD->getLocation())))
750239462Sdim              Diag(DiagD->getLocation(), diag::warn_unneeded_static_internal_decl)
751239462Sdim                << DiagD->getDeclName();
752239462Sdim            else
753239462Sdim              Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
754239462Sdim                   << /*function*/0 << DiagD->getDeclName();
755239462Sdim          }
756221345Sdim        } else {
757221345Sdim          Diag(DiagD->getLocation(),
758221345Sdim               isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
759221345Sdim                                         : diag::warn_unused_function)
760221345Sdim                << DiagD->getDeclName();
761221345Sdim        }
762218893Sdim      } else {
763218893Sdim        const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
764218893Sdim        if (!DiagD)
765218893Sdim          DiagD = cast<VarDecl>(*I);
766221345Sdim        if (DiagD->isReferenced()) {
767221345Sdim          Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
768221345Sdim                << /*variable*/1 << DiagD->getDeclName();
769263508Sdim        } else if (DiagD->getType().isConstQualified()) {
770263508Sdim          Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
771263508Sdim              << DiagD->getDeclName();
772263508Sdim        } else {
773221345Sdim          Diag(DiagD->getLocation(), diag::warn_unused_variable)
774251662Sdim              << DiagD->getDeclName();
775221345Sdim        }
776218893Sdim      }
777212904Sdim    }
778218893Sdim
779249423Sdim    if (ExternalSource)
780249423Sdim      ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
781249423Sdim    checkUndefinedButUsed(*this);
782212904Sdim  }
783212904Sdim
784239462Sdim  if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
785239462Sdim                               SourceLocation())
786239462Sdim        != DiagnosticsEngine::Ignored) {
787239462Sdim    RecordCompleteMap RecordsComplete;
788239462Sdim    RecordCompleteMap MNCComplete;
789239462Sdim    for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
790239462Sdim         E = UnusedPrivateFields.end(); I != E; ++I) {
791239462Sdim      const NamedDecl *D = *I;
792239462Sdim      const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
793239462Sdim      if (RD && !RD->isUnion() &&
794239462Sdim          IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
795239462Sdim        Diag(D->getLocation(), diag::warn_unused_private_field)
796239462Sdim              << D->getDeclName();
797239462Sdim      }
798239462Sdim    }
799239462Sdim  }
800239462Sdim
801219077Sdim  // Check we've noticed that we're no longer parsing the initializer for every
802219077Sdim  // variable. If we miss cases, then at best we have a performance issue and
803219077Sdim  // at worst a rejects-valid bug.
804219077Sdim  assert(ParsingInitForAutoVars.empty() &&
805219077Sdim         "Didn't unmark var as having its initializer parsed");
806219077Sdim
807212904Sdim  TUScope = 0;
808193326Sed}
809193326Sed
810193326Sed
811193326Sed//===----------------------------------------------------------------------===//
812193326Sed// Helper functions.
813193326Sed//===----------------------------------------------------------------------===//
814193326Sed
815198092SrdivackyDeclContext *Sema::getFunctionLevelDeclContext() {
816201361Srdivacky  DeclContext *DC = CurContext;
817198092Srdivacky
818234353Sdim  while (true) {
819251662Sdim    if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) {
820234353Sdim      DC = DC->getParent();
821234353Sdim    } else if (isa<CXXMethodDecl>(DC) &&
822234353Sdim               cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
823234353Sdim               cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
824234353Sdim      DC = DC->getParent()->getParent();
825234353Sdim    }
826234353Sdim    else break;
827234353Sdim  }
828198092Srdivacky
829198092Srdivacky  return DC;
830198092Srdivacky}
831198092Srdivacky
832193326Sed/// getCurFunctionDecl - If inside of a function body, this returns a pointer
833193326Sed/// to the function decl for the function being parsed.  If we're currently
834193326Sed/// in a 'block', this returns the containing context.
835193326SedFunctionDecl *Sema::getCurFunctionDecl() {
836198092Srdivacky  DeclContext *DC = getFunctionLevelDeclContext();
837193326Sed  return dyn_cast<FunctionDecl>(DC);
838193326Sed}
839193326Sed
840193326SedObjCMethodDecl *Sema::getCurMethodDecl() {
841198092Srdivacky  DeclContext *DC = getFunctionLevelDeclContext();
842263508Sdim  while (isa<RecordDecl>(DC))
843263508Sdim    DC = DC->getParent();
844193326Sed  return dyn_cast<ObjCMethodDecl>(DC);
845193326Sed}
846193326Sed
847193326SedNamedDecl *Sema::getCurFunctionOrMethodDecl() {
848198092Srdivacky  DeclContext *DC = getFunctionLevelDeclContext();
849193326Sed  if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
850193326Sed    return cast<NamedDecl>(DC);
851193326Sed  return 0;
852193326Sed}
853193326Sed
854234353Sdimvoid Sema::EmitCurrentDiagnostic(unsigned DiagID) {
855234353Sdim  // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
856234353Sdim  // and yet we also use the current diag ID on the DiagnosticsEngine. This has
857234353Sdim  // been made more painfully obvious by the refactor that introduced this
858234353Sdim  // function, but it is possible that the incoming argument can be
859234353Sdim  // eliminnated. If it truly cannot be (for example, there is some reentrancy
860234353Sdim  // issue I am not seeing yet), then there should at least be a clarifying
861234353Sdim  // comment somewhere.
862249423Sdim  if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
863234353Sdim    switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
864234353Sdim              Diags.getCurrentDiagID())) {
865218893Sdim    case DiagnosticIDs::SFINAE_Report:
866234353Sdim      // We'll report the diagnostic below.
867218893Sdim      break;
868249423Sdim
869234353Sdim    case DiagnosticIDs::SFINAE_SubstitutionFailure:
870234353Sdim      // Count this failure so that we know that template argument deduction
871234353Sdim      // has failed.
872234353Sdim      ++NumSFINAEErrors;
873239462Sdim
874239462Sdim      // Make a copy of this suppressed diagnostic and store it with the
875239462Sdim      // template-deduction information.
876239462Sdim      if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
877239462Sdim        Diagnostic DiagInfo(&Diags);
878239462Sdim        (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
879239462Sdim                       PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
880239462Sdim      }
881239462Sdim
882234353Sdim      Diags.setLastDiagnosticIgnored();
883234353Sdim      Diags.Clear();
884234353Sdim      return;
885249423Sdim
886234353Sdim    case DiagnosticIDs::SFINAE_AccessControl: {
887223017Sdim      // Per C++ Core Issue 1170, access control is part of SFINAE.
888234353Sdim      // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
889223017Sdim      // make access control a part of SFINAE for the purposes of checking
890223017Sdim      // type traits.
891249423Sdim      if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
892218893Sdim        break;
893234353Sdim
894234353Sdim      SourceLocation Loc = Diags.getCurrentDiagLoc();
895234353Sdim
896234353Sdim      // Suppress this diagnostic.
897234353Sdim      ++NumSFINAEErrors;
898239462Sdim
899239462Sdim      // Make a copy of this suppressed diagnostic and store it with the
900239462Sdim      // template-deduction information.
901239462Sdim      if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
902239462Sdim        Diagnostic DiagInfo(&Diags);
903239462Sdim        (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
904239462Sdim                       PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
905239462Sdim      }
906239462Sdim
907234353Sdim      Diags.setLastDiagnosticIgnored();
908234353Sdim      Diags.Clear();
909234353Sdim
910234353Sdim      // Now the diagnostic state is clear, produce a C++98 compatibility
911234353Sdim      // warning.
912234353Sdim      Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
913234353Sdim
914234353Sdim      // The last diagnostic which Sema produced was ignored. Suppress any
915234353Sdim      // notes attached to it.
916234353Sdim      Diags.setLastDiagnosticIgnored();
917218893Sdim      return;
918234353Sdim    }
919234353Sdim
920218893Sdim    case DiagnosticIDs::SFINAE_Suppress:
921218893Sdim      // Make a copy of this suppressed diagnostic and store it with the
922218893Sdim      // template-deduction information;
923239462Sdim      if (*Info) {
924239462Sdim        Diagnostic DiagInfo(&Diags);
925218893Sdim        (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
926239462Sdim                       PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
927239462Sdim      }
928239462Sdim
929239462Sdim      // Suppress this diagnostic.
930234353Sdim      Diags.setLastDiagnosticIgnored();
931234353Sdim      Diags.Clear();
932218893Sdim      return;
933218893Sdim    }
934218893Sdim  }
935249423Sdim
936226633Sdim  // Set up the context's printing policy based on our current state.
937234353Sdim  Context.setPrintingPolicy(getPrintingPolicy());
938249423Sdim
939218893Sdim  // Emit the diagnostic.
940234353Sdim  if (!Diags.EmitCurrentDiagnostic())
941194179Sed    return;
942198092Srdivacky
943193326Sed  // If this is not a note, and we're in a template instantiation
944193326Sed  // that is different from the last template instantiation where
945193326Sed  // we emitted an error, print a template instantiation
946193326Sed  // backtrace.
947218893Sdim  if (!DiagnosticIDs::isBuiltinNote(DiagID) &&
948234353Sdim      !ActiveTemplateInstantiations.empty() &&
949234353Sdim      ActiveTemplateInstantiations.back()
950234353Sdim        != LastTemplateInstantiationErrorContext) {
951234353Sdim    PrintInstantiationStack();
952234353Sdim    LastTemplateInstantiationErrorContext = ActiveTemplateInstantiations.back();
953193326Sed  }
954193326Sed}
955195341Sed
956198092SrdivackySema::SemaDiagnosticBuilder
957198092SrdivackySema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
958198092Srdivacky  SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
959198092Srdivacky  PD.Emit(Builder);
960198092Srdivacky
961198092Srdivacky  return Builder;
962198092Srdivacky}
963198092Srdivacky
964226633Sdim/// \brief Looks through the macro-expansion chain for the given
965226633Sdim/// location, looking for a macro expansion with the given name.
966221345Sdim/// If one is found, returns true and sets the location to that
967226633Sdim/// expansion loc.
968226633Sdimbool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
969221345Sdim  SourceLocation loc = locref;
970221345Sdim  if (!loc.isMacroID()) return false;
971221345Sdim
972221345Sdim  // There's no good way right now to look at the intermediate
973226633Sdim  // expansions, so just jump to the expansion location.
974226633Sdim  loc = getSourceManager().getExpansionLoc(loc);
975221345Sdim
976221345Sdim  // If that's written with the name, stop here.
977226633Sdim  SmallVector<char, 16> buffer;
978221345Sdim  if (getPreprocessor().getSpelling(loc, buffer) == name) {
979221345Sdim    locref = loc;
980221345Sdim    return true;
981221345Sdim  }
982221345Sdim  return false;
983221345Sdim}
984221345Sdim
985210299Sed/// \brief Determines the active Scope associated with the given declaration
986210299Sed/// context.
987210299Sed///
988210299Sed/// This routine maps a declaration context to the active Scope object that
989210299Sed/// represents that declaration context in the parser. It is typically used
990210299Sed/// from "scope-less" code (e.g., template instantiation, lazy creation of
991210299Sed/// declarations) that injects a name for name-lookup purposes and, therefore,
992210299Sed/// must update the Scope.
993210299Sed///
994210299Sed/// \returns The scope corresponding to the given declaraion context, or NULL
995210299Sed/// if no such scope is open.
996210299SedScope *Sema::getScopeForContext(DeclContext *Ctx) {
997249423Sdim
998210299Sed  if (!Ctx)
999210299Sed    return 0;
1000249423Sdim
1001210299Sed  Ctx = Ctx->getPrimaryContext();
1002210299Sed  for (Scope *S = getCurScope(); S; S = S->getParent()) {
1003210299Sed    // Ignore scopes that cannot have declarations. This is important for
1004210299Sed    // out-of-line definitions of static class members.
1005210299Sed    if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
1006263508Sdim      if (DeclContext *Entity = S->getEntity())
1007210299Sed        if (Ctx == Entity->getPrimaryContext())
1008210299Sed          return S;
1009210299Sed  }
1010249423Sdim
1011210299Sed  return 0;
1012210299Sed}
1013204643Srdivacky
1014204643Srdivacky/// \brief Enter a new function scope
1015204643Srdivackyvoid Sema::PushFunctionScope() {
1016212904Sdim  if (FunctionScopes.size() == 1) {
1017212904Sdim    // Use the "top" function scope rather than having to allocate
1018212904Sdim    // memory for a new scope.
1019218893Sdim    FunctionScopes.back()->Clear();
1020212904Sdim    FunctionScopes.push_back(FunctionScopes.back());
1021204643Srdivacky    return;
1022204643Srdivacky  }
1023249423Sdim
1024218893Sdim  FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
1025204643Srdivacky}
1026204643Srdivacky
1027204643Srdivackyvoid Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
1028218893Sdim  FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
1029204643Srdivacky                                              BlockScope, Block));
1030204643Srdivacky}
1031204643Srdivacky
1032263508SdimLambdaScopeInfo *Sema::PushLambdaScope() {
1033263508Sdim  LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
1034263508Sdim  FunctionScopes.push_back(LSI);
1035263508Sdim  return LSI;
1036234353Sdim}
1037234353Sdim
1038263508Sdimvoid Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
1039263508Sdim  if (LambdaScopeInfo *const LSI = getCurLambda()) {
1040263508Sdim    LSI->AutoTemplateParameterDepth = Depth;
1041263508Sdim    return;
1042263508Sdim  }
1043263508Sdim  llvm_unreachable(
1044263508Sdim      "Remove assertion if intentionally called in a non-lambda context.");
1045263508Sdim}
1046263508Sdim
1047234353Sdimvoid Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
1048234353Sdim                                const Decl *D, const BlockExpr *blkExpr) {
1049249423Sdim  FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
1050212904Sdim  assert(!FunctionScopes.empty() && "mismatched push/pop!");
1051249423Sdim
1052219077Sdim  // Issue any analysis-based warnings.
1053219077Sdim  if (WP && D)
1054219077Sdim    AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
1055219077Sdim  else {
1056226633Sdim    for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
1057219077Sdim         i = Scope->PossiblyUnreachableDiags.begin(),
1058219077Sdim         e = Scope->PossiblyUnreachableDiags.end();
1059219077Sdim         i != e; ++i) {
1060219077Sdim      const sema::PossiblyUnreachableDiag &D = *i;
1061219077Sdim      Diag(D.Loc, D.PD);
1062219077Sdim    }
1063219077Sdim  }
1064219077Sdim
1065219077Sdim  if (FunctionScopes.back() != Scope) {
1066212904Sdim    delete Scope;
1067219077Sdim  }
1068204643Srdivacky}
1069204643Srdivacky
1070234353Sdimvoid Sema::PushCompoundScope() {
1071234353Sdim  getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo());
1072234353Sdim}
1073234353Sdim
1074234353Sdimvoid Sema::PopCompoundScope() {
1075234353Sdim  FunctionScopeInfo *CurFunction = getCurFunction();
1076234353Sdim  assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
1077234353Sdim
1078234353Sdim  CurFunction->CompoundScopes.pop_back();
1079234353Sdim}
1080234353Sdim
1081204643Srdivacky/// \brief Determine whether any errors occurred within this function/method/
1082204643Srdivacky/// block.
1083224145Sdimbool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
1084224145Sdim  return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
1085204643Srdivacky}
1086204643Srdivacky
1087204643SrdivackyBlockScopeInfo *Sema::getCurBlock() {
1088204643Srdivacky  if (FunctionScopes.empty())
1089204643Srdivacky    return 0;
1090249423Sdim
1091249423Sdim  return dyn_cast<BlockScopeInfo>(FunctionScopes.back());
1092204643Srdivacky}
1093210299Sed
1094234353SdimLambdaScopeInfo *Sema::getCurLambda() {
1095234353Sdim  if (FunctionScopes.empty())
1096234353Sdim    return 0;
1097249423Sdim
1098249423Sdim  return dyn_cast<LambdaScopeInfo>(FunctionScopes.back());
1099234353Sdim}
1100263508Sdim// We have a generic lambda if we parsed auto parameters, or we have
1101263508Sdim// an associated template parameter list.
1102263508SdimLambdaScopeInfo *Sema::getCurGenericLambda() {
1103263508Sdim  if (LambdaScopeInfo *LSI =  getCurLambda()) {
1104263508Sdim    return (LSI->AutoTemplateParams.size() ||
1105263508Sdim                    LSI->GLTemplateParameterList) ? LSI : 0;
1106263508Sdim  }
1107263508Sdim  return 0;
1108263508Sdim}
1109234353Sdim
1110263508Sdim
1111239462Sdimvoid Sema::ActOnComment(SourceRange Comment) {
1112243830Sdim  if (!LangOpts.RetainCommentsFromSystemHeaders &&
1113243830Sdim      SourceMgr.isInSystemHeader(Comment.getBegin()))
1114243830Sdim    return;
1115251662Sdim  RawComment RC(SourceMgr, Comment, false,
1116251662Sdim                LangOpts.CommentOpts.ParseAllComments);
1117239462Sdim  if (RC.isAlmostTrailingComment()) {
1118239462Sdim    SourceRange MagicMarkerRange(Comment.getBegin(),
1119239462Sdim                                 Comment.getBegin().getLocWithOffset(3));
1120239462Sdim    StringRef MagicMarkerText;
1121239462Sdim    switch (RC.getKind()) {
1122239462Sdim    case RawComment::RCK_OrdinaryBCPL:
1123239462Sdim      MagicMarkerText = "///<";
1124239462Sdim      break;
1125239462Sdim    case RawComment::RCK_OrdinaryC:
1126239462Sdim      MagicMarkerText = "/**<";
1127239462Sdim      break;
1128239462Sdim    default:
1129239462Sdim      llvm_unreachable("if this is an almost Doxygen comment, "
1130239462Sdim                       "it should be ordinary");
1131239462Sdim    }
1132239462Sdim    Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
1133239462Sdim      FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
1134239462Sdim  }
1135239462Sdim  Context.addComment(RC);
1136239462Sdim}
1137239462Sdim
1138210299Sed// Pin this vtable to this file.
1139210299SedExternalSemaSource::~ExternalSemaSource() {}
1140212904Sdim
1141234353Sdimvoid ExternalSemaSource::ReadMethodPool(Selector Sel) { }
1142218893Sdim
1143224145Sdimvoid ExternalSemaSource::ReadKnownNamespaces(
1144249423Sdim                           SmallVectorImpl<NamespaceDecl *> &Namespaces) {
1145224145Sdim}
1146224145Sdim
1147249423Sdimvoid ExternalSemaSource::ReadUndefinedButUsed(
1148249423Sdim                       llvm::DenseMap<NamedDecl *, SourceLocation> &Undefined) {
1149249423Sdim}
1150249423Sdim
1151226633Sdimvoid PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
1152212904Sdim  SourceLocation Loc = this->Loc;
1153212904Sdim  if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
1154212904Sdim  if (Loc.isValid()) {
1155212904Sdim    Loc.print(OS, S.getSourceManager());
1156212904Sdim    OS << ": ";
1157212904Sdim  }
1158212904Sdim  OS << Message;
1159212904Sdim
1160212904Sdim  if (TheDecl && isa<NamedDecl>(TheDecl)) {
1161212904Sdim    std::string Name = cast<NamedDecl>(TheDecl)->getNameAsString();
1162212904Sdim    if (!Name.empty())
1163212904Sdim      OS << " '" << Name << '\'';
1164212904Sdim  }
1165212904Sdim
1166212904Sdim  OS << '\n';
1167212904Sdim}
1168223017Sdim
1169223017Sdim/// \brief Figure out if an expression could be turned into a call.
1170223017Sdim///
1171223017Sdim/// Use this when trying to recover from an error where the programmer may have
1172223017Sdim/// written just the name of a function instead of actually calling it.
1173223017Sdim///
1174223017Sdim/// \param E - The expression to examine.
1175223017Sdim/// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1176223017Sdim///  with no arguments, this parameter is set to the type returned by such a
1177223017Sdim///  call; otherwise, it is set to an empty QualType.
1178226633Sdim/// \param OverloadSet - If the expression is an overloaded function
1179223017Sdim///  name, this parameter is populated with the decls of the various overloads.
1180263508Sdimbool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1181263508Sdim                         UnresolvedSetImpl &OverloadSet) {
1182223017Sdim  ZeroArgCallReturnTy = QualType();
1183226633Sdim  OverloadSet.clear();
1184226633Sdim
1185263508Sdim  const OverloadExpr *Overloads = NULL;
1186263508Sdim  bool IsMemExpr = false;
1187226633Sdim  if (E.getType() == Context.OverloadTy) {
1188226633Sdim    OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
1189226633Sdim
1190263508Sdim    // Ignore overloads that are pointer-to-member constants.
1191263508Sdim    if (FR.HasFormOfMemberPointer)
1192263508Sdim      return false;
1193263508Sdim
1194263508Sdim    Overloads = FR.Expression;
1195263508Sdim  } else if (E.getType() == Context.BoundMemberTy) {
1196263508Sdim    Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
1197263508Sdim    IsMemExpr = true;
1198263508Sdim  }
1199263508Sdim
1200263508Sdim  bool Ambiguous = false;
1201263508Sdim
1202263508Sdim  if (Overloads) {
1203223017Sdim    for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
1204223017Sdim         DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
1205226633Sdim      OverloadSet.addDecl(*it);
1206226633Sdim
1207263508Sdim      // Check whether the function is a non-template, non-member which takes no
1208226633Sdim      // arguments.
1209263508Sdim      if (IsMemExpr)
1210263508Sdim        continue;
1211226633Sdim      if (const FunctionDecl *OverloadDecl
1212226633Sdim            = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
1213263508Sdim        if (OverloadDecl->getMinRequiredArguments() == 0) {
1214263508Sdim          if (!ZeroArgCallReturnTy.isNull() && !Ambiguous) {
1215263508Sdim            ZeroArgCallReturnTy = QualType();
1216263508Sdim            Ambiguous = true;
1217263508Sdim          } else
1218263508Sdim            ZeroArgCallReturnTy = OverloadDecl->getResultType();
1219263508Sdim        }
1220223017Sdim      }
1221223017Sdim    }
1222226633Sdim
1223263508Sdim    // If it's not a member, use better machinery to try to resolve the call
1224263508Sdim    if (!IsMemExpr)
1225263508Sdim      return !ZeroArgCallReturnTy.isNull();
1226263508Sdim  }
1227226633Sdim
1228263508Sdim  // Attempt to call the member with no arguments - this will correctly handle
1229263508Sdim  // member templates with defaults/deduction of template arguments, overloads
1230263508Sdim  // with default arguments, etc.
1231263508Sdim  if (IsMemExpr && !E.isTypeDependent()) {
1232263508Sdim    bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
1233263508Sdim    getDiagnostics().setSuppressAllDiagnostics(true);
1234263508Sdim    ExprResult R = BuildCallToMemberFunction(NULL, &E, SourceLocation(), None,
1235263508Sdim                                             SourceLocation());
1236263508Sdim    getDiagnostics().setSuppressAllDiagnostics(Suppress);
1237263508Sdim    if (R.isUsable()) {
1238263508Sdim      ZeroArgCallReturnTy = R.get()->getType();
1239263508Sdim      return true;
1240263508Sdim    }
1241263508Sdim    return false;
1242223017Sdim  }
1243223017Sdim
1244226633Sdim  if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
1245223017Sdim    if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
1246223017Sdim      if (Fun->getMinRequiredArguments() == 0)
1247223017Sdim        ZeroArgCallReturnTy = Fun->getResultType();
1248223017Sdim      return true;
1249223017Sdim    }
1250223017Sdim  }
1251223017Sdim
1252223017Sdim  // We don't have an expression that's convenient to get a FunctionDecl from,
1253223017Sdim  // but we can at least check if the type is "function of 0 arguments".
1254223017Sdim  QualType ExprTy = E.getType();
1255223017Sdim  const FunctionType *FunTy = NULL;
1256223017Sdim  QualType PointeeTy = ExprTy->getPointeeType();
1257223017Sdim  if (!PointeeTy.isNull())
1258223017Sdim    FunTy = PointeeTy->getAs<FunctionType>();
1259223017Sdim  if (!FunTy)
1260223017Sdim    FunTy = ExprTy->getAs<FunctionType>();
1261223017Sdim
1262223017Sdim  if (const FunctionProtoType *FPT =
1263223017Sdim      dyn_cast_or_null<FunctionProtoType>(FunTy)) {
1264223017Sdim    if (FPT->getNumArgs() == 0)
1265223017Sdim      ZeroArgCallReturnTy = FunTy->getResultType();
1266223017Sdim    return true;
1267223017Sdim  }
1268223017Sdim  return false;
1269223017Sdim}
1270223017Sdim
1271223017Sdim/// \brief Give notes for a set of overloads.
1272223017Sdim///
1273263508Sdim/// A companion to tryExprAsCall. In cases when the name that the programmer
1274223017Sdim/// wrote was an overloaded function, we may be able to make some guesses about
1275223017Sdim/// plausible overloads based on their return types; such guesses can be handed
1276223017Sdim/// off to this method to be emitted as notes.
1277223017Sdim///
1278223017Sdim/// \param Overloads - The overloads to note.
1279223017Sdim/// \param FinalNoteLoc - If we've suppressed printing some overloads due to
1280223017Sdim///  -fshow-overloads=best, this is the location to attach to the note about too
1281223017Sdim///  many candidates. Typically this will be the location of the original
1282223017Sdim///  ill-formed expression.
1283226633Sdimstatic void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
1284226633Sdim                          const SourceLocation FinalNoteLoc) {
1285223017Sdim  int ShownOverloads = 0;
1286223017Sdim  int SuppressedOverloads = 0;
1287223017Sdim  for (UnresolvedSetImpl::iterator It = Overloads.begin(),
1288223017Sdim       DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1289223017Sdim    // FIXME: Magic number for max shown overloads stolen from
1290223017Sdim    // OverloadCandidateSet::NoteCandidates.
1291243830Sdim    if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) {
1292223017Sdim      ++SuppressedOverloads;
1293223017Sdim      continue;
1294223017Sdim    }
1295226633Sdim
1296226633Sdim    NamedDecl *Fn = (*It)->getUnderlyingDecl();
1297234353Sdim    S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
1298223017Sdim    ++ShownOverloads;
1299223017Sdim  }
1300226633Sdim
1301223017Sdim  if (SuppressedOverloads)
1302226633Sdim    S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
1303226633Sdim      << SuppressedOverloads;
1304223017Sdim}
1305226633Sdim
1306226633Sdimstatic void notePlausibleOverloads(Sema &S, SourceLocation Loc,
1307226633Sdim                                   const UnresolvedSetImpl &Overloads,
1308226633Sdim                                   bool (*IsPlausibleResult)(QualType)) {
1309226633Sdim  if (!IsPlausibleResult)
1310226633Sdim    return noteOverloads(S, Overloads, Loc);
1311226633Sdim
1312226633Sdim  UnresolvedSet<2> PlausibleOverloads;
1313226633Sdim  for (OverloadExpr::decls_iterator It = Overloads.begin(),
1314226633Sdim         DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1315226633Sdim    const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
1316226633Sdim    QualType OverloadResultTy = OverloadDecl->getResultType();
1317226633Sdim    if (IsPlausibleResult(OverloadResultTy))
1318226633Sdim      PlausibleOverloads.addDecl(It.getDecl());
1319226633Sdim  }
1320226633Sdim  noteOverloads(S, PlausibleOverloads, Loc);
1321226633Sdim}
1322226633Sdim
1323226633Sdim/// Determine whether the given expression can be called by just
1324226633Sdim/// putting parentheses after it.  Notably, expressions with unary
1325226633Sdim/// operators can't be because the unary operator will start parsing
1326226633Sdim/// outside the call.
1327226633Sdimstatic bool IsCallableWithAppend(Expr *E) {
1328226633Sdim  E = E->IgnoreImplicit();
1329226633Sdim  return (!isa<CStyleCastExpr>(E) &&
1330226633Sdim          !isa<UnaryOperator>(E) &&
1331226633Sdim          !isa<BinaryOperator>(E) &&
1332226633Sdim          !isa<CXXOperatorCallExpr>(E));
1333226633Sdim}
1334226633Sdim
1335226633Sdimbool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1336226633Sdim                                bool ForceComplain,
1337226633Sdim                                bool (*IsPlausibleResult)(QualType)) {
1338226633Sdim  SourceLocation Loc = E.get()->getExprLoc();
1339226633Sdim  SourceRange Range = E.get()->getSourceRange();
1340226633Sdim
1341226633Sdim  QualType ZeroArgCallTy;
1342226633Sdim  UnresolvedSet<4> Overloads;
1343263508Sdim  if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
1344226633Sdim      !ZeroArgCallTy.isNull() &&
1345226633Sdim      (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
1346226633Sdim    // At this point, we know E is potentially callable with 0
1347226633Sdim    // arguments and that it returns something of a reasonable type,
1348226633Sdim    // so we can emit a fixit and carry on pretending that E was
1349226633Sdim    // actually a CallExpr.
1350263508Sdim    SourceLocation ParenInsertionLoc = PP.getLocForEndOfToken(Range.getEnd());
1351249423Sdim    Diag(Loc, PD)
1352226633Sdim      << /*zero-arg*/ 1 << Range
1353226633Sdim      << (IsCallableWithAppend(E.get())
1354226633Sdim          ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
1355226633Sdim          : FixItHint());
1356226633Sdim    notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1357226633Sdim
1358226633Sdim    // FIXME: Try this before emitting the fixit, and suppress diagnostics
1359226633Sdim    // while doing so.
1360263508Sdim    E = ActOnCallExpr(0, E.take(), Range.getEnd(), None,
1361263508Sdim                      Range.getEnd().getLocWithOffset(1));
1362226633Sdim    return true;
1363226633Sdim  }
1364226633Sdim
1365226633Sdim  if (!ForceComplain) return false;
1366226633Sdim
1367226633Sdim  Diag(Loc, PD) << /*not zero-arg*/ 0 << Range;
1368226633Sdim  notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1369226633Sdim  E = ExprError();
1370226633Sdim  return true;
1371226633Sdim}
1372249423Sdim
1373249423SdimIdentifierInfo *Sema::getSuperIdentifier() const {
1374249423Sdim  if (!Ident_super)
1375249423Sdim    Ident_super = &Context.Idents.get("super");
1376249423Sdim  return Ident_super;
1377249423Sdim}
1378251662Sdim
1379263508SdimIdentifierInfo *Sema::getFloat128Identifier() const {
1380263508Sdim  if (!Ident___float128)
1381263508Sdim    Ident___float128 = &Context.Idents.get("__float128");
1382263508Sdim  return Ident___float128;
1383263508Sdim}
1384263508Sdim
1385251662Sdimvoid Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
1386251662Sdim                                   CapturedRegionKind K) {
1387251662Sdim  CapturingScopeInfo *CSI = new CapturedRegionScopeInfo(getDiagnostics(), S, CD, RD,
1388251662Sdim                                                        CD->getContextParam(), K);
1389251662Sdim  CSI->ReturnType = Context.VoidTy;
1390251662Sdim  FunctionScopes.push_back(CSI);
1391251662Sdim}
1392251662Sdim
1393251662SdimCapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
1394251662Sdim  if (FunctionScopes.empty())
1395251662Sdim    return 0;
1396251662Sdim
1397251662Sdim  return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
1398251662Sdim}
1399