SemaInit.cpp revision c1efaecf0373f1a55c5ef4c234357cf726fc0600
1//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
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 semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
14// This file also implements Sema::CheckInitializerTypes.
15//
16//===----------------------------------------------------------------------===//
17
18#include "Sema.h"
19#include "clang/Parse/Designator.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/ExprObjC.h"
22#include <map>
23using namespace clang;
24
25//===----------------------------------------------------------------------===//
26// Sema Initialization Checking
27//===----------------------------------------------------------------------===//
28
29static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
30  const ArrayType *AT = Context.getAsArrayType(DeclType);
31  if (!AT) return 0;
32
33  // See if this is a string literal or @encode.
34  Init = Init->IgnoreParens();
35
36  // Handle @encode, which is a narrow string.
37  if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
38    return Init;
39
40  // Otherwise we can only handle string literals.
41  StringLiteral *SL = dyn_cast<StringLiteral>(Init);
42  if (SL == 0) return 0;
43
44  // char array can be initialized with a narrow string.
45  // Only allow char x[] = "foo";  not char x[] = L"foo";
46  if (!SL->isWide())
47    return AT->getElementType()->isCharType() ? Init : 0;
48
49  // wchar_t array can be initialized with a wide string: C99 6.7.8p15:
50  // "An array with element type compatible with wchar_t may be initialized by a
51  // wide string literal, optionally enclosed in braces."
52  if (Context.typesAreCompatible(Context.getWCharType(), AT->getElementType()))
53    // Only allow wchar_t x[] = L"foo";  not wchar_t x[] = "foo";
54    return Init;
55
56  return 0;
57}
58
59static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
60                                   bool DirectInit, Sema &S) {
61  // Get the type before calling CheckSingleAssignmentConstraints(), since
62  // it can promote the expression.
63  QualType InitType = Init->getType();
64
65  if (S.getLangOptions().CPlusPlus) {
66    // FIXME: I dislike this error message. A lot.
67    if (S.PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
68      return S.Diag(Init->getSourceRange().getBegin(),
69                    diag::err_typecheck_convert_incompatible)
70        << DeclType << Init->getType() << "initializing"
71        << Init->getSourceRange();
72    return false;
73  }
74
75  Sema::AssignConvertType ConvTy =
76    S.CheckSingleAssignmentConstraints(DeclType, Init);
77  return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
78                                  InitType, Init, "initializing");
79}
80
81static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
82  // Get the length of the string as parsed.
83  uint64_t StrLength =
84    cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
85
86
87  const ArrayType *AT = S.Context.getAsArrayType(DeclT);
88  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
89    // C99 6.7.8p14. We have an array of character type with unknown size
90    // being initialized to a string literal.
91    llvm::APSInt ConstVal(32);
92    ConstVal = StrLength;
93    // Return a new array type (C99 6.7.8p22).
94    DeclT = S.Context.getConstantArrayType(IAT->getElementType(), ConstVal,
95                                           ArrayType::Normal, 0);
96    return;
97  }
98
99  const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
100
101  // C99 6.7.8p14. We have an array of character type with known size.  However,
102  // the size may be smaller or larger than the string we are initializing.
103  // FIXME: Avoid truncation for 64-bit length strings.
104  if (StrLength-1 > CAT->getSize().getZExtValue())
105    S.Diag(Str->getSourceRange().getBegin(),
106           diag::warn_initializer_string_for_char_array_too_long)
107      << Str->getSourceRange();
108
109  // Set the type to the actual size that we are initializing.  If we have
110  // something like:
111  //   char x[1] = "foo";
112  // then this will set the string literal's type to char[1].
113  Str->setType(DeclT);
114}
115
116bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
117                                 SourceLocation InitLoc,
118                                 DeclarationName InitEntity,
119                                 bool DirectInit) {
120  if (DeclType->isDependentType() || Init->isTypeDependent())
121    return false;
122
123  // C++ [dcl.init.ref]p1:
124  //   A variable declared to be a T&, that is "reference to type T"
125  //   (8.3.2), shall be initialized by an object, or function, of
126  //   type T or by an object that can be converted into a T.
127  if (DeclType->isReferenceType())
128    return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
129
130  // C99 6.7.8p3: The type of the entity to be initialized shall be an array
131  // of unknown size ("[]") or an object type that is not a variable array type.
132  if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
133    return Diag(InitLoc,  diag::err_variable_object_no_init)
134    << VAT->getSizeExpr()->getSourceRange();
135
136  InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
137  if (!InitList) {
138    // FIXME: Handle wide strings
139    if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
140      CheckStringInit(Str, DeclType, *this);
141      return false;
142    }
143
144    // C++ [dcl.init]p14:
145    //   -- If the destination type is a (possibly cv-qualified) class
146    //      type:
147    if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
148      QualType DeclTypeC = Context.getCanonicalType(DeclType);
149      QualType InitTypeC = Context.getCanonicalType(Init->getType());
150
151      //   -- If the initialization is direct-initialization, or if it is
152      //      copy-initialization where the cv-unqualified version of the
153      //      source type is the same class as, or a derived class of, the
154      //      class of the destination, constructors are considered.
155      if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
156          IsDerivedFrom(InitTypeC, DeclTypeC)) {
157        CXXConstructorDecl *Constructor
158        = PerformInitializationByConstructor(DeclType, &Init, 1,
159                                             InitLoc, Init->getSourceRange(),
160                                             InitEntity,
161                                             DirectInit? IK_Direct : IK_Copy);
162        return Constructor == 0;
163      }
164
165      //   -- Otherwise (i.e., for the remaining copy-initialization
166      //      cases), user-defined conversion sequences that can
167      //      convert from the source type to the destination type or
168      //      (when a conversion function is used) to a derived class
169      //      thereof are enumerated as described in 13.3.1.4, and the
170      //      best one is chosen through overload resolution
171      //      (13.3). If the conversion cannot be done or is
172      //      ambiguous, the initialization is ill-formed. The
173      //      function selected is called with the initializer
174      //      expression as its argument; if the function is a
175      //      constructor, the call initializes a temporary of the
176      //      destination type.
177      // FIXME: We're pretending to do copy elision here; return to
178      // this when we have ASTs for such things.
179      if (!PerformImplicitConversion(Init, DeclType, "initializing"))
180        return false;
181
182      if (InitEntity)
183        return Diag(InitLoc, diag::err_cannot_initialize_decl)
184        << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
185        << Init->getType() << Init->getSourceRange();
186      else
187        return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
188        << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
189        << Init->getType() << Init->getSourceRange();
190    }
191
192    // C99 6.7.8p16.
193    if (DeclType->isArrayType())
194      return Diag(Init->getLocStart(), diag::err_array_init_list_required)
195      << Init->getSourceRange();
196
197    return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
198  }
199
200  bool hadError = CheckInitList(InitList, DeclType);
201  Init = InitList;
202  return hadError;
203}
204
205//===----------------------------------------------------------------------===//
206// Semantic checking for initializer lists.
207//===----------------------------------------------------------------------===//
208
209/// @brief Semantic checking for initializer lists.
210///
211/// The InitListChecker class contains a set of routines that each
212/// handle the initialization of a certain kind of entity, e.g.,
213/// arrays, vectors, struct/union types, scalars, etc. The
214/// InitListChecker itself performs a recursive walk of the subobject
215/// structure of the type to be initialized, while stepping through
216/// the initializer list one element at a time. The IList and Index
217/// parameters to each of the Check* routines contain the active
218/// (syntactic) initializer list and the index into that initializer
219/// list that represents the current initializer. Each routine is
220/// responsible for moving that Index forward as it consumes elements.
221///
222/// Each Check* routine also has a StructuredList/StructuredIndex
223/// arguments, which contains the current the "structured" (semantic)
224/// initializer list and the index into that initializer list where we
225/// are copying initializers as we map them over to the semantic
226/// list. Once we have completed our recursive walk of the subobject
227/// structure, we will have constructed a full semantic initializer
228/// list.
229///
230/// C99 designators cause changes in the initializer list traversal,
231/// because they make the initialization "jump" into a specific
232/// subobject and then continue the initialization from that
233/// point. CheckDesignatedInitializer() recursively steps into the
234/// designated subobject and manages backing out the recursion to
235/// initialize the subobjects after the one designated.
236namespace {
237class InitListChecker {
238  Sema &SemaRef;
239  bool hadError;
240  std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
241  InitListExpr *FullyStructuredList;
242
243  void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
244                             unsigned &Index, InitListExpr *StructuredList,
245                             unsigned &StructuredIndex,
246                             bool TopLevelObject = false);
247  void CheckExplicitInitList(InitListExpr *IList, QualType &T,
248                             unsigned &Index, InitListExpr *StructuredList,
249                             unsigned &StructuredIndex,
250                             bool TopLevelObject = false);
251  void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
252                             bool SubobjectIsDesignatorContext,
253                             unsigned &Index,
254                             InitListExpr *StructuredList,
255                             unsigned &StructuredIndex,
256                             bool TopLevelObject = false);
257  void CheckSubElementType(InitListExpr *IList, QualType ElemType,
258                           unsigned &Index,
259                           InitListExpr *StructuredList,
260                           unsigned &StructuredIndex);
261  void CheckScalarType(InitListExpr *IList, QualType DeclType,
262                       unsigned &Index,
263                       InitListExpr *StructuredList,
264                       unsigned &StructuredIndex);
265  void CheckReferenceType(InitListExpr *IList, QualType DeclType,
266                          unsigned &Index,
267                          InitListExpr *StructuredList,
268                          unsigned &StructuredIndex);
269  void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
270                       InitListExpr *StructuredList,
271                       unsigned &StructuredIndex);
272  void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
273                             RecordDecl::field_iterator Field,
274                             bool SubobjectIsDesignatorContext, unsigned &Index,
275                             InitListExpr *StructuredList,
276                             unsigned &StructuredIndex,
277                             bool TopLevelObject = false);
278  void CheckArrayType(InitListExpr *IList, QualType &DeclType,
279                      llvm::APSInt elementIndex,
280                      bool SubobjectIsDesignatorContext, unsigned &Index,
281                      InitListExpr *StructuredList,
282                      unsigned &StructuredIndex);
283  bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
284                                  DesignatedInitExpr::designators_iterator D,
285                                  QualType &CurrentObjectType,
286                                  RecordDecl::field_iterator *NextField,
287                                  llvm::APSInt *NextElementIndex,
288                                  unsigned &Index,
289                                  InitListExpr *StructuredList,
290                                  unsigned &StructuredIndex,
291                                  bool FinishSubobjectInit,
292                                  bool TopLevelObject);
293  InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
294                                           QualType CurrentObjectType,
295                                           InitListExpr *StructuredList,
296                                           unsigned StructuredIndex,
297                                           SourceRange InitRange);
298  void UpdateStructuredListElement(InitListExpr *StructuredList,
299                                   unsigned &StructuredIndex,
300                                   Expr *expr);
301  int numArrayElements(QualType DeclType);
302  int numStructUnionElements(QualType DeclType);
303
304  void FillInValueInitializations(InitListExpr *ILE);
305public:
306  InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
307  bool HadError() { return hadError; }
308
309  // @brief Retrieves the fully-structured initializer list used for
310  // semantic analysis and code generation.
311  InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
312};
313} // end anonymous namespace
314
315/// Recursively replaces NULL values within the given initializer list
316/// with expressions that perform value-initialization of the
317/// appropriate type.
318void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
319  assert((ILE->getType() != SemaRef.Context.VoidTy) &&
320         "Should not have void type");
321  SourceLocation Loc = ILE->getSourceRange().getBegin();
322  if (ILE->getSyntacticForm())
323    Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
324
325  if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
326    unsigned Init = 0, NumInits = ILE->getNumInits();
327    for (RecordDecl::field_iterator Field = RType->getDecl()->field_begin(),
328                                 FieldEnd = RType->getDecl()->field_end();
329         Field != FieldEnd; ++Field) {
330      if (Field->isUnnamedBitfield())
331        continue;
332
333      if (Init >= NumInits || !ILE->getInit(Init)) {
334        if (Field->getType()->isReferenceType()) {
335          // C++ [dcl.init.aggr]p9:
336          //   If an incomplete or empty initializer-list leaves a
337          //   member of reference type uninitialized, the program is
338          //   ill-formed.
339          SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
340            << Field->getType()
341            << ILE->getSyntacticForm()->getSourceRange();
342          SemaRef.Diag(Field->getLocation(),
343                        diag::note_uninit_reference_member);
344          hadError = true;
345          return;
346        } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
347          hadError = true;
348          return;
349        }
350
351        // FIXME: If value-initialization involves calling a
352        // constructor, should we make that call explicit in the
353        // representation (even when it means extending the
354        // initializer list)?
355        if (Init < NumInits && !hadError)
356          ILE->setInit(Init,
357              new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
358      } else if (InitListExpr *InnerILE
359                 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
360        FillInValueInitializations(InnerILE);
361      ++Init;
362
363      // Only look at the first initialization of a union.
364      if (RType->getDecl()->isUnion())
365        break;
366    }
367
368    return;
369  }
370
371  QualType ElementType;
372
373  unsigned NumInits = ILE->getNumInits();
374  unsigned NumElements = NumInits;
375  if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
376    ElementType = AType->getElementType();
377    if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
378      NumElements = CAType->getSize().getZExtValue();
379  } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
380    ElementType = VType->getElementType();
381    NumElements = VType->getNumElements();
382  } else
383    ElementType = ILE->getType();
384
385  for (unsigned Init = 0; Init != NumElements; ++Init) {
386    if (Init >= NumInits || !ILE->getInit(Init)) {
387      if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
388        hadError = true;
389        return;
390      }
391
392      // FIXME: If value-initialization involves calling a
393      // constructor, should we make that call explicit in the
394      // representation (even when it means extending the
395      // initializer list)?
396      if (Init < NumInits && !hadError)
397        ILE->setInit(Init,
398                     new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
399    }
400    else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
401      FillInValueInitializations(InnerILE);
402  }
403}
404
405
406InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
407  : SemaRef(S) {
408  hadError = false;
409
410  unsigned newIndex = 0;
411  unsigned newStructuredIndex = 0;
412  FullyStructuredList
413    = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, SourceRange());
414  CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
415                        /*TopLevelObject=*/true);
416
417  if (!hadError)
418    FillInValueInitializations(FullyStructuredList);
419}
420
421int InitListChecker::numArrayElements(QualType DeclType) {
422  // FIXME: use a proper constant
423  int maxElements = 0x7FFFFFFF;
424  if (const ConstantArrayType *CAT =
425        SemaRef.Context.getAsConstantArrayType(DeclType)) {
426    maxElements = static_cast<int>(CAT->getSize().getZExtValue());
427  }
428  return maxElements;
429}
430
431int InitListChecker::numStructUnionElements(QualType DeclType) {
432  RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
433  int InitializableMembers = 0;
434  for (RecordDecl::field_iterator Field = structDecl->field_begin(),
435                               FieldEnd = structDecl->field_end();
436       Field != FieldEnd; ++Field) {
437    if ((*Field)->getIdentifier() || !(*Field)->isBitField())
438      ++InitializableMembers;
439  }
440  if (structDecl->isUnion())
441    return std::min(InitializableMembers, 1);
442  return InitializableMembers - structDecl->hasFlexibleArrayMember();
443}
444
445void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
446                                            QualType T, unsigned &Index,
447                                            InitListExpr *StructuredList,
448                                            unsigned &StructuredIndex,
449                                            bool TopLevelObject) {
450  int maxElements = 0;
451
452  if (T->isArrayType())
453    maxElements = numArrayElements(T);
454  else if (T->isStructureType() || T->isUnionType())
455    maxElements = numStructUnionElements(T);
456  else if (T->isVectorType())
457    maxElements = T->getAsVectorType()->getNumElements();
458  else
459    assert(0 && "CheckImplicitInitList(): Illegal type");
460
461  if (maxElements == 0) {
462    SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
463                  diag::err_implicit_empty_initializer);
464    ++Index;
465    hadError = true;
466    return;
467  }
468
469  // Build a structured initializer list corresponding to this subobject.
470  InitListExpr *StructuredSubobjectInitList
471    = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
472                                 StructuredIndex,
473                                 ParentIList->getInit(Index)->getSourceRange());
474  unsigned StructuredSubobjectInitIndex = 0;
475
476  // Check the element types and build the structural subobject.
477  unsigned StartIndex = Index;
478  CheckListElementTypes(ParentIList, T, false, Index,
479                        StructuredSubobjectInitList,
480                        StructuredSubobjectInitIndex,
481                        TopLevelObject);
482  unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
483
484  // Update the structured sub-object initialize so that it's ending
485  // range corresponds with the end of the last initializer it used.
486  if (EndIndex < ParentIList->getNumInits()) {
487    SourceLocation EndLoc
488      = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
489    StructuredSubobjectInitList->setRBraceLoc(EndLoc);
490  }
491}
492
493void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
494                                            unsigned &Index,
495                                            InitListExpr *StructuredList,
496                                            unsigned &StructuredIndex,
497                                            bool TopLevelObject) {
498  assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
499  SyntacticToSemantic[IList] = StructuredList;
500  StructuredList->setSyntacticForm(IList);
501  CheckListElementTypes(IList, T, true, Index, StructuredList,
502                        StructuredIndex, TopLevelObject);
503  IList->setType(T);
504  StructuredList->setType(T);
505  if (hadError)
506    return;
507
508  if (Index < IList->getNumInits()) {
509    // We have leftover initializers
510    if (IList->getNumInits() > 0 &&
511        IsStringInit(IList->getInit(Index), T, SemaRef.Context)) {
512      unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
513      if (SemaRef.getLangOptions().CPlusPlus)
514        DK = diag::err_excess_initializers_in_char_array_initializer;
515      // Special-case
516      SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
517        << IList->getInit(Index)->getSourceRange();
518      hadError = true;
519    } else if (!T->isIncompleteType()) {
520      // Don't complain for incomplete types, since we'll get an error
521      // elsewhere
522      QualType CurrentObjectType = StructuredList->getType();
523      int initKind =
524        CurrentObjectType->isArrayType()? 0 :
525        CurrentObjectType->isVectorType()? 1 :
526        CurrentObjectType->isScalarType()? 2 :
527        CurrentObjectType->isUnionType()? 3 :
528        4;
529
530      unsigned DK = diag::warn_excess_initializers;
531      if (SemaRef.getLangOptions().CPlusPlus)
532          DK = diag::err_excess_initializers;
533
534      SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
535        << initKind << IList->getInit(Index)->getSourceRange();
536    }
537  }
538
539  if (T->isScalarType())
540    SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
541      << IList->getSourceRange();
542}
543
544void InitListChecker::CheckListElementTypes(InitListExpr *IList,
545                                            QualType &DeclType,
546                                            bool SubobjectIsDesignatorContext,
547                                            unsigned &Index,
548                                            InitListExpr *StructuredList,
549                                            unsigned &StructuredIndex,
550                                            bool TopLevelObject) {
551  if (DeclType->isScalarType()) {
552    CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
553  } else if (DeclType->isVectorType()) {
554    CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
555  } else if (DeclType->isAggregateType()) {
556    if (DeclType->isRecordType()) {
557      RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
558      CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
559                            SubobjectIsDesignatorContext, Index,
560                            StructuredList, StructuredIndex,
561                            TopLevelObject);
562    } else if (DeclType->isArrayType()) {
563      llvm::APSInt Zero(
564                      SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
565                      false);
566      CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
567                     StructuredList, StructuredIndex);
568    }
569    else
570      assert(0 && "Aggregate that isn't a structure or array?!");
571  } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
572    // This type is invalid, issue a diagnostic.
573    ++Index;
574    SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
575      << DeclType;
576    hadError = true;
577  } else if (DeclType->isRecordType()) {
578    // C++ [dcl.init]p14:
579    //   [...] If the class is an aggregate (8.5.1), and the initializer
580    //   is a brace-enclosed list, see 8.5.1.
581    //
582    // Note: 8.5.1 is handled below; here, we diagnose the case where
583    // we have an initializer list and a destination type that is not
584    // an aggregate.
585    // FIXME: In C++0x, this is yet another form of initialization.
586    SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
587      << DeclType << IList->getSourceRange();
588    hadError = true;
589  } else if (DeclType->isReferenceType()) {
590    CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
591  } else {
592    // In C, all types are either scalars or aggregates, but
593    // additional handling is needed here for C++ (and possibly others?).
594    assert(0 && "Unsupported initializer type");
595  }
596}
597
598void InitListChecker::CheckSubElementType(InitListExpr *IList,
599                                          QualType ElemType,
600                                          unsigned &Index,
601                                          InitListExpr *StructuredList,
602                                          unsigned &StructuredIndex) {
603  Expr *expr = IList->getInit(Index);
604  if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
605    unsigned newIndex = 0;
606    unsigned newStructuredIndex = 0;
607    InitListExpr *newStructuredList
608      = getStructuredSubobjectInit(IList, Index, ElemType,
609                                   StructuredList, StructuredIndex,
610                                   SubInitList->getSourceRange());
611    CheckExplicitInitList(SubInitList, ElemType, newIndex,
612                          newStructuredList, newStructuredIndex);
613    ++StructuredIndex;
614    ++Index;
615  } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
616    CheckStringInit(Str, ElemType, SemaRef);
617    UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
618    ++Index;
619  } else if (ElemType->isScalarType()) {
620    CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
621  } else if (ElemType->isReferenceType()) {
622    CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
623  } else {
624    if (SemaRef.getLangOptions().CPlusPlus) {
625      // C++ [dcl.init.aggr]p12:
626      //   All implicit type conversions (clause 4) are considered when
627      //   initializing the aggregate member with an ini- tializer from
628      //   an initializer-list. If the initializer can initialize a
629      //   member, the member is initialized. [...]
630      ImplicitConversionSequence ICS
631        = SemaRef.TryCopyInitialization(expr, ElemType);
632      if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
633        if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
634                                               "initializing"))
635          hadError = true;
636        UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
637        ++Index;
638        return;
639      }
640
641      // Fall through for subaggregate initialization
642    } else {
643      // C99 6.7.8p13:
644      //
645      //   The initializer for a structure or union object that has
646      //   automatic storage duration shall be either an initializer
647      //   list as described below, or a single expression that has
648      //   compatible structure or union type. In the latter case, the
649      //   initial value of the object, including unnamed members, is
650      //   that of the expression.
651      QualType ExprType = SemaRef.Context.getCanonicalType(expr->getType());
652      QualType ElemTypeCanon = SemaRef.Context.getCanonicalType(ElemType);
653      if (SemaRef.Context.typesAreCompatible(ExprType.getUnqualifiedType(),
654                                          ElemTypeCanon.getUnqualifiedType())) {
655        UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
656        ++Index;
657        return;
658      }
659
660      // Fall through for subaggregate initialization
661    }
662
663    // C++ [dcl.init.aggr]p12:
664    //
665    //   [...] Otherwise, if the member is itself a non-empty
666    //   subaggregate, brace elision is assumed and the initializer is
667    //   considered for the initialization of the first member of
668    //   the subaggregate.
669    if (ElemType->isAggregateType() || ElemType->isVectorType()) {
670      CheckImplicitInitList(IList, ElemType, Index, StructuredList,
671                            StructuredIndex);
672      ++StructuredIndex;
673    } else {
674      // We cannot initialize this element, so let
675      // PerformCopyInitialization produce the appropriate diagnostic.
676      SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
677      hadError = true;
678      ++Index;
679      ++StructuredIndex;
680    }
681  }
682}
683
684void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
685                                      unsigned &Index,
686                                      InitListExpr *StructuredList,
687                                      unsigned &StructuredIndex) {
688  if (Index < IList->getNumInits()) {
689    Expr *expr = IList->getInit(Index);
690    if (isa<InitListExpr>(expr)) {
691      SemaRef.Diag(IList->getLocStart(),
692                    diag::err_many_braces_around_scalar_init)
693        << IList->getSourceRange();
694      hadError = true;
695      ++Index;
696      ++StructuredIndex;
697      return;
698    } else if (isa<DesignatedInitExpr>(expr)) {
699      SemaRef.Diag(expr->getSourceRange().getBegin(),
700                    diag::err_designator_for_scalar_init)
701        << DeclType << expr->getSourceRange();
702      hadError = true;
703      ++Index;
704      ++StructuredIndex;
705      return;
706    }
707
708    Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
709    if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
710      hadError = true; // types weren't compatible.
711    else if (savExpr != expr) {
712      // The type was promoted, update initializer list.
713      IList->setInit(Index, expr);
714    }
715    if (hadError)
716      ++StructuredIndex;
717    else
718      UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
719    ++Index;
720  } else {
721    SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
722      << IList->getSourceRange();
723    hadError = true;
724    ++Index;
725    ++StructuredIndex;
726    return;
727  }
728}
729
730void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
731                                         unsigned &Index,
732                                         InitListExpr *StructuredList,
733                                         unsigned &StructuredIndex) {
734  if (Index < IList->getNumInits()) {
735    Expr *expr = IList->getInit(Index);
736    if (isa<InitListExpr>(expr)) {
737      SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
738        << DeclType << IList->getSourceRange();
739      hadError = true;
740      ++Index;
741      ++StructuredIndex;
742      return;
743    }
744
745    Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
746    if (SemaRef.CheckReferenceInit(expr, DeclType))
747      hadError = true;
748    else if (savExpr != expr) {
749      // The type was promoted, update initializer list.
750      IList->setInit(Index, expr);
751    }
752    if (hadError)
753      ++StructuredIndex;
754    else
755      UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
756    ++Index;
757  } else {
758    // FIXME: It would be wonderful if we could point at the actual
759    // member. In general, it would be useful to pass location
760    // information down the stack, so that we know the location (or
761    // decl) of the "current object" being initialized.
762    SemaRef.Diag(IList->getLocStart(),
763                  diag::err_init_reference_member_uninitialized)
764      << DeclType
765      << IList->getSourceRange();
766    hadError = true;
767    ++Index;
768    ++StructuredIndex;
769    return;
770  }
771}
772
773void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
774                                      unsigned &Index,
775                                      InitListExpr *StructuredList,
776                                      unsigned &StructuredIndex) {
777  if (Index < IList->getNumInits()) {
778    const VectorType *VT = DeclType->getAsVectorType();
779    int maxElements = VT->getNumElements();
780    QualType elementType = VT->getElementType();
781
782    for (int i = 0; i < maxElements; ++i) {
783      // Don't attempt to go past the end of the init list
784      if (Index >= IList->getNumInits())
785        break;
786      CheckSubElementType(IList, elementType, Index,
787                          StructuredList, StructuredIndex);
788    }
789  }
790}
791
792void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
793                                     llvm::APSInt elementIndex,
794                                     bool SubobjectIsDesignatorContext,
795                                     unsigned &Index,
796                                     InitListExpr *StructuredList,
797                                     unsigned &StructuredIndex) {
798  // Check for the special-case of initializing an array with a string.
799  if (Index < IList->getNumInits()) {
800    if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
801                                 SemaRef.Context)) {
802      CheckStringInit(Str, DeclType, SemaRef);
803      // We place the string literal directly into the resulting
804      // initializer list. This is the only place where the structure
805      // of the structured initializer list doesn't match exactly,
806      // because doing so would involve allocating one character
807      // constant for each string.
808      UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
809      StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
810      ++Index;
811      return;
812    }
813  }
814  if (const VariableArrayType *VAT =
815        SemaRef.Context.getAsVariableArrayType(DeclType)) {
816    // Check for VLAs; in standard C it would be possible to check this
817    // earlier, but I don't know where clang accepts VLAs (gcc accepts
818    // them in all sorts of strange places).
819    SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
820                  diag::err_variable_object_no_init)
821      << VAT->getSizeExpr()->getSourceRange();
822    hadError = true;
823    ++Index;
824    ++StructuredIndex;
825    return;
826  }
827
828  // We might know the maximum number of elements in advance.
829  llvm::APSInt maxElements(elementIndex.getBitWidth(),
830                           elementIndex.isUnsigned());
831  bool maxElementsKnown = false;
832  if (const ConstantArrayType *CAT =
833        SemaRef.Context.getAsConstantArrayType(DeclType)) {
834    maxElements = CAT->getSize();
835    elementIndex.extOrTrunc(maxElements.getBitWidth());
836    elementIndex.setIsUnsigned(maxElements.isUnsigned());
837    maxElementsKnown = true;
838  }
839
840  QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
841                             ->getElementType();
842  while (Index < IList->getNumInits()) {
843    Expr *Init = IList->getInit(Index);
844    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
845      // If we're not the subobject that matches up with the '{' for
846      // the designator, we shouldn't be handling the
847      // designator. Return immediately.
848      if (!SubobjectIsDesignatorContext)
849        return;
850
851      // Handle this designated initializer. elementIndex will be
852      // updated to be the next array element we'll initialize.
853      if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
854                                     DeclType, 0, &elementIndex, Index,
855                                     StructuredList, StructuredIndex, true,
856                                     false)) {
857        hadError = true;
858        continue;
859      }
860
861      if (elementIndex.getBitWidth() > maxElements.getBitWidth())
862        maxElements.extend(elementIndex.getBitWidth());
863      else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
864        elementIndex.extend(maxElements.getBitWidth());
865      elementIndex.setIsUnsigned(maxElements.isUnsigned());
866
867      // If the array is of incomplete type, keep track of the number of
868      // elements in the initializer.
869      if (!maxElementsKnown && elementIndex > maxElements)
870        maxElements = elementIndex;
871
872      continue;
873    }
874
875    // If we know the maximum number of elements, and we've already
876    // hit it, stop consuming elements in the initializer list.
877    if (maxElementsKnown && elementIndex == maxElements)
878      break;
879
880    // Check this element.
881    CheckSubElementType(IList, elementType, Index,
882                        StructuredList, StructuredIndex);
883    ++elementIndex;
884
885    // If the array is of incomplete type, keep track of the number of
886    // elements in the initializer.
887    if (!maxElementsKnown && elementIndex > maxElements)
888      maxElements = elementIndex;
889  }
890  if (DeclType->isIncompleteArrayType()) {
891    // If this is an incomplete array type, the actual type needs to
892    // be calculated here.
893    llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
894    if (maxElements == Zero) {
895      // Sizing an array implicitly to zero is not allowed by ISO C,
896      // but is supported by GNU.
897      SemaRef.Diag(IList->getLocStart(),
898                    diag::ext_typecheck_zero_array_size);
899    }
900
901    DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
902                                                     ArrayType::Normal, 0);
903  }
904}
905
906void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
907                                            QualType DeclType,
908                                            RecordDecl::field_iterator Field,
909                                            bool SubobjectIsDesignatorContext,
910                                            unsigned &Index,
911                                            InitListExpr *StructuredList,
912                                            unsigned &StructuredIndex,
913                                            bool TopLevelObject) {
914  RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
915
916  // If the record is invalid, some of it's members are invalid. To avoid
917  // confusion, we forgo checking the intializer for the entire record.
918  if (structDecl->isInvalidDecl()) {
919    hadError = true;
920    return;
921  }
922
923  if (DeclType->isUnionType() && IList->getNumInits() == 0) {
924    // Value-initialize the first named member of the union.
925    RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
926    for (RecordDecl::field_iterator FieldEnd = RD->field_end();
927         Field != FieldEnd; ++Field) {
928      if (Field->getDeclName()) {
929        StructuredList->setInitializedFieldInUnion(*Field);
930        break;
931      }
932    }
933    return;
934  }
935
936  // If structDecl is a forward declaration, this loop won't do
937  // anything except look at designated initializers; That's okay,
938  // because an error should get printed out elsewhere. It might be
939  // worthwhile to skip over the rest of the initializer, though.
940  RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
941  RecordDecl::field_iterator FieldEnd = RD->field_end();
942  bool InitializedSomething = false;
943  while (Index < IList->getNumInits()) {
944    Expr *Init = IList->getInit(Index);
945
946    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
947      // If we're not the subobject that matches up with the '{' for
948      // the designator, we shouldn't be handling the
949      // designator. Return immediately.
950      if (!SubobjectIsDesignatorContext)
951        return;
952
953      // Handle this designated initializer. Field will be updated to
954      // the next field that we'll be initializing.
955      if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
956                                     DeclType, &Field, 0, Index,
957                                     StructuredList, StructuredIndex,
958                                     true, TopLevelObject))
959        hadError = true;
960
961      InitializedSomething = true;
962      continue;
963    }
964
965    if (Field == FieldEnd) {
966      // We've run out of fields. We're done.
967      break;
968    }
969
970    // We've already initialized a member of a union. We're done.
971    if (InitializedSomething && DeclType->isUnionType())
972      break;
973
974    // If we've hit the flexible array member at the end, we're done.
975    if (Field->getType()->isIncompleteArrayType())
976      break;
977
978    if (Field->isUnnamedBitfield()) {
979      // Don't initialize unnamed bitfields, e.g. "int : 20;"
980      ++Field;
981      continue;
982    }
983
984    CheckSubElementType(IList, Field->getType(), Index,
985                        StructuredList, StructuredIndex);
986    InitializedSomething = true;
987
988    if (DeclType->isUnionType()) {
989      // Initialize the first field within the union.
990      StructuredList->setInitializedFieldInUnion(*Field);
991    }
992
993    ++Field;
994  }
995
996  if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
997      Index >= IList->getNumInits() ||
998      !isa<InitListExpr>(IList->getInit(Index)))
999    return;
1000
1001  // Handle GNU flexible array initializers.
1002  if (!TopLevelObject &&
1003      cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0) {
1004    SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1005                  diag::err_flexible_array_init_nonempty)
1006      << IList->getInit(Index)->getSourceRange().getBegin();
1007    SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1008      << *Field;
1009    hadError = true;
1010  }
1011
1012  CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1013                      StructuredIndex);
1014}
1015
1016/// @brief Check the well-formedness of a C99 designated initializer.
1017///
1018/// Determines whether the designated initializer @p DIE, which
1019/// resides at the given @p Index within the initializer list @p
1020/// IList, is well-formed for a current object of type @p DeclType
1021/// (C99 6.7.8). The actual subobject that this designator refers to
1022/// within the current subobject is returned in either
1023/// @p NextField or @p NextElementIndex (whichever is appropriate).
1024///
1025/// @param IList  The initializer list in which this designated
1026/// initializer occurs.
1027///
1028/// @param DIE  The designated initializer and its initialization
1029/// expression.
1030///
1031/// @param DeclType  The type of the "current object" (C99 6.7.8p17),
1032/// into which the designation in @p DIE should refer.
1033///
1034/// @param NextField  If non-NULL and the first designator in @p DIE is
1035/// a field, this will be set to the field declaration corresponding
1036/// to the field named by the designator.
1037///
1038/// @param NextElementIndex  If non-NULL and the first designator in @p
1039/// DIE is an array designator or GNU array-range designator, this
1040/// will be set to the last index initialized by this designator.
1041///
1042/// @param Index  Index into @p IList where the designated initializer
1043/// @p DIE occurs.
1044///
1045/// @param StructuredList  The initializer list expression that
1046/// describes all of the subobject initializers in the order they'll
1047/// actually be initialized.
1048///
1049/// @returns true if there was an error, false otherwise.
1050bool
1051InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1052                                      DesignatedInitExpr *DIE,
1053                                     DesignatedInitExpr::designators_iterator D,
1054                                      QualType &CurrentObjectType,
1055                                      RecordDecl::field_iterator *NextField,
1056                                      llvm::APSInt *NextElementIndex,
1057                                      unsigned &Index,
1058                                      InitListExpr *StructuredList,
1059                                      unsigned &StructuredIndex,
1060                                            bool FinishSubobjectInit,
1061                                            bool TopLevelObject) {
1062  if (D == DIE->designators_end()) {
1063    // Check the actual initialization for the designated object type.
1064    bool prevHadError = hadError;
1065
1066    // Temporarily remove the designator expression from the
1067    // initializer list that the child calls see, so that we don't try
1068    // to re-process the designator.
1069    unsigned OldIndex = Index;
1070    IList->setInit(OldIndex, DIE->getInit());
1071
1072    CheckSubElementType(IList, CurrentObjectType, Index,
1073                        StructuredList, StructuredIndex);
1074
1075    // Restore the designated initializer expression in the syntactic
1076    // form of the initializer list.
1077    if (IList->getInit(OldIndex) != DIE->getInit())
1078      DIE->setInit(IList->getInit(OldIndex));
1079    IList->setInit(OldIndex, DIE);
1080
1081    return hadError && !prevHadError;
1082  }
1083
1084  bool IsFirstDesignator = (D == DIE->designators_begin());
1085  assert((IsFirstDesignator || StructuredList) &&
1086         "Need a non-designated initializer list to start from");
1087
1088  // Determine the structural initializer list that corresponds to the
1089  // current subobject.
1090  StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1091    : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList,
1092                                 StructuredIndex,
1093                                 SourceRange(D->getStartLocation(),
1094                                             DIE->getSourceRange().getEnd()));
1095  assert(StructuredList && "Expected a structured initializer list");
1096
1097  if (D->isFieldDesignator()) {
1098    // C99 6.7.8p7:
1099    //
1100    //   If a designator has the form
1101    //
1102    //      . identifier
1103    //
1104    //   then the current object (defined below) shall have
1105    //   structure or union type and the identifier shall be the
1106    //   name of a member of that type.
1107    const RecordType *RT = CurrentObjectType->getAsRecordType();
1108    if (!RT) {
1109      SourceLocation Loc = D->getDotLoc();
1110      if (Loc.isInvalid())
1111        Loc = D->getFieldLoc();
1112      SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1113        << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
1114      ++Index;
1115      return true;
1116    }
1117
1118    // Note: we perform a linear search of the fields here, despite
1119    // the fact that we have a faster lookup method, because we always
1120    // need to compute the field's index.
1121    IdentifierInfo *FieldName = D->getFieldName();
1122    unsigned FieldIndex = 0;
1123    RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
1124                            FieldEnd = RT->getDecl()->field_end();
1125    for (; Field != FieldEnd; ++Field) {
1126      if (Field->isUnnamedBitfield())
1127        continue;
1128
1129      if (Field->getIdentifier() == FieldName)
1130        break;
1131
1132      ++FieldIndex;
1133    }
1134
1135    if (Field == FieldEnd) {
1136      // We did not find the field we're looking for. Produce a
1137      // suitable diagnostic and return a failure.
1138      DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1139      if (Lookup.first == Lookup.second) {
1140        // Name lookup didn't find anything.
1141        SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1142          << FieldName << CurrentObjectType;
1143      } else {
1144        // Name lookup found something, but it wasn't a field.
1145        SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1146          << FieldName;
1147        SemaRef.Diag((*Lookup.first)->getLocation(),
1148                      diag::note_field_designator_found);
1149      }
1150
1151      ++Index;
1152      return true;
1153    } else if (cast<RecordDecl>((*Field)->getDeclContext())
1154                 ->isAnonymousStructOrUnion()) {
1155      SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
1156        << FieldName
1157        << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
1158            (int)SemaRef.getLangOptions().CPlusPlus);
1159      SemaRef.Diag((*Field)->getLocation(), diag::note_field_designator_found);
1160      ++Index;
1161      return true;
1162    }
1163
1164    // All of the fields of a union are located at the same place in
1165    // the initializer list.
1166    if (RT->getDecl()->isUnion()) {
1167      FieldIndex = 0;
1168      StructuredList->setInitializedFieldInUnion(*Field);
1169    }
1170
1171    // Update the designator with the field declaration.
1172    D->setField(*Field);
1173
1174    // Make sure that our non-designated initializer list has space
1175    // for a subobject corresponding to this field.
1176    if (FieldIndex >= StructuredList->getNumInits())
1177      StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1178
1179    // This designator names a flexible array member.
1180    if (Field->getType()->isIncompleteArrayType()) {
1181      bool Invalid = false;
1182      DesignatedInitExpr::designators_iterator NextD = D;
1183      ++NextD;
1184      if (NextD != DIE->designators_end()) {
1185        // We can't designate an object within the flexible array
1186        // member (because GCC doesn't allow it).
1187        SemaRef.Diag(NextD->getStartLocation(),
1188                      diag::err_designator_into_flexible_array_member)
1189          << SourceRange(NextD->getStartLocation(),
1190                         DIE->getSourceRange().getEnd());
1191        SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1192          << *Field;
1193        Invalid = true;
1194      }
1195
1196      if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1197        // The initializer is not an initializer list.
1198        SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1199                      diag::err_flexible_array_init_needs_braces)
1200          << DIE->getInit()->getSourceRange();
1201        SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1202          << *Field;
1203        Invalid = true;
1204      }
1205
1206      // Handle GNU flexible array initializers.
1207      if (!Invalid && !TopLevelObject &&
1208          cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
1209        SemaRef.Diag(DIE->getSourceRange().getBegin(),
1210                      diag::err_flexible_array_init_nonempty)
1211          << DIE->getSourceRange().getBegin();
1212        SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1213          << *Field;
1214        Invalid = true;
1215      }
1216
1217      if (Invalid) {
1218        ++Index;
1219        return true;
1220      }
1221
1222      // Initialize the array.
1223      bool prevHadError = hadError;
1224      unsigned newStructuredIndex = FieldIndex;
1225      unsigned OldIndex = Index;
1226      IList->setInit(Index, DIE->getInit());
1227      CheckSubElementType(IList, Field->getType(), Index,
1228                          StructuredList, newStructuredIndex);
1229      IList->setInit(OldIndex, DIE);
1230      if (hadError && !prevHadError) {
1231        ++Field;
1232        ++FieldIndex;
1233        if (NextField)
1234          *NextField = Field;
1235        StructuredIndex = FieldIndex;
1236        return true;
1237      }
1238    } else {
1239      // Recurse to check later designated subobjects.
1240      QualType FieldType = (*Field)->getType();
1241      unsigned newStructuredIndex = FieldIndex;
1242      if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
1243                                     StructuredList, newStructuredIndex,
1244                                     true, false))
1245        return true;
1246    }
1247
1248    // Find the position of the next field to be initialized in this
1249    // subobject.
1250    ++Field;
1251    ++FieldIndex;
1252
1253    // If this the first designator, our caller will continue checking
1254    // the rest of this struct/class/union subobject.
1255    if (IsFirstDesignator) {
1256      if (NextField)
1257        *NextField = Field;
1258      StructuredIndex = FieldIndex;
1259      return false;
1260    }
1261
1262    if (!FinishSubobjectInit)
1263      return false;
1264
1265    // Check the remaining fields within this class/struct/union subobject.
1266    bool prevHadError = hadError;
1267    CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1268                          StructuredList, FieldIndex);
1269    return hadError && !prevHadError;
1270  }
1271
1272  // C99 6.7.8p6:
1273  //
1274  //   If a designator has the form
1275  //
1276  //      [ constant-expression ]
1277  //
1278  //   then the current object (defined below) shall have array
1279  //   type and the expression shall be an integer constant
1280  //   expression. If the array is of unknown size, any
1281  //   nonnegative value is valid.
1282  //
1283  // Additionally, cope with the GNU extension that permits
1284  // designators of the form
1285  //
1286  //      [ constant-expression ... constant-expression ]
1287  const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
1288  if (!AT) {
1289    SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1290      << CurrentObjectType;
1291    ++Index;
1292    return true;
1293  }
1294
1295  Expr *IndexExpr = 0;
1296  llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1297  if (D->isArrayDesignator()) {
1298    IndexExpr = DIE->getArrayIndex(*D);
1299
1300    bool ConstExpr
1301      = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef.Context);
1302    assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
1303
1304    DesignatedEndIndex = DesignatedStartIndex;
1305  } else {
1306    assert(D->isArrayRangeDesignator() && "Need array-range designator");
1307
1308    bool StartConstExpr
1309      = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex,
1310                                                           SemaRef.Context);
1311    assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr;
1312
1313    bool EndConstExpr
1314      = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex,
1315                                                         SemaRef.Context);
1316    assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr;
1317
1318    IndexExpr = DIE->getArrayRangeEnd(*D);
1319
1320    if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue())
1321      FullyStructuredList->sawArrayRangeDesignator();
1322  }
1323
1324  if (isa<ConstantArrayType>(AT)) {
1325    llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
1326    DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1327    DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1328    DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1329    DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1330    if (DesignatedEndIndex >= MaxElements) {
1331      SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1332                    diag::err_array_designator_too_large)
1333        << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1334        << IndexExpr->getSourceRange();
1335      ++Index;
1336      return true;
1337    }
1338  } else {
1339    // Make sure the bit-widths and signedness match.
1340    if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1341      DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
1342    else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth())
1343      DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1344    DesignatedStartIndex.setIsUnsigned(true);
1345    DesignatedEndIndex.setIsUnsigned(true);
1346  }
1347
1348  // Make sure that our non-designated initializer list has space
1349  // for a subobject corresponding to this array element.
1350  if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
1351    StructuredList->resizeInits(SemaRef.Context,
1352                                DesignatedEndIndex.getZExtValue() + 1);
1353
1354  // Repeatedly perform subobject initializations in the range
1355  // [DesignatedStartIndex, DesignatedEndIndex].
1356
1357  // Move to the next designator
1358  unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1359  unsigned OldIndex = Index;
1360  ++D;
1361  while (DesignatedStartIndex <= DesignatedEndIndex) {
1362    // Recurse to check later designated subobjects.
1363    QualType ElementType = AT->getElementType();
1364    Index = OldIndex;
1365    if (CheckDesignatedInitializer(IList, DIE, D, ElementType, 0, 0, Index,
1366                                   StructuredList, ElementIndex,
1367                                   (DesignatedStartIndex == DesignatedEndIndex),
1368                                   false))
1369      return true;
1370
1371    // Move to the next index in the array that we'll be initializing.
1372    ++DesignatedStartIndex;
1373    ElementIndex = DesignatedStartIndex.getZExtValue();
1374  }
1375
1376  // If this the first designator, our caller will continue checking
1377  // the rest of this array subobject.
1378  if (IsFirstDesignator) {
1379    if (NextElementIndex)
1380      *NextElementIndex = DesignatedStartIndex;
1381    StructuredIndex = ElementIndex;
1382    return false;
1383  }
1384
1385  if (!FinishSubobjectInit)
1386    return false;
1387
1388  // Check the remaining elements within this array subobject.
1389  bool prevHadError = hadError;
1390  CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
1391                 StructuredList, ElementIndex);
1392  return hadError && !prevHadError;
1393}
1394
1395// Get the structured initializer list for a subobject of type
1396// @p CurrentObjectType.
1397InitListExpr *
1398InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1399                                            QualType CurrentObjectType,
1400                                            InitListExpr *StructuredList,
1401                                            unsigned StructuredIndex,
1402                                            SourceRange InitRange) {
1403  Expr *ExistingInit = 0;
1404  if (!StructuredList)
1405    ExistingInit = SyntacticToSemantic[IList];
1406  else if (StructuredIndex < StructuredList->getNumInits())
1407    ExistingInit = StructuredList->getInit(StructuredIndex);
1408
1409  if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1410    return Result;
1411
1412  if (ExistingInit) {
1413    // We are creating an initializer list that initializes the
1414    // subobjects of the current object, but there was already an
1415    // initialization that completely initialized the current
1416    // subobject, e.g., by a compound literal:
1417    //
1418    // struct X { int a, b; };
1419    // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1420    //
1421    // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1422    // designated initializer re-initializes the whole
1423    // subobject [0], overwriting previous initializers.
1424    SemaRef.Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides)
1425      << InitRange;
1426    SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
1427                  diag::note_previous_initializer)
1428      << /*FIXME:has side effects=*/0
1429      << ExistingInit->getSourceRange();
1430  }
1431
1432  SourceLocation StartLoc;
1433  if (Index < IList->getNumInits())
1434    StartLoc = IList->getInit(Index)->getSourceRange().getBegin();
1435  InitListExpr *Result
1436    = new (SemaRef.Context) InitListExpr(StartLoc, 0, 0,
1437                                          IList->getSourceRange().getEnd());
1438  Result->setType(CurrentObjectType);
1439
1440  // Link this new initializer list into the structured initializer
1441  // lists.
1442  if (StructuredList)
1443    StructuredList->updateInit(StructuredIndex, Result);
1444  else {
1445    Result->setSyntacticForm(IList);
1446    SyntacticToSemantic[IList] = Result;
1447  }
1448
1449  return Result;
1450}
1451
1452/// Update the initializer at index @p StructuredIndex within the
1453/// structured initializer list to the value @p expr.
1454void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1455                                                  unsigned &StructuredIndex,
1456                                                  Expr *expr) {
1457  // No structured initializer list to update
1458  if (!StructuredList)
1459    return;
1460
1461  if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1462    // This initializer overwrites a previous initializer. Warn.
1463    SemaRef.Diag(expr->getSourceRange().getBegin(),
1464                  diag::warn_initializer_overrides)
1465      << expr->getSourceRange();
1466    SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
1467                  diag::note_previous_initializer)
1468      << /*FIXME:has side effects=*/0
1469      << PrevInit->getSourceRange();
1470  }
1471
1472  ++StructuredIndex;
1473}
1474
1475/// Check that the given Index expression is a valid array designator
1476/// value. This is essentailly just a wrapper around
1477/// Expr::isIntegerConstantExpr that also checks for negative values
1478/// and produces a reasonable diagnostic if there is a
1479/// failure. Returns true if there was an error, false otherwise.  If
1480/// everything went okay, Value will receive the value of the constant
1481/// expression.
1482static bool
1483CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
1484  SourceLocation Loc = Index->getSourceRange().getBegin();
1485
1486  // Make sure this is an integer constant expression.
1487  if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
1488    return Self.Diag(Loc, diag::err_array_designator_nonconstant)
1489      << Index->getSourceRange();
1490
1491  // Make sure this constant expression is non-negative.
1492  llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
1493                    Value.isUnsigned());
1494  if (Value < Zero)
1495    return Self.Diag(Loc, diag::err_array_designator_negative)
1496      << Value.toString(10) << Index->getSourceRange();
1497
1498  Value.setIsUnsigned(true);
1499  return false;
1500}
1501
1502Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1503                                                        SourceLocation Loc,
1504                                                        bool UsedColonSyntax,
1505                                                        OwningExprResult Init) {
1506  typedef DesignatedInitExpr::Designator ASTDesignator;
1507
1508  bool Invalid = false;
1509  llvm::SmallVector<ASTDesignator, 32> Designators;
1510  llvm::SmallVector<Expr *, 32> InitExpressions;
1511
1512  // Build designators and check array designator expressions.
1513  for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1514    const Designator &D = Desig.getDesignator(Idx);
1515    switch (D.getKind()) {
1516    case Designator::FieldDesignator:
1517      Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1518                                          D.getFieldLoc()));
1519      break;
1520
1521    case Designator::ArrayDesignator: {
1522      Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1523      llvm::APSInt IndexValue;
1524      if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
1525        Invalid = true;
1526      else {
1527        Designators.push_back(ASTDesignator(InitExpressions.size(),
1528                                            D.getLBracketLoc(),
1529                                            D.getRBracketLoc()));
1530        InitExpressions.push_back(Index);
1531      }
1532      break;
1533    }
1534
1535    case Designator::ArrayRangeDesignator: {
1536      Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1537      Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1538      llvm::APSInt StartValue;
1539      llvm::APSInt EndValue;
1540      if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
1541          CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
1542        Invalid = true;
1543      else {
1544        // Make sure we're comparing values with the same bit width.
1545        if (StartValue.getBitWidth() > EndValue.getBitWidth())
1546          EndValue.extend(StartValue.getBitWidth());
1547        else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1548          StartValue.extend(EndValue.getBitWidth());
1549
1550        if (EndValue < StartValue) {
1551          Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1552            << StartValue.toString(10) << EndValue.toString(10)
1553            << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1554          Invalid = true;
1555        } else {
1556          Designators.push_back(ASTDesignator(InitExpressions.size(),
1557                                              D.getLBracketLoc(),
1558                                              D.getEllipsisLoc(),
1559                                              D.getRBracketLoc()));
1560          InitExpressions.push_back(StartIndex);
1561          InitExpressions.push_back(EndIndex);
1562        }
1563      }
1564      break;
1565    }
1566    }
1567  }
1568
1569  if (Invalid || Init.isInvalid())
1570    return ExprError();
1571
1572  // Clear out the expressions within the designation.
1573  Desig.ClearExprs(*this);
1574
1575  DesignatedInitExpr *DIE
1576    = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
1577                                 &InitExpressions[0], InitExpressions.size(),
1578                                 Loc, UsedColonSyntax,
1579                                 static_cast<Expr *>(Init.release()));
1580  return Owned(DIE);
1581}
1582
1583bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
1584  InitListChecker CheckInitList(*this, InitList, DeclType);
1585  if (!CheckInitList.HadError())
1586    InitList = CheckInitList.getFullyStructuredList();
1587
1588  return CheckInitList.HadError();
1589}
1590
1591/// \brief Diagnose any semantic errors with value-initialization of
1592/// the given type.
1593///
1594/// Value-initialization effectively zero-initializes any types
1595/// without user-declared constructors, and calls the default
1596/// constructor for a for any type that has a user-declared
1597/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1598/// a type with a user-declared constructor does not have an
1599/// accessible, non-deleted default constructor. In C, everything can
1600/// be value-initialized, which corresponds to C's notion of
1601/// initializing objects with static storage duration when no
1602/// initializer is provided for that object.
1603///
1604/// \returns true if there was an error, false otherwise.
1605bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1606  // C++ [dcl.init]p5:
1607  //
1608  //   To value-initialize an object of type T means:
1609
1610  //     -- if T is an array type, then each element is value-initialized;
1611  if (const ArrayType *AT = Context.getAsArrayType(Type))
1612    return CheckValueInitialization(AT->getElementType(), Loc);
1613
1614  if (const RecordType *RT = Type->getAsRecordType()) {
1615    if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1616      // -- if T is a class type (clause 9) with a user-declared
1617      //    constructor (12.1), then the default constructor for T is
1618      //    called (and the initialization is ill-formed if T has no
1619      //    accessible default constructor);
1620      if (ClassDecl->hasUserDeclaredConstructor())
1621        // FIXME: Eventually, we'll need to put the constructor decl
1622        // into the AST.
1623        return PerformInitializationByConstructor(Type, 0, 0, Loc,
1624                                                  SourceRange(Loc),
1625                                                  DeclarationName(),
1626                                                  IK_Direct);
1627    }
1628  }
1629
1630  if (Type->isReferenceType()) {
1631    // C++ [dcl.init]p5:
1632    //   [...] A program that calls for default-initialization or
1633    //   value-initialization of an entity of reference type is
1634    //   ill-formed. [...]
1635    // FIXME: Once we have code that goes through this path, add an
1636    // actual diagnostic :)
1637  }
1638
1639  return false;
1640}
1641