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