SemaInit.cpp revision 81359b0a88510087a873de771f9a2f5ee7ed97d9
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 "clang/Sema/Initialization.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/ExprObjC.h"
19#include "clang/AST/TypeLoc.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Sema/Designator.h"
22#include "clang/Sema/Lookup.h"
23#include "clang/Sema/SemaInternal.h"
24#include "llvm/ADT/APInt.h"
25#include "llvm/ADT/SmallString.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/raw_ostream.h"
28#include <map>
29using namespace clang;
30
31//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
35/// \brief Check whether T is compatible with a wide character type (wchar_t,
36/// char16_t or char32_t).
37static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
38  if (Context.typesAreCompatible(Context.getWideCharType(), T))
39    return true;
40  if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
41    return Context.typesAreCompatible(Context.Char16Ty, T) ||
42           Context.typesAreCompatible(Context.Char32Ty, T);
43  }
44  return false;
45}
46
47enum StringInitFailureKind {
48  SIF_None,
49  SIF_NarrowStringIntoWideChar,
50  SIF_WideStringIntoChar,
51  SIF_IncompatWideStringIntoWideChar,
52  SIF_Other
53};
54
55/// \brief Check whether the array of type AT can be initialized by the Init
56/// expression by means of string initialization. Returns SIF_None if so,
57/// otherwise returns a StringInitFailureKind that describes why the
58/// initialization would not work.
59static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
60                                          ASTContext &Context) {
61  if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
62    return SIF_Other;
63
64  // See if this is a string literal or @encode.
65  Init = Init->IgnoreParens();
66
67  // Handle @encode, which is a narrow string.
68  if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
69    return SIF_None;
70
71  // Otherwise we can only handle string literals.
72  StringLiteral *SL = dyn_cast<StringLiteral>(Init);
73  if (SL == 0)
74    return SIF_Other;
75
76  const QualType ElemTy =
77      Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
78
79  switch (SL->getKind()) {
80  case StringLiteral::Ascii:
81  case StringLiteral::UTF8:
82    // char array can be initialized with a narrow string.
83    // Only allow char x[] = "foo";  not char x[] = L"foo";
84    if (ElemTy->isCharType())
85      return SIF_None;
86    if (IsWideCharCompatible(ElemTy, Context))
87      return SIF_NarrowStringIntoWideChar;
88    return SIF_Other;
89  // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
90  // "An array with element type compatible with a qualified or unqualified
91  // version of wchar_t, char16_t, or char32_t may be initialized by a wide
92  // string literal with the corresponding encoding prefix (L, u, or U,
93  // respectively), optionally enclosed in braces.
94  case StringLiteral::UTF16:
95    if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
96      return SIF_None;
97    if (ElemTy->isCharType())
98      return SIF_WideStringIntoChar;
99    if (IsWideCharCompatible(ElemTy, Context))
100      return SIF_IncompatWideStringIntoWideChar;
101    return SIF_Other;
102  case StringLiteral::UTF32:
103    if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
104      return SIF_None;
105    if (ElemTy->isCharType())
106      return SIF_WideStringIntoChar;
107    if (IsWideCharCompatible(ElemTy, Context))
108      return SIF_IncompatWideStringIntoWideChar;
109    return SIF_Other;
110  case StringLiteral::Wide:
111    if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
112      return SIF_None;
113    if (ElemTy->isCharType())
114      return SIF_WideStringIntoChar;
115    if (IsWideCharCompatible(ElemTy, Context))
116      return SIF_IncompatWideStringIntoWideChar;
117    return SIF_Other;
118  }
119
120  llvm_unreachable("missed a StringLiteral kind?");
121}
122
123static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
124                                          ASTContext &Context) {
125  const ArrayType *arrayType = Context.getAsArrayType(declType);
126  if (!arrayType)
127    return SIF_Other;
128  return IsStringInit(init, arrayType, Context);
129}
130
131/// Update the type of a string literal, including any surrounding parentheses,
132/// to match the type of the object which it is initializing.
133static void updateStringLiteralType(Expr *E, QualType Ty) {
134  while (true) {
135    E->setType(Ty);
136    if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
137      break;
138    else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
139      E = PE->getSubExpr();
140    else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
141      E = UO->getSubExpr();
142    else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
143      E = GSE->getResultExpr();
144    else
145      llvm_unreachable("unexpected expr in string literal init");
146  }
147}
148
149static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
150                            Sema &S) {
151  // Get the length of the string as parsed.
152  uint64_t StrLength =
153    cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
154
155
156  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
157    // C99 6.7.8p14. We have an array of character type with unknown size
158    // being initialized to a string literal.
159    llvm::APInt ConstVal(32, StrLength);
160    // Return a new array type (C99 6.7.8p22).
161    DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
162                                           ConstVal,
163                                           ArrayType::Normal, 0);
164    updateStringLiteralType(Str, DeclT);
165    return;
166  }
167
168  const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
169
170  // We have an array of character type with known size.  However,
171  // the size may be smaller or larger than the string we are initializing.
172  // FIXME: Avoid truncation for 64-bit length strings.
173  if (S.getLangOpts().CPlusPlus) {
174    if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
175      // For Pascal strings it's OK to strip off the terminating null character,
176      // so the example below is valid:
177      //
178      // unsigned char a[2] = "\pa";
179      if (SL->isPascal())
180        StrLength--;
181    }
182
183    // [dcl.init.string]p2
184    if (StrLength > CAT->getSize().getZExtValue())
185      S.Diag(Str->getLocStart(),
186             diag::err_initializer_string_for_char_array_too_long)
187        << Str->getSourceRange();
188  } else {
189    // C99 6.7.8p14.
190    if (StrLength-1 > CAT->getSize().getZExtValue())
191      S.Diag(Str->getLocStart(),
192             diag::warn_initializer_string_for_char_array_too_long)
193        << Str->getSourceRange();
194  }
195
196  // Set the type to the actual size that we are initializing.  If we have
197  // something like:
198  //   char x[1] = "foo";
199  // then this will set the string literal's type to char[1].
200  updateStringLiteralType(Str, DeclT);
201}
202
203//===----------------------------------------------------------------------===//
204// Semantic checking for initializer lists.
205//===----------------------------------------------------------------------===//
206
207/// @brief Semantic checking for initializer lists.
208///
209/// The InitListChecker class contains a set of routines that each
210/// handle the initialization of a certain kind of entity, e.g.,
211/// arrays, vectors, struct/union types, scalars, etc. The
212/// InitListChecker itself performs a recursive walk of the subobject
213/// structure of the type to be initialized, while stepping through
214/// the initializer list one element at a time. The IList and Index
215/// parameters to each of the Check* routines contain the active
216/// (syntactic) initializer list and the index into that initializer
217/// list that represents the current initializer. Each routine is
218/// responsible for moving that Index forward as it consumes elements.
219///
220/// Each Check* routine also has a StructuredList/StructuredIndex
221/// arguments, which contains the current "structured" (semantic)
222/// initializer list and the index into that initializer list where we
223/// are copying initializers as we map them over to the semantic
224/// list. Once we have completed our recursive walk of the subobject
225/// structure, we will have constructed a full semantic initializer
226/// list.
227///
228/// C99 designators cause changes in the initializer list traversal,
229/// because they make the initialization "jump" into a specific
230/// subobject and then continue the initialization from that
231/// point. CheckDesignatedInitializer() recursively steps into the
232/// designated subobject and manages backing out the recursion to
233/// initialize the subobjects after the one designated.
234namespace {
235class InitListChecker {
236  Sema &SemaRef;
237  bool hadError;
238  bool VerifyOnly; // no diagnostics, no structure building
239  llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
240  InitListExpr *FullyStructuredList;
241
242  void CheckImplicitInitList(const InitializedEntity &Entity,
243                             InitListExpr *ParentIList, QualType T,
244                             unsigned &Index, InitListExpr *StructuredList,
245                             unsigned &StructuredIndex);
246  void CheckExplicitInitList(const InitializedEntity &Entity,
247                             InitListExpr *IList, QualType &T,
248                             unsigned &Index, InitListExpr *StructuredList,
249                             unsigned &StructuredIndex,
250                             bool TopLevelObject = false);
251  void CheckListElementTypes(const InitializedEntity &Entity,
252                             InitListExpr *IList, QualType &DeclType,
253                             bool SubobjectIsDesignatorContext,
254                             unsigned &Index,
255                             InitListExpr *StructuredList,
256                             unsigned &StructuredIndex,
257                             bool TopLevelObject = false);
258  void CheckSubElementType(const InitializedEntity &Entity,
259                           InitListExpr *IList, QualType ElemType,
260                           unsigned &Index,
261                           InitListExpr *StructuredList,
262                           unsigned &StructuredIndex);
263  void CheckComplexType(const InitializedEntity &Entity,
264                        InitListExpr *IList, QualType DeclType,
265                        unsigned &Index,
266                        InitListExpr *StructuredList,
267                        unsigned &StructuredIndex);
268  void CheckScalarType(const InitializedEntity &Entity,
269                       InitListExpr *IList, QualType DeclType,
270                       unsigned &Index,
271                       InitListExpr *StructuredList,
272                       unsigned &StructuredIndex);
273  void CheckReferenceType(const InitializedEntity &Entity,
274                          InitListExpr *IList, QualType DeclType,
275                          unsigned &Index,
276                          InitListExpr *StructuredList,
277                          unsigned &StructuredIndex);
278  void CheckVectorType(const InitializedEntity &Entity,
279                       InitListExpr *IList, QualType DeclType, unsigned &Index,
280                       InitListExpr *StructuredList,
281                       unsigned &StructuredIndex);
282  void CheckStructUnionTypes(const InitializedEntity &Entity,
283                             InitListExpr *IList, QualType DeclType,
284                             RecordDecl::field_iterator Field,
285                             bool SubobjectIsDesignatorContext, unsigned &Index,
286                             InitListExpr *StructuredList,
287                             unsigned &StructuredIndex,
288                             bool TopLevelObject = false);
289  void CheckArrayType(const InitializedEntity &Entity,
290                      InitListExpr *IList, QualType &DeclType,
291                      llvm::APSInt elementIndex,
292                      bool SubobjectIsDesignatorContext, unsigned &Index,
293                      InitListExpr *StructuredList,
294                      unsigned &StructuredIndex);
295  bool CheckDesignatedInitializer(const InitializedEntity &Entity,
296                                  InitListExpr *IList, DesignatedInitExpr *DIE,
297                                  unsigned DesigIdx,
298                                  QualType &CurrentObjectType,
299                                  RecordDecl::field_iterator *NextField,
300                                  llvm::APSInt *NextElementIndex,
301                                  unsigned &Index,
302                                  InitListExpr *StructuredList,
303                                  unsigned &StructuredIndex,
304                                  bool FinishSubobjectInit,
305                                  bool TopLevelObject);
306  InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
307                                           QualType CurrentObjectType,
308                                           InitListExpr *StructuredList,
309                                           unsigned StructuredIndex,
310                                           SourceRange InitRange);
311  void UpdateStructuredListElement(InitListExpr *StructuredList,
312                                   unsigned &StructuredIndex,
313                                   Expr *expr);
314  int numArrayElements(QualType DeclType);
315  int numStructUnionElements(QualType DeclType);
316
317  void FillInValueInitForField(unsigned Init, FieldDecl *Field,
318                               const InitializedEntity &ParentEntity,
319                               InitListExpr *ILE, bool &RequiresSecondPass);
320  void FillInValueInitializations(const InitializedEntity &Entity,
321                                  InitListExpr *ILE, bool &RequiresSecondPass);
322  bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
323                              Expr *InitExpr, FieldDecl *Field,
324                              bool TopLevelObject);
325  void CheckValueInitializable(const InitializedEntity &Entity);
326
327public:
328  InitListChecker(Sema &S, const InitializedEntity &Entity,
329                  InitListExpr *IL, QualType &T, bool VerifyOnly);
330  bool HadError() { return hadError; }
331
332  // @brief Retrieves the fully-structured initializer list used for
333  // semantic analysis and code generation.
334  InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
335};
336} // end anonymous namespace
337
338void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
339  assert(VerifyOnly &&
340         "CheckValueInitializable is only inteded for verification mode.");
341
342  SourceLocation Loc;
343  InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
344                                                            true);
345  InitializationSequence InitSeq(SemaRef, Entity, Kind, None);
346  if (InitSeq.Failed())
347    hadError = true;
348}
349
350void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
351                                        const InitializedEntity &ParentEntity,
352                                              InitListExpr *ILE,
353                                              bool &RequiresSecondPass) {
354  SourceLocation Loc = ILE->getLocStart();
355  unsigned NumInits = ILE->getNumInits();
356  InitializedEntity MemberEntity
357    = InitializedEntity::InitializeMember(Field, &ParentEntity);
358  if (Init >= NumInits || !ILE->getInit(Init)) {
359    // If there's no explicit initializer but we have a default initializer, use
360    // that. This only happens in C++1y, since classes with default
361    // initializers are not aggregates in C++11.
362    if (Field->hasInClassInitializer()) {
363      Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
364                                             ILE->getRBraceLoc(), Field);
365      if (Init < NumInits)
366        ILE->setInit(Init, DIE);
367      else {
368        ILE->updateInit(SemaRef.Context, Init, DIE);
369        RequiresSecondPass = true;
370      }
371      return;
372    }
373
374    // FIXME: We probably don't need to handle references
375    // specially here, since value-initialization of references is
376    // handled in InitializationSequence.
377    if (Field->getType()->isReferenceType()) {
378      // C++ [dcl.init.aggr]p9:
379      //   If an incomplete or empty initializer-list leaves a
380      //   member of reference type uninitialized, the program is
381      //   ill-formed.
382      SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
383        << Field->getType()
384        << ILE->getSyntacticForm()->getSourceRange();
385      SemaRef.Diag(Field->getLocation(),
386                   diag::note_uninit_reference_member);
387      hadError = true;
388      return;
389    }
390
391    InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
392                                                              true);
393    InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, None);
394    if (!InitSeq) {
395      InitSeq.Diagnose(SemaRef, MemberEntity, Kind, None);
396      hadError = true;
397      return;
398    }
399
400    ExprResult MemberInit
401      = InitSeq.Perform(SemaRef, MemberEntity, Kind, None);
402    if (MemberInit.isInvalid()) {
403      hadError = true;
404      return;
405    }
406
407    if (hadError) {
408      // Do nothing
409    } else if (Init < NumInits) {
410      ILE->setInit(Init, MemberInit.takeAs<Expr>());
411    } else if (InitSeq.isConstructorInitialization()) {
412      // Value-initialization requires a constructor call, so
413      // extend the initializer list to include the constructor
414      // call and make a note that we'll need to take another pass
415      // through the initializer list.
416      ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
417      RequiresSecondPass = true;
418    }
419  } else if (InitListExpr *InnerILE
420               = dyn_cast<InitListExpr>(ILE->getInit(Init)))
421    FillInValueInitializations(MemberEntity, InnerILE,
422                               RequiresSecondPass);
423}
424
425/// Recursively replaces NULL values within the given initializer list
426/// with expressions that perform value-initialization of the
427/// appropriate type.
428void
429InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
430                                            InitListExpr *ILE,
431                                            bool &RequiresSecondPass) {
432  assert((ILE->getType() != SemaRef.Context.VoidTy) &&
433         "Should not have void type");
434  SourceLocation Loc = ILE->getLocStart();
435  if (ILE->getSyntacticForm())
436    Loc = ILE->getSyntacticForm()->getLocStart();
437
438  if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
439    const RecordDecl *RDecl = RType->getDecl();
440    if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
441      FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
442                              Entity, ILE, RequiresSecondPass);
443    else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
444             cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
445      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
446                                      FieldEnd = RDecl->field_end();
447           Field != FieldEnd; ++Field) {
448        if (Field->hasInClassInitializer()) {
449          FillInValueInitForField(0, *Field, Entity, ILE, RequiresSecondPass);
450          break;
451        }
452      }
453    } else {
454      unsigned Init = 0;
455      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
456                                      FieldEnd = RDecl->field_end();
457           Field != FieldEnd; ++Field) {
458        if (Field->isUnnamedBitfield())
459          continue;
460
461        if (hadError)
462          return;
463
464        FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
465        if (hadError)
466          return;
467
468        ++Init;
469
470        // Only look at the first initialization of a union.
471        if (RDecl->isUnion())
472          break;
473      }
474    }
475
476    return;
477  }
478
479  QualType ElementType;
480
481  InitializedEntity ElementEntity = Entity;
482  unsigned NumInits = ILE->getNumInits();
483  unsigned NumElements = NumInits;
484  if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
485    ElementType = AType->getElementType();
486    if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
487      NumElements = CAType->getSize().getZExtValue();
488    ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
489                                                         0, Entity);
490  } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
491    ElementType = VType->getElementType();
492    NumElements = VType->getNumElements();
493    ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
494                                                         0, Entity);
495  } else
496    ElementType = ILE->getType();
497
498
499  for (unsigned Init = 0; Init != NumElements; ++Init) {
500    if (hadError)
501      return;
502
503    if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
504        ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
505      ElementEntity.setElementIndex(Init);
506
507    Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
508    if (!InitExpr && !ILE->hasArrayFiller()) {
509      InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
510                                                                true);
511      InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, None);
512      if (!InitSeq) {
513        InitSeq.Diagnose(SemaRef, ElementEntity, Kind, None);
514        hadError = true;
515        return;
516      }
517
518      ExprResult ElementInit
519        = InitSeq.Perform(SemaRef, ElementEntity, Kind, None);
520      if (ElementInit.isInvalid()) {
521        hadError = true;
522        return;
523      }
524
525      if (hadError) {
526        // Do nothing
527      } else if (Init < NumInits) {
528        // For arrays, just set the expression used for value-initialization
529        // of the "holes" in the array.
530        if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
531          ILE->setArrayFiller(ElementInit.takeAs<Expr>());
532        else
533          ILE->setInit(Init, ElementInit.takeAs<Expr>());
534      } else {
535        // For arrays, just set the expression used for value-initialization
536        // of the rest of elements and exit.
537        if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
538          ILE->setArrayFiller(ElementInit.takeAs<Expr>());
539          return;
540        }
541
542        if (InitSeq.isConstructorInitialization()) {
543          // Value-initialization requires a constructor call, so
544          // extend the initializer list to include the constructor
545          // call and make a note that we'll need to take another pass
546          // through the initializer list.
547          ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
548          RequiresSecondPass = true;
549        }
550      }
551    } else if (InitListExpr *InnerILE
552                 = dyn_cast_or_null<InitListExpr>(InitExpr))
553      FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
554  }
555}
556
557
558InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
559                                 InitListExpr *IL, QualType &T,
560                                 bool VerifyOnly)
561  : SemaRef(S), VerifyOnly(VerifyOnly) {
562  hadError = false;
563
564  unsigned newIndex = 0;
565  unsigned newStructuredIndex = 0;
566  FullyStructuredList
567    = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
568  CheckExplicitInitList(Entity, IL, T, newIndex,
569                        FullyStructuredList, newStructuredIndex,
570                        /*TopLevelObject=*/true);
571
572  if (!hadError && !VerifyOnly) {
573    bool RequiresSecondPass = false;
574    FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
575    if (RequiresSecondPass && !hadError)
576      FillInValueInitializations(Entity, FullyStructuredList,
577                                 RequiresSecondPass);
578  }
579}
580
581int InitListChecker::numArrayElements(QualType DeclType) {
582  // FIXME: use a proper constant
583  int maxElements = 0x7FFFFFFF;
584  if (const ConstantArrayType *CAT =
585        SemaRef.Context.getAsConstantArrayType(DeclType)) {
586    maxElements = static_cast<int>(CAT->getSize().getZExtValue());
587  }
588  return maxElements;
589}
590
591int InitListChecker::numStructUnionElements(QualType DeclType) {
592  RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
593  int InitializableMembers = 0;
594  for (RecordDecl::field_iterator
595         Field = structDecl->field_begin(),
596         FieldEnd = structDecl->field_end();
597       Field != FieldEnd; ++Field) {
598    if (!Field->isUnnamedBitfield())
599      ++InitializableMembers;
600  }
601  if (structDecl->isUnion())
602    return std::min(InitializableMembers, 1);
603  return InitializableMembers - structDecl->hasFlexibleArrayMember();
604}
605
606void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
607                                            InitListExpr *ParentIList,
608                                            QualType T, unsigned &Index,
609                                            InitListExpr *StructuredList,
610                                            unsigned &StructuredIndex) {
611  int maxElements = 0;
612
613  if (T->isArrayType())
614    maxElements = numArrayElements(T);
615  else if (T->isRecordType())
616    maxElements = numStructUnionElements(T);
617  else if (T->isVectorType())
618    maxElements = T->getAs<VectorType>()->getNumElements();
619  else
620    llvm_unreachable("CheckImplicitInitList(): Illegal type");
621
622  if (maxElements == 0) {
623    if (!VerifyOnly)
624      SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
625                   diag::err_implicit_empty_initializer);
626    ++Index;
627    hadError = true;
628    return;
629  }
630
631  // Build a structured initializer list corresponding to this subobject.
632  InitListExpr *StructuredSubobjectInitList
633    = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
634                                 StructuredIndex,
635          SourceRange(ParentIList->getInit(Index)->getLocStart(),
636                      ParentIList->getSourceRange().getEnd()));
637  unsigned StructuredSubobjectInitIndex = 0;
638
639  // Check the element types and build the structural subobject.
640  unsigned StartIndex = Index;
641  CheckListElementTypes(Entity, ParentIList, T,
642                        /*SubobjectIsDesignatorContext=*/false, Index,
643                        StructuredSubobjectInitList,
644                        StructuredSubobjectInitIndex);
645
646  if (!VerifyOnly) {
647    StructuredSubobjectInitList->setType(T);
648
649    unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
650    // Update the structured sub-object initializer so that it's ending
651    // range corresponds with the end of the last initializer it used.
652    if (EndIndex < ParentIList->getNumInits()) {
653      SourceLocation EndLoc
654        = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
655      StructuredSubobjectInitList->setRBraceLoc(EndLoc);
656    }
657
658    // Complain about missing braces.
659    if (T->isArrayType() || T->isRecordType()) {
660      SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
661                   diag::warn_missing_braces)
662        << StructuredSubobjectInitList->getSourceRange()
663        << FixItHint::CreateInsertion(
664              StructuredSubobjectInitList->getLocStart(), "{")
665        << FixItHint::CreateInsertion(
666              SemaRef.PP.getLocForEndOfToken(
667                                      StructuredSubobjectInitList->getLocEnd()),
668              "}");
669    }
670  }
671}
672
673void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
674                                            InitListExpr *IList, QualType &T,
675                                            unsigned &Index,
676                                            InitListExpr *StructuredList,
677                                            unsigned &StructuredIndex,
678                                            bool TopLevelObject) {
679  assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
680  if (!VerifyOnly) {
681    SyntacticToSemantic[IList] = StructuredList;
682    StructuredList->setSyntacticForm(IList);
683  }
684  CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
685                        Index, StructuredList, StructuredIndex, TopLevelObject);
686  if (!VerifyOnly) {
687    QualType ExprTy = T;
688    if (!ExprTy->isArrayType())
689      ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
690    IList->setType(ExprTy);
691    StructuredList->setType(ExprTy);
692  }
693  if (hadError)
694    return;
695
696  if (Index < IList->getNumInits()) {
697    // We have leftover initializers
698    if (VerifyOnly) {
699      if (SemaRef.getLangOpts().CPlusPlus ||
700          (SemaRef.getLangOpts().OpenCL &&
701           IList->getType()->isVectorType())) {
702        hadError = true;
703      }
704      return;
705    }
706
707    if (StructuredIndex == 1 &&
708        IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
709            SIF_None) {
710      unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
711      if (SemaRef.getLangOpts().CPlusPlus) {
712        DK = diag::err_excess_initializers_in_char_array_initializer;
713        hadError = true;
714      }
715      // Special-case
716      SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
717        << IList->getInit(Index)->getSourceRange();
718    } else if (!T->isIncompleteType()) {
719      // Don't complain for incomplete types, since we'll get an error
720      // elsewhere
721      QualType CurrentObjectType = StructuredList->getType();
722      int initKind =
723        CurrentObjectType->isArrayType()? 0 :
724        CurrentObjectType->isVectorType()? 1 :
725        CurrentObjectType->isScalarType()? 2 :
726        CurrentObjectType->isUnionType()? 3 :
727        4;
728
729      unsigned DK = diag::warn_excess_initializers;
730      if (SemaRef.getLangOpts().CPlusPlus) {
731        DK = diag::err_excess_initializers;
732        hadError = true;
733      }
734      if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
735        DK = diag::err_excess_initializers;
736        hadError = true;
737      }
738
739      SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
740        << initKind << IList->getInit(Index)->getSourceRange();
741    }
742  }
743
744  if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
745      !TopLevelObject)
746    SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
747      << IList->getSourceRange()
748      << FixItHint::CreateRemoval(IList->getLocStart())
749      << FixItHint::CreateRemoval(IList->getLocEnd());
750}
751
752void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
753                                            InitListExpr *IList,
754                                            QualType &DeclType,
755                                            bool SubobjectIsDesignatorContext,
756                                            unsigned &Index,
757                                            InitListExpr *StructuredList,
758                                            unsigned &StructuredIndex,
759                                            bool TopLevelObject) {
760  if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
761    // Explicitly braced initializer for complex type can be real+imaginary
762    // parts.
763    CheckComplexType(Entity, IList, DeclType, Index,
764                     StructuredList, StructuredIndex);
765  } else if (DeclType->isScalarType()) {
766    CheckScalarType(Entity, IList, DeclType, Index,
767                    StructuredList, StructuredIndex);
768  } else if (DeclType->isVectorType()) {
769    CheckVectorType(Entity, IList, DeclType, Index,
770                    StructuredList, StructuredIndex);
771  } else if (DeclType->isRecordType()) {
772    assert(DeclType->isAggregateType() &&
773           "non-aggregate records should be handed in CheckSubElementType");
774    RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
775    CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
776                          SubobjectIsDesignatorContext, Index,
777                          StructuredList, StructuredIndex,
778                          TopLevelObject);
779  } else if (DeclType->isArrayType()) {
780    llvm::APSInt Zero(
781                    SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
782                    false);
783    CheckArrayType(Entity, IList, DeclType, Zero,
784                   SubobjectIsDesignatorContext, Index,
785                   StructuredList, StructuredIndex);
786  } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
787    // This type is invalid, issue a diagnostic.
788    ++Index;
789    if (!VerifyOnly)
790      SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
791        << DeclType;
792    hadError = true;
793  } else if (DeclType->isReferenceType()) {
794    CheckReferenceType(Entity, IList, DeclType, Index,
795                       StructuredList, StructuredIndex);
796  } else if (DeclType->isObjCObjectType()) {
797    if (!VerifyOnly)
798      SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
799        << DeclType;
800    hadError = true;
801  } else {
802    if (!VerifyOnly)
803      SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
804        << DeclType;
805    hadError = true;
806  }
807}
808
809void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
810                                          InitListExpr *IList,
811                                          QualType ElemType,
812                                          unsigned &Index,
813                                          InitListExpr *StructuredList,
814                                          unsigned &StructuredIndex) {
815  Expr *expr = IList->getInit(Index);
816
817  if (ElemType->isReferenceType())
818    return CheckReferenceType(Entity, IList, ElemType, Index,
819                              StructuredList, StructuredIndex);
820
821  if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
822    if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
823      unsigned newIndex = 0;
824      unsigned newStructuredIndex = 0;
825      InitListExpr *newStructuredList
826        = getStructuredSubobjectInit(IList, Index, ElemType,
827                                     StructuredList, StructuredIndex,
828                                     SubInitList->getSourceRange());
829      CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
830                            newStructuredList, newStructuredIndex);
831      ++StructuredIndex;
832      ++Index;
833      return;
834    }
835    assert(SemaRef.getLangOpts().CPlusPlus &&
836           "non-aggregate records are only possible in C++");
837    // C++ initialization is handled later.
838  }
839
840  if (ElemType->isScalarType())
841    return CheckScalarType(Entity, IList, ElemType, Index,
842                           StructuredList, StructuredIndex);
843
844  if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
845    // arrayType can be incomplete if we're initializing a flexible
846    // array member.  There's nothing we can do with the completed
847    // type here, though.
848
849    if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
850      if (!VerifyOnly) {
851        CheckStringInit(expr, ElemType, arrayType, SemaRef);
852        UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
853      }
854      ++Index;
855      return;
856    }
857
858    // Fall through for subaggregate initialization.
859
860  } else if (SemaRef.getLangOpts().CPlusPlus) {
861    // C++ [dcl.init.aggr]p12:
862    //   All implicit type conversions (clause 4) are considered when
863    //   initializing the aggregate member with an initializer from
864    //   an initializer-list. If the initializer can initialize a
865    //   member, the member is initialized. [...]
866
867    // FIXME: Better EqualLoc?
868    InitializationKind Kind =
869      InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
870    InitializationSequence Seq(SemaRef, Entity, Kind, expr);
871
872    if (Seq) {
873      if (!VerifyOnly) {
874        ExprResult Result =
875          Seq.Perform(SemaRef, Entity, Kind, expr);
876        if (Result.isInvalid())
877          hadError = true;
878
879        UpdateStructuredListElement(StructuredList, StructuredIndex,
880                                    Result.takeAs<Expr>());
881      }
882      ++Index;
883      return;
884    }
885
886    // Fall through for subaggregate initialization
887  } else {
888    // C99 6.7.8p13:
889    //
890    //   The initializer for a structure or union object that has
891    //   automatic storage duration shall be either an initializer
892    //   list as described below, or a single expression that has
893    //   compatible structure or union type. In the latter case, the
894    //   initial value of the object, including unnamed members, is
895    //   that of the expression.
896    ExprResult ExprRes = SemaRef.Owned(expr);
897    if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
898        SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
899                                                 !VerifyOnly)
900          == Sema::Compatible) {
901      if (ExprRes.isInvalid())
902        hadError = true;
903      else {
904        ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
905          if (ExprRes.isInvalid())
906            hadError = true;
907      }
908      UpdateStructuredListElement(StructuredList, StructuredIndex,
909                                  ExprRes.takeAs<Expr>());
910      ++Index;
911      return;
912    }
913    ExprRes.release();
914    // Fall through for subaggregate initialization
915  }
916
917  // C++ [dcl.init.aggr]p12:
918  //
919  //   [...] Otherwise, if the member is itself a non-empty
920  //   subaggregate, brace elision is assumed and the initializer is
921  //   considered for the initialization of the first member of
922  //   the subaggregate.
923  if (!SemaRef.getLangOpts().OpenCL &&
924      (ElemType->isAggregateType() || ElemType->isVectorType())) {
925    CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
926                          StructuredIndex);
927    ++StructuredIndex;
928  } else {
929    if (!VerifyOnly) {
930      // We cannot initialize this element, so let
931      // PerformCopyInitialization produce the appropriate diagnostic.
932      SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
933                                        SemaRef.Owned(expr),
934                                        /*TopLevelOfInitList=*/true);
935    }
936    hadError = true;
937    ++Index;
938    ++StructuredIndex;
939  }
940}
941
942void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
943                                       InitListExpr *IList, QualType DeclType,
944                                       unsigned &Index,
945                                       InitListExpr *StructuredList,
946                                       unsigned &StructuredIndex) {
947  assert(Index == 0 && "Index in explicit init list must be zero");
948
949  // As an extension, clang supports complex initializers, which initialize
950  // a complex number component-wise.  When an explicit initializer list for
951  // a complex number contains two two initializers, this extension kicks in:
952  // it exepcts the initializer list to contain two elements convertible to
953  // the element type of the complex type. The first element initializes
954  // the real part, and the second element intitializes the imaginary part.
955
956  if (IList->getNumInits() != 2)
957    return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
958                           StructuredIndex);
959
960  // This is an extension in C.  (The builtin _Complex type does not exist
961  // in the C++ standard.)
962  if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
963    SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
964      << IList->getSourceRange();
965
966  // Initialize the complex number.
967  QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
968  InitializedEntity ElementEntity =
969    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
970
971  for (unsigned i = 0; i < 2; ++i) {
972    ElementEntity.setElementIndex(Index);
973    CheckSubElementType(ElementEntity, IList, elementType, Index,
974                        StructuredList, StructuredIndex);
975  }
976}
977
978
979void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
980                                      InitListExpr *IList, QualType DeclType,
981                                      unsigned &Index,
982                                      InitListExpr *StructuredList,
983                                      unsigned &StructuredIndex) {
984  if (Index >= IList->getNumInits()) {
985    if (!VerifyOnly)
986      SemaRef.Diag(IList->getLocStart(),
987                   SemaRef.getLangOpts().CPlusPlus11 ?
988                     diag::warn_cxx98_compat_empty_scalar_initializer :
989                     diag::err_empty_scalar_initializer)
990        << IList->getSourceRange();
991    hadError = !SemaRef.getLangOpts().CPlusPlus11;
992    ++Index;
993    ++StructuredIndex;
994    return;
995  }
996
997  Expr *expr = IList->getInit(Index);
998  if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
999    if (!VerifyOnly)
1000      SemaRef.Diag(SubIList->getLocStart(),
1001                   diag::warn_many_braces_around_scalar_init)
1002        << SubIList->getSourceRange();
1003
1004    CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1005                    StructuredIndex);
1006    return;
1007  } else if (isa<DesignatedInitExpr>(expr)) {
1008    if (!VerifyOnly)
1009      SemaRef.Diag(expr->getLocStart(),
1010                   diag::err_designator_for_scalar_init)
1011        << DeclType << expr->getSourceRange();
1012    hadError = true;
1013    ++Index;
1014    ++StructuredIndex;
1015    return;
1016  }
1017
1018  if (VerifyOnly) {
1019    if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1020      hadError = true;
1021    ++Index;
1022    return;
1023  }
1024
1025  ExprResult Result =
1026    SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1027                                      SemaRef.Owned(expr),
1028                                      /*TopLevelOfInitList=*/true);
1029
1030  Expr *ResultExpr = 0;
1031
1032  if (Result.isInvalid())
1033    hadError = true; // types weren't compatible.
1034  else {
1035    ResultExpr = Result.takeAs<Expr>();
1036
1037    if (ResultExpr != expr) {
1038      // The type was promoted, update initializer list.
1039      IList->setInit(Index, ResultExpr);
1040    }
1041  }
1042  if (hadError)
1043    ++StructuredIndex;
1044  else
1045    UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1046  ++Index;
1047}
1048
1049void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1050                                         InitListExpr *IList, QualType DeclType,
1051                                         unsigned &Index,
1052                                         InitListExpr *StructuredList,
1053                                         unsigned &StructuredIndex) {
1054  if (Index >= IList->getNumInits()) {
1055    // FIXME: It would be wonderful if we could point at the actual member. In
1056    // general, it would be useful to pass location information down the stack,
1057    // so that we know the location (or decl) of the "current object" being
1058    // initialized.
1059    if (!VerifyOnly)
1060      SemaRef.Diag(IList->getLocStart(),
1061                    diag::err_init_reference_member_uninitialized)
1062        << DeclType
1063        << IList->getSourceRange();
1064    hadError = true;
1065    ++Index;
1066    ++StructuredIndex;
1067    return;
1068  }
1069
1070  Expr *expr = IList->getInit(Index);
1071  if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1072    if (!VerifyOnly)
1073      SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1074        << DeclType << IList->getSourceRange();
1075    hadError = true;
1076    ++Index;
1077    ++StructuredIndex;
1078    return;
1079  }
1080
1081  if (VerifyOnly) {
1082    if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1083      hadError = true;
1084    ++Index;
1085    return;
1086  }
1087
1088  ExprResult Result =
1089    SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1090                                      SemaRef.Owned(expr),
1091                                      /*TopLevelOfInitList=*/true);
1092
1093  if (Result.isInvalid())
1094    hadError = true;
1095
1096  expr = Result.takeAs<Expr>();
1097  IList->setInit(Index, expr);
1098
1099  if (hadError)
1100    ++StructuredIndex;
1101  else
1102    UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1103  ++Index;
1104}
1105
1106void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1107                                      InitListExpr *IList, QualType DeclType,
1108                                      unsigned &Index,
1109                                      InitListExpr *StructuredList,
1110                                      unsigned &StructuredIndex) {
1111  const VectorType *VT = DeclType->getAs<VectorType>();
1112  unsigned maxElements = VT->getNumElements();
1113  unsigned numEltsInit = 0;
1114  QualType elementType = VT->getElementType();
1115
1116  if (Index >= IList->getNumInits()) {
1117    // Make sure the element type can be value-initialized.
1118    if (VerifyOnly)
1119      CheckValueInitializable(
1120          InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1121    return;
1122  }
1123
1124  if (!SemaRef.getLangOpts().OpenCL) {
1125    // If the initializing element is a vector, try to copy-initialize
1126    // instead of breaking it apart (which is doomed to failure anyway).
1127    Expr *Init = IList->getInit(Index);
1128    if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1129      if (VerifyOnly) {
1130        if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1131          hadError = true;
1132        ++Index;
1133        return;
1134      }
1135
1136      ExprResult Result =
1137        SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
1138                                          SemaRef.Owned(Init),
1139                                          /*TopLevelOfInitList=*/true);
1140
1141      Expr *ResultExpr = 0;
1142      if (Result.isInvalid())
1143        hadError = true; // types weren't compatible.
1144      else {
1145        ResultExpr = Result.takeAs<Expr>();
1146
1147        if (ResultExpr != Init) {
1148          // The type was promoted, update initializer list.
1149          IList->setInit(Index, ResultExpr);
1150        }
1151      }
1152      if (hadError)
1153        ++StructuredIndex;
1154      else
1155        UpdateStructuredListElement(StructuredList, StructuredIndex,
1156                                    ResultExpr);
1157      ++Index;
1158      return;
1159    }
1160
1161    InitializedEntity ElementEntity =
1162      InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1163
1164    for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1165      // Don't attempt to go past the end of the init list
1166      if (Index >= IList->getNumInits()) {
1167        if (VerifyOnly)
1168          CheckValueInitializable(ElementEntity);
1169        break;
1170      }
1171
1172      ElementEntity.setElementIndex(Index);
1173      CheckSubElementType(ElementEntity, IList, elementType, Index,
1174                          StructuredList, StructuredIndex);
1175    }
1176    return;
1177  }
1178
1179  InitializedEntity ElementEntity =
1180    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1181
1182  // OpenCL initializers allows vectors to be constructed from vectors.
1183  for (unsigned i = 0; i < maxElements; ++i) {
1184    // Don't attempt to go past the end of the init list
1185    if (Index >= IList->getNumInits())
1186      break;
1187
1188    ElementEntity.setElementIndex(Index);
1189
1190    QualType IType = IList->getInit(Index)->getType();
1191    if (!IType->isVectorType()) {
1192      CheckSubElementType(ElementEntity, IList, elementType, Index,
1193                          StructuredList, StructuredIndex);
1194      ++numEltsInit;
1195    } else {
1196      QualType VecType;
1197      const VectorType *IVT = IType->getAs<VectorType>();
1198      unsigned numIElts = IVT->getNumElements();
1199
1200      if (IType->isExtVectorType())
1201        VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1202      else
1203        VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1204                                                IVT->getVectorKind());
1205      CheckSubElementType(ElementEntity, IList, VecType, Index,
1206                          StructuredList, StructuredIndex);
1207      numEltsInit += numIElts;
1208    }
1209  }
1210
1211  // OpenCL requires all elements to be initialized.
1212  if (numEltsInit != maxElements) {
1213    if (!VerifyOnly)
1214      SemaRef.Diag(IList->getLocStart(),
1215                   diag::err_vector_incorrect_num_initializers)
1216        << (numEltsInit < maxElements) << maxElements << numEltsInit;
1217    hadError = true;
1218  }
1219}
1220
1221void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1222                                     InitListExpr *IList, QualType &DeclType,
1223                                     llvm::APSInt elementIndex,
1224                                     bool SubobjectIsDesignatorContext,
1225                                     unsigned &Index,
1226                                     InitListExpr *StructuredList,
1227                                     unsigned &StructuredIndex) {
1228  const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1229
1230  // Check for the special-case of initializing an array with a string.
1231  if (Index < IList->getNumInits()) {
1232    if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1233        SIF_None) {
1234      // We place the string literal directly into the resulting
1235      // initializer list. This is the only place where the structure
1236      // of the structured initializer list doesn't match exactly,
1237      // because doing so would involve allocating one character
1238      // constant for each string.
1239      if (!VerifyOnly) {
1240        CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1241        UpdateStructuredListElement(StructuredList, StructuredIndex,
1242                                    IList->getInit(Index));
1243        StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1244      }
1245      ++Index;
1246      return;
1247    }
1248  }
1249  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1250    // Check for VLAs; in standard C it would be possible to check this
1251    // earlier, but I don't know where clang accepts VLAs (gcc accepts
1252    // them in all sorts of strange places).
1253    if (!VerifyOnly)
1254      SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1255                    diag::err_variable_object_no_init)
1256        << VAT->getSizeExpr()->getSourceRange();
1257    hadError = true;
1258    ++Index;
1259    ++StructuredIndex;
1260    return;
1261  }
1262
1263  // We might know the maximum number of elements in advance.
1264  llvm::APSInt maxElements(elementIndex.getBitWidth(),
1265                           elementIndex.isUnsigned());
1266  bool maxElementsKnown = false;
1267  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1268    maxElements = CAT->getSize();
1269    elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1270    elementIndex.setIsUnsigned(maxElements.isUnsigned());
1271    maxElementsKnown = true;
1272  }
1273
1274  QualType elementType = arrayType->getElementType();
1275  while (Index < IList->getNumInits()) {
1276    Expr *Init = IList->getInit(Index);
1277    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1278      // If we're not the subobject that matches up with the '{' for
1279      // the designator, we shouldn't be handling the
1280      // designator. Return immediately.
1281      if (!SubobjectIsDesignatorContext)
1282        return;
1283
1284      // Handle this designated initializer. elementIndex will be
1285      // updated to be the next array element we'll initialize.
1286      if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1287                                     DeclType, 0, &elementIndex, Index,
1288                                     StructuredList, StructuredIndex, true,
1289                                     false)) {
1290        hadError = true;
1291        continue;
1292      }
1293
1294      if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1295        maxElements = maxElements.extend(elementIndex.getBitWidth());
1296      else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1297        elementIndex = elementIndex.extend(maxElements.getBitWidth());
1298      elementIndex.setIsUnsigned(maxElements.isUnsigned());
1299
1300      // If the array is of incomplete type, keep track of the number of
1301      // elements in the initializer.
1302      if (!maxElementsKnown && elementIndex > maxElements)
1303        maxElements = elementIndex;
1304
1305      continue;
1306    }
1307
1308    // If we know the maximum number of elements, and we've already
1309    // hit it, stop consuming elements in the initializer list.
1310    if (maxElementsKnown && elementIndex == maxElements)
1311      break;
1312
1313    InitializedEntity ElementEntity =
1314      InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1315                                           Entity);
1316    // Check this element.
1317    CheckSubElementType(ElementEntity, IList, elementType, Index,
1318                        StructuredList, StructuredIndex);
1319    ++elementIndex;
1320
1321    // If the array is of incomplete type, keep track of the number of
1322    // elements in the initializer.
1323    if (!maxElementsKnown && elementIndex > maxElements)
1324      maxElements = elementIndex;
1325  }
1326  if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1327    // If this is an incomplete array type, the actual type needs to
1328    // be calculated here.
1329    llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1330    if (maxElements == Zero) {
1331      // Sizing an array implicitly to zero is not allowed by ISO C,
1332      // but is supported by GNU.
1333      SemaRef.Diag(IList->getLocStart(),
1334                    diag::ext_typecheck_zero_array_size);
1335    }
1336
1337    DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1338                                                     ArrayType::Normal, 0);
1339  }
1340  if (!hadError && VerifyOnly) {
1341    // Check if there are any members of the array that get value-initialized.
1342    // If so, check if doing that is possible.
1343    // FIXME: This needs to detect holes left by designated initializers too.
1344    if (maxElementsKnown && elementIndex < maxElements)
1345      CheckValueInitializable(InitializedEntity::InitializeElement(
1346                                                  SemaRef.Context, 0, Entity));
1347  }
1348}
1349
1350bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1351                                             Expr *InitExpr,
1352                                             FieldDecl *Field,
1353                                             bool TopLevelObject) {
1354  // Handle GNU flexible array initializers.
1355  unsigned FlexArrayDiag;
1356  if (isa<InitListExpr>(InitExpr) &&
1357      cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1358    // Empty flexible array init always allowed as an extension
1359    FlexArrayDiag = diag::ext_flexible_array_init;
1360  } else if (SemaRef.getLangOpts().CPlusPlus) {
1361    // Disallow flexible array init in C++; it is not required for gcc
1362    // compatibility, and it needs work to IRGen correctly in general.
1363    FlexArrayDiag = diag::err_flexible_array_init;
1364  } else if (!TopLevelObject) {
1365    // Disallow flexible array init on non-top-level object
1366    FlexArrayDiag = diag::err_flexible_array_init;
1367  } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1368    // Disallow flexible array init on anything which is not a variable.
1369    FlexArrayDiag = diag::err_flexible_array_init;
1370  } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1371    // Disallow flexible array init on local variables.
1372    FlexArrayDiag = diag::err_flexible_array_init;
1373  } else {
1374    // Allow other cases.
1375    FlexArrayDiag = diag::ext_flexible_array_init;
1376  }
1377
1378  if (!VerifyOnly) {
1379    SemaRef.Diag(InitExpr->getLocStart(),
1380                 FlexArrayDiag)
1381      << InitExpr->getLocStart();
1382    SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1383      << Field;
1384  }
1385
1386  return FlexArrayDiag != diag::ext_flexible_array_init;
1387}
1388
1389void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
1390                                            InitListExpr *IList,
1391                                            QualType DeclType,
1392                                            RecordDecl::field_iterator Field,
1393                                            bool SubobjectIsDesignatorContext,
1394                                            unsigned &Index,
1395                                            InitListExpr *StructuredList,
1396                                            unsigned &StructuredIndex,
1397                                            bool TopLevelObject) {
1398  RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
1399
1400  // If the record is invalid, some of it's members are invalid. To avoid
1401  // confusion, we forgo checking the intializer for the entire record.
1402  if (structDecl->isInvalidDecl()) {
1403    // Assume it was supposed to consume a single initializer.
1404    ++Index;
1405    hadError = true;
1406    return;
1407  }
1408
1409  if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1410    RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1411
1412    // If there's a default initializer, use it.
1413    if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1414      if (VerifyOnly)
1415        return;
1416      for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1417           Field != FieldEnd; ++Field) {
1418        if (Field->hasInClassInitializer()) {
1419          StructuredList->setInitializedFieldInUnion(*Field);
1420          // FIXME: Actually build a CXXDefaultInitExpr?
1421          return;
1422        }
1423      }
1424    }
1425
1426    // Value-initialize the first named member of the union.
1427    for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1428         Field != FieldEnd; ++Field) {
1429      if (Field->getDeclName()) {
1430        if (VerifyOnly)
1431          CheckValueInitializable(
1432              InitializedEntity::InitializeMember(*Field, &Entity));
1433        else
1434          StructuredList->setInitializedFieldInUnion(*Field);
1435        break;
1436      }
1437    }
1438    return;
1439  }
1440
1441  // If structDecl is a forward declaration, this loop won't do
1442  // anything except look at designated initializers; That's okay,
1443  // because an error should get printed out elsewhere. It might be
1444  // worthwhile to skip over the rest of the initializer, though.
1445  RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1446  RecordDecl::field_iterator FieldEnd = RD->field_end();
1447  bool InitializedSomething = false;
1448  bool CheckForMissingFields = true;
1449  while (Index < IList->getNumInits()) {
1450    Expr *Init = IList->getInit(Index);
1451
1452    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1453      // If we're not the subobject that matches up with the '{' for
1454      // the designator, we shouldn't be handling the
1455      // designator. Return immediately.
1456      if (!SubobjectIsDesignatorContext)
1457        return;
1458
1459      // Handle this designated initializer. Field will be updated to
1460      // the next field that we'll be initializing.
1461      if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1462                                     DeclType, &Field, 0, Index,
1463                                     StructuredList, StructuredIndex,
1464                                     true, TopLevelObject))
1465        hadError = true;
1466
1467      InitializedSomething = true;
1468
1469      // Disable check for missing fields when designators are used.
1470      // This matches gcc behaviour.
1471      CheckForMissingFields = false;
1472      continue;
1473    }
1474
1475    if (Field == FieldEnd) {
1476      // We've run out of fields. We're done.
1477      break;
1478    }
1479
1480    // We've already initialized a member of a union. We're done.
1481    if (InitializedSomething && DeclType->isUnionType())
1482      break;
1483
1484    // If we've hit the flexible array member at the end, we're done.
1485    if (Field->getType()->isIncompleteArrayType())
1486      break;
1487
1488    if (Field->isUnnamedBitfield()) {
1489      // Don't initialize unnamed bitfields, e.g. "int : 20;"
1490      ++Field;
1491      continue;
1492    }
1493
1494    // Make sure we can use this declaration.
1495    bool InvalidUse;
1496    if (VerifyOnly)
1497      InvalidUse = !SemaRef.CanUseDecl(*Field);
1498    else
1499      InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1500                                          IList->getInit(Index)->getLocStart());
1501    if (InvalidUse) {
1502      ++Index;
1503      ++Field;
1504      hadError = true;
1505      continue;
1506    }
1507
1508    InitializedEntity MemberEntity =
1509      InitializedEntity::InitializeMember(*Field, &Entity);
1510    CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1511                        StructuredList, StructuredIndex);
1512    InitializedSomething = true;
1513
1514    if (DeclType->isUnionType() && !VerifyOnly) {
1515      // Initialize the first field within the union.
1516      StructuredList->setInitializedFieldInUnion(*Field);
1517    }
1518
1519    ++Field;
1520  }
1521
1522  // Emit warnings for missing struct field initializers.
1523  if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1524      Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1525      !DeclType->isUnionType()) {
1526    // It is possible we have one or more unnamed bitfields remaining.
1527    // Find first (if any) named field and emit warning.
1528    for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1529         it != end; ++it) {
1530      if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
1531        SemaRef.Diag(IList->getSourceRange().getEnd(),
1532                     diag::warn_missing_field_initializers) << it->getName();
1533        break;
1534      }
1535    }
1536  }
1537
1538  // Check that any remaining fields can be value-initialized.
1539  if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1540      !Field->getType()->isIncompleteArrayType()) {
1541    // FIXME: Should check for holes left by designated initializers too.
1542    for (; Field != FieldEnd && !hadError; ++Field) {
1543      if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
1544        CheckValueInitializable(
1545            InitializedEntity::InitializeMember(*Field, &Entity));
1546    }
1547  }
1548
1549  if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
1550      Index >= IList->getNumInits())
1551    return;
1552
1553  if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1554                             TopLevelObject)) {
1555    hadError = true;
1556    ++Index;
1557    return;
1558  }
1559
1560  InitializedEntity MemberEntity =
1561    InitializedEntity::InitializeMember(*Field, &Entity);
1562
1563  if (isa<InitListExpr>(IList->getInit(Index)))
1564    CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1565                        StructuredList, StructuredIndex);
1566  else
1567    CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
1568                          StructuredList, StructuredIndex);
1569}
1570
1571/// \brief Expand a field designator that refers to a member of an
1572/// anonymous struct or union into a series of field designators that
1573/// refers to the field within the appropriate subobject.
1574///
1575static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1576                                           DesignatedInitExpr *DIE,
1577                                           unsigned DesigIdx,
1578                                           IndirectFieldDecl *IndirectField) {
1579  typedef DesignatedInitExpr::Designator Designator;
1580
1581  // Build the replacement designators.
1582  SmallVector<Designator, 4> Replacements;
1583  for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1584       PE = IndirectField->chain_end(); PI != PE; ++PI) {
1585    if (PI + 1 == PE)
1586      Replacements.push_back(Designator((IdentifierInfo *)0,
1587                                    DIE->getDesignator(DesigIdx)->getDotLoc(),
1588                                DIE->getDesignator(DesigIdx)->getFieldLoc()));
1589    else
1590      Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1591                                        SourceLocation()));
1592    assert(isa<FieldDecl>(*PI));
1593    Replacements.back().setField(cast<FieldDecl>(*PI));
1594  }
1595
1596  // Expand the current designator into the set of replacement
1597  // designators, so we have a full subobject path down to where the
1598  // member of the anonymous struct/union is actually stored.
1599  DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
1600                        &Replacements[0] + Replacements.size());
1601}
1602
1603/// \brief Given an implicit anonymous field, search the IndirectField that
1604///  corresponds to FieldName.
1605static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1606                                                 IdentifierInfo *FieldName) {
1607  if (!FieldName)
1608    return 0;
1609
1610  assert(AnonField->isAnonymousStructOrUnion());
1611  Decl *NextDecl = AnonField->getNextDeclInContext();
1612  while (IndirectFieldDecl *IF =
1613          dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
1614    if (FieldName == IF->getAnonField()->getIdentifier())
1615      return IF;
1616    NextDecl = NextDecl->getNextDeclInContext();
1617  }
1618  return 0;
1619}
1620
1621static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1622                                                   DesignatedInitExpr *DIE) {
1623  unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1624  SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1625  for (unsigned I = 0; I < NumIndexExprs; ++I)
1626    IndexExprs[I] = DIE->getSubExpr(I + 1);
1627  return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1628                                    DIE->size(), IndexExprs,
1629                                    DIE->getEqualOrColonLoc(),
1630                                    DIE->usesGNUSyntax(), DIE->getInit());
1631}
1632
1633namespace {
1634
1635// Callback to only accept typo corrections that are for field members of
1636// the given struct or union.
1637class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1638 public:
1639  explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1640      : Record(RD) {}
1641
1642  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1643    FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1644    return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1645  }
1646
1647 private:
1648  RecordDecl *Record;
1649};
1650
1651}
1652
1653/// @brief Check the well-formedness of a C99 designated initializer.
1654///
1655/// Determines whether the designated initializer @p DIE, which
1656/// resides at the given @p Index within the initializer list @p
1657/// IList, is well-formed for a current object of type @p DeclType
1658/// (C99 6.7.8). The actual subobject that this designator refers to
1659/// within the current subobject is returned in either
1660/// @p NextField or @p NextElementIndex (whichever is appropriate).
1661///
1662/// @param IList  The initializer list in which this designated
1663/// initializer occurs.
1664///
1665/// @param DIE The designated initializer expression.
1666///
1667/// @param DesigIdx  The index of the current designator.
1668///
1669/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
1670/// into which the designation in @p DIE should refer.
1671///
1672/// @param NextField  If non-NULL and the first designator in @p DIE is
1673/// a field, this will be set to the field declaration corresponding
1674/// to the field named by the designator.
1675///
1676/// @param NextElementIndex  If non-NULL and the first designator in @p
1677/// DIE is an array designator or GNU array-range designator, this
1678/// will be set to the last index initialized by this designator.
1679///
1680/// @param Index  Index into @p IList where the designated initializer
1681/// @p DIE occurs.
1682///
1683/// @param StructuredList  The initializer list expression that
1684/// describes all of the subobject initializers in the order they'll
1685/// actually be initialized.
1686///
1687/// @returns true if there was an error, false otherwise.
1688bool
1689InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
1690                                            InitListExpr *IList,
1691                                            DesignatedInitExpr *DIE,
1692                                            unsigned DesigIdx,
1693                                            QualType &CurrentObjectType,
1694                                          RecordDecl::field_iterator *NextField,
1695                                            llvm::APSInt *NextElementIndex,
1696                                            unsigned &Index,
1697                                            InitListExpr *StructuredList,
1698                                            unsigned &StructuredIndex,
1699                                            bool FinishSubobjectInit,
1700                                            bool TopLevelObject) {
1701  if (DesigIdx == DIE->size()) {
1702    // Check the actual initialization for the designated object type.
1703    bool prevHadError = hadError;
1704
1705    // Temporarily remove the designator expression from the
1706    // initializer list that the child calls see, so that we don't try
1707    // to re-process the designator.
1708    unsigned OldIndex = Index;
1709    IList->setInit(OldIndex, DIE->getInit());
1710
1711    CheckSubElementType(Entity, IList, CurrentObjectType, Index,
1712                        StructuredList, StructuredIndex);
1713
1714    // Restore the designated initializer expression in the syntactic
1715    // form of the initializer list.
1716    if (IList->getInit(OldIndex) != DIE->getInit())
1717      DIE->setInit(IList->getInit(OldIndex));
1718    IList->setInit(OldIndex, DIE);
1719
1720    return hadError && !prevHadError;
1721  }
1722
1723  DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
1724  bool IsFirstDesignator = (DesigIdx == 0);
1725  if (!VerifyOnly) {
1726    assert((IsFirstDesignator || StructuredList) &&
1727           "Need a non-designated initializer list to start from");
1728
1729    // Determine the structural initializer list that corresponds to the
1730    // current subobject.
1731    StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
1732      : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1733                                   StructuredList, StructuredIndex,
1734                                   SourceRange(D->getLocStart(),
1735                                               DIE->getLocEnd()));
1736    assert(StructuredList && "Expected a structured initializer list");
1737  }
1738
1739  if (D->isFieldDesignator()) {
1740    // C99 6.7.8p7:
1741    //
1742    //   If a designator has the form
1743    //
1744    //      . identifier
1745    //
1746    //   then the current object (defined below) shall have
1747    //   structure or union type and the identifier shall be the
1748    //   name of a member of that type.
1749    const RecordType *RT = CurrentObjectType->getAs<RecordType>();
1750    if (!RT) {
1751      SourceLocation Loc = D->getDotLoc();
1752      if (Loc.isInvalid())
1753        Loc = D->getFieldLoc();
1754      if (!VerifyOnly)
1755        SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1756          << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
1757      ++Index;
1758      return true;
1759    }
1760
1761    // Note: we perform a linear search of the fields here, despite
1762    // the fact that we have a faster lookup method, because we always
1763    // need to compute the field's index.
1764    FieldDecl *KnownField = D->getField();
1765    IdentifierInfo *FieldName = D->getFieldName();
1766    unsigned FieldIndex = 0;
1767    RecordDecl::field_iterator
1768      Field = RT->getDecl()->field_begin(),
1769      FieldEnd = RT->getDecl()->field_end();
1770    for (; Field != FieldEnd; ++Field) {
1771      if (Field->isUnnamedBitfield())
1772        continue;
1773
1774      // If we find a field representing an anonymous field, look in the
1775      // IndirectFieldDecl that follow for the designated initializer.
1776      if (!KnownField && Field->isAnonymousStructOrUnion()) {
1777        if (IndirectFieldDecl *IF =
1778            FindIndirectFieldDesignator(*Field, FieldName)) {
1779          // In verify mode, don't modify the original.
1780          if (VerifyOnly)
1781            DIE = CloneDesignatedInitExpr(SemaRef, DIE);
1782          ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1783          D = DIE->getDesignator(DesigIdx);
1784          break;
1785        }
1786      }
1787      if (KnownField && KnownField == *Field)
1788        break;
1789      if (FieldName && FieldName == Field->getIdentifier())
1790        break;
1791
1792      ++FieldIndex;
1793    }
1794
1795    if (Field == FieldEnd) {
1796      if (VerifyOnly) {
1797        ++Index;
1798        return true; // No typo correction when just trying this out.
1799      }
1800
1801      // There was no normal field in the struct with the designated
1802      // name. Perform another lookup for this name, which may find
1803      // something that we can't designate (e.g., a member function),
1804      // may find nothing, or may find a member of an anonymous
1805      // struct/union.
1806      DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1807      FieldDecl *ReplacementField = 0;
1808      if (Lookup.empty()) {
1809        // Name lookup didn't find anything. Determine whether this
1810        // was a typo for another field name.
1811        FieldInitializerValidatorCCC Validator(RT->getDecl());
1812        TypoCorrection Corrected = SemaRef.CorrectTypo(
1813            DeclarationNameInfo(FieldName, D->getFieldLoc()),
1814            Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
1815            RT->getDecl());
1816        if (Corrected) {
1817          std::string CorrectedStr(
1818              Corrected.getAsString(SemaRef.getLangOpts()));
1819          std::string CorrectedQuotedStr(
1820              Corrected.getQuoted(SemaRef.getLangOpts()));
1821          ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
1822          SemaRef.Diag(D->getFieldLoc(),
1823                       diag::err_field_designator_unknown_suggest)
1824            << FieldName << CurrentObjectType << CorrectedQuotedStr
1825            << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
1826          SemaRef.Diag(ReplacementField->getLocation(),
1827                       diag::note_previous_decl) << CorrectedQuotedStr;
1828          hadError = true;
1829        } else {
1830          SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1831            << FieldName << CurrentObjectType;
1832          ++Index;
1833          return true;
1834        }
1835      }
1836
1837      if (!ReplacementField) {
1838        // Name lookup found something, but it wasn't a field.
1839        SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1840          << FieldName;
1841        SemaRef.Diag(Lookup.front()->getLocation(),
1842                      diag::note_field_designator_found);
1843        ++Index;
1844        return true;
1845      }
1846
1847      if (!KnownField) {
1848        // The replacement field comes from typo correction; find it
1849        // in the list of fields.
1850        FieldIndex = 0;
1851        Field = RT->getDecl()->field_begin();
1852        for (; Field != FieldEnd; ++Field) {
1853          if (Field->isUnnamedBitfield())
1854            continue;
1855
1856          if (ReplacementField == *Field ||
1857              Field->getIdentifier() == ReplacementField->getIdentifier())
1858            break;
1859
1860          ++FieldIndex;
1861        }
1862      }
1863    }
1864
1865    // All of the fields of a union are located at the same place in
1866    // the initializer list.
1867    if (RT->getDecl()->isUnion()) {
1868      FieldIndex = 0;
1869      if (!VerifyOnly)
1870        StructuredList->setInitializedFieldInUnion(*Field);
1871    }
1872
1873    // Make sure we can use this declaration.
1874    bool InvalidUse;
1875    if (VerifyOnly)
1876      InvalidUse = !SemaRef.CanUseDecl(*Field);
1877    else
1878      InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1879    if (InvalidUse) {
1880      ++Index;
1881      return true;
1882    }
1883
1884    if (!VerifyOnly) {
1885      // Update the designator with the field declaration.
1886      D->setField(*Field);
1887
1888      // Make sure that our non-designated initializer list has space
1889      // for a subobject corresponding to this field.
1890      if (FieldIndex >= StructuredList->getNumInits())
1891        StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1892    }
1893
1894    // This designator names a flexible array member.
1895    if (Field->getType()->isIncompleteArrayType()) {
1896      bool Invalid = false;
1897      if ((DesigIdx + 1) != DIE->size()) {
1898        // We can't designate an object within the flexible array
1899        // member (because GCC doesn't allow it).
1900        if (!VerifyOnly) {
1901          DesignatedInitExpr::Designator *NextD
1902            = DIE->getDesignator(DesigIdx + 1);
1903          SemaRef.Diag(NextD->getLocStart(),
1904                        diag::err_designator_into_flexible_array_member)
1905            << SourceRange(NextD->getLocStart(),
1906                           DIE->getLocEnd());
1907          SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1908            << *Field;
1909        }
1910        Invalid = true;
1911      }
1912
1913      if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1914          !isa<StringLiteral>(DIE->getInit())) {
1915        // The initializer is not an initializer list.
1916        if (!VerifyOnly) {
1917          SemaRef.Diag(DIE->getInit()->getLocStart(),
1918                        diag::err_flexible_array_init_needs_braces)
1919            << DIE->getInit()->getSourceRange();
1920          SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1921            << *Field;
1922        }
1923        Invalid = true;
1924      }
1925
1926      // Check GNU flexible array initializer.
1927      if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1928                                             TopLevelObject))
1929        Invalid = true;
1930
1931      if (Invalid) {
1932        ++Index;
1933        return true;
1934      }
1935
1936      // Initialize the array.
1937      bool prevHadError = hadError;
1938      unsigned newStructuredIndex = FieldIndex;
1939      unsigned OldIndex = Index;
1940      IList->setInit(Index, DIE->getInit());
1941
1942      InitializedEntity MemberEntity =
1943        InitializedEntity::InitializeMember(*Field, &Entity);
1944      CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1945                          StructuredList, newStructuredIndex);
1946
1947      IList->setInit(OldIndex, DIE);
1948      if (hadError && !prevHadError) {
1949        ++Field;
1950        ++FieldIndex;
1951        if (NextField)
1952          *NextField = Field;
1953        StructuredIndex = FieldIndex;
1954        return true;
1955      }
1956    } else {
1957      // Recurse to check later designated subobjects.
1958      QualType FieldType = Field->getType();
1959      unsigned newStructuredIndex = FieldIndex;
1960
1961      InitializedEntity MemberEntity =
1962        InitializedEntity::InitializeMember(*Field, &Entity);
1963      if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1964                                     FieldType, 0, 0, Index,
1965                                     StructuredList, newStructuredIndex,
1966                                     true, false))
1967        return true;
1968    }
1969
1970    // Find the position of the next field to be initialized in this
1971    // subobject.
1972    ++Field;
1973    ++FieldIndex;
1974
1975    // If this the first designator, our caller will continue checking
1976    // the rest of this struct/class/union subobject.
1977    if (IsFirstDesignator) {
1978      if (NextField)
1979        *NextField = Field;
1980      StructuredIndex = FieldIndex;
1981      return false;
1982    }
1983
1984    if (!FinishSubobjectInit)
1985      return false;
1986
1987    // We've already initialized something in the union; we're done.
1988    if (RT->getDecl()->isUnion())
1989      return hadError;
1990
1991    // Check the remaining fields within this class/struct/union subobject.
1992    bool prevHadError = hadError;
1993
1994    CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
1995                          StructuredList, FieldIndex);
1996    return hadError && !prevHadError;
1997  }
1998
1999  // C99 6.7.8p6:
2000  //
2001  //   If a designator has the form
2002  //
2003  //      [ constant-expression ]
2004  //
2005  //   then the current object (defined below) shall have array
2006  //   type and the expression shall be an integer constant
2007  //   expression. If the array is of unknown size, any
2008  //   nonnegative value is valid.
2009  //
2010  // Additionally, cope with the GNU extension that permits
2011  // designators of the form
2012  //
2013  //      [ constant-expression ... constant-expression ]
2014  const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2015  if (!AT) {
2016    if (!VerifyOnly)
2017      SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2018        << CurrentObjectType;
2019    ++Index;
2020    return true;
2021  }
2022
2023  Expr *IndexExpr = 0;
2024  llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2025  if (D->isArrayDesignator()) {
2026    IndexExpr = DIE->getArrayIndex(*D);
2027    DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
2028    DesignatedEndIndex = DesignatedStartIndex;
2029  } else {
2030    assert(D->isArrayRangeDesignator() && "Need array-range designator");
2031
2032    DesignatedStartIndex =
2033      DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
2034    DesignatedEndIndex =
2035      DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2036    IndexExpr = DIE->getArrayRangeEnd(*D);
2037
2038    // Codegen can't handle evaluating array range designators that have side
2039    // effects, because we replicate the AST value for each initialized element.
2040    // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2041    // elements with something that has a side effect, so codegen can emit an
2042    // "error unsupported" error instead of miscompiling the app.
2043    if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
2044        DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
2045      FullyStructuredList->sawArrayRangeDesignator();
2046  }
2047
2048  if (isa<ConstantArrayType>(AT)) {
2049    llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2050    DesignatedStartIndex
2051      = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2052    DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2053    DesignatedEndIndex
2054      = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2055    DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2056    if (DesignatedEndIndex >= MaxElements) {
2057      if (!VerifyOnly)
2058        SemaRef.Diag(IndexExpr->getLocStart(),
2059                      diag::err_array_designator_too_large)
2060          << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2061          << IndexExpr->getSourceRange();
2062      ++Index;
2063      return true;
2064    }
2065  } else {
2066    // Make sure the bit-widths and signedness match.
2067    if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
2068      DesignatedEndIndex
2069        = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
2070    else if (DesignatedStartIndex.getBitWidth() <
2071             DesignatedEndIndex.getBitWidth())
2072      DesignatedStartIndex
2073        = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
2074    DesignatedStartIndex.setIsUnsigned(true);
2075    DesignatedEndIndex.setIsUnsigned(true);
2076  }
2077
2078  if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2079    // We're modifying a string literal init; we have to decompose the string
2080    // so we can modify the individual characters.
2081    ASTContext &Context = SemaRef.Context;
2082    Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2083
2084    // Compute the character type
2085    QualType CharTy = AT->getElementType();
2086
2087    // Compute the type of the integer literals.
2088    QualType PromotedCharTy = CharTy;
2089    if (CharTy->isPromotableIntegerType())
2090      PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2091    unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2092
2093    if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2094      // Get the length of the string.
2095      uint64_t StrLen = SL->getLength();
2096      if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2097        StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2098      StructuredList->resizeInits(Context, StrLen);
2099
2100      // Build a literal for each character in the string, and put them into
2101      // the init list.
2102      for (unsigned i = 0, e = StrLen; i != e; ++i) {
2103        llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2104        Expr *Init = new (Context) IntegerLiteral(
2105            Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2106        if (CharTy != PromotedCharTy)
2107          Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2108                                          Init, 0, VK_RValue);
2109        StructuredList->updateInit(Context, i, Init);
2110      }
2111    } else {
2112      ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2113      std::string Str;
2114      Context.getObjCEncodingForType(E->getEncodedType(), Str);
2115
2116      // Get the length of the string.
2117      uint64_t StrLen = Str.size();
2118      if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2119        StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2120      StructuredList->resizeInits(Context, StrLen);
2121
2122      // Build a literal for each character in the string, and put them into
2123      // the init list.
2124      for (unsigned i = 0, e = StrLen; i != e; ++i) {
2125        llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2126        Expr *Init = new (Context) IntegerLiteral(
2127            Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2128        if (CharTy != PromotedCharTy)
2129          Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2130                                          Init, 0, VK_RValue);
2131        StructuredList->updateInit(Context, i, Init);
2132      }
2133    }
2134  }
2135
2136  // Make sure that our non-designated initializer list has space
2137  // for a subobject corresponding to this array element.
2138  if (!VerifyOnly &&
2139      DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
2140    StructuredList->resizeInits(SemaRef.Context,
2141                                DesignatedEndIndex.getZExtValue() + 1);
2142
2143  // Repeatedly perform subobject initializations in the range
2144  // [DesignatedStartIndex, DesignatedEndIndex].
2145
2146  // Move to the next designator
2147  unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2148  unsigned OldIndex = Index;
2149
2150  InitializedEntity ElementEntity =
2151    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
2152
2153  while (DesignatedStartIndex <= DesignatedEndIndex) {
2154    // Recurse to check later designated subobjects.
2155    QualType ElementType = AT->getElementType();
2156    Index = OldIndex;
2157
2158    ElementEntity.setElementIndex(ElementIndex);
2159    if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2160                                   ElementType, 0, 0, Index,
2161                                   StructuredList, ElementIndex,
2162                                   (DesignatedStartIndex == DesignatedEndIndex),
2163                                   false))
2164      return true;
2165
2166    // Move to the next index in the array that we'll be initializing.
2167    ++DesignatedStartIndex;
2168    ElementIndex = DesignatedStartIndex.getZExtValue();
2169  }
2170
2171  // If this the first designator, our caller will continue checking
2172  // the rest of this array subobject.
2173  if (IsFirstDesignator) {
2174    if (NextElementIndex)
2175      *NextElementIndex = DesignatedStartIndex;
2176    StructuredIndex = ElementIndex;
2177    return false;
2178  }
2179
2180  if (!FinishSubobjectInit)
2181    return false;
2182
2183  // Check the remaining elements within this array subobject.
2184  bool prevHadError = hadError;
2185  CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
2186                 /*SubobjectIsDesignatorContext=*/false, Index,
2187                 StructuredList, ElementIndex);
2188  return hadError && !prevHadError;
2189}
2190
2191// Get the structured initializer list for a subobject of type
2192// @p CurrentObjectType.
2193InitListExpr *
2194InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2195                                            QualType CurrentObjectType,
2196                                            InitListExpr *StructuredList,
2197                                            unsigned StructuredIndex,
2198                                            SourceRange InitRange) {
2199  if (VerifyOnly)
2200    return 0; // No structured list in verification-only mode.
2201  Expr *ExistingInit = 0;
2202  if (!StructuredList)
2203    ExistingInit = SyntacticToSemantic.lookup(IList);
2204  else if (StructuredIndex < StructuredList->getNumInits())
2205    ExistingInit = StructuredList->getInit(StructuredIndex);
2206
2207  if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2208    return Result;
2209
2210  if (ExistingInit) {
2211    // We are creating an initializer list that initializes the
2212    // subobjects of the current object, but there was already an
2213    // initialization that completely initialized the current
2214    // subobject, e.g., by a compound literal:
2215    //
2216    // struct X { int a, b; };
2217    // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2218    //
2219    // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2220    // designated initializer re-initializes the whole
2221    // subobject [0], overwriting previous initializers.
2222    SemaRef.Diag(InitRange.getBegin(),
2223                 diag::warn_subobject_initializer_overrides)
2224      << InitRange;
2225    SemaRef.Diag(ExistingInit->getLocStart(),
2226                  diag::note_previous_initializer)
2227      << /*FIXME:has side effects=*/0
2228      << ExistingInit->getSourceRange();
2229  }
2230
2231  InitListExpr *Result
2232    = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2233                                         InitRange.getBegin(), None,
2234                                         InitRange.getEnd());
2235
2236  QualType ResultType = CurrentObjectType;
2237  if (!ResultType->isArrayType())
2238    ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2239  Result->setType(ResultType);
2240
2241  // Pre-allocate storage for the structured initializer list.
2242  unsigned NumElements = 0;
2243  unsigned NumInits = 0;
2244  bool GotNumInits = false;
2245  if (!StructuredList) {
2246    NumInits = IList->getNumInits();
2247    GotNumInits = true;
2248  } else if (Index < IList->getNumInits()) {
2249    if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2250      NumInits = SubList->getNumInits();
2251      GotNumInits = true;
2252    }
2253  }
2254
2255  if (const ArrayType *AType
2256      = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2257    if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2258      NumElements = CAType->getSize().getZExtValue();
2259      // Simple heuristic so that we don't allocate a very large
2260      // initializer with many empty entries at the end.
2261      if (GotNumInits && NumElements > NumInits)
2262        NumElements = 0;
2263    }
2264  } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2265    NumElements = VType->getNumElements();
2266  else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2267    RecordDecl *RDecl = RType->getDecl();
2268    if (RDecl->isUnion())
2269      NumElements = 1;
2270    else
2271      NumElements = std::distance(RDecl->field_begin(),
2272                                  RDecl->field_end());
2273  }
2274
2275  Result->reserveInits(SemaRef.Context, NumElements);
2276
2277  // Link this new initializer list into the structured initializer
2278  // lists.
2279  if (StructuredList)
2280    StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2281  else {
2282    Result->setSyntacticForm(IList);
2283    SyntacticToSemantic[IList] = Result;
2284  }
2285
2286  return Result;
2287}
2288
2289/// Update the initializer at index @p StructuredIndex within the
2290/// structured initializer list to the value @p expr.
2291void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2292                                                  unsigned &StructuredIndex,
2293                                                  Expr *expr) {
2294  // No structured initializer list to update
2295  if (!StructuredList)
2296    return;
2297
2298  if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2299                                                  StructuredIndex, expr)) {
2300    // This initializer overwrites a previous initializer. Warn.
2301    SemaRef.Diag(expr->getLocStart(),
2302                  diag::warn_initializer_overrides)
2303      << expr->getSourceRange();
2304    SemaRef.Diag(PrevInit->getLocStart(),
2305                  diag::note_previous_initializer)
2306      << /*FIXME:has side effects=*/0
2307      << PrevInit->getSourceRange();
2308  }
2309
2310  ++StructuredIndex;
2311}
2312
2313/// Check that the given Index expression is a valid array designator
2314/// value. This is essentially just a wrapper around
2315/// VerifyIntegerConstantExpression that also checks for negative values
2316/// and produces a reasonable diagnostic if there is a
2317/// failure. Returns the index expression, possibly with an implicit cast
2318/// added, on success.  If everything went okay, Value will receive the
2319/// value of the constant expression.
2320static ExprResult
2321CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2322  SourceLocation Loc = Index->getLocStart();
2323
2324  // Make sure this is an integer constant expression.
2325  ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2326  if (Result.isInvalid())
2327    return Result;
2328
2329  if (Value.isSigned() && Value.isNegative())
2330    return S.Diag(Loc, diag::err_array_designator_negative)
2331      << Value.toString(10) << Index->getSourceRange();
2332
2333  Value.setIsUnsigned(true);
2334  return Result;
2335}
2336
2337ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
2338                                            SourceLocation Loc,
2339                                            bool GNUSyntax,
2340                                            ExprResult Init) {
2341  typedef DesignatedInitExpr::Designator ASTDesignator;
2342
2343  bool Invalid = false;
2344  SmallVector<ASTDesignator, 32> Designators;
2345  SmallVector<Expr *, 32> InitExpressions;
2346
2347  // Build designators and check array designator expressions.
2348  for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2349    const Designator &D = Desig.getDesignator(Idx);
2350    switch (D.getKind()) {
2351    case Designator::FieldDesignator:
2352      Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
2353                                          D.getFieldLoc()));
2354      break;
2355
2356    case Designator::ArrayDesignator: {
2357      Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2358      llvm::APSInt IndexValue;
2359      if (!Index->isTypeDependent() && !Index->isValueDependent())
2360        Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2361      if (!Index)
2362        Invalid = true;
2363      else {
2364        Designators.push_back(ASTDesignator(InitExpressions.size(),
2365                                            D.getLBracketLoc(),
2366                                            D.getRBracketLoc()));
2367        InitExpressions.push_back(Index);
2368      }
2369      break;
2370    }
2371
2372    case Designator::ArrayRangeDesignator: {
2373      Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2374      Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2375      llvm::APSInt StartValue;
2376      llvm::APSInt EndValue;
2377      bool StartDependent = StartIndex->isTypeDependent() ||
2378                            StartIndex->isValueDependent();
2379      bool EndDependent = EndIndex->isTypeDependent() ||
2380                          EndIndex->isValueDependent();
2381      if (!StartDependent)
2382        StartIndex =
2383            CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2384      if (!EndDependent)
2385        EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2386
2387      if (!StartIndex || !EndIndex)
2388        Invalid = true;
2389      else {
2390        // Make sure we're comparing values with the same bit width.
2391        if (StartDependent || EndDependent) {
2392          // Nothing to compute.
2393        } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
2394          EndValue = EndValue.extend(StartValue.getBitWidth());
2395        else if (StartValue.getBitWidth() < EndValue.getBitWidth())
2396          StartValue = StartValue.extend(EndValue.getBitWidth());
2397
2398        if (!StartDependent && !EndDependent && EndValue < StartValue) {
2399          Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
2400            << StartValue.toString(10) << EndValue.toString(10)
2401            << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2402          Invalid = true;
2403        } else {
2404          Designators.push_back(ASTDesignator(InitExpressions.size(),
2405                                              D.getLBracketLoc(),
2406                                              D.getEllipsisLoc(),
2407                                              D.getRBracketLoc()));
2408          InitExpressions.push_back(StartIndex);
2409          InitExpressions.push_back(EndIndex);
2410        }
2411      }
2412      break;
2413    }
2414    }
2415  }
2416
2417  if (Invalid || Init.isInvalid())
2418    return ExprError();
2419
2420  // Clear out the expressions within the designation.
2421  Desig.ClearExprs(*this);
2422
2423  DesignatedInitExpr *DIE
2424    = DesignatedInitExpr::Create(Context,
2425                                 Designators.data(), Designators.size(),
2426                                 InitExpressions, Loc, GNUSyntax,
2427                                 Init.takeAs<Expr>());
2428
2429  if (!getLangOpts().C99)
2430    Diag(DIE->getLocStart(), diag::ext_designated_init)
2431      << DIE->getSourceRange();
2432
2433  return Owned(DIE);
2434}
2435
2436//===----------------------------------------------------------------------===//
2437// Initialization entity
2438//===----------------------------------------------------------------------===//
2439
2440InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
2441                                     const InitializedEntity &Parent)
2442  : Parent(&Parent), Index(Index)
2443{
2444  if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2445    Kind = EK_ArrayElement;
2446    Type = AT->getElementType();
2447  } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
2448    Kind = EK_VectorElement;
2449    Type = VT->getElementType();
2450  } else {
2451    const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2452    assert(CT && "Unexpected type");
2453    Kind = EK_ComplexElement;
2454    Type = CT->getElementType();
2455  }
2456}
2457
2458InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
2459                                                    CXXBaseSpecifier *Base,
2460                                                    bool IsInheritedVirtualBase)
2461{
2462  InitializedEntity Result;
2463  Result.Kind = EK_Base;
2464  Result.Base = reinterpret_cast<uintptr_t>(Base);
2465  if (IsInheritedVirtualBase)
2466    Result.Base |= 0x01;
2467
2468  Result.Type = Base->getType();
2469  return Result;
2470}
2471
2472DeclarationName InitializedEntity::getName() const {
2473  switch (getKind()) {
2474  case EK_Parameter: {
2475    ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2476    return (D ? D->getDeclName() : DeclarationName());
2477  }
2478
2479  case EK_Variable:
2480  case EK_Member:
2481    return VariableOrMember->getDeclName();
2482
2483  case EK_LambdaCapture:
2484    return Capture.Var->getDeclName();
2485
2486  case EK_Result:
2487  case EK_Exception:
2488  case EK_New:
2489  case EK_Temporary:
2490  case EK_Base:
2491  case EK_Delegating:
2492  case EK_ArrayElement:
2493  case EK_VectorElement:
2494  case EK_ComplexElement:
2495  case EK_BlockElement:
2496  case EK_CompoundLiteralInit:
2497    return DeclarationName();
2498  }
2499
2500  llvm_unreachable("Invalid EntityKind!");
2501}
2502
2503DeclaratorDecl *InitializedEntity::getDecl() const {
2504  switch (getKind()) {
2505  case EK_Variable:
2506  case EK_Member:
2507    return VariableOrMember;
2508
2509  case EK_Parameter:
2510    return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2511
2512  case EK_Result:
2513  case EK_Exception:
2514  case EK_New:
2515  case EK_Temporary:
2516  case EK_Base:
2517  case EK_Delegating:
2518  case EK_ArrayElement:
2519  case EK_VectorElement:
2520  case EK_ComplexElement:
2521  case EK_BlockElement:
2522  case EK_LambdaCapture:
2523  case EK_CompoundLiteralInit:
2524    return 0;
2525  }
2526
2527  llvm_unreachable("Invalid EntityKind!");
2528}
2529
2530bool InitializedEntity::allowsNRVO() const {
2531  switch (getKind()) {
2532  case EK_Result:
2533  case EK_Exception:
2534    return LocAndNRVO.NRVO;
2535
2536  case EK_Variable:
2537  case EK_Parameter:
2538  case EK_Member:
2539  case EK_New:
2540  case EK_Temporary:
2541  case EK_CompoundLiteralInit:
2542  case EK_Base:
2543  case EK_Delegating:
2544  case EK_ArrayElement:
2545  case EK_VectorElement:
2546  case EK_ComplexElement:
2547  case EK_BlockElement:
2548  case EK_LambdaCapture:
2549    break;
2550  }
2551
2552  return false;
2553}
2554
2555unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
2556  unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2557  for (unsigned I = 0; I != Depth; ++I)
2558    OS << "`-";
2559
2560  switch (getKind()) {
2561  case EK_Variable: OS << "Variable"; break;
2562  case EK_Parameter: OS << "Parameter"; break;
2563  case EK_Result: OS << "Result"; break;
2564  case EK_Exception: OS << "Exception"; break;
2565  case EK_Member: OS << "Member"; break;
2566  case EK_New: OS << "New"; break;
2567  case EK_Temporary: OS << "Temporary"; break;
2568  case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
2569  case EK_Base: OS << "Base"; break;
2570  case EK_Delegating: OS << "Delegating"; break;
2571  case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2572  case EK_VectorElement: OS << "VectorElement " << Index; break;
2573  case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2574  case EK_BlockElement: OS << "Block"; break;
2575  case EK_LambdaCapture:
2576    OS << "LambdaCapture ";
2577    getCapturedVar()->printName(OS);
2578    break;
2579  }
2580
2581  if (Decl *D = getDecl()) {
2582    OS << " ";
2583    cast<NamedDecl>(D)->printQualifiedName(OS);
2584  }
2585
2586  OS << " '" << getType().getAsString() << "'\n";
2587
2588  return Depth + 1;
2589}
2590
2591void InitializedEntity::dump() const {
2592  dumpImpl(llvm::errs());
2593}
2594
2595//===----------------------------------------------------------------------===//
2596// Initialization sequence
2597//===----------------------------------------------------------------------===//
2598
2599void InitializationSequence::Step::Destroy() {
2600  switch (Kind) {
2601  case SK_ResolveAddressOfOverloadedFunction:
2602  case SK_CastDerivedToBaseRValue:
2603  case SK_CastDerivedToBaseXValue:
2604  case SK_CastDerivedToBaseLValue:
2605  case SK_BindReference:
2606  case SK_BindReferenceToTemporary:
2607  case SK_ExtraneousCopyToTemporary:
2608  case SK_UserConversion:
2609  case SK_QualificationConversionRValue:
2610  case SK_QualificationConversionXValue:
2611  case SK_QualificationConversionLValue:
2612  case SK_LValueToRValue:
2613  case SK_ListInitialization:
2614  case SK_ListConstructorCall:
2615  case SK_UnwrapInitList:
2616  case SK_RewrapInitList:
2617  case SK_ConstructorInitialization:
2618  case SK_ZeroInitialization:
2619  case SK_CAssignment:
2620  case SK_StringInit:
2621  case SK_ObjCObjectConversion:
2622  case SK_ArrayInit:
2623  case SK_ParenthesizedArrayInit:
2624  case SK_PassByIndirectCopyRestore:
2625  case SK_PassByIndirectRestore:
2626  case SK_ProduceObjCObject:
2627  case SK_StdInitializerList:
2628  case SK_OCLSamplerInit:
2629  case SK_OCLZeroEvent:
2630    break;
2631
2632  case SK_ConversionSequence:
2633    delete ICS;
2634  }
2635}
2636
2637bool InitializationSequence::isDirectReferenceBinding() const {
2638  return !Steps.empty() && Steps.back().Kind == SK_BindReference;
2639}
2640
2641bool InitializationSequence::isAmbiguous() const {
2642  if (!Failed())
2643    return false;
2644
2645  switch (getFailureKind()) {
2646  case FK_TooManyInitsForReference:
2647  case FK_ArrayNeedsInitList:
2648  case FK_ArrayNeedsInitListOrStringLiteral:
2649  case FK_ArrayNeedsInitListOrWideStringLiteral:
2650  case FK_NarrowStringIntoWideCharArray:
2651  case FK_WideStringIntoCharArray:
2652  case FK_IncompatWideStringIntoWideChar:
2653  case FK_AddressOfOverloadFailed: // FIXME: Could do better
2654  case FK_NonConstLValueReferenceBindingToTemporary:
2655  case FK_NonConstLValueReferenceBindingToUnrelated:
2656  case FK_RValueReferenceBindingToLValue:
2657  case FK_ReferenceInitDropsQualifiers:
2658  case FK_ReferenceInitFailed:
2659  case FK_ConversionFailed:
2660  case FK_ConversionFromPropertyFailed:
2661  case FK_TooManyInitsForScalar:
2662  case FK_ReferenceBindingToInitList:
2663  case FK_InitListBadDestinationType:
2664  case FK_DefaultInitOfConst:
2665  case FK_Incomplete:
2666  case FK_ArrayTypeMismatch:
2667  case FK_NonConstantArrayInit:
2668  case FK_ListInitializationFailed:
2669  case FK_VariableLengthArrayHasInitializer:
2670  case FK_PlaceholderType:
2671  case FK_InitListElementCopyFailure:
2672  case FK_ExplicitConstructor:
2673    return false;
2674
2675  case FK_ReferenceInitOverloadFailed:
2676  case FK_UserConversionOverloadFailed:
2677  case FK_ConstructorOverloadFailed:
2678  case FK_ListConstructorOverloadFailed:
2679    return FailedOverloadResult == OR_Ambiguous;
2680  }
2681
2682  llvm_unreachable("Invalid EntityKind!");
2683}
2684
2685bool InitializationSequence::isConstructorInitialization() const {
2686  return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2687}
2688
2689void
2690InitializationSequence
2691::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2692                                   DeclAccessPair Found,
2693                                   bool HadMultipleCandidates) {
2694  Step S;
2695  S.Kind = SK_ResolveAddressOfOverloadedFunction;
2696  S.Type = Function->getType();
2697  S.Function.HadMultipleCandidates = HadMultipleCandidates;
2698  S.Function.Function = Function;
2699  S.Function.FoundDecl = Found;
2700  Steps.push_back(S);
2701}
2702
2703void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2704                                                      ExprValueKind VK) {
2705  Step S;
2706  switch (VK) {
2707  case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2708  case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2709  case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
2710  }
2711  S.Type = BaseType;
2712  Steps.push_back(S);
2713}
2714
2715void InitializationSequence::AddReferenceBindingStep(QualType T,
2716                                                     bool BindingTemporary) {
2717  Step S;
2718  S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2719  S.Type = T;
2720  Steps.push_back(S);
2721}
2722
2723void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2724  Step S;
2725  S.Kind = SK_ExtraneousCopyToTemporary;
2726  S.Type = T;
2727  Steps.push_back(S);
2728}
2729
2730void
2731InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2732                                              DeclAccessPair FoundDecl,
2733                                              QualType T,
2734                                              bool HadMultipleCandidates) {
2735  Step S;
2736  S.Kind = SK_UserConversion;
2737  S.Type = T;
2738  S.Function.HadMultipleCandidates = HadMultipleCandidates;
2739  S.Function.Function = Function;
2740  S.Function.FoundDecl = FoundDecl;
2741  Steps.push_back(S);
2742}
2743
2744void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2745                                                            ExprValueKind VK) {
2746  Step S;
2747  S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
2748  switch (VK) {
2749  case VK_RValue:
2750    S.Kind = SK_QualificationConversionRValue;
2751    break;
2752  case VK_XValue:
2753    S.Kind = SK_QualificationConversionXValue;
2754    break;
2755  case VK_LValue:
2756    S.Kind = SK_QualificationConversionLValue;
2757    break;
2758  }
2759  S.Type = Ty;
2760  Steps.push_back(S);
2761}
2762
2763void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2764  assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2765
2766  Step S;
2767  S.Kind = SK_LValueToRValue;
2768  S.Type = Ty;
2769  Steps.push_back(S);
2770}
2771
2772void InitializationSequence::AddConversionSequenceStep(
2773                                       const ImplicitConversionSequence &ICS,
2774                                                       QualType T) {
2775  Step S;
2776  S.Kind = SK_ConversionSequence;
2777  S.Type = T;
2778  S.ICS = new ImplicitConversionSequence(ICS);
2779  Steps.push_back(S);
2780}
2781
2782void InitializationSequence::AddListInitializationStep(QualType T) {
2783  Step S;
2784  S.Kind = SK_ListInitialization;
2785  S.Type = T;
2786  Steps.push_back(S);
2787}
2788
2789void
2790InitializationSequence
2791::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2792                                   AccessSpecifier Access,
2793                                   QualType T,
2794                                   bool HadMultipleCandidates,
2795                                   bool FromInitList, bool AsInitList) {
2796  Step S;
2797  S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2798                                       : SK_ConstructorInitialization;
2799  S.Type = T;
2800  S.Function.HadMultipleCandidates = HadMultipleCandidates;
2801  S.Function.Function = Constructor;
2802  S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
2803  Steps.push_back(S);
2804}
2805
2806void InitializationSequence::AddZeroInitializationStep(QualType T) {
2807  Step S;
2808  S.Kind = SK_ZeroInitialization;
2809  S.Type = T;
2810  Steps.push_back(S);
2811}
2812
2813void InitializationSequence::AddCAssignmentStep(QualType T) {
2814  Step S;
2815  S.Kind = SK_CAssignment;
2816  S.Type = T;
2817  Steps.push_back(S);
2818}
2819
2820void InitializationSequence::AddStringInitStep(QualType T) {
2821  Step S;
2822  S.Kind = SK_StringInit;
2823  S.Type = T;
2824  Steps.push_back(S);
2825}
2826
2827void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2828  Step S;
2829  S.Kind = SK_ObjCObjectConversion;
2830  S.Type = T;
2831  Steps.push_back(S);
2832}
2833
2834void InitializationSequence::AddArrayInitStep(QualType T) {
2835  Step S;
2836  S.Kind = SK_ArrayInit;
2837  S.Type = T;
2838  Steps.push_back(S);
2839}
2840
2841void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2842  Step S;
2843  S.Kind = SK_ParenthesizedArrayInit;
2844  S.Type = T;
2845  Steps.push_back(S);
2846}
2847
2848void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2849                                                              bool shouldCopy) {
2850  Step s;
2851  s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2852                       : SK_PassByIndirectRestore);
2853  s.Type = type;
2854  Steps.push_back(s);
2855}
2856
2857void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2858  Step S;
2859  S.Kind = SK_ProduceObjCObject;
2860  S.Type = T;
2861  Steps.push_back(S);
2862}
2863
2864void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2865  Step S;
2866  S.Kind = SK_StdInitializerList;
2867  S.Type = T;
2868  Steps.push_back(S);
2869}
2870
2871void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
2872  Step S;
2873  S.Kind = SK_OCLSamplerInit;
2874  S.Type = T;
2875  Steps.push_back(S);
2876}
2877
2878void InitializationSequence::AddOCLZeroEventStep(QualType T) {
2879  Step S;
2880  S.Kind = SK_OCLZeroEvent;
2881  S.Type = T;
2882  Steps.push_back(S);
2883}
2884
2885void InitializationSequence::RewrapReferenceInitList(QualType T,
2886                                                     InitListExpr *Syntactic) {
2887  assert(Syntactic->getNumInits() == 1 &&
2888         "Can only rewrap trivial init lists.");
2889  Step S;
2890  S.Kind = SK_UnwrapInitList;
2891  S.Type = Syntactic->getInit(0)->getType();
2892  Steps.insert(Steps.begin(), S);
2893
2894  S.Kind = SK_RewrapInitList;
2895  S.Type = T;
2896  S.WrappingSyntacticList = Syntactic;
2897  Steps.push_back(S);
2898}
2899
2900void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2901                                                OverloadingResult Result) {
2902  setSequenceKind(FailedSequence);
2903  this->Failure = Failure;
2904  this->FailedOverloadResult = Result;
2905}
2906
2907//===----------------------------------------------------------------------===//
2908// Attempt initialization
2909//===----------------------------------------------------------------------===//
2910
2911static void MaybeProduceObjCObject(Sema &S,
2912                                   InitializationSequence &Sequence,
2913                                   const InitializedEntity &Entity) {
2914  if (!S.getLangOpts().ObjCAutoRefCount) return;
2915
2916  /// When initializing a parameter, produce the value if it's marked
2917  /// __attribute__((ns_consumed)).
2918  if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2919    if (!Entity.isParameterConsumed())
2920      return;
2921
2922    assert(Entity.getType()->isObjCRetainableType() &&
2923           "consuming an object of unretainable type?");
2924    Sequence.AddProduceObjCObjectStep(Entity.getType());
2925
2926  /// When initializing a return value, if the return type is a
2927  /// retainable type, then returns need to immediately retain the
2928  /// object.  If an autorelease is required, it will be done at the
2929  /// last instant.
2930  } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2931    if (!Entity.getType()->isObjCRetainableType())
2932      return;
2933
2934    Sequence.AddProduceObjCObjectStep(Entity.getType());
2935  }
2936}
2937
2938/// \brief When initializing from init list via constructor, handle
2939/// initialization of an object of type std::initializer_list<T>.
2940///
2941/// \return true if we have handled initialization of an object of type
2942/// std::initializer_list<T>, false otherwise.
2943static bool TryInitializerListConstruction(Sema &S,
2944                                           InitListExpr *List,
2945                                           QualType DestType,
2946                                           InitializationSequence &Sequence) {
2947  QualType E;
2948  if (!S.isStdInitializerList(DestType, &E))
2949    return false;
2950
2951  // Check that each individual element can be copy-constructed. But since we
2952  // have no place to store further information, we'll recalculate everything
2953  // later.
2954  InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2955      S.Context.getConstantArrayType(E,
2956          llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2957                      List->getNumInits()),
2958          ArrayType::Normal, 0));
2959  InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2960      0, HiddenArray);
2961  for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
2962    Element.setElementIndex(i);
2963    if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
2964      Sequence.SetFailed(
2965          InitializationSequence::FK_InitListElementCopyFailure);
2966      return true;
2967    }
2968  }
2969  Sequence.AddStdInitializerListConstructionStep(DestType);
2970  return true;
2971}
2972
2973static OverloadingResult
2974ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
2975                           MultiExprArg Args,
2976                           OverloadCandidateSet &CandidateSet,
2977                           ArrayRef<NamedDecl *> Ctors,
2978                           OverloadCandidateSet::iterator &Best,
2979                           bool CopyInitializing, bool AllowExplicit,
2980                           bool OnlyListConstructors, bool InitListSyntax) {
2981  CandidateSet.clear();
2982
2983  for (ArrayRef<NamedDecl *>::iterator
2984         Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
2985    NamedDecl *D = *Con;
2986    DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2987    bool SuppressUserConversions = false;
2988
2989    // Find the constructor (which may be a template).
2990    CXXConstructorDecl *Constructor = 0;
2991    FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2992    if (ConstructorTmpl)
2993      Constructor = cast<CXXConstructorDecl>(
2994                                           ConstructorTmpl->getTemplatedDecl());
2995    else {
2996      Constructor = cast<CXXConstructorDecl>(D);
2997
2998      // If we're performing copy initialization using a copy constructor, we
2999      // suppress user-defined conversions on the arguments. We do the same for
3000      // move constructors.
3001      if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
3002          Constructor->isCopyOrMoveConstructor())
3003        SuppressUserConversions = true;
3004    }
3005
3006    if (!Constructor->isInvalidDecl() &&
3007        (AllowExplicit || !Constructor->isExplicit()) &&
3008        (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
3009      if (ConstructorTmpl)
3010        S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3011                                       /*ExplicitArgs*/ 0, Args,
3012                                       CandidateSet, SuppressUserConversions);
3013      else {
3014        // C++ [over.match.copy]p1:
3015        //   - When initializing a temporary to be bound to the first parameter
3016        //     of a constructor that takes a reference to possibly cv-qualified
3017        //     T as its first argument, called with a single argument in the
3018        //     context of direct-initialization, explicit conversion functions
3019        //     are also considered.
3020        bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
3021                                 Args.size() == 1 &&
3022                                 Constructor->isCopyOrMoveConstructor();
3023        S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
3024                               SuppressUserConversions,
3025                               /*PartialOverloading=*/false,
3026                               /*AllowExplicit=*/AllowExplicitConv);
3027      }
3028    }
3029  }
3030
3031  // Perform overload resolution and return the result.
3032  return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3033}
3034
3035/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3036/// enumerates the constructors of the initialized entity and performs overload
3037/// resolution to select the best.
3038/// If InitListSyntax is true, this is list-initialization of a non-aggregate
3039/// class type.
3040static void TryConstructorInitialization(Sema &S,
3041                                         const InitializedEntity &Entity,
3042                                         const InitializationKind &Kind,
3043                                         MultiExprArg Args, QualType DestType,
3044                                         InitializationSequence &Sequence,
3045                                         bool InitListSyntax = false) {
3046  assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3047         "InitListSyntax must come with a single initializer list argument.");
3048
3049  // The type we're constructing needs to be complete.
3050  if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
3051    Sequence.setIncompleteTypeFailure(DestType);
3052    return;
3053  }
3054
3055  const RecordType *DestRecordType = DestType->getAs<RecordType>();
3056  assert(DestRecordType && "Constructor initialization requires record type");
3057  CXXRecordDecl *DestRecordDecl
3058    = cast<CXXRecordDecl>(DestRecordType->getDecl());
3059
3060  // Build the candidate set directly in the initialization sequence
3061  // structure, so that it will persist if we fail.
3062  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3063
3064  // Determine whether we are allowed to call explicit constructors or
3065  // explicit conversion operators.
3066  bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
3067  bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
3068
3069  //   - Otherwise, if T is a class type, constructors are considered. The
3070  //     applicable constructors are enumerated, and the best one is chosen
3071  //     through overload resolution.
3072  DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
3073  // The container holding the constructors can under certain conditions
3074  // be changed while iterating (e.g. because of deserialization).
3075  // To be safe we copy the lookup results to a new container.
3076  SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
3077
3078  OverloadingResult Result = OR_No_Viable_Function;
3079  OverloadCandidateSet::iterator Best;
3080  bool AsInitializerList = false;
3081
3082  // C++11 [over.match.list]p1:
3083  //   When objects of non-aggregate type T are list-initialized, overload
3084  //   resolution selects the constructor in two phases:
3085  //   - Initially, the candidate functions are the initializer-list
3086  //     constructors of the class T and the argument list consists of the
3087  //     initializer list as a single argument.
3088  if (InitListSyntax) {
3089    InitListExpr *ILE = cast<InitListExpr>(Args[0]);
3090    AsInitializerList = true;
3091
3092    // If the initializer list has no elements and T has a default constructor,
3093    // the first phase is omitted.
3094    if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
3095      Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3096                                          CandidateSet, Ctors, Best,
3097                                          CopyInitialization, AllowExplicit,
3098                                          /*OnlyListConstructor=*/true,
3099                                          InitListSyntax);
3100
3101    // Time to unwrap the init list.
3102    Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
3103  }
3104
3105  // C++11 [over.match.list]p1:
3106  //   - If no viable initializer-list constructor is found, overload resolution
3107  //     is performed again, where the candidate functions are all the
3108  //     constructors of the class T and the argument list consists of the
3109  //     elements of the initializer list.
3110  if (Result == OR_No_Viable_Function) {
3111    AsInitializerList = false;
3112    Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3113                                        CandidateSet, Ctors, Best,
3114                                        CopyInitialization, AllowExplicit,
3115                                        /*OnlyListConstructors=*/false,
3116                                        InitListSyntax);
3117  }
3118  if (Result) {
3119    Sequence.SetOverloadFailure(InitListSyntax ?
3120                      InitializationSequence::FK_ListConstructorOverloadFailed :
3121                      InitializationSequence::FK_ConstructorOverloadFailed,
3122                                Result);
3123    return;
3124  }
3125
3126  // C++11 [dcl.init]p6:
3127  //   If a program calls for the default initialization of an object
3128  //   of a const-qualified type T, T shall be a class type with a
3129  //   user-provided default constructor.
3130  if (Kind.getKind() == InitializationKind::IK_Default &&
3131      Entity.getType().isConstQualified() &&
3132      !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
3133    Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3134    return;
3135  }
3136
3137  // C++11 [over.match.list]p1:
3138  //   In copy-list-initialization, if an explicit constructor is chosen, the
3139  //   initializer is ill-formed.
3140  CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3141  if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3142    Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3143    return;
3144  }
3145
3146  // Add the constructor initialization step. Any cv-qualification conversion is
3147  // subsumed by the initialization.
3148  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3149  Sequence.AddConstructorInitializationStep(CtorDecl,
3150                                            Best->FoundDecl.getAccess(),
3151                                            DestType, HadMultipleCandidates,
3152                                            InitListSyntax, AsInitializerList);
3153}
3154
3155static bool
3156ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3157                                             Expr *Initializer,
3158                                             QualType &SourceType,
3159                                             QualType &UnqualifiedSourceType,
3160                                             QualType UnqualifiedTargetType,
3161                                             InitializationSequence &Sequence) {
3162  if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3163        S.Context.OverloadTy) {
3164    DeclAccessPair Found;
3165    bool HadMultipleCandidates = false;
3166    if (FunctionDecl *Fn
3167        = S.ResolveAddressOfOverloadedFunction(Initializer,
3168                                               UnqualifiedTargetType,
3169                                               false, Found,
3170                                               &HadMultipleCandidates)) {
3171      Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3172                                                HadMultipleCandidates);
3173      SourceType = Fn->getType();
3174      UnqualifiedSourceType = SourceType.getUnqualifiedType();
3175    } else if (!UnqualifiedTargetType->isRecordType()) {
3176      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3177      return true;
3178    }
3179  }
3180  return false;
3181}
3182
3183static void TryReferenceInitializationCore(Sema &S,
3184                                           const InitializedEntity &Entity,
3185                                           const InitializationKind &Kind,
3186                                           Expr *Initializer,
3187                                           QualType cv1T1, QualType T1,
3188                                           Qualifiers T1Quals,
3189                                           QualType cv2T2, QualType T2,
3190                                           Qualifiers T2Quals,
3191                                           InitializationSequence &Sequence);
3192
3193static void TryValueInitialization(Sema &S,
3194                                   const InitializedEntity &Entity,
3195                                   const InitializationKind &Kind,
3196                                   InitializationSequence &Sequence,
3197                                   InitListExpr *InitList = 0);
3198
3199static void TryListInitialization(Sema &S,
3200                                  const InitializedEntity &Entity,
3201                                  const InitializationKind &Kind,
3202                                  InitListExpr *InitList,
3203                                  InitializationSequence &Sequence);
3204
3205/// \brief Attempt list initialization of a reference.
3206static void TryReferenceListInitialization(Sema &S,
3207                                           const InitializedEntity &Entity,
3208                                           const InitializationKind &Kind,
3209                                           InitListExpr *InitList,
3210                                           InitializationSequence &Sequence) {
3211  // First, catch C++03 where this isn't possible.
3212  if (!S.getLangOpts().CPlusPlus11) {
3213    Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3214    return;
3215  }
3216
3217  QualType DestType = Entity.getType();
3218  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3219  Qualifiers T1Quals;
3220  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3221
3222  // Reference initialization via an initializer list works thus:
3223  // If the initializer list consists of a single element that is
3224  // reference-related to the referenced type, bind directly to that element
3225  // (possibly creating temporaries).
3226  // Otherwise, initialize a temporary with the initializer list and
3227  // bind to that.
3228  if (InitList->getNumInits() == 1) {
3229    Expr *Initializer = InitList->getInit(0);
3230    QualType cv2T2 = Initializer->getType();
3231    Qualifiers T2Quals;
3232    QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3233
3234    // If this fails, creating a temporary wouldn't work either.
3235    if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3236                                                     T1, Sequence))
3237      return;
3238
3239    SourceLocation DeclLoc = Initializer->getLocStart();
3240    bool dummy1, dummy2, dummy3;
3241    Sema::ReferenceCompareResult RefRelationship
3242      = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3243                                       dummy2, dummy3);
3244    if (RefRelationship >= Sema::Ref_Related) {
3245      // Try to bind the reference here.
3246      TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3247                                     T1Quals, cv2T2, T2, T2Quals, Sequence);
3248      if (Sequence)
3249        Sequence.RewrapReferenceInitList(cv1T1, InitList);
3250      return;
3251    }
3252
3253    // Update the initializer if we've resolved an overloaded function.
3254    if (Sequence.step_begin() != Sequence.step_end())
3255      Sequence.RewrapReferenceInitList(cv1T1, InitList);
3256  }
3257
3258  // Not reference-related. Create a temporary and bind to that.
3259  InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3260
3261  TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3262  if (Sequence) {
3263    if (DestType->isRValueReferenceType() ||
3264        (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3265      Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3266    else
3267      Sequence.SetFailed(
3268          InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3269  }
3270}
3271
3272/// \brief Attempt list initialization (C++0x [dcl.init.list])
3273static void TryListInitialization(Sema &S,
3274                                  const InitializedEntity &Entity,
3275                                  const InitializationKind &Kind,
3276                                  InitListExpr *InitList,
3277                                  InitializationSequence &Sequence) {
3278  QualType DestType = Entity.getType();
3279
3280  // C++ doesn't allow scalar initialization with more than one argument.
3281  // But C99 complex numbers are scalars and it makes sense there.
3282  if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
3283      !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3284    Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3285    return;
3286  }
3287  if (DestType->isReferenceType()) {
3288    TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
3289    return;
3290  }
3291  if (DestType->isRecordType()) {
3292    if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
3293      Sequence.setIncompleteTypeFailure(DestType);
3294      return;
3295    }
3296
3297    // C++11 [dcl.init.list]p3:
3298    //   - If T is an aggregate, aggregate initialization is performed.
3299    if (!DestType->isAggregateType()) {
3300      if (S.getLangOpts().CPlusPlus11) {
3301        //   - Otherwise, if the initializer list has no elements and T is a
3302        //     class type with a default constructor, the object is
3303        //     value-initialized.
3304        if (InitList->getNumInits() == 0) {
3305          CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
3306          if (RD->hasDefaultConstructor()) {
3307            TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3308            return;
3309          }
3310        }
3311
3312        //   - Otherwise, if T is a specialization of std::initializer_list<E>,
3313        //     an initializer_list object constructed [...]
3314        if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3315          return;
3316
3317        //   - Otherwise, if T is a class type, constructors are considered.
3318        Expr *InitListAsExpr = InitList;
3319        TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
3320                                     Sequence, /*InitListSyntax*/true);
3321      } else
3322        Sequence.SetFailed(
3323            InitializationSequence::FK_InitListBadDestinationType);
3324      return;
3325    }
3326  }
3327
3328  InitListChecker CheckInitList(S, Entity, InitList,
3329          DestType, /*VerifyOnly=*/true);
3330  if (CheckInitList.HadError()) {
3331    Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3332    return;
3333  }
3334
3335  // Add the list initialization step with the built init list.
3336  Sequence.AddListInitializationStep(DestType);
3337}
3338
3339/// \brief Try a reference initialization that involves calling a conversion
3340/// function.
3341static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3342                                             const InitializedEntity &Entity,
3343                                             const InitializationKind &Kind,
3344                                             Expr *Initializer,
3345                                             bool AllowRValues,
3346                                             InitializationSequence &Sequence) {
3347  QualType DestType = Entity.getType();
3348  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3349  QualType T1 = cv1T1.getUnqualifiedType();
3350  QualType cv2T2 = Initializer->getType();
3351  QualType T2 = cv2T2.getUnqualifiedType();
3352
3353  bool DerivedToBase;
3354  bool ObjCConversion;
3355  bool ObjCLifetimeConversion;
3356  assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
3357                                         T1, T2, DerivedToBase,
3358                                         ObjCConversion,
3359                                         ObjCLifetimeConversion) &&
3360         "Must have incompatible references when binding via conversion");
3361  (void)DerivedToBase;
3362  (void)ObjCConversion;
3363  (void)ObjCLifetimeConversion;
3364
3365  // Build the candidate set directly in the initialization sequence
3366  // structure, so that it will persist if we fail.
3367  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3368  CandidateSet.clear();
3369
3370  // Determine whether we are allowed to call explicit constructors or
3371  // explicit conversion operators.
3372  bool AllowExplicit = Kind.AllowExplicit();
3373  bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
3374
3375  const RecordType *T1RecordType = 0;
3376  if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3377      !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
3378    // The type we're converting to is a class type. Enumerate its constructors
3379    // to see if there is a suitable conversion.
3380    CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
3381
3382    DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
3383    // The container holding the constructors can under certain conditions
3384    // be changed while iterating (e.g. because of deserialization).
3385    // To be safe we copy the lookup results to a new container.
3386    SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
3387    for (SmallVector<NamedDecl*, 16>::iterator
3388           CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3389      NamedDecl *D = *CI;
3390      DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3391
3392      // Find the constructor (which may be a template).
3393      CXXConstructorDecl *Constructor = 0;
3394      FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3395      if (ConstructorTmpl)
3396        Constructor = cast<CXXConstructorDecl>(
3397                                         ConstructorTmpl->getTemplatedDecl());
3398      else
3399        Constructor = cast<CXXConstructorDecl>(D);
3400
3401      if (!Constructor->isInvalidDecl() &&
3402          Constructor->isConvertingConstructor(AllowExplicit)) {
3403        if (ConstructorTmpl)
3404          S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3405                                         /*ExplicitArgs*/ 0,
3406                                         Initializer, CandidateSet,
3407                                         /*SuppressUserConversions=*/true);
3408        else
3409          S.AddOverloadCandidate(Constructor, FoundDecl,
3410                                 Initializer, CandidateSet,
3411                                 /*SuppressUserConversions=*/true);
3412      }
3413    }
3414  }
3415  if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3416    return OR_No_Viable_Function;
3417
3418  const RecordType *T2RecordType = 0;
3419  if ((T2RecordType = T2->getAs<RecordType>()) &&
3420      !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
3421    // The type we're converting from is a class type, enumerate its conversion
3422    // functions.
3423    CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3424
3425    std::pair<CXXRecordDecl::conversion_iterator,
3426              CXXRecordDecl::conversion_iterator>
3427      Conversions = T2RecordDecl->getVisibleConversionFunctions();
3428    for (CXXRecordDecl::conversion_iterator
3429           I = Conversions.first, E = Conversions.second; I != E; ++I) {
3430      NamedDecl *D = *I;
3431      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3432      if (isa<UsingShadowDecl>(D))
3433        D = cast<UsingShadowDecl>(D)->getTargetDecl();
3434
3435      FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3436      CXXConversionDecl *Conv;
3437      if (ConvTemplate)
3438        Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3439      else
3440        Conv = cast<CXXConversionDecl>(D);
3441
3442      // If the conversion function doesn't return a reference type,
3443      // it can't be considered for this conversion unless we're allowed to
3444      // consider rvalues.
3445      // FIXME: Do we need to make sure that we only consider conversion
3446      // candidates with reference-compatible results? That might be needed to
3447      // break recursion.
3448      if ((AllowExplicitConvs || !Conv->isExplicit()) &&
3449          (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3450        if (ConvTemplate)
3451          S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3452                                           ActingDC, Initializer,
3453                                           DestType, CandidateSet);
3454        else
3455          S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
3456                                   Initializer, DestType, CandidateSet);
3457      }
3458    }
3459  }
3460  if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3461    return OR_No_Viable_Function;
3462
3463  SourceLocation DeclLoc = Initializer->getLocStart();
3464
3465  // Perform overload resolution. If it fails, return the failed result.
3466  OverloadCandidateSet::iterator Best;
3467  if (OverloadingResult Result
3468        = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
3469    return Result;
3470
3471  FunctionDecl *Function = Best->Function;
3472  // This is the overload that will be used for this initialization step if we
3473  // use this initialization. Mark it as referenced.
3474  Function->setReferenced();
3475
3476  // Compute the returned type of the conversion.
3477  if (isa<CXXConversionDecl>(Function))
3478    T2 = Function->getResultType();
3479  else
3480    T2 = cv1T1;
3481
3482  // Add the user-defined conversion step.
3483  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3484  Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3485                                 T2.getNonLValueExprType(S.Context),
3486                                 HadMultipleCandidates);
3487
3488  // Determine whether we need to perform derived-to-base or
3489  // cv-qualification adjustments.
3490  ExprValueKind VK = VK_RValue;
3491  if (T2->isLValueReferenceType())
3492    VK = VK_LValue;
3493  else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
3494    VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
3495
3496  bool NewDerivedToBase = false;
3497  bool NewObjCConversion = false;
3498  bool NewObjCLifetimeConversion = false;
3499  Sema::ReferenceCompareResult NewRefRelationship
3500    = S.CompareReferenceRelationship(DeclLoc, T1,
3501                                     T2.getNonLValueExprType(S.Context),
3502                                     NewDerivedToBase, NewObjCConversion,
3503                                     NewObjCLifetimeConversion);
3504  if (NewRefRelationship == Sema::Ref_Incompatible) {
3505    // If the type we've converted to is not reference-related to the
3506    // type we're looking for, then there is another conversion step
3507    // we need to perform to produce a temporary of the right type
3508    // that we'll be binding to.
3509    ImplicitConversionSequence ICS;
3510    ICS.setStandard();
3511    ICS.Standard = Best->FinalConversion;
3512    T2 = ICS.Standard.getToType(2);
3513    Sequence.AddConversionSequenceStep(ICS, T2);
3514  } else if (NewDerivedToBase)
3515    Sequence.AddDerivedToBaseCastStep(
3516                                S.Context.getQualifiedType(T1,
3517                                  T2.getNonReferenceType().getQualifiers()),
3518                                      VK);
3519  else if (NewObjCConversion)
3520    Sequence.AddObjCObjectConversionStep(
3521                                S.Context.getQualifiedType(T1,
3522                                  T2.getNonReferenceType().getQualifiers()));
3523
3524  if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
3525    Sequence.AddQualificationConversionStep(cv1T1, VK);
3526
3527  Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3528  return OR_Success;
3529}
3530
3531static void CheckCXX98CompatAccessibleCopy(Sema &S,
3532                                           const InitializedEntity &Entity,
3533                                           Expr *CurInitExpr);
3534
3535/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3536static void TryReferenceInitialization(Sema &S,
3537                                       const InitializedEntity &Entity,
3538                                       const InitializationKind &Kind,
3539                                       Expr *Initializer,
3540                                       InitializationSequence &Sequence) {
3541  QualType DestType = Entity.getType();
3542  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3543  Qualifiers T1Quals;
3544  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3545  QualType cv2T2 = Initializer->getType();
3546  Qualifiers T2Quals;
3547  QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3548
3549  // If the initializer is the address of an overloaded function, try
3550  // to resolve the overloaded function. If all goes well, T2 is the
3551  // type of the resulting function.
3552  if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3553                                                   T1, Sequence))
3554    return;
3555
3556  // Delegate everything else to a subfunction.
3557  TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3558                                 T1Quals, cv2T2, T2, T2Quals, Sequence);
3559}
3560
3561/// Converts the target of reference initialization so that it has the
3562/// appropriate qualifiers and value kind.
3563///
3564/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3565/// \code
3566///   int x;
3567///   const int &r = x;
3568/// \endcode
3569///
3570/// In this case the reference is binding to a bitfield lvalue, which isn't
3571/// valid. Perform a load to create a lifetime-extended temporary instead.
3572/// \code
3573///   const int &r = someStruct.bitfield;
3574/// \endcode
3575static ExprValueKind
3576convertQualifiersAndValueKindIfNecessary(Sema &S,
3577                                         InitializationSequence &Sequence,
3578                                         Expr *Initializer,
3579                                         QualType cv1T1,
3580                                         Qualifiers T1Quals,
3581                                         Qualifiers T2Quals,
3582                                         bool IsLValueRef) {
3583  bool IsNonAddressableType = Initializer->refersToBitField() ||
3584                              Initializer->refersToVectorElement();
3585
3586  if (IsNonAddressableType) {
3587    // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3588    // lvalue reference to a non-volatile const type, or the reference shall be
3589    // an rvalue reference.
3590    //
3591    // If not, we can't make a temporary and bind to that. Give up and allow the
3592    // error to be diagnosed later.
3593    if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3594      assert(Initializer->isGLValue());
3595      return Initializer->getValueKind();
3596    }
3597
3598    // Force a load so we can materialize a temporary.
3599    Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3600    return VK_RValue;
3601  }
3602
3603  if (T1Quals != T2Quals) {
3604    Sequence.AddQualificationConversionStep(cv1T1,
3605                                            Initializer->getValueKind());
3606  }
3607
3608  return Initializer->getValueKind();
3609}
3610
3611
3612/// \brief Reference initialization without resolving overloaded functions.
3613static void TryReferenceInitializationCore(Sema &S,
3614                                           const InitializedEntity &Entity,
3615                                           const InitializationKind &Kind,
3616                                           Expr *Initializer,
3617                                           QualType cv1T1, QualType T1,
3618                                           Qualifiers T1Quals,
3619                                           QualType cv2T2, QualType T2,
3620                                           Qualifiers T2Quals,
3621                                           InitializationSequence &Sequence) {
3622  QualType DestType = Entity.getType();
3623  SourceLocation DeclLoc = Initializer->getLocStart();
3624  // Compute some basic properties of the types and the initializer.
3625  bool isLValueRef = DestType->isLValueReferenceType();
3626  bool isRValueRef = !isLValueRef;
3627  bool DerivedToBase = false;
3628  bool ObjCConversion = false;
3629  bool ObjCLifetimeConversion = false;
3630  Expr::Classification InitCategory = Initializer->Classify(S.Context);
3631  Sema::ReferenceCompareResult RefRelationship
3632    = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
3633                                     ObjCConversion, ObjCLifetimeConversion);
3634
3635  // C++0x [dcl.init.ref]p5:
3636  //   A reference to type "cv1 T1" is initialized by an expression of type
3637  //   "cv2 T2" as follows:
3638  //
3639  //     - If the reference is an lvalue reference and the initializer
3640  //       expression
3641  // Note the analogous bullet points for rvlaue refs to functions. Because
3642  // there are no function rvalues in C++, rvalue refs to functions are treated
3643  // like lvalue refs.
3644  OverloadingResult ConvOvlResult = OR_Success;
3645  bool T1Function = T1->isFunctionType();
3646  if (isLValueRef || T1Function) {
3647    if (InitCategory.isLValue() &&
3648        (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3649         (Kind.isCStyleOrFunctionalCast() &&
3650          RefRelationship == Sema::Ref_Related))) {
3651      //   - is an lvalue (but is not a bit-field), and "cv1 T1" is
3652      //     reference-compatible with "cv2 T2," or
3653      //
3654      // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
3655      // bit-field when we're determining whether the reference initialization
3656      // can occur. However, we do pay attention to whether it is a bit-field
3657      // to decide whether we're actually binding to a temporary created from
3658      // the bit-field.
3659      if (DerivedToBase)
3660        Sequence.AddDerivedToBaseCastStep(
3661                         S.Context.getQualifiedType(T1, T2Quals),
3662                         VK_LValue);
3663      else if (ObjCConversion)
3664        Sequence.AddObjCObjectConversionStep(
3665                                     S.Context.getQualifiedType(T1, T2Quals));
3666
3667      ExprValueKind ValueKind =
3668        convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3669                                                 cv1T1, T1Quals, T2Quals,
3670                                                 isLValueRef);
3671      Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
3672      return;
3673    }
3674
3675    //     - has a class type (i.e., T2 is a class type), where T1 is not
3676    //       reference-related to T2, and can be implicitly converted to an
3677    //       lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3678    //       with "cv3 T3" (this conversion is selected by enumerating the
3679    //       applicable conversion functions (13.3.1.6) and choosing the best
3680    //       one through overload resolution (13.3)),
3681    // If we have an rvalue ref to function type here, the rhs must be
3682    // an rvalue.
3683    if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3684        (isLValueRef || InitCategory.isRValue())) {
3685      ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
3686                                                       Initializer,
3687                                                   /*AllowRValues=*/isRValueRef,
3688                                                       Sequence);
3689      if (ConvOvlResult == OR_Success)
3690        return;
3691      if (ConvOvlResult != OR_No_Viable_Function) {
3692        Sequence.SetOverloadFailure(
3693                      InitializationSequence::FK_ReferenceInitOverloadFailed,
3694                                    ConvOvlResult);
3695      }
3696    }
3697  }
3698
3699  //     - Otherwise, the reference shall be an lvalue reference to a
3700  //       non-volatile const type (i.e., cv1 shall be const), or the reference
3701  //       shall be an rvalue reference.
3702  if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
3703    if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3704      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3705    else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3706      Sequence.SetOverloadFailure(
3707                        InitializationSequence::FK_ReferenceInitOverloadFailed,
3708                                  ConvOvlResult);
3709    else
3710      Sequence.SetFailed(InitCategory.isLValue()
3711        ? (RefRelationship == Sema::Ref_Related
3712             ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3713             : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3714        : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3715
3716    return;
3717  }
3718
3719  //    - If the initializer expression
3720  //      - is an xvalue, class prvalue, array prvalue, or function lvalue and
3721  //        "cv1 T1" is reference-compatible with "cv2 T2"
3722  // Note: functions are handled below.
3723  if (!T1Function &&
3724      (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3725       (Kind.isCStyleOrFunctionalCast() &&
3726        RefRelationship == Sema::Ref_Related)) &&
3727      (InitCategory.isXValue() ||
3728       (InitCategory.isPRValue() && T2->isRecordType()) ||
3729       (InitCategory.isPRValue() && T2->isArrayType()))) {
3730    ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3731    if (InitCategory.isPRValue() && T2->isRecordType()) {
3732      // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3733      // compiler the freedom to perform a copy here or bind to the
3734      // object, while C++0x requires that we bind directly to the
3735      // object. Hence, we always bind to the object without making an
3736      // extra copy. However, in C++03 requires that we check for the
3737      // presence of a suitable copy constructor:
3738      //
3739      //   The constructor that would be used to make the copy shall
3740      //   be callable whether or not the copy is actually done.
3741      if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
3742        Sequence.AddExtraneousCopyToTemporary(cv2T2);
3743      else if (S.getLangOpts().CPlusPlus11)
3744        CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
3745    }
3746
3747    if (DerivedToBase)
3748      Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3749                                        ValueKind);
3750    else if (ObjCConversion)
3751      Sequence.AddObjCObjectConversionStep(
3752                                       S.Context.getQualifiedType(T1, T2Quals));
3753
3754    ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3755                                                         Initializer, cv1T1,
3756                                                         T1Quals, T2Quals,
3757                                                         isLValueRef);
3758
3759    Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
3760    return;
3761  }
3762
3763  //       - has a class type (i.e., T2 is a class type), where T1 is not
3764  //         reference-related to T2, and can be implicitly converted to an
3765  //         xvalue, class prvalue, or function lvalue of type "cv3 T3",
3766  //         where "cv1 T1" is reference-compatible with "cv3 T3",
3767  if (T2->isRecordType()) {
3768    if (RefRelationship == Sema::Ref_Incompatible) {
3769      ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3770                                                       Kind, Initializer,
3771                                                       /*AllowRValues=*/true,
3772                                                       Sequence);
3773      if (ConvOvlResult)
3774        Sequence.SetOverloadFailure(
3775                      InitializationSequence::FK_ReferenceInitOverloadFailed,
3776                                    ConvOvlResult);
3777
3778      return;
3779    }
3780
3781    if ((RefRelationship == Sema::Ref_Compatible ||
3782         RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3783        isRValueRef && InitCategory.isLValue()) {
3784      Sequence.SetFailed(
3785        InitializationSequence::FK_RValueReferenceBindingToLValue);
3786      return;
3787    }
3788
3789    Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3790    return;
3791  }
3792
3793  //      - Otherwise, a temporary of type "cv1 T1" is created and initialized
3794  //        from the initializer expression using the rules for a non-reference
3795  //        copy initialization (8.5). The reference is then bound to the
3796  //        temporary. [...]
3797
3798  // Determine whether we are allowed to call explicit constructors or
3799  // explicit conversion operators.
3800  bool AllowExplicit = Kind.AllowExplicit();
3801
3802  InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3803
3804  ImplicitConversionSequence ICS
3805    = S.TryImplicitConversion(Initializer, TempEntity.getType(),
3806                              /*SuppressUserConversions*/ false,
3807                              AllowExplicit,
3808                              /*FIXME:InOverloadResolution=*/false,
3809                              /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3810                              /*AllowObjCWritebackConversion=*/false);
3811
3812  if (ICS.isBad()) {
3813    // FIXME: Use the conversion function set stored in ICS to turn
3814    // this into an overloading ambiguity diagnostic. However, we need
3815    // to keep that set as an OverloadCandidateSet rather than as some
3816    // other kind of set.
3817    if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3818      Sequence.SetOverloadFailure(
3819                        InitializationSequence::FK_ReferenceInitOverloadFailed,
3820                                  ConvOvlResult);
3821    else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3822      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3823    else
3824      Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
3825    return;
3826  } else {
3827    Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
3828  }
3829
3830  //        [...] If T1 is reference-related to T2, cv1 must be the
3831  //        same cv-qualification as, or greater cv-qualification
3832  //        than, cv2; otherwise, the program is ill-formed.
3833  unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3834  unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
3835  if (RefRelationship == Sema::Ref_Related &&
3836      (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
3837    Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3838    return;
3839  }
3840
3841  //   [...] If T1 is reference-related to T2 and the reference is an rvalue
3842  //   reference, the initializer expression shall not be an lvalue.
3843  if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
3844      InitCategory.isLValue()) {
3845    Sequence.SetFailed(
3846                    InitializationSequence::FK_RValueReferenceBindingToLValue);
3847    return;
3848  }
3849
3850  Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3851  return;
3852}
3853
3854/// \brief Attempt character array initialization from a string literal
3855/// (C++ [dcl.init.string], C99 6.7.8).
3856static void TryStringLiteralInitialization(Sema &S,
3857                                           const InitializedEntity &Entity,
3858                                           const InitializationKind &Kind,
3859                                           Expr *Initializer,
3860                                       InitializationSequence &Sequence) {
3861  Sequence.AddStringInitStep(Entity.getType());
3862}
3863
3864/// \brief Attempt value initialization (C++ [dcl.init]p7).
3865static void TryValueInitialization(Sema &S,
3866                                   const InitializedEntity &Entity,
3867                                   const InitializationKind &Kind,
3868                                   InitializationSequence &Sequence,
3869                                   InitListExpr *InitList) {
3870  assert((!InitList || InitList->getNumInits() == 0) &&
3871         "Shouldn't use value-init for non-empty init lists");
3872
3873  // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
3874  //
3875  //   To value-initialize an object of type T means:
3876  QualType T = Entity.getType();
3877
3878  //     -- if T is an array type, then each element is value-initialized;
3879  T = S.Context.getBaseElementType(T);
3880
3881  if (const RecordType *RT = T->getAs<RecordType>()) {
3882    if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3883      bool NeedZeroInitialization = true;
3884      if (!S.getLangOpts().CPlusPlus11) {
3885        // C++98:
3886        // -- if T is a class type (clause 9) with a user-declared constructor
3887        //    (12.1), then the default constructor for T is called (and the
3888        //    initialization is ill-formed if T has no accessible default
3889        //    constructor);
3890        if (ClassDecl->hasUserDeclaredConstructor())
3891          NeedZeroInitialization = false;
3892      } else {
3893        // C++11:
3894        // -- if T is a class type (clause 9) with either no default constructor
3895        //    (12.1 [class.ctor]) or a default constructor that is user-provided
3896        //    or deleted, then the object is default-initialized;
3897        CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3898        if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
3899          NeedZeroInitialization = false;
3900      }
3901
3902      // -- if T is a (possibly cv-qualified) non-union class type without a
3903      //    user-provided or deleted default constructor, then the object is
3904      //    zero-initialized and, if T has a non-trivial default constructor,
3905      //    default-initialized;
3906      // The 'non-union' here was removed by DR1502. The 'non-trivial default
3907      // constructor' part was removed by DR1507.
3908      if (NeedZeroInitialization)
3909        Sequence.AddZeroInitializationStep(Entity.getType());
3910
3911      // C++03:
3912      // -- if T is a non-union class type without a user-declared constructor,
3913      //    then every non-static data member and base class component of T is
3914      //    value-initialized;
3915      // [...] A program that calls for [...] value-initialization of an
3916      // entity of reference type is ill-formed.
3917      //
3918      // C++11 doesn't need this handling, because value-initialization does not
3919      // occur recursively there, and the implicit default constructor is
3920      // defined as deleted in the problematic cases.
3921      if (!S.getLangOpts().CPlusPlus11 &&
3922          ClassDecl->hasUninitializedReferenceMember()) {
3923        Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3924        return;
3925      }
3926
3927      // If this is list-value-initialization, pass the empty init list on when
3928      // building the constructor call. This affects the semantics of a few
3929      // things (such as whether an explicit default constructor can be called).
3930      Expr *InitListAsExpr = InitList;
3931      MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
3932      bool InitListSyntax = InitList;
3933
3934      return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
3935                                          InitListSyntax);
3936    }
3937  }
3938
3939  Sequence.AddZeroInitializationStep(Entity.getType());
3940}
3941
3942/// \brief Attempt default initialization (C++ [dcl.init]p6).
3943static void TryDefaultInitialization(Sema &S,
3944                                     const InitializedEntity &Entity,
3945                                     const InitializationKind &Kind,
3946                                     InitializationSequence &Sequence) {
3947  assert(Kind.getKind() == InitializationKind::IK_Default);
3948
3949  // C++ [dcl.init]p6:
3950  //   To default-initialize an object of type T means:
3951  //     - if T is an array type, each element is default-initialized;
3952  QualType DestType = S.Context.getBaseElementType(Entity.getType());
3953
3954  //     - if T is a (possibly cv-qualified) class type (Clause 9), the default
3955  //       constructor for T is called (and the initialization is ill-formed if
3956  //       T has no accessible default constructor);
3957  if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
3958    TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
3959    return;
3960  }
3961
3962  //     - otherwise, no initialization is performed.
3963
3964  //   If a program calls for the default initialization of an object of
3965  //   a const-qualified type T, T shall be a class type with a user-provided
3966  //   default constructor.
3967  if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
3968    Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3969    return;
3970  }
3971
3972  // If the destination type has a lifetime property, zero-initialize it.
3973  if (DestType.getQualifiers().hasObjCLifetime()) {
3974    Sequence.AddZeroInitializationStep(Entity.getType());
3975    return;
3976  }
3977}
3978
3979/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3980/// which enumerates all conversion functions and performs overload resolution
3981/// to select the best.
3982static void TryUserDefinedConversion(Sema &S,
3983                                     const InitializedEntity &Entity,
3984                                     const InitializationKind &Kind,
3985                                     Expr *Initializer,
3986                                     InitializationSequence &Sequence) {
3987  QualType DestType = Entity.getType();
3988  assert(!DestType->isReferenceType() && "References are handled elsewhere");
3989  QualType SourceType = Initializer->getType();
3990  assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3991         "Must have a class type to perform a user-defined conversion");
3992
3993  // Build the candidate set directly in the initialization sequence
3994  // structure, so that it will persist if we fail.
3995  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3996  CandidateSet.clear();
3997
3998  // Determine whether we are allowed to call explicit constructors or
3999  // explicit conversion operators.
4000  bool AllowExplicit = Kind.AllowExplicit();
4001
4002  if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4003    // The type we're converting to is a class type. Enumerate its constructors
4004    // to see if there is a suitable conversion.
4005    CXXRecordDecl *DestRecordDecl
4006      = cast<CXXRecordDecl>(DestRecordType->getDecl());
4007
4008    // Try to complete the type we're converting to.
4009    if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
4010      DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
4011      // The container holding the constructors can under certain conditions
4012      // be changed while iterating. To be safe we copy the lookup results
4013      // to a new container.
4014      SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
4015      for (SmallVector<NamedDecl*, 8>::iterator
4016             Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
4017           Con != ConEnd; ++Con) {
4018        NamedDecl *D = *Con;
4019        DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
4020
4021        // Find the constructor (which may be a template).
4022        CXXConstructorDecl *Constructor = 0;
4023        FunctionTemplateDecl *ConstructorTmpl
4024          = dyn_cast<FunctionTemplateDecl>(D);
4025        if (ConstructorTmpl)
4026          Constructor = cast<CXXConstructorDecl>(
4027                                           ConstructorTmpl->getTemplatedDecl());
4028        else
4029          Constructor = cast<CXXConstructorDecl>(D);
4030
4031        if (!Constructor->isInvalidDecl() &&
4032            Constructor->isConvertingConstructor(AllowExplicit)) {
4033          if (ConstructorTmpl)
4034            S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
4035                                           /*ExplicitArgs*/ 0,
4036                                           Initializer, CandidateSet,
4037                                           /*SuppressUserConversions=*/true);
4038          else
4039            S.AddOverloadCandidate(Constructor, FoundDecl,
4040                                   Initializer, CandidateSet,
4041                                   /*SuppressUserConversions=*/true);
4042        }
4043      }
4044    }
4045  }
4046
4047  SourceLocation DeclLoc = Initializer->getLocStart();
4048
4049  if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4050    // The type we're converting from is a class type, enumerate its conversion
4051    // functions.
4052
4053    // We can only enumerate the conversion functions for a complete type; if
4054    // the type isn't complete, simply skip this step.
4055    if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4056      CXXRecordDecl *SourceRecordDecl
4057        = cast<CXXRecordDecl>(SourceRecordType->getDecl());
4058
4059      std::pair<CXXRecordDecl::conversion_iterator,
4060                CXXRecordDecl::conversion_iterator>
4061        Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4062      for (CXXRecordDecl::conversion_iterator
4063             I = Conversions.first, E = Conversions.second; I != E; ++I) {
4064        NamedDecl *D = *I;
4065        CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4066        if (isa<UsingShadowDecl>(D))
4067          D = cast<UsingShadowDecl>(D)->getTargetDecl();
4068
4069        FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4070        CXXConversionDecl *Conv;
4071        if (ConvTemplate)
4072          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4073        else
4074          Conv = cast<CXXConversionDecl>(D);
4075
4076        if (AllowExplicit || !Conv->isExplicit()) {
4077          if (ConvTemplate)
4078            S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
4079                                             ActingDC, Initializer, DestType,
4080                                             CandidateSet);
4081          else
4082            S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
4083                                     Initializer, DestType, CandidateSet);
4084        }
4085      }
4086    }
4087  }
4088
4089  // Perform overload resolution. If it fails, return the failed result.
4090  OverloadCandidateSet::iterator Best;
4091  if (OverloadingResult Result
4092        = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4093    Sequence.SetOverloadFailure(
4094                        InitializationSequence::FK_UserConversionOverloadFailed,
4095                                Result);
4096    return;
4097  }
4098
4099  FunctionDecl *Function = Best->Function;
4100  Function->setReferenced();
4101  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4102
4103  if (isa<CXXConstructorDecl>(Function)) {
4104    // Add the user-defined conversion step. Any cv-qualification conversion is
4105    // subsumed by the initialization. Per DR5, the created temporary is of the
4106    // cv-unqualified type of the destination.
4107    Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4108                                   DestType.getUnqualifiedType(),
4109                                   HadMultipleCandidates);
4110    return;
4111  }
4112
4113  // Add the user-defined conversion step that calls the conversion function.
4114  QualType ConvType = Function->getCallResultType();
4115  if (ConvType->getAs<RecordType>()) {
4116    // If we're converting to a class type, there may be an copy of
4117    // the resulting temporary object (possible to create an object of
4118    // a base class type). That copy is not a separate conversion, so
4119    // we just make a note of the actual destination type (possibly a
4120    // base class of the type returned by the conversion function) and
4121    // let the user-defined conversion step handle the conversion.
4122    Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4123                                   HadMultipleCandidates);
4124    return;
4125  }
4126
4127  Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4128                                 HadMultipleCandidates);
4129
4130  // If the conversion following the call to the conversion function
4131  // is interesting, add it as a separate step.
4132  if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4133      Best->FinalConversion.Third) {
4134    ImplicitConversionSequence ICS;
4135    ICS.setStandard();
4136    ICS.Standard = Best->FinalConversion;
4137    Sequence.AddConversionSequenceStep(ICS, DestType);
4138  }
4139}
4140
4141/// The non-zero enum values here are indexes into diagnostic alternatives.
4142enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4143
4144/// Determines whether this expression is an acceptable ICR source.
4145static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
4146                                         bool isAddressOf, bool &isWeakAccess) {
4147  // Skip parens.
4148  e = e->IgnoreParens();
4149
4150  // Skip address-of nodes.
4151  if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4152    if (op->getOpcode() == UO_AddrOf)
4153      return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4154                                isWeakAccess);
4155
4156  // Skip certain casts.
4157  } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4158    switch (ce->getCastKind()) {
4159    case CK_Dependent:
4160    case CK_BitCast:
4161    case CK_LValueBitCast:
4162    case CK_NoOp:
4163      return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
4164
4165    case CK_ArrayToPointerDecay:
4166      return IIK_nonscalar;
4167
4168    case CK_NullToPointer:
4169      return IIK_okay;
4170
4171    default:
4172      break;
4173    }
4174
4175  // If we have a declaration reference, it had better be a local variable.
4176  } else if (isa<DeclRefExpr>(e)) {
4177    // set isWeakAccess to true, to mean that there will be an implicit
4178    // load which requires a cleanup.
4179    if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4180      isWeakAccess = true;
4181
4182    if (!isAddressOf) return IIK_nonlocal;
4183
4184    VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4185    if (!var) return IIK_nonlocal;
4186
4187    return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
4188
4189  // If we have a conditional operator, check both sides.
4190  } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
4191    if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4192                                                isWeakAccess))
4193      return iik;
4194
4195    return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
4196
4197  // These are never scalar.
4198  } else if (isa<ArraySubscriptExpr>(e)) {
4199    return IIK_nonscalar;
4200
4201  // Otherwise, it needs to be a null pointer constant.
4202  } else {
4203    return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4204            ? IIK_okay : IIK_nonlocal);
4205  }
4206
4207  return IIK_nonlocal;
4208}
4209
4210/// Check whether the given expression is a valid operand for an
4211/// indirect copy/restore.
4212static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4213  assert(src->isRValue());
4214  bool isWeakAccess = false;
4215  InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4216  // If isWeakAccess to true, there will be an implicit
4217  // load which requires a cleanup.
4218  if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4219    S.ExprNeedsCleanups = true;
4220
4221  if (iik == IIK_okay) return;
4222
4223  S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4224    << ((unsigned) iik - 1)  // shift index into diagnostic explanations
4225    << src->getSourceRange();
4226}
4227
4228/// \brief Determine whether we have compatible array types for the
4229/// purposes of GNU by-copy array initialization.
4230static bool hasCompatibleArrayTypes(ASTContext &Context,
4231                                    const ArrayType *Dest,
4232                                    const ArrayType *Source) {
4233  // If the source and destination array types are equivalent, we're
4234  // done.
4235  if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4236    return true;
4237
4238  // Make sure that the element types are the same.
4239  if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4240    return false;
4241
4242  // The only mismatch we allow is when the destination is an
4243  // incomplete array type and the source is a constant array type.
4244  return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4245}
4246
4247static bool tryObjCWritebackConversion(Sema &S,
4248                                       InitializationSequence &Sequence,
4249                                       const InitializedEntity &Entity,
4250                                       Expr *Initializer) {
4251  bool ArrayDecay = false;
4252  QualType ArgType = Initializer->getType();
4253  QualType ArgPointee;
4254  if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4255    ArrayDecay = true;
4256    ArgPointee = ArgArrayType->getElementType();
4257    ArgType = S.Context.getPointerType(ArgPointee);
4258  }
4259
4260  // Handle write-back conversion.
4261  QualType ConvertedArgType;
4262  if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4263                                   ConvertedArgType))
4264    return false;
4265
4266  // We should copy unless we're passing to an argument explicitly
4267  // marked 'out'.
4268  bool ShouldCopy = true;
4269  if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4270    ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4271
4272  // Do we need an lvalue conversion?
4273  if (ArrayDecay || Initializer->isGLValue()) {
4274    ImplicitConversionSequence ICS;
4275    ICS.setStandard();
4276    ICS.Standard.setAsIdentityConversion();
4277
4278    QualType ResultType;
4279    if (ArrayDecay) {
4280      ICS.Standard.First = ICK_Array_To_Pointer;
4281      ResultType = S.Context.getPointerType(ArgPointee);
4282    } else {
4283      ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4284      ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4285    }
4286
4287    Sequence.AddConversionSequenceStep(ICS, ResultType);
4288  }
4289
4290  Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4291  return true;
4292}
4293
4294static bool TryOCLSamplerInitialization(Sema &S,
4295                                        InitializationSequence &Sequence,
4296                                        QualType DestType,
4297                                        Expr *Initializer) {
4298  if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4299    !Initializer->isIntegerConstantExpr(S.getASTContext()))
4300    return false;
4301
4302  Sequence.AddOCLSamplerInitStep(DestType);
4303  return true;
4304}
4305
4306//
4307// OpenCL 1.2 spec, s6.12.10
4308//
4309// The event argument can also be used to associate the
4310// async_work_group_copy with a previous async copy allowing
4311// an event to be shared by multiple async copies; otherwise
4312// event should be zero.
4313//
4314static bool TryOCLZeroEventInitialization(Sema &S,
4315                                          InitializationSequence &Sequence,
4316                                          QualType DestType,
4317                                          Expr *Initializer) {
4318  if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4319      !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4320      (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4321    return false;
4322
4323  Sequence.AddOCLZeroEventStep(DestType);
4324  return true;
4325}
4326
4327InitializationSequence::InitializationSequence(Sema &S,
4328                                               const InitializedEntity &Entity,
4329                                               const InitializationKind &Kind,
4330                                               MultiExprArg Args)
4331    : FailedCandidateSet(Kind.getLocation()) {
4332  ASTContext &Context = S.Context;
4333
4334  // Eliminate non-overload placeholder types in the arguments.  We
4335  // need to do this before checking whether types are dependent
4336  // because lowering a pseudo-object expression might well give us
4337  // something of dependent type.
4338  for (unsigned I = 0, E = Args.size(); I != E; ++I)
4339    if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4340      // FIXME: should we be doing this here?
4341      ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4342      if (result.isInvalid()) {
4343        SetFailed(FK_PlaceholderType);
4344        return;
4345      }
4346      Args[I] = result.take();
4347    }
4348
4349  // C++0x [dcl.init]p16:
4350  //   The semantics of initializers are as follows. The destination type is
4351  //   the type of the object or reference being initialized and the source
4352  //   type is the type of the initializer expression. The source type is not
4353  //   defined when the initializer is a braced-init-list or when it is a
4354  //   parenthesized list of expressions.
4355  QualType DestType = Entity.getType();
4356
4357  if (DestType->isDependentType() ||
4358      Expr::hasAnyTypeDependentArguments(Args)) {
4359    SequenceKind = DependentSequence;
4360    return;
4361  }
4362
4363  // Almost everything is a normal sequence.
4364  setSequenceKind(NormalSequence);
4365
4366  QualType SourceType;
4367  Expr *Initializer = 0;
4368  if (Args.size() == 1) {
4369    Initializer = Args[0];
4370    if (!isa<InitListExpr>(Initializer))
4371      SourceType = Initializer->getType();
4372  }
4373
4374  //     - If the initializer is a (non-parenthesized) braced-init-list, the
4375  //       object is list-initialized (8.5.4).
4376  if (Kind.getKind() != InitializationKind::IK_Direct) {
4377    if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4378      TryListInitialization(S, Entity, Kind, InitList, *this);
4379      return;
4380    }
4381  }
4382
4383  //     - If the destination type is a reference type, see 8.5.3.
4384  if (DestType->isReferenceType()) {
4385    // C++0x [dcl.init.ref]p1:
4386    //   A variable declared to be a T& or T&&, that is, "reference to type T"
4387    //   (8.3.2), shall be initialized by an object, or function, of type T or
4388    //   by an object that can be converted into a T.
4389    // (Therefore, multiple arguments are not permitted.)
4390    if (Args.size() != 1)
4391      SetFailed(FK_TooManyInitsForReference);
4392    else
4393      TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
4394    return;
4395  }
4396
4397  //     - If the initializer is (), the object is value-initialized.
4398  if (Kind.getKind() == InitializationKind::IK_Value ||
4399      (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
4400    TryValueInitialization(S, Entity, Kind, *this);
4401    return;
4402  }
4403
4404  // Handle default initialization.
4405  if (Kind.getKind() == InitializationKind::IK_Default) {
4406    TryDefaultInitialization(S, Entity, Kind, *this);
4407    return;
4408  }
4409
4410  //     - If the destination type is an array of characters, an array of
4411  //       char16_t, an array of char32_t, or an array of wchar_t, and the
4412  //       initializer is a string literal, see 8.5.2.
4413  //     - Otherwise, if the destination type is an array, the program is
4414  //       ill-formed.
4415  if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
4416    if (Initializer && isa<VariableArrayType>(DestAT)) {
4417      SetFailed(FK_VariableLengthArrayHasInitializer);
4418      return;
4419    }
4420
4421    if (Initializer) {
4422      switch (IsStringInit(Initializer, DestAT, Context)) {
4423      case SIF_None:
4424        TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4425        return;
4426      case SIF_NarrowStringIntoWideChar:
4427        SetFailed(FK_NarrowStringIntoWideCharArray);
4428        return;
4429      case SIF_WideStringIntoChar:
4430        SetFailed(FK_WideStringIntoCharArray);
4431        return;
4432      case SIF_IncompatWideStringIntoWideChar:
4433        SetFailed(FK_IncompatWideStringIntoWideChar);
4434        return;
4435      case SIF_Other:
4436        break;
4437      }
4438    }
4439
4440    // Note: as an GNU C extension, we allow initialization of an
4441    // array from a compound literal that creates an array of the same
4442    // type, so long as the initializer has no side effects.
4443    if (!S.getLangOpts().CPlusPlus && Initializer &&
4444        isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4445        Initializer->getType()->isArrayType()) {
4446      const ArrayType *SourceAT
4447        = Context.getAsArrayType(Initializer->getType());
4448      if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
4449        SetFailed(FK_ArrayTypeMismatch);
4450      else if (Initializer->HasSideEffects(S.Context))
4451        SetFailed(FK_NonConstantArrayInit);
4452      else {
4453        AddArrayInitStep(DestType);
4454      }
4455    }
4456    // Note: as a GNU C++ extension, we allow list-initialization of a
4457    // class member of array type from a parenthesized initializer list.
4458    else if (S.getLangOpts().CPlusPlus &&
4459             Entity.getKind() == InitializedEntity::EK_Member &&
4460             Initializer && isa<InitListExpr>(Initializer)) {
4461      TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4462                            *this);
4463      AddParenthesizedArrayInitStep(DestType);
4464    } else if (DestAT->getElementType()->isCharType())
4465      SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
4466    else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4467      SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
4468    else
4469      SetFailed(FK_ArrayNeedsInitList);
4470
4471    return;
4472  }
4473
4474  // Determine whether we should consider writeback conversions for
4475  // Objective-C ARC.
4476  bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
4477    Entity.getKind() == InitializedEntity::EK_Parameter;
4478
4479  // We're at the end of the line for C: it's either a write-back conversion
4480  // or it's a C assignment. There's no need to check anything else.
4481  if (!S.getLangOpts().CPlusPlus) {
4482    // If allowed, check whether this is an Objective-C writeback conversion.
4483    if (allowObjCWritebackConversion &&
4484        tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
4485      return;
4486    }
4487
4488    if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4489      return;
4490
4491    if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4492      return;
4493
4494    // Handle initialization in C
4495    AddCAssignmentStep(DestType);
4496    MaybeProduceObjCObject(S, *this, Entity);
4497    return;
4498  }
4499
4500  assert(S.getLangOpts().CPlusPlus);
4501
4502  //     - If the destination type is a (possibly cv-qualified) class type:
4503  if (DestType->isRecordType()) {
4504    //     - If the initialization is direct-initialization, or if it is
4505    //       copy-initialization where the cv-unqualified version of the
4506    //       source type is the same class as, or a derived class of, the
4507    //       class of the destination, constructors are considered. [...]
4508    if (Kind.getKind() == InitializationKind::IK_Direct ||
4509        (Kind.getKind() == InitializationKind::IK_Copy &&
4510         (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4511          S.IsDerivedFrom(SourceType, DestType))))
4512      TryConstructorInitialization(S, Entity, Kind, Args,
4513                                   Entity.getType(), *this);
4514    //     - Otherwise (i.e., for the remaining copy-initialization cases),
4515    //       user-defined conversion sequences that can convert from the source
4516    //       type to the destination type or (when a conversion function is
4517    //       used) to a derived class thereof are enumerated as described in
4518    //       13.3.1.4, and the best one is chosen through overload resolution
4519    //       (13.3).
4520    else
4521      TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4522    return;
4523  }
4524
4525  if (Args.size() > 1) {
4526    SetFailed(FK_TooManyInitsForScalar);
4527    return;
4528  }
4529  assert(Args.size() == 1 && "Zero-argument case handled above");
4530
4531  //    - Otherwise, if the source type is a (possibly cv-qualified) class
4532  //      type, conversion functions are considered.
4533  if (!SourceType.isNull() && SourceType->isRecordType()) {
4534    TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4535    MaybeProduceObjCObject(S, *this, Entity);
4536    return;
4537  }
4538
4539  //    - Otherwise, the initial value of the object being initialized is the
4540  //      (possibly converted) value of the initializer expression. Standard
4541  //      conversions (Clause 4) will be used, if necessary, to convert the
4542  //      initializer expression to the cv-unqualified version of the
4543  //      destination type; no user-defined conversions are considered.
4544
4545  ImplicitConversionSequence ICS
4546    = S.TryImplicitConversion(Initializer, Entity.getType(),
4547                              /*SuppressUserConversions*/true,
4548                              /*AllowExplicitConversions*/ false,
4549                              /*InOverloadResolution*/ false,
4550                              /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4551                              allowObjCWritebackConversion);
4552
4553  if (ICS.isStandard() &&
4554      ICS.Standard.Second == ICK_Writeback_Conversion) {
4555    // Objective-C ARC writeback conversion.
4556
4557    // We should copy unless we're passing to an argument explicitly
4558    // marked 'out'.
4559    bool ShouldCopy = true;
4560    if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4561      ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4562
4563    // If there was an lvalue adjustment, add it as a separate conversion.
4564    if (ICS.Standard.First == ICK_Array_To_Pointer ||
4565        ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4566      ImplicitConversionSequence LvalueICS;
4567      LvalueICS.setStandard();
4568      LvalueICS.Standard.setAsIdentityConversion();
4569      LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4570      LvalueICS.Standard.First = ICS.Standard.First;
4571      AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
4572    }
4573
4574    AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4575  } else if (ICS.isBad()) {
4576    DeclAccessPair dap;
4577    if (Initializer->getType() == Context.OverloadTy &&
4578          !S.ResolveAddressOfOverloadedFunction(Initializer
4579                      , DestType, false, dap))
4580      SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4581    else
4582      SetFailed(InitializationSequence::FK_ConversionFailed);
4583  } else {
4584    AddConversionSequenceStep(ICS, Entity.getType());
4585
4586    MaybeProduceObjCObject(S, *this, Entity);
4587  }
4588}
4589
4590InitializationSequence::~InitializationSequence() {
4591  for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
4592                                          StepEnd = Steps.end();
4593       Step != StepEnd; ++Step)
4594    Step->Destroy();
4595}
4596
4597//===----------------------------------------------------------------------===//
4598// Perform initialization
4599//===----------------------------------------------------------------------===//
4600static Sema::AssignmentAction
4601getAssignmentAction(const InitializedEntity &Entity) {
4602  switch(Entity.getKind()) {
4603  case InitializedEntity::EK_Variable:
4604  case InitializedEntity::EK_New:
4605  case InitializedEntity::EK_Exception:
4606  case InitializedEntity::EK_Base:
4607  case InitializedEntity::EK_Delegating:
4608    return Sema::AA_Initializing;
4609
4610  case InitializedEntity::EK_Parameter:
4611    if (Entity.getDecl() &&
4612        isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4613      return Sema::AA_Sending;
4614
4615    return Sema::AA_Passing;
4616
4617  case InitializedEntity::EK_Result:
4618    return Sema::AA_Returning;
4619
4620  case InitializedEntity::EK_Temporary:
4621    // FIXME: Can we tell apart casting vs. converting?
4622    return Sema::AA_Casting;
4623
4624  case InitializedEntity::EK_Member:
4625  case InitializedEntity::EK_ArrayElement:
4626  case InitializedEntity::EK_VectorElement:
4627  case InitializedEntity::EK_ComplexElement:
4628  case InitializedEntity::EK_BlockElement:
4629  case InitializedEntity::EK_LambdaCapture:
4630  case InitializedEntity::EK_CompoundLiteralInit:
4631    return Sema::AA_Initializing;
4632  }
4633
4634  llvm_unreachable("Invalid EntityKind!");
4635}
4636
4637/// \brief Whether we should bind a created object as a temporary when
4638/// initializing the given entity.
4639static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
4640  switch (Entity.getKind()) {
4641  case InitializedEntity::EK_ArrayElement:
4642  case InitializedEntity::EK_Member:
4643  case InitializedEntity::EK_Result:
4644  case InitializedEntity::EK_New:
4645  case InitializedEntity::EK_Variable:
4646  case InitializedEntity::EK_Base:
4647  case InitializedEntity::EK_Delegating:
4648  case InitializedEntity::EK_VectorElement:
4649  case InitializedEntity::EK_ComplexElement:
4650  case InitializedEntity::EK_Exception:
4651  case InitializedEntity::EK_BlockElement:
4652  case InitializedEntity::EK_LambdaCapture:
4653  case InitializedEntity::EK_CompoundLiteralInit:
4654    return false;
4655
4656  case InitializedEntity::EK_Parameter:
4657  case InitializedEntity::EK_Temporary:
4658    return true;
4659  }
4660
4661  llvm_unreachable("missed an InitializedEntity kind?");
4662}
4663
4664/// \brief Whether the given entity, when initialized with an object
4665/// created for that initialization, requires destruction.
4666static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4667  switch (Entity.getKind()) {
4668    case InitializedEntity::EK_Result:
4669    case InitializedEntity::EK_New:
4670    case InitializedEntity::EK_Base:
4671    case InitializedEntity::EK_Delegating:
4672    case InitializedEntity::EK_VectorElement:
4673    case InitializedEntity::EK_ComplexElement:
4674    case InitializedEntity::EK_BlockElement:
4675    case InitializedEntity::EK_LambdaCapture:
4676      return false;
4677
4678    case InitializedEntity::EK_Member:
4679    case InitializedEntity::EK_Variable:
4680    case InitializedEntity::EK_Parameter:
4681    case InitializedEntity::EK_Temporary:
4682    case InitializedEntity::EK_ArrayElement:
4683    case InitializedEntity::EK_Exception:
4684    case InitializedEntity::EK_CompoundLiteralInit:
4685      return true;
4686  }
4687
4688  llvm_unreachable("missed an InitializedEntity kind?");
4689}
4690
4691/// \brief Look for copy and move constructors and constructor templates, for
4692/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4693static void LookupCopyAndMoveConstructors(Sema &S,
4694                                          OverloadCandidateSet &CandidateSet,
4695                                          CXXRecordDecl *Class,
4696                                          Expr *CurInitExpr) {
4697  DeclContext::lookup_result R = S.LookupConstructors(Class);
4698  // The container holding the constructors can under certain conditions
4699  // be changed while iterating (e.g. because of deserialization).
4700  // To be safe we copy the lookup results to a new container.
4701  SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
4702  for (SmallVector<NamedDecl*, 16>::iterator
4703         CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4704    NamedDecl *D = *CI;
4705    CXXConstructorDecl *Constructor = 0;
4706
4707    if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
4708      // Handle copy/moveconstructors, only.
4709      if (!Constructor || Constructor->isInvalidDecl() ||
4710          !Constructor->isCopyOrMoveConstructor() ||
4711          !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4712        continue;
4713
4714      DeclAccessPair FoundDecl
4715        = DeclAccessPair::make(Constructor, Constructor->getAccess());
4716      S.AddOverloadCandidate(Constructor, FoundDecl,
4717                             CurInitExpr, CandidateSet);
4718      continue;
4719    }
4720
4721    // Handle constructor templates.
4722    FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
4723    if (ConstructorTmpl->isInvalidDecl())
4724      continue;
4725
4726    Constructor = cast<CXXConstructorDecl>(
4727                                         ConstructorTmpl->getTemplatedDecl());
4728    if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4729      continue;
4730
4731    // FIXME: Do we need to limit this to copy-constructor-like
4732    // candidates?
4733    DeclAccessPair FoundDecl
4734      = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4735    S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4736                                   CurInitExpr, CandidateSet, true);
4737  }
4738}
4739
4740/// \brief Get the location at which initialization diagnostics should appear.
4741static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4742                                           Expr *Initializer) {
4743  switch (Entity.getKind()) {
4744  case InitializedEntity::EK_Result:
4745    return Entity.getReturnLoc();
4746
4747  case InitializedEntity::EK_Exception:
4748    return Entity.getThrowLoc();
4749
4750  case InitializedEntity::EK_Variable:
4751    return Entity.getDecl()->getLocation();
4752
4753  case InitializedEntity::EK_LambdaCapture:
4754    return Entity.getCaptureLoc();
4755
4756  case InitializedEntity::EK_ArrayElement:
4757  case InitializedEntity::EK_Member:
4758  case InitializedEntity::EK_Parameter:
4759  case InitializedEntity::EK_Temporary:
4760  case InitializedEntity::EK_New:
4761  case InitializedEntity::EK_Base:
4762  case InitializedEntity::EK_Delegating:
4763  case InitializedEntity::EK_VectorElement:
4764  case InitializedEntity::EK_ComplexElement:
4765  case InitializedEntity::EK_BlockElement:
4766  case InitializedEntity::EK_CompoundLiteralInit:
4767    return Initializer->getLocStart();
4768  }
4769  llvm_unreachable("missed an InitializedEntity kind?");
4770}
4771
4772/// \brief Make a (potentially elidable) temporary copy of the object
4773/// provided by the given initializer by calling the appropriate copy
4774/// constructor.
4775///
4776/// \param S The Sema object used for type-checking.
4777///
4778/// \param T The type of the temporary object, which must either be
4779/// the type of the initializer expression or a superclass thereof.
4780///
4781/// \param Entity The entity being initialized.
4782///
4783/// \param CurInit The initializer expression.
4784///
4785/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4786/// is permitted in C++03 (but not C++0x) when binding a reference to
4787/// an rvalue.
4788///
4789/// \returns An expression that copies the initializer expression into
4790/// a temporary object, or an error expression if a copy could not be
4791/// created.
4792static ExprResult CopyObject(Sema &S,
4793                             QualType T,
4794                             const InitializedEntity &Entity,
4795                             ExprResult CurInit,
4796                             bool IsExtraneousCopy) {
4797  // Determine which class type we're copying to.
4798  Expr *CurInitExpr = (Expr *)CurInit.get();
4799  CXXRecordDecl *Class = 0;
4800  if (const RecordType *Record = T->getAs<RecordType>())
4801    Class = cast<CXXRecordDecl>(Record->getDecl());
4802  if (!Class)
4803    return CurInit;
4804
4805  // C++0x [class.copy]p32:
4806  //   When certain criteria are met, an implementation is allowed to
4807  //   omit the copy/move construction of a class object, even if the
4808  //   copy/move constructor and/or destructor for the object have
4809  //   side effects. [...]
4810  //     - when a temporary class object that has not been bound to a
4811  //       reference (12.2) would be copied/moved to a class object
4812  //       with the same cv-unqualified type, the copy/move operation
4813  //       can be omitted by constructing the temporary object
4814  //       directly into the target of the omitted copy/move
4815  //
4816  // Note that the other three bullets are handled elsewhere. Copy
4817  // elision for return statements and throw expressions are handled as part
4818  // of constructor initialization, while copy elision for exception handlers
4819  // is handled by the run-time.
4820  bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
4821  SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
4822
4823  // Make sure that the type we are copying is complete.
4824  if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
4825    return CurInit;
4826
4827  // Perform overload resolution using the class's copy/move constructors.
4828  // Only consider constructors and constructor templates. Per
4829  // C++0x [dcl.init]p16, second bullet to class types, this initialization
4830  // is direct-initialization.
4831  OverloadCandidateSet CandidateSet(Loc);
4832  LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
4833
4834  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4835
4836  OverloadCandidateSet::iterator Best;
4837  switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
4838  case OR_Success:
4839    break;
4840
4841  case OR_No_Viable_Function:
4842    S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4843           ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4844           : diag::err_temp_copy_no_viable)
4845      << (int)Entity.getKind() << CurInitExpr->getType()
4846      << CurInitExpr->getSourceRange();
4847    CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
4848    if (!IsExtraneousCopy || S.isSFINAEContext())
4849      return ExprError();
4850    return CurInit;
4851
4852  case OR_Ambiguous:
4853    S.Diag(Loc, diag::err_temp_copy_ambiguous)
4854      << (int)Entity.getKind() << CurInitExpr->getType()
4855      << CurInitExpr->getSourceRange();
4856    CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
4857    return ExprError();
4858
4859  case OR_Deleted:
4860    S.Diag(Loc, diag::err_temp_copy_deleted)
4861      << (int)Entity.getKind() << CurInitExpr->getType()
4862      << CurInitExpr->getSourceRange();
4863    S.NoteDeletedFunction(Best->Function);
4864    return ExprError();
4865  }
4866
4867  CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4868  SmallVector<Expr*, 8> ConstructorArgs;
4869  CurInit.release(); // Ownership transferred into MultiExprArg, below.
4870
4871  S.CheckConstructorAccess(Loc, Constructor, Entity,
4872                           Best->FoundDecl.getAccess(), IsExtraneousCopy);
4873
4874  if (IsExtraneousCopy) {
4875    // If this is a totally extraneous copy for C++03 reference
4876    // binding purposes, just return the original initialization
4877    // expression. We don't generate an (elided) copy operation here
4878    // because doing so would require us to pass down a flag to avoid
4879    // infinite recursion, where each step adds another extraneous,
4880    // elidable copy.
4881
4882    // Instantiate the default arguments of any extra parameters in
4883    // the selected copy constructor, as if we were going to create a
4884    // proper call to the copy constructor.
4885    for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4886      ParmVarDecl *Parm = Constructor->getParamDecl(I);
4887      if (S.RequireCompleteType(Loc, Parm->getType(),
4888                                diag::err_call_incomplete_argument))
4889        break;
4890
4891      // Build the default argument expression; we don't actually care
4892      // if this succeeds or not, because this routine will complain
4893      // if there was a problem.
4894      S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4895    }
4896
4897    return S.Owned(CurInitExpr);
4898  }
4899
4900  // Determine the arguments required to actually perform the
4901  // constructor call (we might have derived-to-base conversions, or
4902  // the copy constructor may have default arguments).
4903  if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
4904    return ExprError();
4905
4906  // Actually perform the constructor call.
4907  CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
4908                                    ConstructorArgs,
4909                                    HadMultipleCandidates,
4910                                    /*ListInit*/ false,
4911                                    /*ZeroInit*/ false,
4912                                    CXXConstructExpr::CK_Complete,
4913                                    SourceRange());
4914
4915  // If we're supposed to bind temporaries, do so.
4916  if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4917    CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4918  return CurInit;
4919}
4920
4921/// \brief Check whether elidable copy construction for binding a reference to
4922/// a temporary would have succeeded if we were building in C++98 mode, for
4923/// -Wc++98-compat.
4924static void CheckCXX98CompatAccessibleCopy(Sema &S,
4925                                           const InitializedEntity &Entity,
4926                                           Expr *CurInitExpr) {
4927  assert(S.getLangOpts().CPlusPlus11);
4928
4929  const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4930  if (!Record)
4931    return;
4932
4933  SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4934  if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4935        == DiagnosticsEngine::Ignored)
4936    return;
4937
4938  // Find constructors which would have been considered.
4939  OverloadCandidateSet CandidateSet(Loc);
4940  LookupCopyAndMoveConstructors(
4941      S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4942
4943  // Perform overload resolution.
4944  OverloadCandidateSet::iterator Best;
4945  OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4946
4947  PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4948    << OR << (int)Entity.getKind() << CurInitExpr->getType()
4949    << CurInitExpr->getSourceRange();
4950
4951  switch (OR) {
4952  case OR_Success:
4953    S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4954                             Entity, Best->FoundDecl.getAccess(), Diag);
4955    // FIXME: Check default arguments as far as that's possible.
4956    break;
4957
4958  case OR_No_Viable_Function:
4959    S.Diag(Loc, Diag);
4960    CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
4961    break;
4962
4963  case OR_Ambiguous:
4964    S.Diag(Loc, Diag);
4965    CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
4966    break;
4967
4968  case OR_Deleted:
4969    S.Diag(Loc, Diag);
4970    S.NoteDeletedFunction(Best->Function);
4971    break;
4972  }
4973}
4974
4975void InitializationSequence::PrintInitLocationNote(Sema &S,
4976                                              const InitializedEntity &Entity) {
4977  if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4978    if (Entity.getDecl()->getLocation().isInvalid())
4979      return;
4980
4981    if (Entity.getDecl()->getDeclName())
4982      S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4983        << Entity.getDecl()->getDeclName();
4984    else
4985      S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4986  }
4987}
4988
4989static bool isReferenceBinding(const InitializationSequence::Step &s) {
4990  return s.Kind == InitializationSequence::SK_BindReference ||
4991         s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4992}
4993
4994/// Returns true if the parameters describe a constructor initialization of
4995/// an explicit temporary object, e.g. "Point(x, y)".
4996static bool isExplicitTemporary(const InitializedEntity &Entity,
4997                                const InitializationKind &Kind,
4998                                unsigned NumArgs) {
4999  switch (Entity.getKind()) {
5000  case InitializedEntity::EK_Temporary:
5001  case InitializedEntity::EK_CompoundLiteralInit:
5002    break;
5003  default:
5004    return false;
5005  }
5006
5007  switch (Kind.getKind()) {
5008  case InitializationKind::IK_DirectList:
5009    return true;
5010  // FIXME: Hack to work around cast weirdness.
5011  case InitializationKind::IK_Direct:
5012  case InitializationKind::IK_Value:
5013    return NumArgs != 1;
5014  default:
5015    return false;
5016  }
5017}
5018
5019static ExprResult
5020PerformConstructorInitialization(Sema &S,
5021                                 const InitializedEntity &Entity,
5022                                 const InitializationKind &Kind,
5023                                 MultiExprArg Args,
5024                                 const InitializationSequence::Step& Step,
5025                                 bool &ConstructorInitRequiresZeroInit,
5026                                 bool IsListInitialization) {
5027  unsigned NumArgs = Args.size();
5028  CXXConstructorDecl *Constructor
5029    = cast<CXXConstructorDecl>(Step.Function.Function);
5030  bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5031
5032  // Build a call to the selected constructor.
5033  SmallVector<Expr*, 8> ConstructorArgs;
5034  SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5035                         ? Kind.getEqualLoc()
5036                         : Kind.getLocation();
5037
5038  if (Kind.getKind() == InitializationKind::IK_Default) {
5039    // Force even a trivial, implicit default constructor to be
5040    // semantically checked. We do this explicitly because we don't build
5041    // the definition for completely trivial constructors.
5042    assert(Constructor->getParent() && "No parent class for constructor.");
5043    if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
5044        Constructor->isTrivial() && !Constructor->isUsed(false))
5045      S.DefineImplicitDefaultConstructor(Loc, Constructor);
5046  }
5047
5048  ExprResult CurInit = S.Owned((Expr *)0);
5049
5050  // C++ [over.match.copy]p1:
5051  //   - When initializing a temporary to be bound to the first parameter
5052  //     of a constructor that takes a reference to possibly cv-qualified
5053  //     T as its first argument, called with a single argument in the
5054  //     context of direct-initialization, explicit conversion functions
5055  //     are also considered.
5056  bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5057                           Args.size() == 1 &&
5058                           Constructor->isCopyOrMoveConstructor();
5059
5060  // Determine the arguments required to actually perform the constructor
5061  // call.
5062  if (S.CompleteConstructorCall(Constructor, Args,
5063                                Loc, ConstructorArgs,
5064                                AllowExplicitConv,
5065                                IsListInitialization))
5066    return ExprError();
5067
5068
5069  if (isExplicitTemporary(Entity, Kind, NumArgs)) {
5070    // An explicitly-constructed temporary, e.g., X(1, 2).
5071    S.MarkFunctionReferenced(Loc, Constructor);
5072    if (S.DiagnoseUseOfDecl(Constructor, Loc))
5073      return ExprError();
5074
5075    TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5076    if (!TSInfo)
5077      TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
5078    SourceRange ParenRange;
5079    if (Kind.getKind() != InitializationKind::IK_DirectList)
5080      ParenRange = Kind.getParenRange();
5081
5082    CurInit = S.Owned(
5083      new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
5084                                             TSInfo, ConstructorArgs,
5085                                             ParenRange, IsListInitialization,
5086                                             HadMultipleCandidates,
5087                                             ConstructorInitRequiresZeroInit));
5088  } else {
5089    CXXConstructExpr::ConstructionKind ConstructKind =
5090      CXXConstructExpr::CK_Complete;
5091
5092    if (Entity.getKind() == InitializedEntity::EK_Base) {
5093      ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5094        CXXConstructExpr::CK_VirtualBase :
5095        CXXConstructExpr::CK_NonVirtualBase;
5096    } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5097      ConstructKind = CXXConstructExpr::CK_Delegating;
5098    }
5099
5100    // Only get the parenthesis range if it is a direct construction.
5101    SourceRange parenRange =
5102        Kind.getKind() == InitializationKind::IK_Direct ?
5103        Kind.getParenRange() : SourceRange();
5104
5105    // If the entity allows NRVO, mark the construction as elidable
5106    // unconditionally.
5107    if (Entity.allowsNRVO())
5108      CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5109                                        Constructor, /*Elidable=*/true,
5110                                        ConstructorArgs,
5111                                        HadMultipleCandidates,
5112                                        IsListInitialization,
5113                                        ConstructorInitRequiresZeroInit,
5114                                        ConstructKind,
5115                                        parenRange);
5116    else
5117      CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5118                                        Constructor,
5119                                        ConstructorArgs,
5120                                        HadMultipleCandidates,
5121                                        IsListInitialization,
5122                                        ConstructorInitRequiresZeroInit,
5123                                        ConstructKind,
5124                                        parenRange);
5125  }
5126  if (CurInit.isInvalid())
5127    return ExprError();
5128
5129  // Only check access if all of that succeeded.
5130  S.CheckConstructorAccess(Loc, Constructor, Entity,
5131                           Step.Function.FoundDecl.getAccess());
5132  if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5133    return ExprError();
5134
5135  if (shouldBindAsTemporary(Entity))
5136    CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
5137
5138  return CurInit;
5139}
5140
5141/// Determine whether the specified InitializedEntity definitely has a lifetime
5142/// longer than the current full-expression. Conservatively returns false if
5143/// it's unclear.
5144static bool
5145InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5146  const InitializedEntity *Top = &Entity;
5147  while (Top->getParent())
5148    Top = Top->getParent();
5149
5150  switch (Top->getKind()) {
5151  case InitializedEntity::EK_Variable:
5152  case InitializedEntity::EK_Result:
5153  case InitializedEntity::EK_Exception:
5154  case InitializedEntity::EK_Member:
5155  case InitializedEntity::EK_New:
5156  case InitializedEntity::EK_Base:
5157  case InitializedEntity::EK_Delegating:
5158    return true;
5159
5160  case InitializedEntity::EK_ArrayElement:
5161  case InitializedEntity::EK_VectorElement:
5162  case InitializedEntity::EK_BlockElement:
5163  case InitializedEntity::EK_ComplexElement:
5164    // Could not determine what the full initialization is. Assume it might not
5165    // outlive the full-expression.
5166    return false;
5167
5168  case InitializedEntity::EK_Parameter:
5169  case InitializedEntity::EK_Temporary:
5170  case InitializedEntity::EK_LambdaCapture:
5171  case InitializedEntity::EK_CompoundLiteralInit:
5172    // The entity being initialized might not outlive the full-expression.
5173    return false;
5174  }
5175
5176  llvm_unreachable("unknown entity kind");
5177}
5178
5179/// Determine the declaration which an initialized entity ultimately refers to,
5180/// for the purpose of lifetime-extending a temporary bound to a reference in
5181/// the initialization of \p Entity.
5182static const ValueDecl *
5183getDeclForTemporaryLifetimeExtension(const InitializedEntity &Entity,
5184                                     const ValueDecl *FallbackDecl = 0) {
5185  // C++11 [class.temporary]p5:
5186  switch (Entity.getKind()) {
5187  case InitializedEntity::EK_Variable:
5188    //   The temporary [...] persists for the lifetime of the reference
5189    return Entity.getDecl();
5190
5191  case InitializedEntity::EK_Member:
5192    // For subobjects, we look at the complete object.
5193    if (Entity.getParent())
5194      return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5195                                                  Entity.getDecl());
5196
5197    //   except:
5198    //   -- A temporary bound to a reference member in a constructor's
5199    //      ctor-initializer persists until the constructor exits.
5200    return Entity.getDecl();
5201
5202  case InitializedEntity::EK_Parameter:
5203    //   -- A temporary bound to a reference parameter in a function call
5204    //      persists until the completion of the full-expression containing
5205    //      the call.
5206  case InitializedEntity::EK_Result:
5207    //   -- The lifetime of a temporary bound to the returned value in a
5208    //      function return statement is not extended; the temporary is
5209    //      destroyed at the end of the full-expression in the return statement.
5210  case InitializedEntity::EK_New:
5211    //   -- A temporary bound to a reference in a new-initializer persists
5212    //      until the completion of the full-expression containing the
5213    //      new-initializer.
5214    return 0;
5215
5216  case InitializedEntity::EK_Temporary:
5217  case InitializedEntity::EK_CompoundLiteralInit:
5218    // We don't yet know the storage duration of the surrounding temporary.
5219    // Assume it's got full-expression duration for now, it will patch up our
5220    // storage duration if that's not correct.
5221    return 0;
5222
5223  case InitializedEntity::EK_ArrayElement:
5224    // For subobjects, we look at the complete object.
5225    return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5226                                                FallbackDecl);
5227
5228  case InitializedEntity::EK_Base:
5229  case InitializedEntity::EK_Delegating:
5230    // We can reach this case for aggregate initialization in a constructor:
5231    //   struct A { int &&r; };
5232    //   struct B : A { B() : A{0} {} };
5233    // In this case, use the innermost field decl as the context.
5234    return FallbackDecl;
5235
5236  case InitializedEntity::EK_BlockElement:
5237  case InitializedEntity::EK_LambdaCapture:
5238  case InitializedEntity::EK_Exception:
5239  case InitializedEntity::EK_VectorElement:
5240  case InitializedEntity::EK_ComplexElement:
5241    llvm_unreachable("should not materialize a temporary to initialize this");
5242  }
5243  llvm_unreachable("unknown entity kind");
5244}
5245
5246static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD);
5247
5248/// Update a glvalue expression that is used as the initializer of a reference
5249/// to note that its lifetime is extended.
5250static void performReferenceExtension(Expr *Init, const ValueDecl *ExtendingD) {
5251  if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5252    if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5253      // This is just redundant braces around an initializer. Step over it.
5254      Init = ILE->getInit(0);
5255    }
5256  }
5257
5258  if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5259    // Update the storage duration of the materialized temporary.
5260    // FIXME: Rebuild the expression instead of mutating it.
5261    ME->setExtendingDecl(ExtendingD);
5262    performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingD);
5263  }
5264}
5265
5266/// Update a prvalue expression that is going to be materialized as a
5267/// lifetime-extended temporary.
5268static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD) {
5269  // Dig out the expression which constructs the extended temporary.
5270  SmallVector<const Expr *, 2> CommaLHSs;
5271  SmallVector<SubobjectAdjustment, 2> Adjustments;
5272  Init = const_cast<Expr *>(
5273      Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5274
5275  if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5276    if (ILE->initializesStdInitializerList() || ILE->getType()->isArrayType()) {
5277      // FIXME: If this is an InitListExpr which creates a std::initializer_list
5278      //        object, we also need to lifetime-extend the underlying array
5279      //        itself. Fix the representation to explicitly materialize an
5280      //        array temporary so we can model this properly.
5281      for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
5282        performLifetimeExtension(ILE->getInit(I), ExtendingD);
5283      return;
5284    }
5285
5286    CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl();
5287    if (RD) {
5288      assert(RD->isAggregate() && "aggregate init on non-aggregate");
5289
5290      // If we lifetime-extend a braced initializer which is initializing an
5291      // aggregate, and that aggregate contains reference members which are
5292      // bound to temporaries, those temporaries are also lifetime-extended.
5293      if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5294          ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
5295        performReferenceExtension(ILE->getInit(0), ExtendingD);
5296      else {
5297        unsigned Index = 0;
5298        for (RecordDecl::field_iterator I = RD->field_begin(),
5299                                        E = RD->field_end();
5300             I != E; ++I) {
5301          if (I->isUnnamedBitfield())
5302            continue;
5303          if (I->getType()->isReferenceType())
5304            performReferenceExtension(ILE->getInit(Index), ExtendingD);
5305          else if (isa<InitListExpr>(ILE->getInit(Index)))
5306            // This may be either aggregate-initialization of a member or
5307            // initialization of a std::initializer_list object. Either way,
5308            // we should recursively lifetime-extend that initializer.
5309            performLifetimeExtension(ILE->getInit(Index), ExtendingD);
5310          ++Index;
5311        }
5312      }
5313    }
5314  }
5315}
5316
5317ExprResult
5318InitializationSequence::Perform(Sema &S,
5319                                const InitializedEntity &Entity,
5320                                const InitializationKind &Kind,
5321                                MultiExprArg Args,
5322                                QualType *ResultType) {
5323  if (Failed()) {
5324    Diagnose(S, Entity, Kind, Args);
5325    return ExprError();
5326  }
5327
5328  if (getKind() == DependentSequence) {
5329    // If the declaration is a non-dependent, incomplete array type
5330    // that has an initializer, then its type will be completed once
5331    // the initializer is instantiated.
5332    if (ResultType && !Entity.getType()->isDependentType() &&
5333        Args.size() == 1) {
5334      QualType DeclType = Entity.getType();
5335      if (const IncompleteArrayType *ArrayT
5336                           = S.Context.getAsIncompleteArrayType(DeclType)) {
5337        // FIXME: We don't currently have the ability to accurately
5338        // compute the length of an initializer list without
5339        // performing full type-checking of the initializer list
5340        // (since we have to determine where braces are implicitly
5341        // introduced and such).  So, we fall back to making the array
5342        // type a dependently-sized array type with no specified
5343        // bound.
5344        if (isa<InitListExpr>((Expr *)Args[0])) {
5345          SourceRange Brackets;
5346
5347          // Scavange the location of the brackets from the entity, if we can.
5348          if (DeclaratorDecl *DD = Entity.getDecl()) {
5349            if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5350              TypeLoc TL = TInfo->getTypeLoc();
5351              if (IncompleteArrayTypeLoc ArrayLoc =
5352                      TL.getAs<IncompleteArrayTypeLoc>())
5353                Brackets = ArrayLoc.getBracketsRange();
5354            }
5355          }
5356
5357          *ResultType
5358            = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5359                                                   /*NumElts=*/0,
5360                                                   ArrayT->getSizeModifier(),
5361                                       ArrayT->getIndexTypeCVRQualifiers(),
5362                                                   Brackets);
5363        }
5364
5365      }
5366    }
5367    if (Kind.getKind() == InitializationKind::IK_Direct &&
5368        !Kind.isExplicitCast()) {
5369      // Rebuild the ParenListExpr.
5370      SourceRange ParenRange = Kind.getParenRange();
5371      return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
5372                                  Args);
5373    }
5374    assert(Kind.getKind() == InitializationKind::IK_Copy ||
5375           Kind.isExplicitCast() ||
5376           Kind.getKind() == InitializationKind::IK_DirectList);
5377    return ExprResult(Args[0]);
5378  }
5379
5380  // No steps means no initialization.
5381  if (Steps.empty())
5382    return S.Owned((Expr *)0);
5383
5384  if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
5385      Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
5386      Entity.getKind() != InitializedEntity::EK_Parameter) {
5387    // Produce a C++98 compatibility warning if we are initializing a reference
5388    // from an initializer list. For parameters, we produce a better warning
5389    // elsewhere.
5390    Expr *Init = Args[0];
5391    S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5392      << Init->getSourceRange();
5393  }
5394
5395  // Diagnose cases where we initialize a pointer to an array temporary, and the
5396  // pointer obviously outlives the temporary.
5397  if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
5398      Entity.getType()->isPointerType() &&
5399      InitializedEntityOutlivesFullExpression(Entity)) {
5400    Expr *Init = Args[0];
5401    Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5402    if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5403      S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5404        << Init->getSourceRange();
5405  }
5406
5407  QualType DestType = Entity.getType().getNonReferenceType();
5408  // FIXME: Ugly hack around the fact that Entity.getType() is not
5409  // the same as Entity.getDecl()->getType() in cases involving type merging,
5410  //  and we want latter when it makes sense.
5411  if (ResultType)
5412    *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
5413                                     Entity.getType();
5414
5415  ExprResult CurInit = S.Owned((Expr *)0);
5416
5417  // For initialization steps that start with a single initializer,
5418  // grab the only argument out the Args and place it into the "current"
5419  // initializer.
5420  switch (Steps.front().Kind) {
5421  case SK_ResolveAddressOfOverloadedFunction:
5422  case SK_CastDerivedToBaseRValue:
5423  case SK_CastDerivedToBaseXValue:
5424  case SK_CastDerivedToBaseLValue:
5425  case SK_BindReference:
5426  case SK_BindReferenceToTemporary:
5427  case SK_ExtraneousCopyToTemporary:
5428  case SK_UserConversion:
5429  case SK_QualificationConversionLValue:
5430  case SK_QualificationConversionXValue:
5431  case SK_QualificationConversionRValue:
5432  case SK_LValueToRValue:
5433  case SK_ConversionSequence:
5434  case SK_ListInitialization:
5435  case SK_UnwrapInitList:
5436  case SK_RewrapInitList:
5437  case SK_CAssignment:
5438  case SK_StringInit:
5439  case SK_ObjCObjectConversion:
5440  case SK_ArrayInit:
5441  case SK_ParenthesizedArrayInit:
5442  case SK_PassByIndirectCopyRestore:
5443  case SK_PassByIndirectRestore:
5444  case SK_ProduceObjCObject:
5445  case SK_StdInitializerList:
5446  case SK_OCLSamplerInit:
5447  case SK_OCLZeroEvent: {
5448    assert(Args.size() == 1);
5449    CurInit = Args[0];
5450    if (!CurInit.get()) return ExprError();
5451    break;
5452  }
5453
5454  case SK_ConstructorInitialization:
5455  case SK_ListConstructorCall:
5456  case SK_ZeroInitialization:
5457    break;
5458  }
5459
5460  // Walk through the computed steps for the initialization sequence,
5461  // performing the specified conversions along the way.
5462  bool ConstructorInitRequiresZeroInit = false;
5463  for (step_iterator Step = step_begin(), StepEnd = step_end();
5464       Step != StepEnd; ++Step) {
5465    if (CurInit.isInvalid())
5466      return ExprError();
5467
5468    QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
5469
5470    switch (Step->Kind) {
5471    case SK_ResolveAddressOfOverloadedFunction:
5472      // Overload resolution determined which function invoke; update the
5473      // initializer to reflect that choice.
5474      S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
5475      if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5476        return ExprError();
5477      CurInit = S.FixOverloadedFunctionReference(CurInit,
5478                                                 Step->Function.FoundDecl,
5479                                                 Step->Function.Function);
5480      break;
5481
5482    case SK_CastDerivedToBaseRValue:
5483    case SK_CastDerivedToBaseXValue:
5484    case SK_CastDerivedToBaseLValue: {
5485      // We have a derived-to-base cast that produces either an rvalue or an
5486      // lvalue. Perform that cast.
5487
5488      CXXCastPath BasePath;
5489
5490      // Casts to inaccessible base classes are allowed with C-style casts.
5491      bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5492      if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
5493                                         CurInit.get()->getLocStart(),
5494                                         CurInit.get()->getSourceRange(),
5495                                         &BasePath, IgnoreBaseAccess))
5496        return ExprError();
5497
5498      if (S.BasePathInvolvesVirtualBase(BasePath)) {
5499        QualType T = SourceType;
5500        if (const PointerType *Pointer = T->getAs<PointerType>())
5501          T = Pointer->getPointeeType();
5502        if (const RecordType *RecordTy = T->getAs<RecordType>())
5503          S.MarkVTableUsed(CurInit.get()->getLocStart(),
5504                           cast<CXXRecordDecl>(RecordTy->getDecl()));
5505      }
5506
5507      ExprValueKind VK =
5508          Step->Kind == SK_CastDerivedToBaseLValue ?
5509              VK_LValue :
5510              (Step->Kind == SK_CastDerivedToBaseXValue ?
5511                   VK_XValue :
5512                   VK_RValue);
5513      CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5514                                                 Step->Type,
5515                                                 CK_DerivedToBase,
5516                                                 CurInit.get(),
5517                                                 &BasePath, VK));
5518      break;
5519    }
5520
5521    case SK_BindReference:
5522      // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5523      if (CurInit.get()->refersToBitField()) {
5524        // We don't necessarily have an unambiguous source bit-field.
5525        FieldDecl *BitField = CurInit.get()->getSourceBitField();
5526        S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
5527          << Entity.getType().isVolatileQualified()
5528          << (BitField ? BitField->getDeclName() : DeclarationName())
5529          << (BitField != NULL)
5530          << CurInit.get()->getSourceRange();
5531        if (BitField)
5532          S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5533
5534        return ExprError();
5535      }
5536
5537      if (CurInit.get()->refersToVectorElement()) {
5538        // References cannot bind to vector elements.
5539        S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5540          << Entity.getType().isVolatileQualified()
5541          << CurInit.get()->getSourceRange();
5542        PrintInitLocationNote(S, Entity);
5543        return ExprError();
5544      }
5545
5546      // Reference binding does not have any corresponding ASTs.
5547
5548      // Check exception specifications
5549      if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
5550        return ExprError();
5551
5552      break;
5553
5554    case SK_BindReferenceToTemporary: {
5555      // Make sure the "temporary" is actually an rvalue.
5556      assert(CurInit.get()->isRValue() && "not a temporary");
5557
5558      // Check exception specifications
5559      if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
5560        return ExprError();
5561
5562      // Maybe lifetime-extend the temporary's subobjects to match the
5563      // entity's lifetime.
5564      const ValueDecl *ExtendingDecl =
5565          getDeclForTemporaryLifetimeExtension(Entity);
5566      if (ExtendingDecl)
5567        performLifetimeExtension(CurInit.get(), ExtendingDecl);
5568
5569      // Materialize the temporary into memory.
5570      CurInit = new (S.Context) MaterializeTemporaryExpr(
5571          Entity.getType().getNonReferenceType(), CurInit.get(),
5572          Entity.getType()->isLValueReferenceType(), ExtendingDecl);
5573
5574      // If we're binding to an Objective-C object that has lifetime, we
5575      // need cleanups.
5576      if (S.getLangOpts().ObjCAutoRefCount &&
5577          CurInit.get()->getType()->isObjCLifetimeType())
5578        S.ExprNeedsCleanups = true;
5579
5580      break;
5581    }
5582
5583    case SK_ExtraneousCopyToTemporary:
5584      CurInit = CopyObject(S, Step->Type, Entity, CurInit,
5585                           /*IsExtraneousCopy=*/true);
5586      break;
5587
5588    case SK_UserConversion: {
5589      // We have a user-defined conversion that invokes either a constructor
5590      // or a conversion function.
5591      CastKind CastKind;
5592      bool IsCopy = false;
5593      FunctionDecl *Fn = Step->Function.Function;
5594      DeclAccessPair FoundFn = Step->Function.FoundDecl;
5595      bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
5596      bool CreatedObject = false;
5597      if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
5598        // Build a call to the selected constructor.
5599        SmallVector<Expr*, 8> ConstructorArgs;
5600        SourceLocation Loc = CurInit.get()->getLocStart();
5601        CurInit.release(); // Ownership transferred into MultiExprArg, below.
5602
5603        // Determine the arguments required to actually perform the constructor
5604        // call.
5605        Expr *Arg = CurInit.get();
5606        if (S.CompleteConstructorCall(Constructor,
5607                                      MultiExprArg(&Arg, 1),
5608                                      Loc, ConstructorArgs))
5609          return ExprError();
5610
5611        // Build an expression that constructs a temporary.
5612        CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
5613                                          ConstructorArgs,
5614                                          HadMultipleCandidates,
5615                                          /*ListInit*/ false,
5616                                          /*ZeroInit*/ false,
5617                                          CXXConstructExpr::CK_Complete,
5618                                          SourceRange());
5619        if (CurInit.isInvalid())
5620          return ExprError();
5621
5622        S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
5623                                 FoundFn.getAccess());
5624        if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5625          return ExprError();
5626
5627        CastKind = CK_ConstructorConversion;
5628        QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5629        if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5630            S.IsDerivedFrom(SourceType, Class))
5631          IsCopy = true;
5632
5633        CreatedObject = true;
5634      } else {
5635        // Build a call to the conversion function.
5636        CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
5637        S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
5638                                    FoundFn);
5639        if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5640          return ExprError();
5641
5642        // FIXME: Should we move this initialization into a separate
5643        // derived-to-base conversion? I believe the answer is "no", because
5644        // we don't want to turn off access control here for c-style casts.
5645        ExprResult CurInitExprRes =
5646          S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5647                                                FoundFn, Conversion);
5648        if(CurInitExprRes.isInvalid())
5649          return ExprError();
5650        CurInit = CurInitExprRes;
5651
5652        // Build the actual call to the conversion function.
5653        CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5654                                           HadMultipleCandidates);
5655        if (CurInit.isInvalid() || !CurInit.get())
5656          return ExprError();
5657
5658        CastKind = CK_UserDefinedConversion;
5659
5660        CreatedObject = Conversion->getResultType()->isRecordType();
5661      }
5662
5663      bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
5664      bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5665
5666      if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
5667        QualType T = CurInit.get()->getType();
5668        if (const RecordType *Record = T->getAs<RecordType>()) {
5669          CXXDestructorDecl *Destructor
5670            = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
5671          S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
5672                                  S.PDiag(diag::err_access_dtor_temp) << T);
5673          S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
5674          if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
5675            return ExprError();
5676        }
5677      }
5678
5679      CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5680                                                 CurInit.get()->getType(),
5681                                                 CastKind, CurInit.get(), 0,
5682                                                CurInit.get()->getValueKind()));
5683      if (MaybeBindToTemp)
5684        CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
5685      if (RequiresCopy)
5686        CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
5687                             CurInit, /*IsExtraneousCopy=*/false);
5688      break;
5689    }
5690
5691    case SK_QualificationConversionLValue:
5692    case SK_QualificationConversionXValue:
5693    case SK_QualificationConversionRValue: {
5694      // Perform a qualification conversion; these can never go wrong.
5695      ExprValueKind VK =
5696          Step->Kind == SK_QualificationConversionLValue ?
5697              VK_LValue :
5698              (Step->Kind == SK_QualificationConversionXValue ?
5699                   VK_XValue :
5700                   VK_RValue);
5701      CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
5702      break;
5703    }
5704
5705    case SK_LValueToRValue: {
5706      assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5707      CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5708                                                 CK_LValueToRValue,
5709                                                 CurInit.take(),
5710                                                 /*BasePath=*/0,
5711                                                 VK_RValue));
5712      break;
5713    }
5714
5715    case SK_ConversionSequence: {
5716      Sema::CheckedConversionKind CCK
5717        = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5718        : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
5719        : Kind.isExplicitCast()? Sema::CCK_OtherCast
5720        : Sema::CCK_ImplicitConversion;
5721      ExprResult CurInitExprRes =
5722        S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
5723                                    getAssignmentAction(Entity), CCK);
5724      if (CurInitExprRes.isInvalid())
5725        return ExprError();
5726      CurInit = CurInitExprRes;
5727      break;
5728    }
5729
5730    case SK_ListInitialization: {
5731      InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5732      // Hack: We must pass *ResultType if available in order to set the type
5733      // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5734      // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5735      // temporary, not a reference, so we should pass Ty.
5736      // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5737      // Since this step is never used for a reference directly, we explicitly
5738      // unwrap references here and rewrap them afterwards.
5739      // We also need to create a InitializeTemporary entity for this.
5740      QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
5741      bool IsTemporary = Entity.getType()->isReferenceType();
5742      InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5743      InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5744      InitListChecker PerformInitList(S, InitEntity,
5745          InitList, Ty, /*VerifyOnly=*/false);
5746      if (PerformInitList.HadError())
5747        return ExprError();
5748
5749      if (ResultType) {
5750        if ((*ResultType)->isRValueReferenceType())
5751          Ty = S.Context.getRValueReferenceType(Ty);
5752        else if ((*ResultType)->isLValueReferenceType())
5753          Ty = S.Context.getLValueReferenceType(Ty,
5754            (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5755        *ResultType = Ty;
5756      }
5757
5758      InitListExpr *StructuredInitList =
5759          PerformInitList.getFullyStructuredList();
5760      CurInit.release();
5761      CurInit = shouldBindAsTemporary(InitEntity)
5762          ? S.MaybeBindToTemporary(StructuredInitList)
5763          : S.Owned(StructuredInitList);
5764      break;
5765    }
5766
5767    case SK_ListConstructorCall: {
5768      // When an initializer list is passed for a parameter of type "reference
5769      // to object", we don't get an EK_Temporary entity, but instead an
5770      // EK_Parameter entity with reference type.
5771      // FIXME: This is a hack. What we really should do is create a user
5772      // conversion step for this case, but this makes it considerably more
5773      // complicated. For now, this will do.
5774      InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5775                                        Entity.getType().getNonReferenceType());
5776      bool UseTemporary = Entity.getType()->isReferenceType();
5777      assert(Args.size() == 1 && "expected a single argument for list init");
5778      InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5779      S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
5780        << InitList->getSourceRange();
5781      MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
5782      CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5783                                                                   Entity,
5784                                                 Kind, Arg, *Step,
5785                                               ConstructorInitRequiresZeroInit,
5786                                               /*IsListInitialization*/ true);
5787      break;
5788    }
5789
5790    case SK_UnwrapInitList:
5791      CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5792      break;
5793
5794    case SK_RewrapInitList: {
5795      Expr *E = CurInit.take();
5796      InitListExpr *Syntactic = Step->WrappingSyntacticList;
5797      InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5798          Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
5799      ILE->setSyntacticForm(Syntactic);
5800      ILE->setType(E->getType());
5801      ILE->setValueKind(E->getValueKind());
5802      CurInit = S.Owned(ILE);
5803      break;
5804    }
5805
5806    case SK_ConstructorInitialization: {
5807      // When an initializer list is passed for a parameter of type "reference
5808      // to object", we don't get an EK_Temporary entity, but instead an
5809      // EK_Parameter entity with reference type.
5810      // FIXME: This is a hack. What we really should do is create a user
5811      // conversion step for this case, but this makes it considerably more
5812      // complicated. For now, this will do.
5813      InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5814                                        Entity.getType().getNonReferenceType());
5815      bool UseTemporary = Entity.getType()->isReferenceType();
5816      CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5817                                                                 : Entity,
5818                                                 Kind, Args, *Step,
5819                                               ConstructorInitRequiresZeroInit,
5820                                               /*IsListInitialization*/ false);
5821      break;
5822    }
5823
5824    case SK_ZeroInitialization: {
5825      step_iterator NextStep = Step;
5826      ++NextStep;
5827      if (NextStep != StepEnd &&
5828          (NextStep->Kind == SK_ConstructorInitialization ||
5829           NextStep->Kind == SK_ListConstructorCall)) {
5830        // The need for zero-initialization is recorded directly into
5831        // the call to the object's constructor within the next step.
5832        ConstructorInitRequiresZeroInit = true;
5833      } else if (Kind.getKind() == InitializationKind::IK_Value &&
5834                 S.getLangOpts().CPlusPlus &&
5835                 !Kind.isImplicitValueInit()) {
5836        TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5837        if (!TSInfo)
5838          TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
5839                                                    Kind.getRange().getBegin());
5840
5841        CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5842                              TSInfo->getType().getNonLValueExprType(S.Context),
5843                                                                 TSInfo,
5844                                                    Kind.getRange().getEnd()));
5845      } else {
5846        CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
5847      }
5848      break;
5849    }
5850
5851    case SK_CAssignment: {
5852      QualType SourceType = CurInit.get()->getType();
5853      ExprResult Result = CurInit;
5854      Sema::AssignConvertType ConvTy =
5855        S.CheckSingleAssignmentConstraints(Step->Type, Result);
5856      if (Result.isInvalid())
5857        return ExprError();
5858      CurInit = Result;
5859
5860      // If this is a call, allow conversion to a transparent union.
5861      ExprResult CurInitExprRes = CurInit;
5862      if (ConvTy != Sema::Compatible &&
5863          Entity.getKind() == InitializedEntity::EK_Parameter &&
5864          S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
5865            == Sema::Compatible)
5866        ConvTy = Sema::Compatible;
5867      if (CurInitExprRes.isInvalid())
5868        return ExprError();
5869      CurInit = CurInitExprRes;
5870
5871      bool Complained;
5872      if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5873                                     Step->Type, SourceType,
5874                                     CurInit.get(),
5875                                     getAssignmentAction(Entity),
5876                                     &Complained)) {
5877        PrintInitLocationNote(S, Entity);
5878        return ExprError();
5879      } else if (Complained)
5880        PrintInitLocationNote(S, Entity);
5881      break;
5882    }
5883
5884    case SK_StringInit: {
5885      QualType Ty = Step->Type;
5886      CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
5887                      S.Context.getAsArrayType(Ty), S);
5888      break;
5889    }
5890
5891    case SK_ObjCObjectConversion:
5892      CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
5893                          CK_ObjCObjectLValueCast,
5894                          CurInit.get()->getValueKind());
5895      break;
5896
5897    case SK_ArrayInit:
5898      // Okay: we checked everything before creating this step. Note that
5899      // this is a GNU extension.
5900      S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
5901        << Step->Type << CurInit.get()->getType()
5902        << CurInit.get()->getSourceRange();
5903
5904      // If the destination type is an incomplete array type, update the
5905      // type accordingly.
5906      if (ResultType) {
5907        if (const IncompleteArrayType *IncompleteDest
5908                           = S.Context.getAsIncompleteArrayType(Step->Type)) {
5909          if (const ConstantArrayType *ConstantSource
5910                 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
5911            *ResultType = S.Context.getConstantArrayType(
5912                                             IncompleteDest->getElementType(),
5913                                             ConstantSource->getSize(),
5914                                             ArrayType::Normal, 0);
5915          }
5916        }
5917      }
5918      break;
5919
5920    case SK_ParenthesizedArrayInit:
5921      // Okay: we checked everything before creating this step. Note that
5922      // this is a GNU extension.
5923      S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
5924        << CurInit.get()->getSourceRange();
5925      break;
5926
5927    case SK_PassByIndirectCopyRestore:
5928    case SK_PassByIndirectRestore:
5929      checkIndirectCopyRestoreSource(S, CurInit.get());
5930      CurInit = S.Owned(new (S.Context)
5931                        ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5932                                Step->Kind == SK_PassByIndirectCopyRestore));
5933      break;
5934
5935    case SK_ProduceObjCObject:
5936      CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5937                                                 CK_ARCProduceObject,
5938                                                 CurInit.take(), 0, VK_RValue));
5939      break;
5940
5941    case SK_StdInitializerList: {
5942      QualType Dest = Step->Type;
5943      QualType E;
5944      bool Success = S.isStdInitializerList(Dest.getNonReferenceType(), &E);
5945      (void)Success;
5946      assert(Success && "Destination type changed?");
5947
5948      // If the element type has a destructor, check it.
5949      if (CXXRecordDecl *RD = E->getAsCXXRecordDecl()) {
5950        if (!RD->hasIrrelevantDestructor()) {
5951          if (CXXDestructorDecl *Destructor = S.LookupDestructor(RD)) {
5952            S.MarkFunctionReferenced(Kind.getLocation(), Destructor);
5953            S.CheckDestructorAccess(Kind.getLocation(), Destructor,
5954                                    S.PDiag(diag::err_access_dtor_temp) << E);
5955            if (S.DiagnoseUseOfDecl(Destructor, Kind.getLocation()))
5956              return ExprError();
5957          }
5958        }
5959      }
5960
5961      InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
5962      S.Diag(ILE->getExprLoc(), diag::warn_cxx98_compat_initializer_list_init)
5963        << ILE->getSourceRange();
5964      unsigned NumInits = ILE->getNumInits();
5965      SmallVector<Expr*, 16> Converted(NumInits);
5966      InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5967          S.Context.getConstantArrayType(E,
5968              llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5969                          NumInits),
5970              ArrayType::Normal, 0));
5971      InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5972          0, HiddenArray);
5973      for (unsigned i = 0; i < NumInits; ++i) {
5974        Element.setElementIndex(i);
5975        ExprResult Init = S.Owned(ILE->getInit(i));
5976        ExprResult Res = S.PerformCopyInitialization(
5977                             Element, Init.get()->getExprLoc(), Init,
5978                             /*TopLevelOfInitList=*/ true);
5979        if (Res.isInvalid())
5980          return ExprError();
5981        Converted[i] = Res.take();
5982      }
5983      InitListExpr *Semantic = new (S.Context)
5984          InitListExpr(S.Context, ILE->getLBraceLoc(),
5985                       Converted, ILE->getRBraceLoc());
5986      Semantic->setSyntacticForm(ILE);
5987      Semantic->setType(Dest);
5988      Semantic->setInitializesStdInitializerList();
5989      CurInit = S.Owned(Semantic);
5990      break;
5991    }
5992    case SK_OCLSamplerInit: {
5993      assert(Step->Type->isSamplerT() &&
5994             "Sampler initialization on non sampler type.");
5995
5996      QualType SourceType = CurInit.get()->getType();
5997      InitializedEntity::EntityKind EntityKind = Entity.getKind();
5998
5999      if (EntityKind == InitializedEntity::EK_Parameter) {
6000        if (!SourceType->isSamplerT())
6001          S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6002            << SourceType;
6003      } else if (EntityKind != InitializedEntity::EK_Variable) {
6004        llvm_unreachable("Invalid EntityKind!");
6005      }
6006
6007      break;
6008    }
6009    case SK_OCLZeroEvent: {
6010      assert(Step->Type->isEventT() &&
6011             "Event initialization on non event type.");
6012
6013      CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
6014                                    CK_ZeroToOCLEvent,
6015                                    CurInit.get()->getValueKind());
6016      break;
6017    }
6018    }
6019  }
6020
6021  // Diagnose non-fatal problems with the completed initialization.
6022  if (Entity.getKind() == InitializedEntity::EK_Member &&
6023      cast<FieldDecl>(Entity.getDecl())->isBitField())
6024    S.CheckBitFieldInitialization(Kind.getLocation(),
6025                                  cast<FieldDecl>(Entity.getDecl()),
6026                                  CurInit.get());
6027
6028  return CurInit;
6029}
6030
6031/// Somewhere within T there is an uninitialized reference subobject.
6032/// Dig it out and diagnose it.
6033static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6034                                           QualType T) {
6035  if (T->isReferenceType()) {
6036    S.Diag(Loc, diag::err_reference_without_init)
6037      << T.getNonReferenceType();
6038    return true;
6039  }
6040
6041  CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6042  if (!RD || !RD->hasUninitializedReferenceMember())
6043    return false;
6044
6045  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
6046                                     FE = RD->field_end(); FI != FE; ++FI) {
6047    if (FI->isUnnamedBitfield())
6048      continue;
6049
6050    if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6051      S.Diag(Loc, diag::note_value_initialization_here) << RD;
6052      return true;
6053    }
6054  }
6055
6056  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
6057                                          BE = RD->bases_end();
6058       BI != BE; ++BI) {
6059    if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
6060      S.Diag(Loc, diag::note_value_initialization_here) << RD;
6061      return true;
6062    }
6063  }
6064
6065  return false;
6066}
6067
6068
6069//===----------------------------------------------------------------------===//
6070// Diagnose initialization failures
6071//===----------------------------------------------------------------------===//
6072
6073/// Emit notes associated with an initialization that failed due to a
6074/// "simple" conversion failure.
6075static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6076                                   Expr *op) {
6077  QualType destType = entity.getType();
6078  if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6079      op->getType()->isObjCObjectPointerType()) {
6080
6081    // Emit a possible note about the conversion failing because the
6082    // operand is a message send with a related result type.
6083    S.EmitRelatedResultTypeNote(op);
6084
6085    // Emit a possible note about a return failing because we're
6086    // expecting a related result type.
6087    if (entity.getKind() == InitializedEntity::EK_Result)
6088      S.EmitRelatedResultTypeNoteForReturn(destType);
6089  }
6090}
6091
6092bool InitializationSequence::Diagnose(Sema &S,
6093                                      const InitializedEntity &Entity,
6094                                      const InitializationKind &Kind,
6095                                      ArrayRef<Expr *> Args) {
6096  if (!Failed())
6097    return false;
6098
6099  QualType DestType = Entity.getType();
6100  switch (Failure) {
6101  case FK_TooManyInitsForReference:
6102    // FIXME: Customize for the initialized entity?
6103    if (Args.empty()) {
6104      // Dig out the reference subobject which is uninitialized and diagnose it.
6105      // If this is value-initialization, this could be nested some way within
6106      // the target type.
6107      assert(Kind.getKind() == InitializationKind::IK_Value ||
6108             DestType->isReferenceType());
6109      bool Diagnosed =
6110        DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6111      assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6112      (void)Diagnosed;
6113    } else  // FIXME: diagnostic below could be better!
6114      S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
6115        << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
6116    break;
6117
6118  case FK_ArrayNeedsInitList:
6119    S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
6120    break;
6121  case FK_ArrayNeedsInitListOrStringLiteral:
6122    S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6123    break;
6124  case FK_ArrayNeedsInitListOrWideStringLiteral:
6125    S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6126    break;
6127  case FK_NarrowStringIntoWideCharArray:
6128    S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6129    break;
6130  case FK_WideStringIntoCharArray:
6131    S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6132    break;
6133  case FK_IncompatWideStringIntoWideChar:
6134    S.Diag(Kind.getLocation(),
6135           diag::err_array_init_incompat_wide_string_into_wchar);
6136    break;
6137  case FK_ArrayTypeMismatch:
6138  case FK_NonConstantArrayInit:
6139    S.Diag(Kind.getLocation(),
6140           (Failure == FK_ArrayTypeMismatch
6141              ? diag::err_array_init_different_type
6142              : diag::err_array_init_non_constant_array))
6143      << DestType.getNonReferenceType()
6144      << Args[0]->getType()
6145      << Args[0]->getSourceRange();
6146    break;
6147
6148  case FK_VariableLengthArrayHasInitializer:
6149    S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6150      << Args[0]->getSourceRange();
6151    break;
6152
6153  case FK_AddressOfOverloadFailed: {
6154    DeclAccessPair Found;
6155    S.ResolveAddressOfOverloadedFunction(Args[0],
6156                                         DestType.getNonReferenceType(),
6157                                         true,
6158                                         Found);
6159    break;
6160  }
6161
6162  case FK_ReferenceInitOverloadFailed:
6163  case FK_UserConversionOverloadFailed:
6164    switch (FailedOverloadResult) {
6165    case OR_Ambiguous:
6166      if (Failure == FK_UserConversionOverloadFailed)
6167        S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6168          << Args[0]->getType() << DestType
6169          << Args[0]->getSourceRange();
6170      else
6171        S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6172          << DestType << Args[0]->getType()
6173          << Args[0]->getSourceRange();
6174
6175      FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
6176      break;
6177
6178    case OR_No_Viable_Function:
6179      S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6180        << Args[0]->getType() << DestType.getNonReferenceType()
6181        << Args[0]->getSourceRange();
6182      FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
6183      break;
6184
6185    case OR_Deleted: {
6186      S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6187        << Args[0]->getType() << DestType.getNonReferenceType()
6188        << Args[0]->getSourceRange();
6189      OverloadCandidateSet::iterator Best;
6190      OverloadingResult Ovl
6191        = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6192                                                true);
6193      if (Ovl == OR_Deleted) {
6194        S.NoteDeletedFunction(Best->Function);
6195      } else {
6196        llvm_unreachable("Inconsistent overload resolution?");
6197      }
6198      break;
6199    }
6200
6201    case OR_Success:
6202      llvm_unreachable("Conversion did not fail!");
6203    }
6204    break;
6205
6206  case FK_NonConstLValueReferenceBindingToTemporary:
6207    if (isa<InitListExpr>(Args[0])) {
6208      S.Diag(Kind.getLocation(),
6209             diag::err_lvalue_reference_bind_to_initlist)
6210      << DestType.getNonReferenceType().isVolatileQualified()
6211      << DestType.getNonReferenceType()
6212      << Args[0]->getSourceRange();
6213      break;
6214    }
6215    // Intentional fallthrough
6216
6217  case FK_NonConstLValueReferenceBindingToUnrelated:
6218    S.Diag(Kind.getLocation(),
6219           Failure == FK_NonConstLValueReferenceBindingToTemporary
6220             ? diag::err_lvalue_reference_bind_to_temporary
6221             : diag::err_lvalue_reference_bind_to_unrelated)
6222      << DestType.getNonReferenceType().isVolatileQualified()
6223      << DestType.getNonReferenceType()
6224      << Args[0]->getType()
6225      << Args[0]->getSourceRange();
6226    break;
6227
6228  case FK_RValueReferenceBindingToLValue:
6229    S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
6230      << DestType.getNonReferenceType() << Args[0]->getType()
6231      << Args[0]->getSourceRange();
6232    break;
6233
6234  case FK_ReferenceInitDropsQualifiers:
6235    S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6236      << DestType.getNonReferenceType()
6237      << Args[0]->getType()
6238      << Args[0]->getSourceRange();
6239    break;
6240
6241  case FK_ReferenceInitFailed:
6242    S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6243      << DestType.getNonReferenceType()
6244      << Args[0]->isLValue()
6245      << Args[0]->getType()
6246      << Args[0]->getSourceRange();
6247    emitBadConversionNotes(S, Entity, Args[0]);
6248    break;
6249
6250  case FK_ConversionFailed: {
6251    QualType FromType = Args[0]->getType();
6252    PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
6253      << (int)Entity.getKind()
6254      << DestType
6255      << Args[0]->isLValue()
6256      << FromType
6257      << Args[0]->getSourceRange();
6258    S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6259    S.Diag(Kind.getLocation(), PDiag);
6260    emitBadConversionNotes(S, Entity, Args[0]);
6261    break;
6262  }
6263
6264  case FK_ConversionFromPropertyFailed:
6265    // No-op. This error has already been reported.
6266    break;
6267
6268  case FK_TooManyInitsForScalar: {
6269    SourceRange R;
6270
6271    if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
6272      R = SourceRange(InitList->getInit(0)->getLocEnd(),
6273                      InitList->getLocEnd());
6274    else
6275      R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
6276
6277    R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
6278    if (Kind.isCStyleOrFunctionalCast())
6279      S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6280        << R;
6281    else
6282      S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6283        << /*scalar=*/2 << R;
6284    break;
6285  }
6286
6287  case FK_ReferenceBindingToInitList:
6288    S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6289      << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6290    break;
6291
6292  case FK_InitListBadDestinationType:
6293    S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6294      << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6295    break;
6296
6297  case FK_ListConstructorOverloadFailed:
6298  case FK_ConstructorOverloadFailed: {
6299    SourceRange ArgsRange;
6300    if (Args.size())
6301      ArgsRange = SourceRange(Args.front()->getLocStart(),
6302                              Args.back()->getLocEnd());
6303
6304    if (Failure == FK_ListConstructorOverloadFailed) {
6305      assert(Args.size() == 1 && "List construction from other than 1 argument.");
6306      InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6307      Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
6308    }
6309
6310    // FIXME: Using "DestType" for the entity we're printing is probably
6311    // bad.
6312    switch (FailedOverloadResult) {
6313      case OR_Ambiguous:
6314        S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6315          << DestType << ArgsRange;
6316        FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
6317        break;
6318
6319      case OR_No_Viable_Function:
6320        if (Kind.getKind() == InitializationKind::IK_Default &&
6321            (Entity.getKind() == InitializedEntity::EK_Base ||
6322             Entity.getKind() == InitializedEntity::EK_Member) &&
6323            isa<CXXConstructorDecl>(S.CurContext)) {
6324          // This is implicit default initialization of a member or
6325          // base within a constructor. If no viable function was
6326          // found, notify the user that she needs to explicitly
6327          // initialize this base/member.
6328          CXXConstructorDecl *Constructor
6329            = cast<CXXConstructorDecl>(S.CurContext);
6330          if (Entity.getKind() == InitializedEntity::EK_Base) {
6331            S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
6332              << (Constructor->getInheritedConstructor() ? 2 :
6333                  Constructor->isImplicit() ? 1 : 0)
6334              << S.Context.getTypeDeclType(Constructor->getParent())
6335              << /*base=*/0
6336              << Entity.getType();
6337
6338            RecordDecl *BaseDecl
6339              = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6340                                                                  ->getDecl();
6341            S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6342              << S.Context.getTagDeclType(BaseDecl);
6343          } else {
6344            S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
6345              << (Constructor->getInheritedConstructor() ? 2 :
6346                  Constructor->isImplicit() ? 1 : 0)
6347              << S.Context.getTypeDeclType(Constructor->getParent())
6348              << /*member=*/1
6349              << Entity.getName();
6350            S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
6351
6352            if (const RecordType *Record
6353                                 = Entity.getType()->getAs<RecordType>())
6354              S.Diag(Record->getDecl()->getLocation(),
6355                     diag::note_previous_decl)
6356                << S.Context.getTagDeclType(Record->getDecl());
6357          }
6358          break;
6359        }
6360
6361        S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6362          << DestType << ArgsRange;
6363        FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
6364        break;
6365
6366      case OR_Deleted: {
6367        OverloadCandidateSet::iterator Best;
6368        OverloadingResult Ovl
6369          = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
6370        if (Ovl != OR_Deleted) {
6371          S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6372            << true << DestType << ArgsRange;
6373          llvm_unreachable("Inconsistent overload resolution?");
6374          break;
6375        }
6376
6377        // If this is a defaulted or implicitly-declared function, then
6378        // it was implicitly deleted. Make it clear that the deletion was
6379        // implicit.
6380        if (S.isImplicitlyDeleted(Best->Function))
6381          S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
6382            << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
6383            << DestType << ArgsRange;
6384        else
6385          S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6386            << true << DestType << ArgsRange;
6387
6388        S.NoteDeletedFunction(Best->Function);
6389        break;
6390      }
6391
6392      case OR_Success:
6393        llvm_unreachable("Conversion did not fail!");
6394    }
6395  }
6396  break;
6397
6398  case FK_DefaultInitOfConst:
6399    if (Entity.getKind() == InitializedEntity::EK_Member &&
6400        isa<CXXConstructorDecl>(S.CurContext)) {
6401      // This is implicit default-initialization of a const member in
6402      // a constructor. Complain that it needs to be explicitly
6403      // initialized.
6404      CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6405      S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
6406        << (Constructor->getInheritedConstructor() ? 2 :
6407            Constructor->isImplicit() ? 1 : 0)
6408        << S.Context.getTypeDeclType(Constructor->getParent())
6409        << /*const=*/1
6410        << Entity.getName();
6411      S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6412        << Entity.getName();
6413    } else {
6414      S.Diag(Kind.getLocation(), diag::err_default_init_const)
6415        << DestType << (bool)DestType->getAs<RecordType>();
6416    }
6417    break;
6418
6419  case FK_Incomplete:
6420    S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
6421                          diag::err_init_incomplete_type);
6422    break;
6423
6424  case FK_ListInitializationFailed: {
6425    // Run the init list checker again to emit diagnostics.
6426    InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6427    QualType DestType = Entity.getType();
6428    InitListChecker DiagnoseInitList(S, Entity, InitList,
6429            DestType, /*VerifyOnly=*/false);
6430    assert(DiagnoseInitList.HadError() &&
6431           "Inconsistent init list check result.");
6432    break;
6433  }
6434
6435  case FK_PlaceholderType: {
6436    // FIXME: Already diagnosed!
6437    break;
6438  }
6439
6440  case FK_InitListElementCopyFailure: {
6441    // Try to perform all copies again.
6442    InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6443    unsigned NumInits = InitList->getNumInits();
6444    QualType DestType = Entity.getType();
6445    QualType E;
6446    bool Success = S.isStdInitializerList(DestType.getNonReferenceType(), &E);
6447    (void)Success;
6448    assert(Success && "Where did the std::initializer_list go?");
6449    InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
6450        S.Context.getConstantArrayType(E,
6451            llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6452                        NumInits),
6453            ArrayType::Normal, 0));
6454    InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
6455        0, HiddenArray);
6456    // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
6457    // where the init list type is wrong, e.g.
6458    //   std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
6459    // FIXME: Emit a note if we hit the limit?
6460    int ErrorCount = 0;
6461    for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
6462      Element.setElementIndex(i);
6463      ExprResult Init = S.Owned(InitList->getInit(i));
6464      if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
6465           .isInvalid())
6466        ++ErrorCount;
6467    }
6468    break;
6469  }
6470
6471  case FK_ExplicitConstructor: {
6472    S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6473      << Args[0]->getSourceRange();
6474    OverloadCandidateSet::iterator Best;
6475    OverloadingResult Ovl
6476      = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
6477    (void)Ovl;
6478    assert(Ovl == OR_Success && "Inconsistent overload resolution");
6479    CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6480    S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6481    break;
6482  }
6483  }
6484
6485  PrintInitLocationNote(S, Entity);
6486  return true;
6487}
6488
6489void InitializationSequence::dump(raw_ostream &OS) const {
6490  switch (SequenceKind) {
6491  case FailedSequence: {
6492    OS << "Failed sequence: ";
6493    switch (Failure) {
6494    case FK_TooManyInitsForReference:
6495      OS << "too many initializers for reference";
6496      break;
6497
6498    case FK_ArrayNeedsInitList:
6499      OS << "array requires initializer list";
6500      break;
6501
6502    case FK_ArrayNeedsInitListOrStringLiteral:
6503      OS << "array requires initializer list or string literal";
6504      break;
6505
6506    case FK_ArrayNeedsInitListOrWideStringLiteral:
6507      OS << "array requires initializer list or wide string literal";
6508      break;
6509
6510    case FK_NarrowStringIntoWideCharArray:
6511      OS << "narrow string into wide char array";
6512      break;
6513
6514    case FK_WideStringIntoCharArray:
6515      OS << "wide string into char array";
6516      break;
6517
6518    case FK_IncompatWideStringIntoWideChar:
6519      OS << "incompatible wide string into wide char array";
6520      break;
6521
6522    case FK_ArrayTypeMismatch:
6523      OS << "array type mismatch";
6524      break;
6525
6526    case FK_NonConstantArrayInit:
6527      OS << "non-constant array initializer";
6528      break;
6529
6530    case FK_AddressOfOverloadFailed:
6531      OS << "address of overloaded function failed";
6532      break;
6533
6534    case FK_ReferenceInitOverloadFailed:
6535      OS << "overload resolution for reference initialization failed";
6536      break;
6537
6538    case FK_NonConstLValueReferenceBindingToTemporary:
6539      OS << "non-const lvalue reference bound to temporary";
6540      break;
6541
6542    case FK_NonConstLValueReferenceBindingToUnrelated:
6543      OS << "non-const lvalue reference bound to unrelated type";
6544      break;
6545
6546    case FK_RValueReferenceBindingToLValue:
6547      OS << "rvalue reference bound to an lvalue";
6548      break;
6549
6550    case FK_ReferenceInitDropsQualifiers:
6551      OS << "reference initialization drops qualifiers";
6552      break;
6553
6554    case FK_ReferenceInitFailed:
6555      OS << "reference initialization failed";
6556      break;
6557
6558    case FK_ConversionFailed:
6559      OS << "conversion failed";
6560      break;
6561
6562    case FK_ConversionFromPropertyFailed:
6563      OS << "conversion from property failed";
6564      break;
6565
6566    case FK_TooManyInitsForScalar:
6567      OS << "too many initializers for scalar";
6568      break;
6569
6570    case FK_ReferenceBindingToInitList:
6571      OS << "referencing binding to initializer list";
6572      break;
6573
6574    case FK_InitListBadDestinationType:
6575      OS << "initializer list for non-aggregate, non-scalar type";
6576      break;
6577
6578    case FK_UserConversionOverloadFailed:
6579      OS << "overloading failed for user-defined conversion";
6580      break;
6581
6582    case FK_ConstructorOverloadFailed:
6583      OS << "constructor overloading failed";
6584      break;
6585
6586    case FK_DefaultInitOfConst:
6587      OS << "default initialization of a const variable";
6588      break;
6589
6590    case FK_Incomplete:
6591      OS << "initialization of incomplete type";
6592      break;
6593
6594    case FK_ListInitializationFailed:
6595      OS << "list initialization checker failure";
6596      break;
6597
6598    case FK_VariableLengthArrayHasInitializer:
6599      OS << "variable length array has an initializer";
6600      break;
6601
6602    case FK_PlaceholderType:
6603      OS << "initializer expression isn't contextually valid";
6604      break;
6605
6606    case FK_ListConstructorOverloadFailed:
6607      OS << "list constructor overloading failed";
6608      break;
6609
6610    case FK_InitListElementCopyFailure:
6611      OS << "copy construction of initializer list element failed";
6612      break;
6613
6614    case FK_ExplicitConstructor:
6615      OS << "list copy initialization chose explicit constructor";
6616      break;
6617    }
6618    OS << '\n';
6619    return;
6620  }
6621
6622  case DependentSequence:
6623    OS << "Dependent sequence\n";
6624    return;
6625
6626  case NormalSequence:
6627    OS << "Normal sequence: ";
6628    break;
6629  }
6630
6631  for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6632    if (S != step_begin()) {
6633      OS << " -> ";
6634    }
6635
6636    switch (S->Kind) {
6637    case SK_ResolveAddressOfOverloadedFunction:
6638      OS << "resolve address of overloaded function";
6639      break;
6640
6641    case SK_CastDerivedToBaseRValue:
6642      OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6643      break;
6644
6645    case SK_CastDerivedToBaseXValue:
6646      OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6647      break;
6648
6649    case SK_CastDerivedToBaseLValue:
6650      OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6651      break;
6652
6653    case SK_BindReference:
6654      OS << "bind reference to lvalue";
6655      break;
6656
6657    case SK_BindReferenceToTemporary:
6658      OS << "bind reference to a temporary";
6659      break;
6660
6661    case SK_ExtraneousCopyToTemporary:
6662      OS << "extraneous C++03 copy to temporary";
6663      break;
6664
6665    case SK_UserConversion:
6666      OS << "user-defined conversion via " << *S->Function.Function;
6667      break;
6668
6669    case SK_QualificationConversionRValue:
6670      OS << "qualification conversion (rvalue)";
6671      break;
6672
6673    case SK_QualificationConversionXValue:
6674      OS << "qualification conversion (xvalue)";
6675      break;
6676
6677    case SK_QualificationConversionLValue:
6678      OS << "qualification conversion (lvalue)";
6679      break;
6680
6681    case SK_LValueToRValue:
6682      OS << "load (lvalue to rvalue)";
6683      break;
6684
6685    case SK_ConversionSequence:
6686      OS << "implicit conversion sequence (";
6687      S->ICS->DebugPrint(); // FIXME: use OS
6688      OS << ")";
6689      break;
6690
6691    case SK_ListInitialization:
6692      OS << "list aggregate initialization";
6693      break;
6694
6695    case SK_ListConstructorCall:
6696      OS << "list initialization via constructor";
6697      break;
6698
6699    case SK_UnwrapInitList:
6700      OS << "unwrap reference initializer list";
6701      break;
6702
6703    case SK_RewrapInitList:
6704      OS << "rewrap reference initializer list";
6705      break;
6706
6707    case SK_ConstructorInitialization:
6708      OS << "constructor initialization";
6709      break;
6710
6711    case SK_ZeroInitialization:
6712      OS << "zero initialization";
6713      break;
6714
6715    case SK_CAssignment:
6716      OS << "C assignment";
6717      break;
6718
6719    case SK_StringInit:
6720      OS << "string initialization";
6721      break;
6722
6723    case SK_ObjCObjectConversion:
6724      OS << "Objective-C object conversion";
6725      break;
6726
6727    case SK_ArrayInit:
6728      OS << "array initialization";
6729      break;
6730
6731    case SK_ParenthesizedArrayInit:
6732      OS << "parenthesized array initialization";
6733      break;
6734
6735    case SK_PassByIndirectCopyRestore:
6736      OS << "pass by indirect copy and restore";
6737      break;
6738
6739    case SK_PassByIndirectRestore:
6740      OS << "pass by indirect restore";
6741      break;
6742
6743    case SK_ProduceObjCObject:
6744      OS << "Objective-C object retension";
6745      break;
6746
6747    case SK_StdInitializerList:
6748      OS << "std::initializer_list from initializer list";
6749      break;
6750
6751    case SK_OCLSamplerInit:
6752      OS << "OpenCL sampler_t from integer constant";
6753      break;
6754
6755    case SK_OCLZeroEvent:
6756      OS << "OpenCL event_t from zero";
6757      break;
6758    }
6759
6760    OS << " [" << S->Type.getAsString() << ']';
6761  }
6762
6763  OS << '\n';
6764}
6765
6766void InitializationSequence::dump() const {
6767  dump(llvm::errs());
6768}
6769
6770static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
6771                                        QualType EntityType,
6772                                        const Expr *PreInit,
6773                                        const Expr *PostInit) {
6774  if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
6775    return;
6776
6777  // A narrowing conversion can only appear as the final implicit conversion in
6778  // an initialization sequence.
6779  const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
6780  if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
6781    return;
6782
6783  const ImplicitConversionSequence &ICS = *LastStep.ICS;
6784  const StandardConversionSequence *SCS = 0;
6785  switch (ICS.getKind()) {
6786  case ImplicitConversionSequence::StandardConversion:
6787    SCS = &ICS.Standard;
6788    break;
6789  case ImplicitConversionSequence::UserDefinedConversion:
6790    SCS = &ICS.UserDefined.After;
6791    break;
6792  case ImplicitConversionSequence::AmbiguousConversion:
6793  case ImplicitConversionSequence::EllipsisConversion:
6794  case ImplicitConversionSequence::BadConversion:
6795    return;
6796  }
6797
6798  // Determine the type prior to the narrowing conversion. If a conversion
6799  // operator was used, this may be different from both the type of the entity
6800  // and of the pre-initialization expression.
6801  QualType PreNarrowingType = PreInit->getType();
6802  if (Seq.step_begin() + 1 != Seq.step_end())
6803    PreNarrowingType = Seq.step_end()[-2].Type;
6804
6805  // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6806  APValue ConstantValue;
6807  QualType ConstantType;
6808  switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6809                                ConstantType)) {
6810  case NK_Not_Narrowing:
6811    // No narrowing occurred.
6812    return;
6813
6814  case NK_Type_Narrowing:
6815    // This was a floating-to-integer conversion, which is always considered a
6816    // narrowing conversion even if the value is a constant and can be
6817    // represented exactly as an integer.
6818    S.Diag(PostInit->getLocStart(),
6819           S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
6820             diag::warn_init_list_type_narrowing
6821           : S.isSFINAEContext()?
6822             diag::err_init_list_type_narrowing_sfinae
6823           : diag::err_init_list_type_narrowing)
6824      << PostInit->getSourceRange()
6825      << PreNarrowingType.getLocalUnqualifiedType()
6826      << EntityType.getLocalUnqualifiedType();
6827    break;
6828
6829  case NK_Constant_Narrowing:
6830    // A constant value was narrowed.
6831    S.Diag(PostInit->getLocStart(),
6832           S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
6833             diag::warn_init_list_constant_narrowing
6834           : S.isSFINAEContext()?
6835             diag::err_init_list_constant_narrowing_sfinae
6836           : diag::err_init_list_constant_narrowing)
6837      << PostInit->getSourceRange()
6838      << ConstantValue.getAsString(S.getASTContext(), ConstantType)
6839      << EntityType.getLocalUnqualifiedType();
6840    break;
6841
6842  case NK_Variable_Narrowing:
6843    // A variable's value may have been narrowed.
6844    S.Diag(PostInit->getLocStart(),
6845           S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
6846             diag::warn_init_list_variable_narrowing
6847           : S.isSFINAEContext()?
6848             diag::err_init_list_variable_narrowing_sfinae
6849           : diag::err_init_list_variable_narrowing)
6850      << PostInit->getSourceRange()
6851      << PreNarrowingType.getLocalUnqualifiedType()
6852      << EntityType.getLocalUnqualifiedType();
6853    break;
6854  }
6855
6856  SmallString<128> StaticCast;
6857  llvm::raw_svector_ostream OS(StaticCast);
6858  OS << "static_cast<";
6859  if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6860    // It's important to use the typedef's name if there is one so that the
6861    // fixit doesn't break code using types like int64_t.
6862    //
6863    // FIXME: This will break if the typedef requires qualification.  But
6864    // getQualifiedNameAsString() includes non-machine-parsable components.
6865    OS << *TT->getDecl();
6866  } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
6867    OS << BT->getName(S.getLangOpts());
6868  else {
6869    // Oops, we didn't find the actual type of the variable.  Don't emit a fixit
6870    // with a broken cast.
6871    return;
6872  }
6873  OS << ">(";
6874  S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6875    << PostInit->getSourceRange()
6876    << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
6877    << FixItHint::CreateInsertion(
6878      S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
6879}
6880
6881//===----------------------------------------------------------------------===//
6882// Initialization helper functions
6883//===----------------------------------------------------------------------===//
6884bool
6885Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6886                                   ExprResult Init) {
6887  if (Init.isInvalid())
6888    return false;
6889
6890  Expr *InitE = Init.get();
6891  assert(InitE && "No initialization expression");
6892
6893  InitializationKind Kind
6894    = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
6895  InitializationSequence Seq(*this, Entity, Kind, InitE);
6896  return !Seq.Failed();
6897}
6898
6899ExprResult
6900Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6901                                SourceLocation EqualLoc,
6902                                ExprResult Init,
6903                                bool TopLevelOfInitList,
6904                                bool AllowExplicit) {
6905  if (Init.isInvalid())
6906    return ExprError();
6907
6908  Expr *InitE = Init.get();
6909  assert(InitE && "No initialization expression?");
6910
6911  if (EqualLoc.isInvalid())
6912    EqualLoc = InitE->getLocStart();
6913
6914  InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
6915                                                           EqualLoc,
6916                                                           AllowExplicit);
6917  InitializationSequence Seq(*this, Entity, Kind, InitE);
6918  Init.release();
6919
6920  ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
6921
6922  if (!Result.isInvalid() && TopLevelOfInitList)
6923    DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6924                                InitE, Result.get());
6925
6926  return Result;
6927}
6928