blob: 244538147e53ddfd4325db9435c05d88a0c21a13 [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
15#include "Sema.h"
Anton Korobeynikov82d0a412010-01-10 12:58:08 +000016#include "TargetAttributesSema.h"
Ryan Flynne25ff832009-07-30 03:15:39 +000017#include "llvm/ADT/DenseMap.h"
Sebastian Redle9d12b62010-01-31 22:27:38 +000018#include "llvm/ADT/SmallSet.h"
John McCall680523a2009-11-07 03:30:10 +000019#include "llvm/ADT/APFloat.h"
John McCall76bd1f32010-06-01 09:23:16 +000020#include "clang/Sema/ExternalSemaSource.h"
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +000021#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/AST/ASTContext.h"
Douglas Gregor79a9a342010-02-09 22:26:47 +000023#include "clang/AST/ASTDiagnostic.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000025#include "clang/AST/Expr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include "clang/Lex/Preprocessor.h"
Anders Carlsson91a0cc92009-08-26 22:33:56 +000027#include "clang/Basic/PartialDiagnostic.h"
Chris Lattner4d150c82009-04-30 06:18:40 +000028#include "clang/Basic/TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000030
31FunctionScopeInfo::~FunctionScopeInfo() { }
32
33void FunctionScopeInfo::Clear(unsigned NumErrors) {
John McCallb60a77e2010-08-01 00:26:45 +000034 HasBranchProtectedScope = false;
35 HasBranchIntoScope = false;
36 HasIndirectGoto = false;
37
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000038 LabelMap.clear();
39 SwitchStack.clear();
Douglas Gregor5077c382010-05-15 06:01:05 +000040 Returns.clear();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000041 NumErrorsAtStartOfFunction = NumErrors;
42}
43
44BlockScopeInfo::~BlockScopeInfo() { }
45
Steve Naroffb216c882007-10-09 22:01:59 +000046void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) {
47 TUScope = S;
Douglas Gregor44b43212008-12-11 16:49:14 +000048 PushDeclContext(S, Context.getTranslationUnitDecl());
Mike Stump1eb44332009-09-09 15:08:12 +000049
John McCallc7e04da2010-05-28 18:45:08 +000050 VAListTagName = PP.getIdentifierInfo("__va_list_tag");
51
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +000052 if (!Context.isInt128Installed() && // May be set by PCHReader.
53 PP.getTargetInfo().getPointerWidth(0) >= 64) {
John McCalla93c9342009-12-07 02:54:59 +000054 TypeSourceInfo *TInfo;
John McCallba6a9bd2009-10-24 08:00:42 +000055
Chris Lattner4d150c82009-04-30 06:18:40 +000056 // Install [u]int128_t for 64-bit targets.
John McCalla93c9342009-12-07 02:54:59 +000057 TInfo = Context.getTrivialTypeSourceInfo(Context.Int128Ty);
Chris Lattner4d150c82009-04-30 06:18:40 +000058 PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
59 SourceLocation(),
60 &Context.Idents.get("__int128_t"),
John McCalla93c9342009-12-07 02:54:59 +000061 TInfo), TUScope);
John McCallba6a9bd2009-10-24 08:00:42 +000062
John McCalla93c9342009-12-07 02:54:59 +000063 TInfo = Context.getTrivialTypeSourceInfo(Context.UnsignedInt128Ty);
Chris Lattner4d150c82009-04-30 06:18:40 +000064 PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
65 SourceLocation(),
66 &Context.Idents.get("__uint128_t"),
John McCalla93c9342009-12-07 02:54:59 +000067 TInfo), TUScope);
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +000068 Context.setInt128Installed();
Chris Lattner4d150c82009-04-30 06:18:40 +000069 }
Mike Stump1eb44332009-09-09 15:08:12 +000070
71
Chris Lattner2ae34ed2008-02-06 00:46:58 +000072 if (!PP.getLangOptions().ObjC1) return;
Mike Stump1eb44332009-09-09 15:08:12 +000073
Steve Naroffcb83c532009-06-16 00:20:10 +000074 // Built-in ObjC types may already be set by PCHReader (hence isNull checks).
Douglas Gregor319ac892009-04-23 22:29:11 +000075 if (Context.getObjCSelType().isNull()) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +000076 // Create the built-in typedef for 'SEL'.
Fariborz Jahanian04765ac2009-11-23 18:04:25 +000077 QualType SelT = Context.getPointerType(Context.ObjCBuiltinSelTy);
John McCalla93c9342009-12-07 02:54:59 +000078 TypeSourceInfo *SelInfo = Context.getTrivialTypeSourceInfo(SelT);
John McCallba6a9bd2009-10-24 08:00:42 +000079 TypedefDecl *SelTypedef
80 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
81 &Context.Idents.get("SEL"), SelInfo);
Douglas Gregor319ac892009-04-23 22:29:11 +000082 PushOnScopeChains(SelTypedef, TUScope);
83 Context.setObjCSelType(Context.getTypeDeclType(SelTypedef));
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +000084 Context.ObjCSelRedefinitionType = Context.getObjCSelType();
Douglas Gregor319ac892009-04-23 22:29:11 +000085 }
Chris Lattner6ee1f9c2008-06-21 20:20:39 +000086
Chris Lattner6ee1f9c2008-06-21 20:20:39 +000087 // Synthesize "@class Protocol;
Douglas Gregor319ac892009-04-23 22:29:11 +000088 if (Context.getObjCProtoType().isNull()) {
89 ObjCInterfaceDecl *ProtocolDecl =
90 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000091 &Context.Idents.get("Protocol"),
Douglas Gregor319ac892009-04-23 22:29:11 +000092 SourceLocation(), true);
93 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
Fariborz Jahanian10324db2009-11-18 23:15:37 +000094 PushOnScopeChains(ProtocolDecl, TUScope, false);
Douglas Gregor319ac892009-04-23 22:29:11 +000095 }
Steve Naroffde2e22d2009-07-15 18:40:39 +000096 // Create the built-in typedef for 'id'.
Douglas Gregor319ac892009-04-23 22:29:11 +000097 if (Context.getObjCIdType().isNull()) {
John McCallc12c5bb2010-05-15 11:32:37 +000098 QualType T = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 0, 0);
99 T = Context.getObjCObjectPointerType(T);
100 TypeSourceInfo *IdInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +0000101 TypedefDecl *IdTypedef
102 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
103 &Context.Idents.get("id"), IdInfo);
Douglas Gregor319ac892009-04-23 22:29:11 +0000104 PushOnScopeChains(IdTypedef, TUScope);
105 Context.setObjCIdType(Context.getTypeDeclType(IdTypedef));
David Chisnall0f436562009-08-17 16:35:33 +0000106 Context.ObjCIdRedefinitionType = Context.getObjCIdType();
Douglas Gregor319ac892009-04-23 22:29:11 +0000107 }
Steve Naroffde2e22d2009-07-15 18:40:39 +0000108 // Create the built-in typedef for 'Class'.
Steve Naroff14108da2009-07-10 23:34:53 +0000109 if (Context.getObjCClassType().isNull()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000110 QualType T = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 0, 0);
111 T = Context.getObjCObjectPointerType(T);
112 TypeSourceInfo *ClassInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +0000113 TypedefDecl *ClassTypedef
114 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
115 &Context.Idents.get("Class"), ClassInfo);
Steve Naroff14108da2009-07-10 23:34:53 +0000116 PushOnScopeChains(ClassTypedef, TUScope);
117 Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef));
David Chisnall0f436562009-08-17 16:35:33 +0000118 Context.ObjCClassRedefinitionType = Context.getObjCClassType();
Steve Naroff14108da2009-07-10 23:34:53 +0000119 }
Steve Naroff3b950172007-10-10 21:53:07 +0000120}
121
Douglas Gregorf807fe02009-04-14 16:27:31 +0000122Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
Daniel Dunbar3a2838d2009-11-13 08:58:20 +0000123 bool CompleteTranslationUnit,
124 CodeCompleteConsumer *CodeCompleter)
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000125 : TheTargetAttributesSema(0),
126 LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
Mike Stump1eb44332009-09-09 15:08:12 +0000127 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
Daniel Dunbar3a2838d2009-11-13 08:58:20 +0000128 ExternalSource(0), CodeCompleter(CodeCompleter), CurContext(0),
Eli Friedmanaa8b0d12010-08-05 06:57:20 +0000129 PackContext(0), VisContext(0), TopFunctionScope(0), ParsingDeclDepth(0),
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +0000130 IdResolver(pp.getLangOptions()), GlobalNewDeleteDeclared(false),
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000131 CompleteTranslationUnit(CompleteTranslationUnit),
Chandler Carruth926c4b42010-06-28 08:39:25 +0000132 NumSFINAEErrors(0), SuppressAccessChecking(false),
133 NonInstantiationEntries(0), CurrentInstantiationScope(0), TyposCorrected(0),
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000134 AnalysisWarnings(*this)
Douglas Gregorf35f8282009-11-11 21:54:23 +0000135{
Steve Naroff3b950172007-10-10 21:53:07 +0000136 TUScope = 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000137 if (getLangOptions().CPlusPlus)
138 FieldCollector.reset(new CXXFieldCollector());
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Chris Lattner22caddc2008-11-23 09:13:29 +0000140 // Tell diagnostics how to render things from the AST library.
Douglas Gregor79a9a342010-02-09 22:26:47 +0000141 PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
142 &Context);
Douglas Gregor2afce722009-11-26 00:44:06 +0000143
144 ExprEvalContexts.push_back(
145 ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0));
Reid Spencer5f016e22007-07-11 17:01:13 +0000146}
147
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000148Sema::~Sema() {
149 if (PackContext) FreePackedContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +0000150 if (VisContext) FreeVisContext();
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000151 delete TheTargetAttributesSema;
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000152 while (!FunctionScopes.empty())
153 PopFunctionOrBlockScope();
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000154}
155
Mike Stump1eb44332009-09-09 15:08:12 +0000156/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Chris Lattner1e0a3902008-01-16 19:17:22 +0000157/// If there is already an implicit cast, merge into the existing one.
Sebastian Redl906082e2010-07-20 04:20:21 +0000158/// The result is of the given category.
Mike Stump1eb44332009-09-09 15:08:12 +0000159void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty,
Anders Carlsson88465d32010-04-23 22:18:37 +0000160 CastExpr::CastKind Kind,
Sebastian Redl906082e2010-07-20 04:20:21 +0000161 ImplicitCastExpr::ResultCategory Category,
162 CXXBaseSpecifierArray BasePath) {
Mon P Wang3a2c7442008-09-04 08:38:01 +0000163 QualType ExprTy = Context.getCanonicalType(Expr->getType());
164 QualType TypeTy = Context.getCanonicalType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000165
Mon P Wang3a2c7442008-09-04 08:38:01 +0000166 if (ExprTy == TypeTy)
167 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000168
John McCall680523a2009-11-07 03:30:10 +0000169 if (Expr->getType()->isPointerType() && Ty->isPointerType()) {
170 QualType ExprBaseType = cast<PointerType>(ExprTy)->getPointeeType();
171 QualType BaseType = cast<PointerType>(TypeTy)->getPointeeType();
Mon P Wang3a2c7442008-09-04 08:38:01 +0000172 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000173 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
174 << Expr->getSourceRange();
Mon P Wang3a2c7442008-09-04 08:38:01 +0000175 }
176 }
Mike Stump1eb44332009-09-09 15:08:12 +0000177
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000178 // If this is a derived-to-base cast to a through a virtual base, we
179 // need a vtable.
180 if (Kind == CastExpr::CK_DerivedToBase &&
181 BasePathInvolvesVirtualBase(BasePath)) {
182 QualType T = Expr->getType();
183 if (const PointerType *Pointer = T->getAs<PointerType>())
184 T = Pointer->getPointeeType();
185 if (const RecordType *RecordTy = T->getAs<RecordType>())
186 MarkVTableUsed(Expr->getLocStart(),
187 cast<CXXRecordDecl>(RecordTy->getDecl()));
188 }
189
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000190 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
Anders Carlssoncee22422010-04-24 19:22:20 +0000191 if (ImpCast->getCastKind() == Kind && BasePath.empty()) {
Anders Carlsson4c5fad32009-09-15 05:28:24 +0000192 ImpCast->setType(Ty);
Sebastian Redl906082e2010-07-20 04:20:21 +0000193 ImpCast->setCategory(Category);
Anders Carlsson4c5fad32009-09-15 05:28:24 +0000194 return;
195 }
196 }
197
Sebastian Redl906082e2010-07-20 04:20:21 +0000198 Expr = new (Context) ImplicitCastExpr(Ty, Kind, Expr, BasePath, Category);
199}
200
201ImplicitCastExpr::ResultCategory Sema::CastCategory(Expr *E) {
202 Expr::Classification Classification = E->Classify(Context);
203 return Classification.isRValue() ?
204 ImplicitCastExpr::RValue :
205 (Classification.isLValue() ?
206 ImplicitCastExpr::LValue :
207 ImplicitCastExpr::XValue);
Chris Lattner1e0a3902008-01-16 19:17:22 +0000208}
209
Chris Lattner394a3fd2007-08-31 04:53:24 +0000210void Sema::DeleteExpr(ExprTy *E) {
Chris Lattner394a3fd2007-08-31 04:53:24 +0000211}
212void Sema::DeleteStmt(StmtTy *S) {
Chris Lattner394a3fd2007-08-31 04:53:24 +0000213}
214
Chris Lattner9299f3f2008-08-23 03:19:52 +0000215/// ActOnEndOfTranslationUnit - This is called at the very end of the
216/// translation unit when EOF is reached and all but the top-level scope is
217/// popped.
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +0000218void Sema::ActOnEndOfTranslationUnit() {
219 // At PCH writing, implicit instantiations and VTable handling info are
220 // stored and performed when the PCH is included.
221 if (CompleteTranslationUnit)
222 while (1) {
223 // C++: Perform implicit template instantiations.
224 //
225 // FIXME: When we perform these implicit instantiations, we do not
226 // carefully keep track of the point of instantiation (C++ [temp.point]).
227 // This means that name lookup that occurs within the template
228 // instantiation will always happen at the end of the translation unit,
229 // so it will find some names that should not be found. Although this is
230 // common behavior for C++ compilers, it is technically wrong. In the
231 // future, we either need to be able to filter the results of name lookup
232 // or we need to perform template instantiations earlier.
233 PerformPendingImplicitInstantiations();
234
235 /// If DefinedUsedVTables ends up marking any virtual member
236 /// functions it might lead to more pending template
237 /// instantiations, which is why we need to loop here.
238 if (!DefineUsedVTables())
239 break;
240 }
Anders Carlssond6a637f2009-12-07 08:24:59 +0000241
Douglas Gregor47268a32010-04-09 17:41:13 +0000242 // Remove functions that turned out to be used.
243 UnusedStaticFuncs.erase(std::remove_if(UnusedStaticFuncs.begin(),
244 UnusedStaticFuncs.end(),
Douglas Gregorc070cc62010-06-17 23:14:26 +0000245 std::bind2nd(std::mem_fun(&FunctionDecl::isUsed),
246 true)),
Douglas Gregor47268a32010-04-09 17:41:13 +0000247 UnusedStaticFuncs.end());
248
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +0000249 if (!CompleteTranslationUnit)
250 return;
251
Chris Lattner63d65f82009-09-08 18:19:27 +0000252 // Check for #pragma weak identifiers that were never declared
253 // FIXME: This will cause diagnostics to be emitted in a non-determinstic
254 // order! Iterating over a densemap like this is bad.
Ryan Flynne25ff832009-07-30 03:15:39 +0000255 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
Chris Lattner63d65f82009-09-08 18:19:27 +0000256 I = WeakUndeclaredIdentifiers.begin(),
257 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
258 if (I->second.getUsed()) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000259
Chris Lattner63d65f82009-09-08 18:19:27 +0000260 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
261 << I->first;
Ryan Flynne25ff832009-07-30 03:15:39 +0000262 }
263
Douglas Gregor275a3692009-03-10 23:43:53 +0000264 // C99 6.9.2p2:
265 // A declaration of an identifier for an object that has file
266 // scope without an initializer, and without a storage-class
267 // specifier or with the storage-class specifier static,
268 // constitutes a tentative definition. If a translation unit
269 // contains one or more tentative definitions for an identifier,
270 // and the translation unit contains no external definition for
271 // that identifier, then the behavior is exactly as if the
272 // translation unit contains a file scope declaration of that
273 // identifier, with the composite type as of the end of the
274 // translation unit, with an initializer equal to 0.
Sebastian Redle9d12b62010-01-31 22:27:38 +0000275 llvm::SmallSet<VarDecl *, 32> Seen;
276 for (unsigned i = 0, e = TentativeDefinitions.size(); i != e; ++i) {
277 VarDecl *VD = TentativeDefinitions[i]->getActingDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Sebastian Redle9d12b62010-01-31 22:27:38 +0000279 // If the tentative definition was completed, getActingDefinition() returns
280 // null. If we've already seen this variable before, insert()'s second
281 // return value is false.
282 if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000283 continue;
284
Mike Stump1eb44332009-09-09 15:08:12 +0000285 if (const IncompleteArrayType *ArrayT
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000286 = Context.getAsIncompleteArrayType(VD->getType())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000287 if (RequireCompleteType(VD->getLocation(),
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000288 ArrayT->getElementType(),
Chris Lattner63d65f82009-09-08 18:19:27 +0000289 diag::err_tentative_def_incomplete_type_arr)) {
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000290 VD->setInvalidDecl();
Chris Lattner63d65f82009-09-08 18:19:27 +0000291 continue;
Douglas Gregor275a3692009-03-10 23:43:53 +0000292 }
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Chris Lattner63d65f82009-09-08 18:19:27 +0000294 // Set the length of the array to 1 (C99 6.9.2p5).
295 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
296 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
John McCall46a617a2009-10-16 00:14:28 +0000297 QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
298 One, ArrayType::Normal, 0);
Chris Lattner63d65f82009-09-08 18:19:27 +0000299 VD->setType(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000300 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000301 diag::err_tentative_def_incomplete_type))
302 VD->setInvalidDecl();
303
304 // Notify the consumer that we've completed a tentative definition.
305 if (!VD->isInvalidDecl())
306 Consumer.CompleteTentativeDefinition(VD);
307
Douglas Gregor275a3692009-03-10 23:43:53 +0000308 }
Tanya Lattnere6bbc012010-02-12 00:07:30 +0000309
310 // Output warning for unused functions.
311 for (std::vector<FunctionDecl*>::iterator
312 F = UnusedStaticFuncs.begin(),
313 FEnd = UnusedStaticFuncs.end();
314 F != FEnd;
315 ++F)
316 Diag((*F)->getLocation(), diag::warn_unused_function) << (*F)->getDeclName();
317
Chris Lattner9299f3f2008-08-23 03:19:52 +0000318}
319
320
Reid Spencer5f016e22007-07-11 17:01:13 +0000321//===----------------------------------------------------------------------===//
322// Helper functions.
323//===----------------------------------------------------------------------===//
324
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000325DeclContext *Sema::getFunctionLevelDeclContext() {
John McCalldb0ee1d2009-12-19 10:53:49 +0000326 DeclContext *DC = CurContext;
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Douglas Gregord9008312010-05-22 16:25:05 +0000328 while (isa<BlockDecl>(DC) || isa<EnumDecl>(DC))
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000329 DC = DC->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000331 return DC;
332}
333
Chris Lattner371f2582008-12-04 23:50:19 +0000334/// getCurFunctionDecl - If inside of a function body, this returns a pointer
335/// to the function decl for the function being parsed. If we're currently
336/// in a 'block', this returns the containing context.
337FunctionDecl *Sema::getCurFunctionDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000338 DeclContext *DC = getFunctionLevelDeclContext();
Chris Lattner371f2582008-12-04 23:50:19 +0000339 return dyn_cast<FunctionDecl>(DC);
340}
341
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +0000342ObjCMethodDecl *Sema::getCurMethodDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000343 DeclContext *DC = getFunctionLevelDeclContext();
Steve Naroffd7612e12008-11-17 16:28:52 +0000344 return dyn_cast<ObjCMethodDecl>(DC);
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +0000345}
Chris Lattner371f2582008-12-04 23:50:19 +0000346
347NamedDecl *Sema::getCurFunctionOrMethodDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000348 DeclContext *DC = getFunctionLevelDeclContext();
Chris Lattner371f2582008-12-04 23:50:19 +0000349 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000350 return cast<NamedDecl>(DC);
Chris Lattner371f2582008-12-04 23:50:19 +0000351 return 0;
352}
353
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000354Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000355 if (!this->Emit())
356 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000358 // If this is not a note, and we're in a template instantiation
359 // that is different from the last template instantiation where
360 // we emitted an error, print a template instantiation
361 // backtrace.
362 if (!SemaRef.Diags.isBuiltinNote(DiagID) &&
363 !SemaRef.ActiveTemplateInstantiations.empty() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000364 SemaRef.ActiveTemplateInstantiations.back()
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000365 != SemaRef.LastTemplateInstantiationErrorContext) {
366 SemaRef.PrintInstantiationStack();
Mike Stump1eb44332009-09-09 15:08:12 +0000367 SemaRef.LastTemplateInstantiationErrorContext
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000368 = SemaRef.ActiveTemplateInstantiations.back();
369 }
370}
Douglas Gregor2e222532009-07-02 17:08:52 +0000371
Douglas Gregoreab5d1e2010-03-25 22:17:48 +0000372Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) {
373 if (isSFINAEContext()) {
374 switch (Diagnostic::getDiagnosticSFINAEResponse(DiagID)) {
375 case Diagnostic::SFINAE_Report:
376 // Fall through; we'll report the diagnostic below.
377 break;
378
379 case Diagnostic::SFINAE_SubstitutionFailure:
380 // Count this failure so that we know that template argument deduction
381 // has failed.
382 ++NumSFINAEErrors;
383 // Fall through
384
385 case Diagnostic::SFINAE_Suppress:
386 // Suppress this diagnostic.
387 Diags.setLastDiagnosticIgnored();
388 return SemaDiagnosticBuilder(*this);
389 }
390 }
391
392 DiagnosticBuilder DB = Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
393 return SemaDiagnosticBuilder(DB, *this, DiagID);
394}
395
Anders Carlsson91a0cc92009-08-26 22:33:56 +0000396Sema::SemaDiagnosticBuilder
397Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
398 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
399 PD.Emit(Builder);
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Anders Carlsson91a0cc92009-08-26 22:33:56 +0000401 return Builder;
402}
403
Douglas Gregor23c94db2010-07-02 17:43:08 +0000404/// \brief Determines the active Scope associated with the given declaration
405/// context.
406///
407/// This routine maps a declaration context to the active Scope object that
408/// represents that declaration context in the parser. It is typically used
409/// from "scope-less" code (e.g., template instantiation, lazy creation of
410/// declarations) that injects a name for name-lookup purposes and, therefore,
411/// must update the Scope.
412///
413/// \returns The scope corresponding to the given declaraion context, or NULL
414/// if no such scope is open.
415Scope *Sema::getScopeForContext(DeclContext *Ctx) {
416
417 if (!Ctx)
418 return 0;
419
420 Ctx = Ctx->getPrimaryContext();
421 for (Scope *S = getCurScope(); S; S = S->getParent()) {
Sebastian Redlcddc69f2010-07-08 23:07:34 +0000422 // Ignore scopes that cannot have declarations. This is important for
423 // out-of-line definitions of static class members.
424 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
425 if (DeclContext *Entity = static_cast<DeclContext *> (S->getEntity()))
426 if (Ctx == Entity->getPrimaryContext())
427 return S;
Douglas Gregor23c94db2010-07-02 17:43:08 +0000428 }
429
430 return 0;
431}
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000432
433/// \brief Enter a new function scope
434void Sema::PushFunctionScope() {
435 if (FunctionScopes.empty()) {
436 // Use the "top" function scope rather than having to allocate memory for
437 // a new scope.
438 TopFunctionScope.Clear(getDiagnostics().getNumErrors());
439 FunctionScopes.push_back(&TopFunctionScope);
440 return;
441 }
442
443 FunctionScopes.push_back(
444 new FunctionScopeInfo(getDiagnostics().getNumErrors()));
445}
446
447void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
448 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics().getNumErrors(),
449 BlockScope, Block));
450}
451
452void Sema::PopFunctionOrBlockScope() {
453 if (FunctionScopes.back() != &TopFunctionScope)
454 delete FunctionScopes.back();
455 else
456 TopFunctionScope.Clear(getDiagnostics().getNumErrors());
457
458 FunctionScopes.pop_back();
459}
460
461/// \brief Determine whether any errors occurred within this function/method/
462/// block.
463bool Sema::hasAnyErrorsInThisFunction() const {
464 unsigned NumErrors = TopFunctionScope.NumErrorsAtStartOfFunction;
465 if (!FunctionScopes.empty())
466 NumErrors = FunctionScopes.back()->NumErrorsAtStartOfFunction;
467 return NumErrors != getDiagnostics().getNumErrors();
468}
469
470BlockScopeInfo *Sema::getCurBlock() {
471 if (FunctionScopes.empty())
472 return 0;
473
474 return dyn_cast<BlockScopeInfo>(FunctionScopes.back());
475}
John McCall76bd1f32010-06-01 09:23:16 +0000476
477// Pin this vtable to this file.
478ExternalSemaSource::~ExternalSemaSource() {}