1 //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the actions class which performs semantic analysis and
11 // builds an AST out of a parse stream.
13 //===----------------------------------------------------------------------===//
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/Basic/TargetInfo.h"
22 using namespace clang
;
24 /// ConvertQualTypeToStringFn - This function is used to pretty print the
25 /// specified QualType as a string in diagnostics.
26 static void ConvertArgToStringFn(Diagnostic::ArgumentKind Kind
, intptr_t Val
,
27 const char *Modifier
, unsigned ModLen
,
28 const char *Argument
, unsigned ArgLen
,
29 llvm::SmallVectorImpl
<char> &Output
,
31 ASTContext
&Context
= *static_cast<ASTContext
*>(Cookie
);
34 if (Kind
== Diagnostic::ak_qualtype
) {
35 assert(ModLen
== 0 && ArgLen
== 0 &&
36 "Invalid modifier for QualType argument");
38 QualType
Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val
)));
40 // FIXME: Playing with std::string is really slow.
41 S
= Ty
.getAsString(Context
.PrintingPolicy
);
43 // If this is a sugared type (like a typedef, typeof, etc), then unwrap one
44 // level of the sugar so that the type is more obvious to the user.
45 QualType DesugaredTy
= Ty
->getDesugaredType(true);
46 DesugaredTy
.setCVRQualifiers(DesugaredTy
.getCVRQualifiers() |
47 Ty
.getCVRQualifiers());
49 if (Ty
!= DesugaredTy
&&
50 // If the desugared type is a vector type, we don't want to expand it,
51 // it will turn into an attribute mess. People want their "vec4".
52 !isa
<VectorType
>(DesugaredTy
) &&
54 // Don't desugar magic Objective-C types.
55 Ty
.getUnqualifiedType() != Context
.getObjCIdType() &&
56 Ty
.getUnqualifiedType() != Context
.getObjCSelType() &&
57 Ty
.getUnqualifiedType() != Context
.getObjCProtoType() &&
58 Ty
.getUnqualifiedType() != Context
.getObjCClassType() &&
61 Ty
.getUnqualifiedType() != Context
.getBuiltinVaListType()) {
63 S
+= DesugaredTy
.getAsString(Context
.PrintingPolicy
);
65 Output
.append(S
.begin(), S
.end());
69 } else if (Kind
== Diagnostic::ak_declarationname
) {
71 DeclarationName N
= DeclarationName::getFromOpaqueInteger(Val
);
74 if (ModLen
== 9 && !memcmp(Modifier
, "objcclass", 9) && ArgLen
== 0)
76 else if (ModLen
== 12 && !memcmp(Modifier
, "objcinstance", 12) && ArgLen
==0)
79 assert(ModLen
== 0 && ArgLen
== 0 &&
80 "Invalid modifier for DeclarationName argument");
82 assert(Kind
== Diagnostic::ak_nameddecl
);
83 if (ModLen
== 1 && Modifier
[0] == 'q' && ArgLen
== 0)
84 S
= reinterpret_cast<NamedDecl
*>(Val
)->getQualifiedNameAsString();
86 assert(ModLen
== 0 && ArgLen
== 0 &&
87 "Invalid modifier for NamedDecl* argument");
88 S
= reinterpret_cast<NamedDecl
*>(Val
)->getNameAsString();
92 Output
.push_back('\'');
93 Output
.append(S
.begin(), S
.end());
94 Output
.push_back('\'');
98 static inline RecordDecl
*CreateStructDecl(ASTContext
&C
, const char *Name
) {
99 if (C
.getLangOptions().CPlusPlus
)
100 return CXXRecordDecl::Create(C
, TagDecl::TK_struct
,
101 C
.getTranslationUnitDecl(),
102 SourceLocation(), &C
.Idents
.get(Name
));
104 return RecordDecl::Create(C
, TagDecl::TK_struct
,
105 C
.getTranslationUnitDecl(),
106 SourceLocation(), &C
.Idents
.get(Name
));
109 void Sema::ActOnTranslationUnitScope(SourceLocation Loc
, Scope
*S
) {
111 PushDeclContext(S
, Context
.getTranslationUnitDecl());
113 if (PP
.getTargetInfo().getPointerWidth(0) >= 64) {
114 // Install [u]int128_t for 64-bit targets.
115 PushOnScopeChains(TypedefDecl::Create(Context
, CurContext
,
117 &Context
.Idents
.get("__int128_t"),
118 Context
.Int128Ty
), TUScope
);
119 PushOnScopeChains(TypedefDecl::Create(Context
, CurContext
,
121 &Context
.Idents
.get("__uint128_t"),
122 Context
.UnsignedInt128Ty
), TUScope
);
126 if (!PP
.getLangOptions().ObjC1
) return;
128 if (Context
.getObjCSelType().isNull()) {
129 // Synthesize "typedef struct objc_selector *SEL;"
130 RecordDecl
*SelTag
= CreateStructDecl(Context
, "objc_selector");
131 PushOnScopeChains(SelTag
, TUScope
);
133 QualType SelT
= Context
.getPointerType(Context
.getTagDeclType(SelTag
));
134 TypedefDecl
*SelTypedef
= TypedefDecl::Create(Context
, CurContext
,
136 &Context
.Idents
.get("SEL"),
138 PushOnScopeChains(SelTypedef
, TUScope
);
139 Context
.setObjCSelType(Context
.getTypeDeclType(SelTypedef
));
142 if (Context
.getObjCClassType().isNull()) {
143 RecordDecl
*ClassTag
= CreateStructDecl(Context
, "objc_class");
144 QualType ClassT
= Context
.getPointerType(Context
.getTagDeclType(ClassTag
));
145 TypedefDecl
*ClassTypedef
=
146 TypedefDecl::Create(Context
, CurContext
, SourceLocation(),
147 &Context
.Idents
.get("Class"), ClassT
);
148 PushOnScopeChains(ClassTag
, TUScope
);
149 PushOnScopeChains(ClassTypedef
, TUScope
);
150 Context
.setObjCClassType(Context
.getTypeDeclType(ClassTypedef
));
153 // Synthesize "@class Protocol;
154 if (Context
.getObjCProtoType().isNull()) {
155 ObjCInterfaceDecl
*ProtocolDecl
=
156 ObjCInterfaceDecl::Create(Context
, CurContext
, SourceLocation(),
157 &Context
.Idents
.get("Protocol"),
158 SourceLocation(), true);
159 Context
.setObjCProtoType(Context
.getObjCInterfaceType(ProtocolDecl
));
160 PushOnScopeChains(ProtocolDecl
, TUScope
);
163 // Synthesize "typedef struct objc_object { Class isa; } *id;"
164 if (Context
.getObjCIdType().isNull()) {
165 RecordDecl
*ObjectTag
= CreateStructDecl(Context
, "objc_object");
167 QualType ObjT
= Context
.getPointerType(Context
.getTagDeclType(ObjectTag
));
168 PushOnScopeChains(ObjectTag
, TUScope
);
169 TypedefDecl
*IdTypedef
= TypedefDecl::Create(Context
, CurContext
,
171 &Context
.Idents
.get("id"),
173 PushOnScopeChains(IdTypedef
, TUScope
);
174 Context
.setObjCIdType(Context
.getTypeDeclType(IdTypedef
));
178 Sema::Sema(Preprocessor
&pp
, ASTContext
&ctxt
, ASTConsumer
&consumer
,
179 bool CompleteTranslationUnit
)
180 : LangOpts(pp
.getLangOptions()), PP(pp
), Context(ctxt
), Consumer(consumer
),
181 Diags(PP
.getDiagnostics()), SourceMgr(PP
.getSourceManager()),
182 ExternalSource(0), CurContext(0), PreDeclaratorDC(0),
183 CurBlock(0), PackContext(0), IdResolver(pp
.getLangOptions()),
184 GlobalNewDeleteDeclared(false),
185 CompleteTranslationUnit(CompleteTranslationUnit
),
186 CurrentInstantiationScope(0) {
190 if (getLangOptions().CPlusPlus
)
191 FieldCollector
.reset(new CXXFieldCollector());
193 // Tell diagnostics how to render things from the AST library.
194 PP
.getDiagnostics().SetArgToStringFn(ConvertArgToStringFn
, &Context
);
197 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
198 /// If there is already an implicit cast, merge into the existing one.
199 /// If isLvalue, the result of the cast is an lvalue.
200 void Sema::ImpCastExprToType(Expr
*&Expr
, QualType Ty
, bool isLvalue
) {
201 QualType ExprTy
= Context
.getCanonicalType(Expr
->getType());
202 QualType TypeTy
= Context
.getCanonicalType(Ty
);
204 if (ExprTy
== TypeTy
)
207 if (Expr
->getType().getTypePtr()->isPointerType() &&
208 Ty
.getTypePtr()->isPointerType()) {
209 QualType ExprBaseType
=
210 cast
<PointerType
>(ExprTy
.getUnqualifiedType())->getPointeeType();
212 cast
<PointerType
>(TypeTy
.getUnqualifiedType())->getPointeeType();
213 if (ExprBaseType
.getAddressSpace() != BaseType
.getAddressSpace()) {
214 Diag(Expr
->getExprLoc(), diag::err_implicit_pointer_address_space_cast
)
215 << Expr
->getSourceRange();
219 if (ImplicitCastExpr
*ImpCast
= dyn_cast
<ImplicitCastExpr
>(Expr
)) {
220 ImpCast
->setType(Ty
);
221 ImpCast
->setLvalueCast(isLvalue
);
223 Expr
= new (Context
) ImplicitCastExpr(Ty
, Expr
, isLvalue
);
226 void Sema::DeleteExpr(ExprTy
*E
) {
227 if (E
) static_cast<Expr
*>(E
)->Destroy(Context
);
229 void Sema::DeleteStmt(StmtTy
*S
) {
230 if (S
) static_cast<Stmt
*>(S
)->Destroy(Context
);
233 /// ActOnEndOfTranslationUnit - This is called at the very end of the
234 /// translation unit when EOF is reached and all but the top-level scope is
236 void Sema::ActOnEndOfTranslationUnit() {
237 if (!CompleteTranslationUnit
)
241 // A declaration of an identifier for an object that has file
242 // scope without an initializer, and without a storage-class
243 // specifier or with the storage-class specifier static,
244 // constitutes a tentative definition. If a translation unit
245 // contains one or more tentative definitions for an identifier,
246 // and the translation unit contains no external definition for
247 // that identifier, then the behavior is exactly as if the
248 // translation unit contains a file scope declaration of that
249 // identifier, with the composite type as of the end of the
250 // translation unit, with an initializer equal to 0.
251 for (llvm::DenseMap
<DeclarationName
, VarDecl
*>::iterator
252 D
= TentativeDefinitions
.begin(),
253 DEnd
= TentativeDefinitions
.end();
255 VarDecl
*VD
= D
->second
;
257 if (VD
->isInvalidDecl() || !VD
->isTentativeDefinition(Context
))
260 if (const IncompleteArrayType
*ArrayT
261 = Context
.getAsIncompleteArrayType(VD
->getType())) {
262 if (RequireCompleteType(VD
->getLocation(),
263 ArrayT
->getElementType(),
264 diag::err_tentative_def_incomplete_type_arr
))
265 VD
->setInvalidDecl();
267 // Set the length of the array to 1 (C99 6.9.2p5).
268 Diag(VD
->getLocation(), diag::warn_tentative_incomplete_array
);
269 llvm::APInt
One(Context
.getTypeSize(Context
.getSizeType()),
272 = Context
.getConstantArrayType(ArrayT
->getElementType(),
273 One
, ArrayType::Normal
, 0);
276 } else if (RequireCompleteType(VD
->getLocation(), VD
->getType(),
277 diag::err_tentative_def_incomplete_type
))
278 VD
->setInvalidDecl();
280 // Notify the consumer that we've completed a tentative definition.
281 if (!VD
->isInvalidDecl())
282 Consumer
.CompleteTentativeDefinition(VD
);
288 //===----------------------------------------------------------------------===//
290 //===----------------------------------------------------------------------===//
292 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
293 /// to the function decl for the function being parsed. If we're currently
294 /// in a 'block', this returns the containing context.
295 FunctionDecl
*Sema::getCurFunctionDecl() {
296 DeclContext
*DC
= CurContext
;
297 while (isa
<BlockDecl
>(DC
))
298 DC
= DC
->getParent();
299 return dyn_cast
<FunctionDecl
>(DC
);
302 ObjCMethodDecl
*Sema::getCurMethodDecl() {
303 DeclContext
*DC
= CurContext
;
304 while (isa
<BlockDecl
>(DC
))
305 DC
= DC
->getParent();
306 return dyn_cast
<ObjCMethodDecl
>(DC
);
309 NamedDecl
*Sema::getCurFunctionOrMethodDecl() {
310 DeclContext
*DC
= CurContext
;
311 while (isa
<BlockDecl
>(DC
))
312 DC
= DC
->getParent();
313 if (isa
<ObjCMethodDecl
>(DC
) || isa
<FunctionDecl
>(DC
))
314 return cast
<NamedDecl
>(DC
);
318 Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
321 // If this is not a note, and we're in a template instantiation
322 // that is different from the last template instantiation where
323 // we emitted an error, print a template instantiation
325 if (!SemaRef
.Diags
.isBuiltinNote(DiagID
) &&
326 !SemaRef
.ActiveTemplateInstantiations
.empty() &&
327 SemaRef
.ActiveTemplateInstantiations
.back()
328 != SemaRef
.LastTemplateInstantiationErrorContext
) {
329 SemaRef
.PrintInstantiationStack();
330 SemaRef
.LastTemplateInstantiationErrorContext
331 = SemaRef
.ActiveTemplateInstantiations
.back();