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