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