blob: 9ef43cc81f64accd6777e79f9c7b7919a18a1fbd [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- 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//
Sebastian Redl26bcc942011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattner0cb78032009-02-24 22:27:37 +000011//
Steve Narofff8ecff22008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Initialization.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000015#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000016#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000017#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000019#include "clang/AST/TypeLoc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Sema/Designator.h"
21#include "clang/Sema/Lookup.h"
22#include "clang/Sema/SemaInternal.h"
Sebastian Redlc1839b12012-01-17 22:49:42 +000023#include "llvm/ADT/APInt.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000024#include "llvm/ADT/SmallString.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000025#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000026#include "llvm/Support/raw_ostream.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000027#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000028using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000029
Chris Lattner0cb78032009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000034/// \brief Check whether T is compatible with a wide character type (wchar_t,
35/// char16_t or char32_t).
36static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
37 if (Context.typesAreCompatible(Context.getWideCharType(), T))
38 return true;
39 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
40 return Context.typesAreCompatible(Context.Char16Ty, T) ||
41 Context.typesAreCompatible(Context.Char32Ty, T);
42 }
43 return false;
44}
45
46enum StringInitFailureKind {
47 SIF_None,
48 SIF_NarrowStringIntoWideChar,
49 SIF_WideStringIntoChar,
50 SIF_IncompatWideStringIntoWideChar,
51 SIF_Other
52};
53
54/// \brief Check whether the array of type AT can be initialized by the Init
55/// expression by means of string initialization. Returns SIF_None if so,
56/// otherwise returns a StringInitFailureKind that describes why the
57/// initialization would not work.
58static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
59 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000060 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000061 return SIF_Other;
Eli Friedman893abe42009-05-29 18:22:49 +000062
Chris Lattnera9196812009-02-26 23:26:43 +000063 // See if this is a string literal or @encode.
64 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000065
Chris Lattnera9196812009-02-26 23:26:43 +000066 // Handle @encode, which is a narrow string.
67 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000068 return SIF_None;
Chris Lattnera9196812009-02-26 23:26:43 +000069
70 // Otherwise we can only handle string literals.
71 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Craig Topperc3ec1492014-05-26 06:22:03 +000072 if (!SL)
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000073 return SIF_Other;
Eli Friedman42a84652009-05-31 10:54:53 +000074
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000075 const QualType ElemTy =
76 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
Douglas Gregorfb65e592011-07-27 05:40:30 +000077
78 switch (SL->getKind()) {
79 case StringLiteral::Ascii:
80 case StringLiteral::UTF8:
81 // char array can be initialized with a narrow string.
82 // Only allow char x[] = "foo"; not char x[] = L"foo";
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000083 if (ElemTy->isCharType())
84 return SIF_None;
85 if (IsWideCharCompatible(ElemTy, Context))
86 return SIF_NarrowStringIntoWideChar;
87 return SIF_Other;
88 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
89 // "An array with element type compatible with a qualified or unqualified
90 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
91 // string literal with the corresponding encoding prefix (L, u, or U,
92 // respectively), optionally enclosed in braces.
Douglas Gregorfb65e592011-07-27 05:40:30 +000093 case StringLiteral::UTF16:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000094 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
95 return SIF_None;
96 if (ElemTy->isCharType())
97 return SIF_WideStringIntoChar;
98 if (IsWideCharCompatible(ElemTy, Context))
99 return SIF_IncompatWideStringIntoWideChar;
100 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000101 case StringLiteral::UTF32:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000102 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
103 return SIF_None;
104 if (ElemTy->isCharType())
105 return SIF_WideStringIntoChar;
106 if (IsWideCharCompatible(ElemTy, Context))
107 return SIF_IncompatWideStringIntoWideChar;
108 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000109 case StringLiteral::Wide:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000110 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
111 return SIF_None;
112 if (ElemTy->isCharType())
113 return SIF_WideStringIntoChar;
114 if (IsWideCharCompatible(ElemTy, Context))
115 return SIF_IncompatWideStringIntoWideChar;
116 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000117 }
Mike Stump11289f42009-09-09 15:08:12 +0000118
Douglas Gregorfb65e592011-07-27 05:40:30 +0000119 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +0000120}
121
Hans Wennborg950f3182013-05-16 09:22:40 +0000122static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
123 ASTContext &Context) {
John McCall66884dd2011-02-21 07:22:22 +0000124 const ArrayType *arrayType = Context.getAsArrayType(declType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000125 if (!arrayType)
Hans Wennborg950f3182013-05-16 09:22:40 +0000126 return SIF_Other;
127 return IsStringInit(init, arrayType, Context);
John McCall66884dd2011-02-21 07:22:22 +0000128}
129
Richard Smith430c23b2013-05-05 16:40:13 +0000130/// Update the type of a string literal, including any surrounding parentheses,
131/// to match the type of the object which it is initializing.
132static void updateStringLiteralType(Expr *E, QualType Ty) {
Richard Smithd74b16062013-05-06 00:35:47 +0000133 while (true) {
Richard Smith430c23b2013-05-05 16:40:13 +0000134 E->setType(Ty);
Richard Smithd74b16062013-05-06 00:35:47 +0000135 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
136 break;
137 else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
138 E = PE->getSubExpr();
139 else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
140 E = UO->getSubExpr();
141 else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
142 E = GSE->getResultExpr();
143 else
144 llvm_unreachable("unexpected expr in string literal init");
Richard Smith430c23b2013-05-05 16:40:13 +0000145 }
Richard Smith430c23b2013-05-05 16:40:13 +0000146}
147
John McCall5decec92011-02-21 07:57:55 +0000148static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
149 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000150 // Get the length of the string as parsed.
151 uint64_t StrLength =
152 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
153
Mike Stump11289f42009-09-09 15:08:12 +0000154
Chris Lattner0cb78032009-02-24 22:27:37 +0000155 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000156 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000157 // being initialized to a string literal.
Benjamin Kramere0731772012-08-04 17:00:46 +0000158 llvm::APInt ConstVal(32, StrLength);
Chris Lattner0cb78032009-02-24 22:27:37 +0000159 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000160 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
161 ConstVal,
162 ArrayType::Normal, 0);
Richard Smith430c23b2013-05-05 16:40:13 +0000163 updateStringLiteralType(Str, DeclT);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000164 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000165 }
Mike Stump11289f42009-09-09 15:08:12 +0000166
Eli Friedman893abe42009-05-29 18:22:49 +0000167 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000168
Eli Friedman554eba92011-04-11 00:23:45 +0000169 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000170 // the size may be smaller or larger than the string we are initializing.
171 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000172 if (S.getLangOpts().CPlusPlus) {
Richard Smith430c23b2013-05-05 16:40:13 +0000173 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000174 // For Pascal strings it's OK to strip off the terminating null character,
175 // so the example below is valid:
176 //
177 // unsigned char a[2] = "\pa";
178 if (SL->isPascal())
179 StrLength--;
180 }
181
Eli Friedman554eba92011-04-11 00:23:45 +0000182 // [dcl.init.string]p2
183 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000184 S.Diag(Str->getLocStart(),
Eli Friedman554eba92011-04-11 00:23:45 +0000185 diag::err_initializer_string_for_char_array_too_long)
186 << Str->getSourceRange();
187 } else {
188 // C99 6.7.8p14.
189 if (StrLength-1 > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000190 S.Diag(Str->getLocStart(),
Eli Friedman554eba92011-04-11 00:23:45 +0000191 diag::warn_initializer_string_for_char_array_too_long)
192 << Str->getSourceRange();
193 }
Mike Stump11289f42009-09-09 15:08:12 +0000194
Eli Friedman893abe42009-05-29 18:22:49 +0000195 // Set the type to the actual size that we are initializing. If we have
196 // something like:
197 // char x[1] = "foo";
198 // then this will set the string literal's type to char[1].
Richard Smith430c23b2013-05-05 16:40:13 +0000199 updateStringLiteralType(Str, DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000200}
201
Chris Lattner0cb78032009-02-24 22:27:37 +0000202//===----------------------------------------------------------------------===//
203// Semantic checking for initializer lists.
204//===----------------------------------------------------------------------===//
205
Douglas Gregorcde232f2009-01-29 01:05:33 +0000206/// @brief Semantic checking for initializer lists.
207///
208/// The InitListChecker class contains a set of routines that each
209/// handle the initialization of a certain kind of entity, e.g.,
210/// arrays, vectors, struct/union types, scalars, etc. The
211/// InitListChecker itself performs a recursive walk of the subobject
212/// structure of the type to be initialized, while stepping through
213/// the initializer list one element at a time. The IList and Index
214/// parameters to each of the Check* routines contain the active
215/// (syntactic) initializer list and the index into that initializer
216/// list that represents the current initializer. Each routine is
217/// responsible for moving that Index forward as it consumes elements.
218///
219/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000220/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000221/// initializer list and the index into that initializer list where we
222/// are copying initializers as we map them over to the semantic
223/// list. Once we have completed our recursive walk of the subobject
224/// structure, we will have constructed a full semantic initializer
225/// list.
226///
227/// C99 designators cause changes in the initializer list traversal,
228/// because they make the initialization "jump" into a specific
229/// subobject and then continue the initialization from that
230/// point. CheckDesignatedInitializer() recursively steps into the
231/// designated subobject and manages backing out the recursion to
232/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000233namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000234class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000235 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000236 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000237 bool VerifyOnly; // no diagnostics, no structure building
Benjamin Kramer6b441d62012-02-23 14:48:40 +0000238 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000239 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000240
Anders Carlsson6cabf312010-01-23 23:23:01 +0000241 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000242 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000243 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000244 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000245 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000246 InitListExpr *IList, QualType &T,
Richard Smith4e0d2e42013-09-20 20:10:22 +0000247 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000248 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000249 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000250 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000251 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000252 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000253 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000254 unsigned &StructuredIndex,
255 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000256 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000257 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000258 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000259 InitListExpr *StructuredList,
260 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000261 void CheckComplexType(const InitializedEntity &Entity,
262 InitListExpr *IList, QualType DeclType,
263 unsigned &Index,
264 InitListExpr *StructuredList,
265 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000266 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000267 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000268 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000269 InitListExpr *StructuredList,
270 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000271 void CheckReferenceType(const InitializedEntity &Entity,
272 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000273 unsigned &Index,
274 InitListExpr *StructuredList,
275 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000276 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000277 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000278 InitListExpr *StructuredList,
279 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000280 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000281 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000282 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000283 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000284 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000285 unsigned &StructuredIndex,
286 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000287 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000288 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000289 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000290 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000291 InitListExpr *StructuredList,
292 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000293 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000294 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000295 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000296 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000297 RecordDecl::field_iterator *NextField,
298 llvm::APSInt *NextElementIndex,
299 unsigned &Index,
300 InitListExpr *StructuredList,
301 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000302 bool FinishSubobjectInit,
303 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000304 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
305 QualType CurrentObjectType,
306 InitListExpr *StructuredList,
307 unsigned StructuredIndex,
308 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000309 void UpdateStructuredListElement(InitListExpr *StructuredList,
310 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000311 Expr *expr);
312 int numArrayElements(QualType DeclType);
313 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000314
Douglas Gregor2bb07652009-12-22 00:05:34 +0000315 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
316 const InitializedEntity &ParentEntity,
317 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000318 void FillInValueInitializations(const InitializedEntity &Entity,
319 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000320 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
321 Expr *InitExpr, FieldDecl *Field,
322 bool TopLevelObject);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000323 void CheckValueInitializable(const InitializedEntity &Entity);
324
Douglas Gregor85df8d82009-01-29 00:45:39 +0000325public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000326 InitListChecker(Sema &S, const InitializedEntity &Entity,
Richard Smithde229232013-06-06 11:41:05 +0000327 InitListExpr *IL, QualType &T, bool VerifyOnly);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000328 bool HadError() { return hadError; }
329
330 // @brief Retrieves the fully-structured initializer list used for
331 // semantic analysis and code generation.
332 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
333};
Chris Lattner9ececce2009-02-24 22:48:58 +0000334} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000335
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000336void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
337 assert(VerifyOnly &&
338 "CheckValueInitializable is only inteded for verification mode.");
339
340 SourceLocation Loc;
341 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
342 true);
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000343 InitializationSequence InitSeq(SemaRef, Entity, Kind, None);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000344 if (InitSeq.Failed())
345 hadError = true;
346}
347
Douglas Gregor2bb07652009-12-22 00:05:34 +0000348void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
349 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000350 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000351 bool &RequiresSecondPass) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000352 SourceLocation Loc = ILE->getLocStart();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000353 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000354 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000355 = InitializedEntity::InitializeMember(Field, &ParentEntity);
356 if (Init >= NumInits || !ILE->getInit(Init)) {
Richard Smith852c9db2013-04-20 22:23:05 +0000357 // If there's no explicit initializer but we have a default initializer, use
358 // that. This only happens in C++1y, since classes with default
359 // initializers are not aggregates in C++11.
360 if (Field->hasInClassInitializer()) {
361 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
362 ILE->getRBraceLoc(), Field);
363 if (Init < NumInits)
364 ILE->setInit(Init, DIE);
365 else {
366 ILE->updateInit(SemaRef.Context, Init, DIE);
367 RequiresSecondPass = true;
368 }
369 return;
370 }
371
Douglas Gregor2bb07652009-12-22 00:05:34 +0000372 // FIXME: We probably don't need to handle references
373 // specially here, since value-initialization of references is
374 // handled in InitializationSequence.
375 if (Field->getType()->isReferenceType()) {
376 // C++ [dcl.init.aggr]p9:
377 // If an incomplete or empty initializer-list leaves a
378 // member of reference type uninitialized, the program is
379 // ill-formed.
380 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
381 << Field->getType()
382 << ILE->getSyntacticForm()->getSourceRange();
383 SemaRef.Diag(Field->getLocation(),
384 diag::note_uninit_reference_member);
385 hadError = true;
386 return;
387 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000388
Douglas Gregor2bb07652009-12-22 00:05:34 +0000389 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
390 true);
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000391 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, None);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000392 if (!InitSeq) {
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000393 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, None);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000394 hadError = true;
395 return;
396 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000397
John McCalldadc5752010-08-24 06:29:42 +0000398 ExprResult MemberInit
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000399 = InitSeq.Perform(SemaRef, MemberEntity, Kind, None);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000400 if (MemberInit.isInvalid()) {
401 hadError = true;
402 return;
403 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000404
Douglas Gregor2bb07652009-12-22 00:05:34 +0000405 if (hadError) {
406 // Do nothing
407 } else if (Init < NumInits) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000408 ILE->setInit(Init, MemberInit.getAs<Expr>());
Sebastian Redld201edf2011-06-05 13:59:11 +0000409 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000410 // Value-initialization requires a constructor call, so
411 // extend the initializer list to include the constructor
412 // call and make a note that we'll need to take another pass
413 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000414 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000415 RequiresSecondPass = true;
416 }
417 } else if (InitListExpr *InnerILE
418 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000419 FillInValueInitializations(MemberEntity, InnerILE,
420 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000421}
422
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000423/// Recursively replaces NULL values within the given initializer list
424/// with expressions that perform value-initialization of the
425/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000426void
Douglas Gregor723796a2009-12-16 06:35:08 +0000427InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
428 InitListExpr *ILE,
429 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000430 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000431 "Should not have void type");
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000432 SourceLocation Loc = ILE->getLocStart();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000433 if (ILE->getSyntacticForm())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000434 Loc = ILE->getSyntacticForm()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000435
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000436 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000437 const RecordDecl *RDecl = RType->getDecl();
438 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000439 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
440 Entity, ILE, RequiresSecondPass);
Richard Smith852c9db2013-04-20 22:23:05 +0000441 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
442 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000443 for (auto *Field : RDecl->fields()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000444 if (Field->hasInClassInitializer()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000445 FillInValueInitForField(0, Field, Entity, ILE, RequiresSecondPass);
Richard Smith852c9db2013-04-20 22:23:05 +0000446 break;
447 }
448 }
449 } else {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000450 unsigned Init = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000451 for (auto *Field : RDecl->fields()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000452 if (Field->isUnnamedBitfield())
453 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000454
Douglas Gregor2bb07652009-12-22 00:05:34 +0000455 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000456 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000457
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000458 FillInValueInitForField(Init, Field, Entity, ILE, RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000459 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000460 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000461
Douglas Gregor2bb07652009-12-22 00:05:34 +0000462 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000463
Douglas Gregor2bb07652009-12-22 00:05:34 +0000464 // Only look at the first initialization of a union.
Richard Smith852c9db2013-04-20 22:23:05 +0000465 if (RDecl->isUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000466 break;
467 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000468 }
469
470 return;
Mike Stump11289f42009-09-09 15:08:12 +0000471 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000472
473 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000474
Douglas Gregor723796a2009-12-16 06:35:08 +0000475 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000476 unsigned NumInits = ILE->getNumInits();
477 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000478 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000479 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000480 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
481 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000482 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000483 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000484 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000485 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000486 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000487 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000488 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000489 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000490 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000491
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000492
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000493 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000494 if (hadError)
495 return;
496
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000497 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
498 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000499 ElementEntity.setElementIndex(Init);
500
Craig Topperc3ec1492014-05-26 06:22:03 +0000501 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000502 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000503 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
504 true);
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000505 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, None);
Douglas Gregor723796a2009-12-16 06:35:08 +0000506 if (!InitSeq) {
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000507 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, None);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000508 hadError = true;
509 return;
510 }
511
John McCalldadc5752010-08-24 06:29:42 +0000512 ExprResult ElementInit
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000513 = InitSeq.Perform(SemaRef, ElementEntity, Kind, None);
Douglas Gregor723796a2009-12-16 06:35:08 +0000514 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000515 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000516 return;
517 }
518
519 if (hadError) {
520 // Do nothing
521 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000522 // For arrays, just set the expression used for value-initialization
523 // of the "holes" in the array.
524 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000525 ILE->setArrayFiller(ElementInit.getAs<Expr>());
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000526 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000527 ILE->setInit(Init, ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000528 } else {
529 // For arrays, just set the expression used for value-initialization
530 // of the rest of elements and exit.
531 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000532 ILE->setArrayFiller(ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000533 return;
534 }
535
Sebastian Redld201edf2011-06-05 13:59:11 +0000536 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000537 // Value-initialization requires a constructor call, so
538 // extend the initializer list to include the constructor
539 // call and make a note that we'll need to take another pass
540 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000541 ILE->updateInit(SemaRef.Context, Init, ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000542 RequiresSecondPass = true;
543 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000544 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000545 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000546 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregor723796a2009-12-16 06:35:08 +0000547 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000548 }
549}
550
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000551
Douglas Gregor723796a2009-12-16 06:35:08 +0000552InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000553 InitListExpr *IL, QualType &T,
Richard Smithde229232013-06-06 11:41:05 +0000554 bool VerifyOnly)
555 : SemaRef(S), VerifyOnly(VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000556 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000557
Richard Smith4e0d2e42013-09-20 20:10:22 +0000558 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000559 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000560 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000561 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000562
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000563 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000564 bool RequiresSecondPass = false;
565 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000566 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000567 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000568 RequiresSecondPass);
569 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000570}
571
572int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000573 // FIXME: use a proper constant
574 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000575 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000576 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000577 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
578 }
579 return maxElements;
580}
581
582int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000583 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000584 int InitializableMembers = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000585 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000586 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000587 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000588
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000589 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000590 return std::min(InitializableMembers, 1);
591 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000592}
593
Richard Smith4e0d2e42013-09-20 20:10:22 +0000594/// Check whether the range of the initializer \p ParentIList from element
595/// \p Index onwards can be used to initialize an object of type \p T. Update
596/// \p Index to indicate how many elements of the list were consumed.
597///
598/// This also fills in \p StructuredList, from element \p StructuredIndex
599/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000600void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000601 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000602 QualType T, unsigned &Index,
603 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000604 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000605 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000606
Steve Narofff8ecff22008-05-01 22:18:59 +0000607 if (T->isArrayType())
608 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000609 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000610 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000611 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000612 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000613 else
David Blaikie83d382b2011-09-23 05:06:16 +0000614 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000615
Eli Friedmane0f832b2008-05-25 13:49:22 +0000616 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000617 if (!VerifyOnly)
618 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
619 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000620 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000621 hadError = true;
622 return;
623 }
624
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000625 // Build a structured initializer list corresponding to this subobject.
626 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000627 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
628 StructuredIndex,
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000629 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregor5741efb2009-03-01 17:12:46 +0000630 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000631 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000632
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000633 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000634 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000635 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000636 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000637 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000638 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000639
Richard Smithde229232013-06-06 11:41:05 +0000640 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000641 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000642
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000643 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000644 // Update the structured sub-object initializer so that it's ending
645 // range corresponds with the end of the last initializer it used.
646 if (EndIndex < ParentIList->getNumInits()) {
647 SourceLocation EndLoc
648 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
649 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
650 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000651
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000652 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000653 if (T->isArrayType() || T->isRecordType()) {
654 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smithde229232013-06-06 11:41:05 +0000655 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000656 << StructuredSubobjectInitList->getSourceRange()
657 << FixItHint::CreateInsertion(
658 StructuredSubobjectInitList->getLocStart(), "{")
659 << FixItHint::CreateInsertion(
660 SemaRef.getLocForEndOfToken(
661 StructuredSubobjectInitList->getLocEnd()),
662 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000663 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000664 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000665}
666
Richard Smith4e0d2e42013-09-20 20:10:22 +0000667/// Check whether the initializer \p IList (that was written with explicit
668/// braces) can be used to initialize an object of type \p T.
669///
670/// This also fills in \p StructuredList with the fully-braced, desugared
671/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000672void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000673 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000674 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000675 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000676 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000677 if (!VerifyOnly) {
678 SyntacticToSemantic[IList] = StructuredList;
679 StructuredList->setSyntacticForm(IList);
680 }
Richard Smith4e0d2e42013-09-20 20:10:22 +0000681
682 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000683 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000684 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000685 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +0000686 QualType ExprTy = T;
687 if (!ExprTy->isArrayType())
688 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000689 IList->setType(ExprTy);
690 StructuredList->setType(ExprTy);
691 }
Eli Friedman85f54972008-05-25 13:22:35 +0000692 if (hadError)
693 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000694
Eli Friedman85f54972008-05-25 13:22:35 +0000695 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000696 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000697 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000698 if (SemaRef.getLangOpts().CPlusPlus ||
699 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000700 IList->getType()->isVectorType())) {
701 hadError = true;
702 }
703 return;
704 }
705
Eli Friedmanbd327452009-05-29 20:20:05 +0000706 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +0000707 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
708 SIF_None) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000709 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000710 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000711 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000712 hadError = true;
713 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000714 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000715 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000716 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000717 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000718 // Don't complain for incomplete types, since we'll get an error
719 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000720 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000721 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000722 CurrentObjectType->isArrayType()? 0 :
723 CurrentObjectType->isVectorType()? 1 :
724 CurrentObjectType->isScalarType()? 2 :
725 CurrentObjectType->isUnionType()? 3 :
726 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000727
728 unsigned DK = diag::warn_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000729 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +0000730 DK = diag::err_excess_initializers;
731 hadError = true;
732 }
David Blaikiebbafb8a2012-03-11 07:00:24 +0000733 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +0000734 DK = diag::err_excess_initializers;
735 hadError = true;
736 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000737
Chris Lattnerb0912a52009-02-24 22:50:46 +0000738 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000739 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000740 }
741 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000742
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000743 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
744 !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000745 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000746 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000747 << FixItHint::CreateRemoval(IList->getLocStart())
748 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000749}
750
Anders Carlsson6cabf312010-01-23 23:23:01 +0000751void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000752 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000753 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000754 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000755 unsigned &Index,
756 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000757 unsigned &StructuredIndex,
758 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000759 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
760 // Explicitly braced initializer for complex type can be real+imaginary
761 // parts.
762 CheckComplexType(Entity, IList, DeclType, Index,
763 StructuredList, StructuredIndex);
764 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000765 CheckScalarType(Entity, IList, DeclType, Index,
766 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000767 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000768 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000769 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +0000770 } else if (DeclType->isRecordType()) {
771 assert(DeclType->isAggregateType() &&
772 "non-aggregate records should be handed in CheckSubElementType");
773 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
774 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
775 SubobjectIsDesignatorContext, Index,
776 StructuredList, StructuredIndex,
777 TopLevelObject);
778 } else if (DeclType->isArrayType()) {
779 llvm::APSInt Zero(
780 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
781 false);
782 CheckArrayType(Entity, IList, DeclType, Zero,
783 SubobjectIsDesignatorContext, Index,
784 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +0000785 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
786 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000787 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000788 if (!VerifyOnly)
789 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
790 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000791 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000792 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000793 CheckReferenceType(Entity, IList, DeclType, Index,
794 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000795 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000796 if (!VerifyOnly)
797 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
798 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000799 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000800 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000801 if (!VerifyOnly)
802 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
803 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000804 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000805 }
806}
807
Anders Carlsson6cabf312010-01-23 23:23:01 +0000808void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000809 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000810 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000811 unsigned &Index,
812 InitListExpr *StructuredList,
813 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000814 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +0000815
816 if (ElemType->isReferenceType())
817 return CheckReferenceType(Entity, IList, ElemType, Index,
818 StructuredList, StructuredIndex);
819
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000820 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smithe20c83d2012-07-07 08:35:56 +0000821 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
Richard Smith4e0d2e42013-09-20 20:10:22 +0000822 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +0000823 = getStructuredSubobjectInit(IList, Index, ElemType,
824 StructuredList, StructuredIndex,
825 SubInitList->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000826 CheckExplicitInitList(Entity, SubInitList, ElemType,
827 InnerStructuredList);
Richard Smithe20c83d2012-07-07 08:35:56 +0000828 ++StructuredIndex;
829 ++Index;
830 return;
831 }
832 assert(SemaRef.getLangOpts().CPlusPlus &&
833 "non-aggregate records are only possible in C++");
834 // C++ initialization is handled later.
835 }
836
Eli Friedman4628cf72013-08-19 22:12:56 +0000837 // FIXME: Need to handle atomic aggregate types with implicit init lists.
838 if (ElemType->isScalarType() || ElemType->isAtomicType())
John McCall5decec92011-02-21 07:57:55 +0000839 return CheckScalarType(Entity, IList, ElemType, Index,
840 StructuredList, StructuredIndex);
Anders Carlsson03068aa2009-08-27 17:18:13 +0000841
Eli Friedman4628cf72013-08-19 22:12:56 +0000842 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
843 ElemType->isArrayType()) && "Unexpected type");
844
John McCall5decec92011-02-21 07:57:55 +0000845 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
846 // arrayType can be incomplete if we're initializing a flexible
847 // array member. There's nothing we can do with the completed
848 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000849
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000850 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +0000851 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000852 CheckStringInit(expr, ElemType, arrayType, SemaRef);
853 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +0000854 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000855 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000856 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000857 }
John McCall5decec92011-02-21 07:57:55 +0000858
859 // Fall through for subaggregate initialization.
860
David Blaikiebbafb8a2012-03-11 07:00:24 +0000861 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCall5decec92011-02-21 07:57:55 +0000862 // C++ [dcl.init.aggr]p12:
863 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000864 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000865 // an initializer-list. If the initializer can initialize a
866 // member, the member is initialized. [...]
867
868 // FIXME: Better EqualLoc?
869 InitializationKind Kind =
870 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000871 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCall5decec92011-02-21 07:57:55 +0000872
873 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000874 if (!VerifyOnly) {
Richard Smith0f8ede12011-12-20 04:00:21 +0000875 ExprResult Result =
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000876 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smith0f8ede12011-12-20 04:00:21 +0000877 if (Result.isInvalid())
878 hadError = true;
John McCall5decec92011-02-21 07:57:55 +0000879
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000880 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000881 Result.getAs<Expr>());
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000882 }
John McCall5decec92011-02-21 07:57:55 +0000883 ++Index;
884 return;
885 }
886
887 // Fall through for subaggregate initialization
888 } else {
889 // C99 6.7.8p13:
890 //
891 // The initializer for a structure or union object that has
892 // automatic storage duration shall be either an initializer
893 // list as described below, or a single expression that has
894 // compatible structure or union type. In the latter case, the
895 // initial value of the object, including unnamed members, is
896 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000897 ExprResult ExprRes = expr;
John McCall5decec92011-02-21 07:57:55 +0000898 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000899 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
900 !VerifyOnly)
Eli Friedmanb2a8d462013-09-17 04:07:04 +0000901 != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +0000902 if (ExprRes.isInvalid())
903 hadError = true;
904 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000905 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000906 if (ExprRes.isInvalid())
907 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +0000908 }
909 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000910 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000911 ++Index;
912 return;
913 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000914 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +0000915 // Fall through for subaggregate initialization
916 }
917
918 // C++ [dcl.init.aggr]p12:
919 //
920 // [...] Otherwise, if the member is itself a non-empty
921 // subaggregate, brace elision is assumed and the initializer is
922 // considered for the initialization of the first member of
923 // the subaggregate.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000924 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +0000925 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +0000926 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
927 StructuredIndex);
928 ++StructuredIndex;
929 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000930 if (!VerifyOnly) {
931 // We cannot initialize this element, so let
932 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000933 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000934 /*TopLevelOfInitList=*/true);
935 }
John McCall5decec92011-02-21 07:57:55 +0000936 hadError = true;
937 ++Index;
938 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000939 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000940}
941
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000942void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
943 InitListExpr *IList, QualType DeclType,
944 unsigned &Index,
945 InitListExpr *StructuredList,
946 unsigned &StructuredIndex) {
947 assert(Index == 0 && "Index in explicit init list must be zero");
948
949 // As an extension, clang supports complex initializers, which initialize
950 // a complex number component-wise. When an explicit initializer list for
951 // a complex number contains two two initializers, this extension kicks in:
952 // it exepcts the initializer list to contain two elements convertible to
953 // the element type of the complex type. The first element initializes
954 // the real part, and the second element intitializes the imaginary part.
955
956 if (IList->getNumInits() != 2)
957 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
958 StructuredIndex);
959
960 // This is an extension in C. (The builtin _Complex type does not exist
961 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000962 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000963 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
964 << IList->getSourceRange();
965
966 // Initialize the complex number.
967 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
968 InitializedEntity ElementEntity =
969 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
970
971 for (unsigned i = 0; i < 2; ++i) {
972 ElementEntity.setElementIndex(Index);
973 CheckSubElementType(ElementEntity, IList, elementType, Index,
974 StructuredList, StructuredIndex);
975 }
976}
977
978
Anders Carlsson6cabf312010-01-23 23:23:01 +0000979void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000980 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000981 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000982 InitListExpr *StructuredList,
983 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000984 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +0000985 if (!VerifyOnly)
986 SemaRef.Diag(IList->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000987 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smithc8239732011-10-18 21:39:00 +0000988 diag::warn_cxx98_compat_empty_scalar_initializer :
989 diag::err_empty_scalar_initializer)
990 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000991 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000992 ++Index;
993 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000994 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000995 }
John McCall643169b2010-11-11 00:46:36 +0000996
997 Expr *expr = IList->getInit(Index);
998 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +0000999 // FIXME: This is invalid, and accepting it causes overload resolution
1000 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001001 if (!VerifyOnly)
1002 SemaRef.Diag(SubIList->getLocStart(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001003 diag::ext_many_braces_around_scalar_init)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001004 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001005
1006 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1007 StructuredIndex);
1008 return;
1009 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001010 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001011 SemaRef.Diag(expr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001012 diag::err_designator_for_scalar_init)
1013 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001014 hadError = true;
1015 ++Index;
1016 ++StructuredIndex;
1017 return;
1018 }
1019
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001020 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001021 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001022 hadError = true;
1023 ++Index;
1024 return;
1025 }
1026
John McCall643169b2010-11-11 00:46:36 +00001027 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001028 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001029 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001030
Craig Topperc3ec1492014-05-26 06:22:03 +00001031 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001032
1033 if (Result.isInvalid())
1034 hadError = true; // types weren't compatible.
1035 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001036 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001037
John McCall643169b2010-11-11 00:46:36 +00001038 if (ResultExpr != expr) {
1039 // The type was promoted, update initializer list.
1040 IList->setInit(Index, ResultExpr);
1041 }
1042 }
1043 if (hadError)
1044 ++StructuredIndex;
1045 else
1046 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1047 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001048}
1049
Anders Carlsson6cabf312010-01-23 23:23:01 +00001050void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1051 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001052 unsigned &Index,
1053 InitListExpr *StructuredList,
1054 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001055 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001056 // FIXME: It would be wonderful if we could point at the actual member. In
1057 // general, it would be useful to pass location information down the stack,
1058 // so that we know the location (or decl) of the "current object" being
1059 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001060 if (!VerifyOnly)
1061 SemaRef.Diag(IList->getLocStart(),
1062 diag::err_init_reference_member_uninitialized)
1063 << DeclType
1064 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001065 hadError = true;
1066 ++Index;
1067 ++StructuredIndex;
1068 return;
1069 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001070
1071 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001072 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001073 if (!VerifyOnly)
1074 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1075 << DeclType << IList->getSourceRange();
1076 hadError = true;
1077 ++Index;
1078 ++StructuredIndex;
1079 return;
1080 }
1081
1082 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001083 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001084 hadError = true;
1085 ++Index;
1086 return;
1087 }
1088
1089 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001090 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1091 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001092
1093 if (Result.isInvalid())
1094 hadError = true;
1095
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001096 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001097 IList->setInit(Index, expr);
1098
1099 if (hadError)
1100 ++StructuredIndex;
1101 else
1102 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1103 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001104}
1105
Anders Carlsson6cabf312010-01-23 23:23:01 +00001106void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001107 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001108 unsigned &Index,
1109 InitListExpr *StructuredList,
1110 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001111 const VectorType *VT = DeclType->getAs<VectorType>();
1112 unsigned maxElements = VT->getNumElements();
1113 unsigned numEltsInit = 0;
1114 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001115
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001116 if (Index >= IList->getNumInits()) {
1117 // Make sure the element type can be value-initialized.
1118 if (VerifyOnly)
1119 CheckValueInitializable(
1120 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1121 return;
1122 }
1123
David Blaikiebbafb8a2012-03-11 07:00:24 +00001124 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001125 // If the initializing element is a vector, try to copy-initialize
1126 // instead of breaking it apart (which is doomed to failure anyway).
1127 Expr *Init = IList->getInit(Index);
1128 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001129 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001130 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001131 hadError = true;
1132 ++Index;
1133 return;
1134 }
1135
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001136 ExprResult Result =
1137 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1138 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001139
Craig Topperc3ec1492014-05-26 06:22:03 +00001140 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001141 if (Result.isInvalid())
1142 hadError = true; // types weren't compatible.
1143 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001144 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001145
John McCall6a16b2f2010-10-30 00:11:39 +00001146 if (ResultExpr != Init) {
1147 // The type was promoted, update initializer list.
1148 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001149 }
1150 }
John McCall6a16b2f2010-10-30 00:11:39 +00001151 if (hadError)
1152 ++StructuredIndex;
1153 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001154 UpdateStructuredListElement(StructuredList, StructuredIndex,
1155 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001156 ++Index;
1157 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001158 }
Mike Stump11289f42009-09-09 15:08:12 +00001159
John McCall6a16b2f2010-10-30 00:11:39 +00001160 InitializedEntity ElementEntity =
1161 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001162
John McCall6a16b2f2010-10-30 00:11:39 +00001163 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1164 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001165 if (Index >= IList->getNumInits()) {
1166 if (VerifyOnly)
1167 CheckValueInitializable(ElementEntity);
John McCall6a16b2f2010-10-30 00:11:39 +00001168 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001169 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001170
John McCall6a16b2f2010-10-30 00:11:39 +00001171 ElementEntity.setElementIndex(Index);
1172 CheckSubElementType(ElementEntity, IList, elementType, Index,
1173 StructuredList, StructuredIndex);
1174 }
1175 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001176 }
John McCall6a16b2f2010-10-30 00:11:39 +00001177
1178 InitializedEntity ElementEntity =
1179 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001180
John McCall6a16b2f2010-10-30 00:11:39 +00001181 // OpenCL initializers allows vectors to be constructed from vectors.
1182 for (unsigned i = 0; i < maxElements; ++i) {
1183 // Don't attempt to go past the end of the init list
1184 if (Index >= IList->getNumInits())
1185 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001186
John McCall6a16b2f2010-10-30 00:11:39 +00001187 ElementEntity.setElementIndex(Index);
1188
1189 QualType IType = IList->getInit(Index)->getType();
1190 if (!IType->isVectorType()) {
1191 CheckSubElementType(ElementEntity, IList, elementType, Index,
1192 StructuredList, StructuredIndex);
1193 ++numEltsInit;
1194 } else {
1195 QualType VecType;
1196 const VectorType *IVT = IType->getAs<VectorType>();
1197 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001198
John McCall6a16b2f2010-10-30 00:11:39 +00001199 if (IType->isExtVectorType())
1200 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1201 else
1202 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001203 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001204 CheckSubElementType(ElementEntity, IList, VecType, Index,
1205 StructuredList, StructuredIndex);
1206 numEltsInit += numIElts;
1207 }
1208 }
1209
1210 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001211 if (numEltsInit != maxElements) {
1212 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001213 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001214 diag::err_vector_incorrect_num_initializers)
1215 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1216 hadError = true;
1217 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001218}
1219
Anders Carlsson6cabf312010-01-23 23:23:01 +00001220void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001221 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001222 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001223 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001224 unsigned &Index,
1225 InitListExpr *StructuredList,
1226 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001227 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1228
Steve Narofff8ecff22008-05-01 22:18:59 +00001229 // Check for the special-case of initializing an array with a string.
1230 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001231 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1232 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001233 // We place the string literal directly into the resulting
1234 // initializer list. This is the only place where the structure
1235 // of the structured initializer list doesn't match exactly,
1236 // because doing so would involve allocating one character
1237 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001238 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001239 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1240 UpdateStructuredListElement(StructuredList, StructuredIndex,
1241 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001242 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1243 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001244 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001245 return;
1246 }
1247 }
John McCall66884dd2011-02-21 07:22:22 +00001248 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001249 // Check for VLAs; in standard C it would be possible to check this
1250 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1251 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001252 if (!VerifyOnly)
1253 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1254 diag::err_variable_object_no_init)
1255 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001256 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001257 ++Index;
1258 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001259 return;
1260 }
1261
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001262 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001263 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1264 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001265 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001266 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001267 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001268 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001269 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001270 maxElementsKnown = true;
1271 }
1272
John McCall66884dd2011-02-21 07:22:22 +00001273 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001274 while (Index < IList->getNumInits()) {
1275 Expr *Init = IList->getInit(Index);
1276 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001277 // If we're not the subobject that matches up with the '{' for
1278 // the designator, we shouldn't be handling the
1279 // designator. Return immediately.
1280 if (!SubobjectIsDesignatorContext)
1281 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001282
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001283 // Handle this designated initializer. elementIndex will be
1284 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001285 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001286 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001287 StructuredList, StructuredIndex, true,
1288 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001289 hadError = true;
1290 continue;
1291 }
1292
Douglas Gregor033d1252009-01-23 16:54:12 +00001293 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001294 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001295 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001296 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001297 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001298
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001299 // If the array is of incomplete type, keep track of the number of
1300 // elements in the initializer.
1301 if (!maxElementsKnown && elementIndex > maxElements)
1302 maxElements = elementIndex;
1303
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001304 continue;
1305 }
1306
1307 // If we know the maximum number of elements, and we've already
1308 // hit it, stop consuming elements in the initializer list.
1309 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001310 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001311
Anders Carlsson6cabf312010-01-23 23:23:01 +00001312 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001313 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001314 Entity);
1315 // Check this element.
1316 CheckSubElementType(ElementEntity, IList, elementType, Index,
1317 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001318 ++elementIndex;
1319
1320 // If the array is of incomplete type, keep track of the number of
1321 // elements in the initializer.
1322 if (!maxElementsKnown && elementIndex > maxElements)
1323 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001324 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001325 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001326 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001327 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001328 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001329 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001330 // Sizing an array implicitly to zero is not allowed by ISO C,
1331 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001332 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001333 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001334 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001335
Mike Stump11289f42009-09-09 15:08:12 +00001336 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001337 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001338 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001339 if (!hadError && VerifyOnly) {
1340 // Check if there are any members of the array that get value-initialized.
1341 // If so, check if doing that is possible.
1342 // FIXME: This needs to detect holes left by designated initializers too.
1343 if (maxElementsKnown && elementIndex < maxElements)
1344 CheckValueInitializable(InitializedEntity::InitializeElement(
1345 SemaRef.Context, 0, Entity));
1346 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001347}
1348
Eli Friedman3fa64df2011-08-23 22:24:57 +00001349bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1350 Expr *InitExpr,
1351 FieldDecl *Field,
1352 bool TopLevelObject) {
1353 // Handle GNU flexible array initializers.
1354 unsigned FlexArrayDiag;
1355 if (isa<InitListExpr>(InitExpr) &&
1356 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1357 // Empty flexible array init always allowed as an extension
1358 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001359 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001360 // Disallow flexible array init in C++; it is not required for gcc
1361 // compatibility, and it needs work to IRGen correctly in general.
1362 FlexArrayDiag = diag::err_flexible_array_init;
1363 } else if (!TopLevelObject) {
1364 // Disallow flexible array init on non-top-level object
1365 FlexArrayDiag = diag::err_flexible_array_init;
1366 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1367 // Disallow flexible array init on anything which is not a variable.
1368 FlexArrayDiag = diag::err_flexible_array_init;
1369 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1370 // Disallow flexible array init on local variables.
1371 FlexArrayDiag = diag::err_flexible_array_init;
1372 } else {
1373 // Allow other cases.
1374 FlexArrayDiag = diag::ext_flexible_array_init;
1375 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001376
1377 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001378 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001379 FlexArrayDiag)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001380 << InitExpr->getLocStart();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001381 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1382 << Field;
1383 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001384
1385 return FlexArrayDiag != diag::ext_flexible_array_init;
1386}
1387
Anders Carlsson6cabf312010-01-23 23:23:01 +00001388void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001389 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001390 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001391 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001392 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001393 unsigned &Index,
1394 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001395 unsigned &StructuredIndex,
1396 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001397 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001398
Eli Friedman23a9e312008-05-19 19:16:24 +00001399 // If the record is invalid, some of it's members are invalid. To avoid
1400 // confusion, we forgo checking the intializer for the entire record.
1401 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001402 // Assume it was supposed to consume a single initializer.
1403 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001404 hadError = true;
1405 return;
Mike Stump11289f42009-09-09 15:08:12 +00001406 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001407
1408 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001409 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001410
1411 // If there's a default initializer, use it.
1412 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1413 if (VerifyOnly)
1414 return;
1415 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1416 Field != FieldEnd; ++Field) {
1417 if (Field->hasInClassInitializer()) {
1418 StructuredList->setInitializedFieldInUnion(*Field);
1419 // FIXME: Actually build a CXXDefaultInitExpr?
1420 return;
1421 }
1422 }
1423 }
1424
1425 // Value-initialize the first named member of the union.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001426 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1427 Field != FieldEnd; ++Field) {
1428 if (Field->getDeclName()) {
1429 if (VerifyOnly)
1430 CheckValueInitializable(
David Blaikie40ed2972012-06-06 20:45:41 +00001431 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001432 else
David Blaikie40ed2972012-06-06 20:45:41 +00001433 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001434 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001435 }
1436 }
1437 return;
1438 }
1439
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001440 // If structDecl is a forward declaration, this loop won't do
1441 // anything except look at designated initializers; That's okay,
1442 // because an error should get printed out elsewhere. It might be
1443 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001444 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001445 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001446 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001447 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001448 while (Index < IList->getNumInits()) {
1449 Expr *Init = IList->getInit(Index);
1450
1451 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001452 // If we're not the subobject that matches up with the '{' for
1453 // the designator, we shouldn't be handling the
1454 // designator. Return immediately.
1455 if (!SubobjectIsDesignatorContext)
1456 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001457
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001458 // Handle this designated initializer. Field will be updated to
1459 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001460 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001461 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001462 StructuredList, StructuredIndex,
1463 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001464 hadError = true;
1465
Douglas Gregora9add4e2009-02-12 19:00:39 +00001466 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001467
1468 // Disable check for missing fields when designators are used.
1469 // This matches gcc behaviour.
1470 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001471 continue;
1472 }
1473
1474 if (Field == FieldEnd) {
1475 // We've run out of fields. We're done.
1476 break;
1477 }
1478
Douglas Gregora9add4e2009-02-12 19:00:39 +00001479 // We've already initialized a member of a union. We're done.
1480 if (InitializedSomething && DeclType->isUnionType())
1481 break;
1482
Douglas Gregor91f84212008-12-11 16:49:14 +00001483 // If we've hit the flexible array member at the end, we're done.
1484 if (Field->getType()->isIncompleteArrayType())
1485 break;
1486
Douglas Gregor51695702009-01-29 16:53:55 +00001487 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001488 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001489 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001490 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001491 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001492
Douglas Gregora82064c2011-06-29 21:51:31 +00001493 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001494 bool InvalidUse;
1495 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00001496 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001497 else
David Blaikie40ed2972012-06-06 20:45:41 +00001498 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001499 IList->getInit(Index)->getLocStart());
1500 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001501 ++Index;
1502 ++Field;
1503 hadError = true;
1504 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001505 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001506
Anders Carlsson6cabf312010-01-23 23:23:01 +00001507 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001508 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001509 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1510 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001511 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001512
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001513 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001514 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00001515 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001516 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001517
1518 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001519 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001520
John McCalle40b58e2010-03-11 19:32:38 +00001521 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001522 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1523 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1524 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001525 // It is possible we have one or more unnamed bitfields remaining.
1526 // Find first (if any) named field and emit warning.
1527 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1528 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00001529 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00001530 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00001531 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00001532 break;
1533 }
1534 }
1535 }
1536
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001537 // Check that any remaining fields can be value-initialized.
1538 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1539 !Field->getType()->isIncompleteArrayType()) {
1540 // FIXME: Should check for holes left by designated initializers too.
1541 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00001542 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001543 CheckValueInitializable(
David Blaikie40ed2972012-06-06 20:45:41 +00001544 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001545 }
1546 }
1547
Mike Stump11289f42009-09-09 15:08:12 +00001548 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001549 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001550 return;
1551
David Blaikie40ed2972012-06-06 20:45:41 +00001552 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00001553 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001554 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001555 ++Index;
1556 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001557 }
1558
Anders Carlsson6cabf312010-01-23 23:23:01 +00001559 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001560 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001561
Anders Carlsson6cabf312010-01-23 23:23:01 +00001562 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001563 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001564 StructuredList, StructuredIndex);
1565 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001566 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001567 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001568}
Steve Narofff8ecff22008-05-01 22:18:59 +00001569
Douglas Gregord5846a12009-04-15 06:41:24 +00001570/// \brief Expand a field designator that refers to a member of an
1571/// anonymous struct or union into a series of field designators that
1572/// refers to the field within the appropriate subobject.
1573///
Douglas Gregord5846a12009-04-15 06:41:24 +00001574static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001575 DesignatedInitExpr *DIE,
1576 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001577 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001578 typedef DesignatedInitExpr::Designator Designator;
1579
Douglas Gregord5846a12009-04-15 06:41:24 +00001580 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001581 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001582 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1583 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1584 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00001585 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00001586 DIE->getDesignator(DesigIdx)->getDotLoc(),
1587 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1588 else
Craig Topperc3ec1492014-05-26 06:22:03 +00001589 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1590 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001591 assert(isa<FieldDecl>(*PI));
1592 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001593 }
1594
1595 // Expand the current designator into the set of replacement
1596 // designators, so we have a full subobject path down to where the
1597 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001598 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001599 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001600}
Mike Stump11289f42009-09-09 15:08:12 +00001601
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001602/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001603/// corresponds to FieldName.
1604static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1605 IdentifierInfo *FieldName) {
Argyrios Kyrtzidis54b10292012-09-10 22:04:26 +00001606 if (!FieldName)
Craig Topperc3ec1492014-05-26 06:22:03 +00001607 return nullptr;
Argyrios Kyrtzidis54b10292012-09-10 22:04:26 +00001608
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001609 assert(AnonField->isAnonymousStructOrUnion());
1610 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman6d1bebb2012-02-09 22:16:56 +00001611 while (IndirectFieldDecl *IF =
1612 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidis54b10292012-09-10 22:04:26 +00001613 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001614 return IF;
1615 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001616 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001617 return nullptr;
Douglas Gregord5846a12009-04-15 06:41:24 +00001618}
1619
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001620static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1621 DesignatedInitExpr *DIE) {
1622 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1623 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1624 for (unsigned I = 0; I < NumIndexExprs; ++I)
1625 IndexExprs[I] = DIE->getSubExpr(I + 1);
1626 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001627 DIE->size(), IndexExprs,
1628 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001629 DIE->usesGNUSyntax(), DIE->getInit());
1630}
1631
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001632namespace {
1633
1634// Callback to only accept typo corrections that are for field members of
1635// the given struct or union.
1636class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1637 public:
1638 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1639 : Record(RD) {}
1640
Craig Toppere14c0f82014-03-12 04:55:44 +00001641 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001642 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1643 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1644 }
1645
1646 private:
1647 RecordDecl *Record;
1648};
1649
1650}
1651
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001652/// @brief Check the well-formedness of a C99 designated initializer.
1653///
1654/// Determines whether the designated initializer @p DIE, which
1655/// resides at the given @p Index within the initializer list @p
1656/// IList, is well-formed for a current object of type @p DeclType
1657/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001658/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001659/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001660///
1661/// @param IList The initializer list in which this designated
1662/// initializer occurs.
1663///
Douglas Gregora5324162009-04-15 04:56:10 +00001664/// @param DIE The designated initializer expression.
1665///
1666/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001667///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00001668/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001669/// into which the designation in @p DIE should refer.
1670///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001671/// @param NextField If non-NULL and the first designator in @p DIE is
1672/// a field, this will be set to the field declaration corresponding
1673/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001674///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001675/// @param NextElementIndex If non-NULL and the first designator in @p
1676/// DIE is an array designator or GNU array-range designator, this
1677/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001678///
1679/// @param Index Index into @p IList where the designated initializer
1680/// @p DIE occurs.
1681///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001682/// @param StructuredList The initializer list expression that
1683/// describes all of the subobject initializers in the order they'll
1684/// actually be initialized.
1685///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001686/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001687bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001688InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001689 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001690 DesignatedInitExpr *DIE,
1691 unsigned DesigIdx,
1692 QualType &CurrentObjectType,
1693 RecordDecl::field_iterator *NextField,
1694 llvm::APSInt *NextElementIndex,
1695 unsigned &Index,
1696 InitListExpr *StructuredList,
1697 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001698 bool FinishSubobjectInit,
1699 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001700 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001701 // Check the actual initialization for the designated object type.
1702 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001703
1704 // Temporarily remove the designator expression from the
1705 // initializer list that the child calls see, so that we don't try
1706 // to re-process the designator.
1707 unsigned OldIndex = Index;
1708 IList->setInit(OldIndex, DIE->getInit());
1709
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001710 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001711 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001712
1713 // Restore the designated initializer expression in the syntactic
1714 // form of the initializer list.
1715 if (IList->getInit(OldIndex) != DIE->getInit())
1716 DIE->setInit(IList->getInit(OldIndex));
1717 IList->setInit(OldIndex, DIE);
1718
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001719 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001720 }
1721
Douglas Gregora5324162009-04-15 04:56:10 +00001722 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001723 bool IsFirstDesignator = (DesigIdx == 0);
1724 if (!VerifyOnly) {
1725 assert((IsFirstDesignator || StructuredList) &&
1726 "Need a non-designated initializer list to start from");
1727
1728 // Determine the structural initializer list that corresponds to the
1729 // current subobject.
Benjamin Kramer6b441d62012-02-23 14:48:40 +00001730 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001731 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1732 StructuredList, StructuredIndex,
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001733 SourceRange(D->getLocStart(),
1734 DIE->getLocEnd()));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001735 assert(StructuredList && "Expected a structured initializer list");
1736 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001737
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001738 if (D->isFieldDesignator()) {
1739 // C99 6.7.8p7:
1740 //
1741 // If a designator has the form
1742 //
1743 // . identifier
1744 //
1745 // then the current object (defined below) shall have
1746 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001747 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001748 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001749 if (!RT) {
1750 SourceLocation Loc = D->getDotLoc();
1751 if (Loc.isInvalid())
1752 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001753 if (!VerifyOnly)
1754 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001755 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001756 ++Index;
1757 return true;
1758 }
1759
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001760 // Note: we perform a linear search of the fields here, despite
1761 // the fact that we have a faster lookup method, because we always
1762 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001763 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001764 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001765 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001766 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001767 Field = RT->getDecl()->field_begin(),
1768 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001769 for (; Field != FieldEnd; ++Field) {
1770 if (Field->isUnnamedBitfield())
1771 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001772
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001773 // If we find a field representing an anonymous field, look in the
1774 // IndirectFieldDecl that follow for the designated initializer.
1775 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1776 if (IndirectFieldDecl *IF =
David Blaikie40ed2972012-06-06 20:45:41 +00001777 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001778 // In verify mode, don't modify the original.
1779 if (VerifyOnly)
1780 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001781 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1782 D = DIE->getDesignator(DesigIdx);
1783 break;
1784 }
1785 }
David Blaikie40ed2972012-06-06 20:45:41 +00001786 if (KnownField && KnownField == *Field)
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001787 break;
1788 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001789 break;
1790
1791 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001792 }
1793
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001794 if (Field == FieldEnd) {
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001795 if (VerifyOnly) {
1796 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001797 return true; // No typo correction when just trying this out.
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001798 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001799
Douglas Gregord5846a12009-04-15 06:41:24 +00001800 // There was no normal field in the struct with the designated
1801 // name. Perform another lookup for this name, which may find
1802 // something that we can't designate (e.g., a member function),
1803 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001804 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001805 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Craig Topperc3ec1492014-05-26 06:22:03 +00001806 FieldDecl *ReplacementField = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00001807 if (Lookup.empty()) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001808 // Name lookup didn't find anything. Determine whether this
1809 // was a typo for another field name.
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001810 FieldInitializerValidatorCCC Validator(RT->getDecl());
Richard Smithf9b15102013-08-17 00:46:16 +00001811 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
1812 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Craig Topperc3ec1492014-05-26 06:22:03 +00001813 Sema::LookupMemberName, /*Scope=*/ nullptr, /*SS=*/ nullptr,
1814 Validator, Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00001815 SemaRef.diagnoseTypo(
1816 Corrected,
1817 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
1818 << FieldName << CurrentObjectType);
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001819 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001820 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001821 } else {
1822 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1823 << FieldName << CurrentObjectType;
1824 ++Index;
1825 return true;
1826 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001827 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001828
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001829 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001830 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001831 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001832 << FieldName;
David Blaikieff7d47a2012-12-19 00:45:41 +00001833 SemaRef.Diag(Lookup.front()->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001834 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001835 ++Index;
1836 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001837 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001838
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001839 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001840 // The replacement field comes from typo correction; find it
1841 // in the list of fields.
1842 FieldIndex = 0;
1843 Field = RT->getDecl()->field_begin();
1844 for (; Field != FieldEnd; ++Field) {
1845 if (Field->isUnnamedBitfield())
1846 continue;
1847
David Blaikie40ed2972012-06-06 20:45:41 +00001848 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001849 Field->getIdentifier() == ReplacementField->getIdentifier())
1850 break;
1851
1852 ++FieldIndex;
1853 }
1854 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001855 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001856
1857 // All of the fields of a union are located at the same place in
1858 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001859 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001860 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00001861 if (!VerifyOnly) {
1862 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
1863 if (CurrentField && CurrentField != *Field) {
1864 assert(StructuredList->getNumInits() == 1
1865 && "A union should never have more than one initializer!");
1866
1867 // we're about to throw away an initializer, emit warning
1868 SemaRef.Diag(D->getFieldLoc(),
1869 diag::warn_initializer_overrides)
1870 << D->getSourceRange();
1871 Expr *ExistingInit = StructuredList->getInit(0);
1872 SemaRef.Diag(ExistingInit->getLocStart(),
1873 diag::note_previous_initializer)
1874 << /*FIXME:has side effects=*/0
1875 << ExistingInit->getSourceRange();
1876
1877 // remove existing initializer
1878 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00001879 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00001880 }
1881
David Blaikie40ed2972012-06-06 20:45:41 +00001882 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00001883 }
Douglas Gregor51695702009-01-29 16:53:55 +00001884 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001885
Douglas Gregora82064c2011-06-29 21:51:31 +00001886 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001887 bool InvalidUse;
1888 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00001889 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001890 else
David Blaikie40ed2972012-06-06 20:45:41 +00001891 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001892 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001893 ++Index;
1894 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001895 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001896
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001897 if (!VerifyOnly) {
1898 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00001899 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001900
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001901 // Make sure that our non-designated initializer list has space
1902 // for a subobject corresponding to this field.
1903 if (FieldIndex >= StructuredList->getNumInits())
1904 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1905 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001906
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001907 // This designator names a flexible array member.
1908 if (Field->getType()->isIncompleteArrayType()) {
1909 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001910 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001911 // We can't designate an object within the flexible array
1912 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001913 if (!VerifyOnly) {
1914 DesignatedInitExpr::Designator *NextD
1915 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001916 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001917 diag::err_designator_into_flexible_array_member)
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001918 << SourceRange(NextD->getLocStart(),
1919 DIE->getLocEnd());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001920 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00001921 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001922 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001923 Invalid = true;
1924 }
1925
Chris Lattner001b29c2010-10-10 17:49:49 +00001926 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1927 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001928 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001929 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001930 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001931 diag::err_flexible_array_init_needs_braces)
1932 << DIE->getInit()->getSourceRange();
1933 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00001934 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001935 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001936 Invalid = true;
1937 }
1938
Eli Friedman3fa64df2011-08-23 22:24:57 +00001939 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00001940 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00001941 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001942 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001943
1944 if (Invalid) {
1945 ++Index;
1946 return true;
1947 }
1948
1949 // Initialize the array.
1950 bool prevHadError = hadError;
1951 unsigned newStructuredIndex = FieldIndex;
1952 unsigned OldIndex = Index;
1953 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001954
1955 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001956 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001957 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001958 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001959
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001960 IList->setInit(OldIndex, DIE);
1961 if (hadError && !prevHadError) {
1962 ++Field;
1963 ++FieldIndex;
1964 if (NextField)
1965 *NextField = Field;
1966 StructuredIndex = FieldIndex;
1967 return true;
1968 }
1969 } else {
1970 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00001971 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001972 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001973
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001974 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001975 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001976 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00001977 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001978 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001979 true, false))
1980 return true;
1981 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001982
1983 // Find the position of the next field to be initialized in this
1984 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001985 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001986 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001987
1988 // If this the first designator, our caller will continue checking
1989 // the rest of this struct/class/union subobject.
1990 if (IsFirstDesignator) {
1991 if (NextField)
1992 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001993 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001994 return false;
1995 }
1996
Douglas Gregor17bd0942009-01-28 23:36:17 +00001997 if (!FinishSubobjectInit)
1998 return false;
1999
Douglas Gregord5846a12009-04-15 06:41:24 +00002000 // We've already initialized something in the union; we're done.
2001 if (RT->getDecl()->isUnion())
2002 return hadError;
2003
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002004 // Check the remaining fields within this class/struct/union subobject.
2005 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002006
Anders Carlsson6cabf312010-01-23 23:23:01 +00002007 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002008 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002009 return hadError && !prevHadError;
2010 }
2011
2012 // C99 6.7.8p6:
2013 //
2014 // If a designator has the form
2015 //
2016 // [ constant-expression ]
2017 //
2018 // then the current object (defined below) shall have array
2019 // type and the expression shall be an integer constant
2020 // expression. If the array is of unknown size, any
2021 // nonnegative value is valid.
2022 //
2023 // Additionally, cope with the GNU extension that permits
2024 // designators of the form
2025 //
2026 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002027 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002028 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002029 if (!VerifyOnly)
2030 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2031 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002032 ++Index;
2033 return true;
2034 }
2035
Craig Topperc3ec1492014-05-26 06:22:03 +00002036 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002037 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2038 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002039 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002040 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002041 DesignatedEndIndex = DesignatedStartIndex;
2042 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002043 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002044
Mike Stump11289f42009-09-09 15:08:12 +00002045 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002046 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002047 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002048 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002049 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002050
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002051 // Codegen can't handle evaluating array range designators that have side
2052 // effects, because we replicate the AST value for each initialized element.
2053 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2054 // elements with something that has a side effect, so codegen can emit an
2055 // "error unsupported" error instead of miscompiling the app.
2056 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002057 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002058 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002059 }
2060
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002061 if (isa<ConstantArrayType>(AT)) {
2062 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002063 DesignatedStartIndex
2064 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002065 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002066 DesignatedEndIndex
2067 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002068 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2069 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002070 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002071 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002072 diag::err_array_designator_too_large)
2073 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2074 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002075 ++Index;
2076 return true;
2077 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002078 } else {
2079 // Make sure the bit-widths and signedness match.
2080 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002081 DesignatedEndIndex
2082 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002083 else if (DesignatedStartIndex.getBitWidth() <
2084 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002085 DesignatedStartIndex
2086 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002087 DesignatedStartIndex.setIsUnsigned(true);
2088 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002089 }
Mike Stump11289f42009-09-09 15:08:12 +00002090
Eli Friedman1f16b742013-06-11 21:48:11 +00002091 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2092 // We're modifying a string literal init; we have to decompose the string
2093 // so we can modify the individual characters.
2094 ASTContext &Context = SemaRef.Context;
2095 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2096
2097 // Compute the character type
2098 QualType CharTy = AT->getElementType();
2099
2100 // Compute the type of the integer literals.
2101 QualType PromotedCharTy = CharTy;
2102 if (CharTy->isPromotableIntegerType())
2103 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2104 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2105
2106 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2107 // Get the length of the string.
2108 uint64_t StrLen = SL->getLength();
2109 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2110 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2111 StructuredList->resizeInits(Context, StrLen);
2112
2113 // Build a literal for each character in the string, and put them into
2114 // the init list.
2115 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2116 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2117 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002118 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002119 if (CharTy != PromotedCharTy)
2120 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002121 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002122 StructuredList->updateInit(Context, i, Init);
2123 }
2124 } else {
2125 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2126 std::string Str;
2127 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2128
2129 // Get the length of the string.
2130 uint64_t StrLen = Str.size();
2131 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2132 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2133 StructuredList->resizeInits(Context, StrLen);
2134
2135 // Build a literal for each character in the string, and put them into
2136 // the init list.
2137 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2138 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2139 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002140 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002141 if (CharTy != PromotedCharTy)
2142 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002143 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002144 StructuredList->updateInit(Context, i, Init);
2145 }
2146 }
2147 }
2148
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002149 // Make sure that our non-designated initializer list has space
2150 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002151 if (!VerifyOnly &&
2152 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002153 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002154 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002155
Douglas Gregor17bd0942009-01-28 23:36:17 +00002156 // Repeatedly perform subobject initializations in the range
2157 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002158
Douglas Gregor17bd0942009-01-28 23:36:17 +00002159 // Move to the next designator
2160 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2161 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002162
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002163 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002164 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002165
Douglas Gregor17bd0942009-01-28 23:36:17 +00002166 while (DesignatedStartIndex <= DesignatedEndIndex) {
2167 // Recurse to check later designated subobjects.
2168 QualType ElementType = AT->getElementType();
2169 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002170
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002171 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002172 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002173 ElementType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002174 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002175 (DesignatedStartIndex == DesignatedEndIndex),
2176 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002177 return true;
2178
2179 // Move to the next index in the array that we'll be initializing.
2180 ++DesignatedStartIndex;
2181 ElementIndex = DesignatedStartIndex.getZExtValue();
2182 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002183
2184 // If this the first designator, our caller will continue checking
2185 // the rest of this array subobject.
2186 if (IsFirstDesignator) {
2187 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002188 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002189 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002190 return false;
2191 }
Mike Stump11289f42009-09-09 15:08:12 +00002192
Douglas Gregor17bd0942009-01-28 23:36:17 +00002193 if (!FinishSubobjectInit)
2194 return false;
2195
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002196 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002197 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002198 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002199 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002200 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002201 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002202}
2203
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002204// Get the structured initializer list for a subobject of type
2205// @p CurrentObjectType.
2206InitListExpr *
2207InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2208 QualType CurrentObjectType,
2209 InitListExpr *StructuredList,
2210 unsigned StructuredIndex,
2211 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002212 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002213 return nullptr; // No structured list in verification-only mode.
2214 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002215 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002216 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002217 else if (StructuredIndex < StructuredList->getNumInits())
2218 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002219
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002220 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2221 return Result;
2222
2223 if (ExistingInit) {
2224 // We are creating an initializer list that initializes the
2225 // subobjects of the current object, but there was already an
2226 // initialization that completely initialized the current
2227 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002228 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002229 // struct X { int a, b; };
2230 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002231 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002232 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2233 // designated initializer re-initializes the whole
2234 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002235 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002236 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002237 << InitRange;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002238 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002239 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002240 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002241 << ExistingInit->getSourceRange();
2242 }
2243
Mike Stump11289f42009-09-09 15:08:12 +00002244 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002245 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002246 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002247 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002248
Eli Friedman91f5ae52012-02-23 02:25:10 +00002249 QualType ResultType = CurrentObjectType;
2250 if (!ResultType->isArrayType())
2251 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2252 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002253
Douglas Gregor6d00c992009-03-20 23:58:33 +00002254 // Pre-allocate storage for the structured initializer list.
2255 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002256 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002257 bool GotNumInits = false;
2258 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002259 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002260 GotNumInits = true;
2261 } else if (Index < IList->getNumInits()) {
2262 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002263 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002264 GotNumInits = true;
2265 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002266 }
2267
Mike Stump11289f42009-09-09 15:08:12 +00002268 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002269 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2270 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2271 NumElements = CAType->getSize().getZExtValue();
2272 // Simple heuristic so that we don't allocate a very large
2273 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002274 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002275 NumElements = 0;
2276 }
John McCall9dd450b2009-09-21 23:43:11 +00002277 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002278 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002279 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002280 RecordDecl *RDecl = RType->getDecl();
2281 if (RDecl->isUnion())
2282 NumElements = 1;
2283 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002284 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002285 }
2286
Ted Kremenekac034612010-04-13 23:39:13 +00002287 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002288
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002289 // Link this new initializer list into the structured initializer
2290 // lists.
2291 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002292 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002293 else {
2294 Result->setSyntacticForm(IList);
2295 SyntacticToSemantic[IList] = Result;
2296 }
2297
2298 return Result;
2299}
2300
2301/// Update the initializer at index @p StructuredIndex within the
2302/// structured initializer list to the value @p expr.
2303void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2304 unsigned &StructuredIndex,
2305 Expr *expr) {
2306 // No structured initializer list to update
2307 if (!StructuredList)
2308 return;
2309
Ted Kremenekac034612010-04-13 23:39:13 +00002310 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2311 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002312 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002313 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002314 diag::warn_initializer_overrides)
2315 << expr->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002316 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002317 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002318 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002319 << PrevInit->getSourceRange();
2320 }
Mike Stump11289f42009-09-09 15:08:12 +00002321
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002322 ++StructuredIndex;
2323}
2324
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002325/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002326/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002327/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002328/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002329/// failure. Returns the index expression, possibly with an implicit cast
2330/// added, on success. If everything went okay, Value will receive the
2331/// value of the constant expression.
2332static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002333CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002334 SourceLocation Loc = Index->getLocStart();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002335
2336 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002337 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2338 if (Result.isInvalid())
2339 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002340
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002341 if (Value.isSigned() && Value.isNegative())
2342 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002343 << Value.toString(10) << Index->getSourceRange();
2344
Douglas Gregor51650d32009-01-23 21:04:18 +00002345 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002346 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002347}
2348
John McCalldadc5752010-08-24 06:29:42 +00002349ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002350 SourceLocation Loc,
2351 bool GNUSyntax,
2352 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002353 typedef DesignatedInitExpr::Designator ASTDesignator;
2354
2355 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002356 SmallVector<ASTDesignator, 32> Designators;
2357 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002358
2359 // Build designators and check array designator expressions.
2360 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2361 const Designator &D = Desig.getDesignator(Idx);
2362 switch (D.getKind()) {
2363 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002364 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002365 D.getFieldLoc()));
2366 break;
2367
2368 case Designator::ArrayDesignator: {
2369 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2370 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002371 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002372 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002373 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002374 Invalid = true;
2375 else {
2376 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002377 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002378 D.getRBracketLoc()));
2379 InitExpressions.push_back(Index);
2380 }
2381 break;
2382 }
2383
2384 case Designator::ArrayRangeDesignator: {
2385 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2386 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2387 llvm::APSInt StartValue;
2388 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002389 bool StartDependent = StartIndex->isTypeDependent() ||
2390 StartIndex->isValueDependent();
2391 bool EndDependent = EndIndex->isTypeDependent() ||
2392 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002393 if (!StartDependent)
2394 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002395 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002396 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002397 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002398
2399 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002400 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002401 else {
2402 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002403 if (StartDependent || EndDependent) {
2404 // Nothing to compute.
2405 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002406 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002407 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002408 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002409
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002410 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002411 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002412 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002413 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2414 Invalid = true;
2415 } else {
2416 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002417 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002418 D.getEllipsisLoc(),
2419 D.getRBracketLoc()));
2420 InitExpressions.push_back(StartIndex);
2421 InitExpressions.push_back(EndIndex);
2422 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002423 }
2424 break;
2425 }
2426 }
2427 }
2428
2429 if (Invalid || Init.isInvalid())
2430 return ExprError();
2431
2432 // Clear out the expressions within the designation.
2433 Desig.ClearExprs(*this);
2434
2435 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002436 = DesignatedInitExpr::Create(Context,
2437 Designators.data(), Designators.size(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00002438 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002439 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002440
David Blaikiebbafb8a2012-03-11 07:00:24 +00002441 if (!getLangOpts().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002442 Diag(DIE->getLocStart(), diag::ext_designated_init)
2443 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002444
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002445 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002446}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002447
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002448//===----------------------------------------------------------------------===//
2449// Initialization entity
2450//===----------------------------------------------------------------------===//
2451
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002452InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002453 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002454 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002455{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002456 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2457 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002458 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002459 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002460 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002461 Type = VT->getElementType();
2462 } else {
2463 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2464 assert(CT && "Unexpected type");
2465 Kind = EK_ComplexElement;
2466 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002467 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002468}
2469
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002470InitializedEntity
2471InitializedEntity::InitializeBase(ASTContext &Context,
2472 const CXXBaseSpecifier *Base,
2473 bool IsInheritedVirtualBase) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002474 InitializedEntity Result;
2475 Result.Kind = EK_Base;
Craig Topperc3ec1492014-05-26 06:22:03 +00002476 Result.Parent = nullptr;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002477 Result.Base = reinterpret_cast<uintptr_t>(Base);
2478 if (IsInheritedVirtualBase)
2479 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002480
Douglas Gregor1b303932009-12-22 15:35:07 +00002481 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002482 return Result;
2483}
2484
Douglas Gregor85dabae2009-12-16 01:38:02 +00002485DeclarationName InitializedEntity::getName() const {
2486 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002487 case EK_Parameter:
2488 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00002489 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2490 return (D ? D->getDeclName() : DeclarationName());
2491 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002492
2493 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002494 case EK_Member:
2495 return VariableOrMember->getDeclName();
2496
Douglas Gregor19666fb2012-02-15 16:57:26 +00002497 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002498 return DeclarationName(Capture.VarID);
Douglas Gregor19666fb2012-02-15 16:57:26 +00002499
Douglas Gregor85dabae2009-12-16 01:38:02 +00002500 case EK_Result:
2501 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002502 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002503 case EK_Temporary:
2504 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002505 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002506 case EK_ArrayElement:
2507 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002508 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002509 case EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002510 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002511 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002512 return DeclarationName();
2513 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002514
David Blaikie8a40f702012-01-17 06:56:22 +00002515 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002516}
2517
Douglas Gregora4b592a2009-12-19 03:01:41 +00002518DeclaratorDecl *InitializedEntity::getDecl() const {
2519 switch (getKind()) {
2520 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002521 case EK_Member:
2522 return VariableOrMember;
2523
John McCall31168b02011-06-15 23:02:42 +00002524 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002525 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00002526 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2527
Douglas Gregora4b592a2009-12-19 03:01:41 +00002528 case EK_Result:
2529 case EK_Exception:
2530 case EK_New:
2531 case EK_Temporary:
2532 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002533 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002534 case EK_ArrayElement:
2535 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002536 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002537 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002538 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002539 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002540 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00002541 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00002542 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002543
David Blaikie8a40f702012-01-17 06:56:22 +00002544 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002545}
2546
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002547bool InitializedEntity::allowsNRVO() const {
2548 switch (getKind()) {
2549 case EK_Result:
2550 case EK_Exception:
2551 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002552
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002553 case EK_Variable:
2554 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002555 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002556 case EK_Member:
2557 case EK_New:
2558 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002559 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002560 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002561 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002562 case EK_ArrayElement:
2563 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002564 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002565 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002566 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002567 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002568 break;
2569 }
2570
2571 return false;
2572}
2573
Richard Smithe6c01442013-06-05 00:46:14 +00002574unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00002575 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00002576 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2577 for (unsigned I = 0; I != Depth; ++I)
2578 OS << "`-";
2579
2580 switch (getKind()) {
2581 case EK_Variable: OS << "Variable"; break;
2582 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002583 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2584 break;
Richard Smithe6c01442013-06-05 00:46:14 +00002585 case EK_Result: OS << "Result"; break;
2586 case EK_Exception: OS << "Exception"; break;
2587 case EK_Member: OS << "Member"; break;
2588 case EK_New: OS << "New"; break;
2589 case EK_Temporary: OS << "Temporary"; break;
2590 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002591 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00002592 case EK_Base: OS << "Base"; break;
2593 case EK_Delegating: OS << "Delegating"; break;
2594 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2595 case EK_VectorElement: OS << "VectorElement " << Index; break;
2596 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2597 case EK_BlockElement: OS << "Block"; break;
2598 case EK_LambdaCapture:
2599 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002600 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00002601 break;
2602 }
2603
2604 if (Decl *D = getDecl()) {
2605 OS << " ";
2606 cast<NamedDecl>(D)->printQualifiedName(OS);
2607 }
2608
2609 OS << " '" << getType().getAsString() << "'\n";
2610
2611 return Depth + 1;
2612}
2613
2614void InitializedEntity::dump() const {
2615 dumpImpl(llvm::errs());
2616}
2617
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002618//===----------------------------------------------------------------------===//
2619// Initialization sequence
2620//===----------------------------------------------------------------------===//
2621
2622void InitializationSequence::Step::Destroy() {
2623 switch (Kind) {
2624 case SK_ResolveAddressOfOverloadedFunction:
2625 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002626 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002627 case SK_CastDerivedToBaseLValue:
2628 case SK_BindReference:
2629 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002630 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002631 case SK_UserConversion:
2632 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002633 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002634 case SK_QualificationConversionLValue:
Jordan Roseb1312a52013-04-11 00:58:58 +00002635 case SK_LValueToRValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002636 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002637 case SK_ListConstructorCall:
Sebastian Redl29526f02011-11-27 16:50:07 +00002638 case SK_UnwrapInitList:
2639 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002640 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002641 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002642 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002643 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002644 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002645 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00002646 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002647 case SK_PassByIndirectCopyRestore:
2648 case SK_PassByIndirectRestore:
2649 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002650 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00002651 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002652 case SK_OCLZeroEvent:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002653 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002654
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002655 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00002656 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002657 delete ICS;
2658 }
2659}
2660
Douglas Gregor838fcc32010-03-26 20:14:36 +00002661bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002662 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002663}
2664
2665bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002666 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002667 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002668
Douglas Gregor838fcc32010-03-26 20:14:36 +00002669 switch (getFailureKind()) {
2670 case FK_TooManyInitsForReference:
2671 case FK_ArrayNeedsInitList:
2672 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00002673 case FK_ArrayNeedsInitListOrWideStringLiteral:
2674 case FK_NarrowStringIntoWideCharArray:
2675 case FK_WideStringIntoCharArray:
2676 case FK_IncompatWideStringIntoWideChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002677 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2678 case FK_NonConstLValueReferenceBindingToTemporary:
2679 case FK_NonConstLValueReferenceBindingToUnrelated:
2680 case FK_RValueReferenceBindingToLValue:
2681 case FK_ReferenceInitDropsQualifiers:
2682 case FK_ReferenceInitFailed:
2683 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002684 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002685 case FK_TooManyInitsForScalar:
2686 case FK_ReferenceBindingToInitList:
2687 case FK_InitListBadDestinationType:
2688 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002689 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002690 case FK_ArrayTypeMismatch:
2691 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002692 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002693 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002694 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00002695 case FK_ExplicitConstructor:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002696 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002697
Douglas Gregor838fcc32010-03-26 20:14:36 +00002698 case FK_ReferenceInitOverloadFailed:
2699 case FK_UserConversionOverloadFailed:
2700 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002701 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002702 return FailedOverloadResult == OR_Ambiguous;
2703 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002704
David Blaikie8a40f702012-01-17 06:56:22 +00002705 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00002706}
2707
Douglas Gregorb33eed02010-04-16 22:09:46 +00002708bool InitializationSequence::isConstructorInitialization() const {
2709 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2710}
2711
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002712void
2713InitializationSequence
2714::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2715 DeclAccessPair Found,
2716 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002717 Step S;
2718 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2719 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002720 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002721 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002722 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002723 Steps.push_back(S);
2724}
2725
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002726void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002727 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002728 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002729 switch (VK) {
2730 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2731 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2732 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002733 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002734 S.Type = BaseType;
2735 Steps.push_back(S);
2736}
2737
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002738void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002739 bool BindingTemporary) {
2740 Step S;
2741 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2742 S.Type = T;
2743 Steps.push_back(S);
2744}
2745
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002746void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2747 Step S;
2748 S.Kind = SK_ExtraneousCopyToTemporary;
2749 S.Type = T;
2750 Steps.push_back(S);
2751}
2752
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002753void
2754InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2755 DeclAccessPair FoundDecl,
2756 QualType T,
2757 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002758 Step S;
2759 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002760 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002761 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002762 S.Function.Function = Function;
2763 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002764 Steps.push_back(S);
2765}
2766
2767void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002768 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002769 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002770 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002771 switch (VK) {
2772 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002773 S.Kind = SK_QualificationConversionRValue;
2774 break;
John McCall2536c6d2010-08-25 10:28:54 +00002775 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002776 S.Kind = SK_QualificationConversionXValue;
2777 break;
John McCall2536c6d2010-08-25 10:28:54 +00002778 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002779 S.Kind = SK_QualificationConversionLValue;
2780 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002781 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002782 S.Type = Ty;
2783 Steps.push_back(S);
2784}
2785
Jordan Roseb1312a52013-04-11 00:58:58 +00002786void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2787 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2788
2789 Step S;
2790 S.Kind = SK_LValueToRValue;
2791 S.Type = Ty;
2792 Steps.push_back(S);
2793}
2794
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002795void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00002796 const ImplicitConversionSequence &ICS, QualType T,
2797 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002798 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00002799 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
2800 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002801 S.Type = T;
2802 S.ICS = new ImplicitConversionSequence(ICS);
2803 Steps.push_back(S);
2804}
2805
Douglas Gregor51e77d52009-12-10 17:56:55 +00002806void InitializationSequence::AddListInitializationStep(QualType T) {
2807 Step S;
2808 S.Kind = SK_ListInitialization;
2809 S.Type = T;
2810 Steps.push_back(S);
2811}
2812
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002813void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002814InitializationSequence
2815::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2816 AccessSpecifier Access,
2817 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002818 bool HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002819 bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002820 Step S;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002821 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2822 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002823 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002824 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002825 S.Function.Function = Constructor;
2826 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002827 Steps.push_back(S);
2828}
2829
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002830void InitializationSequence::AddZeroInitializationStep(QualType T) {
2831 Step S;
2832 S.Kind = SK_ZeroInitialization;
2833 S.Type = T;
2834 Steps.push_back(S);
2835}
2836
Douglas Gregore1314a62009-12-18 05:02:21 +00002837void InitializationSequence::AddCAssignmentStep(QualType T) {
2838 Step S;
2839 S.Kind = SK_CAssignment;
2840 S.Type = T;
2841 Steps.push_back(S);
2842}
2843
Eli Friedman78275202009-12-19 08:11:05 +00002844void InitializationSequence::AddStringInitStep(QualType T) {
2845 Step S;
2846 S.Kind = SK_StringInit;
2847 S.Type = T;
2848 Steps.push_back(S);
2849}
2850
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002851void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2852 Step S;
2853 S.Kind = SK_ObjCObjectConversion;
2854 S.Type = T;
2855 Steps.push_back(S);
2856}
2857
Douglas Gregore2f943b2011-02-22 18:29:51 +00002858void InitializationSequence::AddArrayInitStep(QualType T) {
2859 Step S;
2860 S.Kind = SK_ArrayInit;
2861 S.Type = T;
2862 Steps.push_back(S);
2863}
2864
Richard Smithebeed412012-02-15 22:38:09 +00002865void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2866 Step S;
2867 S.Kind = SK_ParenthesizedArrayInit;
2868 S.Type = T;
2869 Steps.push_back(S);
2870}
2871
John McCall31168b02011-06-15 23:02:42 +00002872void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2873 bool shouldCopy) {
2874 Step s;
2875 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2876 : SK_PassByIndirectRestore);
2877 s.Type = type;
2878 Steps.push_back(s);
2879}
2880
2881void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2882 Step S;
2883 S.Kind = SK_ProduceObjCObject;
2884 S.Type = T;
2885 Steps.push_back(S);
2886}
2887
Sebastian Redlc1839b12012-01-17 22:49:42 +00002888void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2889 Step S;
2890 S.Kind = SK_StdInitializerList;
2891 S.Type = T;
2892 Steps.push_back(S);
2893}
2894
Guy Benyei61054192013-02-07 10:55:47 +00002895void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
2896 Step S;
2897 S.Kind = SK_OCLSamplerInit;
2898 S.Type = T;
2899 Steps.push_back(S);
2900}
2901
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002902void InitializationSequence::AddOCLZeroEventStep(QualType T) {
2903 Step S;
2904 S.Kind = SK_OCLZeroEvent;
2905 S.Type = T;
2906 Steps.push_back(S);
2907}
2908
Sebastian Redl29526f02011-11-27 16:50:07 +00002909void InitializationSequence::RewrapReferenceInitList(QualType T,
2910 InitListExpr *Syntactic) {
2911 assert(Syntactic->getNumInits() == 1 &&
2912 "Can only rewrap trivial init lists.");
2913 Step S;
2914 S.Kind = SK_UnwrapInitList;
2915 S.Type = Syntactic->getInit(0)->getType();
2916 Steps.insert(Steps.begin(), S);
2917
2918 S.Kind = SK_RewrapInitList;
2919 S.Type = T;
2920 S.WrappingSyntacticList = Syntactic;
2921 Steps.push_back(S);
2922}
2923
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002924void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002925 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002926 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002927 this->Failure = Failure;
2928 this->FailedOverloadResult = Result;
2929}
2930
2931//===----------------------------------------------------------------------===//
2932// Attempt initialization
2933//===----------------------------------------------------------------------===//
2934
John McCall31168b02011-06-15 23:02:42 +00002935static void MaybeProduceObjCObject(Sema &S,
2936 InitializationSequence &Sequence,
2937 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002938 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00002939
2940 /// When initializing a parameter, produce the value if it's marked
2941 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002942 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00002943 if (!Entity.isParameterConsumed())
2944 return;
2945
2946 assert(Entity.getType()->isObjCRetainableType() &&
2947 "consuming an object of unretainable type?");
2948 Sequence.AddProduceObjCObjectStep(Entity.getType());
2949
2950 /// When initializing a return value, if the return type is a
2951 /// retainable type, then returns need to immediately retain the
2952 /// object. If an autorelease is required, it will be done at the
2953 /// last instant.
2954 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2955 if (!Entity.getType()->isObjCRetainableType())
2956 return;
2957
2958 Sequence.AddProduceObjCObjectStep(Entity.getType());
2959 }
2960}
2961
Richard Smithcc1b96d2013-06-12 22:31:48 +00002962static void TryListInitialization(Sema &S,
2963 const InitializedEntity &Entity,
2964 const InitializationKind &Kind,
2965 InitListExpr *InitList,
2966 InitializationSequence &Sequence);
2967
Richard Smithd86812d2012-07-05 08:39:21 +00002968/// \brief When initializing from init list via constructor, handle
2969/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00002970///
Richard Smithd86812d2012-07-05 08:39:21 +00002971/// \return true if we have handled initialization of an object of type
2972/// std::initializer_list<T>, false otherwise.
2973static bool TryInitializerListConstruction(Sema &S,
2974 InitListExpr *List,
2975 QualType DestType,
2976 InitializationSequence &Sequence) {
2977 QualType E;
2978 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00002979 return false;
2980
Richard Smithcc1b96d2013-06-12 22:31:48 +00002981 if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
2982 Sequence.setIncompleteTypeFailure(E);
2983 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00002984 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00002985
2986 // Try initializing a temporary array from the init list.
2987 QualType ArrayType = S.Context.getConstantArrayType(
2988 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2989 List->getNumInits()),
2990 clang::ArrayType::Normal, 0);
2991 InitializedEntity HiddenArray =
2992 InitializedEntity::InitializeTemporary(ArrayType);
2993 InitializationKind Kind =
2994 InitializationKind::CreateDirectList(List->getExprLoc());
2995 TryListInitialization(S, HiddenArray, Kind, List, Sequence);
2996 if (Sequence)
2997 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00002998 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00002999}
3000
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003001static OverloadingResult
3002ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003003 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003004 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003005 ArrayRef<NamedDecl *> Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003006 OverloadCandidateSet::iterator &Best,
3007 bool CopyInitializing, bool AllowExplicit,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003008 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003009 CandidateSet.clear();
3010
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003011 for (ArrayRef<NamedDecl *>::iterator
3012 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003013 NamedDecl *D = *Con;
3014 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3015 bool SuppressUserConversions = false;
3016
3017 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003018 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003019 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3020 if (ConstructorTmpl)
3021 Constructor = cast<CXXConstructorDecl>(
3022 ConstructorTmpl->getTemplatedDecl());
3023 else {
3024 Constructor = cast<CXXConstructorDecl>(D);
3025
Richard Smith6c6ddab2013-09-21 21:23:47 +00003026 // C++11 [over.best.ics]p4:
3027 // However, when considering the argument of a constructor or
3028 // user-defined conversion function that is a candidate:
3029 // -- by 13.3.1.3 when invoked for the copying/moving of a temporary
3030 // in the second step of a class copy-initialization,
3031 // -- by 13.3.1.7 when passing the initializer list as a single
3032 // argument or when the initializer list has exactly one elementand
3033 // a conversion to some class X or reference to (possibly
3034 // cv-qualified) X is considered for the first parameter of a
3035 // constructor of X, or
3036 // -- by 13.3.1.4, 13.3.1.5, or 13.3.1.6 in all cases,
3037 // only standard conversion sequences and ellipsis conversion sequences
3038 // are considered.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003039 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003040 Constructor->isCopyOrMoveConstructor())
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003041 SuppressUserConversions = true;
3042 }
3043
3044 if (!Constructor->isInvalidDecl() &&
3045 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003046 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003047 if (ConstructorTmpl)
3048 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003049 /*ExplicitArgs*/ nullptr, Args,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003050 CandidateSet, SuppressUserConversions);
Douglas Gregor6073dca2012-02-24 23:56:31 +00003051 else {
3052 // C++ [over.match.copy]p1:
3053 // - When initializing a temporary to be bound to the first parameter
3054 // of a constructor that takes a reference to possibly cv-qualified
3055 // T as its first argument, called with a single argument in the
3056 // context of direct-initialization, explicit conversion functions
3057 // are also considered.
3058 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003059 Args.size() == 1 &&
Douglas Gregor6073dca2012-02-24 23:56:31 +00003060 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003061 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003062 SuppressUserConversions,
3063 /*PartialOverloading=*/false,
3064 /*AllowExplicit=*/AllowExplicitConv);
3065 }
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003066 }
3067 }
3068
3069 // Perform overload resolution and return the result.
3070 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3071}
3072
Sebastian Redled2e5322011-12-22 14:44:04 +00003073/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3074/// enumerates the constructors of the initialized entity and performs overload
3075/// resolution to select the best.
Sebastian Redl88e4d492012-02-04 21:27:33 +00003076/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redled2e5322011-12-22 14:44:04 +00003077/// class type.
3078static void TryConstructorInitialization(Sema &S,
3079 const InitializedEntity &Entity,
3080 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003081 MultiExprArg Args, QualType DestType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003082 InitializationSequence &Sequence,
Sebastian Redl88e4d492012-02-04 21:27:33 +00003083 bool InitListSyntax = false) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003084 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Sebastian Redl88e4d492012-02-04 21:27:33 +00003085 "InitListSyntax must come with a single initializer list argument.");
3086
Sebastian Redled2e5322011-12-22 14:44:04 +00003087 // The type we're constructing needs to be complete.
3088 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003089 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003090 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003091 }
3092
3093 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3094 assert(DestRecordType && "Constructor initialization requires record type");
3095 CXXRecordDecl *DestRecordDecl
3096 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3097
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003098 // Build the candidate set directly in the initialization sequence
3099 // structure, so that it will persist if we fail.
3100 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3101
3102 // Determine whether we are allowed to call explicit constructors or
3103 // explicit conversion operators.
Sebastian Redl048a6d72012-04-01 19:54:59 +00003104 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003105 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003106
Sebastian Redled2e5322011-12-22 14:44:04 +00003107 // - Otherwise, if T is a class type, constructors are considered. The
3108 // applicable constructors are enumerated, and the best one is chosen
3109 // through overload resolution.
David Blaikieff7d47a2012-12-19 00:45:41 +00003110 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003111 // The container holding the constructors can under certain conditions
3112 // be changed while iterating (e.g. because of deserialization).
3113 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003114 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redled2e5322011-12-22 14:44:04 +00003115
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003116 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003117 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003118 bool AsInitializerList = false;
3119
3120 // C++11 [over.match.list]p1:
3121 // When objects of non-aggregate type T are list-initialized, overload
3122 // resolution selects the constructor in two phases:
3123 // - Initially, the candidate functions are the initializer-list
3124 // constructors of the class T and the argument list consists of the
3125 // initializer list as a single argument.
3126 if (InitListSyntax) {
Richard Smithd86812d2012-07-05 08:39:21 +00003127 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003128 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003129
3130 // If the initializer list has no elements and T has a default constructor,
3131 // the first phase is omitted.
Richard Smith2be35f52012-12-01 02:35:44 +00003132 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003133 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003134 CandidateSet, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003135 CopyInitialization, AllowExplicit,
3136 /*OnlyListConstructor=*/true,
3137 InitListSyntax);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003138
3139 // Time to unwrap the init list.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003140 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003141 }
3142
3143 // C++11 [over.match.list]p1:
3144 // - If no viable initializer-list constructor is found, overload resolution
3145 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003146 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003147 // elements of the initializer list.
3148 if (Result == OR_No_Viable_Function) {
3149 AsInitializerList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003150 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003151 CandidateSet, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003152 CopyInitialization, AllowExplicit,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003153 /*OnlyListConstructors=*/false,
3154 InitListSyntax);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003155 }
3156 if (Result) {
Sebastian Redl88e4d492012-02-04 21:27:33 +00003157 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003158 InitializationSequence::FK_ListConstructorOverloadFailed :
3159 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003160 Result);
3161 return;
3162 }
3163
Richard Smithd86812d2012-07-05 08:39:21 +00003164 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003165 // If a program calls for the default initialization of an object
3166 // of a const-qualified type T, T shall be a class type with a
3167 // user-provided default constructor.
3168 if (Kind.getKind() == InitializationKind::IK_Default &&
3169 Entity.getType().isConstQualified() &&
Aaron Ballman899b9c62012-07-31 22:40:31 +00003170 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redled2e5322011-12-22 14:44:04 +00003171 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3172 return;
3173 }
3174
Sebastian Redl048a6d72012-04-01 19:54:59 +00003175 // C++11 [over.match.list]p1:
3176 // In copy-list-initialization, if an explicit constructor is chosen, the
3177 // initializer is ill-formed.
3178 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3179 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3180 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3181 return;
3182 }
3183
Sebastian Redled2e5322011-12-22 14:44:04 +00003184 // Add the constructor initialization step. Any cv-qualification conversion is
3185 // subsumed by the initialization.
3186 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redled2e5322011-12-22 14:44:04 +00003187 Sequence.AddConstructorInitializationStep(CtorDecl,
3188 Best->FoundDecl.getAccess(),
3189 DestType, HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003190 InitListSyntax, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003191}
3192
Sebastian Redl29526f02011-11-27 16:50:07 +00003193static bool
3194ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3195 Expr *Initializer,
3196 QualType &SourceType,
3197 QualType &UnqualifiedSourceType,
3198 QualType UnqualifiedTargetType,
3199 InitializationSequence &Sequence) {
3200 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3201 S.Context.OverloadTy) {
3202 DeclAccessPair Found;
3203 bool HadMultipleCandidates = false;
3204 if (FunctionDecl *Fn
3205 = S.ResolveAddressOfOverloadedFunction(Initializer,
3206 UnqualifiedTargetType,
3207 false, Found,
3208 &HadMultipleCandidates)) {
3209 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3210 HadMultipleCandidates);
3211 SourceType = Fn->getType();
3212 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3213 } else if (!UnqualifiedTargetType->isRecordType()) {
3214 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3215 return true;
3216 }
3217 }
3218 return false;
3219}
3220
3221static void TryReferenceInitializationCore(Sema &S,
3222 const InitializedEntity &Entity,
3223 const InitializationKind &Kind,
3224 Expr *Initializer,
3225 QualType cv1T1, QualType T1,
3226 Qualifiers T1Quals,
3227 QualType cv2T2, QualType T2,
3228 Qualifiers T2Quals,
3229 InitializationSequence &Sequence);
3230
Richard Smithd86812d2012-07-05 08:39:21 +00003231static void TryValueInitialization(Sema &S,
3232 const InitializedEntity &Entity,
3233 const InitializationKind &Kind,
3234 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00003235 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00003236
Sebastian Redl29526f02011-11-27 16:50:07 +00003237/// \brief Attempt list initialization of a reference.
3238static void TryReferenceListInitialization(Sema &S,
3239 const InitializedEntity &Entity,
3240 const InitializationKind &Kind,
3241 InitListExpr *InitList,
Richard Smithfaadef72013-06-08 00:02:08 +00003242 InitializationSequence &Sequence) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003243 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003244 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003245 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3246 return;
3247 }
3248
3249 QualType DestType = Entity.getType();
3250 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3251 Qualifiers T1Quals;
3252 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3253
3254 // Reference initialization via an initializer list works thus:
3255 // If the initializer list consists of a single element that is
3256 // reference-related to the referenced type, bind directly to that element
3257 // (possibly creating temporaries).
3258 // Otherwise, initialize a temporary with the initializer list and
3259 // bind to that.
3260 if (InitList->getNumInits() == 1) {
3261 Expr *Initializer = InitList->getInit(0);
3262 QualType cv2T2 = Initializer->getType();
3263 Qualifiers T2Quals;
3264 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3265
3266 // If this fails, creating a temporary wouldn't work either.
3267 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3268 T1, Sequence))
3269 return;
3270
3271 SourceLocation DeclLoc = Initializer->getLocStart();
3272 bool dummy1, dummy2, dummy3;
3273 Sema::ReferenceCompareResult RefRelationship
3274 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3275 dummy2, dummy3);
3276 if (RefRelationship >= Sema::Ref_Related) {
3277 // Try to bind the reference here.
3278 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3279 T1Quals, cv2T2, T2, T2Quals, Sequence);
3280 if (Sequence)
3281 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3282 return;
3283 }
Richard Smith03d93932013-01-15 07:58:29 +00003284
3285 // Update the initializer if we've resolved an overloaded function.
3286 if (Sequence.step_begin() != Sequence.step_end())
3287 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00003288 }
3289
3290 // Not reference-related. Create a temporary and bind to that.
3291 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3292
3293 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3294 if (Sequence) {
3295 if (DestType->isRValueReferenceType() ||
3296 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3297 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3298 else
3299 Sequence.SetFailed(
3300 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3301 }
3302}
3303
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003304/// \brief Attempt list initialization (C++0x [dcl.init.list])
3305static void TryListInitialization(Sema &S,
3306 const InitializedEntity &Entity,
3307 const InitializationKind &Kind,
3308 InitListExpr *InitList,
3309 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003310 QualType DestType = Entity.getType();
3311
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003312 // C++ doesn't allow scalar initialization with more than one argument.
3313 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003314 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003315 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3316 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3317 return;
3318 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003319 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003320 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003321 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003322 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003323 if (DestType->isRecordType()) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003324 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003325 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl4f28b582012-02-19 12:27:43 +00003326 return;
3327 }
3328
Richard Smithd86812d2012-07-05 08:39:21 +00003329 // C++11 [dcl.init.list]p3:
3330 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redl4f28b582012-02-19 12:27:43 +00003331 if (!DestType->isAggregateType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003332 if (S.getLangOpts().CPlusPlus11) {
Richard Smithd86812d2012-07-05 08:39:21 +00003333 // - Otherwise, if the initializer list has no elements and T is a
3334 // class type with a default constructor, the object is
3335 // value-initialized.
3336 if (InitList->getNumInits() == 0) {
3337 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
Richard Smith2be35f52012-12-01 02:35:44 +00003338 if (RD->hasDefaultConstructor()) {
Richard Smithd86812d2012-07-05 08:39:21 +00003339 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3340 return;
3341 }
3342 }
3343
3344 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3345 // an initializer_list object constructed [...]
3346 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3347 return;
3348
3349 // - Otherwise, if T is a class type, constructors are considered.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003350 Expr *InitListAsExpr = InitList;
3351 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smithd86812d2012-07-05 08:39:21 +00003352 Sequence, /*InitListSyntax*/true);
Sebastian Redl4f28b582012-02-19 12:27:43 +00003353 } else
3354 Sequence.SetFailed(
3355 InitializationSequence::FK_InitListBadDestinationType);
3356 return;
3357 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003358 }
Richard Smith089c3162013-09-21 21:55:46 +00003359 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
3360 InitList->getNumInits() == 1 &&
3361 InitList->getInit(0)->getType()->isRecordType()) {
3362 // - Otherwise, if the initializer list has a single element of type E
3363 // [...references are handled above...], the object or reference is
3364 // initialized from that element; if a narrowing conversion is required
3365 // to convert the element to T, the program is ill-formed.
3366 //
3367 // Per core-24034, this is direct-initialization if we were performing
3368 // direct-list-initialization and copy-initialization otherwise.
3369 // We can't use InitListChecker for this, because it always performs
3370 // copy-initialization. This only matters if we might use an 'explicit'
3371 // conversion operator, so we only need to handle the cases where the source
3372 // is of record type.
3373 InitializationKind SubKind =
3374 Kind.getKind() == InitializationKind::IK_DirectList
3375 ? InitializationKind::CreateDirect(Kind.getLocation(),
3376 InitList->getLBraceLoc(),
3377 InitList->getRBraceLoc())
3378 : Kind;
3379 Expr *SubInit[1] = { InitList->getInit(0) };
3380 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3381 /*TopLevelOfInitList*/true);
3382 if (Sequence)
3383 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3384 return;
3385 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003386
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003387 InitListChecker CheckInitList(S, Entity, InitList,
Richard Smithde229232013-06-06 11:41:05 +00003388 DestType, /*VerifyOnly=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003389 if (CheckInitList.HadError()) {
3390 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3391 return;
3392 }
3393
3394 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003395 Sequence.AddListInitializationStep(DestType);
3396}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003397
3398/// \brief Try a reference initialization that involves calling a conversion
3399/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003400static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3401 const InitializedEntity &Entity,
3402 const InitializationKind &Kind,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003403 Expr *Initializer,
3404 bool AllowRValues,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003405 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003406 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003407 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3408 QualType T1 = cv1T1.getUnqualifiedType();
3409 QualType cv2T2 = Initializer->getType();
3410 QualType T2 = cv2T2.getUnqualifiedType();
3411
3412 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003413 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003414 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003415 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003416 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003417 ObjCConversion,
3418 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003419 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003420 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003421 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003422 (void)ObjCLifetimeConversion;
3423
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003424 // Build the candidate set directly in the initialization sequence
3425 // structure, so that it will persist if we fail.
3426 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3427 CandidateSet.clear();
3428
3429 // Determine whether we are allowed to call explicit constructors or
3430 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003431 bool AllowExplicit = Kind.AllowExplicit();
Richard Smith6c6ddab2013-09-21 21:23:47 +00003432 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3433
Craig Topperc3ec1492014-05-26 06:22:03 +00003434 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003435 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3436 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003437 // The type we're converting to is a class type. Enumerate its constructors
3438 // to see if there is a suitable conversion.
3439 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003440
David Blaikieff7d47a2012-12-19 00:45:41 +00003441 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003442 // The container holding the constructors can under certain conditions
3443 // be changed while iterating (e.g. because of deserialization).
3444 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003445 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00003446 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003447 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3448 NamedDecl *D = *CI;
John McCalla0296f72010-03-19 07:35:19 +00003449 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3450
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003451 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003452 CXXConstructorDecl *Constructor = nullptr;
John McCalla0296f72010-03-19 07:35:19 +00003453 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003454 if (ConstructorTmpl)
3455 Constructor = cast<CXXConstructorDecl>(
3456 ConstructorTmpl->getTemplatedDecl());
3457 else
John McCalla0296f72010-03-19 07:35:19 +00003458 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003459
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003460 if (!Constructor->isInvalidDecl() &&
3461 Constructor->isConvertingConstructor(AllowExplicit)) {
3462 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003463 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003464 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003465 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003466 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003467 else
John McCalla0296f72010-03-19 07:35:19 +00003468 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003469 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003470 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003471 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003472 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003473 }
John McCall3696dcb2010-08-17 07:23:57 +00003474 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3475 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003476
Craig Topperc3ec1492014-05-26 06:22:03 +00003477 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003478 if ((T2RecordType = T2->getAs<RecordType>()) &&
3479 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003480 // The type we're converting from is a class type, enumerate its conversion
3481 // functions.
3482 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3483
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003484 std::pair<CXXRecordDecl::conversion_iterator,
3485 CXXRecordDecl::conversion_iterator>
3486 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3487 for (CXXRecordDecl::conversion_iterator
3488 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003489 NamedDecl *D = *I;
3490 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3491 if (isa<UsingShadowDecl>(D))
3492 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003493
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003494 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3495 CXXConversionDecl *Conv;
3496 if (ConvTemplate)
3497 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3498 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003499 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003500
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003501 // If the conversion function doesn't return a reference type,
3502 // it can't be considered for this conversion unless we're allowed to
3503 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003504 // FIXME: Do we need to make sure that we only consider conversion
3505 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003506 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00003507 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003508 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3509 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003510 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003511 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00003512 DestType, CandidateSet,
3513 /*AllowObjCConversionOnExplicit=*/
3514 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003515 else
John McCalla0296f72010-03-19 07:35:19 +00003516 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00003517 Initializer, DestType, CandidateSet,
3518 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003519 }
3520 }
3521 }
John McCall3696dcb2010-08-17 07:23:57 +00003522 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3523 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003524
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003525 SourceLocation DeclLoc = Initializer->getLocStart();
3526
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003527 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003528 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003529 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003530 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003531 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003532
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003533 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00003534 // This is the overload that will be used for this initialization step if we
3535 // use this initialization. Mark it as referenced.
3536 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00003537
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003538 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003539 if (isa<CXXConversionDecl>(Function))
Alp Toker314cc812014-01-25 16:55:45 +00003540 T2 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003541 else
3542 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003543
3544 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003545 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003546 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003547 T2.getNonLValueExprType(S.Context),
3548 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003549
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003550 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003551 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003552 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003553 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003554 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003555 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003556 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003557
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003558 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003559 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003560 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003561 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003562 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003563 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003564 NewDerivedToBase, NewObjCConversion,
3565 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003566 if (NewRefRelationship == Sema::Ref_Incompatible) {
3567 // If the type we've converted to is not reference-related to the
3568 // type we're looking for, then there is another conversion step
3569 // we need to perform to produce a temporary of the right type
3570 // that we'll be binding to.
3571 ImplicitConversionSequence ICS;
3572 ICS.setStandard();
3573 ICS.Standard = Best->FinalConversion;
3574 T2 = ICS.Standard.getToType(2);
3575 Sequence.AddConversionSequenceStep(ICS, T2);
3576 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003577 Sequence.AddDerivedToBaseCastStep(
3578 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003579 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003580 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003581 else if (NewObjCConversion)
3582 Sequence.AddObjCObjectConversionStep(
3583 S.Context.getQualifiedType(T1,
3584 T2.getNonReferenceType().getQualifiers()));
3585
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003586 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003587 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003588
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003589 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3590 return OR_Success;
3591}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003592
Richard Smithc620f552011-10-19 16:55:56 +00003593static void CheckCXX98CompatAccessibleCopy(Sema &S,
3594 const InitializedEntity &Entity,
3595 Expr *CurInitExpr);
3596
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003597/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3598static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003599 const InitializedEntity &Entity,
3600 const InitializationKind &Kind,
3601 Expr *Initializer,
3602 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003603 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003604 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003605 Qualifiers T1Quals;
3606 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003607 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003608 Qualifiers T2Quals;
3609 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003610
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003611 // If the initializer is the address of an overloaded function, try
3612 // to resolve the overloaded function. If all goes well, T2 is the
3613 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003614 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3615 T1, Sequence))
3616 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003617
Sebastian Redl29526f02011-11-27 16:50:07 +00003618 // Delegate everything else to a subfunction.
3619 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3620 T1Quals, cv2T2, T2, T2Quals, Sequence);
3621}
3622
Jordan Roseb1312a52013-04-11 00:58:58 +00003623/// Converts the target of reference initialization so that it has the
3624/// appropriate qualifiers and value kind.
3625///
3626/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3627/// \code
3628/// int x;
3629/// const int &r = x;
3630/// \endcode
3631///
3632/// In this case the reference is binding to a bitfield lvalue, which isn't
3633/// valid. Perform a load to create a lifetime-extended temporary instead.
3634/// \code
3635/// const int &r = someStruct.bitfield;
3636/// \endcode
3637static ExprValueKind
3638convertQualifiersAndValueKindIfNecessary(Sema &S,
3639 InitializationSequence &Sequence,
3640 Expr *Initializer,
3641 QualType cv1T1,
3642 Qualifiers T1Quals,
3643 Qualifiers T2Quals,
3644 bool IsLValueRef) {
John McCalld25db7e2013-05-06 21:39:12 +00003645 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Roseb1312a52013-04-11 00:58:58 +00003646 Initializer->refersToVectorElement();
3647
3648 if (IsNonAddressableType) {
3649 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3650 // lvalue reference to a non-volatile const type, or the reference shall be
3651 // an rvalue reference.
3652 //
3653 // If not, we can't make a temporary and bind to that. Give up and allow the
3654 // error to be diagnosed later.
3655 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3656 assert(Initializer->isGLValue());
3657 return Initializer->getValueKind();
3658 }
3659
3660 // Force a load so we can materialize a temporary.
3661 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3662 return VK_RValue;
3663 }
3664
3665 if (T1Quals != T2Quals) {
3666 Sequence.AddQualificationConversionStep(cv1T1,
3667 Initializer->getValueKind());
3668 }
3669
3670 return Initializer->getValueKind();
3671}
3672
3673
Sebastian Redl29526f02011-11-27 16:50:07 +00003674/// \brief Reference initialization without resolving overloaded functions.
3675static void TryReferenceInitializationCore(Sema &S,
3676 const InitializedEntity &Entity,
3677 const InitializationKind &Kind,
3678 Expr *Initializer,
3679 QualType cv1T1, QualType T1,
3680 Qualifiers T1Quals,
3681 QualType cv2T2, QualType T2,
3682 Qualifiers T2Quals,
3683 InitializationSequence &Sequence) {
3684 QualType DestType = Entity.getType();
3685 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003686 // Compute some basic properties of the types and the initializer.
3687 bool isLValueRef = DestType->isLValueReferenceType();
3688 bool isRValueRef = !isLValueRef;
3689 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003690 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003691 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003692 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003693 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003694 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003695 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003696
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003697 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003698 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003699 // "cv2 T2" as follows:
3700 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003701 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003702 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00003703 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00003704 // there are no function rvalues in C++, rvalue refs to functions are treated
3705 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003706 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003707 bool T1Function = T1->isFunctionType();
3708 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003709 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003710 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003711 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003712 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003713 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003714 // reference-compatible with "cv2 T2," or
3715 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003716 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003717 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003718 // can occur. However, we do pay attention to whether it is a bit-field
3719 // to decide whether we're actually binding to a temporary created from
3720 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003721 if (DerivedToBase)
3722 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003723 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003724 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003725 else if (ObjCConversion)
3726 Sequence.AddObjCObjectConversionStep(
3727 S.Context.getQualifiedType(T1, T2Quals));
3728
Jordan Roseb1312a52013-04-11 00:58:58 +00003729 ExprValueKind ValueKind =
3730 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3731 cv1T1, T1Quals, T2Quals,
3732 isLValueRef);
3733 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003734 return;
3735 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003736
3737 // - has a class type (i.e., T2 is a class type), where T1 is not
3738 // reference-related to T2, and can be implicitly converted to an
3739 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3740 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003741 // applicable conversion functions (13.3.1.6) and choosing the best
3742 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003743 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00003744 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00003745 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3746 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003747 ConvOvlResult = TryRefInitWithConversionFunction(
3748 S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003749 if (ConvOvlResult == OR_Success)
3750 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00003751 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00003752 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003753 InitializationSequence::FK_ReferenceInitOverloadFailed,
3754 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003755 }
3756 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003757
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003758 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003759 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003760 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003761 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003762 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3763 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3764 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003765 Sequence.SetOverloadFailure(
3766 InitializationSequence::FK_ReferenceInitOverloadFailed,
3767 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003768 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003769 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003770 ? (RefRelationship == Sema::Ref_Related
3771 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3772 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3773 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003774
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003775 return;
3776 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003777
Douglas Gregor92e460e2011-01-20 16:44:54 +00003778 // - If the initializer expression
3779 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3780 // "cv1 T1" is reference-compatible with "cv2 T2"
3781 // Note: functions are handled below.
3782 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003783 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003784 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003785 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003786 (InitCategory.isXValue() ||
3787 (InitCategory.isPRValue() && T2->isRecordType()) ||
3788 (InitCategory.isPRValue() && T2->isArrayType()))) {
3789 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3790 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003791 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3792 // compiler the freedom to perform a copy here or bind to the
3793 // object, while C++0x requires that we bind directly to the
3794 // object. Hence, we always bind to the object without making an
3795 // extra copy. However, in C++03 requires that we check for the
3796 // presence of a suitable copy constructor:
3797 //
3798 // The constructor that would be used to make the copy shall
3799 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003800 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003801 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003802 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00003803 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003805
Douglas Gregor92e460e2011-01-20 16:44:54 +00003806 if (DerivedToBase)
3807 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3808 ValueKind);
3809 else if (ObjCConversion)
3810 Sequence.AddObjCObjectConversionStep(
3811 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003812
Jordan Roseb1312a52013-04-11 00:58:58 +00003813 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3814 Initializer, cv1T1,
3815 T1Quals, T2Quals,
3816 isLValueRef);
3817
3818 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003819 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003820 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003821
3822 // - has a class type (i.e., T2 is a class type), where T1 is not
3823 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003824 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3825 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00003826 //
3827 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00003828 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003829 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003830 ConvOvlResult = TryRefInitWithConversionFunction(
3831 S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003832 if (ConvOvlResult)
3833 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003834 InitializationSequence::FK_ReferenceInitOverloadFailed,
3835 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003836
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003837 return;
3838 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003839
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00003840 if ((RefRelationship == Sema::Ref_Compatible ||
3841 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3842 isRValueRef && InitCategory.isLValue()) {
3843 Sequence.SetFailed(
3844 InitializationSequence::FK_RValueReferenceBindingToLValue);
3845 return;
3846 }
3847
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003848 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3849 return;
3850 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003851
3852 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003853 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00003854 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003855 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003856
John McCallec6f4e92010-06-04 02:29:22 +00003857 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3858
Richard Smith2eabf782013-06-13 00:57:57 +00003859 // FIXME: Why do we use an implicit conversion here rather than trying
3860 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00003861 ImplicitConversionSequence ICS
3862 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00003863 /*SuppressUserConversions=*/false,
3864 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003865 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003866 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3867 /*AllowObjCWritebackConversion=*/false);
3868
3869 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003870 // FIXME: Use the conversion function set stored in ICS to turn
3871 // this into an overloading ambiguity diagnostic. However, we need
3872 // to keep that set as an OverloadCandidateSet rather than as some
3873 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003874 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3875 Sequence.SetOverloadFailure(
3876 InitializationSequence::FK_ReferenceInitOverloadFailed,
3877 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003878 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3879 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003880 else
3881 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003882 return;
John McCall31168b02011-06-15 23:02:42 +00003883 } else {
3884 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003885 }
3886
3887 // [...] If T1 is reference-related to T2, cv1 must be the
3888 // same cv-qualification as, or greater cv-qualification
3889 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003890 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3891 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003892 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003893 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003894 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3895 return;
3896 }
3897
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003898 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003899 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003900 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003901 InitCategory.isLValue()) {
3902 Sequence.SetFailed(
3903 InitializationSequence::FK_RValueReferenceBindingToLValue);
3904 return;
3905 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003906
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003907 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3908 return;
3909}
3910
3911/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003912/// (C++ [dcl.init.string], C99 6.7.8).
3913static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003914 const InitializedEntity &Entity,
3915 const InitializationKind &Kind,
3916 Expr *Initializer,
3917 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003918 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003919}
3920
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003921/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003922static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003923 const InitializedEntity &Entity,
3924 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00003925 InitializationSequence &Sequence,
3926 InitListExpr *InitList) {
3927 assert((!InitList || InitList->getNumInits() == 0) &&
3928 "Shouldn't use value-init for non-empty init lists");
3929
Richard Smith1bfe0682012-02-14 21:14:13 +00003930 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003931 //
3932 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003933 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003934
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003935 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00003936 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003937
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003938 if (const RecordType *RT = T->getAs<RecordType>()) {
3939 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00003940 bool NeedZeroInitialization = true;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003941 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithd86812d2012-07-05 08:39:21 +00003942 // C++98:
3943 // -- if T is a class type (clause 9) with a user-declared constructor
3944 // (12.1), then the default constructor for T is called (and the
3945 // initialization is ill-formed if T has no accessible default
3946 // constructor);
Richard Smith1bfe0682012-02-14 21:14:13 +00003947 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithd86812d2012-07-05 08:39:21 +00003948 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00003949 } else {
3950 // C++11:
3951 // -- if T is a class type (clause 9) with either no default constructor
3952 // (12.1 [class.ctor]) or a default constructor that is user-provided
3953 // or deleted, then the object is default-initialized;
3954 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3955 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithd86812d2012-07-05 08:39:21 +00003956 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00003957 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003958
Richard Smith1bfe0682012-02-14 21:14:13 +00003959 // -- if T is a (possibly cv-qualified) non-union class type without a
3960 // user-provided or deleted default constructor, then the object is
3961 // zero-initialized and, if T has a non-trivial default constructor,
3962 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00003963 // The 'non-union' here was removed by DR1502. The 'non-trivial default
3964 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00003965 if (NeedZeroInitialization)
3966 Sequence.AddZeroInitializationStep(Entity.getType());
3967
Richard Smith593f9932012-12-08 02:01:17 +00003968 // C++03:
3969 // -- if T is a non-union class type without a user-declared constructor,
3970 // then every non-static data member and base class component of T is
3971 // value-initialized;
3972 // [...] A program that calls for [...] value-initialization of an
3973 // entity of reference type is ill-formed.
3974 //
3975 // C++11 doesn't need this handling, because value-initialization does not
3976 // occur recursively there, and the implicit default constructor is
3977 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003978 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00003979 ClassDecl->hasUninitializedReferenceMember()) {
3980 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3981 return;
3982 }
3983
Richard Smithd86812d2012-07-05 08:39:21 +00003984 // If this is list-value-initialization, pass the empty init list on when
3985 // building the constructor call. This affects the semantics of a few
3986 // things (such as whether an explicit default constructor can be called).
3987 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003988 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00003989 bool InitListSyntax = InitList;
3990
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003991 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
3992 InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003993 }
3994 }
3995
Douglas Gregor1b303932009-12-22 15:35:07 +00003996 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003997}
3998
Douglas Gregor85dabae2009-12-16 01:38:02 +00003999/// \brief Attempt default initialization (C++ [dcl.init]p6).
4000static void TryDefaultInitialization(Sema &S,
4001 const InitializedEntity &Entity,
4002 const InitializationKind &Kind,
4003 InitializationSequence &Sequence) {
4004 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004005
Douglas Gregor85dabae2009-12-16 01:38:02 +00004006 // C++ [dcl.init]p6:
4007 // To default-initialize an object of type T means:
4008 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004009 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4010
Douglas Gregor85dabae2009-12-16 01:38:02 +00004011 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4012 // constructor for T is called (and the initialization is ill-formed if
4013 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004014 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004015 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004016 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004017 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004018
Douglas Gregor85dabae2009-12-16 01:38:02 +00004019 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004020
Douglas Gregor85dabae2009-12-16 01:38:02 +00004021 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004022 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004023 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004024 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004025 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004026 return;
4027 }
4028
4029 // If the destination type has a lifetime property, zero-initialize it.
4030 if (DestType.getQualifiers().hasObjCLifetime()) {
4031 Sequence.AddZeroInitializationStep(Entity.getType());
4032 return;
4033 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004034}
4035
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004036/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4037/// which enumerates all conversion functions and performs overload resolution
4038/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004039static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004040 const InitializedEntity &Entity,
4041 const InitializationKind &Kind,
4042 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004043 InitializationSequence &Sequence,
4044 bool TopLevelOfInitList) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004045 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004046 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4047 QualType SourceType = Initializer->getType();
4048 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4049 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004050
Douglas Gregor540c3b02009-12-14 17:27:33 +00004051 // Build the candidate set directly in the initialization sequence
4052 // structure, so that it will persist if we fail.
4053 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4054 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004055
Douglas Gregor540c3b02009-12-14 17:27:33 +00004056 // Determine whether we are allowed to call explicit constructors or
4057 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004058 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004059
Douglas Gregor540c3b02009-12-14 17:27:33 +00004060 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4061 // The type we're converting to is a class type. Enumerate its constructors
4062 // to see if there is a suitable conversion.
4063 CXXRecordDecl *DestRecordDecl
4064 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004065
Douglas Gregord9848152010-04-26 14:36:57 +00004066 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004067 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004068 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie12be6392012-10-18 16:57:32 +00004069 // The container holding the constructors can under certain conditions
4070 // be changed while iterating. To be safe we copy the lookup results
4071 // to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004072 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004073 for (SmallVectorImpl<NamedDecl *>::iterator
David Blaikie12be6392012-10-18 16:57:32 +00004074 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregord9848152010-04-26 14:36:57 +00004075 Con != ConEnd; ++Con) {
4076 NamedDecl *D = *Con;
4077 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004078
Douglas Gregord9848152010-04-26 14:36:57 +00004079 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00004080 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregord9848152010-04-26 14:36:57 +00004081 FunctionTemplateDecl *ConstructorTmpl
4082 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004083 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00004084 Constructor = cast<CXXConstructorDecl>(
4085 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00004086 else
Douglas Gregord9848152010-04-26 14:36:57 +00004087 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004088
Douglas Gregord9848152010-04-26 14:36:57 +00004089 if (!Constructor->isInvalidDecl() &&
4090 Constructor->isConvertingConstructor(AllowExplicit)) {
4091 if (ConstructorTmpl)
4092 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004093 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004094 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004095 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004096 else
4097 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004098 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004099 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004100 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004101 }
Douglas Gregord9848152010-04-26 14:36:57 +00004102 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004103 }
Eli Friedman78275202009-12-19 08:11:05 +00004104
4105 SourceLocation DeclLoc = Initializer->getLocStart();
4106
Douglas Gregor540c3b02009-12-14 17:27:33 +00004107 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4108 // The type we're converting from is a class type, enumerate its conversion
4109 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004110
Eli Friedman4afe9a32009-12-20 22:12:03 +00004111 // We can only enumerate the conversion functions for a complete type; if
4112 // the type isn't complete, simply skip this step.
4113 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4114 CXXRecordDecl *SourceRecordDecl
4115 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004116
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004117 std::pair<CXXRecordDecl::conversion_iterator,
4118 CXXRecordDecl::conversion_iterator>
4119 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4120 for (CXXRecordDecl::conversion_iterator
4121 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004122 NamedDecl *D = *I;
4123 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4124 if (isa<UsingShadowDecl>(D))
4125 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004126
Eli Friedman4afe9a32009-12-20 22:12:03 +00004127 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4128 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004129 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004130 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004131 else
John McCallda4458e2010-03-31 01:36:47 +00004132 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004133
Eli Friedman4afe9a32009-12-20 22:12:03 +00004134 if (AllowExplicit || !Conv->isExplicit()) {
4135 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004136 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004137 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004138 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004139 else
John McCalla0296f72010-03-19 07:35:19 +00004140 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004141 Initializer, DestType, CandidateSet,
4142 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004143 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004144 }
4145 }
4146 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004147
4148 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004149 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004150 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00004151 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004152 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004153 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004154 Result);
4155 return;
4156 }
John McCall0d1da222010-01-12 00:44:57 +00004157
Douglas Gregor540c3b02009-12-14 17:27:33 +00004158 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004159 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004160 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004161
Douglas Gregor540c3b02009-12-14 17:27:33 +00004162 if (isa<CXXConstructorDecl>(Function)) {
4163 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004164 // subsumed by the initialization. Per DR5, the created temporary is of the
4165 // cv-unqualified type of the destination.
4166 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4167 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004168 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004169 return;
4170 }
4171
4172 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004173 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004174 if (ConvType->getAs<RecordType>()) {
Richard Smithb24f0672012-02-11 19:22:50 +00004175 // If we're converting to a class type, there may be an copy of
Douglas Gregor5ab11652010-04-17 22:01:05 +00004176 // the resulting temporary object (possible to create an object of
4177 // a base class type). That copy is not a separate conversion, so
4178 // we just make a note of the actual destination type (possibly a
4179 // base class of the type returned by the conversion function) and
4180 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004181 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4182 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004183 return;
4184 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004185
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004186 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4187 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004188
Douglas Gregor5ab11652010-04-17 22:01:05 +00004189 // If the conversion following the call to the conversion function
4190 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004191 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4192 Best->FinalConversion.Third) {
4193 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004194 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004195 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004196 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004197 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004198}
4199
Richard Smithf032001b2013-06-20 02:18:31 +00004200/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4201/// a function with a pointer return type contains a 'return false;' statement.
4202/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4203/// code using that header.
4204///
4205/// Work around this by treating 'return false;' as zero-initializing the result
4206/// if it's used in a pointer-returning function in a system header.
4207static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4208 const InitializedEntity &Entity,
4209 const Expr *Init) {
4210 return S.getLangOpts().CPlusPlus11 &&
4211 Entity.getKind() == InitializedEntity::EK_Result &&
4212 Entity.getType()->isPointerType() &&
4213 isa<CXXBoolLiteralExpr>(Init) &&
4214 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4215 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4216}
4217
John McCall31168b02011-06-15 23:02:42 +00004218/// The non-zero enum values here are indexes into diagnostic alternatives.
4219enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4220
4221/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00004222static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004223 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00004224 // Skip parens.
4225 e = e->IgnoreParens();
4226
4227 // Skip address-of nodes.
4228 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4229 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004230 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4231 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004232
4233 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00004234 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4235 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00004236 case CK_Dependent:
4237 case CK_BitCast:
4238 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00004239 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004240 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004241
4242 case CK_ArrayToPointerDecay:
4243 return IIK_nonscalar;
4244
4245 case CK_NullToPointer:
4246 return IIK_okay;
4247
4248 default:
4249 break;
4250 }
4251
4252 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00004253 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004254 // set isWeakAccess to true, to mean that there will be an implicit
4255 // load which requires a cleanup.
4256 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4257 isWeakAccess = true;
4258
John McCall63f84442011-06-27 23:59:58 +00004259 if (!isAddressOf) return IIK_nonlocal;
4260
John McCall113bee02012-03-10 09:33:50 +00004261 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4262 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00004263
4264 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00004265
4266 // If we have a conditional operator, check both sides.
4267 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004268 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4269 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00004270 return iik;
4271
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004272 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004273
4274 // These are never scalar.
4275 } else if (isa<ArraySubscriptExpr>(e)) {
4276 return IIK_nonscalar;
4277
4278 // Otherwise, it needs to be a null pointer constant.
4279 } else {
4280 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4281 ? IIK_okay : IIK_nonlocal);
4282 }
4283
4284 return IIK_nonlocal;
4285}
4286
4287/// Check whether the given expression is a valid operand for an
4288/// indirect copy/restore.
4289static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4290 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004291 bool isWeakAccess = false;
4292 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4293 // If isWeakAccess to true, there will be an implicit
4294 // load which requires a cleanup.
4295 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4296 S.ExprNeedsCleanups = true;
4297
John McCall31168b02011-06-15 23:02:42 +00004298 if (iik == IIK_okay) return;
4299
4300 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4301 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4302 << src->getSourceRange();
4303}
4304
Douglas Gregore2f943b2011-02-22 18:29:51 +00004305/// \brief Determine whether we have compatible array types for the
4306/// purposes of GNU by-copy array initialization.
4307static bool hasCompatibleArrayTypes(ASTContext &Context,
4308 const ArrayType *Dest,
4309 const ArrayType *Source) {
4310 // If the source and destination array types are equivalent, we're
4311 // done.
4312 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4313 return true;
4314
4315 // Make sure that the element types are the same.
4316 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4317 return false;
4318
4319 // The only mismatch we allow is when the destination is an
4320 // incomplete array type and the source is a constant array type.
4321 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4322}
4323
John McCall31168b02011-06-15 23:02:42 +00004324static bool tryObjCWritebackConversion(Sema &S,
4325 InitializationSequence &Sequence,
4326 const InitializedEntity &Entity,
4327 Expr *Initializer) {
4328 bool ArrayDecay = false;
4329 QualType ArgType = Initializer->getType();
4330 QualType ArgPointee;
4331 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4332 ArrayDecay = true;
4333 ArgPointee = ArgArrayType->getElementType();
4334 ArgType = S.Context.getPointerType(ArgPointee);
4335 }
4336
4337 // Handle write-back conversion.
4338 QualType ConvertedArgType;
4339 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4340 ConvertedArgType))
4341 return false;
4342
4343 // We should copy unless we're passing to an argument explicitly
4344 // marked 'out'.
4345 bool ShouldCopy = true;
4346 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4347 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4348
4349 // Do we need an lvalue conversion?
4350 if (ArrayDecay || Initializer->isGLValue()) {
4351 ImplicitConversionSequence ICS;
4352 ICS.setStandard();
4353 ICS.Standard.setAsIdentityConversion();
4354
4355 QualType ResultType;
4356 if (ArrayDecay) {
4357 ICS.Standard.First = ICK_Array_To_Pointer;
4358 ResultType = S.Context.getPointerType(ArgPointee);
4359 } else {
4360 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4361 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4362 }
4363
4364 Sequence.AddConversionSequenceStep(ICS, ResultType);
4365 }
4366
4367 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4368 return true;
4369}
4370
Guy Benyei61054192013-02-07 10:55:47 +00004371static bool TryOCLSamplerInitialization(Sema &S,
4372 InitializationSequence &Sequence,
4373 QualType DestType,
4374 Expr *Initializer) {
4375 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4376 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4377 return false;
4378
4379 Sequence.AddOCLSamplerInitStep(DestType);
4380 return true;
4381}
4382
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004383//
4384// OpenCL 1.2 spec, s6.12.10
4385//
4386// The event argument can also be used to associate the
4387// async_work_group_copy with a previous async copy allowing
4388// an event to be shared by multiple async copies; otherwise
4389// event should be zero.
4390//
4391static bool TryOCLZeroEventInitialization(Sema &S,
4392 InitializationSequence &Sequence,
4393 QualType DestType,
4394 Expr *Initializer) {
4395 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4396 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4397 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4398 return false;
4399
4400 Sequence.AddOCLZeroEventStep(DestType);
4401 return true;
4402}
4403
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004404InitializationSequence::InitializationSequence(Sema &S,
4405 const InitializedEntity &Entity,
4406 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004407 MultiExprArg Args,
4408 bool TopLevelOfInitList)
Richard Smith100b24a2014-04-17 01:52:14 +00004409 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Richard Smith089c3162013-09-21 21:55:46 +00004410 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
4411}
4412
4413void InitializationSequence::InitializeFrom(Sema &S,
4414 const InitializedEntity &Entity,
4415 const InitializationKind &Kind,
4416 MultiExprArg Args,
4417 bool TopLevelOfInitList) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004418 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004419
John McCall5e77d762013-04-16 07:28:30 +00004420 // Eliminate non-overload placeholder types in the arguments. We
4421 // need to do this before checking whether types are dependent
4422 // because lowering a pseudo-object expression might well give us
4423 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004424 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00004425 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4426 // FIXME: should we be doing this here?
4427 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4428 if (result.isInvalid()) {
4429 SetFailed(FK_PlaceholderType);
4430 return;
4431 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004432 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00004433 }
4434
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004435 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004436 // The semantics of initializers are as follows. The destination type is
4437 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004438 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004439 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004440 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004441 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004442
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004443 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004444 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004445 SequenceKind = DependentSequence;
4446 return;
4447 }
4448
Sebastian Redld201edf2011-06-05 13:59:11 +00004449 // Almost everything is a normal sequence.
4450 setSequenceKind(NormalSequence);
4451
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004452 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00004453 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004454 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004455 Initializer = Args[0];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004456 if (S.getLangOpts().ObjC1) {
4457 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
4458 DestType, Initializer->getType(),
4459 Initializer) ||
4460 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
4461 Args[0] = Initializer;
4462
4463 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004464 if (!isa<InitListExpr>(Initializer))
4465 SourceType = Initializer->getType();
4466 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004467
Sebastian Redl0501c632012-02-12 16:37:36 +00004468 // - If the initializer is a (non-parenthesized) braced-init-list, the
4469 // object is list-initialized (8.5.4).
4470 if (Kind.getKind() != InitializationKind::IK_Direct) {
4471 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4472 TryListInitialization(S, Entity, Kind, InitList, *this);
4473 return;
4474 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004475 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004476
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004477 // - If the destination type is a reference type, see 8.5.3.
4478 if (DestType->isReferenceType()) {
4479 // C++0x [dcl.init.ref]p1:
4480 // A variable declared to be a T& or T&&, that is, "reference to type T"
4481 // (8.3.2), shall be initialized by an object, or function, of type T or
4482 // by an object that can be converted into a T.
4483 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004484 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004485 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004486 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004487 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004488 return;
4489 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004490
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004491 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004492 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004493 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004494 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004495 return;
4496 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004497
Douglas Gregor85dabae2009-12-16 01:38:02 +00004498 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004499 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004500 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004501 return;
4502 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004503
John McCall66884dd2011-02-21 07:22:22 +00004504 // - If the destination type is an array of characters, an array of
4505 // char16_t, an array of char32_t, or an array of wchar_t, and the
4506 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004507 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004508 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004509 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004510 if (Initializer && isa<VariableArrayType>(DestAT)) {
4511 SetFailed(FK_VariableLengthArrayHasInitializer);
4512 return;
4513 }
4514
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004515 if (Initializer) {
4516 switch (IsStringInit(Initializer, DestAT, Context)) {
4517 case SIF_None:
4518 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4519 return;
4520 case SIF_NarrowStringIntoWideChar:
4521 SetFailed(FK_NarrowStringIntoWideCharArray);
4522 return;
4523 case SIF_WideStringIntoChar:
4524 SetFailed(FK_WideStringIntoCharArray);
4525 return;
4526 case SIF_IncompatWideStringIntoWideChar:
4527 SetFailed(FK_IncompatWideStringIntoWideChar);
4528 return;
4529 case SIF_Other:
4530 break;
4531 }
John McCall66884dd2011-02-21 07:22:22 +00004532 }
4533
Douglas Gregore2f943b2011-02-22 18:29:51 +00004534 // Note: as an GNU C extension, we allow initialization of an
4535 // array from a compound literal that creates an array of the same
4536 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004537 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00004538 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4539 Initializer->getType()->isArrayType()) {
4540 const ArrayType *SourceAT
4541 = Context.getAsArrayType(Initializer->getType());
4542 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004543 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004544 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004545 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004546 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004547 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004548 }
Richard Smithebeed412012-02-15 22:38:09 +00004549 }
Richard Smithd86812d2012-07-05 08:39:21 +00004550 // Note: as a GNU C++ extension, we allow list-initialization of a
4551 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004552 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00004553 Entity.getKind() == InitializedEntity::EK_Member &&
4554 Initializer && isa<InitListExpr>(Initializer)) {
4555 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4556 *this);
4557 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004558 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004559 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004560 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4561 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004562 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004563 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004564
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004565 return;
4566 }
Eli Friedman78275202009-12-19 08:11:05 +00004567
John McCall31168b02011-06-15 23:02:42 +00004568 // Determine whether we should consider writeback conversions for
4569 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004570 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004571 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00004572
4573 // We're at the end of the line for C: it's either a write-back conversion
4574 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004575 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004576 // If allowed, check whether this is an Objective-C writeback conversion.
4577 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004578 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004579 return;
4580 }
Guy Benyei61054192013-02-07 10:55:47 +00004581
4582 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4583 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004584
4585 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4586 return;
4587
John McCall31168b02011-06-15 23:02:42 +00004588 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004589 AddCAssignmentStep(DestType);
4590 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004591 return;
4592 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004593
David Blaikiebbafb8a2012-03-11 07:00:24 +00004594 assert(S.getLangOpts().CPlusPlus);
John McCall31168b02011-06-15 23:02:42 +00004595
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004596 // - If the destination type is a (possibly cv-qualified) class type:
4597 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004598 // - If the initialization is direct-initialization, or if it is
4599 // copy-initialization where the cv-unqualified version of the
4600 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004601 // class of the destination, constructors are considered. [...]
4602 if (Kind.getKind() == InitializationKind::IK_Direct ||
4603 (Kind.getKind() == InitializationKind::IK_Copy &&
4604 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4605 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004606 TryConstructorInitialization(S, Entity, Kind, Args,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004607 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004608 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004609 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004610 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004611 // used) to a derived class thereof are enumerated as described in
4612 // 13.3.1.4, and the best one is chosen through overload resolution
4613 // (13.3).
4614 else
Richard Smithaaa0ec42013-09-21 21:19:19 +00004615 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4616 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004617 return;
4618 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004619
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004620 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004621 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004622 return;
4623 }
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004624 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004625
4626 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004627 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004628 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smithaaa0ec42013-09-21 21:19:19 +00004629 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4630 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004631 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004632 return;
4633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004634
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004635 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004636 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004637 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004638 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004639 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00004640
4641 ImplicitConversionSequence ICS
4642 = S.TryImplicitConversion(Initializer, Entity.getType(),
4643 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004644 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004645 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004646 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4647 allowObjCWritebackConversion);
4648
4649 if (ICS.isStandard() &&
4650 ICS.Standard.Second == ICK_Writeback_Conversion) {
4651 // Objective-C ARC writeback conversion.
4652
4653 // We should copy unless we're passing to an argument explicitly
4654 // marked 'out'.
4655 bool ShouldCopy = true;
4656 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4657 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4658
4659 // If there was an lvalue adjustment, add it as a separate conversion.
4660 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4661 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4662 ImplicitConversionSequence LvalueICS;
4663 LvalueICS.setStandard();
4664 LvalueICS.Standard.setAsIdentityConversion();
4665 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4666 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004667 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004668 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004669
4670 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004671 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004672 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00004673 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4674 AddZeroInitializationStep(Entity.getType());
4675 } else if (Initializer->getType() == Context.OverloadTy &&
4676 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4677 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004678 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004679 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004680 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004681 } else {
Richard Smithaaa0ec42013-09-21 21:19:19 +00004682 AddConversionSequenceStep(ICS, Entity.getType(), TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00004683
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004684 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004685 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004686}
4687
4688InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004689 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004690 StepEnd = Steps.end();
4691 Step != StepEnd; ++Step)
4692 Step->Destroy();
4693}
4694
4695//===----------------------------------------------------------------------===//
4696// Perform initialization
4697//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004698static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004699getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004700 switch(Entity.getKind()) {
4701 case InitializedEntity::EK_Variable:
4702 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004703 case InitializedEntity::EK_Exception:
4704 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004705 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004706 return Sema::AA_Initializing;
4707
4708 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004709 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004710 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4711 return Sema::AA_Sending;
4712
Douglas Gregore1314a62009-12-18 05:02:21 +00004713 return Sema::AA_Passing;
4714
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004715 case InitializedEntity::EK_Parameter_CF_Audited:
4716 if (Entity.getDecl() &&
4717 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4718 return Sema::AA_Sending;
4719
4720 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4721
Douglas Gregore1314a62009-12-18 05:02:21 +00004722 case InitializedEntity::EK_Result:
4723 return Sema::AA_Returning;
4724
Douglas Gregore1314a62009-12-18 05:02:21 +00004725 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00004726 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004727 // FIXME: Can we tell apart casting vs. converting?
4728 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004729
Douglas Gregore1314a62009-12-18 05:02:21 +00004730 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004731 case InitializedEntity::EK_ArrayElement:
4732 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004733 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004734 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004735 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004736 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004737 return Sema::AA_Initializing;
4738 }
4739
David Blaikie8a40f702012-01-17 06:56:22 +00004740 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004741}
4742
Richard Smith27874d62013-01-08 00:08:23 +00004743/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00004744/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004745static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004746 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004747 case InitializedEntity::EK_ArrayElement:
4748 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004749 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004750 case InitializedEntity::EK_New:
4751 case InitializedEntity::EK_Variable:
4752 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004753 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004754 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004755 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004756 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004757 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004758 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004759 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004760 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004761
Douglas Gregore1314a62009-12-18 05:02:21 +00004762 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004763 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00004764 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004765 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004766 return true;
4767 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004768
Douglas Gregore1314a62009-12-18 05:02:21 +00004769 llvm_unreachable("missed an InitializedEntity kind?");
4770}
4771
Douglas Gregor95562572010-04-24 23:45:46 +00004772/// \brief Whether the given entity, when initialized with an object
4773/// created for that initialization, requires destruction.
4774static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4775 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00004776 case InitializedEntity::EK_Result:
4777 case InitializedEntity::EK_New:
4778 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004779 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004780 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004781 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004782 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004783 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00004784 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004785
Richard Smith27874d62013-01-08 00:08:23 +00004786 case InitializedEntity::EK_Member:
Douglas Gregor95562572010-04-24 23:45:46 +00004787 case InitializedEntity::EK_Variable:
4788 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004789 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00004790 case InitializedEntity::EK_Temporary:
4791 case InitializedEntity::EK_ArrayElement:
4792 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004793 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004794 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00004795 return true;
4796 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004797
4798 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004799}
4800
Richard Smithc620f552011-10-19 16:55:56 +00004801/// \brief Look for copy and move constructors and constructor templates, for
4802/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4803static void LookupCopyAndMoveConstructors(Sema &S,
4804 OverloadCandidateSet &CandidateSet,
4805 CXXRecordDecl *Class,
4806 Expr *CurInitExpr) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004807 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004808 // The container holding the constructors can under certain conditions
4809 // be changed while iterating (e.g. because of deserialization).
4810 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004811 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004812 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004813 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4814 NamedDecl *D = *CI;
Craig Topperc3ec1492014-05-26 06:22:03 +00004815 CXXConstructorDecl *Constructor = nullptr;
Richard Smithc620f552011-10-19 16:55:56 +00004816
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004817 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smithc620f552011-10-19 16:55:56 +00004818 // Handle copy/moveconstructors, only.
4819 if (!Constructor || Constructor->isInvalidDecl() ||
4820 !Constructor->isCopyOrMoveConstructor() ||
4821 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4822 continue;
4823
4824 DeclAccessPair FoundDecl
4825 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4826 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004827 CurInitExpr, CandidateSet);
Richard Smithc620f552011-10-19 16:55:56 +00004828 continue;
4829 }
4830
4831 // Handle constructor templates.
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004832 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smithc620f552011-10-19 16:55:56 +00004833 if (ConstructorTmpl->isInvalidDecl())
4834 continue;
4835
4836 Constructor = cast<CXXConstructorDecl>(
4837 ConstructorTmpl->getTemplatedDecl());
4838 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4839 continue;
4840
4841 // FIXME: Do we need to limit this to copy-constructor-like
4842 // candidates?
4843 DeclAccessPair FoundDecl
4844 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
Craig Topperc3ec1492014-05-26 06:22:03 +00004845 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004846 CurInitExpr, CandidateSet, true);
Richard Smithc620f552011-10-19 16:55:56 +00004847 }
4848}
4849
4850/// \brief Get the location at which initialization diagnostics should appear.
4851static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4852 Expr *Initializer) {
4853 switch (Entity.getKind()) {
4854 case InitializedEntity::EK_Result:
4855 return Entity.getReturnLoc();
4856
4857 case InitializedEntity::EK_Exception:
4858 return Entity.getThrowLoc();
4859
4860 case InitializedEntity::EK_Variable:
4861 return Entity.getDecl()->getLocation();
4862
Douglas Gregor19666fb2012-02-15 16:57:26 +00004863 case InitializedEntity::EK_LambdaCapture:
4864 return Entity.getCaptureLoc();
4865
Richard Smithc620f552011-10-19 16:55:56 +00004866 case InitializedEntity::EK_ArrayElement:
4867 case InitializedEntity::EK_Member:
4868 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004869 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00004870 case InitializedEntity::EK_Temporary:
4871 case InitializedEntity::EK_New:
4872 case InitializedEntity::EK_Base:
4873 case InitializedEntity::EK_Delegating:
4874 case InitializedEntity::EK_VectorElement:
4875 case InitializedEntity::EK_ComplexElement:
4876 case InitializedEntity::EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004877 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004878 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00004879 return Initializer->getLocStart();
4880 }
4881 llvm_unreachable("missed an InitializedEntity kind?");
4882}
4883
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004884/// \brief Make a (potentially elidable) temporary copy of the object
4885/// provided by the given initializer by calling the appropriate copy
4886/// constructor.
4887///
4888/// \param S The Sema object used for type-checking.
4889///
Abramo Bagnara92141d22011-01-27 19:55:10 +00004890/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004891/// the type of the initializer expression or a superclass thereof.
4892///
James Dennett634962f2012-06-14 21:40:34 +00004893/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004894///
4895/// \param CurInit The initializer expression.
4896///
4897/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4898/// is permitted in C++03 (but not C++0x) when binding a reference to
4899/// an rvalue.
4900///
4901/// \returns An expression that copies the initializer expression into
4902/// a temporary object, or an error expression if a copy could not be
4903/// created.
John McCalldadc5752010-08-24 06:29:42 +00004904static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00004905 QualType T,
4906 const InitializedEntity &Entity,
4907 ExprResult CurInit,
4908 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00004909 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00004910 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00004911 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004912 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004913 Class = cast<CXXRecordDecl>(Record->getDecl());
4914 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004915 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004916
Douglas Gregor5d369002011-01-21 18:05:27 +00004917 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004918 // When certain criteria are met, an implementation is allowed to
4919 // omit the copy/move construction of a class object, even if the
4920 // copy/move constructor and/or destructor for the object have
4921 // side effects. [...]
4922 // - when a temporary class object that has not been bound to a
4923 // reference (12.2) would be copied/moved to a class object
4924 // with the same cv-unqualified type, the copy/move operation
4925 // can be omitted by constructing the temporary object
4926 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004927 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004928 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004929 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004930 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004931 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00004932 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00004933 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00004934
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004935 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004936 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004937 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00004938
Douglas Gregorf282a762011-01-21 19:38:21 +00004939 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00004940 // Only consider constructors and constructor templates. Per
4941 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4942 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00004943 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00004944 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004945
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004946 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4947
Douglas Gregore1314a62009-12-18 05:02:21 +00004948 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004949 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004950 case OR_Success:
4951 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004952
Douglas Gregore1314a62009-12-18 05:02:21 +00004953 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004954 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4955 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4956 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004957 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004958 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004959 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004960 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004961 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004962 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004963
Douglas Gregore1314a62009-12-18 05:02:21 +00004964 case OR_Ambiguous:
4965 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004966 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004967 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004968 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00004969 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004970
Douglas Gregore1314a62009-12-18 05:02:21 +00004971 case OR_Deleted:
4972 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004973 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004974 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00004975 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00004976 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004977 }
4978
Douglas Gregor5ab11652010-04-17 22:01:05 +00004979 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00004980 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004981 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004982
Anders Carlssona01874b2010-04-21 18:47:17 +00004983 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004984 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004985
4986 if (IsExtraneousCopy) {
4987 // If this is a totally extraneous copy for C++03 reference
4988 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004989 // expression. We don't generate an (elided) copy operation here
4990 // because doing so would require us to pass down a flag to avoid
4991 // infinite recursion, where each step adds another extraneous,
4992 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004993
Douglas Gregor30b52772010-04-18 07:57:34 +00004994 // Instantiate the default arguments of any extra parameters in
4995 // the selected copy constructor, as if we were going to create a
4996 // proper call to the copy constructor.
4997 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4998 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4999 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005000 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005001 break;
5002
5003 // Build the default argument expression; we don't actually care
5004 // if this succeeds or not, because this routine will complain
5005 // if there was a problem.
5006 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5007 }
5008
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005009 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005010 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005011
Douglas Gregor5ab11652010-04-17 22:01:05 +00005012 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005013 // constructor call (we might have derived-to-base conversions, or
5014 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005015 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005016 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005017
Douglas Gregord0ace022010-04-25 00:55:24 +00005018 // Actually perform the constructor call.
5019 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005020 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005021 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005022 /*ListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005023 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005024 CXXConstructExpr::CK_Complete,
5025 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005026
Douglas Gregord0ace022010-04-25 00:55:24 +00005027 // If we're supposed to bind temporaries, do so.
5028 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005029 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005030 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005031}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005032
Richard Smithc620f552011-10-19 16:55:56 +00005033/// \brief Check whether elidable copy construction for binding a reference to
5034/// a temporary would have succeeded if we were building in C++98 mode, for
5035/// -Wc++98-compat.
5036static void CheckCXX98CompatAccessibleCopy(Sema &S,
5037 const InitializedEntity &Entity,
5038 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005039 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005040
5041 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5042 if (!Record)
5043 return;
5044
5045 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
5046 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
5047 == DiagnosticsEngine::Ignored)
5048 return;
5049
5050 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00005051 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005052 LookupCopyAndMoveConstructors(
5053 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5054
5055 // Perform overload resolution.
5056 OverloadCandidateSet::iterator Best;
5057 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5058
5059 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5060 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5061 << CurInitExpr->getSourceRange();
5062
5063 switch (OR) {
5064 case OR_Success:
5065 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCall5dadb652012-04-07 03:04:20 +00005066 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005067 // FIXME: Check default arguments as far as that's possible.
5068 break;
5069
5070 case OR_No_Viable_Function:
5071 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005072 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005073 break;
5074
5075 case OR_Ambiguous:
5076 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005077 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005078 break;
5079
5080 case OR_Deleted:
5081 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005082 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005083 break;
5084 }
5085}
5086
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005087void InitializationSequence::PrintInitLocationNote(Sema &S,
5088 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005089 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005090 if (Entity.getDecl()->getLocation().isInvalid())
5091 return;
5092
5093 if (Entity.getDecl()->getDeclName())
5094 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5095 << Entity.getDecl()->getDeclName();
5096 else
5097 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5098 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005099 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5100 Entity.getMethodDecl())
5101 S.Diag(Entity.getMethodDecl()->getLocation(),
5102 diag::note_method_return_type_change)
5103 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005104}
5105
Sebastian Redl112aa822011-07-14 19:07:55 +00005106static bool isReferenceBinding(const InitializationSequence::Step &s) {
5107 return s.Kind == InitializationSequence::SK_BindReference ||
5108 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5109}
5110
Jordan Rose6c0505e2013-05-06 16:48:12 +00005111/// Returns true if the parameters describe a constructor initialization of
5112/// an explicit temporary object, e.g. "Point(x, y)".
5113static bool isExplicitTemporary(const InitializedEntity &Entity,
5114 const InitializationKind &Kind,
5115 unsigned NumArgs) {
5116 switch (Entity.getKind()) {
5117 case InitializedEntity::EK_Temporary:
5118 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005119 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005120 break;
5121 default:
5122 return false;
5123 }
5124
5125 switch (Kind.getKind()) {
5126 case InitializationKind::IK_DirectList:
5127 return true;
5128 // FIXME: Hack to work around cast weirdness.
5129 case InitializationKind::IK_Direct:
5130 case InitializationKind::IK_Value:
5131 return NumArgs != 1;
5132 default:
5133 return false;
5134 }
5135}
5136
Sebastian Redled2e5322011-12-22 14:44:04 +00005137static ExprResult
5138PerformConstructorInitialization(Sema &S,
5139 const InitializedEntity &Entity,
5140 const InitializationKind &Kind,
5141 MultiExprArg Args,
5142 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00005143 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005144 bool IsListInitialization,
5145 SourceLocation LBraceLoc,
5146 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005147 unsigned NumArgs = Args.size();
5148 CXXConstructorDecl *Constructor
5149 = cast<CXXConstructorDecl>(Step.Function.Function);
5150 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5151
5152 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005153 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00005154 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5155 ? Kind.getEqualLoc()
5156 : Kind.getLocation();
5157
5158 if (Kind.getKind() == InitializationKind::IK_Default) {
5159 // Force even a trivial, implicit default constructor to be
5160 // semantically checked. We do this explicitly because we don't build
5161 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00005162 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00005163 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00005164 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00005165 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5166 }
5167
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005168 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00005169
Douglas Gregor6073dca2012-02-24 23:56:31 +00005170 // C++ [over.match.copy]p1:
5171 // - When initializing a temporary to be bound to the first parameter
5172 // of a constructor that takes a reference to possibly cv-qualified
5173 // T as its first argument, called with a single argument in the
5174 // context of direct-initialization, explicit conversion functions
5175 // are also considered.
5176 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5177 Args.size() == 1 &&
5178 Constructor->isCopyOrMoveConstructor();
5179
Sebastian Redled2e5322011-12-22 14:44:04 +00005180 // Determine the arguments required to actually perform the constructor
5181 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005182 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005183 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00005184 AllowExplicitConv,
5185 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00005186 return ExprError();
5187
5188
Jordan Rose6c0505e2013-05-06 16:48:12 +00005189 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005190 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedmanfa0df832012-02-02 03:46:19 +00005191 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith22262ab2013-05-04 06:44:46 +00005192 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5193 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005194
5195 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5196 if (!TSInfo)
5197 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005198 SourceRange ParenOrBraceRange =
5199 (Kind.getKind() == InitializationKind::IK_DirectList)
5200 ? SourceRange(LBraceLoc, RBraceLoc)
5201 : Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005202
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005203 CurInit = new (S.Context) CXXTemporaryObjectExpr(
5204 S.Context, Constructor, TSInfo, ConstructorArgs, ParenOrBraceRange,
5205 HadMultipleCandidates, IsListInitialization,
5206 ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00005207 } else {
5208 CXXConstructExpr::ConstructionKind ConstructKind =
5209 CXXConstructExpr::CK_Complete;
5210
5211 if (Entity.getKind() == InitializedEntity::EK_Base) {
5212 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5213 CXXConstructExpr::CK_VirtualBase :
5214 CXXConstructExpr::CK_NonVirtualBase;
5215 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5216 ConstructKind = CXXConstructExpr::CK_Delegating;
5217 }
5218
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005219 // Only get the parenthesis or brace range if it is a list initialization or
5220 // direct construction.
5221 SourceRange ParenOrBraceRange;
5222 if (IsListInitialization)
5223 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
5224 else if (Kind.getKind() == InitializationKind::IK_Direct)
5225 ParenOrBraceRange = Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005226
5227 // If the entity allows NRVO, mark the construction as elidable
5228 // unconditionally.
5229 if (Entity.allowsNRVO())
5230 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5231 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005232 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005233 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005234 IsListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005235 ConstructorInitRequiresZeroInit,
5236 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005237 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005238 else
5239 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5240 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005241 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005242 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005243 IsListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005244 ConstructorInitRequiresZeroInit,
5245 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005246 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005247 }
5248 if (CurInit.isInvalid())
5249 return ExprError();
5250
5251 // Only check access if all of that succeeded.
5252 S.CheckConstructorAccess(Loc, Constructor, Entity,
5253 Step.Function.FoundDecl.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005254 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5255 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005256
5257 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005258 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00005259
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005260 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00005261}
5262
Richard Smitheb3cad52012-06-04 22:27:30 +00005263/// Determine whether the specified InitializedEntity definitely has a lifetime
5264/// longer than the current full-expression. Conservatively returns false if
5265/// it's unclear.
5266static bool
5267InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5268 const InitializedEntity *Top = &Entity;
5269 while (Top->getParent())
5270 Top = Top->getParent();
5271
5272 switch (Top->getKind()) {
5273 case InitializedEntity::EK_Variable:
5274 case InitializedEntity::EK_Result:
5275 case InitializedEntity::EK_Exception:
5276 case InitializedEntity::EK_Member:
5277 case InitializedEntity::EK_New:
5278 case InitializedEntity::EK_Base:
5279 case InitializedEntity::EK_Delegating:
5280 return true;
5281
5282 case InitializedEntity::EK_ArrayElement:
5283 case InitializedEntity::EK_VectorElement:
5284 case InitializedEntity::EK_BlockElement:
5285 case InitializedEntity::EK_ComplexElement:
5286 // Could not determine what the full initialization is. Assume it might not
5287 // outlive the full-expression.
5288 return false;
5289
5290 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005291 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00005292 case InitializedEntity::EK_Temporary:
5293 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005294 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005295 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00005296 // The entity being initialized might not outlive the full-expression.
5297 return false;
5298 }
5299
5300 llvm_unreachable("unknown entity kind");
5301}
5302
Richard Smithe6c01442013-06-05 00:46:14 +00005303/// Determine the declaration which an initialized entity ultimately refers to,
5304/// for the purpose of lifetime-extending a temporary bound to a reference in
5305/// the initialization of \p Entity.
David Majnemerdaff3702014-05-01 17:50:17 +00005306static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
5307 const InitializedEntity *Entity,
Craig Topperc3ec1492014-05-26 06:22:03 +00005308 const InitializedEntity *FallbackDecl = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00005309 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00005310 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005311 case InitializedEntity::EK_Variable:
5312 // The temporary [...] persists for the lifetime of the reference
David Majnemerdaff3702014-05-01 17:50:17 +00005313 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005314
5315 case InitializedEntity::EK_Member:
5316 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005317 if (Entity->getParent())
5318 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5319 Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00005320
5321 // except:
5322 // -- A temporary bound to a reference member in a constructor's
5323 // ctor-initializer persists until the constructor exits.
David Majnemerdaff3702014-05-01 17:50:17 +00005324 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005325
5326 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005327 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00005328 // -- A temporary bound to a reference parameter in a function call
5329 // persists until the completion of the full-expression containing
5330 // the call.
5331 case InitializedEntity::EK_Result:
5332 // -- The lifetime of a temporary bound to the returned value in a
5333 // function return statement is not extended; the temporary is
5334 // destroyed at the end of the full-expression in the return statement.
5335 case InitializedEntity::EK_New:
5336 // -- A temporary bound to a reference in a new-initializer persists
5337 // until the completion of the full-expression containing the
5338 // new-initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005339 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005340
5341 case InitializedEntity::EK_Temporary:
5342 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005343 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00005344 // We don't yet know the storage duration of the surrounding temporary.
5345 // Assume it's got full-expression duration for now, it will patch up our
5346 // storage duration if that's not correct.
David Majnemerdaff3702014-05-01 17:50:17 +00005347 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005348
5349 case InitializedEntity::EK_ArrayElement:
5350 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005351 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5352 FallbackDecl);
Richard Smithe6c01442013-06-05 00:46:14 +00005353
5354 case InitializedEntity::EK_Base:
5355 case InitializedEntity::EK_Delegating:
5356 // We can reach this case for aggregate initialization in a constructor:
5357 // struct A { int &&r; };
5358 // struct B : A { B() : A{0} {} };
5359 // In this case, use the innermost field decl as the context.
5360 return FallbackDecl;
5361
5362 case InitializedEntity::EK_BlockElement:
5363 case InitializedEntity::EK_LambdaCapture:
5364 case InitializedEntity::EK_Exception:
5365 case InitializedEntity::EK_VectorElement:
5366 case InitializedEntity::EK_ComplexElement:
David Majnemerdaff3702014-05-01 17:50:17 +00005367 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005368 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00005369 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00005370}
5371
David Majnemerdaff3702014-05-01 17:50:17 +00005372static void performLifetimeExtension(Expr *Init,
5373 const InitializedEntity *ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005374
5375/// Update a glvalue expression that is used as the initializer of a reference
5376/// to note that its lifetime is extended.
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005377/// \return \c true if any temporary had its lifetime extended.
David Majnemerdaff3702014-05-01 17:50:17 +00005378static bool
5379performReferenceExtension(Expr *Init,
5380 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00005381 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5382 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5383 // This is just redundant braces around an initializer. Step over it.
5384 Init = ILE->getInit(0);
5385 }
5386 }
5387
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005388 // Walk past any constructs which we can lifetime-extend across.
5389 Expr *Old;
5390 do {
5391 Old = Init;
5392
5393 // Step over any subobject adjustments; we may have a materialized
5394 // temporary inside them.
5395 SmallVector<const Expr *, 2> CommaLHSs;
5396 SmallVector<SubobjectAdjustment, 2> Adjustments;
5397 Init = const_cast<Expr *>(
5398 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5399
5400 // Per current approach for DR1376, look through casts to reference type
5401 // when performing lifetime extension.
5402 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5403 if (CE->getSubExpr()->isGLValue())
5404 Init = CE->getSubExpr();
5405
5406 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5407 // It's unclear if binding a reference to that xvalue extends the array
5408 // temporary.
5409 } while (Init != Old);
5410
Richard Smithe6c01442013-06-05 00:46:14 +00005411 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5412 // Update the storage duration of the materialized temporary.
5413 // FIXME: Rebuild the expression instead of mutating it.
David Majnemerdaff3702014-05-01 17:50:17 +00005414 ME->setExtendingDecl(ExtendingEntity->getDecl(),
5415 ExtendingEntity->allocateManglingNumber());
5416 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005417 return true;
Richard Smithe6c01442013-06-05 00:46:14 +00005418 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005419
5420 return false;
Richard Smithe6c01442013-06-05 00:46:14 +00005421}
5422
5423/// Update a prvalue expression that is going to be materialized as a
5424/// lifetime-extended temporary.
David Majnemerdaff3702014-05-01 17:50:17 +00005425static void performLifetimeExtension(Expr *Init,
5426 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00005427 // Dig out the expression which constructs the extended temporary.
5428 SmallVector<const Expr *, 2> CommaLHSs;
5429 SmallVector<SubobjectAdjustment, 2> Adjustments;
5430 Init = const_cast<Expr *>(
5431 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5432
Richard Smith736a9472013-06-12 20:42:33 +00005433 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5434 Init = BTE->getSubExpr();
5435
Richard Smithcc1b96d2013-06-12 22:31:48 +00005436 if (CXXStdInitializerListExpr *ILE =
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005437 dyn_cast<CXXStdInitializerListExpr>(Init)) {
David Majnemerdaff3702014-05-01 17:50:17 +00005438 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005439 return;
5440 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00005441
Richard Smithe6c01442013-06-05 00:46:14 +00005442 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00005443 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005444 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
David Majnemerdaff3702014-05-01 17:50:17 +00005445 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005446 return;
5447 }
5448
Richard Smithcc1b96d2013-06-12 22:31:48 +00005449 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005450 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5451
5452 // If we lifetime-extend a braced initializer which is initializing an
5453 // aggregate, and that aggregate contains reference members which are
5454 // bound to temporaries, those temporaries are also lifetime-extended.
5455 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5456 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005457 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005458 else {
5459 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005460 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00005461 if (Index >= ILE->getNumInits())
5462 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005463 if (I->isUnnamedBitfield())
5464 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00005465 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00005466 if (I->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005467 performReferenceExtension(SubInit, ExtendingEntity);
Richard Smith8d7f11d2013-06-27 22:54:33 +00005468 else if (isa<InitListExpr>(SubInit) ||
5469 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smithe6c01442013-06-05 00:46:14 +00005470 // This may be either aggregate-initialization of a member or
5471 // initialization of a std::initializer_list object. Either way,
5472 // we should recursively lifetime-extend that initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005473 performLifetimeExtension(SubInit, ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005474 ++Index;
5475 }
5476 }
5477 }
5478 }
5479}
5480
Richard Smithcc1b96d2013-06-12 22:31:48 +00005481static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5482 const Expr *Init, bool IsInitializerList,
5483 const ValueDecl *ExtendingDecl) {
5484 // Warn if a field lifetime-extends a temporary.
5485 if (isa<FieldDecl>(ExtendingDecl)) {
5486 if (IsInitializerList) {
5487 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5488 << /*at end of constructor*/true;
5489 return;
5490 }
5491
5492 bool IsSubobjectMember = false;
5493 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5494 Ent = Ent->getParent()) {
5495 if (Ent->getKind() != InitializedEntity::EK_Base) {
5496 IsSubobjectMember = true;
5497 break;
5498 }
5499 }
5500 S.Diag(Init->getExprLoc(),
5501 diag::warn_bind_ref_member_to_temporary)
5502 << ExtendingDecl << Init->getSourceRange()
5503 << IsSubobjectMember << IsInitializerList;
5504 if (IsSubobjectMember)
5505 S.Diag(ExtendingDecl->getLocation(),
5506 diag::note_ref_subobject_of_member_declared_here);
5507 else
5508 S.Diag(ExtendingDecl->getLocation(),
5509 diag::note_ref_or_ptr_member_declared_here)
5510 << /*is pointer*/false;
5511 }
5512}
5513
Richard Smithaaa0ec42013-09-21 21:19:19 +00005514static void DiagnoseNarrowingInInitList(Sema &S,
5515 const ImplicitConversionSequence &ICS,
5516 QualType PreNarrowingType,
5517 QualType EntityType,
5518 const Expr *PostInit);
5519
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005520ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005521InitializationSequence::Perform(Sema &S,
5522 const InitializedEntity &Entity,
5523 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00005524 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005525 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005526 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005527 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00005528 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005529 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005530
Sebastian Redld201edf2011-06-05 13:59:11 +00005531 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005532 // If the declaration is a non-dependent, incomplete array type
5533 // that has an initializer, then its type will be completed once
5534 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00005535 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00005536 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00005537 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005538 if (const IncompleteArrayType *ArrayT
5539 = S.Context.getAsIncompleteArrayType(DeclType)) {
5540 // FIXME: We don't currently have the ability to accurately
5541 // compute the length of an initializer list without
5542 // performing full type-checking of the initializer list
5543 // (since we have to determine where braces are implicitly
5544 // introduced and such). So, we fall back to making the array
5545 // type a dependently-sized array type with no specified
5546 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005547 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005548 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00005549
Douglas Gregor51e77d52009-12-10 17:56:55 +00005550 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00005551 if (DeclaratorDecl *DD = Entity.getDecl()) {
5552 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5553 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00005554 if (IncompleteArrayTypeLoc ArrayLoc =
5555 TL.getAs<IncompleteArrayTypeLoc>())
5556 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00005557 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00005558 }
5559
5560 *ResultType
5561 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005562 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005563 ArrayT->getSizeModifier(),
5564 ArrayT->getIndexTypeCVRQualifiers(),
5565 Brackets);
5566 }
5567
5568 }
5569 }
Sebastian Redla9351792012-02-11 23:51:47 +00005570 if (Kind.getKind() == InitializationKind::IK_Direct &&
5571 !Kind.isExplicitCast()) {
5572 // Rebuild the ParenListExpr.
5573 SourceRange ParenRange = Kind.getParenRange();
5574 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005575 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00005576 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00005577 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00005578 Kind.isExplicitCast() ||
5579 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005580 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005581 }
5582
Sebastian Redld201edf2011-06-05 13:59:11 +00005583 // No steps means no initialization.
5584 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005585 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005586
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005587 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005588 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005589 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00005590 // Produce a C++98 compatibility warning if we are initializing a reference
5591 // from an initializer list. For parameters, we produce a better warning
5592 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005593 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00005594 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5595 << Init->getSourceRange();
5596 }
5597
Richard Smitheb3cad52012-06-04 22:27:30 +00005598 // Diagnose cases where we initialize a pointer to an array temporary, and the
5599 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005600 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00005601 Entity.getType()->isPointerType() &&
5602 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005603 Expr *Init = Args[0];
Richard Smitheb3cad52012-06-04 22:27:30 +00005604 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5605 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5606 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5607 << Init->getSourceRange();
5608 }
5609
Douglas Gregor1b303932009-12-22 15:35:07 +00005610 QualType DestType = Entity.getType().getNonReferenceType();
5611 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00005612 // the same as Entity.getDecl()->getType() in cases involving type merging,
5613 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00005614 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00005615 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00005616 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005617
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005618 ExprResult CurInit((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005619
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005620 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00005621 // grab the only argument out the Args and place it into the "current"
5622 // initializer.
5623 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005624 case SK_ResolveAddressOfOverloadedFunction:
5625 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005626 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005627 case SK_CastDerivedToBaseLValue:
5628 case SK_BindReference:
5629 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005630 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00005631 case SK_UserConversion:
5632 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005633 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005634 case SK_QualificationConversionRValue:
Jordan Roseb1312a52013-04-11 00:58:58 +00005635 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005636 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00005637 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00005638 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00005639 case SK_UnwrapInitList:
5640 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00005641 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00005642 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00005643 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00005644 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00005645 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00005646 case SK_PassByIndirectCopyRestore:
5647 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00005648 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005649 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00005650 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005651 case SK_OCLZeroEvent: {
Douglas Gregore1314a62009-12-18 05:02:21 +00005652 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005653 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00005654 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005655 break;
John McCall34376a62010-12-04 03:47:34 +00005656 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005657
Douglas Gregore1314a62009-12-18 05:02:21 +00005658 case SK_ConstructorInitialization:
Richard Smithd86812d2012-07-05 08:39:21 +00005659 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00005660 case SK_ZeroInitialization:
5661 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005663
5664 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005665 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005666 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005667 for (step_iterator Step = step_begin(), StepEnd = step_end();
5668 Step != StepEnd; ++Step) {
5669 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005670 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005671
John Wiegley01296292011-04-08 18:41:53 +00005672 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005673
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005674 switch (Step->Kind) {
5675 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005676 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005677 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00005678 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00005679 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5680 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005681 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00005682 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00005683 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005684 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005685
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005686 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005687 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005688 case SK_CastDerivedToBaseLValue: {
5689 // We have a derived-to-base cast that produces either an rvalue or an
5690 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005691
John McCallcf142162010-08-07 06:22:56 +00005692 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00005693
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005694 // Casts to inaccessible base classes are allowed with C-style casts.
5695 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5696 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00005697 CurInit.get()->getLocStart(),
5698 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00005699 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00005700 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005701
Douglas Gregor88d292c2010-05-13 16:44:06 +00005702 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5703 QualType T = SourceType;
5704 if (const PointerType *Pointer = T->getAs<PointerType>())
5705 T = Pointer->getPointeeType();
5706 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00005707 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00005708 cast<CXXRecordDecl>(RecordTy->getDecl()));
5709 }
5710
John McCall2536c6d2010-08-25 10:28:54 +00005711 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005712 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005713 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005714 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005715 VK_XValue :
5716 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005717 CurInit =
5718 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
5719 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005720 break;
5721 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005722
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005723 case SK_BindReference:
John McCalld25db7e2013-05-06 21:39:12 +00005724 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5725 if (CurInit.get()->refersToBitField()) {
5726 // We don't necessarily have an unambiguous source bit-field.
5727 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005728 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00005729 << Entity.getType().isVolatileQualified()
John McCalld25db7e2013-05-06 21:39:12 +00005730 << (BitField ? BitField->getDeclName() : DeclarationName())
Craig Topperc3ec1492014-05-26 06:22:03 +00005731 << (BitField != nullptr)
John Wiegley01296292011-04-08 18:41:53 +00005732 << CurInit.get()->getSourceRange();
John McCalld25db7e2013-05-06 21:39:12 +00005733 if (BitField)
5734 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5735
John McCallfaf5fb42010-08-26 23:41:50 +00005736 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005737 }
Anders Carlssona91be642010-01-29 02:47:33 +00005738
John Wiegley01296292011-04-08 18:41:53 +00005739 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00005740 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005741 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5742 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00005743 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005744 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005745 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005746 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005747
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005748 // Reference binding does not have any corresponding ASTs.
5749
5750 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005751 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005752 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005753
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005754 // Even though we didn't materialize a temporary, the binding may still
5755 // extend the lifetime of a temporary. This happens if we bind a reference
5756 // to the result of a cast to reference type.
David Majnemerdaff3702014-05-01 17:50:17 +00005757 if (const InitializedEntity *ExtendingEntity =
5758 getEntityForTemporaryLifetimeExtension(&Entity))
5759 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
5760 warnOnLifetimeExtension(S, Entity, CurInit.get(),
5761 /*IsInitializerList=*/false,
5762 ExtendingEntity->getDecl());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005763
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005764 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005765
Richard Smithe6c01442013-06-05 00:46:14 +00005766 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00005767 // Make sure the "temporary" is actually an rvalue.
5768 assert(CurInit.get()->isRValue() && "not a temporary");
5769
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005770 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005771 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005772 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005773
Douglas Gregorfe314812011-06-21 17:03:29 +00005774 // Materialize the temporary into memory.
Richard Smith736a9472013-06-12 20:42:33 +00005775 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Richard Smithe6c01442013-06-05 00:46:14 +00005776 Entity.getType().getNonReferenceType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00005777 Entity.getType()->isLValueReferenceType());
5778
5779 // Maybe lifetime-extend the temporary's subobjects to match the
5780 // entity's lifetime.
5781 if (const InitializedEntity *ExtendingEntity =
5782 getEntityForTemporaryLifetimeExtension(&Entity))
5783 if (performReferenceExtension(MTE, ExtendingEntity))
5784 warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false,
5785 ExtendingEntity->getDecl());
Douglas Gregor58df5092011-06-22 16:12:01 +00005786
5787 // If we're binding to an Objective-C object that has lifetime, we
Richard Smith736a9472013-06-12 20:42:33 +00005788 // need cleanups. Likewise if we're extending this temporary to automatic
5789 // storage duration -- we need to register its cleanup during the
5790 // full-expression's cleanups.
5791 if ((S.getLangOpts().ObjCAutoRefCount &&
5792 MTE->getType()->isObjCLifetimeType()) ||
5793 (MTE->getStorageDuration() == SD_Automatic &&
5794 MTE->getType().isDestructedType()))
Douglas Gregor58df5092011-06-22 16:12:01 +00005795 S.ExprNeedsCleanups = true;
Richard Smith736a9472013-06-12 20:42:33 +00005796
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005797 CurInit = MTE;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005798 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005799 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005800
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005801 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005802 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005803 /*IsExtraneousCopy=*/true);
5804 break;
5805
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005806 case SK_UserConversion: {
5807 // We have a user-defined conversion that invokes either a constructor
5808 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00005809 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00005810 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00005811 FunctionDecl *Fn = Step->Function.Function;
5812 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005813 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00005814 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00005815 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005816 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005817 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00005818 SourceLocation Loc = CurInit.get()->getLocStart();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005819 CurInit.get(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00005820
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005821 // Determine the arguments required to actually perform the constructor
5822 // call.
John Wiegley01296292011-04-08 18:41:53 +00005823 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005824 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00005825 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005826 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005827 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005828
Richard Smithb24f0672012-02-11 19:22:50 +00005829 // Build an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005830 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005831 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005832 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005833 /*ListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005834 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005835 CXXConstructExpr::CK_Complete,
5836 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005837 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005838 return ExprError();
John McCall760af172010-02-01 03:16:54 +00005839
Anders Carlssona01874b2010-04-21 18:47:17 +00005840 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00005841 FoundFn.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005842 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5843 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005844
John McCalle3027922010-08-25 11:45:40 +00005845 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00005846 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5847 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5848 S.IsDerivedFrom(SourceType, Class))
5849 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005850
Douglas Gregor95562572010-04-24 23:45:46 +00005851 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005852 } else {
5853 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00005854 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00005855 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00005856 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00005857 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5858 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005859
5860 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005861 // derived-to-base conversion? I believe the answer is "no", because
5862 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00005863 ExprResult CurInitExprRes =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005864 S.PerformObjectArgumentInitialization(CurInit.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005865 /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00005866 FoundFn, Conversion);
5867 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005868 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005869 CurInit = CurInitExprRes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005870
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005871 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005872 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5873 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005874 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00005875 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005876
John McCalle3027922010-08-25 11:45:40 +00005877 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005878
Alp Toker314cc812014-01-25 16:55:45 +00005879 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005880 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005881
Sebastian Redl112aa822011-07-14 19:07:55 +00005882 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005883 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5884
5885 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00005886 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00005887 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005888 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00005889 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00005890 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00005891 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00005892 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00005893 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
5894 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00005895 }
5896 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005897
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005898 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
5899 CastKind, CurInit.get(), nullptr,
5900 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005901 if (MaybeBindToTemp)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005902 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005903 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005904 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005905 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005906 break;
5907 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005908
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005909 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005910 case SK_QualificationConversionXValue:
5911 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005912 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00005913 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005914 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005915 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005916 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005917 VK_XValue :
5918 VK_RValue);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005919 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005920 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005921 }
5922
Jordan Roseb1312a52013-04-11 00:58:58 +00005923 case SK_LValueToRValue: {
5924 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005925 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
5926 CK_LValueToRValue, CurInit.get(),
5927 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00005928 break;
5929 }
5930
Richard Smithaaa0ec42013-09-21 21:19:19 +00005931 case SK_ConversionSequence:
5932 case SK_ConversionSequenceNoNarrowing: {
5933 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00005934 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5935 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00005936 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00005937 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00005938 ExprResult CurInitExprRes =
5939 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00005940 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00005941 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005942 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005943 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00005944
5945 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
5946 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
5947 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
5948 CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005949 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00005950 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005951
Douglas Gregor51e77d52009-12-10 17:56:55 +00005952 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00005953 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00005954 // If we're not initializing the top-level entity, we need to create an
5955 // InitializeTemporary entity for our target type.
5956 QualType Ty = Step->Type;
5957 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00005958 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00005959 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5960 InitListChecker PerformInitList(S, InitEntity,
Richard Smithde229232013-06-06 11:41:05 +00005961 InitList, Ty, /*VerifyOnly=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005962 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00005963 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005964
Richard Smithcc1b96d2013-06-12 22:31:48 +00005965 // Hack: We must update *ResultType if available in order to set the
5966 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5967 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5968 if (ResultType &&
5969 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00005970 if ((*ResultType)->isRValueReferenceType())
5971 Ty = S.Context.getRValueReferenceType(Ty);
5972 else if ((*ResultType)->isLValueReferenceType())
5973 Ty = S.Context.getLValueReferenceType(Ty,
5974 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5975 *ResultType = Ty;
5976 }
5977
5978 InitListExpr *StructuredInitList =
5979 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005980 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00005981 CurInit = shouldBindAsTemporary(InitEntity)
5982 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005983 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00005984 break;
5985 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005986
Sebastian Redled2e5322011-12-22 14:44:04 +00005987 case SK_ListConstructorCall: {
Sebastian Redl5a41f682012-02-12 16:37:24 +00005988 // When an initializer list is passed for a parameter of type "reference
5989 // to object", we don't get an EK_Temporary entity, but instead an
5990 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00005991 // FIXME: This is a hack. What we really should do is create a user
5992 // conversion step for this case, but this makes it considerably more
5993 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00005994 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5995 Entity.getType().getNonReferenceType());
5996 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00005997 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005998 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00005999 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6000 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006001 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00006002 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6003 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006004 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006005 ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006006 /*IsListInitialization*/ true,
6007 InitList->getLBraceLoc(),
6008 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00006009 break;
6010 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006011
Sebastian Redl29526f02011-11-27 16:50:07 +00006012 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006013 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00006014 break;
6015
6016 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006017 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00006018 InitListExpr *Syntactic = Step->WrappingSyntacticList;
6019 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00006020 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00006021 ILE->setSyntacticForm(Syntactic);
6022 ILE->setType(E->getType());
6023 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006024 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00006025 break;
6026 }
6027
Sebastian Redl99f66162012-02-19 12:27:56 +00006028 case SK_ConstructorInitialization: {
6029 // When an initializer list is passed for a parameter of type "reference
6030 // to object", we don't get an EK_Temporary entity, but instead an
6031 // EK_Parameter entity with reference type.
6032 // FIXME: This is a hack. What we really should do is create a user
6033 // conversion step for this case, but this makes it considerably more
6034 // complicated. For now, this will do.
6035 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6036 Entity.getType().getNonReferenceType());
6037 bool UseTemporary = Entity.getType()->isReferenceType();
6038 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
6039 : Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006040 Kind, Args, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006041 ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006042 /*IsListInitialization*/ false,
6043 /*LBraceLoc*/ SourceLocation(),
6044 /*RBraceLoc*/ SourceLocation());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006045 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00006046 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006047
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006048 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006049 step_iterator NextStep = Step;
6050 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006051 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00006052 (NextStep->Kind == SK_ConstructorInitialization ||
6053 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006054 // The need for zero-initialization is recorded directly into
6055 // the call to the object's constructor within the next step.
6056 ConstructorInitRequiresZeroInit = true;
6057 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006058 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006059 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00006060 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6061 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006062 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00006063 Kind.getRange().getBegin());
6064
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006065 CurInit = new (S.Context) CXXScalarValueInitExpr(
6066 TSInfo->getType().getNonLValueExprType(S.Context), TSInfo,
6067 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006068 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006069 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006070 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006071 break;
6072 }
Douglas Gregore1314a62009-12-18 05:02:21 +00006073
6074 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00006075 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006076 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00006077 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00006078 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6079 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00006080 if (Result.isInvalid())
6081 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006082 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00006083
6084 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006085 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00006086 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006087 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00006088 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00006089 == Sema::Compatible)
6090 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00006091 if (CurInitExprRes.isInvalid())
6092 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006093 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00006094
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006095 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00006096 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6097 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00006098 CurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00006099 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006100 &Complained)) {
6101 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00006102 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006103 } else if (Complained)
6104 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00006105 break;
6106 }
Eli Friedman78275202009-12-19 08:11:05 +00006107
6108 case SK_StringInit: {
6109 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00006110 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00006111 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00006112 break;
6113 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006114
6115 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006116 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00006117 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00006118 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006119 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006120
6121 case SK_ArrayInit:
6122 // Okay: we checked everything before creating this step. Note that
6123 // this is a GNU extension.
6124 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00006125 << Step->Type << CurInit.get()->getType()
6126 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00006127
6128 // If the destination type is an incomplete array type, update the
6129 // type accordingly.
6130 if (ResultType) {
6131 if (const IncompleteArrayType *IncompleteDest
6132 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6133 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00006134 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00006135 *ResultType = S.Context.getConstantArrayType(
6136 IncompleteDest->getElementType(),
6137 ConstantSource->getSize(),
6138 ArrayType::Normal, 0);
6139 }
6140 }
6141 }
John McCall31168b02011-06-15 23:02:42 +00006142 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006143
Richard Smithebeed412012-02-15 22:38:09 +00006144 case SK_ParenthesizedArrayInit:
6145 // Okay: we checked everything before creating this step. Note that
6146 // this is a GNU extension.
6147 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6148 << CurInit.get()->getSourceRange();
6149 break;
6150
John McCall31168b02011-06-15 23:02:42 +00006151 case SK_PassByIndirectCopyRestore:
6152 case SK_PassByIndirectRestore:
6153 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006154 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
6155 CurInit.get(), Step->Type,
6156 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00006157 break;
6158
6159 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006160 CurInit =
6161 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
6162 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00006163 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006164
6165 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006166 S.Diag(CurInit.get()->getExprLoc(),
6167 diag::warn_cxx98_compat_initializer_list_init)
6168 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00006169
Richard Smithcc1b96d2013-06-12 22:31:48 +00006170 // Materialize the temporary into memory.
6171 MaterializeTemporaryExpr *MTE = new (S.Context)
6172 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00006173 /*BoundToLvalueReference=*/false);
6174
6175 // Maybe lifetime-extend the array temporary's subobjects to match the
6176 // entity's lifetime.
6177 if (const InitializedEntity *ExtendingEntity =
6178 getEntityForTemporaryLifetimeExtension(&Entity))
6179 if (performReferenceExtension(MTE, ExtendingEntity))
6180 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6181 /*IsInitializerList=*/true,
6182 ExtendingEntity->getDecl());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006183
6184 // Wrap it in a construction of a std::initializer_list<T>.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006185 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006186
6187 // Bind the result, in case the library has given initializer_list a
6188 // non-trivial destructor.
6189 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006190 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00006191 break;
6192 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006193
Guy Benyei61054192013-02-07 10:55:47 +00006194 case SK_OCLSamplerInit: {
6195 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006196 "Sampler initialization on non-sampler type.");
Guy Benyei61054192013-02-07 10:55:47 +00006197
6198 QualType SourceType = CurInit.get()->getType();
Guy Benyei61054192013-02-07 10:55:47 +00006199
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006200 if (Entity.isParameterKind()) {
Guy Benyei61054192013-02-07 10:55:47 +00006201 if (!SourceType->isSamplerT())
6202 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6203 << SourceType;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006204 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
Guy Benyei61054192013-02-07 10:55:47 +00006205 llvm_unreachable("Invalid EntityKind!");
6206 }
6207
6208 break;
6209 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006210 case SK_OCLZeroEvent: {
6211 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006212 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006213
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006214 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006215 CK_ZeroToOCLEvent,
6216 CurInit.get()->getValueKind());
6217 break;
6218 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006219 }
6220 }
John McCall1f425642010-11-11 03:21:53 +00006221
6222 // Diagnose non-fatal problems with the completed initialization.
6223 if (Entity.getKind() == InitializedEntity::EK_Member &&
6224 cast<FieldDecl>(Entity.getDecl())->isBitField())
6225 S.CheckBitFieldInitialization(Kind.getLocation(),
6226 cast<FieldDecl>(Entity.getDecl()),
6227 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006228
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006229 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006230}
6231
Richard Smith593f9932012-12-08 02:01:17 +00006232/// Somewhere within T there is an uninitialized reference subobject.
6233/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00006234static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6235 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00006236 if (T->isReferenceType()) {
6237 S.Diag(Loc, diag::err_reference_without_init)
6238 << T.getNonReferenceType();
6239 return true;
6240 }
6241
6242 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6243 if (!RD || !RD->hasUninitializedReferenceMember())
6244 return false;
6245
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006246 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00006247 if (FI->isUnnamedBitfield())
6248 continue;
6249
6250 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6251 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6252 return true;
6253 }
6254 }
6255
Aaron Ballman574705e2014-03-13 15:41:46 +00006256 for (const auto &BI : RD->bases()) {
6257 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00006258 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6259 return true;
6260 }
6261 }
6262
6263 return false;
6264}
6265
6266
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006267//===----------------------------------------------------------------------===//
6268// Diagnose initialization failures
6269//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00006270
6271/// Emit notes associated with an initialization that failed due to a
6272/// "simple" conversion failure.
6273static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6274 Expr *op) {
6275 QualType destType = entity.getType();
6276 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6277 op->getType()->isObjCObjectPointerType()) {
6278
6279 // Emit a possible note about the conversion failing because the
6280 // operand is a message send with a related result type.
6281 S.EmitRelatedResultTypeNote(op);
6282
6283 // Emit a possible note about a return failing because we're
6284 // expecting a related result type.
6285 if (entity.getKind() == InitializedEntity::EK_Result)
6286 S.EmitRelatedResultTypeNoteForReturn(destType);
6287 }
6288}
6289
Richard Smith0449aaf2013-11-21 23:30:57 +00006290static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6291 InitListExpr *InitList) {
6292 QualType DestType = Entity.getType();
6293
6294 QualType E;
6295 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6296 QualType ArrayType = S.Context.getConstantArrayType(
6297 E.withConst(),
6298 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6299 InitList->getNumInits()),
6300 clang::ArrayType::Normal, 0);
6301 InitializedEntity HiddenArray =
6302 InitializedEntity::InitializeTemporary(ArrayType);
6303 return diagnoseListInit(S, HiddenArray, InitList);
6304 }
6305
6306 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
6307 /*VerifyOnly=*/false);
6308 assert(DiagnoseInitList.HadError() &&
6309 "Inconsistent init list check result.");
6310}
6311
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006312bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006313 const InitializedEntity &Entity,
6314 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006315 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006316 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006317 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006318
Douglas Gregor1b303932009-12-22 15:35:07 +00006319 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006320 switch (Failure) {
6321 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006322 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006323 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00006324 // Dig out the reference subobject which is uninitialized and diagnose it.
6325 // If this is value-initialization, this could be nested some way within
6326 // the target type.
6327 assert(Kind.getKind() == InitializationKind::IK_Value ||
6328 DestType->isReferenceType());
6329 bool Diagnosed =
6330 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6331 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6332 (void)Diagnosed;
6333 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006334 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006335 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006336 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006337
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006338 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006339 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006340 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006341 case FK_ArrayNeedsInitListOrStringLiteral:
6342 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6343 break;
6344 case FK_ArrayNeedsInitListOrWideStringLiteral:
6345 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6346 break;
6347 case FK_NarrowStringIntoWideCharArray:
6348 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6349 break;
6350 case FK_WideStringIntoCharArray:
6351 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6352 break;
6353 case FK_IncompatWideStringIntoWideChar:
6354 S.Diag(Kind.getLocation(),
6355 diag::err_array_init_incompat_wide_string_into_wchar);
6356 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006357 case FK_ArrayTypeMismatch:
6358 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00006359 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00006360 (Failure == FK_ArrayTypeMismatch
6361 ? diag::err_array_init_different_type
6362 : diag::err_array_init_non_constant_array))
6363 << DestType.getNonReferenceType()
6364 << Args[0]->getType()
6365 << Args[0]->getSourceRange();
6366 break;
6367
John McCalla59dc2f2012-01-05 00:13:19 +00006368 case FK_VariableLengthArrayHasInitializer:
6369 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6370 << Args[0]->getSourceRange();
6371 break;
6372
John McCall16df1e52010-03-30 21:47:33 +00006373 case FK_AddressOfOverloadFailed: {
6374 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006375 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006376 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00006377 true,
6378 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006379 break;
John McCall16df1e52010-03-30 21:47:33 +00006380 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006381
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006382 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00006383 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006384 switch (FailedOverloadResult) {
6385 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00006386 if (Failure == FK_UserConversionOverloadFailed)
6387 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6388 << Args[0]->getType() << DestType
6389 << Args[0]->getSourceRange();
6390 else
6391 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6392 << DestType << Args[0]->getType()
6393 << Args[0]->getSourceRange();
6394
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006395 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006396 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006397
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006398 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00006399 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00006400 DestType.getNonReferenceType(),
6401 diag::err_typecheck_nonviable_condition_incomplete,
6402 Args[0]->getType(), Args[0]->getSourceRange()))
6403 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6404 << Args[0]->getType() << Args[0]->getSourceRange()
6405 << DestType.getNonReferenceType();
6406
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006407 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006408 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006409
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006410 case OR_Deleted: {
6411 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6412 << Args[0]->getType() << DestType.getNonReferenceType()
6413 << Args[0]->getSourceRange();
6414 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006415 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00006416 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6417 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006418 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00006419 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006420 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006421 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006422 }
6423 break;
6424 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006425
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006426 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006427 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006428 }
6429 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006430
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006431 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00006432 if (isa<InitListExpr>(Args[0])) {
6433 S.Diag(Kind.getLocation(),
6434 diag::err_lvalue_reference_bind_to_initlist)
6435 << DestType.getNonReferenceType().isVolatileQualified()
6436 << DestType.getNonReferenceType()
6437 << Args[0]->getSourceRange();
6438 break;
6439 }
6440 // Intentional fallthrough
6441
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006442 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006443 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006444 Failure == FK_NonConstLValueReferenceBindingToTemporary
6445 ? diag::err_lvalue_reference_bind_to_temporary
6446 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00006447 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006448 << DestType.getNonReferenceType()
6449 << Args[0]->getType()
6450 << Args[0]->getSourceRange();
6451 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006452
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006453 case FK_RValueReferenceBindingToLValue:
6454 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00006455 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006456 << Args[0]->getSourceRange();
6457 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006458
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006459 case FK_ReferenceInitDropsQualifiers:
6460 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6461 << DestType.getNonReferenceType()
6462 << Args[0]->getType()
6463 << Args[0]->getSourceRange();
6464 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006465
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006466 case FK_ReferenceInitFailed:
6467 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6468 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00006469 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006470 << Args[0]->getType()
6471 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00006472 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006473 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006474
Douglas Gregorb491ed32011-02-19 21:32:49 +00006475 case FK_ConversionFailed: {
6476 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00006477 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00006478 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006479 << DestType
John McCall086a4642010-11-24 05:12:34 +00006480 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00006481 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006482 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00006483 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6484 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00006485 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00006486 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00006487 }
John Wiegley01296292011-04-08 18:41:53 +00006488
6489 case FK_ConversionFromPropertyFailed:
6490 // No-op. This error has already been reported.
6491 break;
6492
Douglas Gregor51e77d52009-12-10 17:56:55 +00006493 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00006494 SourceRange R;
6495
6496 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00006497 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00006498 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006499 else
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006500 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00006501
Alp Tokerb6cc5922014-05-03 03:45:55 +00006502 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00006503 if (Kind.isCStyleOrFunctionalCast())
6504 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6505 << R;
6506 else
6507 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6508 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006509 break;
6510 }
6511
6512 case FK_ReferenceBindingToInitList:
6513 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6514 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6515 break;
6516
6517 case FK_InitListBadDestinationType:
6518 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6519 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6520 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006521
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006522 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006523 case FK_ConstructorOverloadFailed: {
6524 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006525 if (Args.size())
6526 ArgsRange = SourceRange(Args.front()->getLocStart(),
6527 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006528
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006529 if (Failure == FK_ListConstructorOverloadFailed) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006530 assert(Args.size() == 1 && "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006531 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006532 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006533 }
6534
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006535 // FIXME: Using "DestType" for the entity we're printing is probably
6536 // bad.
6537 switch (FailedOverloadResult) {
6538 case OR_Ambiguous:
6539 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6540 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006541 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006542 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006543
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006544 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006545 if (Kind.getKind() == InitializationKind::IK_Default &&
6546 (Entity.getKind() == InitializedEntity::EK_Base ||
6547 Entity.getKind() == InitializedEntity::EK_Member) &&
6548 isa<CXXConstructorDecl>(S.CurContext)) {
6549 // This is implicit default initialization of a member or
6550 // base within a constructor. If no viable function was
6551 // found, notify the user that she needs to explicitly
6552 // initialize this base/member.
6553 CXXConstructorDecl *Constructor
6554 = cast<CXXConstructorDecl>(S.CurContext);
6555 if (Entity.getKind() == InitializedEntity::EK_Base) {
6556 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006557 << (Constructor->getInheritedConstructor() ? 2 :
6558 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006559 << S.Context.getTypeDeclType(Constructor->getParent())
6560 << /*base=*/0
6561 << Entity.getType();
6562
6563 RecordDecl *BaseDecl
6564 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6565 ->getDecl();
6566 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6567 << S.Context.getTagDeclType(BaseDecl);
6568 } else {
6569 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006570 << (Constructor->getInheritedConstructor() ? 2 :
6571 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006572 << S.Context.getTypeDeclType(Constructor->getParent())
6573 << /*member=*/1
6574 << Entity.getName();
Alp Toker2afa8782014-05-28 12:20:14 +00006575 S.Diag(Entity.getDecl()->getLocation(),
6576 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006577
6578 if (const RecordType *Record
6579 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006580 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006581 diag::note_previous_decl)
6582 << S.Context.getTagDeclType(Record->getDecl());
6583 }
6584 break;
6585 }
6586
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006587 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6588 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006589 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006590 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006591
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006592 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006593 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006594 OverloadingResult Ovl
6595 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00006596 if (Ovl != OR_Deleted) {
6597 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6598 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006599 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00006600 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006601 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00006602
6603 // If this is a defaulted or implicitly-declared function, then
6604 // it was implicitly deleted. Make it clear that the deletion was
6605 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00006606 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006607 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00006608 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006609 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00006610 else
6611 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6612 << true << DestType << ArgsRange;
6613
6614 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006615 break;
6616 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006617
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006618 case OR_Success:
6619 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006620 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006621 }
David Blaikie60deeee2012-01-17 08:24:58 +00006622 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006623
Douglas Gregor85dabae2009-12-16 01:38:02 +00006624 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006625 if (Entity.getKind() == InitializedEntity::EK_Member &&
6626 isa<CXXConstructorDecl>(S.CurContext)) {
6627 // This is implicit default-initialization of a const member in
6628 // a constructor. Complain that it needs to be explicitly
6629 // initialized.
6630 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6631 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006632 << (Constructor->getInheritedConstructor() ? 2 :
6633 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006634 << S.Context.getTypeDeclType(Constructor->getParent())
6635 << /*const=*/1
6636 << Entity.getName();
6637 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6638 << Entity.getName();
6639 } else {
6640 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6641 << DestType << (bool)DestType->getAs<RecordType>();
6642 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00006643 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006644
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006645 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00006646 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006647 diag::err_init_incomplete_type);
6648 break;
6649
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006650 case FK_ListInitializationFailed: {
6651 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00006652 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6653 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006654 break;
6655 }
John McCall4124c492011-10-17 18:40:02 +00006656
6657 case FK_PlaceholderType: {
6658 // FIXME: Already diagnosed!
6659 break;
6660 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00006661
Sebastian Redl048a6d72012-04-01 19:54:59 +00006662 case FK_ExplicitConstructor: {
6663 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6664 << Args[0]->getSourceRange();
6665 OverloadCandidateSet::iterator Best;
6666 OverloadingResult Ovl
6667 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00006668 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00006669 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6670 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6671 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6672 break;
6673 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006674 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006675
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006676 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006677 return true;
6678}
Douglas Gregore1314a62009-12-18 05:02:21 +00006679
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006680void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006681 switch (SequenceKind) {
6682 case FailedSequence: {
6683 OS << "Failed sequence: ";
6684 switch (Failure) {
6685 case FK_TooManyInitsForReference:
6686 OS << "too many initializers for reference";
6687 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006688
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006689 case FK_ArrayNeedsInitList:
6690 OS << "array requires initializer list";
6691 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006692
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006693 case FK_ArrayNeedsInitListOrStringLiteral:
6694 OS << "array requires initializer list or string literal";
6695 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006696
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006697 case FK_ArrayNeedsInitListOrWideStringLiteral:
6698 OS << "array requires initializer list or wide string literal";
6699 break;
6700
6701 case FK_NarrowStringIntoWideCharArray:
6702 OS << "narrow string into wide char array";
6703 break;
6704
6705 case FK_WideStringIntoCharArray:
6706 OS << "wide string into char array";
6707 break;
6708
6709 case FK_IncompatWideStringIntoWideChar:
6710 OS << "incompatible wide string into wide char array";
6711 break;
6712
Douglas Gregore2f943b2011-02-22 18:29:51 +00006713 case FK_ArrayTypeMismatch:
6714 OS << "array type mismatch";
6715 break;
6716
6717 case FK_NonConstantArrayInit:
6718 OS << "non-constant array initializer";
6719 break;
6720
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006721 case FK_AddressOfOverloadFailed:
6722 OS << "address of overloaded function failed";
6723 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006724
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006725 case FK_ReferenceInitOverloadFailed:
6726 OS << "overload resolution for reference initialization failed";
6727 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006728
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006729 case FK_NonConstLValueReferenceBindingToTemporary:
6730 OS << "non-const lvalue reference bound to temporary";
6731 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006732
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006733 case FK_NonConstLValueReferenceBindingToUnrelated:
6734 OS << "non-const lvalue reference bound to unrelated type";
6735 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006736
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006737 case FK_RValueReferenceBindingToLValue:
6738 OS << "rvalue reference bound to an lvalue";
6739 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006740
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006741 case FK_ReferenceInitDropsQualifiers:
6742 OS << "reference initialization drops qualifiers";
6743 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006744
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006745 case FK_ReferenceInitFailed:
6746 OS << "reference initialization failed";
6747 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006748
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006749 case FK_ConversionFailed:
6750 OS << "conversion failed";
6751 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006752
John Wiegley01296292011-04-08 18:41:53 +00006753 case FK_ConversionFromPropertyFailed:
6754 OS << "conversion from property failed";
6755 break;
6756
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006757 case FK_TooManyInitsForScalar:
6758 OS << "too many initializers for scalar";
6759 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006760
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006761 case FK_ReferenceBindingToInitList:
6762 OS << "referencing binding to initializer list";
6763 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006764
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006765 case FK_InitListBadDestinationType:
6766 OS << "initializer list for non-aggregate, non-scalar type";
6767 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006768
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006769 case FK_UserConversionOverloadFailed:
6770 OS << "overloading failed for user-defined conversion";
6771 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006772
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006773 case FK_ConstructorOverloadFailed:
6774 OS << "constructor overloading failed";
6775 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006776
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006777 case FK_DefaultInitOfConst:
6778 OS << "default initialization of a const variable";
6779 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006780
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00006781 case FK_Incomplete:
6782 OS << "initialization of incomplete type";
6783 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006784
6785 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006786 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00006787 break;
6788
John McCalla59dc2f2012-01-05 00:13:19 +00006789 case FK_VariableLengthArrayHasInitializer:
6790 OS << "variable length array has an initializer";
6791 break;
6792
John McCall4124c492011-10-17 18:40:02 +00006793 case FK_PlaceholderType:
6794 OS << "initializer expression isn't contextually valid";
6795 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00006796
6797 case FK_ListConstructorOverloadFailed:
6798 OS << "list constructor overloading failed";
6799 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006800
Sebastian Redl048a6d72012-04-01 19:54:59 +00006801 case FK_ExplicitConstructor:
6802 OS << "list copy initialization chose explicit constructor";
6803 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006804 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006805 OS << '\n';
6806 return;
6807 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006808
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006809 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00006810 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006811 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006812
Sebastian Redld201edf2011-06-05 13:59:11 +00006813 case NormalSequence:
6814 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006815 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006816 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006817
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006818 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6819 if (S != step_begin()) {
6820 OS << " -> ";
6821 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006822
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006823 switch (S->Kind) {
6824 case SK_ResolveAddressOfOverloadedFunction:
6825 OS << "resolve address of overloaded function";
6826 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006827
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006828 case SK_CastDerivedToBaseRValue:
6829 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6830 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006831
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006832 case SK_CastDerivedToBaseXValue:
6833 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6834 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006835
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006836 case SK_CastDerivedToBaseLValue:
6837 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6838 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006839
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006840 case SK_BindReference:
6841 OS << "bind reference to lvalue";
6842 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006843
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006844 case SK_BindReferenceToTemporary:
6845 OS << "bind reference to a temporary";
6846 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006847
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006848 case SK_ExtraneousCopyToTemporary:
6849 OS << "extraneous C++03 copy to temporary";
6850 break;
6851
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006852 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00006853 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006854 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006855
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006856 case SK_QualificationConversionRValue:
6857 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00006858 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006859
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006860 case SK_QualificationConversionXValue:
6861 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00006862 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006863
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006864 case SK_QualificationConversionLValue:
6865 OS << "qualification conversion (lvalue)";
6866 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006867
Jordan Roseb1312a52013-04-11 00:58:58 +00006868 case SK_LValueToRValue:
6869 OS << "load (lvalue to rvalue)";
6870 break;
6871
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006872 case SK_ConversionSequence:
6873 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00006874 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006875 OS << ")";
6876 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006877
Richard Smithaaa0ec42013-09-21 21:19:19 +00006878 case SK_ConversionSequenceNoNarrowing:
6879 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00006880 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00006881 OS << ")";
6882 break;
6883
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006884 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006885 OS << "list aggregate initialization";
6886 break;
6887
6888 case SK_ListConstructorCall:
6889 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006890 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006891
Sebastian Redl29526f02011-11-27 16:50:07 +00006892 case SK_UnwrapInitList:
6893 OS << "unwrap reference initializer list";
6894 break;
6895
6896 case SK_RewrapInitList:
6897 OS << "rewrap reference initializer list";
6898 break;
6899
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006900 case SK_ConstructorInitialization:
6901 OS << "constructor initialization";
6902 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006903
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006904 case SK_ZeroInitialization:
6905 OS << "zero initialization";
6906 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006907
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006908 case SK_CAssignment:
6909 OS << "C assignment";
6910 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006911
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006912 case SK_StringInit:
6913 OS << "string initialization";
6914 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006915
6916 case SK_ObjCObjectConversion:
6917 OS << "Objective-C object conversion";
6918 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006919
6920 case SK_ArrayInit:
6921 OS << "array initialization";
6922 break;
John McCall31168b02011-06-15 23:02:42 +00006923
Richard Smithebeed412012-02-15 22:38:09 +00006924 case SK_ParenthesizedArrayInit:
6925 OS << "parenthesized array initialization";
6926 break;
6927
John McCall31168b02011-06-15 23:02:42 +00006928 case SK_PassByIndirectCopyRestore:
6929 OS << "pass by indirect copy and restore";
6930 break;
6931
6932 case SK_PassByIndirectRestore:
6933 OS << "pass by indirect restore";
6934 break;
6935
6936 case SK_ProduceObjCObject:
6937 OS << "Objective-C object retension";
6938 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006939
6940 case SK_StdInitializerList:
6941 OS << "std::initializer_list from initializer list";
6942 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006943
Guy Benyei61054192013-02-07 10:55:47 +00006944 case SK_OCLSamplerInit:
6945 OS << "OpenCL sampler_t from integer constant";
6946 break;
6947
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006948 case SK_OCLZeroEvent:
6949 OS << "OpenCL event_t from zero";
6950 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006951 }
Richard Smith6b216962013-02-05 05:52:24 +00006952
6953 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006954 }
Richard Smith6b216962013-02-05 05:52:24 +00006955
6956 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006957}
6958
6959void InitializationSequence::dump() const {
6960 dump(llvm::errs());
6961}
6962
Richard Smithaaa0ec42013-09-21 21:19:19 +00006963static void DiagnoseNarrowingInInitList(Sema &S,
6964 const ImplicitConversionSequence &ICS,
6965 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00006966 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00006967 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006968 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00006969 switch (ICS.getKind()) {
6970 case ImplicitConversionSequence::StandardConversion:
6971 SCS = &ICS.Standard;
6972 break;
6973 case ImplicitConversionSequence::UserDefinedConversion:
6974 SCS = &ICS.UserDefined.After;
6975 break;
6976 case ImplicitConversionSequence::AmbiguousConversion:
6977 case ImplicitConversionSequence::EllipsisConversion:
6978 case ImplicitConversionSequence::BadConversion:
6979 return;
6980 }
6981
Richard Smith66e05fe2012-01-18 05:21:49 +00006982 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6983 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00006984 QualType ConstantType;
6985 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6986 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00006987 case NK_Not_Narrowing:
6988 // No narrowing occurred.
6989 return;
6990
6991 case NK_Type_Narrowing:
6992 // This was a floating-to-integer conversion, which is always considered a
6993 // narrowing conversion even if the value is a constant and can be
6994 // represented exactly as an integer.
6995 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00006996 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
6997 ? diag::warn_init_list_type_narrowing
6998 : diag::ext_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00006999 << PostInit->getSourceRange()
7000 << PreNarrowingType.getLocalUnqualifiedType()
7001 << EntityType.getLocalUnqualifiedType();
7002 break;
7003
7004 case NK_Constant_Narrowing:
7005 // A constant value was narrowed.
7006 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007007 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7008 ? diag::warn_init_list_constant_narrowing
7009 : diag::ext_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007010 << PostInit->getSourceRange()
Richard Smith5614ca72012-03-23 23:55:39 +00007011 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007012 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007013 break;
7014
7015 case NK_Variable_Narrowing:
7016 // A variable's value may have been narrowed.
7017 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007018 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7019 ? diag::warn_init_list_variable_narrowing
7020 : diag::ext_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007021 << PostInit->getSourceRange()
7022 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007023 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007024 break;
7025 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007026
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007027 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007028 llvm::raw_svector_ostream OS(StaticCast);
7029 OS << "static_cast<";
7030 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7031 // It's important to use the typedef's name if there is one so that the
7032 // fixit doesn't break code using types like int64_t.
7033 //
7034 // FIXME: This will break if the typedef requires qualification. But
7035 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007036 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007037 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00007038 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007039 else {
7040 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
7041 // with a broken cast.
7042 return;
7043 }
7044 OS << ">(";
Alp Tokerb0869032014-05-17 01:13:18 +00007045 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007046 << PostInit->getSourceRange()
7047 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
7048 << FixItHint::CreateInsertion(
7049 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007050}
7051
Douglas Gregore1314a62009-12-18 05:02:21 +00007052//===----------------------------------------------------------------------===//
7053// Initialization helper functions
7054//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00007055bool
7056Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7057 ExprResult Init) {
7058 if (Init.isInvalid())
7059 return false;
7060
7061 Expr *InitE = Init.get();
7062 assert(InitE && "No initialization expression");
7063
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00007064 InitializationKind Kind
7065 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007066 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00007067 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00007068}
7069
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007070ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00007071Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7072 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007073 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00007074 bool TopLevelOfInitList,
7075 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00007076 if (Init.isInvalid())
7077 return ExprError();
7078
John McCall1f425642010-11-11 03:21:53 +00007079 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00007080 assert(InitE && "No initialization expression?");
7081
7082 if (EqualLoc.isInvalid())
7083 EqualLoc = InitE->getLocStart();
7084
7085 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00007086 EqualLoc,
7087 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00007088 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007089 Init.get();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007090
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007091 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00007092
Richard Smith66e05fe2012-01-18 05:21:49 +00007093 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00007094}