blob: bc398f43ff5dc462a2f7d0f747dfb8df2338317d [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the actions class which performs semantic analysis and
11// builds an AST out of a parse stream.
12//
13//===----------------------------------------------------------------------===//
14
John McCall9c3087b2010-08-26 02:13:20 +000015#include "clang/Sema/SemaInternal.h"
16#include "clang/Sema/DelayedDiagnostic.h"
Anton Korobeynikov82d0a412010-01-10 12:58:08 +000017#include "TargetAttributesSema.h"
Ryan Flynne25ff832009-07-30 03:15:39 +000018#include "llvm/ADT/DenseMap.h"
Sebastian Redle9d12b62010-01-31 22:27:38 +000019#include "llvm/ADT/SmallSet.h"
John McCall680523a2009-11-07 03:30:10 +000020#include "llvm/ADT/APFloat.h"
John McCall5f1e0942010-08-24 08:50:51 +000021#include "clang/Sema/CXXFieldCollector.h"
Douglas Gregor9b623632010-10-12 23:32:35 +000022#include "clang/Sema/TemplateDeduction.h"
John McCall76bd1f32010-06-01 09:23:16 +000023#include "clang/Sema/ExternalSemaSource.h"
Sebastian Redl8c845712010-09-28 20:23:00 +000024#include "clang/Sema/ObjCMethodList.h"
John McCallf312b1e2010-08-26 23:41:50 +000025#include "clang/Sema/PrettyDeclStackTrace.h"
John McCall5f1e0942010-08-24 08:50:51 +000026#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000027#include "clang/Sema/ScopeInfo.h"
Douglas Gregor46ea32a2010-08-12 22:51:45 +000028#include "clang/Sema/SemaConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029#include "clang/AST/ASTContext.h"
Douglas Gregor79a9a342010-02-09 22:26:47 +000030#include "clang/AST/ASTDiagnostic.h"
John McCall384aff82010-08-25 07:42:41 +000031#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000032#include "clang/AST/DeclObjC.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000033#include "clang/AST/Expr.h"
Chris Lattnerad8dcf42011-02-17 07:39:24 +000034#include "clang/AST/StmtCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035#include "clang/Lex/Preprocessor.h"
Anders Carlsson91a0cc92009-08-26 22:33:56 +000036#include "clang/Basic/PartialDiagnostic.h"
Chris Lattner4d150c82009-04-30 06:18:40 +000037#include "clang/Basic/TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000038using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000039using namespace sema;
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000040
41FunctionScopeInfo::~FunctionScopeInfo() { }
42
Argyrios Kyrtzidis8fc32d22010-11-19 00:19:15 +000043void FunctionScopeInfo::Clear() {
John McCallb60a77e2010-08-01 00:26:45 +000044 HasBranchProtectedScope = false;
45 HasBranchIntoScope = false;
46 HasIndirectGoto = false;
47
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000048 SwitchStack.clear();
Douglas Gregor5077c382010-05-15 06:01:05 +000049 Returns.clear();
Argyrios Kyrtzidis8fc32d22010-11-19 00:19:15 +000050 ErrorTrap.reset();
Ted Kremenek351ba912011-02-23 01:52:04 +000051 PossiblyUnreachableDiags.clear();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000052}
53
54BlockScopeInfo::~BlockScopeInfo() { }
55
Douglas Gregorc1a3e5e2010-08-25 18:07:12 +000056void Sema::ActOnTranslationUnitScope(Scope *S) {
Steve Naroffb216c882007-10-09 22:01:59 +000057 TUScope = S;
Douglas Gregor44b43212008-12-11 16:49:14 +000058 PushDeclContext(S, Context.getTranslationUnitDecl());
Mike Stump1eb44332009-09-09 15:08:12 +000059
John McCallc7e04da2010-05-28 18:45:08 +000060 VAListTagName = PP.getIdentifierInfo("__va_list_tag");
61
Sebastian Redlc43b54c2010-08-18 23:56:43 +000062 if (!Context.isInt128Installed() && // May be set by ASTReader.
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +000063 PP.getTargetInfo().getPointerWidth(0) >= 64) {
John McCalla93c9342009-12-07 02:54:59 +000064 TypeSourceInfo *TInfo;
John McCallba6a9bd2009-10-24 08:00:42 +000065
Chris Lattner4d150c82009-04-30 06:18:40 +000066 // Install [u]int128_t for 64-bit targets.
John McCalla93c9342009-12-07 02:54:59 +000067 TInfo = Context.getTrivialTypeSourceInfo(Context.Int128Ty);
Chris Lattner4d150c82009-04-30 06:18:40 +000068 PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
69 SourceLocation(),
70 &Context.Idents.get("__int128_t"),
John McCalla93c9342009-12-07 02:54:59 +000071 TInfo), TUScope);
John McCallba6a9bd2009-10-24 08:00:42 +000072
John McCalla93c9342009-12-07 02:54:59 +000073 TInfo = Context.getTrivialTypeSourceInfo(Context.UnsignedInt128Ty);
Chris Lattner4d150c82009-04-30 06:18:40 +000074 PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
75 SourceLocation(),
76 &Context.Idents.get("__uint128_t"),
John McCalla93c9342009-12-07 02:54:59 +000077 TInfo), TUScope);
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +000078 Context.setInt128Installed();
Chris Lattner4d150c82009-04-30 06:18:40 +000079 }
Mike Stump1eb44332009-09-09 15:08:12 +000080
81
Chris Lattner2ae34ed2008-02-06 00:46:58 +000082 if (!PP.getLangOptions().ObjC1) return;
Mike Stump1eb44332009-09-09 15:08:12 +000083
Sebastian Redlc43b54c2010-08-18 23:56:43 +000084 // Built-in ObjC types may already be set by ASTReader (hence isNull checks).
Douglas Gregor319ac892009-04-23 22:29:11 +000085 if (Context.getObjCSelType().isNull()) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +000086 // Create the built-in typedef for 'SEL'.
Fariborz Jahanian04765ac2009-11-23 18:04:25 +000087 QualType SelT = Context.getPointerType(Context.ObjCBuiltinSelTy);
John McCalla93c9342009-12-07 02:54:59 +000088 TypeSourceInfo *SelInfo = Context.getTrivialTypeSourceInfo(SelT);
John McCallba6a9bd2009-10-24 08:00:42 +000089 TypedefDecl *SelTypedef
90 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
91 &Context.Idents.get("SEL"), SelInfo);
Douglas Gregor319ac892009-04-23 22:29:11 +000092 PushOnScopeChains(SelTypedef, TUScope);
93 Context.setObjCSelType(Context.getTypeDeclType(SelTypedef));
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +000094 Context.ObjCSelRedefinitionType = Context.getObjCSelType();
Douglas Gregor319ac892009-04-23 22:29:11 +000095 }
Chris Lattner6ee1f9c2008-06-21 20:20:39 +000096
Chris Lattner6ee1f9c2008-06-21 20:20:39 +000097 // Synthesize "@class Protocol;
Douglas Gregor319ac892009-04-23 22:29:11 +000098 if (Context.getObjCProtoType().isNull()) {
99 ObjCInterfaceDecl *ProtocolDecl =
100 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000101 &Context.Idents.get("Protocol"),
Douglas Gregordeacbdc2010-08-11 12:19:30 +0000102 SourceLocation(), true);
Douglas Gregor319ac892009-04-23 22:29:11 +0000103 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
Fariborz Jahanian10324db2009-11-18 23:15:37 +0000104 PushOnScopeChains(ProtocolDecl, TUScope, false);
Douglas Gregor319ac892009-04-23 22:29:11 +0000105 }
Steve Naroffde2e22d2009-07-15 18:40:39 +0000106 // Create the built-in typedef for 'id'.
Douglas Gregor319ac892009-04-23 22:29:11 +0000107 if (Context.getObjCIdType().isNull()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000108 QualType T = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 0, 0);
109 T = Context.getObjCObjectPointerType(T);
110 TypeSourceInfo *IdInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +0000111 TypedefDecl *IdTypedef
112 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
113 &Context.Idents.get("id"), IdInfo);
Douglas Gregor319ac892009-04-23 22:29:11 +0000114 PushOnScopeChains(IdTypedef, TUScope);
115 Context.setObjCIdType(Context.getTypeDeclType(IdTypedef));
David Chisnall0f436562009-08-17 16:35:33 +0000116 Context.ObjCIdRedefinitionType = Context.getObjCIdType();
Douglas Gregor319ac892009-04-23 22:29:11 +0000117 }
Steve Naroffde2e22d2009-07-15 18:40:39 +0000118 // Create the built-in typedef for 'Class'.
Steve Naroff14108da2009-07-10 23:34:53 +0000119 if (Context.getObjCClassType().isNull()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000120 QualType T = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 0, 0);
121 T = Context.getObjCObjectPointerType(T);
122 TypeSourceInfo *ClassInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +0000123 TypedefDecl *ClassTypedef
124 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
125 &Context.Idents.get("Class"), ClassInfo);
Steve Naroff14108da2009-07-10 23:34:53 +0000126 PushOnScopeChains(ClassTypedef, TUScope);
127 Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef));
David Chisnall0f436562009-08-17 16:35:33 +0000128 Context.ObjCClassRedefinitionType = Context.getObjCClassType();
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000129 }
Steve Naroff3b950172007-10-10 21:53:07 +0000130}
131
Douglas Gregorf807fe02009-04-14 16:27:31 +0000132Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
Daniel Dunbar3a2838d2009-11-13 08:58:20 +0000133 bool CompleteTranslationUnit,
134 CodeCompleteConsumer *CodeCompleter)
Peter Collingbourne321b8172011-02-14 01:42:35 +0000135 : TheTargetAttributesSema(0), FPFeatures(pp.getLangOptions()),
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000136 LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
Mike Stump1eb44332009-09-09 15:08:12 +0000137 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
Daniel Dunbar3a2838d2009-11-13 08:58:20 +0000138 ExternalSource(0), CodeCompleter(CodeCompleter), CurContext(0),
John McCalleee1d542011-02-14 07:13:47 +0000139 PackContext(0), VisContext(0),
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000140 IdResolver(pp.getLangOptions()), CXXTypeInfoDecl(0), MSVCGuidDecl(0),
Bill Wendlingb7566d82010-09-08 21:30:16 +0000141 GlobalNewDeleteDeclared(false),
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000142 CompleteTranslationUnit(CompleteTranslationUnit),
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000143 NumSFINAEErrors(0), SuppressAccessChecking(false),
144 AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000145 NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
146 CurrentInstantiationScope(0), TyposCorrected(0),
Bill Wendlingb7566d82010-09-08 21:30:16 +0000147 AnalysisWarnings(*this)
Douglas Gregorf35f8282009-11-11 21:54:23 +0000148{
Steve Naroff3b950172007-10-10 21:53:07 +0000149 TUScope = 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000150 if (getLangOptions().CPlusPlus)
151 FieldCollector.reset(new CXXFieldCollector());
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Chris Lattner22caddc2008-11-23 09:13:29 +0000153 // Tell diagnostics how to render things from the AST library.
Douglas Gregor79a9a342010-02-09 22:26:47 +0000154 PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
155 &Context);
Douglas Gregor2afce722009-11-26 00:44:06 +0000156
157 ExprEvalContexts.push_back(
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000158 ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0));
John McCall781472f2010-08-25 08:40:02 +0000159
Argyrios Kyrtzidis8fc32d22010-11-19 00:19:15 +0000160 FunctionScopes.push_back(new FunctionScopeInfo(Diags));
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000161}
162
163void Sema::Initialize() {
164 // Tell the AST consumer about this Sema object.
165 Consumer.Initialize(Context);
166
167 // FIXME: Isn't this redundant with the initialization above?
168 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
169 SC->InitializeSema(*this);
170
171 // Tell the external Sema source about this Sema object.
172 if (ExternalSemaSource *ExternalSema
173 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
174 ExternalSema->InitializeSema(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000175}
176
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000177Sema::~Sema() {
178 if (PackContext) FreePackedContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +0000179 if (VisContext) FreeVisContext();
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000180 delete TheTargetAttributesSema;
John McCall781472f2010-08-25 08:40:02 +0000181
182 // Kill all the active scopes.
183 for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
184 delete FunctionScopes[I];
185 if (FunctionScopes.size() == 1)
186 delete FunctionScopes[0];
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000187
188 // Tell the SemaConsumer to forget about us; we're going out of scope.
189 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
190 SC->ForgetSema();
191
192 // Detach from the external Sema source.
193 if (ExternalSemaSource *ExternalSema
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000194 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000195 ExternalSema->ForgetSema();
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000196}
197
Mike Stump1eb44332009-09-09 15:08:12 +0000198/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Chris Lattner1e0a3902008-01-16 19:17:22 +0000199/// If there is already an implicit cast, merge into the existing one.
Sebastian Redl906082e2010-07-20 04:20:21 +0000200/// The result is of the given category.
Mike Stump1eb44332009-09-09 15:08:12 +0000201void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +0000202 CastKind Kind, ExprValueKind VK,
John McCallf871d0c2010-08-07 06:22:56 +0000203 const CXXCastPath *BasePath) {
Mon P Wang3a2c7442008-09-04 08:38:01 +0000204 QualType ExprTy = Context.getCanonicalType(Expr->getType());
205 QualType TypeTy = Context.getCanonicalType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000206
Mon P Wang3a2c7442008-09-04 08:38:01 +0000207 if (ExprTy == TypeTy)
208 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000209
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000210 // If this is a derived-to-base cast to a through a virtual base, we
211 // need a vtable.
John McCall2de56d12010-08-25 11:45:40 +0000212 if (Kind == CK_DerivedToBase &&
John McCallf871d0c2010-08-07 06:22:56 +0000213 BasePathInvolvesVirtualBase(*BasePath)) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000214 QualType T = Expr->getType();
215 if (const PointerType *Pointer = T->getAs<PointerType>())
216 T = Pointer->getPointeeType();
217 if (const RecordType *RecordTy = T->getAs<RecordType>())
218 MarkVTableUsed(Expr->getLocStart(),
219 cast<CXXRecordDecl>(RecordTy->getDecl()));
220 }
221
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000222 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
John McCallf871d0c2010-08-07 06:22:56 +0000223 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
Anders Carlsson4c5fad32009-09-15 05:28:24 +0000224 ImpCast->setType(Ty);
John McCall5baba9d2010-08-25 10:28:54 +0000225 ImpCast->setValueKind(VK);
Anders Carlsson4c5fad32009-09-15 05:28:24 +0000226 return;
227 }
228 }
229
John McCall5baba9d2010-08-25 10:28:54 +0000230 Expr = ImplicitCastExpr::Create(Context, Ty, Kind, Expr, BasePath, VK);
Sebastian Redl906082e2010-07-20 04:20:21 +0000231}
232
John McCall5baba9d2010-08-25 10:28:54 +0000233ExprValueKind Sema::CastCategory(Expr *E) {
Sebastian Redl906082e2010-07-20 04:20:21 +0000234 Expr::Classification Classification = E->Classify(Context);
John McCall5baba9d2010-08-25 10:28:54 +0000235 return Classification.isRValue() ? VK_RValue :
236 (Classification.isLValue() ? VK_LValue : VK_XValue);
Chris Lattner1e0a3902008-01-16 19:17:22 +0000237}
238
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000239/// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
240static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
241 if (D->isUsed())
242 return true;
243
244 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
245 // UnusedFileScopedDecls stores the first declaration.
246 // The declaration may have become definition so check again.
247 const FunctionDecl *DeclToCheck;
248 if (FD->hasBody(DeclToCheck))
249 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
250
251 // Later redecls may add new information resulting in not having to warn,
252 // so check again.
253 DeclToCheck = FD->getMostRecentDeclaration();
254 if (DeclToCheck != FD)
255 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
256 }
257
258 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
259 // UnusedFileScopedDecls stores the first declaration.
260 // The declaration may have become definition so check again.
261 const VarDecl *DeclToCheck = VD->getDefinition();
262 if (DeclToCheck)
263 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
264
265 // Later redecls may add new information resulting in not having to warn,
266 // so check again.
267 DeclToCheck = VD->getMostRecentDeclaration();
268 if (DeclToCheck != VD)
269 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
270 }
271
272 return false;
273}
274
John McCall15e310a2011-02-19 02:53:41 +0000275namespace {
276 struct UndefinedInternal {
277 NamedDecl *decl;
278 FullSourceLoc useLoc;
279
280 UndefinedInternal(NamedDecl *decl, FullSourceLoc useLoc)
281 : decl(decl), useLoc(useLoc) {}
282 };
283
284 bool operator<(const UndefinedInternal &l, const UndefinedInternal &r) {
285 return l.useLoc.isBeforeInTranslationUnitThan(r.useLoc);
286 }
287}
288
289/// checkUndefinedInternals - Check for undefined objects with internal linkage.
290static void checkUndefinedInternals(Sema &S) {
291 if (S.UndefinedInternals.empty()) return;
292
293 // Collect all the still-undefined entities with internal linkage.
294 llvm::SmallVector<UndefinedInternal, 16> undefined;
295 for (llvm::DenseMap<NamedDecl*,SourceLocation>::iterator
296 i = S.UndefinedInternals.begin(), e = S.UndefinedInternals.end();
297 i != e; ++i) {
298 NamedDecl *decl = i->first;
299
300 // Ignore attributes that have become invalid.
301 if (decl->isInvalidDecl()) continue;
302
303 // __attribute__((weakref)) is basically a definition.
304 if (decl->hasAttr<WeakRefAttr>()) continue;
305
306 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
307 if (fn->isPure() || fn->hasBody())
308 continue;
309 } else {
310 if (cast<VarDecl>(decl)->hasDefinition() != VarDecl::DeclarationOnly)
311 continue;
312 }
313
314 // We build a FullSourceLoc so that we can sort with array_pod_sort.
315 FullSourceLoc loc(i->second, S.Context.getSourceManager());
316 undefined.push_back(UndefinedInternal(decl, loc));
317 }
318
319 if (undefined.empty()) return;
320
321 // Sort (in order of use site) so that we're not (as) dependent on
322 // the iteration order through an llvm::DenseMap.
323 llvm::array_pod_sort(undefined.begin(), undefined.end());
324
325 for (llvm::SmallVectorImpl<UndefinedInternal>::iterator
326 i = undefined.begin(), e = undefined.end(); i != e; ++i) {
327 NamedDecl *decl = i->decl;
328 S.Diag(decl->getLocation(), diag::warn_undefined_internal)
329 << isa<VarDecl>(decl) << decl;
330 S.Diag(i->useLoc, diag::note_used_here);
331 }
332}
333
Chris Lattner9299f3f2008-08-23 03:19:52 +0000334/// ActOnEndOfTranslationUnit - This is called at the very end of the
335/// translation unit when EOF is reached and all but the top-level scope is
336/// popped.
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +0000337void Sema::ActOnEndOfTranslationUnit() {
338 // At PCH writing, implicit instantiations and VTable handling info are
339 // stored and performed when the PCH is included.
Nick Lewycky2a5f99e2010-11-25 00:35:20 +0000340 if (CompleteTranslationUnit) {
Chandler Carruthaee543a2010-12-12 21:36:11 +0000341 // If any dynamic classes have their key function defined within
342 // this translation unit, then those vtables are considered "used" and must
343 // be emitted.
344 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
Anders Carlssona5c6c2a2011-01-25 18:08:22 +0000345 assert(!DynamicClasses[I]->isDependentType() &&
346 "Should not see dependent types here!");
Chandler Carruthaee543a2010-12-12 21:36:11 +0000347 if (const CXXMethodDecl *KeyFunction
348 = Context.getKeyFunction(DynamicClasses[I])) {
349 const FunctionDecl *Definition = 0;
350 if (KeyFunction->hasBody(Definition))
351 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
352 }
353 }
354
Nick Lewycky2a5f99e2010-11-25 00:35:20 +0000355 // If DefinedUsedVTables ends up marking any virtual member functions it
356 // might lead to more pending template instantiations, which we then need
357 // to instantiate.
358 DefineUsedVTables();
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +0000359
Nick Lewycky2a5f99e2010-11-25 00:35:20 +0000360 // C++: Perform implicit template instantiations.
361 //
362 // FIXME: When we perform these implicit instantiations, we do not
363 // carefully keep track of the point of instantiation (C++ [temp.point]).
364 // This means that name lookup that occurs within the template
365 // instantiation will always happen at the end of the translation unit,
366 // so it will find some names that should not be found. Although this is
367 // common behavior for C++ compilers, it is technically wrong. In the
368 // future, we either need to be able to filter the results of name lookup
369 // or we need to perform template instantiations earlier.
370 PerformPendingInstantiations();
371 }
Anders Carlssond6a637f2009-12-07 08:24:59 +0000372
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000373 // Remove file scoped decls that turned out to be used.
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000374 UnusedFileScopedDecls.erase(std::remove_if(UnusedFileScopedDecls.begin(),
375 UnusedFileScopedDecls.end(),
376 std::bind1st(std::ptr_fun(ShouldRemoveFromUnused),
377 this)),
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000378 UnusedFileScopedDecls.end());
Douglas Gregor47268a32010-04-09 17:41:13 +0000379
Douglas Gregor87c08a52010-08-13 22:48:40 +0000380 if (!CompleteTranslationUnit) {
381 TUScope = 0;
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +0000382 return;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000383 }
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +0000384
Chris Lattner63d65f82009-09-08 18:19:27 +0000385 // Check for #pragma weak identifiers that were never declared
386 // FIXME: This will cause diagnostics to be emitted in a non-determinstic
387 // order! Iterating over a densemap like this is bad.
Ryan Flynne25ff832009-07-30 03:15:39 +0000388 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
Chris Lattner63d65f82009-09-08 18:19:27 +0000389 I = WeakUndeclaredIdentifiers.begin(),
390 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
391 if (I->second.getUsed()) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Chris Lattner63d65f82009-09-08 18:19:27 +0000393 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
394 << I->first;
Ryan Flynne25ff832009-07-30 03:15:39 +0000395 }
396
Douglas Gregor275a3692009-03-10 23:43:53 +0000397 // C99 6.9.2p2:
398 // A declaration of an identifier for an object that has file
399 // scope without an initializer, and without a storage-class
400 // specifier or with the storage-class specifier static,
401 // constitutes a tentative definition. If a translation unit
402 // contains one or more tentative definitions for an identifier,
403 // and the translation unit contains no external definition for
404 // that identifier, then the behavior is exactly as if the
405 // translation unit contains a file scope declaration of that
406 // identifier, with the composite type as of the end of the
407 // translation unit, with an initializer equal to 0.
Sebastian Redle9d12b62010-01-31 22:27:38 +0000408 llvm::SmallSet<VarDecl *, 32> Seen;
409 for (unsigned i = 0, e = TentativeDefinitions.size(); i != e; ++i) {
410 VarDecl *VD = TentativeDefinitions[i]->getActingDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Sebastian Redle9d12b62010-01-31 22:27:38 +0000412 // If the tentative definition was completed, getActingDefinition() returns
413 // null. If we've already seen this variable before, insert()'s second
414 // return value is false.
415 if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000416 continue;
417
Mike Stump1eb44332009-09-09 15:08:12 +0000418 if (const IncompleteArrayType *ArrayT
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000419 = Context.getAsIncompleteArrayType(VD->getType())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000420 if (RequireCompleteType(VD->getLocation(),
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000421 ArrayT->getElementType(),
Chris Lattner63d65f82009-09-08 18:19:27 +0000422 diag::err_tentative_def_incomplete_type_arr)) {
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000423 VD->setInvalidDecl();
Chris Lattner63d65f82009-09-08 18:19:27 +0000424 continue;
Douglas Gregor275a3692009-03-10 23:43:53 +0000425 }
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Chris Lattner63d65f82009-09-08 18:19:27 +0000427 // Set the length of the array to 1 (C99 6.9.2p5).
428 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
429 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
John McCall46a617a2009-10-16 00:14:28 +0000430 QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
431 One, ArrayType::Normal, 0);
Chris Lattner63d65f82009-09-08 18:19:27 +0000432 VD->setType(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000433 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000434 diag::err_tentative_def_incomplete_type))
435 VD->setInvalidDecl();
436
437 // Notify the consumer that we've completed a tentative definition.
438 if (!VD->isInvalidDecl())
439 Consumer.CompleteTentativeDefinition(VD);
440
Douglas Gregor275a3692009-03-10 23:43:53 +0000441 }
Argyrios Kyrtzidis43f0a7c2011-01-31 07:04:37 +0000442
443 // If there were errors, disable 'unused' warnings since they will mostly be
444 // noise.
445 if (!Diags.hasErrorOccurred()) {
446 // Output warning for unused file scoped decls.
447 for (llvm::SmallVectorImpl<const DeclaratorDecl*>::iterator
448 I = UnusedFileScopedDecls.begin(),
449 E = UnusedFileScopedDecls.end(); I != E; ++I) {
450 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
451 const FunctionDecl *DiagD;
452 if (!FD->hasBody(DiagD))
453 DiagD = FD;
Argyrios Kyrtzidis48b89592011-03-03 17:47:42 +0000454 if (DiagD->isDeleted())
455 continue; // Deleted functions are supposed to be unused.
Argyrios Kyrtzidis43f0a7c2011-01-31 07:04:37 +0000456 Diag(DiagD->getLocation(),
457 isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
458 : diag::warn_unused_function)
459 << DiagD->getDeclName();
460 } else {
461 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
462 if (!DiagD)
463 DiagD = cast<VarDecl>(*I);
464 Diag(DiagD->getLocation(), diag::warn_unused_variable)
465 << DiagD->getDeclName();
466 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000467 }
John McCall15e310a2011-02-19 02:53:41 +0000468
469 checkUndefinedInternals(*this);
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000470 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000471
Richard Smith483b9f32011-02-21 20:05:19 +0000472 // Check we've noticed that we're no longer parsing the initializer for every
473 // variable. If we miss cases, then at best we have a performance issue and
474 // at worst a rejects-valid bug.
475 assert(ParsingInitForAutoVars.empty() &&
476 "Didn't unmark var as having its initializer parsed");
477
Douglas Gregor87c08a52010-08-13 22:48:40 +0000478 TUScope = 0;
Chris Lattner9299f3f2008-08-23 03:19:52 +0000479}
480
481
Reid Spencer5f016e22007-07-11 17:01:13 +0000482//===----------------------------------------------------------------------===//
483// Helper functions.
484//===----------------------------------------------------------------------===//
485
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000486DeclContext *Sema::getFunctionLevelDeclContext() {
John McCalldb0ee1d2009-12-19 10:53:49 +0000487 DeclContext *DC = CurContext;
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Douglas Gregord9008312010-05-22 16:25:05 +0000489 while (isa<BlockDecl>(DC) || isa<EnumDecl>(DC))
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000490 DC = DC->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000492 return DC;
493}
494
Chris Lattner371f2582008-12-04 23:50:19 +0000495/// getCurFunctionDecl - If inside of a function body, this returns a pointer
496/// to the function decl for the function being parsed. If we're currently
497/// in a 'block', this returns the containing context.
498FunctionDecl *Sema::getCurFunctionDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000499 DeclContext *DC = getFunctionLevelDeclContext();
Chris Lattner371f2582008-12-04 23:50:19 +0000500 return dyn_cast<FunctionDecl>(DC);
501}
502
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +0000503ObjCMethodDecl *Sema::getCurMethodDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000504 DeclContext *DC = getFunctionLevelDeclContext();
Steve Naroffd7612e12008-11-17 16:28:52 +0000505 return dyn_cast<ObjCMethodDecl>(DC);
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +0000506}
Chris Lattner371f2582008-12-04 23:50:19 +0000507
508NamedDecl *Sema::getCurFunctionOrMethodDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000509 DeclContext *DC = getFunctionLevelDeclContext();
Chris Lattner371f2582008-12-04 23:50:19 +0000510 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000511 return cast<NamedDecl>(DC);
Chris Lattner371f2582008-12-04 23:50:19 +0000512 return 0;
513}
514
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000515Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
Douglas Gregor9b623632010-10-12 23:32:35 +0000516 if (!isActive())
517 return;
518
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000519 if (llvm::Optional<TemplateDeductionInfo*> Info = SemaRef.isSFINAEContext()) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000520 switch (DiagnosticIDs::getDiagnosticSFINAEResponse(getDiagID())) {
521 case DiagnosticIDs::SFINAE_Report:
Douglas Gregor9b623632010-10-12 23:32:35 +0000522 // Fall through; we'll report the diagnostic below.
523 break;
524
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000525 case DiagnosticIDs::SFINAE_AccessControl:
526 // Unless access checking is specifically called out as a SFINAE
527 // error, report this diagnostic.
528 if (!SemaRef.AccessCheckingSFINAE)
529 break;
530
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000531 case DiagnosticIDs::SFINAE_SubstitutionFailure:
Douglas Gregor9b623632010-10-12 23:32:35 +0000532 // Count this failure so that we know that template argument deduction
533 // has failed.
534 ++SemaRef.NumSFINAEErrors;
535 SemaRef.Diags.setLastDiagnosticIgnored();
536 SemaRef.Diags.Clear();
537 Clear();
538 return;
539
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000540 case DiagnosticIDs::SFINAE_Suppress:
Douglas Gregor9b623632010-10-12 23:32:35 +0000541 // Make a copy of this suppressed diagnostic and store it with the
542 // template-deduction information;
Douglas Gregorb5350412010-10-13 17:22:14 +0000543 FlushCounts();
Douglas Gregor9b623632010-10-12 23:32:35 +0000544 DiagnosticInfo DiagInfo(&SemaRef.Diags);
Douglas Gregorb5350412010-10-13 17:22:14 +0000545
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000546 if (*Info)
547 (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
Douglas Gregor9b623632010-10-12 23:32:35 +0000548 PartialDiagnostic(DiagInfo,
549 SemaRef.Context.getDiagAllocator()));
550
551 // Suppress this diagnostic.
552 SemaRef.Diags.setLastDiagnosticIgnored();
553 SemaRef.Diags.Clear();
554 Clear();
555 return;
556 }
557 }
558
559 // Emit the diagnostic.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000560 if (!this->Emit())
561 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000563 // If this is not a note, and we're in a template instantiation
564 // that is different from the last template instantiation where
565 // we emitted an error, print a template instantiation
566 // backtrace.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000567 if (!DiagnosticIDs::isBuiltinNote(DiagID) &&
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000568 !SemaRef.ActiveTemplateInstantiations.empty() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000569 SemaRef.ActiveTemplateInstantiations.back()
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000570 != SemaRef.LastTemplateInstantiationErrorContext) {
571 SemaRef.PrintInstantiationStack();
Mike Stump1eb44332009-09-09 15:08:12 +0000572 SemaRef.LastTemplateInstantiationErrorContext
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000573 = SemaRef.ActiveTemplateInstantiations.back();
574 }
575}
Douglas Gregor2e222532009-07-02 17:08:52 +0000576
Douglas Gregoreab5d1e2010-03-25 22:17:48 +0000577Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000578 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
Douglas Gregoreab5d1e2010-03-25 22:17:48 +0000579 return SemaDiagnosticBuilder(DB, *this, DiagID);
580}
581
Anders Carlsson91a0cc92009-08-26 22:33:56 +0000582Sema::SemaDiagnosticBuilder
583Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
584 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
585 PD.Emit(Builder);
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Anders Carlsson91a0cc92009-08-26 22:33:56 +0000587 return Builder;
588}
589
Douglas Gregor23c94db2010-07-02 17:43:08 +0000590/// \brief Determines the active Scope associated with the given declaration
591/// context.
592///
593/// This routine maps a declaration context to the active Scope object that
594/// represents that declaration context in the parser. It is typically used
595/// from "scope-less" code (e.g., template instantiation, lazy creation of
596/// declarations) that injects a name for name-lookup purposes and, therefore,
597/// must update the Scope.
598///
599/// \returns The scope corresponding to the given declaraion context, or NULL
600/// if no such scope is open.
601Scope *Sema::getScopeForContext(DeclContext *Ctx) {
602
603 if (!Ctx)
604 return 0;
605
606 Ctx = Ctx->getPrimaryContext();
607 for (Scope *S = getCurScope(); S; S = S->getParent()) {
Sebastian Redlcddc69f2010-07-08 23:07:34 +0000608 // Ignore scopes that cannot have declarations. This is important for
609 // out-of-line definitions of static class members.
610 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
611 if (DeclContext *Entity = static_cast<DeclContext *> (S->getEntity()))
612 if (Ctx == Entity->getPrimaryContext())
613 return S;
Douglas Gregor23c94db2010-07-02 17:43:08 +0000614 }
615
616 return 0;
617}
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000618
619/// \brief Enter a new function scope
620void Sema::PushFunctionScope() {
John McCall781472f2010-08-25 08:40:02 +0000621 if (FunctionScopes.size() == 1) {
622 // Use the "top" function scope rather than having to allocate
623 // memory for a new scope.
Argyrios Kyrtzidis8fc32d22010-11-19 00:19:15 +0000624 FunctionScopes.back()->Clear();
John McCall781472f2010-08-25 08:40:02 +0000625 FunctionScopes.push_back(FunctionScopes.back());
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000626 return;
627 }
628
Argyrios Kyrtzidis8fc32d22010-11-19 00:19:15 +0000629 FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000630}
631
632void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
Argyrios Kyrtzidis8fc32d22010-11-19 00:19:15 +0000633 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000634 BlockScope, Block));
635}
636
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000637void Sema::PopFunctionOrBlockScope(const AnalysisBasedWarnings::Policy *WP,
638 const Decl *D, const BlockExpr *blkExpr) {
639 FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
John McCall781472f2010-08-25 08:40:02 +0000640 assert(!FunctionScopes.empty() && "mismatched push/pop!");
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000641
642 // Issue any analysis-based warnings.
643 if (WP && D)
Ted Kremenek283a3582011-02-23 01:51:53 +0000644 AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
Ted Kremenek351ba912011-02-23 01:52:04 +0000645 else {
646 for (llvm::SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
647 i = Scope->PossiblyUnreachableDiags.begin(),
648 e = Scope->PossiblyUnreachableDiags.end();
649 i != e; ++i) {
650 const sema::PossiblyUnreachableDiag &D = *i;
651 Diag(D.Loc, D.PD);
652 }
653 }
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000654
Ted Kremenek351ba912011-02-23 01:52:04 +0000655 if (FunctionScopes.back() != Scope) {
John McCall781472f2010-08-25 08:40:02 +0000656 delete Scope;
Ted Kremenek351ba912011-02-23 01:52:04 +0000657 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000658}
659
660/// \brief Determine whether any errors occurred within this function/method/
661/// block.
662bool Sema::hasAnyErrorsInThisFunction() const {
Argyrios Kyrtzidis8fc32d22010-11-19 00:19:15 +0000663 return getCurFunction()->ErrorTrap.hasErrorOccurred();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000664}
665
666BlockScopeInfo *Sema::getCurBlock() {
667 if (FunctionScopes.empty())
668 return 0;
669
670 return dyn_cast<BlockScopeInfo>(FunctionScopes.back());
671}
John McCall76bd1f32010-06-01 09:23:16 +0000672
673// Pin this vtable to this file.
674ExternalSemaSource::~ExternalSemaSource() {}
John McCallf312b1e2010-08-26 23:41:50 +0000675
Sebastian Redl8c845712010-09-28 20:23:00 +0000676std::pair<ObjCMethodList, ObjCMethodList>
677ExternalSemaSource::ReadMethodPool(Selector Sel) {
678 return std::pair<ObjCMethodList, ObjCMethodList>();
679}
680
John McCallf312b1e2010-08-26 23:41:50 +0000681void PrettyDeclStackTraceEntry::print(llvm::raw_ostream &OS) const {
682 SourceLocation Loc = this->Loc;
683 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
684 if (Loc.isValid()) {
685 Loc.print(OS, S.getSourceManager());
686 OS << ": ";
687 }
688 OS << Message;
689
690 if (TheDecl && isa<NamedDecl>(TheDecl)) {
691 std::string Name = cast<NamedDecl>(TheDecl)->getNameAsString();
692 if (!Name.empty())
693 OS << " '" << Name << '\'';
694 }
695
696 OS << '\n';
697}