SemaInit.cpp revision 34e7946831a63f96d3ba3478c74ca8e25ee52d7e
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.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/Parse/Designator.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/Basic/DiagnosticSema.h"
20using namespace clang;
21
22/// Recursively replaces NULL values within the given initializer list
23/// with expressions that perform value-initialization of the
24/// appropriate type.
25static void fillInValueInitializations(ASTContext &Context, InitListExpr *ILE) {
26  assert((ILE->getType() != Context.VoidTy) && "Should not have void type");
27  if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
28    unsigned Init = 0, NumInits = ILE->getNumInits();
29    for (RecordDecl::field_iterator Field = RType->getDecl()->field_begin(),
30                                 FieldEnd = RType->getDecl()->field_end();
31         Field != FieldEnd; ++Field) {
32      if (Field->isUnnamedBitfield())
33        continue;
34
35      if (Init >= NumInits)
36        break;
37
38      // FIXME: Check for fields with reference type in C++?
39      if (!ILE->getInit(Init))
40        ILE->setInit(Init,
41                     new (Context) CXXZeroInitValueExpr(Field->getType(),
42                                                        SourceLocation(),
43                                                        SourceLocation()));
44      else if (InitListExpr *InnerILE = dyn_cast<InitListExpr>(ILE->getInit(Init)))
45        fillInValueInitializations(Context, InnerILE);
46      ++Init;
47    }
48
49    return;
50  }
51
52  QualType ElementType;
53
54  if (const ArrayType *AType = Context.getAsArrayType(ILE->getType()))
55    ElementType = AType->getElementType();
56  else if (const VectorType *VType = ILE->getType()->getAsVectorType())
57    ElementType = VType->getElementType();
58  else
59    ElementType = ILE->getType();
60
61  for (unsigned Init = 0, NumInits = ILE->getNumInits(); Init != NumInits;
62       ++Init) {
63    if (!ILE->getInit(Init))
64      ILE->setInit(Init, new (Context) CXXZeroInitValueExpr(ElementType,
65                                                            SourceLocation(),
66                                                            SourceLocation()));
67    else if (InitListExpr *InnerILE = dyn_cast<InitListExpr>(ILE->getInit(Init)))
68      fillInValueInitializations(Context, InnerILE);
69  }
70}
71
72InitListChecker::InitListChecker(Sema *S, InitListExpr *IL, QualType &T) {
73  hadError = false;
74  SemaRef = S;
75
76  unsigned newIndex = 0;
77  unsigned newStructuredIndex = 0;
78  FullyStructuredList
79    = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, SourceRange());
80  CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex);
81
82  if (!hadError) {
83    fillInValueInitializations(SemaRef->Context, FullyStructuredList);
84  }
85}
86
87int InitListChecker::numArrayElements(QualType DeclType) {
88  // FIXME: use a proper constant
89  int maxElements = 0x7FFFFFFF;
90  if (const ConstantArrayType *CAT =
91        SemaRef->Context.getAsConstantArrayType(DeclType)) {
92    maxElements = static_cast<int>(CAT->getSize().getZExtValue());
93  }
94  return maxElements;
95}
96
97int InitListChecker::numStructUnionElements(QualType DeclType) {
98  RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
99  int InitializableMembers = 0;
100  for (RecordDecl::field_iterator Field = structDecl->field_begin(),
101                               FieldEnd = structDecl->field_end();
102       Field != FieldEnd; ++Field) {
103    if ((*Field)->getIdentifier() || !(*Field)->isBitField())
104      ++InitializableMembers;
105  }
106  if (structDecl->isUnion())
107    return std::min(InitializableMembers, 1);
108  return InitializableMembers - structDecl->hasFlexibleArrayMember();
109}
110
111void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
112                                            QualType T, unsigned &Index,
113                                            InitListExpr *StructuredList,
114                                            unsigned &StructuredIndex) {
115  int maxElements = 0;
116
117  if (T->isArrayType())
118    maxElements = numArrayElements(T);
119  else if (T->isStructureType() || T->isUnionType())
120    maxElements = numStructUnionElements(T);
121  else if (T->isVectorType())
122    maxElements = T->getAsVectorType()->getNumElements();
123  else
124    assert(0 && "CheckImplicitInitList(): Illegal type");
125
126  // FIXME: Perhaps we should move this warning elsewhere?
127  if (maxElements == 0) {
128    SemaRef->Diag(ParentIList->getInit(Index)->getLocStart(),
129                  diag::err_implicit_empty_initializer);
130    ++Index;
131    hadError = true;
132    return;
133  }
134
135  // Build a structured initializer list corresponding to this subobject.
136  InitListExpr *StructuredSubobjectInitList
137    = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
138                                 StructuredIndex,
139                                 ParentIList->getInit(Index)->getSourceRange());
140  unsigned StructuredSubobjectInitIndex = 0;
141
142  // Check the element types and build the structural subobject.
143  CheckListElementTypes(ParentIList, T, false, Index,
144                        StructuredSubobjectInitList,
145                        StructuredSubobjectInitIndex);
146}
147
148void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
149                                            unsigned &Index,
150                                            InitListExpr *StructuredList,
151                                            unsigned &StructuredIndex) {
152  assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
153  SyntacticToSemantic[IList] = StructuredList;
154  StructuredList->setSyntacticForm(IList);
155  CheckListElementTypes(IList, T, true, Index, StructuredList,
156                        StructuredIndex);
157  IList->setType(T);
158  StructuredList->setType(T);
159  if (hadError)
160    return;
161
162  if (Index < IList->getNumInits()) {
163    // We have leftover initializers
164    if (IList->getNumInits() > 0 &&
165        SemaRef->IsStringLiteralInit(IList->getInit(Index), T)) {
166      // Special-case
167      SemaRef->Diag(IList->getInit(Index)->getLocStart(),
168                    diag::err_excess_initializers_in_char_array_initializer)
169        << IList->getInit(Index)->getSourceRange();
170      hadError = true;
171    } else if (!T->isIncompleteType()) {
172      // Don't warn for incomplete types, since we'll get an error elsewhere
173      SemaRef->Diag(IList->getInit(Index)->getLocStart(),
174                    diag::warn_excess_initializers)
175        << IList->getInit(Index)->getSourceRange();
176    }
177  }
178
179  if (T->isScalarType())
180    SemaRef->Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
181      << IList->getSourceRange();
182}
183
184void InitListChecker::CheckListElementTypes(InitListExpr *IList,
185                                            QualType &DeclType,
186                                            bool SubobjectIsDesignatorContext,
187                                            unsigned &Index,
188                                            InitListExpr *StructuredList,
189                                            unsigned &StructuredIndex) {
190  if (DeclType->isScalarType()) {
191    CheckScalarType(IList, DeclType, 0, Index, StructuredList, StructuredIndex);
192  } else if (DeclType->isVectorType()) {
193    CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
194  } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
195    if (DeclType->isStructureType() || DeclType->isUnionType()) {
196      RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
197      CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
198                            SubobjectIsDesignatorContext, Index,
199                            StructuredList, StructuredIndex);
200    } else if (DeclType->isArrayType()) {
201      llvm::APSInt Zero(
202                      SemaRef->Context.getTypeSize(SemaRef->Context.getSizeType()),
203                      false);
204      CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
205                     StructuredList, StructuredIndex);
206    }
207    else
208      assert(0 && "Aggregate that isn't a structure or array?!");
209  } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
210    // This type is invalid, issue a diagnostic.
211    ++Index;
212    SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
213      << DeclType;
214    hadError = true;
215  } else {
216    // In C, all types are either scalars or aggregates, but
217    // additional handling is needed here for C++ (and possibly others?).
218    assert(0 && "Unsupported initializer type");
219  }
220}
221
222void InitListChecker::CheckSubElementType(InitListExpr *IList,
223                                          QualType ElemType,
224                                          Expr *expr,
225                                          unsigned &Index,
226                                          InitListExpr *StructuredList,
227                                          unsigned &StructuredIndex) {
228  if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
229    unsigned newIndex = 0;
230    unsigned newStructuredIndex = 0;
231    InitListExpr *newStructuredList
232      = getStructuredSubobjectInit(IList, Index, ElemType,
233                                   StructuredList, StructuredIndex,
234                                   SubInitList->getSourceRange());
235    CheckExplicitInitList(SubInitList, ElemType, newIndex,
236                          newStructuredList, newStructuredIndex);
237    ++StructuredIndex;
238    ++Index;
239  } else if (StringLiteral *lit =
240             SemaRef->IsStringLiteralInit(expr, ElemType)) {
241    SemaRef->CheckStringLiteralInit(lit, ElemType);
242    UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
243    ++Index;
244  } else if (ElemType->isScalarType()) {
245    CheckScalarType(IList, ElemType, expr, Index, StructuredList,
246                    StructuredIndex);
247  } else if (expr->getType()->getAsRecordType() &&
248             SemaRef->Context.typesAreCompatible(
249               expr->getType().getUnqualifiedType(),
250               ElemType.getUnqualifiedType())) {
251    UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
252    ++Index;
253    // FIXME: Add checking
254  } else {
255    CheckImplicitInitList(IList, ElemType, Index, StructuredList,
256                          StructuredIndex);
257    ++StructuredIndex;
258 }
259}
260
261void InitListChecker::CheckScalarType(InitListExpr *IList, QualType &DeclType,
262                                      Expr *expr, unsigned &Index,
263                                      InitListExpr *StructuredList,
264                                      unsigned &StructuredIndex) {
265  if (Index < IList->getNumInits()) {
266    if (!expr)
267      expr = IList->getInit(Index);
268    if (isa<InitListExpr>(expr)) {
269      SemaRef->Diag(IList->getLocStart(),
270                    diag::err_many_braces_around_scalar_init)
271        << IList->getSourceRange();
272      hadError = true;
273      ++Index;
274      ++StructuredIndex;
275      return;
276    } else if (isa<DesignatedInitExpr>(expr)) {
277      SemaRef->Diag(expr->getSourceRange().getBegin(),
278                    diag::err_designator_for_scalar_init)
279        << DeclType << expr->getSourceRange();
280      hadError = true;
281      ++Index;
282      ++StructuredIndex;
283      return;
284    }
285
286    Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
287    if (SemaRef->CheckSingleInitializer(expr, DeclType, false))
288      hadError = true; // types weren't compatible.
289    else if (savExpr != expr) {
290      // The type was promoted, update initializer list.
291      if (DesignatedInitExpr *DIE
292            = dyn_cast<DesignatedInitExpr>(IList->getInit(Index)))
293        DIE->setInit(expr);
294      else
295        IList->setInit(Index, expr);
296
297    }
298    if (hadError)
299      ++StructuredIndex;
300    else
301      UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
302    ++Index;
303  } else {
304    SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
305      << IList->getSourceRange();
306    hadError = true;
307    ++Index;
308    ++StructuredIndex;
309    return;
310  }
311}
312
313void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
314                                      unsigned &Index,
315                                      InitListExpr *StructuredList,
316                                      unsigned &StructuredIndex) {
317  if (Index < IList->getNumInits()) {
318    const VectorType *VT = DeclType->getAsVectorType();
319    int maxElements = VT->getNumElements();
320    QualType elementType = VT->getElementType();
321
322    for (int i = 0; i < maxElements; ++i) {
323      // Don't attempt to go past the end of the init list
324      if (Index >= IList->getNumInits())
325        break;
326      CheckSubElementType(IList, elementType, IList->getInit(Index), Index,
327                          StructuredList, StructuredIndex);
328    }
329  }
330}
331
332void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
333                                     llvm::APSInt elementIndex,
334                                     bool SubobjectIsDesignatorContext,
335                                     unsigned &Index,
336                                     InitListExpr *StructuredList,
337                                     unsigned &StructuredIndex) {
338  // Check for the special-case of initializing an array with a string.
339  if (Index < IList->getNumInits()) {
340    if (StringLiteral *lit =
341        SemaRef->IsStringLiteralInit(IList->getInit(Index), DeclType)) {
342      SemaRef->CheckStringLiteralInit(lit, DeclType);
343      // We place the string literal directly into the resulting
344      // initializer list. This is the only place where the structure
345      // of the structured initializer list doesn't match exactly,
346      // because doing so would involve allocating one character
347      // constant for each string.
348      UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
349      StructuredList->resizeInits(SemaRef->Context, StructuredIndex);
350      ++Index;
351      return;
352    }
353  }
354  if (const VariableArrayType *VAT =
355        SemaRef->Context.getAsVariableArrayType(DeclType)) {
356    // Check for VLAs; in standard C it would be possible to check this
357    // earlier, but I don't know where clang accepts VLAs (gcc accepts
358    // them in all sorts of strange places).
359    SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
360                  diag::err_variable_object_no_init)
361      << VAT->getSizeExpr()->getSourceRange();
362    hadError = true;
363    ++Index;
364    ++StructuredIndex;
365    return;
366  }
367
368  // We might know the maximum number of elements in advance.
369  llvm::APSInt maxElements(elementIndex.getBitWidth(),
370                           elementIndex.isUnsigned());
371  bool maxElementsKnown = false;
372  if (const ConstantArrayType *CAT =
373        SemaRef->Context.getAsConstantArrayType(DeclType)) {
374    maxElements = CAT->getSize();
375    elementIndex.extOrTrunc(maxElements.getBitWidth());
376    elementIndex.setIsUnsigned(maxElements.isUnsigned());
377    maxElementsKnown = true;
378  }
379
380  QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
381                             ->getElementType();
382  while (Index < IList->getNumInits()) {
383    Expr *Init = IList->getInit(Index);
384    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
385      // If we're not the subobject that matches up with the '{' for
386      // the designator, we shouldn't be handling the
387      // designator. Return immediately.
388      if (!SubobjectIsDesignatorContext)
389        return;
390
391      // Handle this designated initializer. elementIndex will be
392      // updated to be the next array element we'll initialize.
393      if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
394                                     DeclType, 0, &elementIndex, Index,
395                                     StructuredList, StructuredIndex)) {
396        hadError = true;
397        continue;
398      }
399
400      if (elementIndex.getBitWidth() > maxElements.getBitWidth())
401        maxElements.extend(elementIndex.getBitWidth());
402      else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
403        elementIndex.extend(maxElements.getBitWidth());
404      elementIndex.setIsUnsigned(maxElements.isUnsigned());
405
406      // If the array is of incomplete type, keep track of the number of
407      // elements in the initializer.
408      if (!maxElementsKnown && elementIndex > maxElements)
409        maxElements = elementIndex;
410
411      continue;
412    }
413
414    // If we know the maximum number of elements, and we've already
415    // hit it, stop consuming elements in the initializer list.
416    if (maxElementsKnown && elementIndex == maxElements)
417      break;
418
419    // Check this element.
420    CheckSubElementType(IList, elementType, IList->getInit(Index), Index,
421                        StructuredList, StructuredIndex);
422    ++elementIndex;
423
424    // If the array is of incomplete type, keep track of the number of
425    // elements in the initializer.
426    if (!maxElementsKnown && elementIndex > maxElements)
427      maxElements = elementIndex;
428  }
429  if (DeclType->isIncompleteArrayType()) {
430    // If this is an incomplete array type, the actual type needs to
431    // be calculated here.
432    llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
433    if (maxElements == Zero) {
434      // Sizing an array implicitly to zero is not allowed by ISO C,
435      // but is supported by GNU.
436      SemaRef->Diag(IList->getLocStart(),
437                    diag::ext_typecheck_zero_array_size);
438    }
439
440    DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
441                                                     ArrayType::Normal, 0);
442  }
443}
444
445void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
446                                            QualType DeclType,
447                                            RecordDecl::field_iterator Field,
448                                            bool SubobjectIsDesignatorContext,
449                                            unsigned &Index,
450                                            InitListExpr *StructuredList,
451                                            unsigned &StructuredIndex) {
452  RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
453
454  // If the record is invalid, some of it's members are invalid. To avoid
455  // confusion, we forgo checking the intializer for the entire record.
456  if (structDecl->isInvalidDecl()) {
457    hadError = true;
458    return;
459  }
460  // If structDecl is a forward declaration, this loop won't do
461  // anything except look at designated initializers; That's okay,
462  // because an error should get printed out elsewhere. It might be
463  // worthwhile to skip over the rest of the initializer, though.
464  RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
465  RecordDecl::field_iterator FieldEnd = RD->field_end();
466  while (Index < IList->getNumInits()) {
467    Expr *Init = IList->getInit(Index);
468
469    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
470      // If we're not the subobject that matches up with the '{' for
471      // the designator, we shouldn't be handling the
472      // designator. Return immediately.
473      if (!SubobjectIsDesignatorContext)
474        return;
475
476      // Handle this designated initializer. Field will be updated to
477      // the next field that we'll be initializing.
478      if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
479                                     DeclType, &Field, 0, Index,
480                                     StructuredList, StructuredIndex))
481        hadError = true;
482
483      continue;
484    }
485
486    if (Field == FieldEnd) {
487      // We've run out of fields. We're done.
488      break;
489    }
490
491    // If we've hit the flexible array member at the end, we're done.
492    if (Field->getType()->isIncompleteArrayType())
493      break;
494
495    if (!Field->getIdentifier() && Field->isBitField()) {
496      // Don't initialize unnamed bitfields, e.g. "int : 20;"
497      ++Field;
498      continue;
499    }
500
501    CheckSubElementType(IList, Field->getType(), IList->getInit(Index), Index,
502                        StructuredList, StructuredIndex);
503    if (DeclType->isUnionType())
504      break;
505
506    ++Field;
507  }
508
509  // FIXME: Implement flexible array initialization GCC extension (it's a
510  // really messy extension to implement, unfortunately...the necessary
511  // information isn't actually even here!)
512}
513
514/// @brief Check the well-formedness of a C99 designated initializer.
515///
516/// Determines whether the designated initializer @p DIE, which
517/// resides at the given @p Index within the initializer list @p
518/// IList, is well-formed for a current object of type @p DeclType
519/// (C99 6.7.8). The actual subobject that this designator refers to
520/// within the current subobject is returned in either
521/// @p NextField or @p NextElementIndex (whichever is appropriate).
522///
523/// @param IList  The initializer list in which this designated
524/// initializer occurs.
525///
526/// @param DIE  The designated initializer and its initialization
527/// expression.
528///
529/// @param DeclType  The type of the "current object" (C99 6.7.8p17),
530/// into which the designation in @p DIE should refer.
531///
532/// @param NextField  If non-NULL and the first designator in @p DIE is
533/// a field, this will be set to the field declaration corresponding
534/// to the field named by the designator.
535///
536/// @param NextElementIndex  If non-NULL and the first designator in @p
537/// DIE is an array designator or GNU array-range designator, this
538/// will be set to the last index initialized by this designator.
539///
540/// @param Index  Index into @p IList where the designated initializer
541/// @p DIE occurs.
542///
543/// @param StructuredList  The initializer list expression that
544/// describes all of the subobject initializers in the order they'll
545/// actually be initialized.
546///
547/// @returns true if there was an error, false otherwise.
548bool
549InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
550                                      DesignatedInitExpr *DIE,
551                                      DesignatedInitExpr::designators_iterator D,
552                                      QualType &CurrentObjectType,
553                                      RecordDecl::field_iterator *NextField,
554                                      llvm::APSInt *NextElementIndex,
555                                      unsigned &Index,
556                                      InitListExpr *StructuredList,
557                                      unsigned &StructuredIndex,
558                                      bool FinishSubobjectInit) {
559  if (D == DIE->designators_end()) {
560    // Check the actual initialization for the designated object type.
561    bool prevHadError = hadError;
562    CheckSubElementType(IList, CurrentObjectType, DIE->getInit(), Index,
563                        StructuredList, StructuredIndex);
564    return hadError && !prevHadError;
565  }
566
567  bool IsFirstDesignator = (D == DIE->designators_begin());
568  assert((IsFirstDesignator || StructuredList) &&
569         "Need a non-designated initializer list to start from");
570
571  // Determine the structural initializer list that corresponds to the
572  // current subobject.
573  StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
574    : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList,
575                                 StructuredIndex,
576                                 SourceRange(D->getStartLocation(),
577                                             DIE->getSourceRange().getEnd()));
578  assert(StructuredList && "Expected a structured initializer list");
579
580  if (D->isFieldDesignator()) {
581    // C99 6.7.8p7:
582    //
583    //   If a designator has the form
584    //
585    //      . identifier
586    //
587    //   then the current object (defined below) shall have
588    //   structure or union type and the identifier shall be the
589    //   name of a member of that type.
590    const RecordType *RT = CurrentObjectType->getAsRecordType();
591    if (!RT) {
592      SourceLocation Loc = D->getDotLoc();
593      if (Loc.isInvalid())
594        Loc = D->getFieldLoc();
595      SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
596        << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
597      ++Index;
598      return true;
599    }
600
601    // Note: we perform a linear search of the fields here, despite
602    // the fact that we have a faster lookup method, because we always
603    // need to compute the field's index.
604    IdentifierInfo *FieldName = D->getFieldName();
605    unsigned FieldIndex = 0;
606    RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
607                            FieldEnd = RT->getDecl()->field_end();
608    for (; Field != FieldEnd; ++Field) {
609      if (Field->isUnnamedBitfield())
610        continue;
611
612      if (Field->getIdentifier() == FieldName)
613        break;
614
615      ++FieldIndex;
616    }
617
618    if (Field == FieldEnd) {
619      // We did not find the field we're looking for. Produce a
620      // suitable diagnostic and return a failure.
621      DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
622      if (Lookup.first == Lookup.second) {
623        // Name lookup didn't find anything.
624        SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
625          << FieldName << CurrentObjectType;
626      } else {
627        // Name lookup found something, but it wasn't a field.
628        SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
629          << FieldName;
630        SemaRef->Diag((*Lookup.first)->getLocation(),
631                      diag::note_field_designator_found);
632      }
633
634      ++Index;
635      return true;
636    } else if (cast<RecordDecl>((*Field)->getDeclContext())
637                 ->isAnonymousStructOrUnion()) {
638      SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
639        << FieldName
640        << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
641            (int)SemaRef->getLangOptions().CPlusPlus);
642      SemaRef->Diag((*Field)->getLocation(), diag::note_field_designator_found);
643      ++Index;
644      return true;
645    }
646
647    // All of the fields of a union are located at the same place in
648    // the initializer list.
649    if (RT->getDecl()->isUnion())
650      FieldIndex = 0;
651
652    // Update the designator with the field declaration.
653    D->setField(*Field);
654
655    // Make sure that our non-designated initializer list has space
656    // for a subobject corresponding to this field.
657    if (FieldIndex >= StructuredList->getNumInits())
658      StructuredList->resizeInits(SemaRef->Context, FieldIndex + 1);
659
660    // Recurse to check later designated subobjects.
661    QualType FieldType = (*Field)->getType();
662    unsigned newStructuredIndex = FieldIndex;
663    if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
664                                   StructuredList, newStructuredIndex))
665      return true;
666
667    // Find the position of the next field to be initialized in this
668    // subobject.
669    ++Field;
670    ++FieldIndex;
671
672    // If this the first designator, our caller will continue checking
673    // the rest of this struct/class/union subobject.
674    if (IsFirstDesignator) {
675      if (NextField)
676        *NextField = Field;
677      StructuredIndex = FieldIndex;
678      return false;
679    }
680
681    if (!FinishSubobjectInit)
682      return false;
683
684    // Check the remaining fields within this class/struct/union subobject.
685    bool prevHadError = hadError;
686    CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
687                          StructuredList, FieldIndex);
688    return hadError && !prevHadError;
689  }
690
691  // C99 6.7.8p6:
692  //
693  //   If a designator has the form
694  //
695  //      [ constant-expression ]
696  //
697  //   then the current object (defined below) shall have array
698  //   type and the expression shall be an integer constant
699  //   expression. If the array is of unknown size, any
700  //   nonnegative value is valid.
701  //
702  // Additionally, cope with the GNU extension that permits
703  // designators of the form
704  //
705  //      [ constant-expression ... constant-expression ]
706  const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
707  if (!AT) {
708    SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
709      << CurrentObjectType;
710    ++Index;
711    return true;
712  }
713
714  Expr *IndexExpr = 0;
715  llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
716  if (D->isArrayDesignator()) {
717    IndexExpr = DIE->getArrayIndex(*D);
718
719    bool ConstExpr
720      = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef->Context);
721    assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
722
723    DesignatedEndIndex = DesignatedStartIndex;
724  } else {
725    assert(D->isArrayRangeDesignator() && "Need array-range designator");
726
727    bool StartConstExpr
728      = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex,
729                                                           SemaRef->Context);
730    assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr;
731
732    bool EndConstExpr
733      = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex,
734                                                         SemaRef->Context);
735    assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr;
736
737    IndexExpr = DIE->getArrayRangeEnd(*D);
738
739    if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue())
740      SemaRef->Diag(D->getEllipsisLoc(),
741                    diag::warn_gnu_array_range_designator_side_effects)
742        << SourceRange(D->getLBracketLoc(), D->getRBracketLoc());
743  }
744
745  if (isa<ConstantArrayType>(AT)) {
746    llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
747    DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
748    DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
749    DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
750    DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
751    if (DesignatedEndIndex >= MaxElements) {
752      SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
753                    diag::err_array_designator_too_large)
754        << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
755        << IndexExpr->getSourceRange();
756      ++Index;
757      return true;
758    }
759  } else {
760    // Make sure the bit-widths and signedness match.
761    if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
762      DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
763    else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth())
764      DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
765    DesignatedStartIndex.setIsUnsigned(true);
766    DesignatedEndIndex.setIsUnsigned(true);
767  }
768
769  // Make sure that our non-designated initializer list has space
770  // for a subobject corresponding to this array element.
771  if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
772    StructuredList->resizeInits(SemaRef->Context,
773                                DesignatedEndIndex.getZExtValue() + 1);
774
775  // Repeatedly perform subobject initializations in the range
776  // [DesignatedStartIndex, DesignatedEndIndex].
777
778  // Move to the next designator
779  unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
780  unsigned OldIndex = Index;
781  ++D;
782  while (DesignatedStartIndex <= DesignatedEndIndex) {
783    // Recurse to check later designated subobjects.
784    QualType ElementType = AT->getElementType();
785    Index = OldIndex;
786    if (CheckDesignatedInitializer(IList, DIE, D, ElementType, 0, 0, Index,
787                                   StructuredList, ElementIndex,
788                                   (DesignatedStartIndex == DesignatedEndIndex)))
789      return true;
790
791    // Move to the next index in the array that we'll be initializing.
792    ++DesignatedStartIndex;
793    ElementIndex = DesignatedStartIndex.getZExtValue();
794  }
795
796  // If this the first designator, our caller will continue checking
797  // the rest of this array subobject.
798  if (IsFirstDesignator) {
799    if (NextElementIndex)
800      *NextElementIndex = DesignatedStartIndex;
801    StructuredIndex = ElementIndex;
802    return false;
803  }
804
805  if (!FinishSubobjectInit)
806    return false;
807
808  // Check the remaining elements within this array subobject.
809  bool prevHadError = hadError;
810  CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, true, Index,
811                 StructuredList, ElementIndex);
812  return hadError && !prevHadError;
813}
814
815// Get the structured initializer list for a subobject of type
816// @p CurrentObjectType.
817InitListExpr *
818InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
819                                            QualType CurrentObjectType,
820                                            InitListExpr *StructuredList,
821                                            unsigned StructuredIndex,
822                                            SourceRange InitRange) {
823  Expr *ExistingInit = 0;
824  if (!StructuredList)
825    ExistingInit = SyntacticToSemantic[IList];
826  else if (StructuredIndex < StructuredList->getNumInits())
827    ExistingInit = StructuredList->getInit(StructuredIndex);
828
829  if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
830    return Result;
831
832  if (ExistingInit) {
833    // We are creating an initializer list that initializes the
834    // subobjects of the current object, but there was already an
835    // initialization that completely initialized the current
836    // subobject, e.g., by a compound literal:
837    //
838    // struct X { int a, b; };
839    // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
840    //
841    // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
842    // designated initializer re-initializes the whole
843    // subobject [0], overwriting previous initializers.
844    SemaRef->Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides)
845      << InitRange;
846    SemaRef->Diag(ExistingInit->getSourceRange().getBegin(),
847                  diag::note_previous_initializer)
848      << ExistingInit->hasSideEffects(SemaRef->Context)
849      << ExistingInit->getSourceRange();
850  }
851
852  InitListExpr *Result
853    = new (SemaRef->Context) InitListExpr(SourceLocation(), 0, 0,
854                                          SourceLocation());
855  Result->setType(CurrentObjectType);
856
857  // Link this new initializer list into the structured initializer
858  // lists.
859  if (StructuredList)
860    StructuredList->updateInit(StructuredIndex, Result);
861  else {
862    Result->setSyntacticForm(IList);
863    SyntacticToSemantic[IList] = Result;
864  }
865
866  return Result;
867}
868
869/// Update the initializer at index @p StructuredIndex within the
870/// structured initializer list to the value @p expr.
871void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
872                                                  unsigned &StructuredIndex,
873                                                  Expr *expr) {
874  // No structured initializer list to update
875  if (!StructuredList)
876    return;
877
878  if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
879    // This initializer overwrites a previous initializer. Warn.
880    SemaRef->Diag(expr->getSourceRange().getBegin(),
881                  diag::warn_initializer_overrides)
882      << expr->getSourceRange();
883    SemaRef->Diag(PrevInit->getSourceRange().getBegin(),
884                  diag::note_previous_initializer)
885      << (int)PrevInit->hasSideEffects(SemaRef->Context)
886      << PrevInit->getSourceRange();
887  }
888
889  ++StructuredIndex;
890}
891
892/// Check that the given Index expression is a valid array designator
893/// value. This is essentailly just a wrapper around
894/// Expr::isIntegerConstantExpr that also checks for negative values
895/// and produces a reasonable diagnostic if there is a
896/// failure. Returns true if there was an error, false otherwise.  If
897/// everything went okay, Value will receive the value of the constant
898/// expression.
899static bool
900CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
901  SourceLocation Loc = Index->getSourceRange().getBegin();
902
903  // Make sure this is an integer constant expression.
904  if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
905    return Self.Diag(Loc, diag::err_array_designator_nonconstant)
906      << Index->getSourceRange();
907
908  // Make sure this constant expression is non-negative.
909  llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
910                    Value.isUnsigned());
911  if (Value < Zero)
912    return Self.Diag(Loc, diag::err_array_designator_negative)
913      << Value.toString(10) << Index->getSourceRange();
914
915  Value.setIsUnsigned(true);
916  return false;
917}
918
919Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
920                                                        SourceLocation Loc,
921                                                        bool UsedColonSyntax,
922                                                        OwningExprResult Init) {
923  typedef DesignatedInitExpr::Designator ASTDesignator;
924
925  bool Invalid = false;
926  llvm::SmallVector<ASTDesignator, 32> Designators;
927  llvm::SmallVector<Expr *, 32> InitExpressions;
928
929  // Build designators and check array designator expressions.
930  for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
931    const Designator &D = Desig.getDesignator(Idx);
932    switch (D.getKind()) {
933    case Designator::FieldDesignator:
934      Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
935                                          D.getFieldLoc()));
936      break;
937
938    case Designator::ArrayDesignator: {
939      Expr *Index = static_cast<Expr *>(D.getArrayIndex());
940      llvm::APSInt IndexValue;
941      if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
942        Invalid = true;
943      else {
944        Designators.push_back(ASTDesignator(InitExpressions.size(),
945                                            D.getLBracketLoc(),
946                                            D.getRBracketLoc()));
947        InitExpressions.push_back(Index);
948      }
949      break;
950    }
951
952    case Designator::ArrayRangeDesignator: {
953      Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
954      Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
955      llvm::APSInt StartValue;
956      llvm::APSInt EndValue;
957      if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
958          CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
959        Invalid = true;
960      else {
961        // Make sure we're comparing values with the same bit width.
962        if (StartValue.getBitWidth() > EndValue.getBitWidth())
963          EndValue.extend(StartValue.getBitWidth());
964        else if (StartValue.getBitWidth() < EndValue.getBitWidth())
965          StartValue.extend(EndValue.getBitWidth());
966
967        if (EndValue < StartValue) {
968          Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
969            << StartValue.toString(10) << EndValue.toString(10)
970            << StartIndex->getSourceRange() << EndIndex->getSourceRange();
971          Invalid = true;
972        } else {
973          Designators.push_back(ASTDesignator(InitExpressions.size(),
974                                              D.getLBracketLoc(),
975                                              D.getEllipsisLoc(),
976                                              D.getRBracketLoc()));
977          InitExpressions.push_back(StartIndex);
978          InitExpressions.push_back(EndIndex);
979        }
980      }
981      break;
982    }
983    }
984  }
985
986  if (Invalid || Init.isInvalid())
987    return ExprError();
988
989  // Clear out the expressions within the designation.
990  Desig.ClearExprs(*this);
991
992  DesignatedInitExpr *DIE
993    = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
994                                 &InitExpressions[0], InitExpressions.size(),
995                                 Loc, UsedColonSyntax,
996                                 static_cast<Expr *>(Init.release()));
997  return Owned(DIE);
998}
999