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