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