blob: a1ad78418f4da4202add2bbbcd4bf371f992c3c6 [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"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "clang/Lex/Preprocessor.h"
Anders Carlsson91a0cc92009-08-26 22:33:56 +000035#include "clang/Basic/PartialDiagnostic.h"
Chris Lattner4d150c82009-04-30 06:18:40 +000036#include "clang/Basic/TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000037using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000038using namespace sema;
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000039
40FunctionScopeInfo::~FunctionScopeInfo() { }
41
Argyrios Kyrtzidis8fc32d22010-11-19 00:19:15 +000042void FunctionScopeInfo::Clear() {
John McCallb60a77e2010-08-01 00:26:45 +000043 HasBranchProtectedScope = false;
44 HasBranchIntoScope = false;
45 HasIndirectGoto = false;
46
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000047 LabelMap.clear();
48 SwitchStack.clear();
Douglas Gregor5077c382010-05-15 06:01:05 +000049 Returns.clear();
Argyrios Kyrtzidis8fc32d22010-11-19 00:19:15 +000050 ErrorTrap.reset();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000051}
52
53BlockScopeInfo::~BlockScopeInfo() { }
54
Douglas Gregorc1a3e5e2010-08-25 18:07:12 +000055void Sema::ActOnTranslationUnitScope(Scope *S) {
Steve Naroffb216c882007-10-09 22:01:59 +000056 TUScope = S;
Douglas Gregor44b43212008-12-11 16:49:14 +000057 PushDeclContext(S, Context.getTranslationUnitDecl());
Mike Stump1eb44332009-09-09 15:08:12 +000058
John McCallc7e04da2010-05-28 18:45:08 +000059 VAListTagName = PP.getIdentifierInfo("__va_list_tag");
60
Sebastian Redlc43b54c2010-08-18 23:56:43 +000061 if (!Context.isInt128Installed() && // May be set by ASTReader.
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +000062 PP.getTargetInfo().getPointerWidth(0) >= 64) {
John McCalla93c9342009-12-07 02:54:59 +000063 TypeSourceInfo *TInfo;
John McCallba6a9bd2009-10-24 08:00:42 +000064
Chris Lattner4d150c82009-04-30 06:18:40 +000065 // Install [u]int128_t for 64-bit targets.
John McCalla93c9342009-12-07 02:54:59 +000066 TInfo = Context.getTrivialTypeSourceInfo(Context.Int128Ty);
Chris Lattner4d150c82009-04-30 06:18:40 +000067 PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
68 SourceLocation(),
69 &Context.Idents.get("__int128_t"),
John McCalla93c9342009-12-07 02:54:59 +000070 TInfo), TUScope);
John McCallba6a9bd2009-10-24 08:00:42 +000071
John McCalla93c9342009-12-07 02:54:59 +000072 TInfo = Context.getTrivialTypeSourceInfo(Context.UnsignedInt128Ty);
Chris Lattner4d150c82009-04-30 06:18:40 +000073 PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
74 SourceLocation(),
75 &Context.Idents.get("__uint128_t"),
John McCalla93c9342009-12-07 02:54:59 +000076 TInfo), TUScope);
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +000077 Context.setInt128Installed();
Chris Lattner4d150c82009-04-30 06:18:40 +000078 }
Mike Stump1eb44332009-09-09 15:08:12 +000079
80
Chris Lattner2ae34ed2008-02-06 00:46:58 +000081 if (!PP.getLangOptions().ObjC1) return;
Mike Stump1eb44332009-09-09 15:08:12 +000082
Sebastian Redlc43b54c2010-08-18 23:56:43 +000083 // Built-in ObjC types may already be set by ASTReader (hence isNull checks).
Douglas Gregor319ac892009-04-23 22:29:11 +000084 if (Context.getObjCSelType().isNull()) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +000085 // Create the built-in typedef for 'SEL'.
Fariborz Jahanian04765ac2009-11-23 18:04:25 +000086 QualType SelT = Context.getPointerType(Context.ObjCBuiltinSelTy);
John McCalla93c9342009-12-07 02:54:59 +000087 TypeSourceInfo *SelInfo = Context.getTrivialTypeSourceInfo(SelT);
John McCallba6a9bd2009-10-24 08:00:42 +000088 TypedefDecl *SelTypedef
89 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
90 &Context.Idents.get("SEL"), SelInfo);
Douglas Gregor319ac892009-04-23 22:29:11 +000091 PushOnScopeChains(SelTypedef, TUScope);
92 Context.setObjCSelType(Context.getTypeDeclType(SelTypedef));
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +000093 Context.ObjCSelRedefinitionType = Context.getObjCSelType();
Douglas Gregor319ac892009-04-23 22:29:11 +000094 }
Chris Lattner6ee1f9c2008-06-21 20:20:39 +000095
Chris Lattner6ee1f9c2008-06-21 20:20:39 +000096 // Synthesize "@class Protocol;
Douglas Gregor319ac892009-04-23 22:29:11 +000097 if (Context.getObjCProtoType().isNull()) {
98 ObjCInterfaceDecl *ProtocolDecl =
99 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000100 &Context.Idents.get("Protocol"),
Douglas Gregordeacbdc2010-08-11 12:19:30 +0000101 SourceLocation(), true);
Douglas Gregor319ac892009-04-23 22:29:11 +0000102 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
Fariborz Jahanian10324db2009-11-18 23:15:37 +0000103 PushOnScopeChains(ProtocolDecl, TUScope, false);
Douglas Gregor319ac892009-04-23 22:29:11 +0000104 }
Steve Naroffde2e22d2009-07-15 18:40:39 +0000105 // Create the built-in typedef for 'id'.
Douglas Gregor319ac892009-04-23 22:29:11 +0000106 if (Context.getObjCIdType().isNull()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000107 QualType T = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 0, 0);
108 T = Context.getObjCObjectPointerType(T);
109 TypeSourceInfo *IdInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +0000110 TypedefDecl *IdTypedef
111 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
112 &Context.Idents.get("id"), IdInfo);
Douglas Gregor319ac892009-04-23 22:29:11 +0000113 PushOnScopeChains(IdTypedef, TUScope);
114 Context.setObjCIdType(Context.getTypeDeclType(IdTypedef));
David Chisnall0f436562009-08-17 16:35:33 +0000115 Context.ObjCIdRedefinitionType = Context.getObjCIdType();
Douglas Gregor319ac892009-04-23 22:29:11 +0000116 }
Steve Naroffde2e22d2009-07-15 18:40:39 +0000117 // Create the built-in typedef for 'Class'.
Steve Naroff14108da2009-07-10 23:34:53 +0000118 if (Context.getObjCClassType().isNull()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000119 QualType T = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 0, 0);
120 T = Context.getObjCObjectPointerType(T);
121 TypeSourceInfo *ClassInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +0000122 TypedefDecl *ClassTypedef
123 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
124 &Context.Idents.get("Class"), ClassInfo);
Steve Naroff14108da2009-07-10 23:34:53 +0000125 PushOnScopeChains(ClassTypedef, TUScope);
126 Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef));
David Chisnall0f436562009-08-17 16:35:33 +0000127 Context.ObjCClassRedefinitionType = Context.getObjCClassType();
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000128 }
Steve Naroff3b950172007-10-10 21:53:07 +0000129}
130
Douglas Gregorf807fe02009-04-14 16:27:31 +0000131Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
Daniel Dunbar3a2838d2009-11-13 08:58:20 +0000132 bool CompleteTranslationUnit,
133 CodeCompleteConsumer *CodeCompleter)
Peter Collingbourne321b8172011-02-14 01:42:35 +0000134 : TheTargetAttributesSema(0), FPFeatures(pp.getLangOptions()),
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000135 LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
Mike Stump1eb44332009-09-09 15:08:12 +0000136 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
Daniel Dunbar3a2838d2009-11-13 08:58:20 +0000137 ExternalSource(0), CodeCompleter(CodeCompleter), CurContext(0),
John McCall781472f2010-08-25 08:40:02 +0000138 PackContext(0), VisContext(0), ParsingDeclDepth(0),
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000139 IdResolver(pp.getLangOptions()), CXXTypeInfoDecl(0), MSVCGuidDecl(0),
Bill Wendlingb7566d82010-09-08 21:30:16 +0000140 GlobalNewDeleteDeclared(false),
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000141 CompleteTranslationUnit(CompleteTranslationUnit),
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000142 NumSFINAEErrors(0), SuppressAccessChecking(false),
143 AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000144 NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
145 CurrentInstantiationScope(0), TyposCorrected(0),
Bill Wendlingb7566d82010-09-08 21:30:16 +0000146 AnalysisWarnings(*this)
Douglas Gregorf35f8282009-11-11 21:54:23 +0000147{
Steve Naroff3b950172007-10-10 21:53:07 +0000148 TUScope = 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000149 if (getLangOptions().CPlusPlus)
150 FieldCollector.reset(new CXXFieldCollector());
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Chris Lattner22caddc2008-11-23 09:13:29 +0000152 // Tell diagnostics how to render things from the AST library.
Douglas Gregor79a9a342010-02-09 22:26:47 +0000153 PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
154 &Context);
Douglas Gregor2afce722009-11-26 00:44:06 +0000155
156 ExprEvalContexts.push_back(
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000157 ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0));
John McCall781472f2010-08-25 08:40:02 +0000158
Argyrios Kyrtzidis8fc32d22010-11-19 00:19:15 +0000159 FunctionScopes.push_back(new FunctionScopeInfo(Diags));
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000160}
161
162void Sema::Initialize() {
163 // Tell the AST consumer about this Sema object.
164 Consumer.Initialize(Context);
165
166 // FIXME: Isn't this redundant with the initialization above?
167 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
168 SC->InitializeSema(*this);
169
170 // Tell the external Sema source about this Sema object.
171 if (ExternalSemaSource *ExternalSema
172 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
173 ExternalSema->InitializeSema(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000174}
175
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000176Sema::~Sema() {
177 if (PackContext) FreePackedContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +0000178 if (VisContext) FreeVisContext();
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000179 delete TheTargetAttributesSema;
John McCall781472f2010-08-25 08:40:02 +0000180
181 // Kill all the active scopes.
182 for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
183 delete FunctionScopes[I];
184 if (FunctionScopes.size() == 1)
185 delete FunctionScopes[0];
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000186
187 // Tell the SemaConsumer to forget about us; we're going out of scope.
188 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
189 SC->ForgetSema();
190
191 // Detach from the external Sema source.
192 if (ExternalSemaSource *ExternalSema
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000193 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000194 ExternalSema->ForgetSema();
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000195}
196
Mike Stump1eb44332009-09-09 15:08:12 +0000197/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Chris Lattner1e0a3902008-01-16 19:17:22 +0000198/// If there is already an implicit cast, merge into the existing one.
Sebastian Redl906082e2010-07-20 04:20:21 +0000199/// The result is of the given category.
Mike Stump1eb44332009-09-09 15:08:12 +0000200void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +0000201 CastKind Kind, ExprValueKind VK,
John McCallf871d0c2010-08-07 06:22:56 +0000202 const CXXCastPath *BasePath) {
Mon P Wang3a2c7442008-09-04 08:38:01 +0000203 QualType ExprTy = Context.getCanonicalType(Expr->getType());
204 QualType TypeTy = Context.getCanonicalType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000205
Mon P Wang3a2c7442008-09-04 08:38:01 +0000206 if (ExprTy == TypeTy)
207 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000208
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000209 // If this is a derived-to-base cast to a through a virtual base, we
210 // need a vtable.
John McCall2de56d12010-08-25 11:45:40 +0000211 if (Kind == CK_DerivedToBase &&
John McCallf871d0c2010-08-07 06:22:56 +0000212 BasePathInvolvesVirtualBase(*BasePath)) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000213 QualType T = Expr->getType();
214 if (const PointerType *Pointer = T->getAs<PointerType>())
215 T = Pointer->getPointeeType();
216 if (const RecordType *RecordTy = T->getAs<RecordType>())
217 MarkVTableUsed(Expr->getLocStart(),
218 cast<CXXRecordDecl>(RecordTy->getDecl()));
219 }
220
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000221 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
John McCallf871d0c2010-08-07 06:22:56 +0000222 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
Anders Carlsson4c5fad32009-09-15 05:28:24 +0000223 ImpCast->setType(Ty);
John McCall5baba9d2010-08-25 10:28:54 +0000224 ImpCast->setValueKind(VK);
Anders Carlsson4c5fad32009-09-15 05:28:24 +0000225 return;
226 }
227 }
228
John McCall5baba9d2010-08-25 10:28:54 +0000229 Expr = ImplicitCastExpr::Create(Context, Ty, Kind, Expr, BasePath, VK);
Sebastian Redl906082e2010-07-20 04:20:21 +0000230}
231
John McCall5baba9d2010-08-25 10:28:54 +0000232ExprValueKind Sema::CastCategory(Expr *E) {
Sebastian Redl906082e2010-07-20 04:20:21 +0000233 Expr::Classification Classification = E->Classify(Context);
John McCall5baba9d2010-08-25 10:28:54 +0000234 return Classification.isRValue() ? VK_RValue :
235 (Classification.isLValue() ? VK_LValue : VK_XValue);
Chris Lattner1e0a3902008-01-16 19:17:22 +0000236}
237
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000238/// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
239static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
240 if (D->isUsed())
241 return true;
242
243 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
244 // UnusedFileScopedDecls stores the first declaration.
245 // The declaration may have become definition so check again.
246 const FunctionDecl *DeclToCheck;
247 if (FD->hasBody(DeclToCheck))
248 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
249
250 // Later redecls may add new information resulting in not having to warn,
251 // so check again.
252 DeclToCheck = FD->getMostRecentDeclaration();
253 if (DeclToCheck != FD)
254 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
255 }
256
257 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
258 // UnusedFileScopedDecls stores the first declaration.
259 // The declaration may have become definition so check again.
260 const VarDecl *DeclToCheck = VD->getDefinition();
261 if (DeclToCheck)
262 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
263
264 // Later redecls may add new information resulting in not having to warn,
265 // so check again.
266 DeclToCheck = VD->getMostRecentDeclaration();
267 if (DeclToCheck != VD)
268 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
269 }
270
271 return false;
272}
273
Chris Lattner9299f3f2008-08-23 03:19:52 +0000274/// ActOnEndOfTranslationUnit - This is called at the very end of the
275/// translation unit when EOF is reached and all but the top-level scope is
276/// popped.
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +0000277void Sema::ActOnEndOfTranslationUnit() {
278 // At PCH writing, implicit instantiations and VTable handling info are
279 // stored and performed when the PCH is included.
Nick Lewycky2a5f99e2010-11-25 00:35:20 +0000280 if (CompleteTranslationUnit) {
Chandler Carruthaee543a2010-12-12 21:36:11 +0000281 // If any dynamic classes have their key function defined within
282 // this translation unit, then those vtables are considered "used" and must
283 // be emitted.
284 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
Anders Carlssona5c6c2a2011-01-25 18:08:22 +0000285 assert(!DynamicClasses[I]->isDependentType() &&
286 "Should not see dependent types here!");
Chandler Carruthaee543a2010-12-12 21:36:11 +0000287 if (const CXXMethodDecl *KeyFunction
288 = Context.getKeyFunction(DynamicClasses[I])) {
289 const FunctionDecl *Definition = 0;
290 if (KeyFunction->hasBody(Definition))
291 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
292 }
293 }
294
Nick Lewycky2a5f99e2010-11-25 00:35:20 +0000295 // If DefinedUsedVTables ends up marking any virtual member functions it
296 // might lead to more pending template instantiations, which we then need
297 // to instantiate.
298 DefineUsedVTables();
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +0000299
Nick Lewycky2a5f99e2010-11-25 00:35:20 +0000300 // C++: Perform implicit template instantiations.
301 //
302 // FIXME: When we perform these implicit instantiations, we do not
303 // carefully keep track of the point of instantiation (C++ [temp.point]).
304 // This means that name lookup that occurs within the template
305 // instantiation will always happen at the end of the translation unit,
306 // so it will find some names that should not be found. Although this is
307 // common behavior for C++ compilers, it is technically wrong. In the
308 // future, we either need to be able to filter the results of name lookup
309 // or we need to perform template instantiations earlier.
310 PerformPendingInstantiations();
311 }
Anders Carlssond6a637f2009-12-07 08:24:59 +0000312
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000313 // Remove file scoped decls that turned out to be used.
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000314 UnusedFileScopedDecls.erase(std::remove_if(UnusedFileScopedDecls.begin(),
315 UnusedFileScopedDecls.end(),
316 std::bind1st(std::ptr_fun(ShouldRemoveFromUnused),
317 this)),
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000318 UnusedFileScopedDecls.end());
Douglas Gregor47268a32010-04-09 17:41:13 +0000319
Douglas Gregor87c08a52010-08-13 22:48:40 +0000320 if (!CompleteTranslationUnit) {
321 TUScope = 0;
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +0000322 return;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000323 }
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +0000324
Chris Lattner63d65f82009-09-08 18:19:27 +0000325 // Check for #pragma weak identifiers that were never declared
326 // FIXME: This will cause diagnostics to be emitted in a non-determinstic
327 // order! Iterating over a densemap like this is bad.
Ryan Flynne25ff832009-07-30 03:15:39 +0000328 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
Chris Lattner63d65f82009-09-08 18:19:27 +0000329 I = WeakUndeclaredIdentifiers.begin(),
330 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
331 if (I->second.getUsed()) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Chris Lattner63d65f82009-09-08 18:19:27 +0000333 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
334 << I->first;
Ryan Flynne25ff832009-07-30 03:15:39 +0000335 }
336
Douglas Gregor275a3692009-03-10 23:43:53 +0000337 // C99 6.9.2p2:
338 // A declaration of an identifier for an object that has file
339 // scope without an initializer, and without a storage-class
340 // specifier or with the storage-class specifier static,
341 // constitutes a tentative definition. If a translation unit
342 // contains one or more tentative definitions for an identifier,
343 // and the translation unit contains no external definition for
344 // that identifier, then the behavior is exactly as if the
345 // translation unit contains a file scope declaration of that
346 // identifier, with the composite type as of the end of the
347 // translation unit, with an initializer equal to 0.
Sebastian Redle9d12b62010-01-31 22:27:38 +0000348 llvm::SmallSet<VarDecl *, 32> Seen;
349 for (unsigned i = 0, e = TentativeDefinitions.size(); i != e; ++i) {
350 VarDecl *VD = TentativeDefinitions[i]->getActingDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +0000351
Sebastian Redle9d12b62010-01-31 22:27:38 +0000352 // If the tentative definition was completed, getActingDefinition() returns
353 // null. If we've already seen this variable before, insert()'s second
354 // return value is false.
355 if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000356 continue;
357
Mike Stump1eb44332009-09-09 15:08:12 +0000358 if (const IncompleteArrayType *ArrayT
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000359 = Context.getAsIncompleteArrayType(VD->getType())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000360 if (RequireCompleteType(VD->getLocation(),
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000361 ArrayT->getElementType(),
Chris Lattner63d65f82009-09-08 18:19:27 +0000362 diag::err_tentative_def_incomplete_type_arr)) {
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000363 VD->setInvalidDecl();
Chris Lattner63d65f82009-09-08 18:19:27 +0000364 continue;
Douglas Gregor275a3692009-03-10 23:43:53 +0000365 }
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Chris Lattner63d65f82009-09-08 18:19:27 +0000367 // Set the length of the array to 1 (C99 6.9.2p5).
368 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
369 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
John McCall46a617a2009-10-16 00:14:28 +0000370 QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
371 One, ArrayType::Normal, 0);
Chris Lattner63d65f82009-09-08 18:19:27 +0000372 VD->setType(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000373 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000374 diag::err_tentative_def_incomplete_type))
375 VD->setInvalidDecl();
376
377 // Notify the consumer that we've completed a tentative definition.
378 if (!VD->isInvalidDecl())
379 Consumer.CompleteTentativeDefinition(VD);
380
Douglas Gregor275a3692009-03-10 23:43:53 +0000381 }
Argyrios Kyrtzidis43f0a7c2011-01-31 07:04:37 +0000382
383 // If there were errors, disable 'unused' warnings since they will mostly be
384 // noise.
385 if (!Diags.hasErrorOccurred()) {
386 // Output warning for unused file scoped decls.
387 for (llvm::SmallVectorImpl<const DeclaratorDecl*>::iterator
388 I = UnusedFileScopedDecls.begin(),
389 E = UnusedFileScopedDecls.end(); I != E; ++I) {
390 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
391 const FunctionDecl *DiagD;
392 if (!FD->hasBody(DiagD))
393 DiagD = FD;
394 Diag(DiagD->getLocation(),
395 isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
396 : diag::warn_unused_function)
397 << DiagD->getDeclName();
398 } else {
399 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
400 if (!DiagD)
401 DiagD = cast<VarDecl>(*I);
402 Diag(DiagD->getLocation(), diag::warn_unused_variable)
403 << DiagD->getDeclName();
404 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000405 }
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000406 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000407
408 TUScope = 0;
Chris Lattner9299f3f2008-08-23 03:19:52 +0000409}
410
411
Reid Spencer5f016e22007-07-11 17:01:13 +0000412//===----------------------------------------------------------------------===//
413// Helper functions.
414//===----------------------------------------------------------------------===//
415
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000416DeclContext *Sema::getFunctionLevelDeclContext() {
John McCalldb0ee1d2009-12-19 10:53:49 +0000417 DeclContext *DC = CurContext;
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Douglas Gregord9008312010-05-22 16:25:05 +0000419 while (isa<BlockDecl>(DC) || isa<EnumDecl>(DC))
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000420 DC = DC->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000422 return DC;
423}
424
Chris Lattner371f2582008-12-04 23:50:19 +0000425/// getCurFunctionDecl - If inside of a function body, this returns a pointer
426/// to the function decl for the function being parsed. If we're currently
427/// in a 'block', this returns the containing context.
428FunctionDecl *Sema::getCurFunctionDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000429 DeclContext *DC = getFunctionLevelDeclContext();
Chris Lattner371f2582008-12-04 23:50:19 +0000430 return dyn_cast<FunctionDecl>(DC);
431}
432
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +0000433ObjCMethodDecl *Sema::getCurMethodDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000434 DeclContext *DC = getFunctionLevelDeclContext();
Steve Naroffd7612e12008-11-17 16:28:52 +0000435 return dyn_cast<ObjCMethodDecl>(DC);
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +0000436}
Chris Lattner371f2582008-12-04 23:50:19 +0000437
438NamedDecl *Sema::getCurFunctionOrMethodDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000439 DeclContext *DC = getFunctionLevelDeclContext();
Chris Lattner371f2582008-12-04 23:50:19 +0000440 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000441 return cast<NamedDecl>(DC);
Chris Lattner371f2582008-12-04 23:50:19 +0000442 return 0;
443}
444
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000445Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
Douglas Gregor9b623632010-10-12 23:32:35 +0000446 if (!isActive())
447 return;
448
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000449 if (llvm::Optional<TemplateDeductionInfo*> Info = SemaRef.isSFINAEContext()) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000450 switch (DiagnosticIDs::getDiagnosticSFINAEResponse(getDiagID())) {
451 case DiagnosticIDs::SFINAE_Report:
Douglas Gregor9b623632010-10-12 23:32:35 +0000452 // Fall through; we'll report the diagnostic below.
453 break;
454
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000455 case DiagnosticIDs::SFINAE_AccessControl:
456 // Unless access checking is specifically called out as a SFINAE
457 // error, report this diagnostic.
458 if (!SemaRef.AccessCheckingSFINAE)
459 break;
460
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000461 case DiagnosticIDs::SFINAE_SubstitutionFailure:
Douglas Gregor9b623632010-10-12 23:32:35 +0000462 // Count this failure so that we know that template argument deduction
463 // has failed.
464 ++SemaRef.NumSFINAEErrors;
465 SemaRef.Diags.setLastDiagnosticIgnored();
466 SemaRef.Diags.Clear();
467 Clear();
468 return;
469
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000470 case DiagnosticIDs::SFINAE_Suppress:
Douglas Gregor9b623632010-10-12 23:32:35 +0000471 // Make a copy of this suppressed diagnostic and store it with the
472 // template-deduction information;
Douglas Gregorb5350412010-10-13 17:22:14 +0000473 FlushCounts();
Douglas Gregor9b623632010-10-12 23:32:35 +0000474 DiagnosticInfo DiagInfo(&SemaRef.Diags);
Douglas Gregorb5350412010-10-13 17:22:14 +0000475
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000476 if (*Info)
477 (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
Douglas Gregor9b623632010-10-12 23:32:35 +0000478 PartialDiagnostic(DiagInfo,
479 SemaRef.Context.getDiagAllocator()));
480
481 // Suppress this diagnostic.
482 SemaRef.Diags.setLastDiagnosticIgnored();
483 SemaRef.Diags.Clear();
484 Clear();
485 return;
486 }
487 }
488
489 // Emit the diagnostic.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000490 if (!this->Emit())
491 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000493 // If this is not a note, and we're in a template instantiation
494 // that is different from the last template instantiation where
495 // we emitted an error, print a template instantiation
496 // backtrace.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000497 if (!DiagnosticIDs::isBuiltinNote(DiagID) &&
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000498 !SemaRef.ActiveTemplateInstantiations.empty() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000499 SemaRef.ActiveTemplateInstantiations.back()
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000500 != SemaRef.LastTemplateInstantiationErrorContext) {
501 SemaRef.PrintInstantiationStack();
Mike Stump1eb44332009-09-09 15:08:12 +0000502 SemaRef.LastTemplateInstantiationErrorContext
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000503 = SemaRef.ActiveTemplateInstantiations.back();
504 }
505}
Douglas Gregor2e222532009-07-02 17:08:52 +0000506
Douglas Gregoreab5d1e2010-03-25 22:17:48 +0000507Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000508 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
Douglas Gregoreab5d1e2010-03-25 22:17:48 +0000509 return SemaDiagnosticBuilder(DB, *this, DiagID);
510}
511
Anders Carlsson91a0cc92009-08-26 22:33:56 +0000512Sema::SemaDiagnosticBuilder
513Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
514 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
515 PD.Emit(Builder);
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Anders Carlsson91a0cc92009-08-26 22:33:56 +0000517 return Builder;
518}
519
Douglas Gregor23c94db2010-07-02 17:43:08 +0000520/// \brief Determines the active Scope associated with the given declaration
521/// context.
522///
523/// This routine maps a declaration context to the active Scope object that
524/// represents that declaration context in the parser. It is typically used
525/// from "scope-less" code (e.g., template instantiation, lazy creation of
526/// declarations) that injects a name for name-lookup purposes and, therefore,
527/// must update the Scope.
528///
529/// \returns The scope corresponding to the given declaraion context, or NULL
530/// if no such scope is open.
531Scope *Sema::getScopeForContext(DeclContext *Ctx) {
532
533 if (!Ctx)
534 return 0;
535
536 Ctx = Ctx->getPrimaryContext();
537 for (Scope *S = getCurScope(); S; S = S->getParent()) {
Sebastian Redlcddc69f2010-07-08 23:07:34 +0000538 // Ignore scopes that cannot have declarations. This is important for
539 // out-of-line definitions of static class members.
540 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
541 if (DeclContext *Entity = static_cast<DeclContext *> (S->getEntity()))
542 if (Ctx == Entity->getPrimaryContext())
543 return S;
Douglas Gregor23c94db2010-07-02 17:43:08 +0000544 }
545
546 return 0;
547}
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000548
549/// \brief Enter a new function scope
550void Sema::PushFunctionScope() {
John McCall781472f2010-08-25 08:40:02 +0000551 if (FunctionScopes.size() == 1) {
552 // Use the "top" function scope rather than having to allocate
553 // memory for a new scope.
Argyrios Kyrtzidis8fc32d22010-11-19 00:19:15 +0000554 FunctionScopes.back()->Clear();
John McCall781472f2010-08-25 08:40:02 +0000555 FunctionScopes.push_back(FunctionScopes.back());
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000556 return;
557 }
558
Argyrios Kyrtzidis8fc32d22010-11-19 00:19:15 +0000559 FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000560}
561
562void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
Argyrios Kyrtzidis8fc32d22010-11-19 00:19:15 +0000563 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000564 BlockScope, Block));
565}
566
567void Sema::PopFunctionOrBlockScope() {
John McCall781472f2010-08-25 08:40:02 +0000568 FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
569 assert(!FunctionScopes.empty() && "mismatched push/pop!");
570 if (FunctionScopes.back() != Scope)
571 delete Scope;
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000572}
573
574/// \brief Determine whether any errors occurred within this function/method/
575/// block.
576bool Sema::hasAnyErrorsInThisFunction() const {
Argyrios Kyrtzidis8fc32d22010-11-19 00:19:15 +0000577 return getCurFunction()->ErrorTrap.hasErrorOccurred();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000578}
579
580BlockScopeInfo *Sema::getCurBlock() {
581 if (FunctionScopes.empty())
582 return 0;
583
584 return dyn_cast<BlockScopeInfo>(FunctionScopes.back());
585}
John McCall76bd1f32010-06-01 09:23:16 +0000586
587// Pin this vtable to this file.
588ExternalSemaSource::~ExternalSemaSource() {}
John McCallf312b1e2010-08-26 23:41:50 +0000589
Sebastian Redl8c845712010-09-28 20:23:00 +0000590std::pair<ObjCMethodList, ObjCMethodList>
591ExternalSemaSource::ReadMethodPool(Selector Sel) {
592 return std::pair<ObjCMethodList, ObjCMethodList>();
593}
594
John McCallf312b1e2010-08-26 23:41:50 +0000595void PrettyDeclStackTraceEntry::print(llvm::raw_ostream &OS) const {
596 SourceLocation Loc = this->Loc;
597 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
598 if (Loc.isValid()) {
599 Loc.print(OS, S.getSourceManager());
600 OS << ": ";
601 }
602 OS << Message;
603
604 if (TheDecl && isa<NamedDecl>(TheDecl)) {
605 std::string Name = cast<NamedDecl>(TheDecl)->getNameAsString();
606 if (!Name.empty())
607 OS << " '" << Name << '\'';
608 }
609
610 OS << '\n';
611}