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