1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
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 type-related semantic analysis.
12 //===----------------------------------------------------------------------===//
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/Parse/DeclSpec.h"
19 #include "clang/Basic/LangOptions.h"
20 using namespace clang;
22 /// ConvertDeclSpecToType - Convert the specified declspec to the appropriate
23 /// type object. This returns null on error.
24 static QualType ConvertDeclSpecToType(const DeclSpec &DS, ASTContext &Ctx) {
25 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
29 switch (DS.getTypeSpecType()) {
30 default: return QualType(); // FIXME: Handle unimp cases!
31 case DeclSpec::TST_void: return Ctx.VoidTy;
32 case DeclSpec::TST_char:
33 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
35 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
36 Result = Ctx.SignedCharTy;
38 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
40 Result = Ctx.UnsignedCharTy;
43 case DeclSpec::TST_unspecified: // Unspecific typespec defaults to int.
44 case DeclSpec::TST_int: {
45 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
46 switch (DS.getTypeSpecWidth()) {
47 case DeclSpec::TSW_unspecified: Result = Ctx.IntTy; break;
48 case DeclSpec::TSW_short: Result = Ctx.ShortTy; break;
49 case DeclSpec::TSW_long: Result = Ctx.LongTy; break;
50 case DeclSpec::TSW_longlong: Result = Ctx.LongLongTy; break;
53 switch (DS.getTypeSpecWidth()) {
54 case DeclSpec::TSW_unspecified: Result = Ctx.UnsignedIntTy; break;
55 case DeclSpec::TSW_short: Result = Ctx.UnsignedShortTy; break;
56 case DeclSpec::TSW_long: Result = Ctx.UnsignedLongTy; break;
57 case DeclSpec::TSW_longlong: Result = Ctx.UnsignedLongLongTy; break;
62 case DeclSpec::TST_float: Result = Ctx.FloatTy; break;
63 case DeclSpec::TST_double:
64 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
65 Result = Ctx.LongDoubleTy;
67 Result = Ctx.DoubleTy;
69 case DeclSpec::TST_bool: Result = Ctx.BoolTy; break; // _Bool or bool
70 case DeclSpec::TST_decimal32: // _Decimal32
71 case DeclSpec::TST_decimal64: // _Decimal64
72 case DeclSpec::TST_decimal128: // _Decimal128
73 assert(0 && "FIXME: GNU decimal extensions not supported yet!");
74 case DeclSpec::TST_enum:
75 case DeclSpec::TST_union:
76 case DeclSpec::TST_struct: {
77 Decl *D = static_cast<Decl *>(DS.getTypeRep());
78 assert(D && "Didn't get a decl for a enum/union/struct?");
79 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
80 DS.getTypeSpecSign() == 0 &&
81 "Can't handle qualifiers on typedef names yet!");
82 // TypeQuals handled by caller.
83 Result = Ctx.getTagDeclType(cast<TagDecl>(D));
86 case DeclSpec::TST_typedef: {
87 Decl *D = static_cast<Decl *>(DS.getTypeRep());
88 assert(D && "Didn't get a decl for a typedef?");
89 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
90 DS.getTypeSpecSign() == 0 &&
91 "Can't handle qualifiers on typedef names yet!");
92 // FIXME: Adding a TST_objcInterface clause doesn't seem ideal, so
93 // we have this "hack" for now...
94 if (ObjCInterfaceDecl *ObjCIntDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
95 if (DS.getProtocolQualifiers() == 0) {
96 Result = Ctx.getObjCInterfaceType(ObjCIntDecl);
100 Action::DeclTy **PPDecl = &(*DS.getProtocolQualifiers())[0];
101 Result = Ctx.getObjCQualifiedInterfaceType(ObjCIntDecl,
102 reinterpret_cast<ObjCProtocolDecl**>(PPDecl),
103 DS.NumProtocolQualifiers());
106 else if (TypedefDecl *typeDecl = dyn_cast<TypedefDecl>(D)) {
107 if (Ctx.getObjCIdType() == Ctx.getTypedefType(typeDecl)
108 && DS.getProtocolQualifiers()) {
110 Action::DeclTy **PPDecl = &(*DS.getProtocolQualifiers())[0];
111 Result = Ctx.getObjCQualifiedIdType(typeDecl->getUnderlyingType(),
112 reinterpret_cast<ObjCProtocolDecl**>(PPDecl),
113 DS.NumProtocolQualifiers());
117 // TypeQuals handled by caller.
118 Result = Ctx.getTypedefType(cast<TypedefDecl>(D));
121 case DeclSpec::TST_typeofType:
122 Result = QualType::getFromOpaquePtr(DS.getTypeRep());
123 assert(!Result.isNull() && "Didn't get a type for typeof?");
124 // TypeQuals handled by caller.
125 Result = Ctx.getTypeOfType(Result);
127 case DeclSpec::TST_typeofExpr: {
128 Expr *E = static_cast<Expr *>(DS.getTypeRep());
129 assert(E && "Didn't get an expression for typeof?");
130 // TypeQuals handled by caller.
131 Result = Ctx.getTypeOfExpr(E);
136 // Handle complex types.
137 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex)
138 Result = Ctx.getComplexType(Result);
140 assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
141 "FIXME: imaginary types not supported yet!");
146 /// GetTypeForDeclarator - Convert the type for the specified declarator to Type
148 QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
149 // long long is a C99 feature.
150 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
151 D.getDeclSpec().getTypeSpecWidth() == DeclSpec::TSW_longlong)
152 Diag(D.getDeclSpec().getTypeSpecWidthLoc(), diag::ext_longlong);
154 QualType T = ConvertDeclSpecToType(D.getDeclSpec(), Context);
156 // Apply const/volatile/restrict qualifiers to T.
157 T = T.getQualifiedType(D.getDeclSpec().getTypeQualifiers());
159 // Walk the DeclTypeInfo, building the recursive type as we go. DeclTypeInfos
160 // are ordered from the identifier out, which is opposite of what we want :).
161 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
162 const DeclaratorChunk &DeclType = D.getTypeObject(e-i-1);
163 switch (DeclType.Kind) {
164 default: assert(0 && "Unknown decltype!");
165 case DeclaratorChunk::Pointer:
166 if (T->isReferenceType()) {
167 // C++ 8.3.2p4: There shall be no ... pointers to references ...
168 Diag(D.getIdentifierLoc(), diag::err_illegal_decl_pointer_to_reference,
169 D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
170 D.setInvalidType(true);
174 // Apply the pointer typequals to the pointer object.
175 T = Context.getPointerType(T).getQualifiedType(DeclType.Ptr.TypeQuals);
177 case DeclaratorChunk::Reference:
178 if (const ReferenceType *RT = T->getAsReferenceType()) {
179 // C++ 8.3.2p4: There shall be no references to references ...
180 Diag(D.getIdentifierLoc(),
181 diag::err_illegal_decl_reference_to_reference,
182 D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
183 D.setInvalidType(true);
184 T = RT->getReferenceeType();
187 T = Context.getReferenceType(T);
189 case DeclaratorChunk::Array: {
190 const DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
191 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
192 ArrayType::ArraySizeModifier ASM;
194 ASM = ArrayType::Star;
195 else if (ATI.hasStatic)
196 ASM = ArrayType::Static;
198 ASM = ArrayType::Normal;
200 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
201 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
202 if (T->isIncompleteType()) {
203 Diag(D.getIdentifierLoc(), diag::err_illegal_decl_array_incomplete_type,
206 D.setInvalidType(true);
207 } else if (T->isFunctionType()) {
208 Diag(D.getIdentifierLoc(), diag::err_illegal_decl_array_of_functions,
209 D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
210 T = Context.getPointerType(T);
211 D.setInvalidType(true);
212 } else if (const ReferenceType *RT = T->getAsReferenceType()) {
213 // C++ 8.3.2p4: There shall be no ... arrays of references ...
214 Diag(D.getIdentifierLoc(), diag::err_illegal_decl_array_of_references,
215 D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
216 T = RT->getReferenceeType();
217 D.setInvalidType(true);
218 } else if (const RecordType *EltTy = T->getAsRecordType()) {
219 // If the element type is a struct or union that contains a variadic
220 // array, reject it: C99 6.7.2.1p2.
221 if (EltTy->getDecl()->hasFlexibleArrayMember()) {
222 Diag(DeclType.Loc, diag::err_flexible_array_in_array,
225 D.setInvalidType(true);
228 // C99 6.7.5.2p1: The size expression shall have integer type.
229 if (ArraySize && !ArraySize->getType()->isIntegerType()) {
230 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int,
231 ArraySize->getType().getAsString(), ArraySize->getSourceRange());
232 D.setInvalidType(true);
234 llvm::APSInt ConstVal(32);
235 // If no expression was provided, we consider it a VLA.
237 T = Context.getIncompleteArrayType(T, ASM, ATI.TypeQuals);
238 } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context)) {
239 T = Context.getVariableArrayType(T, ArraySize, ASM, ATI.TypeQuals);
241 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
242 // have a value greater than zero.
243 if (ConstVal.isSigned()) {
244 if (ConstVal.isNegative()) {
245 Diag(ArraySize->getLocStart(),
246 diag::err_typecheck_negative_array_size,
247 ArraySize->getSourceRange());
248 D.setInvalidType(true);
249 } else if (ConstVal == 0) {
250 // GCC accepts zero sized static arrays.
251 Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size,
252 ArraySize->getSourceRange());
255 T = Context.getConstantArrayType(T, ConstVal, ASM, ATI.TypeQuals);
257 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
258 if (!getLangOptions().C99 &&
259 (ASM != ArrayType::Normal ||
260 (ArraySize && !ArraySize->isIntegerConstantExpr(Context))))
261 Diag(D.getIdentifierLoc(), diag::ext_vla);
264 case DeclaratorChunk::Function:
265 // If the function declarator has a prototype (i.e. it is not () and
266 // does not have a K&R-style identifier list), then the arguments are part
267 // of the type, otherwise the argument list is ().
268 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
270 // C99 6.7.5.3p1: The return type may not be a function or array type.
271 if (T->isArrayType() || T->isFunctionType()) {
272 Diag(DeclType.Loc, diag::err_func_returning_array_function,
275 D.setInvalidType(true);
278 if (!FTI.hasPrototype) {
279 // Simple void foo(), where the incoming T is the result type.
280 T = Context.getFunctionTypeNoProto(T);
282 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition.
283 if (FTI.NumArgs != 0)
284 Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
287 // Otherwise, we have a function with an argument list that is
288 // potentially variadic.
289 llvm::SmallVector<QualType, 16> ArgTys;
291 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
292 QualType ArgTy = QualType::getFromOpaquePtr(FTI.ArgInfo[i].TypeInfo);
293 assert(!ArgTy.isNull() && "Couldn't parse type?");
295 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
296 // This matches the conversion that is done in
297 // Sema::ActOnParamDeclarator(). Without this conversion, the
298 // argument type in the function prototype *will not* match the
299 // type in ParmVarDecl (which makes the code generator unhappy).
301 // FIXME: We still apparently need the conversion in
302 // Sema::ParseParamDeclarator(). This doesn't make any sense, since
303 // it should be driving off the type being created here.
305 // FIXME: If a source translation tool needs to see the original type,
306 // then we need to consider storing both types somewhere...
308 if (const ArrayType *AT = ArgTy->getAsArrayType()) {
309 // int x[restrict 4] -> int *restrict
310 ArgTy = Context.getPointerType(AT->getElementType());
311 ArgTy = ArgTy.getQualifiedType(AT->getIndexTypeQualifier());
312 } else if (ArgTy->isFunctionType())
313 ArgTy = Context.getPointerType(ArgTy);
314 // Look for 'void'. void is allowed only as a single argument to a
315 // function with no other parameters (C99 6.7.5.3p10). We record
316 // int(void) as a FunctionTypeProto with an empty argument list.
317 else if (ArgTy->isVoidType()) {
318 // If this is something like 'float(int, void)', reject it. 'void'
319 // is an incomplete type (C99 6.2.5p19) and function decls cannot
320 // have arguments of incomplete type.
321 if (FTI.NumArgs != 1 || FTI.isVariadic) {
322 Diag(DeclType.Loc, diag::err_void_only_param);
323 ArgTy = Context.IntTy;
324 FTI.ArgInfo[i].TypeInfo = ArgTy.getAsOpaquePtr();
325 } else if (FTI.ArgInfo[i].Ident) {
326 // Reject, but continue to parse 'int(void abc)'.
327 Diag(FTI.ArgInfo[i].IdentLoc,
328 diag::err_param_with_void_type);
329 ArgTy = Context.IntTy;
330 FTI.ArgInfo[i].TypeInfo = ArgTy.getAsOpaquePtr();
332 // Reject, but continue to parse 'float(const void)'.
333 if (ArgTy.getCVRQualifiers())
334 Diag(DeclType.Loc, diag::err_void_param_qualified);
336 // Do not add 'void' to the ArgTys list.
341 ArgTys.push_back(ArgTy);
343 T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
353 /// ObjCGetTypeForMethodDefinition - Builds the type for a method definition
355 QualType Sema::ObjCGetTypeForMethodDefinition(DeclTy *D) {
356 ObjCMethodDecl *MDecl = dyn_cast<ObjCMethodDecl>(static_cast<Decl *>(D));
357 QualType T = MDecl->getResultType();
358 llvm::SmallVector<QualType, 16> ArgTys;
360 // Add the first two invisible argument types for self and _cmd.
361 if (MDecl->isInstance()) {
362 QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface());
363 selfTy = Context.getPointerType(selfTy);
364 ArgTys.push_back(selfTy);
367 ArgTys.push_back(Context.getObjCIdType());
368 ArgTys.push_back(Context.getObjCSelType());
370 for (int i = 0; i < MDecl->getNumParams(); i++) {
371 ParmVarDecl *PDecl = MDecl->getParamDecl(i);
372 QualType ArgTy = PDecl->getType();
373 assert(!ArgTy.isNull() && "Couldn't parse type?");
374 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
375 // This matches the conversion that is done in
376 // Sema::ParseParamDeclarator().
377 if (const ArrayType *AT = ArgTy->getAsArrayType())
378 ArgTy = Context.getPointerType(AT->getElementType());
379 else if (ArgTy->isFunctionType())
380 ArgTy = Context.getPointerType(ArgTy);
381 ArgTys.push_back(ArgTy);
383 T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
384 MDecl->isVariadic());
388 Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
389 // C99 6.7.6: Type names have no identifier. This is already validated by
391 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
393 QualType T = GetTypeForDeclarator(D, S);
395 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
397 // In this context, we *do not* check D.getInvalidType(). If the declarator
398 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
399 // though it will not reflect the user specified type.
400 return T.getAsOpaquePtr();
403 // Called from Parser::ParseParenDeclarator().
404 Sema::TypeResult Sema::ActOnParamDeclaratorType(Scope *S, Declarator &D) {
405 // Note: parameters have identifiers, but we don't care about them here, we
406 // just want the type converted.
407 QualType T = GetTypeForDeclarator(D, S);
409 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
411 // In this context, we *do not* check D.getInvalidType(). If the declarator
412 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
413 // though it will not reflect the user specified type.
414 return T.getAsOpaquePtr();