SemaType.cpp revision 9e5e4aaf8b8835b552819d68d29b6d94115d8a0b
1//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements type-related semantic analysis.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/Expr.h"
18#include "clang/Basic/Diagnostic.h"
19#include "clang/Parse/DeclSpec.h"
20using namespace clang;
21
22/// ConvertDeclSpecToType - Convert the specified declspec to the appropriate
23/// type object.  This returns null on error.
24QualType Sema::ConvertDeclSpecToType(const DeclSpec &DS) {
25  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
26  // checking.
27  QualType Result;
28
29  switch (DS.getTypeSpecType()) {
30  default: assert(0 && "Unknown TypeSpecType!");
31  case DeclSpec::TST_void:
32    Result = Context.VoidTy;
33    break;
34  case DeclSpec::TST_char:
35    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
36      Result = Context.CharTy;
37    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
38      Result = Context.SignedCharTy;
39    else {
40      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
41             "Unknown TSS value");
42      Result = Context.UnsignedCharTy;
43    }
44    break;
45  case DeclSpec::TST_wchar:
46    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
47      Result = Context.WCharTy;
48    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
49      Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
50        << DS.getSpecifierName(DS.getTypeSpecType());
51      Result = Context.getSignedWCharType();
52    } else {
53      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
54        "Unknown TSS value");
55      Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
56        << DS.getSpecifierName(DS.getTypeSpecType());
57      Result = Context.getUnsignedWCharType();
58    }
59    break;
60  case DeclSpec::TST_unspecified:
61    // "<proto1,proto2>" is an objc qualified ID with a missing id.
62    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
63      Result = Context.getObjCQualifiedIdType((ObjCProtocolDecl**)PQ,
64                                              DS.getNumProtocolQualifiers());
65      break;
66    }
67
68    // Unspecified typespec defaults to int in C90.  However, the C90 grammar
69    // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
70    // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
71    // Note that the one exception to this is function definitions, which are
72    // allowed to be completely missing a declspec.  This is handled in the
73    // parser already though by it pretending to have seen an 'int' in this
74    // case.
75    if (getLangOptions().ImplicitInt) {
76      if ((DS.getParsedSpecifiers() & (DeclSpec::PQ_StorageClassSpecifier |
77                                       DeclSpec::PQ_TypeSpecifier |
78                                       DeclSpec::PQ_TypeQualifier)) == 0)
79        Diag(DS.getSourceRange().getBegin(), diag::ext_missing_declspec);
80    } else {
81      // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
82      // "At least one type specifier shall be given in the declaration
83      // specifiers in each declaration, and in the specifier-qualifier list in
84      // each struct declaration and type name."
85      if (!DS.hasTypeSpecifier())
86        Diag(DS.getSourceRange().getBegin(), diag::ext_missing_type_specifier);
87    }
88
89    // FALL THROUGH.
90  case DeclSpec::TST_int: {
91    if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
92      switch (DS.getTypeSpecWidth()) {
93      case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
94      case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
95      case DeclSpec::TSW_long:        Result = Context.LongTy; break;
96      case DeclSpec::TSW_longlong:    Result = Context.LongLongTy; break;
97      }
98    } else {
99      switch (DS.getTypeSpecWidth()) {
100      case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
101      case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
102      case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
103      case DeclSpec::TSW_longlong:    Result =Context.UnsignedLongLongTy; break;
104      }
105    }
106    break;
107  }
108  case DeclSpec::TST_float: Result = Context.FloatTy; break;
109  case DeclSpec::TST_double:
110    if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
111      Result = Context.LongDoubleTy;
112    else
113      Result = Context.DoubleTy;
114    break;
115  case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
116  case DeclSpec::TST_decimal32:    // _Decimal32
117  case DeclSpec::TST_decimal64:    // _Decimal64
118  case DeclSpec::TST_decimal128:   // _Decimal128
119    assert(0 && "FIXME: GNU decimal extensions not supported yet!");
120  case DeclSpec::TST_class:
121  case DeclSpec::TST_enum:
122  case DeclSpec::TST_union:
123  case DeclSpec::TST_struct: {
124    Decl *D = static_cast<Decl *>(DS.getTypeRep());
125    assert(D && "Didn't get a decl for a class/enum/union/struct?");
126    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
127           DS.getTypeSpecSign() == 0 &&
128           "Can't handle qualifiers on typedef names yet!");
129    // TypeQuals handled by caller.
130    Result = Context.getTypeDeclType(cast<TypeDecl>(D));
131    break;
132  }
133  case DeclSpec::TST_typedef: {
134    Decl *D = static_cast<Decl *>(DS.getTypeRep());
135    assert(D && "Didn't get a decl for a typedef?");
136    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
137           DS.getTypeSpecSign() == 0 &&
138           "Can't handle qualifiers on typedef names yet!");
139    DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers();
140
141    // FIXME: Adding a TST_objcInterface clause doesn't seem ideal, so
142    // we have this "hack" for now...
143    if (ObjCInterfaceDecl *ObjCIntDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
144      if (PQ == 0) {
145        Result = Context.getObjCInterfaceType(ObjCIntDecl);
146        break;
147      }
148
149      Result = Context.getObjCQualifiedInterfaceType(ObjCIntDecl,
150                                                     (ObjCProtocolDecl**)PQ,
151                                                 DS.getNumProtocolQualifiers());
152      break;
153    } else if (TypedefDecl *typeDecl = dyn_cast<TypedefDecl>(D)) {
154      if (Context.getObjCIdType() == Context.getTypedefType(typeDecl) && PQ) {
155        // id<protocol-list>
156        Result = Context.getObjCQualifiedIdType((ObjCProtocolDecl**)PQ,
157                                                DS.getNumProtocolQualifiers());
158        break;
159      }
160    }
161    // TypeQuals handled by caller.
162    Result = Context.getTypeDeclType(dyn_cast<TypeDecl>(D));
163    break;
164  }
165  case DeclSpec::TST_typeofType:
166    Result = QualType::getFromOpaquePtr(DS.getTypeRep());
167    assert(!Result.isNull() && "Didn't get a type for typeof?");
168    // TypeQuals handled by caller.
169    Result = Context.getTypeOfType(Result);
170    break;
171  case DeclSpec::TST_typeofExpr: {
172    Expr *E = static_cast<Expr *>(DS.getTypeRep());
173    assert(E && "Didn't get an expression for typeof?");
174    // TypeQuals handled by caller.
175    Result = Context.getTypeOfExpr(E);
176    break;
177  }
178  }
179
180  // Handle complex types.
181  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex)
182    Result = Context.getComplexType(Result);
183
184  assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
185         "FIXME: imaginary types not supported yet!");
186
187  // See if there are any attributes on the declspec that apply to the type (as
188  // opposed to the decl).
189  if (const AttributeList *AL = DS.getAttributes())
190    ProcessTypeAttributeList(Result, AL);
191
192  // Apply const/volatile/restrict qualifiers to T.
193  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
194
195    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
196    // or incomplete types shall not be restrict-qualified."  C++ also allows
197    // restrict-qualified references.
198    if (TypeQuals & QualType::Restrict) {
199      if (const PointerLikeType *PT = Result->getAsPointerLikeType()) {
200        QualType EltTy = PT->getPointeeType();
201
202        // If we have a pointer or reference, the pointee must have an object or
203        // incomplete type.
204        if (!EltTy->isIncompleteOrObjectType()) {
205          Diag(DS.getRestrictSpecLoc(),
206               diag::err_typecheck_invalid_restrict_invalid_pointee)
207            << EltTy << DS.getSourceRange();
208          TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier.
209        }
210      } else {
211        Diag(DS.getRestrictSpecLoc(),
212             diag::err_typecheck_invalid_restrict_not_pointer)
213          << Result << DS.getSourceRange();
214        TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier.
215      }
216    }
217
218    // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
219    // of a function type includes any type qualifiers, the behavior is
220    // undefined."
221    if (Result->isFunctionType() && TypeQuals) {
222      // Get some location to point at, either the C or V location.
223      SourceLocation Loc;
224      if (TypeQuals & QualType::Const)
225        Loc = DS.getConstSpecLoc();
226      else {
227        assert((TypeQuals & QualType::Volatile) &&
228               "Has CV quals but not C or V?");
229        Loc = DS.getVolatileSpecLoc();
230      }
231      Diag(Loc, diag::warn_typecheck_function_qualifiers)
232        << Result << DS.getSourceRange();
233    }
234
235    // C++ [dcl.ref]p1:
236    //   Cv-qualified references are ill-formed except when the
237    //   cv-qualifiers are introduced through the use of a typedef
238    //   (7.1.3) or of a template type argument (14.3), in which
239    //   case the cv-qualifiers are ignored.
240    if (DS.getTypeSpecType() == DeclSpec::TST_typedef &&
241        TypeQuals && Result->isReferenceType()) {
242      TypeQuals &= ~QualType::Const;
243      TypeQuals &= ~QualType::Volatile;
244    }
245
246    Result = Result.getQualifiedType(TypeQuals);
247  }
248  return Result;
249}
250
251/// GetTypeForDeclarator - Convert the type for the specified declarator to Type
252/// instances. Skip the outermost Skip type objects.
253QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S, unsigned Skip) {
254  // long long is a C99 feature.
255  if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
256      D.getDeclSpec().getTypeSpecWidth() == DeclSpec::TSW_longlong)
257    Diag(D.getDeclSpec().getTypeSpecWidthLoc(), diag::ext_longlong);
258
259  QualType T = ConvertDeclSpecToType(D.getDeclSpec());
260
261  // Walk the DeclTypeInfo, building the recursive type as we go.  DeclTypeInfos
262  // are ordered from the identifier out, which is opposite of what we want :).
263  for (unsigned i = Skip, e = D.getNumTypeObjects(); i != e; ++i) {
264    DeclaratorChunk &DeclType = D.getTypeObject(e-i-1+Skip);
265    switch (DeclType.Kind) {
266    default: assert(0 && "Unknown decltype!");
267    case DeclaratorChunk::BlockPointer:
268      if (DeclType.Cls.TypeQuals)
269        Diag(D.getIdentifierLoc(), diag::err_qualified_block_pointer_type);
270      if (!T.getTypePtr()->isFunctionType())
271        Diag(D.getIdentifierLoc(), diag::err_nonfunction_block_type);
272      else
273        T = Context.getBlockPointerType(T);
274      break;
275    case DeclaratorChunk::Pointer:
276      if (T->isReferenceType()) {
277        // C++ 8.3.2p4: There shall be no ... pointers to references ...
278        Diag(DeclType.Loc, diag::err_illegal_decl_pointer_to_reference)
279         << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
280        D.setInvalidType(true);
281        T = Context.IntTy;
282      }
283
284      // Enforce C99 6.7.3p2: "Types other than pointer types derived from
285      // object or incomplete types shall not be restrict-qualified."
286      if ((DeclType.Ptr.TypeQuals & QualType::Restrict) &&
287          !T->isIncompleteOrObjectType()) {
288        Diag(DeclType.Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
289          << T;
290        DeclType.Ptr.TypeQuals &= ~QualType::Restrict;
291      }
292
293      // Apply the pointer typequals to the pointer object.
294      T = Context.getPointerType(T).getQualifiedType(DeclType.Ptr.TypeQuals);
295      break;
296    case DeclaratorChunk::Reference: {
297      // Whether we should suppress the creation of the reference.
298      bool SuppressReference = false;
299      if (T->isReferenceType()) {
300        // C++ [dcl.ref]p4: There shall be no references to references.
301        //
302        // According to C++ DR 106, references to references are only
303        // diagnosed when they are written directly (e.g., "int & &"),
304        // but not when they happen via a typedef:
305        //
306        //   typedef int& intref;
307        //   typedef intref& intref2;
308        //
309        // Parser::ParserDeclaratorInternal diagnoses the case where
310        // references are written directly; here, we handle the
311        // collapsing of references-to-references as described in C++
312        // DR 106 and amended by C++ DR 540.
313        SuppressReference = true;
314      }
315
316      // C++ [dcl.ref]p1:
317      //   A declarator that specifies the type “reference to cv void”
318      //   is ill-formed.
319      if (T->isVoidType()) {
320        Diag(DeclType.Loc, diag::err_reference_to_void);
321        D.setInvalidType(true);
322        T = Context.IntTy;
323      }
324
325      // Enforce C99 6.7.3p2: "Types other than pointer types derived from
326      // object or incomplete types shall not be restrict-qualified."
327      if (DeclType.Ref.HasRestrict &&
328          !T->isIncompleteOrObjectType()) {
329        Diag(DeclType.Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
330          << T;
331        DeclType.Ref.HasRestrict = false;
332      }
333
334      if (!SuppressReference)
335        T = Context.getReferenceType(T);
336
337      // Handle restrict on references.
338      if (DeclType.Ref.HasRestrict)
339        T.addRestrict();
340      break;
341    }
342    case DeclaratorChunk::Array: {
343      DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
344      Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
345      ArrayType::ArraySizeModifier ASM;
346      if (ATI.isStar)
347        ASM = ArrayType::Star;
348      else if (ATI.hasStatic)
349        ASM = ArrayType::Static;
350      else
351        ASM = ArrayType::Normal;
352
353      // C99 6.7.5.2p1: If the element type is an incomplete or function type,
354      // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
355      if (DiagnoseIncompleteType(D.getIdentifierLoc(), T,
356                                 diag::err_illegal_decl_array_incomplete_type)) {
357        T = Context.IntTy;
358        D.setInvalidType(true);
359      } else if (T->isFunctionType()) {
360        Diag(D.getIdentifierLoc(), diag::err_illegal_decl_array_of_functions)
361          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
362        T = Context.getPointerType(T);
363        D.setInvalidType(true);
364      } else if (const ReferenceType *RT = T->getAsReferenceType()) {
365        // C++ 8.3.2p4: There shall be no ... arrays of references ...
366        Diag(D.getIdentifierLoc(), diag::err_illegal_decl_array_of_references)
367          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
368        T = RT->getPointeeType();
369        D.setInvalidType(true);
370      } else if (const RecordType *EltTy = T->getAsRecordType()) {
371        // If the element type is a struct or union that contains a variadic
372        // array, reject it: C99 6.7.2.1p2.
373        if (EltTy->getDecl()->hasFlexibleArrayMember()) {
374          Diag(DeclType.Loc, diag::err_flexible_array_in_array) << T;
375          T = Context.IntTy;
376          D.setInvalidType(true);
377        }
378      } else if (T->isObjCInterfaceType()) {
379        Diag(DeclType.Loc, diag::warn_objc_array_of_interfaces) << T;
380      }
381
382      // C99 6.7.5.2p1: The size expression shall have integer type.
383      if (ArraySize && !ArraySize->getType()->isIntegerType()) {
384        Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
385          << ArraySize->getType() << ArraySize->getSourceRange();
386        D.setInvalidType(true);
387        delete ArraySize;
388        ATI.NumElts = ArraySize = 0;
389      }
390      llvm::APSInt ConstVal(32);
391      if (!ArraySize) {
392        T = Context.getIncompleteArrayType(T, ASM, ATI.TypeQuals);
393      } else if (ArraySize->isValueDependent()) {
394        T = Context.getDependentSizedArrayType(T, ArraySize, ASM, ATI.TypeQuals);
395      } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
396                 !T->isConstantSizeType()) {
397        // Per C99, a variable array is an array with either a non-constant
398        // size or an element type that has a non-constant-size
399        T = Context.getVariableArrayType(T, ArraySize, ASM, ATI.TypeQuals);
400      } else {
401        // C99 6.7.5.2p1: If the expression is a constant expression, it shall
402        // have a value greater than zero.
403        if (ConstVal.isSigned()) {
404          if (ConstVal.isNegative()) {
405            Diag(ArraySize->getLocStart(),
406                 diag::err_typecheck_negative_array_size)
407              << ArraySize->getSourceRange();
408            D.setInvalidType(true);
409          } else if (ConstVal == 0) {
410            // GCC accepts zero sized static arrays.
411            Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size)
412              << ArraySize->getSourceRange();
413          }
414        }
415        T = Context.getConstantArrayType(T, ConstVal, ASM, ATI.TypeQuals);
416      }
417      // If this is not C99, extwarn about VLA's and C99 array size modifiers.
418      if (!getLangOptions().C99) {
419        if (ArraySize && !ArraySize->isValueDependent() &&
420            !ArraySize->isIntegerConstantExpr(Context))
421          Diag(D.getIdentifierLoc(), diag::ext_vla);
422        else if (ASM != ArrayType::Normal || ATI.TypeQuals != 0)
423          Diag(D.getIdentifierLoc(), diag::ext_c99_array_usage);
424      }
425      break;
426    }
427    case DeclaratorChunk::Function: {
428      // If the function declarator has a prototype (i.e. it is not () and
429      // does not have a K&R-style identifier list), then the arguments are part
430      // of the type, otherwise the argument list is ().
431      const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
432
433      // C99 6.7.5.3p1: The return type may not be a function or array type.
434      if (T->isArrayType() || T->isFunctionType()) {
435        Diag(DeclType.Loc, diag::err_func_returning_array_function) << T;
436        T = Context.IntTy;
437        D.setInvalidType(true);
438      }
439
440      if (FTI.NumArgs == 0) {
441        if (getLangOptions().CPlusPlus) {
442          // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the
443          // function takes no arguments.
444          T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic,FTI.TypeQuals);
445        } else {
446          // Simple void foo(), where the incoming T is the result type.
447          T = Context.getFunctionTypeNoProto(T);
448        }
449      } else if (FTI.ArgInfo[0].Param == 0) {
450        // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition.
451        Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
452      } else {
453        // Otherwise, we have a function with an argument list that is
454        // potentially variadic.
455        llvm::SmallVector<QualType, 16> ArgTys;
456
457        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
458          ParmVarDecl *Param = (ParmVarDecl *)FTI.ArgInfo[i].Param;
459          QualType ArgTy = Param->getType();
460          assert(!ArgTy.isNull() && "Couldn't parse type?");
461          //
462          // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
463          // This matches the conversion that is done in
464          // Sema::ActOnParamDeclarator(). Without this conversion, the
465          // argument type in the function prototype *will not* match the
466          // type in ParmVarDecl (which makes the code generator unhappy).
467          //
468          // FIXME: We still apparently need the conversion in
469          // Sema::ActOnParamDeclarator(). This doesn't make any sense, since
470          // it should be driving off the type being created here.
471          //
472          // FIXME: If a source translation tool needs to see the original type,
473          // then we need to consider storing both types somewhere...
474          //
475          if (ArgTy->isArrayType()) {
476            ArgTy = Context.getArrayDecayedType(ArgTy);
477          } else if (ArgTy->isFunctionType())
478            ArgTy = Context.getPointerType(ArgTy);
479
480          // Look for 'void'.  void is allowed only as a single argument to a
481          // function with no other parameters (C99 6.7.5.3p10).  We record
482          // int(void) as a FunctionTypeProto with an empty argument list.
483          else if (ArgTy->isVoidType()) {
484            // If this is something like 'float(int, void)', reject it.  'void'
485            // is an incomplete type (C99 6.2.5p19) and function decls cannot
486            // have arguments of incomplete type.
487            if (FTI.NumArgs != 1 || FTI.isVariadic) {
488              Diag(DeclType.Loc, diag::err_void_only_param);
489              ArgTy = Context.IntTy;
490              Param->setType(ArgTy);
491            } else if (FTI.ArgInfo[i].Ident) {
492              // Reject, but continue to parse 'int(void abc)'.
493              Diag(FTI.ArgInfo[i].IdentLoc,
494                   diag::err_param_with_void_type);
495              ArgTy = Context.IntTy;
496              Param->setType(ArgTy);
497            } else {
498              // Reject, but continue to parse 'float(const void)'.
499              if (ArgTy.getCVRQualifiers())
500                Diag(DeclType.Loc, diag::err_void_param_qualified);
501
502              // Do not add 'void' to the ArgTys list.
503              break;
504            }
505          } else if (!FTI.hasPrototype) {
506            if (ArgTy->isPromotableIntegerType()) {
507              ArgTy = Context.IntTy;
508            } else if (const BuiltinType* BTy = ArgTy->getAsBuiltinType()) {
509              if (BTy->getKind() == BuiltinType::Float)
510                ArgTy = Context.DoubleTy;
511            }
512          }
513
514          ArgTys.push_back(ArgTy);
515        }
516        T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
517                                    FTI.isVariadic, FTI.TypeQuals);
518      }
519      break;
520    }
521    case DeclaratorChunk::MemberPointer:
522      // The scope spec must refer to a class, or be dependent.
523      DeclContext *DC = static_cast<DeclContext*>(
524        DeclType.Mem.Scope().getScopeRep());
525      QualType ClsType;
526      // FIXME: Extend for dependent types when it's actually supported.
527      // See ActOnCXXNestedNameSpecifier.
528      if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(DC)) {
529        ClsType = Context.getTagDeclType(RD);
530      } else {
531        if (DC) {
532          Diag(DeclType.Mem.Scope().getBeginLoc(),
533               diag::err_illegal_decl_mempointer_in_nonclass)
534            << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
535            << DeclType.Mem.Scope().getRange();
536        }
537        D.setInvalidType(true);
538        ClsType = Context.IntTy;
539      }
540
541      // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member
542      //   with reference type, or "cv void."
543      if (T->isReferenceType()) {
544        Diag(DeclType.Loc, diag::err_illegal_decl_pointer_to_reference)
545          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
546        D.setInvalidType(true);
547        T = Context.IntTy;
548      }
549      if (T->isVoidType()) {
550        Diag(DeclType.Loc, diag::err_illegal_decl_mempointer_to_void)
551          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
552        T = Context.IntTy;
553      }
554
555      // Enforce C99 6.7.3p2: "Types other than pointer types derived from
556      // object or incomplete types shall not be restrict-qualified."
557      if ((DeclType.Mem.TypeQuals & QualType::Restrict) &&
558          !T->isIncompleteOrObjectType()) {
559        Diag(DeclType.Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
560          << T;
561        DeclType.Mem.TypeQuals &= ~QualType::Restrict;
562      }
563
564      T = Context.getMemberPointerType(T, ClsType.getTypePtr()).
565                    getQualifiedType(DeclType.Mem.TypeQuals);
566
567      break;
568    }
569
570    // See if there are any attributes on this declarator chunk.
571    if (const AttributeList *AL = DeclType.getAttrs())
572      ProcessTypeAttributeList(T, AL);
573  }
574
575  if (getLangOptions().CPlusPlus && T->isFunctionType()) {
576    const FunctionTypeProto *FnTy = T->getAsFunctionTypeProto();
577    assert(FnTy && "Why oh why is there not a FunctionTypeProto here ?");
578
579    // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type
580    // for a nonstatic member function, the function type to which a pointer
581    // to member refers, or the top-level function type of a function typedef
582    // declaration.
583    if (FnTy->getTypeQuals() != 0 &&
584        D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
585        ((D.getContext() != Declarator::MemberContext &&
586          (!D.getCXXScopeSpec().isSet() ||
587           !static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep())
588              ->isRecord())) ||
589         D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
590      if (D.isFunctionDeclarator())
591        Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type);
592      else
593        Diag(D.getIdentifierLoc(),
594             diag::err_invalid_qualified_typedef_function_type_use);
595
596      // Strip the cv-quals from the type.
597      T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(),
598                                  FnTy->getNumArgs(), FnTy->isVariadic(), 0);
599    }
600  }
601
602  // If there were any type attributes applied to the decl itself (not the
603  // type, apply the type attribute to the type!)
604  if (const AttributeList *Attrs = D.getAttributes())
605    ProcessTypeAttributeList(T, Attrs);
606
607  return T;
608}
609
610/// ObjCGetTypeForMethodDefinition - Builds the type for a method definition
611/// declarator
612QualType Sema::ObjCGetTypeForMethodDefinition(DeclTy *D) {
613  ObjCMethodDecl *MDecl = dyn_cast<ObjCMethodDecl>(static_cast<Decl *>(D));
614  QualType T = MDecl->getResultType();
615  llvm::SmallVector<QualType, 16> ArgTys;
616
617  // Add the first two invisible argument types for self and _cmd.
618  if (MDecl->isInstanceMethod()) {
619    QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface());
620    selfTy = Context.getPointerType(selfTy);
621    ArgTys.push_back(selfTy);
622  }
623  else
624    ArgTys.push_back(Context.getObjCIdType());
625  ArgTys.push_back(Context.getObjCSelType());
626
627  for (int i = 0, e = MDecl->getNumParams(); i != e; ++i) {
628    ParmVarDecl *PDecl = MDecl->getParamDecl(i);
629    QualType ArgTy = PDecl->getType();
630    assert(!ArgTy.isNull() && "Couldn't parse type?");
631    // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
632    // This matches the conversion that is done in
633    // Sema::ActOnParamDeclarator().
634    if (ArgTy->isArrayType())
635      ArgTy = Context.getArrayDecayedType(ArgTy);
636    else if (ArgTy->isFunctionType())
637      ArgTy = Context.getPointerType(ArgTy);
638    ArgTys.push_back(ArgTy);
639  }
640  T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
641                              MDecl->isVariadic(), 0);
642  return T;
643}
644
645/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
646/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
647/// they point to and return true. If T1 and T2 aren't pointer types
648/// or pointer-to-member types, or if they are not similar at this
649/// level, returns false and leaves T1 and T2 unchanged. Top-level
650/// qualifiers on T1 and T2 are ignored. This function will typically
651/// be called in a loop that successively "unwraps" pointer and
652/// pointer-to-member types to compare them at each level.
653bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2)
654{
655  const PointerType *T1PtrType = T1->getAsPointerType(),
656                    *T2PtrType = T2->getAsPointerType();
657  if (T1PtrType && T2PtrType) {
658    T1 = T1PtrType->getPointeeType();
659    T2 = T2PtrType->getPointeeType();
660    return true;
661  }
662
663  const MemberPointerType *T1MPType = T1->getAsMemberPointerType(),
664                          *T2MPType = T2->getAsMemberPointerType();
665  if (T1MPType && T2MPType) {
666    T1 = T1MPType->getPointeeType();
667    T2 = T2MPType->getPointeeType();
668    return true;
669  }
670  return false;
671}
672
673Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
674  // C99 6.7.6: Type names have no identifier.  This is already validated by
675  // the parser.
676  assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
677
678  QualType T = GetTypeForDeclarator(D, S);
679
680  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
681
682  // Check that there are no default arguments (C++ only).
683  if (getLangOptions().CPlusPlus)
684    CheckExtraCXXDefaultArguments(D);
685
686  // In this context, we *do not* check D.getInvalidType(). If the declarator
687  // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
688  // though it will not reflect the user specified type.
689  return T.getAsOpaquePtr();
690}
691
692
693
694//===----------------------------------------------------------------------===//
695// Type Attribute Processing
696//===----------------------------------------------------------------------===//
697
698/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
699/// specified type.  The attribute contains 1 argument, the id of the address
700/// space for the type.
701static void HandleAddressSpaceTypeAttribute(QualType &Type,
702                                            const AttributeList &Attr, Sema &S){
703  // If this type is already address space qualified, reject it.
704  // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
705  // for two or more different address spaces."
706  if (Type.getAddressSpace()) {
707    S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
708    return;
709  }
710
711  // Check the attribute arguments.
712  if (Attr.getNumArgs() != 1) {
713    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
714    return;
715  }
716  Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
717  llvm::APSInt addrSpace(32);
718  if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
719    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
720      << ASArgExpr->getSourceRange();
721    return;
722  }
723
724  unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
725  Type = S.Context.getASQualType(Type, ASIdx);
726}
727
728void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) {
729  // Scan through and apply attributes to this type where it makes sense.  Some
730  // attributes (such as __address_space__, __vector_size__, etc) apply to the
731  // type, but others can be present in the type specifiers even though they
732  // apply to the decl.  Here we apply type attributes and ignore the rest.
733  for (; AL; AL = AL->getNext()) {
734    // If this is an attribute we can handle, do so now, otherwise, add it to
735    // the LeftOverAttrs list for rechaining.
736    switch (AL->getKind()) {
737    default: break;
738    case AttributeList::AT_address_space:
739      HandleAddressSpaceTypeAttribute(Result, *AL, *this);
740      break;
741    }
742  }
743}
744
745/// @brief If the type T is incomplete and cannot be completed,
746/// produce a suitable diagnostic.
747///
748/// This routine checks whether the type @p T is complete in any
749/// context where a complete type is required. If @p T is a complete
750/// type, returns false. If @p T is incomplete, issues the diagnostic
751/// @p diag (giving it the type @p T) and returns true.
752///
753/// @param Loc  The location in the source that the incomplete type
754/// diagnostic should refer to.
755///
756/// @param T  The type that this routine is examining for completeness.
757///
758/// @param diag The diagnostic value (e.g.,
759/// @c diag::err_typecheck_decl_incomplete_type) that will be used
760/// for the error message if @p T is incomplete.
761///
762/// @param Range1  An optional range in the source code that will be a
763/// part of the "incomplete type" error message.
764///
765/// @param Range2  An optional range in the source code that will be a
766/// part of the "incomplete type" error message.
767///
768/// @param PrintType If non-NULL, the type that should be printed
769/// instead of @p T. This parameter should be used when the type that
770/// we're checking for incompleteness isn't the type that should be
771/// displayed to the user, e.g., when T is a type and PrintType is a
772/// pointer to T.
773///
774/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
775/// @c false otherwise.
776///
777/// @todo When Clang gets proper support for C++ templates, this
778/// routine will also be able perform template instantiation when @p T
779/// is a class template specialization.
780bool Sema::DiagnoseIncompleteType(SourceLocation Loc, QualType T, unsigned diag,
781                                  SourceRange Range1, SourceRange Range2,
782                                  QualType PrintType) {
783  // If we have a complete type, we're done.
784  if (!T->isIncompleteType())
785    return false;
786
787  if (PrintType.isNull())
788    PrintType = T;
789
790  // We have an incomplete type. Produce a diagnostic.
791  Diag(Loc, diag) << PrintType << Range1 << Range2;
792
793  // If the type was a forward declaration of a class/struct/union
794  // type, produce
795  const TagType *Tag = 0;
796  if (const RecordType *Record = T->getAsRecordType())
797    Tag = Record;
798  else if (const EnumType *Enum = T->getAsEnumType())
799    Tag = Enum;
800
801  if (Tag && !Tag->getDecl()->isInvalidDecl())
802    Diag(Tag->getDecl()->getLocation(),
803         Tag->isBeingDefined() ? diag::note_type_being_defined
804                               : diag::note_forward_declaration)
805        << QualType(Tag, 0);
806
807  return true;
808}
809