blob: a0046a2caa1e3b43f3e0e9f12d983fa98b70dd26 [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"
John McCall76bd1f32010-06-01 09:23:16 +000022#include "clang/Sema/ExternalSemaSource.h"
Sebastian Redl8c845712010-09-28 20:23:00 +000023#include "clang/Sema/ObjCMethodList.h"
John McCallf312b1e2010-08-26 23:41:50 +000024#include "clang/Sema/PrettyDeclStackTrace.h"
John McCall5f1e0942010-08-24 08:50:51 +000025#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000026#include "clang/Sema/ScopeInfo.h"
Douglas Gregor46ea32a2010-08-12 22:51:45 +000027#include "clang/Sema/SemaConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "clang/AST/ASTContext.h"
Douglas Gregor79a9a342010-02-09 22:26:47 +000029#include "clang/AST/ASTDiagnostic.h"
John McCall384aff82010-08-25 07:42:41 +000030#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000031#include "clang/AST/DeclObjC.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000032#include "clang/AST/Expr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Lex/Preprocessor.h"
Anders Carlsson91a0cc92009-08-26 22:33:56 +000034#include "clang/Basic/PartialDiagnostic.h"
Chris Lattner4d150c82009-04-30 06:18:40 +000035#include "clang/Basic/TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000036using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000037using namespace sema;
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000038
39FunctionScopeInfo::~FunctionScopeInfo() { }
40
41void FunctionScopeInfo::Clear(unsigned NumErrors) {
John McCallb60a77e2010-08-01 00:26:45 +000042 HasBranchProtectedScope = false;
43 HasBranchIntoScope = false;
44 HasIndirectGoto = false;
45
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000046 LabelMap.clear();
47 SwitchStack.clear();
Douglas Gregor5077c382010-05-15 06:01:05 +000048 Returns.clear();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000049 NumErrorsAtStartOfFunction = NumErrors;
50}
51
52BlockScopeInfo::~BlockScopeInfo() { }
53
Douglas Gregorc1a3e5e2010-08-25 18:07:12 +000054void Sema::ActOnTranslationUnitScope(Scope *S) {
Steve Naroffb216c882007-10-09 22:01:59 +000055 TUScope = S;
Douglas Gregor44b43212008-12-11 16:49:14 +000056 PushDeclContext(S, Context.getTranslationUnitDecl());
Mike Stump1eb44332009-09-09 15:08:12 +000057
John McCallc7e04da2010-05-28 18:45:08 +000058 VAListTagName = PP.getIdentifierInfo("__va_list_tag");
59
Sebastian Redlc43b54c2010-08-18 23:56:43 +000060 if (!Context.isInt128Installed() && // May be set by ASTReader.
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +000061 PP.getTargetInfo().getPointerWidth(0) >= 64) {
John McCalla93c9342009-12-07 02:54:59 +000062 TypeSourceInfo *TInfo;
John McCallba6a9bd2009-10-24 08:00:42 +000063
Chris Lattner4d150c82009-04-30 06:18:40 +000064 // Install [u]int128_t for 64-bit targets.
John McCalla93c9342009-12-07 02:54:59 +000065 TInfo = Context.getTrivialTypeSourceInfo(Context.Int128Ty);
Chris Lattner4d150c82009-04-30 06:18:40 +000066 PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
67 SourceLocation(),
68 &Context.Idents.get("__int128_t"),
John McCalla93c9342009-12-07 02:54:59 +000069 TInfo), TUScope);
John McCallba6a9bd2009-10-24 08:00:42 +000070
John McCalla93c9342009-12-07 02:54:59 +000071 TInfo = Context.getTrivialTypeSourceInfo(Context.UnsignedInt128Ty);
Chris Lattner4d150c82009-04-30 06:18:40 +000072 PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
73 SourceLocation(),
74 &Context.Idents.get("__uint128_t"),
John McCalla93c9342009-12-07 02:54:59 +000075 TInfo), TUScope);
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +000076 Context.setInt128Installed();
Chris Lattner4d150c82009-04-30 06:18:40 +000077 }
Mike Stump1eb44332009-09-09 15:08:12 +000078
79
Chris Lattner2ae34ed2008-02-06 00:46:58 +000080 if (!PP.getLangOptions().ObjC1) return;
Mike Stump1eb44332009-09-09 15:08:12 +000081
Sebastian Redlc43b54c2010-08-18 23:56:43 +000082 // Built-in ObjC types may already be set by ASTReader (hence isNull checks).
Douglas Gregor319ac892009-04-23 22:29:11 +000083 if (Context.getObjCSelType().isNull()) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +000084 // Create the built-in typedef for 'SEL'.
Fariborz Jahanian04765ac2009-11-23 18:04:25 +000085 QualType SelT = Context.getPointerType(Context.ObjCBuiltinSelTy);
John McCalla93c9342009-12-07 02:54:59 +000086 TypeSourceInfo *SelInfo = Context.getTrivialTypeSourceInfo(SelT);
John McCallba6a9bd2009-10-24 08:00:42 +000087 TypedefDecl *SelTypedef
88 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
89 &Context.Idents.get("SEL"), SelInfo);
Douglas Gregor319ac892009-04-23 22:29:11 +000090 PushOnScopeChains(SelTypedef, TUScope);
91 Context.setObjCSelType(Context.getTypeDeclType(SelTypedef));
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +000092 Context.ObjCSelRedefinitionType = Context.getObjCSelType();
Douglas Gregor319ac892009-04-23 22:29:11 +000093 }
Chris Lattner6ee1f9c2008-06-21 20:20:39 +000094
Chris Lattner6ee1f9c2008-06-21 20:20:39 +000095 // Synthesize "@class Protocol;
Douglas Gregor319ac892009-04-23 22:29:11 +000096 if (Context.getObjCProtoType().isNull()) {
97 ObjCInterfaceDecl *ProtocolDecl =
98 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000099 &Context.Idents.get("Protocol"),
Douglas Gregordeacbdc2010-08-11 12:19:30 +0000100 SourceLocation(), true);
Douglas Gregor319ac892009-04-23 22:29:11 +0000101 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
Fariborz Jahanian10324db2009-11-18 23:15:37 +0000102 PushOnScopeChains(ProtocolDecl, TUScope, false);
Douglas Gregor319ac892009-04-23 22:29:11 +0000103 }
Steve Naroffde2e22d2009-07-15 18:40:39 +0000104 // Create the built-in typedef for 'id'.
Douglas Gregor319ac892009-04-23 22:29:11 +0000105 if (Context.getObjCIdType().isNull()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000106 QualType T = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 0, 0);
107 T = Context.getObjCObjectPointerType(T);
108 TypeSourceInfo *IdInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +0000109 TypedefDecl *IdTypedef
110 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
111 &Context.Idents.get("id"), IdInfo);
Douglas Gregor319ac892009-04-23 22:29:11 +0000112 PushOnScopeChains(IdTypedef, TUScope);
113 Context.setObjCIdType(Context.getTypeDeclType(IdTypedef));
David Chisnall0f436562009-08-17 16:35:33 +0000114 Context.ObjCIdRedefinitionType = Context.getObjCIdType();
Douglas Gregor319ac892009-04-23 22:29:11 +0000115 }
Steve Naroffde2e22d2009-07-15 18:40:39 +0000116 // Create the built-in typedef for 'Class'.
Steve Naroff14108da2009-07-10 23:34:53 +0000117 if (Context.getObjCClassType().isNull()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000118 QualType T = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 0, 0);
119 T = Context.getObjCObjectPointerType(T);
120 TypeSourceInfo *ClassInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +0000121 TypedefDecl *ClassTypedef
122 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
123 &Context.Idents.get("Class"), ClassInfo);
Steve Naroff14108da2009-07-10 23:34:53 +0000124 PushOnScopeChains(ClassTypedef, TUScope);
125 Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef));
David Chisnall0f436562009-08-17 16:35:33 +0000126 Context.ObjCClassRedefinitionType = Context.getObjCClassType();
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000127 }
Steve Naroff3b950172007-10-10 21:53:07 +0000128}
129
Douglas Gregorf807fe02009-04-14 16:27:31 +0000130Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
Daniel Dunbar3a2838d2009-11-13 08:58:20 +0000131 bool CompleteTranslationUnit,
132 CodeCompleteConsumer *CodeCompleter)
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000133 : TheTargetAttributesSema(0),
134 LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
Mike Stump1eb44332009-09-09 15:08:12 +0000135 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
Daniel Dunbar3a2838d2009-11-13 08:58:20 +0000136 ExternalSource(0), CodeCompleter(CodeCompleter), CurContext(0),
John McCall781472f2010-08-25 08:40:02 +0000137 PackContext(0), VisContext(0), ParsingDeclDepth(0),
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000138 IdResolver(pp.getLangOptions()), CXXTypeInfoDecl(0), MSVCGuidDecl(0),
Bill Wendlingb7566d82010-09-08 21:30:16 +0000139 GlobalNewDeleteDeclared(false),
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000140 CompleteTranslationUnit(CompleteTranslationUnit),
Chandler Carruth926c4b42010-06-28 08:39:25 +0000141 NumSFINAEErrors(0), SuppressAccessChecking(false),
142 NonInstantiationEntries(0), CurrentInstantiationScope(0), TyposCorrected(0),
Bill Wendlingb7566d82010-09-08 21:30:16 +0000143 AnalysisWarnings(*this)
Douglas Gregorf35f8282009-11-11 21:54:23 +0000144{
Steve Naroff3b950172007-10-10 21:53:07 +0000145 TUScope = 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000146 if (getLangOptions().CPlusPlus)
147 FieldCollector.reset(new CXXFieldCollector());
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Chris Lattner22caddc2008-11-23 09:13:29 +0000149 // Tell diagnostics how to render things from the AST library.
Douglas Gregor79a9a342010-02-09 22:26:47 +0000150 PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
151 &Context);
Douglas Gregor2afce722009-11-26 00:44:06 +0000152
153 ExprEvalContexts.push_back(
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000154 ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0));
John McCall781472f2010-08-25 08:40:02 +0000155
156 FunctionScopes.push_back(new FunctionScopeInfo(Diags.getNumErrors()));
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000157}
158
159void Sema::Initialize() {
160 // Tell the AST consumer about this Sema object.
161 Consumer.Initialize(Context);
162
163 // FIXME: Isn't this redundant with the initialization above?
164 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
165 SC->InitializeSema(*this);
166
167 // Tell the external Sema source about this Sema object.
168 if (ExternalSemaSource *ExternalSema
169 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
170 ExternalSema->InitializeSema(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000171}
172
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000173Sema::~Sema() {
174 if (PackContext) FreePackedContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +0000175 if (VisContext) FreeVisContext();
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000176 delete TheTargetAttributesSema;
John McCall781472f2010-08-25 08:40:02 +0000177
178 // Kill all the active scopes.
179 for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
180 delete FunctionScopes[I];
181 if (FunctionScopes.size() == 1)
182 delete FunctionScopes[0];
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000183
184 // Tell the SemaConsumer to forget about us; we're going out of scope.
185 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
186 SC->ForgetSema();
187
188 // Detach from the external Sema source.
189 if (ExternalSemaSource *ExternalSema
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000190 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000191 ExternalSema->ForgetSema();
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000192}
193
Mike Stump1eb44332009-09-09 15:08:12 +0000194/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Chris Lattner1e0a3902008-01-16 19:17:22 +0000195/// If there is already an implicit cast, merge into the existing one.
Sebastian Redl906082e2010-07-20 04:20:21 +0000196/// The result is of the given category.
Mike Stump1eb44332009-09-09 15:08:12 +0000197void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +0000198 CastKind Kind, ExprValueKind VK,
John McCallf871d0c2010-08-07 06:22:56 +0000199 const CXXCastPath *BasePath) {
Mon P Wang3a2c7442008-09-04 08:38:01 +0000200 QualType ExprTy = Context.getCanonicalType(Expr->getType());
201 QualType TypeTy = Context.getCanonicalType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000202
Mon P Wang3a2c7442008-09-04 08:38:01 +0000203 if (ExprTy == TypeTy)
204 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000205
John McCall680523a2009-11-07 03:30:10 +0000206 if (Expr->getType()->isPointerType() && Ty->isPointerType()) {
207 QualType ExprBaseType = cast<PointerType>(ExprTy)->getPointeeType();
208 QualType BaseType = cast<PointerType>(TypeTy)->getPointeeType();
Mon P Wang3a2c7442008-09-04 08:38:01 +0000209 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000210 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
211 << Expr->getSourceRange();
Mon P Wang3a2c7442008-09-04 08:38:01 +0000212 }
213 }
Mike Stump1eb44332009-09-09 15:08:12 +0000214
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000215 // If this is a derived-to-base cast to a through a virtual base, we
216 // need a vtable.
John McCall2de56d12010-08-25 11:45:40 +0000217 if (Kind == CK_DerivedToBase &&
John McCallf871d0c2010-08-07 06:22:56 +0000218 BasePathInvolvesVirtualBase(*BasePath)) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000219 QualType T = Expr->getType();
220 if (const PointerType *Pointer = T->getAs<PointerType>())
221 T = Pointer->getPointeeType();
222 if (const RecordType *RecordTy = T->getAs<RecordType>())
223 MarkVTableUsed(Expr->getLocStart(),
224 cast<CXXRecordDecl>(RecordTy->getDecl()));
225 }
226
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000227 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
John McCallf871d0c2010-08-07 06:22:56 +0000228 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
Anders Carlsson4c5fad32009-09-15 05:28:24 +0000229 ImpCast->setType(Ty);
John McCall5baba9d2010-08-25 10:28:54 +0000230 ImpCast->setValueKind(VK);
Anders Carlsson4c5fad32009-09-15 05:28:24 +0000231 return;
232 }
233 }
234
John McCall5baba9d2010-08-25 10:28:54 +0000235 Expr = ImplicitCastExpr::Create(Context, Ty, Kind, Expr, BasePath, VK);
Sebastian Redl906082e2010-07-20 04:20:21 +0000236}
237
John McCall5baba9d2010-08-25 10:28:54 +0000238ExprValueKind Sema::CastCategory(Expr *E) {
Sebastian Redl906082e2010-07-20 04:20:21 +0000239 Expr::Classification Classification = E->Classify(Context);
John McCall5baba9d2010-08-25 10:28:54 +0000240 return Classification.isRValue() ? VK_RValue :
241 (Classification.isLValue() ? VK_LValue : VK_XValue);
Chris Lattner1e0a3902008-01-16 19:17:22 +0000242}
243
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000244/// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
245static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
246 if (D->isUsed())
247 return true;
248
249 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
250 // UnusedFileScopedDecls stores the first declaration.
251 // The declaration may have become definition so check again.
252 const FunctionDecl *DeclToCheck;
253 if (FD->hasBody(DeclToCheck))
254 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
255
256 // Later redecls may add new information resulting in not having to warn,
257 // so check again.
258 DeclToCheck = FD->getMostRecentDeclaration();
259 if (DeclToCheck != FD)
260 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
261 }
262
263 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
264 // UnusedFileScopedDecls stores the first declaration.
265 // The declaration may have become definition so check again.
266 const VarDecl *DeclToCheck = VD->getDefinition();
267 if (DeclToCheck)
268 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
269
270 // Later redecls may add new information resulting in not having to warn,
271 // so check again.
272 DeclToCheck = VD->getMostRecentDeclaration();
273 if (DeclToCheck != VD)
274 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
275 }
276
277 return false;
278}
279
Chris Lattner9299f3f2008-08-23 03:19:52 +0000280/// ActOnEndOfTranslationUnit - This is called at the very end of the
281/// translation unit when EOF is reached and all but the top-level scope is
282/// popped.
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +0000283void Sema::ActOnEndOfTranslationUnit() {
284 // At PCH writing, implicit instantiations and VTable handling info are
285 // stored and performed when the PCH is included.
286 if (CompleteTranslationUnit)
287 while (1) {
288 // C++: Perform implicit template instantiations.
289 //
290 // FIXME: When we perform these implicit instantiations, we do not
291 // carefully keep track of the point of instantiation (C++ [temp.point]).
292 // This means that name lookup that occurs within the template
293 // instantiation will always happen at the end of the translation unit,
294 // so it will find some names that should not be found. Although this is
295 // common behavior for C++ compilers, it is technically wrong. In the
296 // future, we either need to be able to filter the results of name lookup
297 // or we need to perform template instantiations earlier.
Chandler Carruth62c78d52010-08-25 08:44:16 +0000298 PerformPendingInstantiations();
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +0000299
300 /// If DefinedUsedVTables ends up marking any virtual member
301 /// functions it might lead to more pending template
302 /// instantiations, which is why we need to loop here.
303 if (!DefineUsedVTables())
304 break;
305 }
Anders Carlssond6a637f2009-12-07 08:24:59 +0000306
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000307 // Remove file scoped decls that turned out to be used.
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000308 UnusedFileScopedDecls.erase(std::remove_if(UnusedFileScopedDecls.begin(),
309 UnusedFileScopedDecls.end(),
310 std::bind1st(std::ptr_fun(ShouldRemoveFromUnused),
311 this)),
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000312 UnusedFileScopedDecls.end());
Douglas Gregor47268a32010-04-09 17:41:13 +0000313
Douglas Gregor87c08a52010-08-13 22:48:40 +0000314 if (!CompleteTranslationUnit) {
315 TUScope = 0;
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +0000316 return;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000317 }
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +0000318
Chris Lattner63d65f82009-09-08 18:19:27 +0000319 // Check for #pragma weak identifiers that were never declared
320 // FIXME: This will cause diagnostics to be emitted in a non-determinstic
321 // order! Iterating over a densemap like this is bad.
Ryan Flynne25ff832009-07-30 03:15:39 +0000322 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
Chris Lattner63d65f82009-09-08 18:19:27 +0000323 I = WeakUndeclaredIdentifiers.begin(),
324 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
325 if (I->second.getUsed()) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Chris Lattner63d65f82009-09-08 18:19:27 +0000327 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
328 << I->first;
Ryan Flynne25ff832009-07-30 03:15:39 +0000329 }
330
Douglas Gregor275a3692009-03-10 23:43:53 +0000331 // C99 6.9.2p2:
332 // A declaration of an identifier for an object that has file
333 // scope without an initializer, and without a storage-class
334 // specifier or with the storage-class specifier static,
335 // constitutes a tentative definition. If a translation unit
336 // contains one or more tentative definitions for an identifier,
337 // and the translation unit contains no external definition for
338 // that identifier, then the behavior is exactly as if the
339 // translation unit contains a file scope declaration of that
340 // identifier, with the composite type as of the end of the
341 // translation unit, with an initializer equal to 0.
Sebastian Redle9d12b62010-01-31 22:27:38 +0000342 llvm::SmallSet<VarDecl *, 32> Seen;
343 for (unsigned i = 0, e = TentativeDefinitions.size(); i != e; ++i) {
344 VarDecl *VD = TentativeDefinitions[i]->getActingDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Sebastian Redle9d12b62010-01-31 22:27:38 +0000346 // If the tentative definition was completed, getActingDefinition() returns
347 // null. If we've already seen this variable before, insert()'s second
348 // return value is false.
349 if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000350 continue;
351
Mike Stump1eb44332009-09-09 15:08:12 +0000352 if (const IncompleteArrayType *ArrayT
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000353 = Context.getAsIncompleteArrayType(VD->getType())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000354 if (RequireCompleteType(VD->getLocation(),
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000355 ArrayT->getElementType(),
Chris Lattner63d65f82009-09-08 18:19:27 +0000356 diag::err_tentative_def_incomplete_type_arr)) {
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000357 VD->setInvalidDecl();
Chris Lattner63d65f82009-09-08 18:19:27 +0000358 continue;
Douglas Gregor275a3692009-03-10 23:43:53 +0000359 }
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Chris Lattner63d65f82009-09-08 18:19:27 +0000361 // Set the length of the array to 1 (C99 6.9.2p5).
362 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
363 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
John McCall46a617a2009-10-16 00:14:28 +0000364 QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
365 One, ArrayType::Normal, 0);
Chris Lattner63d65f82009-09-08 18:19:27 +0000366 VD->setType(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000367 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000368 diag::err_tentative_def_incomplete_type))
369 VD->setInvalidDecl();
370
371 // Notify the consumer that we've completed a tentative definition.
372 if (!VD->isInvalidDecl())
373 Consumer.CompleteTentativeDefinition(VD);
374
Douglas Gregor275a3692009-03-10 23:43:53 +0000375 }
Tanya Lattnere6bbc012010-02-12 00:07:30 +0000376
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000377 // Output warning for unused file scoped decls.
John McCallaab01322010-08-24 17:40:45 +0000378 for (llvm::SmallVectorImpl<const DeclaratorDecl*>::iterator
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000379 I = UnusedFileScopedDecls.begin(),
380 E = UnusedFileScopedDecls.end(); I != E; ++I) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000381 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
382 const FunctionDecl *DiagD;
383 if (!FD->hasBody(DiagD))
384 DiagD = FD;
Argyrios Kyrtzidis3d27b102010-08-17 21:43:11 +0000385 Diag(DiagD->getLocation(),
Argyrios Kyrtzidis42cbd782010-08-17 22:06:44 +0000386 isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
Argyrios Kyrtzidis3d27b102010-08-17 21:43:11 +0000387 : diag::warn_unused_function)
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000388 << DiagD->getDeclName();
389 } else {
390 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
391 if (!DiagD)
392 DiagD = cast<VarDecl>(*I);
393 Diag(DiagD->getLocation(), diag::warn_unused_variable)
394 << DiagD->getDeclName();
395 }
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000396 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000397
398 TUScope = 0;
Chris Lattner9299f3f2008-08-23 03:19:52 +0000399}
400
401
Reid Spencer5f016e22007-07-11 17:01:13 +0000402//===----------------------------------------------------------------------===//
403// Helper functions.
404//===----------------------------------------------------------------------===//
405
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000406DeclContext *Sema::getFunctionLevelDeclContext() {
John McCalldb0ee1d2009-12-19 10:53:49 +0000407 DeclContext *DC = CurContext;
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Douglas Gregord9008312010-05-22 16:25:05 +0000409 while (isa<BlockDecl>(DC) || isa<EnumDecl>(DC))
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000410 DC = DC->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000412 return DC;
413}
414
Chris Lattner371f2582008-12-04 23:50:19 +0000415/// getCurFunctionDecl - If inside of a function body, this returns a pointer
416/// to the function decl for the function being parsed. If we're currently
417/// in a 'block', this returns the containing context.
418FunctionDecl *Sema::getCurFunctionDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000419 DeclContext *DC = getFunctionLevelDeclContext();
Chris Lattner371f2582008-12-04 23:50:19 +0000420 return dyn_cast<FunctionDecl>(DC);
421}
422
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +0000423ObjCMethodDecl *Sema::getCurMethodDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000424 DeclContext *DC = getFunctionLevelDeclContext();
Steve Naroffd7612e12008-11-17 16:28:52 +0000425 return dyn_cast<ObjCMethodDecl>(DC);
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +0000426}
Chris Lattner371f2582008-12-04 23:50:19 +0000427
428NamedDecl *Sema::getCurFunctionOrMethodDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000429 DeclContext *DC = getFunctionLevelDeclContext();
Chris Lattner371f2582008-12-04 23:50:19 +0000430 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000431 return cast<NamedDecl>(DC);
Chris Lattner371f2582008-12-04 23:50:19 +0000432 return 0;
433}
434
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000435Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000436 if (!this->Emit())
437 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000439 // If this is not a note, and we're in a template instantiation
440 // that is different from the last template instantiation where
441 // we emitted an error, print a template instantiation
442 // backtrace.
443 if (!SemaRef.Diags.isBuiltinNote(DiagID) &&
444 !SemaRef.ActiveTemplateInstantiations.empty() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000445 SemaRef.ActiveTemplateInstantiations.back()
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000446 != SemaRef.LastTemplateInstantiationErrorContext) {
447 SemaRef.PrintInstantiationStack();
Mike Stump1eb44332009-09-09 15:08:12 +0000448 SemaRef.LastTemplateInstantiationErrorContext
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000449 = SemaRef.ActiveTemplateInstantiations.back();
450 }
451}
Douglas Gregor2e222532009-07-02 17:08:52 +0000452
Douglas Gregoreab5d1e2010-03-25 22:17:48 +0000453Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) {
454 if (isSFINAEContext()) {
455 switch (Diagnostic::getDiagnosticSFINAEResponse(DiagID)) {
456 case Diagnostic::SFINAE_Report:
457 // Fall through; we'll report the diagnostic below.
458 break;
459
460 case Diagnostic::SFINAE_SubstitutionFailure:
461 // Count this failure so that we know that template argument deduction
462 // has failed.
463 ++NumSFINAEErrors;
464 // Fall through
465
466 case Diagnostic::SFINAE_Suppress:
467 // Suppress this diagnostic.
468 Diags.setLastDiagnosticIgnored();
469 return SemaDiagnosticBuilder(*this);
470 }
471 }
472
473 DiagnosticBuilder DB = Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
474 return SemaDiagnosticBuilder(DB, *this, DiagID);
475}
476
Anders Carlsson91a0cc92009-08-26 22:33:56 +0000477Sema::SemaDiagnosticBuilder
478Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
479 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
480 PD.Emit(Builder);
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Anders Carlsson91a0cc92009-08-26 22:33:56 +0000482 return Builder;
483}
484
Douglas Gregor23c94db2010-07-02 17:43:08 +0000485/// \brief Determines the active Scope associated with the given declaration
486/// context.
487///
488/// This routine maps a declaration context to the active Scope object that
489/// represents that declaration context in the parser. It is typically used
490/// from "scope-less" code (e.g., template instantiation, lazy creation of
491/// declarations) that injects a name for name-lookup purposes and, therefore,
492/// must update the Scope.
493///
494/// \returns The scope corresponding to the given declaraion context, or NULL
495/// if no such scope is open.
496Scope *Sema::getScopeForContext(DeclContext *Ctx) {
497
498 if (!Ctx)
499 return 0;
500
501 Ctx = Ctx->getPrimaryContext();
502 for (Scope *S = getCurScope(); S; S = S->getParent()) {
Sebastian Redlcddc69f2010-07-08 23:07:34 +0000503 // Ignore scopes that cannot have declarations. This is important for
504 // out-of-line definitions of static class members.
505 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
506 if (DeclContext *Entity = static_cast<DeclContext *> (S->getEntity()))
507 if (Ctx == Entity->getPrimaryContext())
508 return S;
Douglas Gregor23c94db2010-07-02 17:43:08 +0000509 }
510
511 return 0;
512}
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000513
514/// \brief Enter a new function scope
515void Sema::PushFunctionScope() {
John McCall781472f2010-08-25 08:40:02 +0000516 if (FunctionScopes.size() == 1) {
517 // Use the "top" function scope rather than having to allocate
518 // memory for a new scope.
519 FunctionScopes.back()->Clear(getDiagnostics().getNumErrors());
520 FunctionScopes.push_back(FunctionScopes.back());
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000521 return;
522 }
523
524 FunctionScopes.push_back(
525 new FunctionScopeInfo(getDiagnostics().getNumErrors()));
526}
527
528void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
529 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics().getNumErrors(),
530 BlockScope, Block));
531}
532
533void Sema::PopFunctionOrBlockScope() {
John McCall781472f2010-08-25 08:40:02 +0000534 FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
535 assert(!FunctionScopes.empty() && "mismatched push/pop!");
536 if (FunctionScopes.back() != Scope)
537 delete Scope;
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000538}
539
540/// \brief Determine whether any errors occurred within this function/method/
541/// block.
542bool Sema::hasAnyErrorsInThisFunction() const {
John McCall781472f2010-08-25 08:40:02 +0000543 return getCurFunction()->NumErrorsAtStartOfFunction
544 != getDiagnostics().getNumErrors();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000545}
546
547BlockScopeInfo *Sema::getCurBlock() {
548 if (FunctionScopes.empty())
549 return 0;
550
551 return dyn_cast<BlockScopeInfo>(FunctionScopes.back());
552}
John McCall76bd1f32010-06-01 09:23:16 +0000553
554// Pin this vtable to this file.
555ExternalSemaSource::~ExternalSemaSource() {}
John McCallf312b1e2010-08-26 23:41:50 +0000556
Sebastian Redl8c845712010-09-28 20:23:00 +0000557std::pair<ObjCMethodList, ObjCMethodList>
558ExternalSemaSource::ReadMethodPool(Selector Sel) {
559 return std::pair<ObjCMethodList, ObjCMethodList>();
560}
561
John McCallf312b1e2010-08-26 23:41:50 +0000562void PrettyDeclStackTraceEntry::print(llvm::raw_ostream &OS) const {
563 SourceLocation Loc = this->Loc;
564 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
565 if (Loc.isValid()) {
566 Loc.print(OS, S.getSourceManager());
567 OS << ": ";
568 }
569 OS << Message;
570
571 if (TheDecl && isa<NamedDecl>(TheDecl)) {
572 std::string Name = cast<NamedDecl>(TheDecl)->getNameAsString();
573 if (!Name.empty())
574 OS << " '" << Name << '\'';
575 }
576
577 OS << '\n';
578}