blob: c6d9a544c4bae60a8ddabae540e40387b99a7afc [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"
James Molloy9eef2652014-06-20 14:35:13 +000020#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Sema/Designator.h"
22#include "clang/Sema/Lookup.h"
23#include "clang/Sema/SemaInternal.h"
Sebastian Redlc1839b12012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000028#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000029using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000030
Chris Lattner0cb78032009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000035/// \brief Check whether T is compatible with a wide character type (wchar_t,
36/// char16_t or char32_t).
37static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
38 if (Context.typesAreCompatible(Context.getWideCharType(), T))
39 return true;
40 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
41 return Context.typesAreCompatible(Context.Char16Ty, T) ||
42 Context.typesAreCompatible(Context.Char32Ty, T);
43 }
44 return false;
45}
46
47enum StringInitFailureKind {
48 SIF_None,
49 SIF_NarrowStringIntoWideChar,
50 SIF_WideStringIntoChar,
51 SIF_IncompatWideStringIntoWideChar,
52 SIF_Other
53};
54
55/// \brief Check whether the array of type AT can be initialized by the Init
56/// expression by means of string initialization. Returns SIF_None if so,
57/// otherwise returns a StringInitFailureKind that describes why the
58/// initialization would not work.
59static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
60 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000061 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000062 return SIF_Other;
Eli Friedman893abe42009-05-29 18:22:49 +000063
Chris Lattnera9196812009-02-26 23:26:43 +000064 // See if this is a string literal or @encode.
65 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000066
Chris Lattnera9196812009-02-26 23:26:43 +000067 // Handle @encode, which is a narrow string.
68 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000069 return SIF_None;
Chris Lattnera9196812009-02-26 23:26:43 +000070
71 // Otherwise we can only handle string literals.
72 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Craig Topperc3ec1492014-05-26 06:22:03 +000073 if (!SL)
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000074 return SIF_Other;
Eli Friedman42a84652009-05-31 10:54:53 +000075
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000076 const QualType ElemTy =
77 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
Douglas Gregorfb65e592011-07-27 05:40:30 +000078
79 switch (SL->getKind()) {
80 case StringLiteral::Ascii:
81 case StringLiteral::UTF8:
82 // char array can be initialized with a narrow string.
83 // Only allow char x[] = "foo"; not char x[] = L"foo";
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000084 if (ElemTy->isCharType())
85 return SIF_None;
86 if (IsWideCharCompatible(ElemTy, Context))
87 return SIF_NarrowStringIntoWideChar;
88 return SIF_Other;
89 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
90 // "An array with element type compatible with a qualified or unqualified
91 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
92 // string literal with the corresponding encoding prefix (L, u, or U,
93 // respectively), optionally enclosed in braces.
Douglas Gregorfb65e592011-07-27 05:40:30 +000094 case StringLiteral::UTF16:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000095 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
96 return SIF_None;
97 if (ElemTy->isCharType())
98 return SIF_WideStringIntoChar;
99 if (IsWideCharCompatible(ElemTy, Context))
100 return SIF_IncompatWideStringIntoWideChar;
101 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000102 case StringLiteral::UTF32:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000103 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
104 return SIF_None;
105 if (ElemTy->isCharType())
106 return SIF_WideStringIntoChar;
107 if (IsWideCharCompatible(ElemTy, Context))
108 return SIF_IncompatWideStringIntoWideChar;
109 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000110 case StringLiteral::Wide:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000111 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
112 return SIF_None;
113 if (ElemTy->isCharType())
114 return SIF_WideStringIntoChar;
115 if (IsWideCharCompatible(ElemTy, Context))
116 return SIF_IncompatWideStringIntoWideChar;
117 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000118 }
Mike Stump11289f42009-09-09 15:08:12 +0000119
Douglas Gregorfb65e592011-07-27 05:40:30 +0000120 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +0000121}
122
Hans Wennborg950f3182013-05-16 09:22:40 +0000123static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
124 ASTContext &Context) {
John McCall66884dd2011-02-21 07:22:22 +0000125 const ArrayType *arrayType = Context.getAsArrayType(declType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000126 if (!arrayType)
Hans Wennborg950f3182013-05-16 09:22:40 +0000127 return SIF_Other;
128 return IsStringInit(init, arrayType, Context);
John McCall66884dd2011-02-21 07:22:22 +0000129}
130
Richard Smith430c23b2013-05-05 16:40:13 +0000131/// Update the type of a string literal, including any surrounding parentheses,
132/// to match the type of the object which it is initializing.
133static void updateStringLiteralType(Expr *E, QualType Ty) {
Richard Smithd74b16062013-05-06 00:35:47 +0000134 while (true) {
Richard Smith430c23b2013-05-05 16:40:13 +0000135 E->setType(Ty);
Richard Smithd74b16062013-05-06 00:35:47 +0000136 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
137 break;
138 else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
139 E = PE->getSubExpr();
140 else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
141 E = UO->getSubExpr();
142 else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
143 E = GSE->getResultExpr();
144 else
145 llvm_unreachable("unexpected expr in string literal init");
Richard Smith430c23b2013-05-05 16:40:13 +0000146 }
Richard Smith430c23b2013-05-05 16:40:13 +0000147}
148
John McCall5decec92011-02-21 07:57:55 +0000149static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
150 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000151 // Get the length of the string as parsed.
Ben Langmuir577b3932015-01-26 19:04:10 +0000152 auto *ConstantArrayTy =
Ben Langmuir7b30f532015-01-26 20:01:17 +0000153 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
Ben Langmuir577b3932015-01-26 19:04:10 +0000154 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +0000155
Chris Lattner0cb78032009-02-24 22:27:37 +0000156 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000157 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000158 // being initialized to a string literal.
Benjamin Kramere0731772012-08-04 17:00:46 +0000159 llvm::APInt ConstVal(32, StrLength);
Chris Lattner0cb78032009-02-24 22:27:37 +0000160 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000161 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
162 ConstVal,
163 ArrayType::Normal, 0);
Richard Smith430c23b2013-05-05 16:40:13 +0000164 updateStringLiteralType(Str, DeclT);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000165 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000166 }
Mike Stump11289f42009-09-09 15:08:12 +0000167
Eli Friedman893abe42009-05-29 18:22:49 +0000168 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000169
Eli Friedman554eba92011-04-11 00:23:45 +0000170 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000171 // the size may be smaller or larger than the string we are initializing.
172 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000173 if (S.getLangOpts().CPlusPlus) {
Richard Smith430c23b2013-05-05 16:40:13 +0000174 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000175 // For Pascal strings it's OK to strip off the terminating null character,
176 // so the example below is valid:
177 //
178 // unsigned char a[2] = "\pa";
179 if (SL->isPascal())
180 StrLength--;
181 }
182
Eli Friedman554eba92011-04-11 00:23:45 +0000183 // [dcl.init.string]p2
184 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000185 S.Diag(Str->getLocStart(),
Eli Friedman554eba92011-04-11 00:23:45 +0000186 diag::err_initializer_string_for_char_array_too_long)
187 << Str->getSourceRange();
188 } else {
189 // C99 6.7.8p14.
190 if (StrLength-1 > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000191 S.Diag(Str->getLocStart(),
Richard Smith1b98ccc2014-07-19 01:39:17 +0000192 diag::ext_initializer_string_for_char_array_too_long)
Eli Friedman554eba92011-04-11 00:23:45 +0000193 << Str->getSourceRange();
194 }
Mike Stump11289f42009-09-09 15:08:12 +0000195
Eli Friedman893abe42009-05-29 18:22:49 +0000196 // Set the type to the actual size that we are initializing. If we have
197 // something like:
198 // char x[1] = "foo";
199 // then this will set the string literal's type to char[1].
Richard Smith430c23b2013-05-05 16:40:13 +0000200 updateStringLiteralType(Str, DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000201}
202
Chris Lattner0cb78032009-02-24 22:27:37 +0000203//===----------------------------------------------------------------------===//
204// Semantic checking for initializer lists.
205//===----------------------------------------------------------------------===//
206
Douglas Gregorcde232f2009-01-29 01:05:33 +0000207/// @brief Semantic checking for initializer lists.
208///
209/// The InitListChecker class contains a set of routines that each
210/// handle the initialization of a certain kind of entity, e.g.,
211/// arrays, vectors, struct/union types, scalars, etc. The
212/// InitListChecker itself performs a recursive walk of the subobject
213/// structure of the type to be initialized, while stepping through
214/// the initializer list one element at a time. The IList and Index
215/// parameters to each of the Check* routines contain the active
216/// (syntactic) initializer list and the index into that initializer
217/// list that represents the current initializer. Each routine is
218/// responsible for moving that Index forward as it consumes elements.
219///
220/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000221/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000222/// initializer list and the index into that initializer list where we
223/// are copying initializers as we map them over to the semantic
224/// list. Once we have completed our recursive walk of the subobject
225/// structure, we will have constructed a full semantic initializer
226/// list.
227///
228/// C99 designators cause changes in the initializer list traversal,
229/// because they make the initialization "jump" into a specific
230/// subobject and then continue the initialization from that
231/// point. CheckDesignatedInitializer() recursively steps into the
232/// designated subobject and manages backing out the recursion to
233/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000234namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000235class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000236 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000237 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000238 bool VerifyOnly; // no diagnostics, no structure building
Benjamin Kramer6b441d62012-02-23 14:48:40 +0000239 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000240 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000241
Anders Carlsson6cabf312010-01-23 23:23:01 +0000242 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000243 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000244 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000245 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000246 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000247 InitListExpr *IList, QualType &T,
Richard Smith4e0d2e42013-09-20 20:10:22 +0000248 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000249 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000250 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000251 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000252 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000253 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000254 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000255 unsigned &StructuredIndex,
256 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000257 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000258 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000259 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000260 InitListExpr *StructuredList,
261 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000262 void CheckComplexType(const InitializedEntity &Entity,
263 InitListExpr *IList, QualType DeclType,
264 unsigned &Index,
265 InitListExpr *StructuredList,
266 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000267 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000268 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000269 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000270 InitListExpr *StructuredList,
271 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000272 void CheckReferenceType(const InitializedEntity &Entity,
273 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000274 unsigned &Index,
275 InitListExpr *StructuredList,
276 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000277 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000278 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000279 InitListExpr *StructuredList,
280 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000281 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000282 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000283 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000284 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000285 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000286 unsigned &StructuredIndex,
287 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000288 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000289 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000290 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000291 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000292 InitListExpr *StructuredList,
293 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000294 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000295 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000296 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000297 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000298 RecordDecl::field_iterator *NextField,
299 llvm::APSInt *NextElementIndex,
300 unsigned &Index,
301 InitListExpr *StructuredList,
302 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000303 bool FinishSubobjectInit,
304 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000305 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
306 QualType CurrentObjectType,
307 InitListExpr *StructuredList,
308 unsigned StructuredIndex,
309 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000310 void UpdateStructuredListElement(InitListExpr *StructuredList,
311 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000312 Expr *expr);
313 int numArrayElements(QualType DeclType);
314 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000315
Richard Smith454a7cd2014-06-03 08:26:00 +0000316 static ExprResult PerformEmptyInit(Sema &SemaRef,
317 SourceLocation Loc,
318 const InitializedEntity &Entity,
319 bool VerifyOnly);
320 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000321 const InitializedEntity &ParentEntity,
322 InitListExpr *ILE, bool &RequiresSecondPass);
Richard Smith454a7cd2014-06-03 08:26:00 +0000323 void FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000324 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000325 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
326 Expr *InitExpr, FieldDecl *Field,
327 bool TopLevelObject);
Richard Smith454a7cd2014-06-03 08:26:00 +0000328 void CheckEmptyInitializable(const InitializedEntity &Entity,
329 SourceLocation Loc);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000330
Douglas Gregor85df8d82009-01-29 00:45:39 +0000331public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000332 InitListChecker(Sema &S, const InitializedEntity &Entity,
Richard Smithde229232013-06-06 11:41:05 +0000333 InitListExpr *IL, QualType &T, bool VerifyOnly);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000334 bool HadError() { return hadError; }
335
336 // @brief Retrieves the fully-structured initializer list used for
337 // semantic analysis and code generation.
338 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
339};
Chris Lattner9ececce2009-02-24 22:48:58 +0000340} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000341
Richard Smith454a7cd2014-06-03 08:26:00 +0000342ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
343 SourceLocation Loc,
344 const InitializedEntity &Entity,
345 bool VerifyOnly) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000346 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
347 true);
Richard Smith454a7cd2014-06-03 08:26:00 +0000348 MultiExprArg SubInit;
349 Expr *InitExpr;
350 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
351
352 // C++ [dcl.init.aggr]p7:
353 // If there are fewer initializer-clauses in the list than there are
354 // members in the aggregate, then each member not explicitly initialized
355 // ...
Nico Weberbcb70ee2014-07-02 23:51:09 +0000356 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
357 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
358 if (EmptyInitList) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000359 // C++1y / DR1070:
360 // shall be initialized [...] from an empty initializer list.
361 //
362 // We apply the resolution of this DR to C++11 but not C++98, since C++98
363 // does not have useful semantics for initialization from an init list.
364 // We treat this as copy-initialization, because aggregate initialization
365 // always performs copy-initialization on its elements.
366 //
367 // Only do this if we're initializing a class type, to avoid filling in
368 // the initializer list where possible.
369 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
370 InitListExpr(SemaRef.Context, Loc, None, Loc);
371 InitExpr->setType(SemaRef.Context.VoidTy);
372 SubInit = InitExpr;
373 Kind = InitializationKind::CreateCopy(Loc, Loc);
374 } else {
375 // C++03:
376 // shall be value-initialized.
377 }
378
379 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000380 // libstdc++4.6 marks the vector default constructor as explicit in
381 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
382 // stlport does so too. Look for std::__debug for libstdc++, and for
383 // std:: for stlport. This is effectively a compiler-side implementation of
384 // LWG2193.
385 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
386 InitializationSequence::FK_ExplicitConstructor) {
387 OverloadCandidateSet::iterator Best;
388 OverloadingResult O =
389 InitSeq.getFailedCandidateSet()
390 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
391 (void)O;
392 assert(O == OR_Success && "Inconsistent overload resolution");
393 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
394 CXXRecordDecl *R = CtorDecl->getParent();
395
396 if (CtorDecl->getMinRequiredArguments() == 0 &&
397 CtorDecl->isExplicit() && R->getDeclName() &&
398 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
399
400
401 bool IsInStd = false;
402 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
Nico Weber5752ad02014-07-03 00:38:25 +0000403 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000404 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
405 IsInStd = true;
406 }
407
408 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
409 .Cases("basic_string", "deque", "forward_list", true)
410 .Cases("list", "map", "multimap", "multiset", true)
411 .Cases("priority_queue", "queue", "set", "stack", true)
412 .Cases("unordered_map", "unordered_set", "vector", true)
413 .Default(false)) {
414 InitSeq.InitializeFrom(
415 SemaRef, Entity,
416 InitializationKind::CreateValue(Loc, Loc, Loc, true),
417 MultiExprArg(), /*TopLevelOfInitList=*/false);
418 // Emit a warning for this. System header warnings aren't shown
419 // by default, but people working on system headers should see it.
420 if (!VerifyOnly) {
421 SemaRef.Diag(CtorDecl->getLocation(),
422 diag::warn_invalid_initializer_from_system_header);
423 SemaRef.Diag(Entity.getDecl()->getLocation(),
424 diag::note_used_in_initialization_here);
425 }
426 }
427 }
428 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000429 if (!InitSeq) {
430 if (!VerifyOnly) {
431 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
432 if (Entity.getKind() == InitializedEntity::EK_Member)
433 SemaRef.Diag(Entity.getDecl()->getLocation(),
434 diag::note_in_omitted_aggregate_initializer)
435 << /*field*/1 << Entity.getDecl();
436 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
437 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
438 << /*array element*/0 << Entity.getElementIndex();
439 }
440 return ExprError();
441 }
442
443 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
444 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
445}
446
447void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
448 SourceLocation Loc) {
449 assert(VerifyOnly &&
450 "CheckEmptyInitializable is only inteded for verification mode.");
451 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true).isInvalid())
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000452 hadError = true;
453}
454
Richard Smith454a7cd2014-06-03 08:26:00 +0000455void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000456 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000457 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000458 bool &RequiresSecondPass) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000459 SourceLocation Loc = ILE->getLocEnd();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000460 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000461 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000462 = InitializedEntity::InitializeMember(Field, &ParentEntity);
463 if (Init >= NumInits || !ILE->getInit(Init)) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000464 // C++1y [dcl.init.aggr]p7:
465 // If there are fewer initializer-clauses in the list than there are
466 // members in the aggregate, then each member not explicitly initialized
467 // shall be initialized from its brace-or-equal-initializer [...]
Richard Smith852c9db2013-04-20 22:23:05 +0000468 if (Field->hasInClassInitializer()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000469 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
470 if (DIE.isInvalid()) {
471 hadError = true;
472 return;
473 }
Richard Smith852c9db2013-04-20 22:23:05 +0000474 if (Init < NumInits)
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000475 ILE->setInit(Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000476 else {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000477 ILE->updateInit(SemaRef.Context, Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000478 RequiresSecondPass = true;
479 }
480 return;
481 }
482
Douglas Gregor2bb07652009-12-22 00:05:34 +0000483 if (Field->getType()->isReferenceType()) {
484 // C++ [dcl.init.aggr]p9:
485 // If an incomplete or empty initializer-list leaves a
486 // member of reference type uninitialized, the program is
487 // ill-formed.
488 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
489 << Field->getType()
490 << ILE->getSyntacticForm()->getSourceRange();
491 SemaRef.Diag(Field->getLocation(),
492 diag::note_uninit_reference_member);
493 hadError = true;
494 return;
495 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000496
Richard Smith454a7cd2014-06-03 08:26:00 +0000497 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
498 /*VerifyOnly*/false);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000499 if (MemberInit.isInvalid()) {
500 hadError = true;
501 return;
502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000503
Douglas Gregor2bb07652009-12-22 00:05:34 +0000504 if (hadError) {
505 // Do nothing
506 } else if (Init < NumInits) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000507 ILE->setInit(Init, MemberInit.getAs<Expr>());
Richard Smith454a7cd2014-06-03 08:26:00 +0000508 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
509 // Empty initialization requires a constructor call, so
Douglas Gregor2bb07652009-12-22 00:05:34 +0000510 // extend the initializer list to include the constructor
511 // call and make a note that we'll need to take another pass
512 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000513 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000514 RequiresSecondPass = true;
515 }
516 } else if (InitListExpr *InnerILE
517 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Richard Smith454a7cd2014-06-03 08:26:00 +0000518 FillInEmptyInitializations(MemberEntity, InnerILE,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000519 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000520}
521
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000522/// Recursively replaces NULL values within the given initializer list
523/// with expressions that perform value-initialization of the
524/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000525void
Richard Smith454a7cd2014-06-03 08:26:00 +0000526InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000527 InitListExpr *ILE,
528 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000529 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000530 "Should not have void type");
Mike Stump11289f42009-09-09 15:08:12 +0000531
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000532 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000533 const RecordDecl *RDecl = RType->getDecl();
534 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Richard Smith454a7cd2014-06-03 08:26:00 +0000535 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Douglas Gregor2bb07652009-12-22 00:05:34 +0000536 Entity, ILE, RequiresSecondPass);
Richard Smith852c9db2013-04-20 22:23:05 +0000537 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
538 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000539 for (auto *Field : RDecl->fields()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000540 if (Field->hasInClassInitializer()) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000541 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass);
Richard Smith852c9db2013-04-20 22:23:05 +0000542 break;
543 }
544 }
545 } else {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000546 unsigned Init = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000547 for (auto *Field : RDecl->fields()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000548 if (Field->isUnnamedBitfield())
549 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000550
Douglas Gregor2bb07652009-12-22 00:05:34 +0000551 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000552 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000553
Richard Smith454a7cd2014-06-03 08:26:00 +0000554 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000555 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000556 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000557
Douglas Gregor2bb07652009-12-22 00:05:34 +0000558 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000559
Douglas Gregor2bb07652009-12-22 00:05:34 +0000560 // Only look at the first initialization of a union.
Richard Smith852c9db2013-04-20 22:23:05 +0000561 if (RDecl->isUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000562 break;
563 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000564 }
565
566 return;
Mike Stump11289f42009-09-09 15:08:12 +0000567 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000568
569 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000570
Douglas Gregor723796a2009-12-16 06:35:08 +0000571 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000572 unsigned NumInits = ILE->getNumInits();
573 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000574 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000575 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000576 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
577 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000578 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000579 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000580 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000581 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000582 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000584 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000585 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000586 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000587
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000588 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000589 if (hadError)
590 return;
591
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000592 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
593 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000594 ElementEntity.setElementIndex(Init);
595
Craig Topperc3ec1492014-05-26 06:22:03 +0000596 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000597 if (!InitExpr && !ILE->hasArrayFiller()) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000598 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
599 ElementEntity,
600 /*VerifyOnly*/false);
Douglas Gregor723796a2009-12-16 06:35:08 +0000601 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000602 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000603 return;
604 }
605
606 if (hadError) {
607 // Do nothing
608 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000609 // For arrays, just set the expression used for value-initialization
610 // of the "holes" in the array.
611 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000612 ILE->setArrayFiller(ElementInit.getAs<Expr>());
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000613 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000614 ILE->setInit(Init, ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000615 } else {
616 // For arrays, just set the expression used for value-initialization
617 // of the rest of elements and exit.
618 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000619 ILE->setArrayFiller(ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000620 return;
621 }
622
Richard Smith454a7cd2014-06-03 08:26:00 +0000623 if (!isa<ImplicitValueInitExpr>(ElementInit.get())) {
624 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000625 // extend the initializer list to include the constructor
626 // call and make a note that we'll need to take another pass
627 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000628 ILE->updateInit(SemaRef.Context, Init, ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000629 RequiresSecondPass = true;
630 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000631 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000632 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000633 = dyn_cast_or_null<InitListExpr>(InitExpr))
Richard Smith454a7cd2014-06-03 08:26:00 +0000634 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000635 }
636}
637
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000638
Douglas Gregor723796a2009-12-16 06:35:08 +0000639InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000640 InitListExpr *IL, QualType &T,
Richard Smithde229232013-06-06 11:41:05 +0000641 bool VerifyOnly)
642 : SemaRef(S), VerifyOnly(VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000643 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000644
Richard Smith4e0d2e42013-09-20 20:10:22 +0000645 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000646 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000647 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000648 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000649
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000650 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000651 bool RequiresSecondPass = false;
Richard Smith454a7cd2014-06-03 08:26:00 +0000652 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000653 if (RequiresSecondPass && !hadError)
Richard Smith454a7cd2014-06-03 08:26:00 +0000654 FillInEmptyInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000655 RequiresSecondPass);
656 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000657}
658
659int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000660 // FIXME: use a proper constant
661 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000662 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000663 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000664 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
665 }
666 return maxElements;
667}
668
669int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000670 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000671 int InitializableMembers = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000672 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000673 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000674 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000675
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000676 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000677 return std::min(InitializableMembers, 1);
678 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000679}
680
Richard Smith4e0d2e42013-09-20 20:10:22 +0000681/// Check whether the range of the initializer \p ParentIList from element
682/// \p Index onwards can be used to initialize an object of type \p T. Update
683/// \p Index to indicate how many elements of the list were consumed.
684///
685/// This also fills in \p StructuredList, from element \p StructuredIndex
686/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000687void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000688 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000689 QualType T, unsigned &Index,
690 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000691 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000692 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000693
Steve Narofff8ecff22008-05-01 22:18:59 +0000694 if (T->isArrayType())
695 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000696 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000697 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000698 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000699 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000700 else
David Blaikie83d382b2011-09-23 05:06:16 +0000701 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000702
Eli Friedmane0f832b2008-05-25 13:49:22 +0000703 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000704 if (!VerifyOnly)
705 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
706 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000707 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000708 hadError = true;
709 return;
710 }
711
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000712 // Build a structured initializer list corresponding to this subobject.
713 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000714 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
715 StructuredIndex,
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000716 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregor5741efb2009-03-01 17:12:46 +0000717 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000718 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000719
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000720 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000721 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000722 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000723 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000724 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000725 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000726
Richard Smithde229232013-06-06 11:41:05 +0000727 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000728 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000729
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000730 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000731 // Update the structured sub-object initializer so that it's ending
732 // range corresponds with the end of the last initializer it used.
733 if (EndIndex < ParentIList->getNumInits()) {
734 SourceLocation EndLoc
735 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
736 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
737 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000738
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000739 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000740 if (T->isArrayType() || T->isRecordType()) {
741 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smithde229232013-06-06 11:41:05 +0000742 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000743 << StructuredSubobjectInitList->getSourceRange()
744 << FixItHint::CreateInsertion(
745 StructuredSubobjectInitList->getLocStart(), "{")
746 << FixItHint::CreateInsertion(
747 SemaRef.getLocForEndOfToken(
748 StructuredSubobjectInitList->getLocEnd()),
749 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000750 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000751 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000752}
753
Richard Smith4e0d2e42013-09-20 20:10:22 +0000754/// Check whether the initializer \p IList (that was written with explicit
755/// braces) can be used to initialize an object of type \p T.
756///
757/// This also fills in \p StructuredList with the fully-braced, desugared
758/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000759void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000760 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000761 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000762 bool TopLevelObject) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000763 if (!VerifyOnly) {
764 SyntacticToSemantic[IList] = StructuredList;
765 StructuredList->setSyntacticForm(IList);
766 }
Richard Smith4e0d2e42013-09-20 20:10:22 +0000767
768 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000769 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000770 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000771 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +0000772 QualType ExprTy = T;
773 if (!ExprTy->isArrayType())
774 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000775 IList->setType(ExprTy);
776 StructuredList->setType(ExprTy);
777 }
Eli Friedman85f54972008-05-25 13:22:35 +0000778 if (hadError)
779 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000780
Eli Friedman85f54972008-05-25 13:22:35 +0000781 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000782 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000783 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000784 if (SemaRef.getLangOpts().CPlusPlus ||
785 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000786 IList->getType()->isVectorType())) {
787 hadError = true;
788 }
789 return;
790 }
791
Eli Friedmanbd327452009-05-29 20:20:05 +0000792 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +0000793 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
794 SIF_None) {
Richard Smith1b98ccc2014-07-19 01:39:17 +0000795 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000796 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000797 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000798 hadError = true;
799 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000800 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000801 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000802 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000803 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000804 // Don't complain for incomplete types, since we'll get an error
805 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000806 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000807 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000808 CurrentObjectType->isArrayType()? 0 :
809 CurrentObjectType->isVectorType()? 1 :
810 CurrentObjectType->isScalarType()? 2 :
811 CurrentObjectType->isUnionType()? 3 :
812 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000813
Richard Smith1b98ccc2014-07-19 01:39:17 +0000814 unsigned DK = diag::ext_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000815 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +0000816 DK = diag::err_excess_initializers;
817 hadError = true;
818 }
David Blaikiebbafb8a2012-03-11 07:00:24 +0000819 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +0000820 DK = diag::err_excess_initializers;
821 hadError = true;
822 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000823
Chris Lattnerb0912a52009-02-24 22:50:46 +0000824 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000825 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000826 }
827 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000828
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000829 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
830 !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000831 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000832 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000833 << FixItHint::CreateRemoval(IList->getLocStart())
834 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000835}
836
Anders Carlsson6cabf312010-01-23 23:23:01 +0000837void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000838 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000839 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000840 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000841 unsigned &Index,
842 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000843 unsigned &StructuredIndex,
844 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000845 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
846 // Explicitly braced initializer for complex type can be real+imaginary
847 // parts.
848 CheckComplexType(Entity, IList, DeclType, Index,
849 StructuredList, StructuredIndex);
850 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000851 CheckScalarType(Entity, IList, DeclType, Index,
852 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000853 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000854 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000855 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +0000856 } else if (DeclType->isRecordType()) {
857 assert(DeclType->isAggregateType() &&
858 "non-aggregate records should be handed in CheckSubElementType");
859 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
860 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
861 SubobjectIsDesignatorContext, Index,
862 StructuredList, StructuredIndex,
863 TopLevelObject);
864 } else if (DeclType->isArrayType()) {
865 llvm::APSInt Zero(
866 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
867 false);
868 CheckArrayType(Entity, IList, DeclType, Zero,
869 SubobjectIsDesignatorContext, Index,
870 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +0000871 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
872 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000873 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000874 if (!VerifyOnly)
875 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
876 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000877 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000878 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000879 CheckReferenceType(Entity, IList, DeclType, Index,
880 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000881 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000882 if (!VerifyOnly)
883 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
884 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000885 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000886 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000887 if (!VerifyOnly)
888 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
889 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000890 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000891 }
892}
893
Anders Carlsson6cabf312010-01-23 23:23:01 +0000894void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000895 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000896 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000897 unsigned &Index,
898 InitListExpr *StructuredList,
899 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000900 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +0000901
902 if (ElemType->isReferenceType())
903 return CheckReferenceType(Entity, IList, ElemType, Index,
904 StructuredList, StructuredIndex);
905
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000906 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smithe20c83d2012-07-07 08:35:56 +0000907 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
Richard Smith4e0d2e42013-09-20 20:10:22 +0000908 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +0000909 = getStructuredSubobjectInit(IList, Index, ElemType,
910 StructuredList, StructuredIndex,
911 SubInitList->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000912 CheckExplicitInitList(Entity, SubInitList, ElemType,
913 InnerStructuredList);
Richard Smithe20c83d2012-07-07 08:35:56 +0000914 ++StructuredIndex;
915 ++Index;
916 return;
917 }
918 assert(SemaRef.getLangOpts().CPlusPlus &&
919 "non-aggregate records are only possible in C++");
920 // C++ initialization is handled later.
Richard Smithc4158e862014-07-18 04:47:25 +0000921 } else if (isa<ImplicitValueInitExpr>(expr)) {
Richard Smith8aa561b2014-07-17 23:12:06 +0000922 // This happens during template instantiation when we see an InitListExpr
923 // that we've already checked once.
Richard Smithc4158e862014-07-18 04:47:25 +0000924 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
Richard Smith8aa561b2014-07-17 23:12:06 +0000925 "found implicit initialization for the wrong type");
926 if (!VerifyOnly)
927 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
928 ++Index;
929 return;
Richard Smithe20c83d2012-07-07 08:35:56 +0000930 }
931
Eli Friedman4628cf72013-08-19 22:12:56 +0000932 // FIXME: Need to handle atomic aggregate types with implicit init lists.
933 if (ElemType->isScalarType() || ElemType->isAtomicType())
John McCall5decec92011-02-21 07:57:55 +0000934 return CheckScalarType(Entity, IList, ElemType, Index,
935 StructuredList, StructuredIndex);
Anders Carlsson03068aa2009-08-27 17:18:13 +0000936
Eli Friedman4628cf72013-08-19 22:12:56 +0000937 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
938 ElemType->isArrayType()) && "Unexpected type");
939
John McCall5decec92011-02-21 07:57:55 +0000940 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
941 // arrayType can be incomplete if we're initializing a flexible
942 // array member. There's nothing we can do with the completed
943 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000944
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000945 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +0000946 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000947 CheckStringInit(expr, ElemType, arrayType, SemaRef);
948 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +0000949 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000950 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000951 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000952 }
John McCall5decec92011-02-21 07:57:55 +0000953
954 // Fall through for subaggregate initialization.
955
David Blaikiebbafb8a2012-03-11 07:00:24 +0000956 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCall5decec92011-02-21 07:57:55 +0000957 // C++ [dcl.init.aggr]p12:
958 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000959 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000960 // an initializer-list. If the initializer can initialize a
961 // member, the member is initialized. [...]
962
963 // FIXME: Better EqualLoc?
964 InitializationKind Kind =
965 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000966 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCall5decec92011-02-21 07:57:55 +0000967
968 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000969 if (!VerifyOnly) {
Richard Smith0f8ede12011-12-20 04:00:21 +0000970 ExprResult Result =
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000971 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smith0f8ede12011-12-20 04:00:21 +0000972 if (Result.isInvalid())
973 hadError = true;
John McCall5decec92011-02-21 07:57:55 +0000974
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000975 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000976 Result.getAs<Expr>());
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000977 }
John McCall5decec92011-02-21 07:57:55 +0000978 ++Index;
979 return;
980 }
981
982 // Fall through for subaggregate initialization
983 } else {
984 // C99 6.7.8p13:
985 //
986 // The initializer for a structure or union object that has
987 // automatic storage duration shall be either an initializer
988 // list as described below, or a single expression that has
989 // compatible structure or union type. In the latter case, the
990 // initial value of the object, including unnamed members, is
991 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000992 ExprResult ExprRes = expr;
John McCall5decec92011-02-21 07:57:55 +0000993 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000994 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
995 !VerifyOnly)
Eli Friedmanb2a8d462013-09-17 04:07:04 +0000996 != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +0000997 if (ExprRes.isInvalid())
998 hadError = true;
999 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001000 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001001 if (ExprRes.isInvalid())
1002 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +00001003 }
1004 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001005 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +00001006 ++Index;
1007 return;
1008 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001009 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +00001010 // Fall through for subaggregate initialization
1011 }
1012
1013 // C++ [dcl.init.aggr]p12:
1014 //
1015 // [...] Otherwise, if the member is itself a non-empty
1016 // subaggregate, brace elision is assumed and the initializer is
1017 // considered for the initialization of the first member of
1018 // the subaggregate.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001019 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00001020 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +00001021 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1022 StructuredIndex);
1023 ++StructuredIndex;
1024 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001025 if (!VerifyOnly) {
1026 // We cannot initialize this element, so let
1027 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001028 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001029 /*TopLevelOfInitList=*/true);
1030 }
John McCall5decec92011-02-21 07:57:55 +00001031 hadError = true;
1032 ++Index;
1033 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +00001034 }
Eli Friedman23a9e312008-05-19 19:16:24 +00001035}
1036
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001037void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1038 InitListExpr *IList, QualType DeclType,
1039 unsigned &Index,
1040 InitListExpr *StructuredList,
1041 unsigned &StructuredIndex) {
1042 assert(Index == 0 && "Index in explicit init list must be zero");
1043
1044 // As an extension, clang supports complex initializers, which initialize
1045 // a complex number component-wise. When an explicit initializer list for
1046 // a complex number contains two two initializers, this extension kicks in:
1047 // it exepcts the initializer list to contain two elements convertible to
1048 // the element type of the complex type. The first element initializes
1049 // the real part, and the second element intitializes the imaginary part.
1050
1051 if (IList->getNumInits() != 2)
1052 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1053 StructuredIndex);
1054
1055 // This is an extension in C. (The builtin _Complex type does not exist
1056 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001057 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001058 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1059 << IList->getSourceRange();
1060
1061 // Initialize the complex number.
1062 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1063 InitializedEntity ElementEntity =
1064 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1065
1066 for (unsigned i = 0; i < 2; ++i) {
1067 ElementEntity.setElementIndex(Index);
1068 CheckSubElementType(ElementEntity, IList, elementType, Index,
1069 StructuredList, StructuredIndex);
1070 }
1071}
1072
1073
Anders Carlsson6cabf312010-01-23 23:23:01 +00001074void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001075 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001076 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001077 InitListExpr *StructuredList,
1078 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001079 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001080 if (!VerifyOnly)
1081 SemaRef.Diag(IList->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001082 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smithc8239732011-10-18 21:39:00 +00001083 diag::warn_cxx98_compat_empty_scalar_initializer :
1084 diag::err_empty_scalar_initializer)
1085 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001086 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001087 ++Index;
1088 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001089 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001090 }
John McCall643169b2010-11-11 00:46:36 +00001091
1092 Expr *expr = IList->getInit(Index);
1093 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001094 // FIXME: This is invalid, and accepting it causes overload resolution
1095 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001096 if (!VerifyOnly)
1097 SemaRef.Diag(SubIList->getLocStart(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001098 diag::ext_many_braces_around_scalar_init)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001099 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001100
1101 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1102 StructuredIndex);
1103 return;
1104 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001105 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001106 SemaRef.Diag(expr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001107 diag::err_designator_for_scalar_init)
1108 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001109 hadError = true;
1110 ++Index;
1111 ++StructuredIndex;
1112 return;
1113 }
1114
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001115 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001116 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001117 hadError = true;
1118 ++Index;
1119 return;
1120 }
1121
John McCall643169b2010-11-11 00:46:36 +00001122 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001123 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001124 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001125
Craig Topperc3ec1492014-05-26 06:22:03 +00001126 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001127
1128 if (Result.isInvalid())
1129 hadError = true; // types weren't compatible.
1130 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001131 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001132
John McCall643169b2010-11-11 00:46:36 +00001133 if (ResultExpr != expr) {
1134 // The type was promoted, update initializer list.
1135 IList->setInit(Index, ResultExpr);
1136 }
1137 }
1138 if (hadError)
1139 ++StructuredIndex;
1140 else
1141 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1142 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001143}
1144
Anders Carlsson6cabf312010-01-23 23:23:01 +00001145void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1146 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001147 unsigned &Index,
1148 InitListExpr *StructuredList,
1149 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001150 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001151 // FIXME: It would be wonderful if we could point at the actual member. In
1152 // general, it would be useful to pass location information down the stack,
1153 // so that we know the location (or decl) of the "current object" being
1154 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001155 if (!VerifyOnly)
1156 SemaRef.Diag(IList->getLocStart(),
1157 diag::err_init_reference_member_uninitialized)
1158 << DeclType
1159 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001160 hadError = true;
1161 ++Index;
1162 ++StructuredIndex;
1163 return;
1164 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001165
1166 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001167 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001168 if (!VerifyOnly)
1169 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1170 << DeclType << IList->getSourceRange();
1171 hadError = true;
1172 ++Index;
1173 ++StructuredIndex;
1174 return;
1175 }
1176
1177 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001178 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001179 hadError = true;
1180 ++Index;
1181 return;
1182 }
1183
1184 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001185 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1186 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001187
1188 if (Result.isInvalid())
1189 hadError = true;
1190
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001191 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001192 IList->setInit(Index, expr);
1193
1194 if (hadError)
1195 ++StructuredIndex;
1196 else
1197 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1198 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001199}
1200
Anders Carlsson6cabf312010-01-23 23:23:01 +00001201void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001202 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001203 unsigned &Index,
1204 InitListExpr *StructuredList,
1205 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001206 const VectorType *VT = DeclType->getAs<VectorType>();
1207 unsigned maxElements = VT->getNumElements();
1208 unsigned numEltsInit = 0;
1209 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001210
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001211 if (Index >= IList->getNumInits()) {
1212 // Make sure the element type can be value-initialized.
1213 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001214 CheckEmptyInitializable(
1215 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1216 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001217 return;
1218 }
1219
David Blaikiebbafb8a2012-03-11 07:00:24 +00001220 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001221 // If the initializing element is a vector, try to copy-initialize
1222 // instead of breaking it apart (which is doomed to failure anyway).
1223 Expr *Init = IList->getInit(Index);
1224 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001225 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001226 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001227 hadError = true;
1228 ++Index;
1229 return;
1230 }
1231
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001232 ExprResult Result =
1233 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1234 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001235
Craig Topperc3ec1492014-05-26 06:22:03 +00001236 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001237 if (Result.isInvalid())
1238 hadError = true; // types weren't compatible.
1239 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001240 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001241
John McCall6a16b2f2010-10-30 00:11:39 +00001242 if (ResultExpr != Init) {
1243 // The type was promoted, update initializer list.
1244 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001245 }
1246 }
John McCall6a16b2f2010-10-30 00:11:39 +00001247 if (hadError)
1248 ++StructuredIndex;
1249 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001250 UpdateStructuredListElement(StructuredList, StructuredIndex,
1251 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001252 ++Index;
1253 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001254 }
Mike Stump11289f42009-09-09 15:08:12 +00001255
John McCall6a16b2f2010-10-30 00:11:39 +00001256 InitializedEntity ElementEntity =
1257 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001258
John McCall6a16b2f2010-10-30 00:11:39 +00001259 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1260 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001261 if (Index >= IList->getNumInits()) {
1262 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001263 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
John McCall6a16b2f2010-10-30 00:11:39 +00001264 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001265 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001266
John McCall6a16b2f2010-10-30 00:11:39 +00001267 ElementEntity.setElementIndex(Index);
1268 CheckSubElementType(ElementEntity, IList, elementType, Index,
1269 StructuredList, StructuredIndex);
1270 }
James Molloy9eef2652014-06-20 14:35:13 +00001271
1272 if (VerifyOnly)
1273 return;
1274
1275 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1276 const VectorType *T = Entity.getType()->getAs<VectorType>();
1277 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1278 T->getVectorKind() == VectorType::NeonPolyVector)) {
1279 // The ability to use vector initializer lists is a GNU vector extension
1280 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1281 // endian machines it works fine, however on big endian machines it
1282 // exhibits surprising behaviour:
1283 //
1284 // uint32x2_t x = {42, 64};
1285 // return vget_lane_u32(x, 0); // Will return 64.
1286 //
1287 // Because of this, explicitly call out that it is non-portable.
1288 //
1289 SemaRef.Diag(IList->getLocStart(),
1290 diag::warn_neon_vector_initializer_non_portable);
1291
1292 const char *typeCode;
1293 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1294
1295 if (elementType->isFloatingType())
1296 typeCode = "f";
1297 else if (elementType->isSignedIntegerType())
1298 typeCode = "s";
1299 else if (elementType->isUnsignedIntegerType())
1300 typeCode = "u";
1301 else
1302 llvm_unreachable("Invalid element type!");
1303
1304 SemaRef.Diag(IList->getLocStart(),
1305 SemaRef.Context.getTypeSize(VT) > 64 ?
1306 diag::note_neon_vector_initializer_non_portable_q :
1307 diag::note_neon_vector_initializer_non_portable)
1308 << typeCode << typeSize;
1309 }
1310
John McCall6a16b2f2010-10-30 00:11:39 +00001311 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001312 }
John McCall6a16b2f2010-10-30 00:11:39 +00001313
1314 InitializedEntity ElementEntity =
1315 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001316
John McCall6a16b2f2010-10-30 00:11:39 +00001317 // OpenCL initializers allows vectors to be constructed from vectors.
1318 for (unsigned i = 0; i < maxElements; ++i) {
1319 // Don't attempt to go past the end of the init list
1320 if (Index >= IList->getNumInits())
1321 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001322
John McCall6a16b2f2010-10-30 00:11:39 +00001323 ElementEntity.setElementIndex(Index);
1324
1325 QualType IType = IList->getInit(Index)->getType();
1326 if (!IType->isVectorType()) {
1327 CheckSubElementType(ElementEntity, IList, elementType, Index,
1328 StructuredList, StructuredIndex);
1329 ++numEltsInit;
1330 } else {
1331 QualType VecType;
1332 const VectorType *IVT = IType->getAs<VectorType>();
1333 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001334
John McCall6a16b2f2010-10-30 00:11:39 +00001335 if (IType->isExtVectorType())
1336 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1337 else
1338 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001339 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001340 CheckSubElementType(ElementEntity, IList, VecType, Index,
1341 StructuredList, StructuredIndex);
1342 numEltsInit += numIElts;
1343 }
1344 }
1345
1346 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001347 if (numEltsInit != maxElements) {
1348 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001349 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001350 diag::err_vector_incorrect_num_initializers)
1351 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1352 hadError = true;
1353 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001354}
1355
Anders Carlsson6cabf312010-01-23 23:23:01 +00001356void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001357 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001358 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001359 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001360 unsigned &Index,
1361 InitListExpr *StructuredList,
1362 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001363 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1364
Steve Narofff8ecff22008-05-01 22:18:59 +00001365 // Check for the special-case of initializing an array with a string.
1366 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001367 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1368 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001369 // We place the string literal directly into the resulting
1370 // initializer list. This is the only place where the structure
1371 // of the structured initializer list doesn't match exactly,
1372 // because doing so would involve allocating one character
1373 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001374 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001375 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1376 UpdateStructuredListElement(StructuredList, StructuredIndex,
1377 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001378 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1379 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001380 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001381 return;
1382 }
1383 }
John McCall66884dd2011-02-21 07:22:22 +00001384 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001385 // Check for VLAs; in standard C it would be possible to check this
1386 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1387 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001388 if (!VerifyOnly)
1389 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1390 diag::err_variable_object_no_init)
1391 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001392 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001393 ++Index;
1394 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001395 return;
1396 }
1397
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001398 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001399 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1400 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001401 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001402 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001403 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001404 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001405 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001406 maxElementsKnown = true;
1407 }
1408
John McCall66884dd2011-02-21 07:22:22 +00001409 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001410 while (Index < IList->getNumInits()) {
1411 Expr *Init = IList->getInit(Index);
1412 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001413 // If we're not the subobject that matches up with the '{' for
1414 // the designator, we shouldn't be handling the
1415 // designator. Return immediately.
1416 if (!SubobjectIsDesignatorContext)
1417 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001418
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001419 // Handle this designated initializer. elementIndex will be
1420 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001421 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001422 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001423 StructuredList, StructuredIndex, true,
1424 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001425 hadError = true;
1426 continue;
1427 }
1428
Douglas Gregor033d1252009-01-23 16:54:12 +00001429 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001430 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001431 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001432 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001433 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001434
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001435 // If the array is of incomplete type, keep track of the number of
1436 // elements in the initializer.
1437 if (!maxElementsKnown && elementIndex > maxElements)
1438 maxElements = elementIndex;
1439
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001440 continue;
1441 }
1442
1443 // If we know the maximum number of elements, and we've already
1444 // hit it, stop consuming elements in the initializer list.
1445 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001446 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001447
Anders Carlsson6cabf312010-01-23 23:23:01 +00001448 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001449 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001450 Entity);
1451 // Check this element.
1452 CheckSubElementType(ElementEntity, IList, elementType, Index,
1453 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001454 ++elementIndex;
1455
1456 // If the array is of incomplete type, keep track of the number of
1457 // elements in the initializer.
1458 if (!maxElementsKnown && elementIndex > maxElements)
1459 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001460 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001461 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001462 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001463 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001464 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001465 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001466 // Sizing an array implicitly to zero is not allowed by ISO C,
1467 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001468 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001469 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001470 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001471
Mike Stump11289f42009-09-09 15:08:12 +00001472 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001473 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001474 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001475 if (!hadError && VerifyOnly) {
1476 // Check if there are any members of the array that get value-initialized.
1477 // If so, check if doing that is possible.
1478 // FIXME: This needs to detect holes left by designated initializers too.
1479 if (maxElementsKnown && elementIndex < maxElements)
Richard Smith454a7cd2014-06-03 08:26:00 +00001480 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1481 SemaRef.Context, 0, Entity),
1482 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001483 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001484}
1485
Eli Friedman3fa64df2011-08-23 22:24:57 +00001486bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1487 Expr *InitExpr,
1488 FieldDecl *Field,
1489 bool TopLevelObject) {
1490 // Handle GNU flexible array initializers.
1491 unsigned FlexArrayDiag;
1492 if (isa<InitListExpr>(InitExpr) &&
1493 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1494 // Empty flexible array init always allowed as an extension
1495 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001496 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001497 // Disallow flexible array init in C++; it is not required for gcc
1498 // compatibility, and it needs work to IRGen correctly in general.
1499 FlexArrayDiag = diag::err_flexible_array_init;
1500 } else if (!TopLevelObject) {
1501 // Disallow flexible array init on non-top-level object
1502 FlexArrayDiag = diag::err_flexible_array_init;
1503 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1504 // Disallow flexible array init on anything which is not a variable.
1505 FlexArrayDiag = diag::err_flexible_array_init;
1506 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1507 // Disallow flexible array init on local variables.
1508 FlexArrayDiag = diag::err_flexible_array_init;
1509 } else {
1510 // Allow other cases.
1511 FlexArrayDiag = diag::ext_flexible_array_init;
1512 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001513
1514 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001515 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001516 FlexArrayDiag)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001517 << InitExpr->getLocStart();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001518 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1519 << Field;
1520 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001521
1522 return FlexArrayDiag != diag::ext_flexible_array_init;
1523}
1524
Anders Carlsson6cabf312010-01-23 23:23:01 +00001525void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001526 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001527 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001528 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001529 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001530 unsigned &Index,
1531 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001532 unsigned &StructuredIndex,
1533 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001534 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001535
Eli Friedman23a9e312008-05-19 19:16:24 +00001536 // If the record is invalid, some of it's members are invalid. To avoid
1537 // confusion, we forgo checking the intializer for the entire record.
1538 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001539 // Assume it was supposed to consume a single initializer.
1540 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001541 hadError = true;
1542 return;
Mike Stump11289f42009-09-09 15:08:12 +00001543 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001544
1545 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001546 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001547
1548 // If there's a default initializer, use it.
1549 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1550 if (VerifyOnly)
1551 return;
1552 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1553 Field != FieldEnd; ++Field) {
1554 if (Field->hasInClassInitializer()) {
1555 StructuredList->setInitializedFieldInUnion(*Field);
1556 // FIXME: Actually build a CXXDefaultInitExpr?
1557 return;
1558 }
1559 }
1560 }
1561
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001562 // Value-initialize the first member of the union that isn't an unnamed
1563 // bitfield.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001564 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1565 Field != FieldEnd; ++Field) {
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001566 if (!Field->isUnnamedBitfield()) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001567 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001568 CheckEmptyInitializable(
1569 InitializedEntity::InitializeMember(*Field, &Entity),
1570 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001571 else
David Blaikie40ed2972012-06-06 20:45:41 +00001572 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001573 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001574 }
1575 }
1576 return;
1577 }
1578
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001579 // If structDecl is a forward declaration, this loop won't do
1580 // anything except look at designated initializers; That's okay,
1581 // because an error should get printed out elsewhere. It might be
1582 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001583 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001584 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001585 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001586 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001587 while (Index < IList->getNumInits()) {
1588 Expr *Init = IList->getInit(Index);
1589
1590 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001591 // If we're not the subobject that matches up with the '{' for
1592 // the designator, we shouldn't be handling the
1593 // designator. Return immediately.
1594 if (!SubobjectIsDesignatorContext)
1595 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001596
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001597 // Handle this designated initializer. Field will be updated to
1598 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001599 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001600 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001601 StructuredList, StructuredIndex,
1602 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001603 hadError = true;
1604
Douglas Gregora9add4e2009-02-12 19:00:39 +00001605 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001606
1607 // Disable check for missing fields when designators are used.
1608 // This matches gcc behaviour.
1609 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001610 continue;
1611 }
1612
1613 if (Field == FieldEnd) {
1614 // We've run out of fields. We're done.
1615 break;
1616 }
1617
Douglas Gregora9add4e2009-02-12 19:00:39 +00001618 // We've already initialized a member of a union. We're done.
1619 if (InitializedSomething && DeclType->isUnionType())
1620 break;
1621
Douglas Gregor91f84212008-12-11 16:49:14 +00001622 // If we've hit the flexible array member at the end, we're done.
1623 if (Field->getType()->isIncompleteArrayType())
1624 break;
1625
Douglas Gregor51695702009-01-29 16:53:55 +00001626 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001627 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001628 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001629 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001630 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001631
Douglas Gregora82064c2011-06-29 21:51:31 +00001632 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001633 bool InvalidUse;
1634 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00001635 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001636 else
David Blaikie40ed2972012-06-06 20:45:41 +00001637 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001638 IList->getInit(Index)->getLocStart());
1639 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001640 ++Index;
1641 ++Field;
1642 hadError = true;
1643 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001644 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001645
Anders Carlsson6cabf312010-01-23 23:23:01 +00001646 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001647 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001648 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1649 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001650 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001651
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001652 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001653 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00001654 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001655 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001656
1657 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001658 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001659
John McCalle40b58e2010-03-11 19:32:38 +00001660 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001661 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1662 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1663 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001664 // It is possible we have one or more unnamed bitfields remaining.
1665 // Find first (if any) named field and emit warning.
1666 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1667 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00001668 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00001669 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00001670 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00001671 break;
1672 }
1673 }
1674 }
1675
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001676 // Check that any remaining fields can be value-initialized.
1677 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1678 !Field->getType()->isIncompleteArrayType()) {
1679 // FIXME: Should check for holes left by designated initializers too.
1680 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00001681 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00001682 CheckEmptyInitializable(
1683 InitializedEntity::InitializeMember(*Field, &Entity),
1684 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001685 }
1686 }
1687
Mike Stump11289f42009-09-09 15:08:12 +00001688 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001689 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001690 return;
1691
David Blaikie40ed2972012-06-06 20:45:41 +00001692 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00001693 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001694 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001695 ++Index;
1696 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001697 }
1698
Anders Carlsson6cabf312010-01-23 23:23:01 +00001699 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001700 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001701
Anders Carlsson6cabf312010-01-23 23:23:01 +00001702 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001703 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001704 StructuredList, StructuredIndex);
1705 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001706 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001707 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001708}
Steve Narofff8ecff22008-05-01 22:18:59 +00001709
Douglas Gregord5846a12009-04-15 06:41:24 +00001710/// \brief Expand a field designator that refers to a member of an
1711/// anonymous struct or union into a series of field designators that
1712/// refers to the field within the appropriate subobject.
1713///
Douglas Gregord5846a12009-04-15 06:41:24 +00001714static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001715 DesignatedInitExpr *DIE,
1716 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001717 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001718 typedef DesignatedInitExpr::Designator Designator;
1719
Douglas Gregord5846a12009-04-15 06:41:24 +00001720 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001721 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001722 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1723 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1724 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00001725 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00001726 DIE->getDesignator(DesigIdx)->getDotLoc(),
1727 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1728 else
Craig Topperc3ec1492014-05-26 06:22:03 +00001729 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1730 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001731 assert(isa<FieldDecl>(*PI));
1732 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001733 }
1734
1735 // Expand the current designator into the set of replacement
1736 // designators, so we have a full subobject path down to where the
1737 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001738 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001739 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001740}
Mike Stump11289f42009-09-09 15:08:12 +00001741
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001742static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1743 DesignatedInitExpr *DIE) {
1744 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1745 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1746 for (unsigned I = 0; I < NumIndexExprs; ++I)
1747 IndexExprs[I] = DIE->getSubExpr(I + 1);
1748 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001749 DIE->size(), IndexExprs,
1750 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001751 DIE->usesGNUSyntax(), DIE->getInit());
1752}
1753
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001754namespace {
1755
1756// Callback to only accept typo corrections that are for field members of
1757// the given struct or union.
1758class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1759 public:
1760 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1761 : Record(RD) {}
1762
Craig Toppere14c0f82014-03-12 04:55:44 +00001763 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001764 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1765 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1766 }
1767
1768 private:
1769 RecordDecl *Record;
1770};
1771
1772}
1773
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001774/// @brief Check the well-formedness of a C99 designated initializer.
1775///
1776/// Determines whether the designated initializer @p DIE, which
1777/// resides at the given @p Index within the initializer list @p
1778/// IList, is well-formed for a current object of type @p DeclType
1779/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001780/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001781/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001782///
1783/// @param IList The initializer list in which this designated
1784/// initializer occurs.
1785///
Douglas Gregora5324162009-04-15 04:56:10 +00001786/// @param DIE The designated initializer expression.
1787///
1788/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001789///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00001790/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001791/// into which the designation in @p DIE should refer.
1792///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001793/// @param NextField If non-NULL and the first designator in @p DIE is
1794/// a field, this will be set to the field declaration corresponding
1795/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001796///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001797/// @param NextElementIndex If non-NULL and the first designator in @p
1798/// DIE is an array designator or GNU array-range designator, this
1799/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001800///
1801/// @param Index Index into @p IList where the designated initializer
1802/// @p DIE occurs.
1803///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001804/// @param StructuredList The initializer list expression that
1805/// describes all of the subobject initializers in the order they'll
1806/// actually be initialized.
1807///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001808/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001809bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001810InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001811 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001812 DesignatedInitExpr *DIE,
1813 unsigned DesigIdx,
1814 QualType &CurrentObjectType,
1815 RecordDecl::field_iterator *NextField,
1816 llvm::APSInt *NextElementIndex,
1817 unsigned &Index,
1818 InitListExpr *StructuredList,
1819 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001820 bool FinishSubobjectInit,
1821 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001822 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001823 // Check the actual initialization for the designated object type.
1824 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001825
1826 // Temporarily remove the designator expression from the
1827 // initializer list that the child calls see, so that we don't try
1828 // to re-process the designator.
1829 unsigned OldIndex = Index;
1830 IList->setInit(OldIndex, DIE->getInit());
1831
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001832 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001833 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001834
1835 // Restore the designated initializer expression in the syntactic
1836 // form of the initializer list.
1837 if (IList->getInit(OldIndex) != DIE->getInit())
1838 DIE->setInit(IList->getInit(OldIndex));
1839 IList->setInit(OldIndex, DIE);
1840
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001841 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001842 }
1843
Douglas Gregora5324162009-04-15 04:56:10 +00001844 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001845 bool IsFirstDesignator = (DesigIdx == 0);
1846 if (!VerifyOnly) {
1847 assert((IsFirstDesignator || StructuredList) &&
1848 "Need a non-designated initializer list to start from");
1849
1850 // Determine the structural initializer list that corresponds to the
1851 // current subobject.
Benjamin Kramer6b441d62012-02-23 14:48:40 +00001852 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001853 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1854 StructuredList, StructuredIndex,
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001855 SourceRange(D->getLocStart(),
1856 DIE->getLocEnd()));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001857 assert(StructuredList && "Expected a structured initializer list");
1858 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001859
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001860 if (D->isFieldDesignator()) {
1861 // C99 6.7.8p7:
1862 //
1863 // If a designator has the form
1864 //
1865 // . identifier
1866 //
1867 // then the current object (defined below) shall have
1868 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001869 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001870 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001871 if (!RT) {
1872 SourceLocation Loc = D->getDotLoc();
1873 if (Loc.isInvalid())
1874 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001875 if (!VerifyOnly)
1876 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001877 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001878 ++Index;
1879 return true;
1880 }
1881
Douglas Gregord5846a12009-04-15 06:41:24 +00001882 FieldDecl *KnownField = D->getField();
David Majnemer36ef8982014-08-11 18:33:59 +00001883 if (!KnownField) {
1884 IdentifierInfo *FieldName = D->getFieldName();
1885 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1886 for (NamedDecl *ND : Lookup) {
1887 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
1888 KnownField = FD;
1889 break;
1890 }
1891 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001892 // In verify mode, don't modify the original.
1893 if (VerifyOnly)
1894 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
David Majnemer36ef8982014-08-11 18:33:59 +00001895 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001896 D = DIE->getDesignator(DesigIdx);
David Majnemer36ef8982014-08-11 18:33:59 +00001897 KnownField = cast<FieldDecl>(*IFD->chain_begin());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001898 break;
1899 }
1900 }
David Majnemer36ef8982014-08-11 18:33:59 +00001901 if (!KnownField) {
1902 if (VerifyOnly) {
1903 ++Index;
1904 return true; // No typo correction when just trying this out.
1905 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001906
David Majnemer36ef8982014-08-11 18:33:59 +00001907 // Name lookup found something, but it wasn't a field.
1908 if (!Lookup.empty()) {
1909 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1910 << FieldName;
1911 SemaRef.Diag(Lookup.front()->getLocation(),
1912 diag::note_field_designator_found);
1913 ++Index;
1914 return true;
1915 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001916
David Majnemer36ef8982014-08-11 18:33:59 +00001917 // Name lookup didn't find anything.
1918 // Determine whether this was a typo for another field name.
Richard Smithf9b15102013-08-17 00:46:16 +00001919 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
1920 DeclarationNameInfo(FieldName, D->getFieldLoc()),
David Majnemer36ef8982014-08-11 18:33:59 +00001921 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001922 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
1923 Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00001924 SemaRef.diagnoseTypo(
1925 Corrected,
1926 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
David Majnemer36ef8982014-08-11 18:33:59 +00001927 << FieldName << CurrentObjectType);
1928 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001929 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001930 } else {
David Majnemer36ef8982014-08-11 18:33:59 +00001931 // Typo correction didn't find anything.
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001932 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1933 << FieldName << CurrentObjectType;
1934 ++Index;
1935 return true;
1936 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001937 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001938 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001939
David Majnemer58e4ea92014-08-23 01:48:50 +00001940 unsigned FieldIndex = 0;
1941 for (auto *FI : RT->getDecl()->fields()) {
1942 if (FI->isUnnamedBitfield())
1943 continue;
1944 if (KnownField == FI)
1945 break;
1946 ++FieldIndex;
1947 }
1948
David Majnemer36ef8982014-08-11 18:33:59 +00001949 RecordDecl::field_iterator Field =
1950 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
1951
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001952 // All of the fields of a union are located at the same place in
1953 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001954 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001955 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00001956 if (!VerifyOnly) {
1957 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
1958 if (CurrentField && CurrentField != *Field) {
1959 assert(StructuredList->getNumInits() == 1
1960 && "A union should never have more than one initializer!");
1961
1962 // we're about to throw away an initializer, emit warning
1963 SemaRef.Diag(D->getFieldLoc(),
1964 diag::warn_initializer_overrides)
1965 << D->getSourceRange();
1966 Expr *ExistingInit = StructuredList->getInit(0);
1967 SemaRef.Diag(ExistingInit->getLocStart(),
1968 diag::note_previous_initializer)
1969 << /*FIXME:has side effects=*/0
1970 << ExistingInit->getSourceRange();
1971
1972 // remove existing initializer
1973 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00001974 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00001975 }
1976
David Blaikie40ed2972012-06-06 20:45:41 +00001977 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00001978 }
Douglas Gregor51695702009-01-29 16:53:55 +00001979 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001980
Douglas Gregora82064c2011-06-29 21:51:31 +00001981 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001982 bool InvalidUse;
1983 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00001984 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001985 else
David Blaikie40ed2972012-06-06 20:45:41 +00001986 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001987 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001988 ++Index;
1989 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001990 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001991
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001992 if (!VerifyOnly) {
1993 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00001994 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001995
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001996 // Make sure that our non-designated initializer list has space
1997 // for a subobject corresponding to this field.
1998 if (FieldIndex >= StructuredList->getNumInits())
1999 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2000 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002001
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002002 // This designator names a flexible array member.
2003 if (Field->getType()->isIncompleteArrayType()) {
2004 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00002005 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002006 // We can't designate an object within the flexible array
2007 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002008 if (!VerifyOnly) {
2009 DesignatedInitExpr::Designator *NextD
2010 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002011 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002012 diag::err_designator_into_flexible_array_member)
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002013 << SourceRange(NextD->getLocStart(),
2014 DIE->getLocEnd());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002015 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002016 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002017 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002018 Invalid = true;
2019 }
2020
Chris Lattner001b29c2010-10-10 17:49:49 +00002021 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2022 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002023 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002024 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002025 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002026 diag::err_flexible_array_init_needs_braces)
2027 << DIE->getInit()->getSourceRange();
2028 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002029 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002030 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002031 Invalid = true;
2032 }
2033
Eli Friedman3fa64df2011-08-23 22:24:57 +00002034 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00002035 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002036 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002037 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002038
2039 if (Invalid) {
2040 ++Index;
2041 return true;
2042 }
2043
2044 // Initialize the array.
2045 bool prevHadError = hadError;
2046 unsigned newStructuredIndex = FieldIndex;
2047 unsigned OldIndex = Index;
2048 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00002049
2050 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002051 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002052 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002053 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002054
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002055 IList->setInit(OldIndex, DIE);
2056 if (hadError && !prevHadError) {
2057 ++Field;
2058 ++FieldIndex;
2059 if (NextField)
2060 *NextField = Field;
2061 StructuredIndex = FieldIndex;
2062 return true;
2063 }
2064 } else {
2065 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002066 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002067 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002068
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002069 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002070 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002071 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002072 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002073 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002074 true, false))
2075 return true;
2076 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002077
2078 // Find the position of the next field to be initialized in this
2079 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002080 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002081 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002082
2083 // If this the first designator, our caller will continue checking
2084 // the rest of this struct/class/union subobject.
2085 if (IsFirstDesignator) {
2086 if (NextField)
2087 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002088 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002089 return false;
2090 }
2091
Douglas Gregor17bd0942009-01-28 23:36:17 +00002092 if (!FinishSubobjectInit)
2093 return false;
2094
Douglas Gregord5846a12009-04-15 06:41:24 +00002095 // We've already initialized something in the union; we're done.
2096 if (RT->getDecl()->isUnion())
2097 return hadError;
2098
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002099 // Check the remaining fields within this class/struct/union subobject.
2100 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002101
Anders Carlsson6cabf312010-01-23 23:23:01 +00002102 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002103 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002104 return hadError && !prevHadError;
2105 }
2106
2107 // C99 6.7.8p6:
2108 //
2109 // If a designator has the form
2110 //
2111 // [ constant-expression ]
2112 //
2113 // then the current object (defined below) shall have array
2114 // type and the expression shall be an integer constant
2115 // expression. If the array is of unknown size, any
2116 // nonnegative value is valid.
2117 //
2118 // Additionally, cope with the GNU extension that permits
2119 // designators of the form
2120 //
2121 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002122 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002123 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002124 if (!VerifyOnly)
2125 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2126 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002127 ++Index;
2128 return true;
2129 }
2130
Craig Topperc3ec1492014-05-26 06:22:03 +00002131 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002132 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2133 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002134 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002135 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002136 DesignatedEndIndex = DesignatedStartIndex;
2137 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002138 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002139
Mike Stump11289f42009-09-09 15:08:12 +00002140 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002141 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002142 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002143 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002144 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002145
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002146 // Codegen can't handle evaluating array range designators that have side
2147 // effects, because we replicate the AST value for each initialized element.
2148 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2149 // elements with something that has a side effect, so codegen can emit an
2150 // "error unsupported" error instead of miscompiling the app.
2151 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002152 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002153 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002154 }
2155
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002156 if (isa<ConstantArrayType>(AT)) {
2157 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002158 DesignatedStartIndex
2159 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002160 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002161 DesignatedEndIndex
2162 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002163 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2164 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002165 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002166 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002167 diag::err_array_designator_too_large)
2168 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2169 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002170 ++Index;
2171 return true;
2172 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002173 } else {
2174 // Make sure the bit-widths and signedness match.
2175 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002176 DesignatedEndIndex
2177 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002178 else if (DesignatedStartIndex.getBitWidth() <
2179 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002180 DesignatedStartIndex
2181 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002182 DesignatedStartIndex.setIsUnsigned(true);
2183 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002184 }
Mike Stump11289f42009-09-09 15:08:12 +00002185
Eli Friedman1f16b742013-06-11 21:48:11 +00002186 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2187 // We're modifying a string literal init; we have to decompose the string
2188 // so we can modify the individual characters.
2189 ASTContext &Context = SemaRef.Context;
2190 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2191
2192 // Compute the character type
2193 QualType CharTy = AT->getElementType();
2194
2195 // Compute the type of the integer literals.
2196 QualType PromotedCharTy = CharTy;
2197 if (CharTy->isPromotableIntegerType())
2198 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2199 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2200
2201 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2202 // Get the length of the string.
2203 uint64_t StrLen = SL->getLength();
2204 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2205 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2206 StructuredList->resizeInits(Context, StrLen);
2207
2208 // Build a literal for each character in the string, and put them into
2209 // the init list.
2210 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2211 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2212 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002213 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002214 if (CharTy != PromotedCharTy)
2215 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002216 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002217 StructuredList->updateInit(Context, i, Init);
2218 }
2219 } else {
2220 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2221 std::string Str;
2222 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2223
2224 // Get the length of the string.
2225 uint64_t StrLen = Str.size();
2226 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2227 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2228 StructuredList->resizeInits(Context, StrLen);
2229
2230 // Build a literal for each character in the string, and put them into
2231 // the init list.
2232 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2233 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2234 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002235 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002236 if (CharTy != PromotedCharTy)
2237 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002238 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002239 StructuredList->updateInit(Context, i, Init);
2240 }
2241 }
2242 }
2243
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002244 // Make sure that our non-designated initializer list has space
2245 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002246 if (!VerifyOnly &&
2247 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002248 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002249 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002250
Douglas Gregor17bd0942009-01-28 23:36:17 +00002251 // Repeatedly perform subobject initializations in the range
2252 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002253
Douglas Gregor17bd0942009-01-28 23:36:17 +00002254 // Move to the next designator
2255 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2256 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002257
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002258 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002259 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002260
Douglas Gregor17bd0942009-01-28 23:36:17 +00002261 while (DesignatedStartIndex <= DesignatedEndIndex) {
2262 // Recurse to check later designated subobjects.
2263 QualType ElementType = AT->getElementType();
2264 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002265
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002266 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002267 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002268 ElementType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002269 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002270 (DesignatedStartIndex == DesignatedEndIndex),
2271 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002272 return true;
2273
2274 // Move to the next index in the array that we'll be initializing.
2275 ++DesignatedStartIndex;
2276 ElementIndex = DesignatedStartIndex.getZExtValue();
2277 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002278
2279 // If this the first designator, our caller will continue checking
2280 // the rest of this array subobject.
2281 if (IsFirstDesignator) {
2282 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002283 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002284 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002285 return false;
2286 }
Mike Stump11289f42009-09-09 15:08:12 +00002287
Douglas Gregor17bd0942009-01-28 23:36:17 +00002288 if (!FinishSubobjectInit)
2289 return false;
2290
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002291 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002292 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002293 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002294 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002295 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002296 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002297}
2298
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002299// Get the structured initializer list for a subobject of type
2300// @p CurrentObjectType.
2301InitListExpr *
2302InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2303 QualType CurrentObjectType,
2304 InitListExpr *StructuredList,
2305 unsigned StructuredIndex,
2306 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002307 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002308 return nullptr; // No structured list in verification-only mode.
2309 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002310 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002311 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002312 else if (StructuredIndex < StructuredList->getNumInits())
2313 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002314
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002315 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2316 return Result;
2317
2318 if (ExistingInit) {
2319 // We are creating an initializer list that initializes the
2320 // subobjects of the current object, but there was already an
2321 // initialization that completely initialized the current
2322 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002323 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002324 // struct X { int a, b; };
2325 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002326 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002327 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2328 // designated initializer re-initializes the whole
2329 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002330 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002331 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002332 << InitRange;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002333 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002334 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002335 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002336 << ExistingInit->getSourceRange();
2337 }
2338
Mike Stump11289f42009-09-09 15:08:12 +00002339 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002340 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002341 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002342 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002343
Eli Friedman91f5ae52012-02-23 02:25:10 +00002344 QualType ResultType = CurrentObjectType;
2345 if (!ResultType->isArrayType())
2346 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2347 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002348
Douglas Gregor6d00c992009-03-20 23:58:33 +00002349 // Pre-allocate storage for the structured initializer list.
2350 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002351 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002352 bool GotNumInits = false;
2353 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002354 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002355 GotNumInits = true;
2356 } else if (Index < IList->getNumInits()) {
2357 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002358 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002359 GotNumInits = true;
2360 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002361 }
2362
Mike Stump11289f42009-09-09 15:08:12 +00002363 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002364 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2365 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2366 NumElements = CAType->getSize().getZExtValue();
2367 // Simple heuristic so that we don't allocate a very large
2368 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002369 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002370 NumElements = 0;
2371 }
John McCall9dd450b2009-09-21 23:43:11 +00002372 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002373 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002374 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002375 RecordDecl *RDecl = RType->getDecl();
2376 if (RDecl->isUnion())
2377 NumElements = 1;
2378 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002379 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002380 }
2381
Ted Kremenekac034612010-04-13 23:39:13 +00002382 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002383
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002384 // Link this new initializer list into the structured initializer
2385 // lists.
2386 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002387 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002388 else {
2389 Result->setSyntacticForm(IList);
2390 SyntacticToSemantic[IList] = Result;
2391 }
2392
2393 return Result;
2394}
2395
2396/// Update the initializer at index @p StructuredIndex within the
2397/// structured initializer list to the value @p expr.
2398void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2399 unsigned &StructuredIndex,
2400 Expr *expr) {
2401 // No structured initializer list to update
2402 if (!StructuredList)
2403 return;
2404
Ted Kremenekac034612010-04-13 23:39:13 +00002405 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2406 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002407 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002408 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002409 diag::warn_initializer_overrides)
2410 << expr->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002411 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002412 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002413 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002414 << PrevInit->getSourceRange();
2415 }
Mike Stump11289f42009-09-09 15:08:12 +00002416
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002417 ++StructuredIndex;
2418}
2419
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002420/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002421/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002422/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002423/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002424/// failure. Returns the index expression, possibly with an implicit cast
2425/// added, on success. If everything went okay, Value will receive the
2426/// value of the constant expression.
2427static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002428CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002429 SourceLocation Loc = Index->getLocStart();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002430
2431 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002432 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2433 if (Result.isInvalid())
2434 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002435
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002436 if (Value.isSigned() && Value.isNegative())
2437 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002438 << Value.toString(10) << Index->getSourceRange();
2439
Douglas Gregor51650d32009-01-23 21:04:18 +00002440 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002441 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002442}
2443
John McCalldadc5752010-08-24 06:29:42 +00002444ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002445 SourceLocation Loc,
2446 bool GNUSyntax,
2447 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002448 typedef DesignatedInitExpr::Designator ASTDesignator;
2449
2450 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002451 SmallVector<ASTDesignator, 32> Designators;
2452 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002453
2454 // Build designators and check array designator expressions.
2455 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2456 const Designator &D = Desig.getDesignator(Idx);
2457 switch (D.getKind()) {
2458 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002459 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002460 D.getFieldLoc()));
2461 break;
2462
2463 case Designator::ArrayDesignator: {
2464 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2465 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002466 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002467 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002468 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002469 Invalid = true;
2470 else {
2471 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002472 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002473 D.getRBracketLoc()));
2474 InitExpressions.push_back(Index);
2475 }
2476 break;
2477 }
2478
2479 case Designator::ArrayRangeDesignator: {
2480 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2481 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2482 llvm::APSInt StartValue;
2483 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002484 bool StartDependent = StartIndex->isTypeDependent() ||
2485 StartIndex->isValueDependent();
2486 bool EndDependent = EndIndex->isTypeDependent() ||
2487 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002488 if (!StartDependent)
2489 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002490 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002491 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002492 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002493
2494 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002495 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002496 else {
2497 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002498 if (StartDependent || EndDependent) {
2499 // Nothing to compute.
2500 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002501 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002502 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002503 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002504
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002505 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002506 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002507 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002508 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2509 Invalid = true;
2510 } else {
2511 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002512 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002513 D.getEllipsisLoc(),
2514 D.getRBracketLoc()));
2515 InitExpressions.push_back(StartIndex);
2516 InitExpressions.push_back(EndIndex);
2517 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002518 }
2519 break;
2520 }
2521 }
2522 }
2523
2524 if (Invalid || Init.isInvalid())
2525 return ExprError();
2526
2527 // Clear out the expressions within the designation.
2528 Desig.ClearExprs(*this);
2529
2530 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002531 = DesignatedInitExpr::Create(Context,
2532 Designators.data(), Designators.size(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00002533 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002534 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002535
David Blaikiebbafb8a2012-03-11 07:00:24 +00002536 if (!getLangOpts().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002537 Diag(DIE->getLocStart(), diag::ext_designated_init)
2538 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002539
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002540 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002541}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002542
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002543//===----------------------------------------------------------------------===//
2544// Initialization entity
2545//===----------------------------------------------------------------------===//
2546
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002547InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002548 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002549 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002550{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002551 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2552 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002553 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002554 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002555 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002556 Type = VT->getElementType();
2557 } else {
2558 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2559 assert(CT && "Unexpected type");
2560 Kind = EK_ComplexElement;
2561 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002562 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002563}
2564
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002565InitializedEntity
2566InitializedEntity::InitializeBase(ASTContext &Context,
2567 const CXXBaseSpecifier *Base,
2568 bool IsInheritedVirtualBase) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002569 InitializedEntity Result;
2570 Result.Kind = EK_Base;
Craig Topperc3ec1492014-05-26 06:22:03 +00002571 Result.Parent = nullptr;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002572 Result.Base = reinterpret_cast<uintptr_t>(Base);
2573 if (IsInheritedVirtualBase)
2574 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002575
Douglas Gregor1b303932009-12-22 15:35:07 +00002576 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002577 return Result;
2578}
2579
Douglas Gregor85dabae2009-12-16 01:38:02 +00002580DeclarationName InitializedEntity::getName() const {
2581 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002582 case EK_Parameter:
2583 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00002584 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2585 return (D ? D->getDeclName() : DeclarationName());
2586 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002587
2588 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002589 case EK_Member:
2590 return VariableOrMember->getDeclName();
2591
Douglas Gregor19666fb2012-02-15 16:57:26 +00002592 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002593 return DeclarationName(Capture.VarID);
Douglas Gregor19666fb2012-02-15 16:57:26 +00002594
Douglas Gregor85dabae2009-12-16 01:38:02 +00002595 case EK_Result:
2596 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002597 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002598 case EK_Temporary:
2599 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002600 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002601 case EK_ArrayElement:
2602 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002603 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002604 case EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002605 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002606 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002607 return DeclarationName();
2608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002609
David Blaikie8a40f702012-01-17 06:56:22 +00002610 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002611}
2612
Douglas Gregora4b592a2009-12-19 03:01:41 +00002613DeclaratorDecl *InitializedEntity::getDecl() const {
2614 switch (getKind()) {
2615 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002616 case EK_Member:
2617 return VariableOrMember;
2618
John McCall31168b02011-06-15 23:02:42 +00002619 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002620 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00002621 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2622
Douglas Gregora4b592a2009-12-19 03:01:41 +00002623 case EK_Result:
2624 case EK_Exception:
2625 case EK_New:
2626 case EK_Temporary:
2627 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002628 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002629 case EK_ArrayElement:
2630 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002631 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002632 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002633 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002634 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002635 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00002636 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00002637 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002638
David Blaikie8a40f702012-01-17 06:56:22 +00002639 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002640}
2641
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002642bool InitializedEntity::allowsNRVO() const {
2643 switch (getKind()) {
2644 case EK_Result:
2645 case EK_Exception:
2646 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002647
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002648 case EK_Variable:
2649 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002650 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002651 case EK_Member:
2652 case EK_New:
2653 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002654 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002655 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002656 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002657 case EK_ArrayElement:
2658 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002659 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002660 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002661 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002662 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002663 break;
2664 }
2665
2666 return false;
2667}
2668
Richard Smithe6c01442013-06-05 00:46:14 +00002669unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00002670 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00002671 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2672 for (unsigned I = 0; I != Depth; ++I)
2673 OS << "`-";
2674
2675 switch (getKind()) {
2676 case EK_Variable: OS << "Variable"; break;
2677 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002678 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2679 break;
Richard Smithe6c01442013-06-05 00:46:14 +00002680 case EK_Result: OS << "Result"; break;
2681 case EK_Exception: OS << "Exception"; break;
2682 case EK_Member: OS << "Member"; break;
2683 case EK_New: OS << "New"; break;
2684 case EK_Temporary: OS << "Temporary"; break;
2685 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002686 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00002687 case EK_Base: OS << "Base"; break;
2688 case EK_Delegating: OS << "Delegating"; break;
2689 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2690 case EK_VectorElement: OS << "VectorElement " << Index; break;
2691 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2692 case EK_BlockElement: OS << "Block"; break;
2693 case EK_LambdaCapture:
2694 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002695 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00002696 break;
2697 }
2698
2699 if (Decl *D = getDecl()) {
2700 OS << " ";
2701 cast<NamedDecl>(D)->printQualifiedName(OS);
2702 }
2703
2704 OS << " '" << getType().getAsString() << "'\n";
2705
2706 return Depth + 1;
2707}
2708
2709void InitializedEntity::dump() const {
2710 dumpImpl(llvm::errs());
2711}
2712
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002713//===----------------------------------------------------------------------===//
2714// Initialization sequence
2715//===----------------------------------------------------------------------===//
2716
2717void InitializationSequence::Step::Destroy() {
2718 switch (Kind) {
2719 case SK_ResolveAddressOfOverloadedFunction:
2720 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002721 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002722 case SK_CastDerivedToBaseLValue:
2723 case SK_BindReference:
2724 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002725 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002726 case SK_UserConversion:
2727 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002728 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002729 case SK_QualificationConversionLValue:
Richard Smith77be48a2014-07-31 06:31:19 +00002730 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00002731 case SK_LValueToRValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002732 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00002733 case SK_UnwrapInitList:
2734 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002735 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00002736 case SK_ConstructorInitializationFromList:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002737 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002738 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002739 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002740 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002741 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00002742 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002743 case SK_PassByIndirectCopyRestore:
2744 case SK_PassByIndirectRestore:
2745 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002746 case SK_StdInitializerList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00002747 case SK_StdInitializerListConstructorCall:
Guy Benyei61054192013-02-07 10:55:47 +00002748 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002749 case SK_OCLZeroEvent:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002750 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002751
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002752 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00002753 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002754 delete ICS;
2755 }
2756}
2757
Douglas Gregor838fcc32010-03-26 20:14:36 +00002758bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002759 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002760}
2761
2762bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002763 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002764 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002765
Douglas Gregor838fcc32010-03-26 20:14:36 +00002766 switch (getFailureKind()) {
2767 case FK_TooManyInitsForReference:
2768 case FK_ArrayNeedsInitList:
2769 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00002770 case FK_ArrayNeedsInitListOrWideStringLiteral:
2771 case FK_NarrowStringIntoWideCharArray:
2772 case FK_WideStringIntoCharArray:
2773 case FK_IncompatWideStringIntoWideChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002774 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2775 case FK_NonConstLValueReferenceBindingToTemporary:
2776 case FK_NonConstLValueReferenceBindingToUnrelated:
2777 case FK_RValueReferenceBindingToLValue:
2778 case FK_ReferenceInitDropsQualifiers:
2779 case FK_ReferenceInitFailed:
2780 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002781 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002782 case FK_TooManyInitsForScalar:
2783 case FK_ReferenceBindingToInitList:
2784 case FK_InitListBadDestinationType:
2785 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002786 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002787 case FK_ArrayTypeMismatch:
2788 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002789 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002790 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002791 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00002792 case FK_ExplicitConstructor:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002793 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002794
Douglas Gregor838fcc32010-03-26 20:14:36 +00002795 case FK_ReferenceInitOverloadFailed:
2796 case FK_UserConversionOverloadFailed:
2797 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002798 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002799 return FailedOverloadResult == OR_Ambiguous;
2800 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002801
David Blaikie8a40f702012-01-17 06:56:22 +00002802 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00002803}
2804
Douglas Gregorb33eed02010-04-16 22:09:46 +00002805bool InitializationSequence::isConstructorInitialization() const {
2806 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2807}
2808
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002809void
2810InitializationSequence
2811::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2812 DeclAccessPair Found,
2813 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002814 Step S;
2815 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2816 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002817 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002818 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002819 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002820 Steps.push_back(S);
2821}
2822
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002823void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002824 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002825 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002826 switch (VK) {
2827 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2828 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2829 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002830 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002831 S.Type = BaseType;
2832 Steps.push_back(S);
2833}
2834
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002835void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002836 bool BindingTemporary) {
2837 Step S;
2838 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2839 S.Type = T;
2840 Steps.push_back(S);
2841}
2842
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002843void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2844 Step S;
2845 S.Kind = SK_ExtraneousCopyToTemporary;
2846 S.Type = T;
2847 Steps.push_back(S);
2848}
2849
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002850void
2851InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2852 DeclAccessPair FoundDecl,
2853 QualType T,
2854 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002855 Step S;
2856 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002857 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002858 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002859 S.Function.Function = Function;
2860 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002861 Steps.push_back(S);
2862}
2863
2864void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002865 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002866 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002867 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002868 switch (VK) {
2869 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002870 S.Kind = SK_QualificationConversionRValue;
2871 break;
John McCall2536c6d2010-08-25 10:28:54 +00002872 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002873 S.Kind = SK_QualificationConversionXValue;
2874 break;
John McCall2536c6d2010-08-25 10:28:54 +00002875 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002876 S.Kind = SK_QualificationConversionLValue;
2877 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002878 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002879 S.Type = Ty;
2880 Steps.push_back(S);
2881}
2882
Richard Smith77be48a2014-07-31 06:31:19 +00002883void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
2884 Step S;
2885 S.Kind = SK_AtomicConversion;
2886 S.Type = Ty;
2887 Steps.push_back(S);
2888}
2889
Jordan Roseb1312a52013-04-11 00:58:58 +00002890void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2891 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2892
2893 Step S;
2894 S.Kind = SK_LValueToRValue;
2895 S.Type = Ty;
2896 Steps.push_back(S);
2897}
2898
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002899void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00002900 const ImplicitConversionSequence &ICS, QualType T,
2901 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002902 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00002903 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
2904 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002905 S.Type = T;
2906 S.ICS = new ImplicitConversionSequence(ICS);
2907 Steps.push_back(S);
2908}
2909
Douglas Gregor51e77d52009-12-10 17:56:55 +00002910void InitializationSequence::AddListInitializationStep(QualType T) {
2911 Step S;
2912 S.Kind = SK_ListInitialization;
2913 S.Type = T;
2914 Steps.push_back(S);
2915}
2916
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002917void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002918InitializationSequence
2919::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2920 AccessSpecifier Access,
2921 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002922 bool HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002923 bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002924 Step S;
Richard Smithf8adcdc2014-07-17 05:12:35 +00002925 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
Richard Smith53324112014-07-16 21:33:43 +00002926 : SK_ConstructorInitializationFromList
2927 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002928 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002929 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002930 S.Function.Function = Constructor;
2931 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002932 Steps.push_back(S);
2933}
2934
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002935void InitializationSequence::AddZeroInitializationStep(QualType T) {
2936 Step S;
2937 S.Kind = SK_ZeroInitialization;
2938 S.Type = T;
2939 Steps.push_back(S);
2940}
2941
Douglas Gregore1314a62009-12-18 05:02:21 +00002942void InitializationSequence::AddCAssignmentStep(QualType T) {
2943 Step S;
2944 S.Kind = SK_CAssignment;
2945 S.Type = T;
2946 Steps.push_back(S);
2947}
2948
Eli Friedman78275202009-12-19 08:11:05 +00002949void InitializationSequence::AddStringInitStep(QualType T) {
2950 Step S;
2951 S.Kind = SK_StringInit;
2952 S.Type = T;
2953 Steps.push_back(S);
2954}
2955
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002956void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2957 Step S;
2958 S.Kind = SK_ObjCObjectConversion;
2959 S.Type = T;
2960 Steps.push_back(S);
2961}
2962
Douglas Gregore2f943b2011-02-22 18:29:51 +00002963void InitializationSequence::AddArrayInitStep(QualType T) {
2964 Step S;
2965 S.Kind = SK_ArrayInit;
2966 S.Type = T;
2967 Steps.push_back(S);
2968}
2969
Richard Smithebeed412012-02-15 22:38:09 +00002970void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2971 Step S;
2972 S.Kind = SK_ParenthesizedArrayInit;
2973 S.Type = T;
2974 Steps.push_back(S);
2975}
2976
John McCall31168b02011-06-15 23:02:42 +00002977void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2978 bool shouldCopy) {
2979 Step s;
2980 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2981 : SK_PassByIndirectRestore);
2982 s.Type = type;
2983 Steps.push_back(s);
2984}
2985
2986void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2987 Step S;
2988 S.Kind = SK_ProduceObjCObject;
2989 S.Type = T;
2990 Steps.push_back(S);
2991}
2992
Sebastian Redlc1839b12012-01-17 22:49:42 +00002993void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2994 Step S;
2995 S.Kind = SK_StdInitializerList;
2996 S.Type = T;
2997 Steps.push_back(S);
2998}
2999
Guy Benyei61054192013-02-07 10:55:47 +00003000void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3001 Step S;
3002 S.Kind = SK_OCLSamplerInit;
3003 S.Type = T;
3004 Steps.push_back(S);
3005}
3006
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003007void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3008 Step S;
3009 S.Kind = SK_OCLZeroEvent;
3010 S.Type = T;
3011 Steps.push_back(S);
3012}
3013
Sebastian Redl29526f02011-11-27 16:50:07 +00003014void InitializationSequence::RewrapReferenceInitList(QualType T,
3015 InitListExpr *Syntactic) {
3016 assert(Syntactic->getNumInits() == 1 &&
3017 "Can only rewrap trivial init lists.");
3018 Step S;
3019 S.Kind = SK_UnwrapInitList;
3020 S.Type = Syntactic->getInit(0)->getType();
3021 Steps.insert(Steps.begin(), S);
3022
3023 S.Kind = SK_RewrapInitList;
3024 S.Type = T;
3025 S.WrappingSyntacticList = Syntactic;
3026 Steps.push_back(S);
3027}
3028
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003029void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003030 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00003031 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003032 this->Failure = Failure;
3033 this->FailedOverloadResult = Result;
3034}
3035
3036//===----------------------------------------------------------------------===//
3037// Attempt initialization
3038//===----------------------------------------------------------------------===//
3039
John McCall31168b02011-06-15 23:02:42 +00003040static void MaybeProduceObjCObject(Sema &S,
3041 InitializationSequence &Sequence,
3042 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003043 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00003044
3045 /// When initializing a parameter, produce the value if it's marked
3046 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003047 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00003048 if (!Entity.isParameterConsumed())
3049 return;
3050
3051 assert(Entity.getType()->isObjCRetainableType() &&
3052 "consuming an object of unretainable type?");
3053 Sequence.AddProduceObjCObjectStep(Entity.getType());
3054
3055 /// When initializing a return value, if the return type is a
3056 /// retainable type, then returns need to immediately retain the
3057 /// object. If an autorelease is required, it will be done at the
3058 /// last instant.
3059 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3060 if (!Entity.getType()->isObjCRetainableType())
3061 return;
3062
3063 Sequence.AddProduceObjCObjectStep(Entity.getType());
3064 }
3065}
3066
Richard Smithcc1b96d2013-06-12 22:31:48 +00003067static void TryListInitialization(Sema &S,
3068 const InitializedEntity &Entity,
3069 const InitializationKind &Kind,
3070 InitListExpr *InitList,
3071 InitializationSequence &Sequence);
3072
Richard Smithd86812d2012-07-05 08:39:21 +00003073/// \brief When initializing from init list via constructor, handle
3074/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003075///
Richard Smithd86812d2012-07-05 08:39:21 +00003076/// \return true if we have handled initialization of an object of type
3077/// std::initializer_list<T>, false otherwise.
3078static bool TryInitializerListConstruction(Sema &S,
3079 InitListExpr *List,
3080 QualType DestType,
3081 InitializationSequence &Sequence) {
3082 QualType E;
3083 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003084 return false;
3085
Richard Smithcc1b96d2013-06-12 22:31:48 +00003086 if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
3087 Sequence.setIncompleteTypeFailure(E);
3088 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003089 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003090
3091 // Try initializing a temporary array from the init list.
3092 QualType ArrayType = S.Context.getConstantArrayType(
3093 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3094 List->getNumInits()),
3095 clang::ArrayType::Normal, 0);
3096 InitializedEntity HiddenArray =
3097 InitializedEntity::InitializeTemporary(ArrayType);
3098 InitializationKind Kind =
3099 InitializationKind::CreateDirectList(List->getExprLoc());
3100 TryListInitialization(S, HiddenArray, Kind, List, Sequence);
3101 if (Sequence)
3102 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003103 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003104}
3105
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003106static OverloadingResult
3107ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003108 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003109 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003110 ArrayRef<NamedDecl *> Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003111 OverloadCandidateSet::iterator &Best,
3112 bool CopyInitializing, bool AllowExplicit,
Larisse Voufo19d08672015-01-27 18:47:05 +00003113 bool OnlyListConstructors) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003114 CandidateSet.clear();
3115
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003116 for (ArrayRef<NamedDecl *>::iterator
3117 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003118 NamedDecl *D = *Con;
3119 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3120 bool SuppressUserConversions = false;
3121
3122 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003123 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003124 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3125 if (ConstructorTmpl)
3126 Constructor = cast<CXXConstructorDecl>(
3127 ConstructorTmpl->getTemplatedDecl());
3128 else {
3129 Constructor = cast<CXXConstructorDecl>(D);
3130
Richard Smith6c6ddab2013-09-21 21:23:47 +00003131 // C++11 [over.best.ics]p4:
Larisse Voufo19d08672015-01-27 18:47:05 +00003132 // ... and the constructor or user-defined conversion function is a
3133 // candidate by
3134 // — 13.3.1.3, when the argument is the temporary in the second step
3135 // of a class copy-initialization, or
3136 // — 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases),
3137 // user-defined conversion sequences are not considered.
3138 if (CopyInitializing && Constructor->isCopyOrMoveConstructor())
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003139 SuppressUserConversions = true;
3140 }
3141
3142 if (!Constructor->isInvalidDecl() &&
3143 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003144 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003145 if (ConstructorTmpl)
3146 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003147 /*ExplicitArgs*/ nullptr, Args,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003148 CandidateSet, SuppressUserConversions);
Douglas Gregor6073dca2012-02-24 23:56:31 +00003149 else {
3150 // C++ [over.match.copy]p1:
3151 // - When initializing a temporary to be bound to the first parameter
3152 // of a constructor that takes a reference to possibly cv-qualified
3153 // T as its first argument, called with a single argument in the
3154 // context of direct-initialization, explicit conversion functions
3155 // are also considered.
3156 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003157 Args.size() == 1 &&
Douglas Gregor6073dca2012-02-24 23:56:31 +00003158 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003159 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003160 SuppressUserConversions,
3161 /*PartialOverloading=*/false,
3162 /*AllowExplicit=*/AllowExplicitConv);
3163 }
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003164 }
3165 }
3166
3167 // Perform overload resolution and return the result.
3168 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3169}
3170
Sebastian Redled2e5322011-12-22 14:44:04 +00003171/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3172/// enumerates the constructors of the initialized entity and performs overload
3173/// resolution to select the best.
Sebastian Redl88e4d492012-02-04 21:27:33 +00003174/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redled2e5322011-12-22 14:44:04 +00003175/// class type.
3176static void TryConstructorInitialization(Sema &S,
3177 const InitializedEntity &Entity,
3178 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003179 MultiExprArg Args, QualType DestType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003180 InitializationSequence &Sequence,
Sebastian Redl88e4d492012-02-04 21:27:33 +00003181 bool InitListSyntax = false) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003182 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Sebastian Redl88e4d492012-02-04 21:27:33 +00003183 "InitListSyntax must come with a single initializer list argument.");
3184
Sebastian Redled2e5322011-12-22 14:44:04 +00003185 // The type we're constructing needs to be complete.
3186 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003187 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003188 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003189 }
3190
3191 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3192 assert(DestRecordType && "Constructor initialization requires record type");
3193 CXXRecordDecl *DestRecordDecl
3194 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3195
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003196 // Build the candidate set directly in the initialization sequence
3197 // structure, so that it will persist if we fail.
3198 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3199
3200 // Determine whether we are allowed to call explicit constructors or
3201 // explicit conversion operators.
Sebastian Redl048a6d72012-04-01 19:54:59 +00003202 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003203 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003204
Sebastian Redled2e5322011-12-22 14:44:04 +00003205 // - Otherwise, if T is a class type, constructors are considered. The
3206 // applicable constructors are enumerated, and the best one is chosen
3207 // through overload resolution.
David Blaikieff7d47a2012-12-19 00:45:41 +00003208 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003209 // The container holding the constructors can under certain conditions
3210 // be changed while iterating (e.g. because of deserialization).
3211 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003212 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redled2e5322011-12-22 14:44:04 +00003213
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003214 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003215 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003216 bool AsInitializerList = false;
3217
Larisse Voufo19d08672015-01-27 18:47:05 +00003218 // C++11 [over.match.list]p1, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003219 // When objects of non-aggregate type T are list-initialized, such that
3220 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3221 // according to the rules in this section, overload resolution selects
3222 // the constructor in two phases:
3223 //
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003224 // - Initially, the candidate functions are the initializer-list
3225 // constructors of the class T and the argument list consists of the
3226 // initializer list as a single argument.
3227 if (InitListSyntax) {
Richard Smithd86812d2012-07-05 08:39:21 +00003228 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003229 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003230
3231 // If the initializer list has no elements and T has a default constructor,
3232 // the first phase is omitted.
Richard Smith2be35f52012-12-01 02:35:44 +00003233 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003234 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003235 CandidateSet, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003236 CopyInitialization, AllowExplicit,
Larisse Voufo19d08672015-01-27 18:47:05 +00003237 /*OnlyListConstructor=*/true);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003238
3239 // Time to unwrap the init list.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003240 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003241 }
3242
3243 // C++11 [over.match.list]p1:
3244 // - If no viable initializer-list constructor is found, overload resolution
3245 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003246 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003247 // elements of the initializer list.
3248 if (Result == OR_No_Viable_Function) {
3249 AsInitializerList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003250 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003251 CandidateSet, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003252 CopyInitialization, AllowExplicit,
Larisse Voufo19d08672015-01-27 18:47:05 +00003253 /*OnlyListConstructors=*/false);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003254 }
3255 if (Result) {
Sebastian Redl88e4d492012-02-04 21:27:33 +00003256 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003257 InitializationSequence::FK_ListConstructorOverloadFailed :
3258 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003259 Result);
3260 return;
3261 }
3262
Richard Smithd86812d2012-07-05 08:39:21 +00003263 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003264 // If a program calls for the default initialization of an object
3265 // of a const-qualified type T, T shall be a class type with a
3266 // user-provided default constructor.
3267 if (Kind.getKind() == InitializationKind::IK_Default &&
3268 Entity.getType().isConstQualified() &&
Aaron Ballman899b9c62012-07-31 22:40:31 +00003269 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redled2e5322011-12-22 14:44:04 +00003270 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3271 return;
3272 }
3273
Sebastian Redl048a6d72012-04-01 19:54:59 +00003274 // C++11 [over.match.list]p1:
3275 // In copy-list-initialization, if an explicit constructor is chosen, the
3276 // initializer is ill-formed.
3277 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3278 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3279 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3280 return;
3281 }
3282
Sebastian Redled2e5322011-12-22 14:44:04 +00003283 // Add the constructor initialization step. Any cv-qualification conversion is
3284 // subsumed by the initialization.
3285 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redled2e5322011-12-22 14:44:04 +00003286 Sequence.AddConstructorInitializationStep(CtorDecl,
3287 Best->FoundDecl.getAccess(),
3288 DestType, HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003289 InitListSyntax, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003290}
3291
Sebastian Redl29526f02011-11-27 16:50:07 +00003292static bool
3293ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3294 Expr *Initializer,
3295 QualType &SourceType,
3296 QualType &UnqualifiedSourceType,
3297 QualType UnqualifiedTargetType,
3298 InitializationSequence &Sequence) {
3299 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3300 S.Context.OverloadTy) {
3301 DeclAccessPair Found;
3302 bool HadMultipleCandidates = false;
3303 if (FunctionDecl *Fn
3304 = S.ResolveAddressOfOverloadedFunction(Initializer,
3305 UnqualifiedTargetType,
3306 false, Found,
3307 &HadMultipleCandidates)) {
3308 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3309 HadMultipleCandidates);
3310 SourceType = Fn->getType();
3311 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3312 } else if (!UnqualifiedTargetType->isRecordType()) {
3313 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3314 return true;
3315 }
3316 }
3317 return false;
3318}
3319
3320static void TryReferenceInitializationCore(Sema &S,
3321 const InitializedEntity &Entity,
3322 const InitializationKind &Kind,
3323 Expr *Initializer,
3324 QualType cv1T1, QualType T1,
3325 Qualifiers T1Quals,
3326 QualType cv2T2, QualType T2,
3327 Qualifiers T2Quals,
3328 InitializationSequence &Sequence);
3329
Richard Smithd86812d2012-07-05 08:39:21 +00003330static void TryValueInitialization(Sema &S,
3331 const InitializedEntity &Entity,
3332 const InitializationKind &Kind,
3333 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00003334 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00003335
Sebastian Redl29526f02011-11-27 16:50:07 +00003336/// \brief Attempt list initialization of a reference.
3337static void TryReferenceListInitialization(Sema &S,
3338 const InitializedEntity &Entity,
3339 const InitializationKind &Kind,
3340 InitListExpr *InitList,
Richard Smithfaadef72013-06-08 00:02:08 +00003341 InitializationSequence &Sequence) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003342 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003343 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003344 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3345 return;
3346 }
3347
3348 QualType DestType = Entity.getType();
3349 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3350 Qualifiers T1Quals;
3351 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3352
3353 // Reference initialization via an initializer list works thus:
3354 // If the initializer list consists of a single element that is
3355 // reference-related to the referenced type, bind directly to that element
3356 // (possibly creating temporaries).
3357 // Otherwise, initialize a temporary with the initializer list and
3358 // bind to that.
3359 if (InitList->getNumInits() == 1) {
3360 Expr *Initializer = InitList->getInit(0);
3361 QualType cv2T2 = Initializer->getType();
3362 Qualifiers T2Quals;
3363 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3364
3365 // If this fails, creating a temporary wouldn't work either.
3366 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3367 T1, Sequence))
3368 return;
3369
3370 SourceLocation DeclLoc = Initializer->getLocStart();
3371 bool dummy1, dummy2, dummy3;
3372 Sema::ReferenceCompareResult RefRelationship
3373 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3374 dummy2, dummy3);
3375 if (RefRelationship >= Sema::Ref_Related) {
3376 // Try to bind the reference here.
3377 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3378 T1Quals, cv2T2, T2, T2Quals, Sequence);
3379 if (Sequence)
3380 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3381 return;
3382 }
Richard Smith03d93932013-01-15 07:58:29 +00003383
3384 // Update the initializer if we've resolved an overloaded function.
3385 if (Sequence.step_begin() != Sequence.step_end())
3386 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00003387 }
3388
3389 // Not reference-related. Create a temporary and bind to that.
3390 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3391
3392 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3393 if (Sequence) {
3394 if (DestType->isRValueReferenceType() ||
3395 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3396 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3397 else
3398 Sequence.SetFailed(
3399 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3400 }
3401}
3402
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003403/// \brief Attempt list initialization (C++0x [dcl.init.list])
3404static void TryListInitialization(Sema &S,
3405 const InitializedEntity &Entity,
3406 const InitializationKind &Kind,
3407 InitListExpr *InitList,
3408 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003409 QualType DestType = Entity.getType();
3410
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003411 // C++ doesn't allow scalar initialization with more than one argument.
3412 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003413 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003414 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3415 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3416 return;
3417 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003418 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003419 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003420 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003421 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003422
Larisse Voufod2010992015-01-24 23:09:54 +00003423 if (DestType->isRecordType() &&
3424 S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
3425 Sequence.setIncompleteTypeFailure(DestType);
3426 return;
3427 }
Richard Smithd86812d2012-07-05 08:39:21 +00003428
Larisse Voufo19d08672015-01-27 18:47:05 +00003429 // C++11 [dcl.init.list]p3, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003430 // - If T is a class type and the initializer list has a single element of
3431 // type cv U, where U is T or a class derived from T, the object is
3432 // initialized from that element (by copy-initialization for
3433 // copy-list-initialization, or by direct-initialization for
3434 // direct-list-initialization).
3435 // - Otherwise, if T is a character array and the initializer list has a
3436 // single element that is an appropriately-typed string literal
3437 // (8.5.2 [dcl.init.string]), initialization is performed as described
3438 // in that section.
Larisse Voufo19d08672015-01-27 18:47:05 +00003439 // - Otherwise, if T is an aggregate, [...] (continue below).
3440 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
Larisse Voufod2010992015-01-24 23:09:54 +00003441 if (DestType->isRecordType()) {
3442 QualType InitType = InitList->getInit(0)->getType();
3443 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
3444 S.IsDerivedFrom(InitType, DestType)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003445 Expr *InitListAsExpr = InitList;
3446 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smithd86812d2012-07-05 08:39:21 +00003447 Sequence, /*InitListSyntax*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00003448 return;
3449 }
3450 }
3451 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
3452 Expr *SubInit[1] = {InitList->getInit(0)};
3453 if (!isa<VariableArrayType>(DestAT) &&
3454 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
3455 InitializationKind SubKind =
3456 Kind.getKind() == InitializationKind::IK_DirectList
3457 ? InitializationKind::CreateDirect(Kind.getLocation(),
3458 InitList->getLBraceLoc(),
3459 InitList->getRBraceLoc())
3460 : Kind;
3461 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3462 /*TopLevelOfInitList*/ true);
3463
3464 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
3465 // the element is not an appropriately-typed string literal, in which
3466 // case we should proceed as in C++11 (below).
3467 if (Sequence) {
3468 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3469 return;
3470 }
3471 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003472 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003473 }
Larisse Voufod2010992015-01-24 23:09:54 +00003474
3475 // C++11 [dcl.init.list]p3:
3476 // - If T is an aggregate, aggregate initialization is performed.
3477 if (DestType->isRecordType() && !DestType->isAggregateType()) {
3478 if (S.getLangOpts().CPlusPlus11) {
3479 // - Otherwise, if the initializer list has no elements and T is a
3480 // class type with a default constructor, the object is
3481 // value-initialized.
3482 if (InitList->getNumInits() == 0) {
3483 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
3484 if (RD->hasDefaultConstructor()) {
3485 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3486 return;
3487 }
3488 }
3489
3490 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3491 // an initializer_list object constructed [...]
3492 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3493 return;
3494
3495 // - Otherwise, if T is a class type, constructors are considered.
3496 Expr *InitListAsExpr = InitList;
3497 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
3498 Sequence, /*InitListSyntax*/ true);
3499 } else
3500 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
3501 return;
3502 }
3503
Richard Smith089c3162013-09-21 21:55:46 +00003504 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
3505 InitList->getNumInits() == 1 &&
3506 InitList->getInit(0)->getType()->isRecordType()) {
3507 // - Otherwise, if the initializer list has a single element of type E
3508 // [...references are handled above...], the object or reference is
Larisse Voufod2010992015-01-24 23:09:54 +00003509 // initialized from that element (by copy-initialization for
3510 // copy-list-initialization, or by direct-initialization for
3511 // direct-list-initialization); if a narrowing conversion is required
3512 // to convert the element to T, the program is ill-formed.
3513 //
Richard Smith089c3162013-09-21 21:55:46 +00003514 // Per core-24034, this is direct-initialization if we were performing
3515 // direct-list-initialization and copy-initialization otherwise.
3516 // We can't use InitListChecker for this, because it always performs
3517 // copy-initialization. This only matters if we might use an 'explicit'
3518 // conversion operator, so we only need to handle the cases where the source
3519 // is of record type.
3520 InitializationKind SubKind =
3521 Kind.getKind() == InitializationKind::IK_DirectList
3522 ? InitializationKind::CreateDirect(Kind.getLocation(),
3523 InitList->getLBraceLoc(),
3524 InitList->getRBraceLoc())
3525 : Kind;
3526 Expr *SubInit[1] = { InitList->getInit(0) };
3527 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3528 /*TopLevelOfInitList*/true);
3529 if (Sequence)
3530 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3531 return;
3532 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003533
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003534 InitListChecker CheckInitList(S, Entity, InitList,
Richard Smithde229232013-06-06 11:41:05 +00003535 DestType, /*VerifyOnly=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003536 if (CheckInitList.HadError()) {
3537 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3538 return;
3539 }
3540
3541 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003542 Sequence.AddListInitializationStep(DestType);
3543}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003544
3545/// \brief Try a reference initialization that involves calling a conversion
3546/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003547static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3548 const InitializedEntity &Entity,
3549 const InitializationKind &Kind,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003550 Expr *Initializer,
3551 bool AllowRValues,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003552 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003553 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003554 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3555 QualType T1 = cv1T1.getUnqualifiedType();
3556 QualType cv2T2 = Initializer->getType();
3557 QualType T2 = cv2T2.getUnqualifiedType();
3558
3559 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003560 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003561 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003562 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003563 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003564 ObjCConversion,
3565 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003566 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003567 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003568 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003569 (void)ObjCLifetimeConversion;
3570
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003571 // Build the candidate set directly in the initialization sequence
3572 // structure, so that it will persist if we fail.
3573 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3574 CandidateSet.clear();
3575
3576 // Determine whether we are allowed to call explicit constructors or
3577 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003578 bool AllowExplicit = Kind.AllowExplicit();
Richard Smith6c6ddab2013-09-21 21:23:47 +00003579 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3580
Craig Topperc3ec1492014-05-26 06:22:03 +00003581 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003582 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3583 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003584 // The type we're converting to is a class type. Enumerate its constructors
3585 // to see if there is a suitable conversion.
3586 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003587
David Blaikieff7d47a2012-12-19 00:45:41 +00003588 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003589 // The container holding the constructors can under certain conditions
3590 // be changed while iterating (e.g. because of deserialization).
3591 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003592 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00003593 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003594 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3595 NamedDecl *D = *CI;
John McCalla0296f72010-03-19 07:35:19 +00003596 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3597
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003598 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003599 CXXConstructorDecl *Constructor = nullptr;
John McCalla0296f72010-03-19 07:35:19 +00003600 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003601 if (ConstructorTmpl)
3602 Constructor = cast<CXXConstructorDecl>(
3603 ConstructorTmpl->getTemplatedDecl());
3604 else
John McCalla0296f72010-03-19 07:35:19 +00003605 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003606
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003607 if (!Constructor->isInvalidDecl() &&
3608 Constructor->isConvertingConstructor(AllowExplicit)) {
3609 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003610 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003611 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003612 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003613 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003614 else
John McCalla0296f72010-03-19 07:35:19 +00003615 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003616 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003617 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003618 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003619 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003620 }
John McCall3696dcb2010-08-17 07:23:57 +00003621 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3622 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003623
Craig Topperc3ec1492014-05-26 06:22:03 +00003624 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003625 if ((T2RecordType = T2->getAs<RecordType>()) &&
3626 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003627 // The type we're converting from is a class type, enumerate its conversion
3628 // functions.
3629 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3630
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003631 std::pair<CXXRecordDecl::conversion_iterator,
3632 CXXRecordDecl::conversion_iterator>
3633 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3634 for (CXXRecordDecl::conversion_iterator
3635 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003636 NamedDecl *D = *I;
3637 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3638 if (isa<UsingShadowDecl>(D))
3639 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003640
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003641 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3642 CXXConversionDecl *Conv;
3643 if (ConvTemplate)
3644 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3645 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003646 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003647
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003648 // If the conversion function doesn't return a reference type,
3649 // it can't be considered for this conversion unless we're allowed to
3650 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003651 // FIXME: Do we need to make sure that we only consider conversion
3652 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003653 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00003654 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003655 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3656 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003657 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003658 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00003659 DestType, CandidateSet,
3660 /*AllowObjCConversionOnExplicit=*/
3661 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003662 else
John McCalla0296f72010-03-19 07:35:19 +00003663 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00003664 Initializer, DestType, CandidateSet,
3665 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003666 }
3667 }
3668 }
John McCall3696dcb2010-08-17 07:23:57 +00003669 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3670 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003671
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003672 SourceLocation DeclLoc = Initializer->getLocStart();
3673
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003674 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003675 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003676 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003677 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003678 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003679
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003680 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00003681 // This is the overload that will be used for this initialization step if we
3682 // use this initialization. Mark it as referenced.
3683 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00003684
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003685 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003686 if (isa<CXXConversionDecl>(Function))
Alp Toker314cc812014-01-25 16:55:45 +00003687 T2 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003688 else
3689 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003690
3691 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003692 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003693 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003694 T2.getNonLValueExprType(S.Context),
3695 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003696
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003697 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003698 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003699 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003700 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003701 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003702 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003703 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003704
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003705 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003706 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003707 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003708 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003709 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003710 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003711 NewDerivedToBase, NewObjCConversion,
3712 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003713 if (NewRefRelationship == Sema::Ref_Incompatible) {
3714 // If the type we've converted to is not reference-related to the
3715 // type we're looking for, then there is another conversion step
3716 // we need to perform to produce a temporary of the right type
3717 // that we'll be binding to.
3718 ImplicitConversionSequence ICS;
3719 ICS.setStandard();
3720 ICS.Standard = Best->FinalConversion;
3721 T2 = ICS.Standard.getToType(2);
3722 Sequence.AddConversionSequenceStep(ICS, T2);
3723 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003724 Sequence.AddDerivedToBaseCastStep(
3725 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003726 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003727 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003728 else if (NewObjCConversion)
3729 Sequence.AddObjCObjectConversionStep(
3730 S.Context.getQualifiedType(T1,
3731 T2.getNonReferenceType().getQualifiers()));
3732
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003733 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003734 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003735
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003736 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3737 return OR_Success;
3738}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003739
Richard Smithc620f552011-10-19 16:55:56 +00003740static void CheckCXX98CompatAccessibleCopy(Sema &S,
3741 const InitializedEntity &Entity,
3742 Expr *CurInitExpr);
3743
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003744/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3745static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003746 const InitializedEntity &Entity,
3747 const InitializationKind &Kind,
3748 Expr *Initializer,
3749 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003750 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003751 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003752 Qualifiers T1Quals;
3753 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003754 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003755 Qualifiers T2Quals;
3756 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003757
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003758 // If the initializer is the address of an overloaded function, try
3759 // to resolve the overloaded function. If all goes well, T2 is the
3760 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003761 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3762 T1, Sequence))
3763 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003764
Sebastian Redl29526f02011-11-27 16:50:07 +00003765 // Delegate everything else to a subfunction.
3766 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3767 T1Quals, cv2T2, T2, T2Quals, Sequence);
3768}
3769
Jordan Roseb1312a52013-04-11 00:58:58 +00003770/// Converts the target of reference initialization so that it has the
3771/// appropriate qualifiers and value kind.
3772///
3773/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3774/// \code
3775/// int x;
3776/// const int &r = x;
3777/// \endcode
3778///
3779/// In this case the reference is binding to a bitfield lvalue, which isn't
3780/// valid. Perform a load to create a lifetime-extended temporary instead.
3781/// \code
3782/// const int &r = someStruct.bitfield;
3783/// \endcode
3784static ExprValueKind
3785convertQualifiersAndValueKindIfNecessary(Sema &S,
3786 InitializationSequence &Sequence,
3787 Expr *Initializer,
3788 QualType cv1T1,
3789 Qualifiers T1Quals,
3790 Qualifiers T2Quals,
3791 bool IsLValueRef) {
John McCalld25db7e2013-05-06 21:39:12 +00003792 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Roseb1312a52013-04-11 00:58:58 +00003793 Initializer->refersToVectorElement();
3794
3795 if (IsNonAddressableType) {
3796 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3797 // lvalue reference to a non-volatile const type, or the reference shall be
3798 // an rvalue reference.
3799 //
3800 // If not, we can't make a temporary and bind to that. Give up and allow the
3801 // error to be diagnosed later.
3802 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3803 assert(Initializer->isGLValue());
3804 return Initializer->getValueKind();
3805 }
3806
3807 // Force a load so we can materialize a temporary.
3808 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3809 return VK_RValue;
3810 }
3811
3812 if (T1Quals != T2Quals) {
3813 Sequence.AddQualificationConversionStep(cv1T1,
3814 Initializer->getValueKind());
3815 }
3816
3817 return Initializer->getValueKind();
3818}
3819
3820
Sebastian Redl29526f02011-11-27 16:50:07 +00003821/// \brief Reference initialization without resolving overloaded functions.
3822static void TryReferenceInitializationCore(Sema &S,
3823 const InitializedEntity &Entity,
3824 const InitializationKind &Kind,
3825 Expr *Initializer,
3826 QualType cv1T1, QualType T1,
3827 Qualifiers T1Quals,
3828 QualType cv2T2, QualType T2,
3829 Qualifiers T2Quals,
3830 InitializationSequence &Sequence) {
3831 QualType DestType = Entity.getType();
3832 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003833 // Compute some basic properties of the types and the initializer.
3834 bool isLValueRef = DestType->isLValueReferenceType();
3835 bool isRValueRef = !isLValueRef;
3836 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003837 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003838 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003839 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003840 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003841 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003842 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003843
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003844 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003845 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003846 // "cv2 T2" as follows:
3847 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003848 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003849 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00003850 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00003851 // there are no function rvalues in C++, rvalue refs to functions are treated
3852 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003853 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003854 bool T1Function = T1->isFunctionType();
3855 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003856 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003857 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003858 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003859 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003860 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003861 // reference-compatible with "cv2 T2," or
3862 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003863 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003864 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003865 // can occur. However, we do pay attention to whether it is a bit-field
3866 // to decide whether we're actually binding to a temporary created from
3867 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003868 if (DerivedToBase)
3869 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003870 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003871 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003872 else if (ObjCConversion)
3873 Sequence.AddObjCObjectConversionStep(
3874 S.Context.getQualifiedType(T1, T2Quals));
3875
Jordan Roseb1312a52013-04-11 00:58:58 +00003876 ExprValueKind ValueKind =
3877 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3878 cv1T1, T1Quals, T2Quals,
3879 isLValueRef);
3880 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003881 return;
3882 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003883
3884 // - has a class type (i.e., T2 is a class type), where T1 is not
3885 // reference-related to T2, and can be implicitly converted to an
3886 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3887 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003888 // applicable conversion functions (13.3.1.6) and choosing the best
3889 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003890 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00003891 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00003892 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3893 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003894 ConvOvlResult = TryRefInitWithConversionFunction(
3895 S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003896 if (ConvOvlResult == OR_Success)
3897 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00003898 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00003899 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003900 InitializationSequence::FK_ReferenceInitOverloadFailed,
3901 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003902 }
3903 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003904
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003905 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003906 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003907 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003908 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003909 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3910 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3911 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003912 Sequence.SetOverloadFailure(
3913 InitializationSequence::FK_ReferenceInitOverloadFailed,
3914 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003915 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003916 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003917 ? (RefRelationship == Sema::Ref_Related
3918 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3919 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3920 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003921
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003922 return;
3923 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003924
Douglas Gregor92e460e2011-01-20 16:44:54 +00003925 // - If the initializer expression
3926 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3927 // "cv1 T1" is reference-compatible with "cv2 T2"
3928 // Note: functions are handled below.
3929 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003930 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003931 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003932 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003933 (InitCategory.isXValue() ||
3934 (InitCategory.isPRValue() && T2->isRecordType()) ||
3935 (InitCategory.isPRValue() && T2->isArrayType()))) {
3936 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3937 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003938 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3939 // compiler the freedom to perform a copy here or bind to the
3940 // object, while C++0x requires that we bind directly to the
3941 // object. Hence, we always bind to the object without making an
3942 // extra copy. However, in C++03 requires that we check for the
3943 // presence of a suitable copy constructor:
3944 //
3945 // The constructor that would be used to make the copy shall
3946 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003947 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003948 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003949 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00003950 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003951 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003952
Douglas Gregor92e460e2011-01-20 16:44:54 +00003953 if (DerivedToBase)
3954 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3955 ValueKind);
3956 else if (ObjCConversion)
3957 Sequence.AddObjCObjectConversionStep(
3958 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003959
Jordan Roseb1312a52013-04-11 00:58:58 +00003960 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3961 Initializer, cv1T1,
3962 T1Quals, T2Quals,
3963 isLValueRef);
3964
3965 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003966 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003967 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003968
3969 // - has a class type (i.e., T2 is a class type), where T1 is not
3970 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003971 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3972 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00003973 //
3974 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00003975 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003976 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003977 ConvOvlResult = TryRefInitWithConversionFunction(
3978 S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003979 if (ConvOvlResult)
3980 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003981 InitializationSequence::FK_ReferenceInitOverloadFailed,
3982 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003983
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003984 return;
3985 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003986
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00003987 if ((RefRelationship == Sema::Ref_Compatible ||
3988 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3989 isRValueRef && InitCategory.isLValue()) {
3990 Sequence.SetFailed(
3991 InitializationSequence::FK_RValueReferenceBindingToLValue);
3992 return;
3993 }
3994
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003995 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3996 return;
3997 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003998
3999 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004000 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00004001 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004002 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00004003
John McCallec6f4e92010-06-04 02:29:22 +00004004 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4005
Richard Smith2eabf782013-06-13 00:57:57 +00004006 // FIXME: Why do we use an implicit conversion here rather than trying
4007 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00004008 ImplicitConversionSequence ICS
4009 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00004010 /*SuppressUserConversions=*/false,
4011 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004012 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004013 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4014 /*AllowObjCWritebackConversion=*/false);
4015
4016 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004017 // FIXME: Use the conversion function set stored in ICS to turn
4018 // this into an overloading ambiguity diagnostic. However, we need
4019 // to keep that set as an OverloadCandidateSet rather than as some
4020 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004021 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4022 Sequence.SetOverloadFailure(
4023 InitializationSequence::FK_ReferenceInitOverloadFailed,
4024 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004025 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4026 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004027 else
4028 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004029 return;
John McCall31168b02011-06-15 23:02:42 +00004030 } else {
4031 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004032 }
4033
4034 // [...] If T1 is reference-related to T2, cv1 must be the
4035 // same cv-qualification as, or greater cv-qualification
4036 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004037 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4038 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004039 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00004040 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004041 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4042 return;
4043 }
4044
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004045 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004046 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004047 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004048 InitCategory.isLValue()) {
4049 Sequence.SetFailed(
4050 InitializationSequence::FK_RValueReferenceBindingToLValue);
4051 return;
4052 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004053
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004054 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4055 return;
4056}
4057
4058/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004059/// (C++ [dcl.init.string], C99 6.7.8).
4060static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004061 const InitializedEntity &Entity,
4062 const InitializationKind &Kind,
4063 Expr *Initializer,
4064 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004065 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004066}
4067
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004068/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004069static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004070 const InitializedEntity &Entity,
4071 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004072 InitializationSequence &Sequence,
4073 InitListExpr *InitList) {
4074 assert((!InitList || InitList->getNumInits() == 0) &&
4075 "Shouldn't use value-init for non-empty init lists");
4076
Richard Smith1bfe0682012-02-14 21:14:13 +00004077 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004078 //
4079 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004080 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004081
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004082 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004083 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004084
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004085 if (const RecordType *RT = T->getAs<RecordType>()) {
4086 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004087 bool NeedZeroInitialization = true;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004088 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithd86812d2012-07-05 08:39:21 +00004089 // C++98:
4090 // -- if T is a class type (clause 9) with a user-declared constructor
4091 // (12.1), then the default constructor for T is called (and the
4092 // initialization is ill-formed if T has no accessible default
4093 // constructor);
Richard Smith1bfe0682012-02-14 21:14:13 +00004094 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithd86812d2012-07-05 08:39:21 +00004095 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00004096 } else {
4097 // C++11:
4098 // -- if T is a class type (clause 9) with either no default constructor
4099 // (12.1 [class.ctor]) or a default constructor that is user-provided
4100 // or deleted, then the object is default-initialized;
4101 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4102 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithd86812d2012-07-05 08:39:21 +00004103 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00004104 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004105
Richard Smith1bfe0682012-02-14 21:14:13 +00004106 // -- if T is a (possibly cv-qualified) non-union class type without a
4107 // user-provided or deleted default constructor, then the object is
4108 // zero-initialized and, if T has a non-trivial default constructor,
4109 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004110 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4111 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004112 if (NeedZeroInitialization)
4113 Sequence.AddZeroInitializationStep(Entity.getType());
4114
Richard Smith593f9932012-12-08 02:01:17 +00004115 // C++03:
4116 // -- if T is a non-union class type without a user-declared constructor,
4117 // then every non-static data member and base class component of T is
4118 // value-initialized;
4119 // [...] A program that calls for [...] value-initialization of an
4120 // entity of reference type is ill-formed.
4121 //
4122 // C++11 doesn't need this handling, because value-initialization does not
4123 // occur recursively there, and the implicit default constructor is
4124 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004125 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004126 ClassDecl->hasUninitializedReferenceMember()) {
4127 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4128 return;
4129 }
4130
Richard Smithd86812d2012-07-05 08:39:21 +00004131 // If this is list-value-initialization, pass the empty init list on when
4132 // building the constructor call. This affects the semantics of a few
4133 // things (such as whether an explicit default constructor can be called).
4134 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004135 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004136 bool InitListSyntax = InitList;
4137
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004138 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4139 InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004140 }
4141 }
4142
Douglas Gregor1b303932009-12-22 15:35:07 +00004143 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004144}
4145
Douglas Gregor85dabae2009-12-16 01:38:02 +00004146/// \brief Attempt default initialization (C++ [dcl.init]p6).
4147static void TryDefaultInitialization(Sema &S,
4148 const InitializedEntity &Entity,
4149 const InitializationKind &Kind,
4150 InitializationSequence &Sequence) {
4151 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004152
Douglas Gregor85dabae2009-12-16 01:38:02 +00004153 // C++ [dcl.init]p6:
4154 // To default-initialize an object of type T means:
4155 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004156 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4157
Douglas Gregor85dabae2009-12-16 01:38:02 +00004158 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4159 // constructor for T is called (and the initialization is ill-formed if
4160 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004161 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004162 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004163 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004165
Douglas Gregor85dabae2009-12-16 01:38:02 +00004166 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004167
Douglas Gregor85dabae2009-12-16 01:38:02 +00004168 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004169 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004170 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004171 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004172 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004173 return;
4174 }
4175
4176 // If the destination type has a lifetime property, zero-initialize it.
4177 if (DestType.getQualifiers().hasObjCLifetime()) {
4178 Sequence.AddZeroInitializationStep(Entity.getType());
4179 return;
4180 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004181}
4182
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004183/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4184/// which enumerates all conversion functions and performs overload resolution
4185/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004186static void TryUserDefinedConversion(Sema &S,
Richard Smith77be48a2014-07-31 06:31:19 +00004187 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004188 const InitializationKind &Kind,
4189 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004190 InitializationSequence &Sequence,
4191 bool TopLevelOfInitList) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004192 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4193 QualType SourceType = Initializer->getType();
4194 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4195 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004196
Douglas Gregor540c3b02009-12-14 17:27:33 +00004197 // Build the candidate set directly in the initialization sequence
4198 // structure, so that it will persist if we fail.
4199 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4200 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004201
Douglas Gregor540c3b02009-12-14 17:27:33 +00004202 // Determine whether we are allowed to call explicit constructors or
4203 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004204 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004205
Douglas Gregor540c3b02009-12-14 17:27:33 +00004206 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4207 // The type we're converting to is a class type. Enumerate its constructors
4208 // to see if there is a suitable conversion.
4209 CXXRecordDecl *DestRecordDecl
4210 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004211
Douglas Gregord9848152010-04-26 14:36:57 +00004212 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004213 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004214 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie12be6392012-10-18 16:57:32 +00004215 // The container holding the constructors can under certain conditions
4216 // be changed while iterating. To be safe we copy the lookup results
4217 // to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004218 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004219 for (SmallVectorImpl<NamedDecl *>::iterator
David Blaikie12be6392012-10-18 16:57:32 +00004220 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregord9848152010-04-26 14:36:57 +00004221 Con != ConEnd; ++Con) {
4222 NamedDecl *D = *Con;
4223 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004224
Douglas Gregord9848152010-04-26 14:36:57 +00004225 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00004226 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregord9848152010-04-26 14:36:57 +00004227 FunctionTemplateDecl *ConstructorTmpl
4228 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004229 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00004230 Constructor = cast<CXXConstructorDecl>(
4231 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00004232 else
Douglas Gregord9848152010-04-26 14:36:57 +00004233 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004234
Douglas Gregord9848152010-04-26 14:36:57 +00004235 if (!Constructor->isInvalidDecl() &&
4236 Constructor->isConvertingConstructor(AllowExplicit)) {
4237 if (ConstructorTmpl)
4238 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004239 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004240 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004241 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004242 else
4243 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004244 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004245 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004246 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004247 }
Douglas Gregord9848152010-04-26 14:36:57 +00004248 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004249 }
Eli Friedman78275202009-12-19 08:11:05 +00004250
4251 SourceLocation DeclLoc = Initializer->getLocStart();
4252
Douglas Gregor540c3b02009-12-14 17:27:33 +00004253 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4254 // The type we're converting from is a class type, enumerate its conversion
4255 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004256
Eli Friedman4afe9a32009-12-20 22:12:03 +00004257 // We can only enumerate the conversion functions for a complete type; if
4258 // the type isn't complete, simply skip this step.
4259 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4260 CXXRecordDecl *SourceRecordDecl
4261 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004262
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004263 std::pair<CXXRecordDecl::conversion_iterator,
4264 CXXRecordDecl::conversion_iterator>
4265 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4266 for (CXXRecordDecl::conversion_iterator
4267 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004268 NamedDecl *D = *I;
4269 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4270 if (isa<UsingShadowDecl>(D))
4271 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004272
Eli Friedman4afe9a32009-12-20 22:12:03 +00004273 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4274 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004275 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004276 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004277 else
John McCallda4458e2010-03-31 01:36:47 +00004278 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004279
Eli Friedman4afe9a32009-12-20 22:12:03 +00004280 if (AllowExplicit || !Conv->isExplicit()) {
4281 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004282 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004283 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004284 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004285 else
John McCalla0296f72010-03-19 07:35:19 +00004286 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004287 Initializer, DestType, CandidateSet,
4288 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004289 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004290 }
4291 }
4292 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004293
4294 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004295 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004296 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00004297 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004298 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004300 Result);
4301 return;
4302 }
John McCall0d1da222010-01-12 00:44:57 +00004303
Douglas Gregor540c3b02009-12-14 17:27:33 +00004304 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004305 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004306 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004307
Douglas Gregor540c3b02009-12-14 17:27:33 +00004308 if (isa<CXXConstructorDecl>(Function)) {
4309 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004310 // subsumed by the initialization. Per DR5, the created temporary is of the
4311 // cv-unqualified type of the destination.
4312 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4313 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004314 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004315 return;
4316 }
4317
4318 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004319 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004320 if (ConvType->getAs<RecordType>()) {
Richard Smithb24f0672012-02-11 19:22:50 +00004321 // If we're converting to a class type, there may be an copy of
Douglas Gregor5ab11652010-04-17 22:01:05 +00004322 // the resulting temporary object (possible to create an object of
4323 // a base class type). That copy is not a separate conversion, so
4324 // we just make a note of the actual destination type (possibly a
4325 // base class of the type returned by the conversion function) and
4326 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004327 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4328 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004329 return;
4330 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004331
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004332 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4333 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004334
Douglas Gregor5ab11652010-04-17 22:01:05 +00004335 // If the conversion following the call to the conversion function
4336 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004337 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4338 Best->FinalConversion.Third) {
4339 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004340 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004341 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004342 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004343 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004344}
4345
Richard Smithf032001b2013-06-20 02:18:31 +00004346/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4347/// a function with a pointer return type contains a 'return false;' statement.
4348/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4349/// code using that header.
4350///
4351/// Work around this by treating 'return false;' as zero-initializing the result
4352/// if it's used in a pointer-returning function in a system header.
4353static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4354 const InitializedEntity &Entity,
4355 const Expr *Init) {
4356 return S.getLangOpts().CPlusPlus11 &&
4357 Entity.getKind() == InitializedEntity::EK_Result &&
4358 Entity.getType()->isPointerType() &&
4359 isa<CXXBoolLiteralExpr>(Init) &&
4360 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4361 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4362}
4363
John McCall31168b02011-06-15 23:02:42 +00004364/// The non-zero enum values here are indexes into diagnostic alternatives.
4365enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4366
4367/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00004368static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004369 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00004370 // Skip parens.
4371 e = e->IgnoreParens();
4372
4373 // Skip address-of nodes.
4374 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4375 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004376 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4377 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004378
4379 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00004380 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4381 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00004382 case CK_Dependent:
4383 case CK_BitCast:
4384 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00004385 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004386 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004387
4388 case CK_ArrayToPointerDecay:
4389 return IIK_nonscalar;
4390
4391 case CK_NullToPointer:
4392 return IIK_okay;
4393
4394 default:
4395 break;
4396 }
4397
4398 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00004399 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004400 // set isWeakAccess to true, to mean that there will be an implicit
4401 // load which requires a cleanup.
4402 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4403 isWeakAccess = true;
4404
John McCall63f84442011-06-27 23:59:58 +00004405 if (!isAddressOf) return IIK_nonlocal;
4406
John McCall113bee02012-03-10 09:33:50 +00004407 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4408 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00004409
4410 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00004411
4412 // If we have a conditional operator, check both sides.
4413 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004414 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4415 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00004416 return iik;
4417
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004418 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004419
4420 // These are never scalar.
4421 } else if (isa<ArraySubscriptExpr>(e)) {
4422 return IIK_nonscalar;
4423
4424 // Otherwise, it needs to be a null pointer constant.
4425 } else {
4426 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4427 ? IIK_okay : IIK_nonlocal);
4428 }
4429
4430 return IIK_nonlocal;
4431}
4432
4433/// Check whether the given expression is a valid operand for an
4434/// indirect copy/restore.
4435static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4436 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004437 bool isWeakAccess = false;
4438 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4439 // If isWeakAccess to true, there will be an implicit
4440 // load which requires a cleanup.
4441 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4442 S.ExprNeedsCleanups = true;
4443
John McCall31168b02011-06-15 23:02:42 +00004444 if (iik == IIK_okay) return;
4445
4446 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4447 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4448 << src->getSourceRange();
4449}
4450
Douglas Gregore2f943b2011-02-22 18:29:51 +00004451/// \brief Determine whether we have compatible array types for the
4452/// purposes of GNU by-copy array initialization.
Larisse Voufod2010992015-01-24 23:09:54 +00004453static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
Douglas Gregore2f943b2011-02-22 18:29:51 +00004454 const ArrayType *Source) {
4455 // If the source and destination array types are equivalent, we're
4456 // done.
4457 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4458 return true;
4459
4460 // Make sure that the element types are the same.
4461 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4462 return false;
4463
4464 // The only mismatch we allow is when the destination is an
4465 // incomplete array type and the source is a constant array type.
4466 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4467}
4468
John McCall31168b02011-06-15 23:02:42 +00004469static bool tryObjCWritebackConversion(Sema &S,
4470 InitializationSequence &Sequence,
4471 const InitializedEntity &Entity,
4472 Expr *Initializer) {
4473 bool ArrayDecay = false;
4474 QualType ArgType = Initializer->getType();
4475 QualType ArgPointee;
4476 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4477 ArrayDecay = true;
4478 ArgPointee = ArgArrayType->getElementType();
4479 ArgType = S.Context.getPointerType(ArgPointee);
4480 }
4481
4482 // Handle write-back conversion.
4483 QualType ConvertedArgType;
4484 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4485 ConvertedArgType))
4486 return false;
4487
4488 // We should copy unless we're passing to an argument explicitly
4489 // marked 'out'.
4490 bool ShouldCopy = true;
4491 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4492 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4493
4494 // Do we need an lvalue conversion?
4495 if (ArrayDecay || Initializer->isGLValue()) {
4496 ImplicitConversionSequence ICS;
4497 ICS.setStandard();
4498 ICS.Standard.setAsIdentityConversion();
4499
4500 QualType ResultType;
4501 if (ArrayDecay) {
4502 ICS.Standard.First = ICK_Array_To_Pointer;
4503 ResultType = S.Context.getPointerType(ArgPointee);
4504 } else {
4505 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4506 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4507 }
4508
4509 Sequence.AddConversionSequenceStep(ICS, ResultType);
4510 }
4511
4512 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4513 return true;
4514}
4515
Guy Benyei61054192013-02-07 10:55:47 +00004516static bool TryOCLSamplerInitialization(Sema &S,
4517 InitializationSequence &Sequence,
4518 QualType DestType,
4519 Expr *Initializer) {
4520 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4521 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4522 return false;
4523
4524 Sequence.AddOCLSamplerInitStep(DestType);
4525 return true;
4526}
4527
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004528//
4529// OpenCL 1.2 spec, s6.12.10
4530//
4531// The event argument can also be used to associate the
4532// async_work_group_copy with a previous async copy allowing
4533// an event to be shared by multiple async copies; otherwise
4534// event should be zero.
4535//
4536static bool TryOCLZeroEventInitialization(Sema &S,
4537 InitializationSequence &Sequence,
4538 QualType DestType,
4539 Expr *Initializer) {
4540 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4541 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4542 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4543 return false;
4544
4545 Sequence.AddOCLZeroEventStep(DestType);
4546 return true;
4547}
4548
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004549InitializationSequence::InitializationSequence(Sema &S,
4550 const InitializedEntity &Entity,
4551 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004552 MultiExprArg Args,
4553 bool TopLevelOfInitList)
Richard Smith100b24a2014-04-17 01:52:14 +00004554 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Richard Smith089c3162013-09-21 21:55:46 +00004555 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
4556}
4557
4558void InitializationSequence::InitializeFrom(Sema &S,
4559 const InitializedEntity &Entity,
4560 const InitializationKind &Kind,
4561 MultiExprArg Args,
4562 bool TopLevelOfInitList) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004563 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004564
John McCall5e77d762013-04-16 07:28:30 +00004565 // Eliminate non-overload placeholder types in the arguments. We
4566 // need to do this before checking whether types are dependent
4567 // because lowering a pseudo-object expression might well give us
4568 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004569 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00004570 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4571 // FIXME: should we be doing this here?
4572 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4573 if (result.isInvalid()) {
4574 SetFailed(FK_PlaceholderType);
4575 return;
4576 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004577 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00004578 }
4579
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004580 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004581 // The semantics of initializers are as follows. The destination type is
4582 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004583 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004584 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004585 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004586 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004587
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004588 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004589 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004590 SequenceKind = DependentSequence;
4591 return;
4592 }
4593
Sebastian Redld201edf2011-06-05 13:59:11 +00004594 // Almost everything is a normal sequence.
4595 setSequenceKind(NormalSequence);
4596
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004597 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00004598 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004599 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004600 Initializer = Args[0];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004601 if (S.getLangOpts().ObjC1) {
4602 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
4603 DestType, Initializer->getType(),
4604 Initializer) ||
4605 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
4606 Args[0] = Initializer;
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004607 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004608 if (!isa<InitListExpr>(Initializer))
4609 SourceType = Initializer->getType();
4610 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004611
Sebastian Redl0501c632012-02-12 16:37:36 +00004612 // - If the initializer is a (non-parenthesized) braced-init-list, the
4613 // object is list-initialized (8.5.4).
4614 if (Kind.getKind() != InitializationKind::IK_Direct) {
4615 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4616 TryListInitialization(S, Entity, Kind, InitList, *this);
4617 return;
4618 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004619 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004620
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004621 // - If the destination type is a reference type, see 8.5.3.
4622 if (DestType->isReferenceType()) {
4623 // C++0x [dcl.init.ref]p1:
4624 // A variable declared to be a T& or T&&, that is, "reference to type T"
4625 // (8.3.2), shall be initialized by an object, or function, of type T or
4626 // by an object that can be converted into a T.
4627 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004628 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004629 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004630 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004631 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
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 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004636 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004637 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004638 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004639 return;
4640 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004641
Douglas Gregor85dabae2009-12-16 01:38:02 +00004642 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004643 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004644 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004645 return;
4646 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004647
John McCall66884dd2011-02-21 07:22:22 +00004648 // - If the destination type is an array of characters, an array of
4649 // char16_t, an array of char32_t, or an array of wchar_t, and the
4650 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004651 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004652 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004653 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004654 if (Initializer && isa<VariableArrayType>(DestAT)) {
4655 SetFailed(FK_VariableLengthArrayHasInitializer);
4656 return;
4657 }
4658
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004659 if (Initializer) {
4660 switch (IsStringInit(Initializer, DestAT, Context)) {
4661 case SIF_None:
4662 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4663 return;
4664 case SIF_NarrowStringIntoWideChar:
4665 SetFailed(FK_NarrowStringIntoWideCharArray);
4666 return;
4667 case SIF_WideStringIntoChar:
4668 SetFailed(FK_WideStringIntoCharArray);
4669 return;
4670 case SIF_IncompatWideStringIntoWideChar:
4671 SetFailed(FK_IncompatWideStringIntoWideChar);
4672 return;
4673 case SIF_Other:
4674 break;
4675 }
John McCall66884dd2011-02-21 07:22:22 +00004676 }
4677
Douglas Gregore2f943b2011-02-22 18:29:51 +00004678 // Note: as an GNU C extension, we allow initialization of an
4679 // array from a compound literal that creates an array of the same
4680 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004681 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00004682 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4683 Initializer->getType()->isArrayType()) {
4684 const ArrayType *SourceAT
4685 = Context.getAsArrayType(Initializer->getType());
4686 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004687 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004688 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004689 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004690 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004691 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004692 }
Richard Smithebeed412012-02-15 22:38:09 +00004693 }
Richard Smithd86812d2012-07-05 08:39:21 +00004694 // Note: as a GNU C++ extension, we allow list-initialization of a
4695 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004696 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00004697 Entity.getKind() == InitializedEntity::EK_Member &&
4698 Initializer && isa<InitListExpr>(Initializer)) {
4699 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4700 *this);
4701 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004702 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004703 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004704 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4705 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004706 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004707 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004708
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004709 return;
4710 }
Eli Friedman78275202009-12-19 08:11:05 +00004711
Larisse Voufod2010992015-01-24 23:09:54 +00004712 // Determine whether we should consider writeback conversions for
John McCall31168b02011-06-15 23:02:42 +00004713 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004714 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004715 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00004716
4717 // We're at the end of the line for C: it's either a write-back conversion
4718 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004719 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004720 // If allowed, check whether this is an Objective-C writeback conversion.
4721 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004722 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004723 return;
4724 }
Guy Benyei61054192013-02-07 10:55:47 +00004725
4726 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4727 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004728
4729 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4730 return;
4731
John McCall31168b02011-06-15 23:02:42 +00004732 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004733 AddCAssignmentStep(DestType);
4734 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004735 return;
4736 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004737
David Blaikiebbafb8a2012-03-11 07:00:24 +00004738 assert(S.getLangOpts().CPlusPlus);
John McCall31168b02011-06-15 23:02:42 +00004739
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004740 // - If the destination type is a (possibly cv-qualified) class type:
4741 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004742 // - If the initialization is direct-initialization, or if it is
4743 // copy-initialization where the cv-unqualified version of the
4744 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004745 // class of the destination, constructors are considered. [...]
4746 if (Kind.getKind() == InitializationKind::IK_Direct ||
4747 (Kind.getKind() == InitializationKind::IK_Copy &&
4748 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4749 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004750 TryConstructorInitialization(S, Entity, Kind, Args,
Richard Smith77be48a2014-07-31 06:31:19 +00004751 DestType, *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004752 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004753 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004754 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004755 // used) to a derived class thereof are enumerated as described in
4756 // 13.3.1.4, and the best one is chosen through overload resolution
4757 // (13.3).
4758 else
Richard Smith77be48a2014-07-31 06:31:19 +00004759 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004760 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004761 return;
4762 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004763
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004764 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004765 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004766 return;
4767 }
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004768 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004769
4770 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004771 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004772 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith77be48a2014-07-31 06:31:19 +00004773 // For a conversion to _Atomic(T) from either T or a class type derived
4774 // from T, initialize the T object then convert to _Atomic type.
4775 bool NeedAtomicConversion = false;
4776 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
4777 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
4778 S.IsDerivedFrom(SourceType, Atomic->getValueType())) {
4779 DestType = Atomic->getValueType();
4780 NeedAtomicConversion = true;
4781 }
4782 }
4783
4784 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004785 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004786 MaybeProduceObjCObject(S, *this, Entity);
Richard Smith77be48a2014-07-31 06:31:19 +00004787 if (!Failed() && NeedAtomicConversion)
4788 AddAtomicConversionStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004789 return;
4790 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004791
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004792 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004793 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004794 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004795 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004796 // destination type; no user-defined conversions are considered.
Richard Smith77be48a2014-07-31 06:31:19 +00004797
John McCall31168b02011-06-15 23:02:42 +00004798 ImplicitConversionSequence ICS
Richard Smith77be48a2014-07-31 06:31:19 +00004799 = S.TryImplicitConversion(Initializer, DestType,
John McCall31168b02011-06-15 23:02:42 +00004800 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004801 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004802 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004803 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4804 allowObjCWritebackConversion);
Richard Smith77be48a2014-07-31 06:31:19 +00004805
4806 if (ICS.isStandard() &&
John McCall31168b02011-06-15 23:02:42 +00004807 ICS.Standard.Second == ICK_Writeback_Conversion) {
4808 // Objective-C ARC writeback conversion.
4809
4810 // We should copy unless we're passing to an argument explicitly
4811 // marked 'out'.
4812 bool ShouldCopy = true;
4813 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4814 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4815
4816 // If there was an lvalue adjustment, add it as a separate conversion.
4817 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4818 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4819 ImplicitConversionSequence LvalueICS;
4820 LvalueICS.setStandard();
4821 LvalueICS.Standard.setAsIdentityConversion();
4822 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4823 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004824 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004825 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004826
Richard Smith77be48a2014-07-31 06:31:19 +00004827 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004828 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004829 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00004830 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4831 AddZeroInitializationStep(Entity.getType());
4832 } else if (Initializer->getType() == Context.OverloadTy &&
4833 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4834 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004835 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004836 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004837 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004838 } else {
Richard Smith77be48a2014-07-31 06:31:19 +00004839 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00004840
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004841 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004842 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004843}
4844
4845InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004846 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004847 StepEnd = Steps.end();
4848 Step != StepEnd; ++Step)
4849 Step->Destroy();
4850}
4851
4852//===----------------------------------------------------------------------===//
4853// Perform initialization
4854//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004855static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004856getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004857 switch(Entity.getKind()) {
4858 case InitializedEntity::EK_Variable:
4859 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004860 case InitializedEntity::EK_Exception:
4861 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004862 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004863 return Sema::AA_Initializing;
4864
4865 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004866 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004867 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4868 return Sema::AA_Sending;
4869
Douglas Gregore1314a62009-12-18 05:02:21 +00004870 return Sema::AA_Passing;
4871
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004872 case InitializedEntity::EK_Parameter_CF_Audited:
4873 if (Entity.getDecl() &&
4874 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4875 return Sema::AA_Sending;
4876
4877 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4878
Douglas Gregore1314a62009-12-18 05:02:21 +00004879 case InitializedEntity::EK_Result:
4880 return Sema::AA_Returning;
4881
Douglas Gregore1314a62009-12-18 05:02:21 +00004882 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00004883 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004884 // FIXME: Can we tell apart casting vs. converting?
4885 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004886
Douglas Gregore1314a62009-12-18 05:02:21 +00004887 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004888 case InitializedEntity::EK_ArrayElement:
4889 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004890 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004891 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004892 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004893 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004894 return Sema::AA_Initializing;
4895 }
4896
David Blaikie8a40f702012-01-17 06:56:22 +00004897 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004898}
4899
Richard Smith27874d62013-01-08 00:08:23 +00004900/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00004901/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004902static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004903 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004904 case InitializedEntity::EK_ArrayElement:
4905 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004906 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004907 case InitializedEntity::EK_New:
4908 case InitializedEntity::EK_Variable:
4909 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004910 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004911 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004912 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004913 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004914 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004915 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004916 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004917 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004918
Douglas Gregore1314a62009-12-18 05:02:21 +00004919 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004920 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00004921 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004922 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004923 return true;
4924 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004925
Douglas Gregore1314a62009-12-18 05:02:21 +00004926 llvm_unreachable("missed an InitializedEntity kind?");
4927}
4928
Douglas Gregor95562572010-04-24 23:45:46 +00004929/// \brief Whether the given entity, when initialized with an object
4930/// created for that initialization, requires destruction.
4931static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4932 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00004933 case InitializedEntity::EK_Result:
4934 case InitializedEntity::EK_New:
4935 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004936 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004937 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004938 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004939 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004940 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00004941 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004942
Richard Smith27874d62013-01-08 00:08:23 +00004943 case InitializedEntity::EK_Member:
Douglas Gregor95562572010-04-24 23:45:46 +00004944 case InitializedEntity::EK_Variable:
4945 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004946 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00004947 case InitializedEntity::EK_Temporary:
4948 case InitializedEntity::EK_ArrayElement:
4949 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004950 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004951 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00004952 return true;
4953 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004954
4955 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004956}
4957
Richard Smithc620f552011-10-19 16:55:56 +00004958/// \brief Look for copy and move constructors and constructor templates, for
4959/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4960static void LookupCopyAndMoveConstructors(Sema &S,
4961 OverloadCandidateSet &CandidateSet,
4962 CXXRecordDecl *Class,
4963 Expr *CurInitExpr) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004964 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004965 // The container holding the constructors can under certain conditions
4966 // be changed while iterating (e.g. because of deserialization).
4967 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004968 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004969 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004970 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4971 NamedDecl *D = *CI;
Craig Topperc3ec1492014-05-26 06:22:03 +00004972 CXXConstructorDecl *Constructor = nullptr;
Richard Smithc620f552011-10-19 16:55:56 +00004973
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004974 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smithc620f552011-10-19 16:55:56 +00004975 // Handle copy/moveconstructors, only.
4976 if (!Constructor || Constructor->isInvalidDecl() ||
4977 !Constructor->isCopyOrMoveConstructor() ||
4978 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4979 continue;
4980
4981 DeclAccessPair FoundDecl
4982 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4983 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004984 CurInitExpr, CandidateSet);
Richard Smithc620f552011-10-19 16:55:56 +00004985 continue;
4986 }
4987
4988 // Handle constructor templates.
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004989 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smithc620f552011-10-19 16:55:56 +00004990 if (ConstructorTmpl->isInvalidDecl())
4991 continue;
4992
4993 Constructor = cast<CXXConstructorDecl>(
4994 ConstructorTmpl->getTemplatedDecl());
4995 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4996 continue;
4997
4998 // FIXME: Do we need to limit this to copy-constructor-like
4999 // candidates?
5000 DeclAccessPair FoundDecl
5001 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
Craig Topperc3ec1492014-05-26 06:22:03 +00005002 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005003 CurInitExpr, CandidateSet, true);
Richard Smithc620f552011-10-19 16:55:56 +00005004 }
5005}
5006
5007/// \brief Get the location at which initialization diagnostics should appear.
5008static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5009 Expr *Initializer) {
5010 switch (Entity.getKind()) {
5011 case InitializedEntity::EK_Result:
5012 return Entity.getReturnLoc();
5013
5014 case InitializedEntity::EK_Exception:
5015 return Entity.getThrowLoc();
5016
5017 case InitializedEntity::EK_Variable:
5018 return Entity.getDecl()->getLocation();
5019
Douglas Gregor19666fb2012-02-15 16:57:26 +00005020 case InitializedEntity::EK_LambdaCapture:
5021 return Entity.getCaptureLoc();
5022
Richard Smithc620f552011-10-19 16:55:56 +00005023 case InitializedEntity::EK_ArrayElement:
5024 case InitializedEntity::EK_Member:
5025 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005026 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00005027 case InitializedEntity::EK_Temporary:
5028 case InitializedEntity::EK_New:
5029 case InitializedEntity::EK_Base:
5030 case InitializedEntity::EK_Delegating:
5031 case InitializedEntity::EK_VectorElement:
5032 case InitializedEntity::EK_ComplexElement:
5033 case InitializedEntity::EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005034 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005035 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00005036 return Initializer->getLocStart();
5037 }
5038 llvm_unreachable("missed an InitializedEntity kind?");
5039}
5040
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005041/// \brief Make a (potentially elidable) temporary copy of the object
5042/// provided by the given initializer by calling the appropriate copy
5043/// constructor.
5044///
5045/// \param S The Sema object used for type-checking.
5046///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005047/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005048/// the type of the initializer expression or a superclass thereof.
5049///
James Dennett634962f2012-06-14 21:40:34 +00005050/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005051///
5052/// \param CurInit The initializer expression.
5053///
5054/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5055/// is permitted in C++03 (but not C++0x) when binding a reference to
5056/// an rvalue.
5057///
5058/// \returns An expression that copies the initializer expression into
5059/// a temporary object, or an error expression if a copy could not be
5060/// created.
John McCalldadc5752010-08-24 06:29:42 +00005061static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005062 QualType T,
5063 const InitializedEntity &Entity,
5064 ExprResult CurInit,
5065 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00005066 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005067 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005068 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005069 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005070 Class = cast<CXXRecordDecl>(Record->getDecl());
5071 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005072 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005073
Douglas Gregor5d369002011-01-21 18:05:27 +00005074 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005075 // When certain criteria are met, an implementation is allowed to
5076 // omit the copy/move construction of a class object, even if the
5077 // copy/move constructor and/or destructor for the object have
5078 // side effects. [...]
5079 // - when a temporary class object that has not been bound to a
5080 // reference (12.2) would be copied/moved to a class object
5081 // with the same cv-unqualified type, the copy/move operation
5082 // can be omitted by constructing the temporary object
5083 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005084 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005085 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00005086 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005087 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00005088 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00005089 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00005090 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005091
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005092 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005093 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005094 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005095
Douglas Gregorf282a762011-01-21 19:38:21 +00005096 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00005097 // Only consider constructors and constructor templates. Per
5098 // C++0x [dcl.init]p16, second bullet to class types, this initialization
5099 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005100 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005101 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005102
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005103 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5104
Douglas Gregore1314a62009-12-18 05:02:21 +00005105 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00005106 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005107 case OR_Success:
5108 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005109
Douglas Gregore1314a62009-12-18 05:02:21 +00005110 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005111 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5112 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5113 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005114 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005115 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005116 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005117 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00005118 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005119 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005120
Douglas Gregore1314a62009-12-18 05:02:21 +00005121 case OR_Ambiguous:
5122 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005123 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005124 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005125 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00005126 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005127
Douglas Gregore1314a62009-12-18 05:02:21 +00005128 case OR_Deleted:
5129 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005130 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005131 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00005132 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00005133 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005134 }
5135
Douglas Gregor5ab11652010-04-17 22:01:05 +00005136 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00005137 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005138 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005139
Anders Carlssona01874b2010-04-21 18:47:17 +00005140 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005141 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005142
5143 if (IsExtraneousCopy) {
5144 // If this is a totally extraneous copy for C++03 reference
5145 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005146 // expression. We don't generate an (elided) copy operation here
5147 // because doing so would require us to pass down a flag to avoid
5148 // infinite recursion, where each step adds another extraneous,
5149 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005150
Douglas Gregor30b52772010-04-18 07:57:34 +00005151 // Instantiate the default arguments of any extra parameters in
5152 // the selected copy constructor, as if we were going to create a
5153 // proper call to the copy constructor.
5154 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5155 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5156 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005157 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005158 break;
5159
5160 // Build the default argument expression; we don't actually care
5161 // if this succeeds or not, because this routine will complain
5162 // if there was a problem.
5163 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5164 }
5165
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005166 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005167 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005168
Douglas Gregor5ab11652010-04-17 22:01:05 +00005169 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005170 // constructor call (we might have derived-to-base conversions, or
5171 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005172 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005173 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005174
Douglas Gregord0ace022010-04-25 00:55:24 +00005175 // Actually perform the constructor call.
5176 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005177 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005178 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005179 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005180 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005181 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005182 CXXConstructExpr::CK_Complete,
5183 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005184
Douglas Gregord0ace022010-04-25 00:55:24 +00005185 // If we're supposed to bind temporaries, do so.
5186 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005187 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005188 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005189}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005190
Richard Smithc620f552011-10-19 16:55:56 +00005191/// \brief Check whether elidable copy construction for binding a reference to
5192/// a temporary would have succeeded if we were building in C++98 mode, for
5193/// -Wc++98-compat.
5194static void CheckCXX98CompatAccessibleCopy(Sema &S,
5195 const InitializedEntity &Entity,
5196 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005197 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005198
5199 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5200 if (!Record)
5201 return;
5202
5203 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005204 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00005205 return;
5206
5207 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00005208 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005209 LookupCopyAndMoveConstructors(
5210 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5211
5212 // Perform overload resolution.
5213 OverloadCandidateSet::iterator Best;
5214 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5215
5216 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5217 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5218 << CurInitExpr->getSourceRange();
5219
5220 switch (OR) {
5221 case OR_Success:
5222 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCall5dadb652012-04-07 03:04:20 +00005223 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005224 // FIXME: Check default arguments as far as that's possible.
5225 break;
5226
5227 case OR_No_Viable_Function:
5228 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005229 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005230 break;
5231
5232 case OR_Ambiguous:
5233 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005234 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005235 break;
5236
5237 case OR_Deleted:
5238 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005239 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005240 break;
5241 }
5242}
5243
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005244void InitializationSequence::PrintInitLocationNote(Sema &S,
5245 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005246 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005247 if (Entity.getDecl()->getLocation().isInvalid())
5248 return;
5249
5250 if (Entity.getDecl()->getDeclName())
5251 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5252 << Entity.getDecl()->getDeclName();
5253 else
5254 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5255 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005256 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5257 Entity.getMethodDecl())
5258 S.Diag(Entity.getMethodDecl()->getLocation(),
5259 diag::note_method_return_type_change)
5260 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005261}
5262
Sebastian Redl112aa822011-07-14 19:07:55 +00005263static bool isReferenceBinding(const InitializationSequence::Step &s) {
5264 return s.Kind == InitializationSequence::SK_BindReference ||
5265 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5266}
5267
Jordan Rose6c0505e2013-05-06 16:48:12 +00005268/// Returns true if the parameters describe a constructor initialization of
5269/// an explicit temporary object, e.g. "Point(x, y)".
5270static bool isExplicitTemporary(const InitializedEntity &Entity,
5271 const InitializationKind &Kind,
5272 unsigned NumArgs) {
5273 switch (Entity.getKind()) {
5274 case InitializedEntity::EK_Temporary:
5275 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005276 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005277 break;
5278 default:
5279 return false;
5280 }
5281
5282 switch (Kind.getKind()) {
5283 case InitializationKind::IK_DirectList:
5284 return true;
5285 // FIXME: Hack to work around cast weirdness.
5286 case InitializationKind::IK_Direct:
5287 case InitializationKind::IK_Value:
5288 return NumArgs != 1;
5289 default:
5290 return false;
5291 }
5292}
5293
Sebastian Redled2e5322011-12-22 14:44:04 +00005294static ExprResult
5295PerformConstructorInitialization(Sema &S,
5296 const InitializedEntity &Entity,
5297 const InitializationKind &Kind,
5298 MultiExprArg Args,
5299 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00005300 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005301 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005302 bool IsStdInitListInitialization,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005303 SourceLocation LBraceLoc,
5304 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005305 unsigned NumArgs = Args.size();
5306 CXXConstructorDecl *Constructor
5307 = cast<CXXConstructorDecl>(Step.Function.Function);
5308 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5309
5310 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005311 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00005312 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5313 ? Kind.getEqualLoc()
5314 : Kind.getLocation();
5315
5316 if (Kind.getKind() == InitializationKind::IK_Default) {
5317 // Force even a trivial, implicit default constructor to be
5318 // semantically checked. We do this explicitly because we don't build
5319 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00005320 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00005321 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00005322 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00005323 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5324 }
5325
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005326 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00005327
Douglas Gregor6073dca2012-02-24 23:56:31 +00005328 // C++ [over.match.copy]p1:
5329 // - When initializing a temporary to be bound to the first parameter
5330 // of a constructor that takes a reference to possibly cv-qualified
5331 // T as its first argument, called with a single argument in the
5332 // context of direct-initialization, explicit conversion functions
5333 // are also considered.
5334 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5335 Args.size() == 1 &&
5336 Constructor->isCopyOrMoveConstructor();
5337
Sebastian Redled2e5322011-12-22 14:44:04 +00005338 // Determine the arguments required to actually perform the constructor
5339 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005340 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005341 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00005342 AllowExplicitConv,
5343 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00005344 return ExprError();
5345
5346
Jordan Rose6c0505e2013-05-06 16:48:12 +00005347 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005348 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedmanfa0df832012-02-02 03:46:19 +00005349 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith22262ab2013-05-04 06:44:46 +00005350 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5351 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005352
5353 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5354 if (!TSInfo)
5355 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005356 SourceRange ParenOrBraceRange =
5357 (Kind.getKind() == InitializationKind::IK_DirectList)
5358 ? SourceRange(LBraceLoc, RBraceLoc)
5359 : Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005360
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005361 CurInit = new (S.Context) CXXTemporaryObjectExpr(
5362 S.Context, Constructor, TSInfo, ConstructorArgs, ParenOrBraceRange,
5363 HadMultipleCandidates, IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005364 IsStdInitListInitialization, ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00005365 } else {
5366 CXXConstructExpr::ConstructionKind ConstructKind =
5367 CXXConstructExpr::CK_Complete;
5368
5369 if (Entity.getKind() == InitializedEntity::EK_Base) {
5370 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5371 CXXConstructExpr::CK_VirtualBase :
5372 CXXConstructExpr::CK_NonVirtualBase;
5373 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5374 ConstructKind = CXXConstructExpr::CK_Delegating;
5375 }
5376
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005377 // Only get the parenthesis or brace range if it is a list initialization or
5378 // direct construction.
5379 SourceRange ParenOrBraceRange;
5380 if (IsListInitialization)
5381 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
5382 else if (Kind.getKind() == InitializationKind::IK_Direct)
5383 ParenOrBraceRange = Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005384
5385 // If the entity allows NRVO, mark the construction as elidable
5386 // unconditionally.
5387 if (Entity.allowsNRVO())
5388 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5389 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005390 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005391 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005392 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005393 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005394 ConstructorInitRequiresZeroInit,
5395 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005396 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005397 else
5398 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5399 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005400 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005401 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005402 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005403 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005404 ConstructorInitRequiresZeroInit,
5405 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005406 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005407 }
5408 if (CurInit.isInvalid())
5409 return ExprError();
5410
5411 // Only check access if all of that succeeded.
5412 S.CheckConstructorAccess(Loc, Constructor, Entity,
5413 Step.Function.FoundDecl.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005414 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5415 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005416
5417 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005418 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00005419
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005420 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00005421}
5422
Richard Smitheb3cad52012-06-04 22:27:30 +00005423/// Determine whether the specified InitializedEntity definitely has a lifetime
5424/// longer than the current full-expression. Conservatively returns false if
5425/// it's unclear.
5426static bool
5427InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5428 const InitializedEntity *Top = &Entity;
5429 while (Top->getParent())
5430 Top = Top->getParent();
5431
5432 switch (Top->getKind()) {
5433 case InitializedEntity::EK_Variable:
5434 case InitializedEntity::EK_Result:
5435 case InitializedEntity::EK_Exception:
5436 case InitializedEntity::EK_Member:
5437 case InitializedEntity::EK_New:
5438 case InitializedEntity::EK_Base:
5439 case InitializedEntity::EK_Delegating:
5440 return true;
5441
5442 case InitializedEntity::EK_ArrayElement:
5443 case InitializedEntity::EK_VectorElement:
5444 case InitializedEntity::EK_BlockElement:
5445 case InitializedEntity::EK_ComplexElement:
5446 // Could not determine what the full initialization is. Assume it might not
5447 // outlive the full-expression.
5448 return false;
5449
5450 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005451 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00005452 case InitializedEntity::EK_Temporary:
5453 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005454 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005455 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00005456 // The entity being initialized might not outlive the full-expression.
5457 return false;
5458 }
5459
5460 llvm_unreachable("unknown entity kind");
5461}
5462
Richard Smithe6c01442013-06-05 00:46:14 +00005463/// Determine the declaration which an initialized entity ultimately refers to,
5464/// for the purpose of lifetime-extending a temporary bound to a reference in
5465/// the initialization of \p Entity.
David Majnemerdaff3702014-05-01 17:50:17 +00005466static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
5467 const InitializedEntity *Entity,
Craig Topperc3ec1492014-05-26 06:22:03 +00005468 const InitializedEntity *FallbackDecl = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00005469 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00005470 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005471 case InitializedEntity::EK_Variable:
5472 // The temporary [...] persists for the lifetime of the reference
David Majnemerdaff3702014-05-01 17:50:17 +00005473 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005474
5475 case InitializedEntity::EK_Member:
5476 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005477 if (Entity->getParent())
5478 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5479 Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00005480
5481 // except:
5482 // -- A temporary bound to a reference member in a constructor's
5483 // ctor-initializer persists until the constructor exits.
David Majnemerdaff3702014-05-01 17:50:17 +00005484 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005485
5486 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005487 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00005488 // -- A temporary bound to a reference parameter in a function call
5489 // persists until the completion of the full-expression containing
5490 // the call.
5491 case InitializedEntity::EK_Result:
5492 // -- The lifetime of a temporary bound to the returned value in a
5493 // function return statement is not extended; the temporary is
5494 // destroyed at the end of the full-expression in the return statement.
5495 case InitializedEntity::EK_New:
5496 // -- A temporary bound to a reference in a new-initializer persists
5497 // until the completion of the full-expression containing the
5498 // new-initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005499 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005500
5501 case InitializedEntity::EK_Temporary:
5502 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005503 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00005504 // We don't yet know the storage duration of the surrounding temporary.
5505 // Assume it's got full-expression duration for now, it will patch up our
5506 // storage duration if that's not correct.
David Majnemerdaff3702014-05-01 17:50:17 +00005507 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005508
5509 case InitializedEntity::EK_ArrayElement:
5510 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005511 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5512 FallbackDecl);
Richard Smithe6c01442013-06-05 00:46:14 +00005513
5514 case InitializedEntity::EK_Base:
5515 case InitializedEntity::EK_Delegating:
5516 // We can reach this case for aggregate initialization in a constructor:
5517 // struct A { int &&r; };
5518 // struct B : A { B() : A{0} {} };
5519 // In this case, use the innermost field decl as the context.
5520 return FallbackDecl;
5521
5522 case InitializedEntity::EK_BlockElement:
5523 case InitializedEntity::EK_LambdaCapture:
5524 case InitializedEntity::EK_Exception:
5525 case InitializedEntity::EK_VectorElement:
5526 case InitializedEntity::EK_ComplexElement:
David Majnemerdaff3702014-05-01 17:50:17 +00005527 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005528 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00005529 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00005530}
5531
David Majnemerdaff3702014-05-01 17:50:17 +00005532static void performLifetimeExtension(Expr *Init,
5533 const InitializedEntity *ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005534
5535/// Update a glvalue expression that is used as the initializer of a reference
5536/// to note that its lifetime is extended.
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005537/// \return \c true if any temporary had its lifetime extended.
David Majnemerdaff3702014-05-01 17:50:17 +00005538static bool
5539performReferenceExtension(Expr *Init,
5540 const InitializedEntity *ExtendingEntity) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005541 // Walk past any constructs which we can lifetime-extend across.
5542 Expr *Old;
5543 do {
5544 Old = Init;
5545
Richard Smithdbc82492015-01-10 01:28:13 +00005546 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5547 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5548 // This is just redundant braces around an initializer. Step over it.
5549 Init = ILE->getInit(0);
5550 }
5551 }
5552
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005553 // Step over any subobject adjustments; we may have a materialized
5554 // temporary inside them.
5555 SmallVector<const Expr *, 2> CommaLHSs;
5556 SmallVector<SubobjectAdjustment, 2> Adjustments;
5557 Init = const_cast<Expr *>(
5558 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5559
5560 // Per current approach for DR1376, look through casts to reference type
5561 // when performing lifetime extension.
5562 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5563 if (CE->getSubExpr()->isGLValue())
5564 Init = CE->getSubExpr();
5565
5566 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5567 // It's unclear if binding a reference to that xvalue extends the array
5568 // temporary.
5569 } while (Init != Old);
5570
Richard Smithe6c01442013-06-05 00:46:14 +00005571 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5572 // Update the storage duration of the materialized temporary.
5573 // FIXME: Rebuild the expression instead of mutating it.
David Majnemerdaff3702014-05-01 17:50:17 +00005574 ME->setExtendingDecl(ExtendingEntity->getDecl(),
5575 ExtendingEntity->allocateManglingNumber());
5576 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005577 return true;
Richard Smithe6c01442013-06-05 00:46:14 +00005578 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005579
5580 return false;
Richard Smithe6c01442013-06-05 00:46:14 +00005581}
5582
5583/// Update a prvalue expression that is going to be materialized as a
5584/// lifetime-extended temporary.
David Majnemerdaff3702014-05-01 17:50:17 +00005585static void performLifetimeExtension(Expr *Init,
5586 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00005587 // Dig out the expression which constructs the extended temporary.
5588 SmallVector<const Expr *, 2> CommaLHSs;
5589 SmallVector<SubobjectAdjustment, 2> Adjustments;
5590 Init = const_cast<Expr *>(
5591 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5592
Richard Smith736a9472013-06-12 20:42:33 +00005593 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5594 Init = BTE->getSubExpr();
5595
Richard Smithcc1b96d2013-06-12 22:31:48 +00005596 if (CXXStdInitializerListExpr *ILE =
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005597 dyn_cast<CXXStdInitializerListExpr>(Init)) {
David Majnemerdaff3702014-05-01 17:50:17 +00005598 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005599 return;
5600 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00005601
Richard Smithe6c01442013-06-05 00:46:14 +00005602 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00005603 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005604 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
David Majnemerdaff3702014-05-01 17:50:17 +00005605 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005606 return;
5607 }
5608
Richard Smithcc1b96d2013-06-12 22:31:48 +00005609 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005610 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5611
5612 // If we lifetime-extend a braced initializer which is initializing an
5613 // aggregate, and that aggregate contains reference members which are
5614 // bound to temporaries, those temporaries are also lifetime-extended.
5615 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5616 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005617 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005618 else {
5619 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005620 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00005621 if (Index >= ILE->getNumInits())
5622 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005623 if (I->isUnnamedBitfield())
5624 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00005625 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00005626 if (I->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005627 performReferenceExtension(SubInit, ExtendingEntity);
Richard Smith8d7f11d2013-06-27 22:54:33 +00005628 else if (isa<InitListExpr>(SubInit) ||
5629 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smithe6c01442013-06-05 00:46:14 +00005630 // This may be either aggregate-initialization of a member or
5631 // initialization of a std::initializer_list object. Either way,
5632 // we should recursively lifetime-extend that initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005633 performLifetimeExtension(SubInit, ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005634 ++Index;
5635 }
5636 }
5637 }
5638 }
5639}
5640
Richard Smithcc1b96d2013-06-12 22:31:48 +00005641static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5642 const Expr *Init, bool IsInitializerList,
5643 const ValueDecl *ExtendingDecl) {
5644 // Warn if a field lifetime-extends a temporary.
5645 if (isa<FieldDecl>(ExtendingDecl)) {
5646 if (IsInitializerList) {
5647 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5648 << /*at end of constructor*/true;
5649 return;
5650 }
5651
5652 bool IsSubobjectMember = false;
5653 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5654 Ent = Ent->getParent()) {
5655 if (Ent->getKind() != InitializedEntity::EK_Base) {
5656 IsSubobjectMember = true;
5657 break;
5658 }
5659 }
5660 S.Diag(Init->getExprLoc(),
5661 diag::warn_bind_ref_member_to_temporary)
5662 << ExtendingDecl << Init->getSourceRange()
5663 << IsSubobjectMember << IsInitializerList;
5664 if (IsSubobjectMember)
5665 S.Diag(ExtendingDecl->getLocation(),
5666 diag::note_ref_subobject_of_member_declared_here);
5667 else
5668 S.Diag(ExtendingDecl->getLocation(),
5669 diag::note_ref_or_ptr_member_declared_here)
5670 << /*is pointer*/false;
5671 }
5672}
5673
Richard Smithaaa0ec42013-09-21 21:19:19 +00005674static void DiagnoseNarrowingInInitList(Sema &S,
5675 const ImplicitConversionSequence &ICS,
5676 QualType PreNarrowingType,
5677 QualType EntityType,
5678 const Expr *PostInit);
5679
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005680ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005681InitializationSequence::Perform(Sema &S,
5682 const InitializedEntity &Entity,
5683 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00005684 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005685 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005686 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005687 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00005688 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005689 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005690
Sebastian Redld201edf2011-06-05 13:59:11 +00005691 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005692 // If the declaration is a non-dependent, incomplete array type
5693 // that has an initializer, then its type will be completed once
5694 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00005695 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00005696 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00005697 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005698 if (const IncompleteArrayType *ArrayT
5699 = S.Context.getAsIncompleteArrayType(DeclType)) {
5700 // FIXME: We don't currently have the ability to accurately
5701 // compute the length of an initializer list without
5702 // performing full type-checking of the initializer list
5703 // (since we have to determine where braces are implicitly
5704 // introduced and such). So, we fall back to making the array
5705 // type a dependently-sized array type with no specified
5706 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005707 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005708 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00005709
Douglas Gregor51e77d52009-12-10 17:56:55 +00005710 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00005711 if (DeclaratorDecl *DD = Entity.getDecl()) {
5712 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5713 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00005714 if (IncompleteArrayTypeLoc ArrayLoc =
5715 TL.getAs<IncompleteArrayTypeLoc>())
5716 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00005717 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00005718 }
5719
5720 *ResultType
5721 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005722 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005723 ArrayT->getSizeModifier(),
5724 ArrayT->getIndexTypeCVRQualifiers(),
5725 Brackets);
5726 }
5727
5728 }
5729 }
Sebastian Redla9351792012-02-11 23:51:47 +00005730 if (Kind.getKind() == InitializationKind::IK_Direct &&
5731 !Kind.isExplicitCast()) {
5732 // Rebuild the ParenListExpr.
5733 SourceRange ParenRange = Kind.getParenRange();
5734 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005735 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00005736 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00005737 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00005738 Kind.isExplicitCast() ||
5739 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005740 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005741 }
5742
Sebastian Redld201edf2011-06-05 13:59:11 +00005743 // No steps means no initialization.
5744 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005745 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005746
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005747 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005748 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005749 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00005750 // Produce a C++98 compatibility warning if we are initializing a reference
5751 // from an initializer list. For parameters, we produce a better warning
5752 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005753 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00005754 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5755 << Init->getSourceRange();
5756 }
5757
Richard Smitheb3cad52012-06-04 22:27:30 +00005758 // Diagnose cases where we initialize a pointer to an array temporary, and the
5759 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005760 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00005761 Entity.getType()->isPointerType() &&
5762 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005763 Expr *Init = Args[0];
Richard Smitheb3cad52012-06-04 22:27:30 +00005764 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5765 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5766 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5767 << Init->getSourceRange();
5768 }
5769
Douglas Gregor1b303932009-12-22 15:35:07 +00005770 QualType DestType = Entity.getType().getNonReferenceType();
5771 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00005772 // the same as Entity.getDecl()->getType() in cases involving type merging,
5773 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00005774 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00005775 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00005776 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005777
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005778 ExprResult CurInit((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005779
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005780 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00005781 // grab the only argument out the Args and place it into the "current"
5782 // initializer.
5783 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005784 case SK_ResolveAddressOfOverloadedFunction:
5785 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005786 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005787 case SK_CastDerivedToBaseLValue:
5788 case SK_BindReference:
5789 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005790 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00005791 case SK_UserConversion:
5792 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005793 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005794 case SK_QualificationConversionRValue:
Richard Smith77be48a2014-07-31 06:31:19 +00005795 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00005796 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005797 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00005798 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00005799 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00005800 case SK_UnwrapInitList:
5801 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00005802 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00005803 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00005804 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00005805 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00005806 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00005807 case SK_PassByIndirectCopyRestore:
5808 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00005809 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005810 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00005811 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005812 case SK_OCLZeroEvent: {
Douglas Gregore1314a62009-12-18 05:02:21 +00005813 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005814 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00005815 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005816 break;
John McCall34376a62010-12-04 03:47:34 +00005817 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005818
Douglas Gregore1314a62009-12-18 05:02:21 +00005819 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00005820 case SK_ConstructorInitializationFromList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00005821 case SK_StdInitializerListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00005822 case SK_ZeroInitialization:
5823 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005824 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005825
5826 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005827 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005828 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005829 for (step_iterator Step = step_begin(), StepEnd = step_end();
5830 Step != StepEnd; ++Step) {
5831 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005832 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005833
John Wiegley01296292011-04-08 18:41:53 +00005834 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005835
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005836 switch (Step->Kind) {
5837 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005838 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005839 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00005840 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00005841 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5842 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005843 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00005844 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00005845 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005846 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005847
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005848 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005849 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005850 case SK_CastDerivedToBaseLValue: {
5851 // We have a derived-to-base cast that produces either an rvalue or an
5852 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005853
John McCallcf142162010-08-07 06:22:56 +00005854 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00005855
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005856 // Casts to inaccessible base classes are allowed with C-style casts.
5857 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5858 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00005859 CurInit.get()->getLocStart(),
5860 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00005861 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00005862 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005863
John McCall2536c6d2010-08-25 10:28:54 +00005864 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005865 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005866 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005867 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005868 VK_XValue :
5869 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005870 CurInit =
5871 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
5872 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005873 break;
5874 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005875
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005876 case SK_BindReference:
John McCalld25db7e2013-05-06 21:39:12 +00005877 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5878 if (CurInit.get()->refersToBitField()) {
5879 // We don't necessarily have an unambiguous source bit-field.
5880 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005881 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00005882 << Entity.getType().isVolatileQualified()
John McCalld25db7e2013-05-06 21:39:12 +00005883 << (BitField ? BitField->getDeclName() : DeclarationName())
Craig Topperc3ec1492014-05-26 06:22:03 +00005884 << (BitField != nullptr)
John Wiegley01296292011-04-08 18:41:53 +00005885 << CurInit.get()->getSourceRange();
John McCalld25db7e2013-05-06 21:39:12 +00005886 if (BitField)
5887 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5888
John McCallfaf5fb42010-08-26 23:41:50 +00005889 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005890 }
Anders Carlssona91be642010-01-29 02:47:33 +00005891
John Wiegley01296292011-04-08 18:41:53 +00005892 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00005893 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005894 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5895 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00005896 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005897 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005898 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005899 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005900
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005901 // Reference binding does not have any corresponding ASTs.
5902
5903 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005904 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005905 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005906
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005907 // Even though we didn't materialize a temporary, the binding may still
5908 // extend the lifetime of a temporary. This happens if we bind a reference
5909 // to the result of a cast to reference type.
David Majnemerdaff3702014-05-01 17:50:17 +00005910 if (const InitializedEntity *ExtendingEntity =
5911 getEntityForTemporaryLifetimeExtension(&Entity))
5912 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
5913 warnOnLifetimeExtension(S, Entity, CurInit.get(),
5914 /*IsInitializerList=*/false,
5915 ExtendingEntity->getDecl());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005916
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005917 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005918
Richard Smithe6c01442013-06-05 00:46:14 +00005919 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00005920 // Make sure the "temporary" is actually an rvalue.
5921 assert(CurInit.get()->isRValue() && "not a temporary");
5922
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005923 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005924 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005925 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005926
Douglas Gregorfe314812011-06-21 17:03:29 +00005927 // Materialize the temporary into memory.
Richard Smith736a9472013-06-12 20:42:33 +00005928 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Richard Smithe6c01442013-06-05 00:46:14 +00005929 Entity.getType().getNonReferenceType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00005930 Entity.getType()->isLValueReferenceType());
5931
5932 // Maybe lifetime-extend the temporary's subobjects to match the
5933 // entity's lifetime.
5934 if (const InitializedEntity *ExtendingEntity =
5935 getEntityForTemporaryLifetimeExtension(&Entity))
5936 if (performReferenceExtension(MTE, ExtendingEntity))
5937 warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false,
5938 ExtendingEntity->getDecl());
Douglas Gregor58df5092011-06-22 16:12:01 +00005939
5940 // If we're binding to an Objective-C object that has lifetime, we
Richard Smith736a9472013-06-12 20:42:33 +00005941 // need cleanups. Likewise if we're extending this temporary to automatic
5942 // storage duration -- we need to register its cleanup during the
5943 // full-expression's cleanups.
5944 if ((S.getLangOpts().ObjCAutoRefCount &&
5945 MTE->getType()->isObjCLifetimeType()) ||
5946 (MTE->getStorageDuration() == SD_Automatic &&
5947 MTE->getType().isDestructedType()))
Douglas Gregor58df5092011-06-22 16:12:01 +00005948 S.ExprNeedsCleanups = true;
Richard Smith736a9472013-06-12 20:42:33 +00005949
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005950 CurInit = MTE;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005951 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005952 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005953
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005954 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005955 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005956 /*IsExtraneousCopy=*/true);
5957 break;
5958
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005959 case SK_UserConversion: {
5960 // We have a user-defined conversion that invokes either a constructor
5961 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00005962 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00005963 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00005964 FunctionDecl *Fn = Step->Function.Function;
5965 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005966 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00005967 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00005968 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005969 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005970 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00005971 SourceLocation Loc = CurInit.get()->getLocStart();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005972 CurInit.get(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00005973
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005974 // Determine the arguments required to actually perform the constructor
5975 // call.
John Wiegley01296292011-04-08 18:41:53 +00005976 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005977 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00005978 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005979 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005980 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005981
Richard Smithb24f0672012-02-11 19:22:50 +00005982 // Build an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005983 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005984 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005985 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005986 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005987 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005988 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005989 CXXConstructExpr::CK_Complete,
5990 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005991 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005992 return ExprError();
John McCall760af172010-02-01 03:16:54 +00005993
Anders Carlssona01874b2010-04-21 18:47:17 +00005994 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00005995 FoundFn.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005996 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5997 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005998
John McCalle3027922010-08-25 11:45:40 +00005999 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00006000 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
6001 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
6002 S.IsDerivedFrom(SourceType, Class))
6003 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006004
Douglas Gregor95562572010-04-24 23:45:46 +00006005 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006006 } else {
6007 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00006008 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00006009 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00006010 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00006011 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6012 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006013
6014 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006015 // derived-to-base conversion? I believe the answer is "no", because
6016 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00006017 ExprResult CurInitExprRes =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006018 S.PerformObjectArgumentInitialization(CurInit.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006019 /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006020 FoundFn, Conversion);
6021 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006022 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006023 CurInit = CurInitExprRes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006024
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006025 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006026 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
6027 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006028 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00006029 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006030
John McCalle3027922010-08-25 11:45:40 +00006031 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006032
Alp Toker314cc812014-01-25 16:55:45 +00006033 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006034 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006035
Sebastian Redl112aa822011-07-14 19:07:55 +00006036 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006037 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
6038
6039 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00006040 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00006041 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006042 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00006043 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00006044 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00006045 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00006046 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00006047 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6048 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00006049 }
6050 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006051
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006052 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6053 CastKind, CurInit.get(), nullptr,
6054 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006055 if (MaybeBindToTemp)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006056 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00006057 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006058 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006059 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006060 break;
6061 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006062
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006063 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006064 case SK_QualificationConversionXValue:
6065 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006066 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00006067 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006068 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006069 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006070 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006071 VK_XValue :
6072 VK_RValue);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006073 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006074 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006075 }
6076
Richard Smith77be48a2014-07-31 06:31:19 +00006077 case SK_AtomicConversion: {
6078 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
6079 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6080 CK_NonAtomicToAtomic, VK_RValue);
6081 break;
6082 }
6083
Jordan Roseb1312a52013-04-11 00:58:58 +00006084 case SK_LValueToRValue: {
6085 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006086 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
6087 CK_LValueToRValue, CurInit.get(),
6088 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00006089 break;
6090 }
6091
Richard Smithaaa0ec42013-09-21 21:19:19 +00006092 case SK_ConversionSequence:
6093 case SK_ConversionSequenceNoNarrowing: {
6094 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00006095 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
6096 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00006097 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00006098 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00006099 ExprResult CurInitExprRes =
6100 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00006101 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00006102 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006103 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006104 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00006105
6106 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
6107 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
6108 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
6109 CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006110 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00006111 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006112
Douglas Gregor51e77d52009-12-10 17:56:55 +00006113 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00006114 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006115 // If we're not initializing the top-level entity, we need to create an
6116 // InitializeTemporary entity for our target type.
6117 QualType Ty = Step->Type;
6118 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00006119 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00006120 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
6121 InitListChecker PerformInitList(S, InitEntity,
Richard Smithde229232013-06-06 11:41:05 +00006122 InitList, Ty, /*VerifyOnly=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006123 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00006124 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00006125
Richard Smithcc1b96d2013-06-12 22:31:48 +00006126 // Hack: We must update *ResultType if available in order to set the
6127 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
6128 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
6129 if (ResultType &&
6130 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00006131 if ((*ResultType)->isRValueReferenceType())
6132 Ty = S.Context.getRValueReferenceType(Ty);
6133 else if ((*ResultType)->isLValueReferenceType())
6134 Ty = S.Context.getLValueReferenceType(Ty,
6135 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
6136 *ResultType = Ty;
6137 }
6138
6139 InitListExpr *StructuredInitList =
6140 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006141 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00006142 CurInit = shouldBindAsTemporary(InitEntity)
6143 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006144 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006145 break;
6146 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006147
Richard Smith53324112014-07-16 21:33:43 +00006148 case SK_ConstructorInitializationFromList: {
Sebastian Redl5a41f682012-02-12 16:37:24 +00006149 // When an initializer list is passed for a parameter of type "reference
6150 // to object", we don't get an EK_Temporary entity, but instead an
6151 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00006152 // FIXME: This is a hack. What we really should do is create a user
6153 // conversion step for this case, but this makes it considerably more
6154 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00006155 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6156 Entity.getType().getNonReferenceType());
6157 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00006158 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006159 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00006160 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6161 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006162 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00006163 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6164 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006165 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006166 ConstructorInitRequiresZeroInit,
Richard Smith53324112014-07-16 21:33:43 +00006167 /*IsListInitialization*/true,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006168 /*IsStdInitListInit*/false,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006169 InitList->getLBraceLoc(),
6170 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00006171 break;
6172 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006173
Sebastian Redl29526f02011-11-27 16:50:07 +00006174 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006175 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00006176 break;
6177
6178 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006179 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00006180 InitListExpr *Syntactic = Step->WrappingSyntacticList;
6181 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00006182 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00006183 ILE->setSyntacticForm(Syntactic);
6184 ILE->setType(E->getType());
6185 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006186 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00006187 break;
6188 }
6189
Richard Smith53324112014-07-16 21:33:43 +00006190 case SK_ConstructorInitialization:
Richard Smithf8adcdc2014-07-17 05:12:35 +00006191 case SK_StdInitializerListConstructorCall: {
Sebastian Redl99f66162012-02-19 12:27:56 +00006192 // When an initializer list is passed for a parameter of type "reference
6193 // to object", we don't get an EK_Temporary entity, but instead an
6194 // EK_Parameter entity with reference type.
6195 // FIXME: This is a hack. What we really should do is create a user
6196 // conversion step for this case, but this makes it considerably more
6197 // complicated. For now, this will do.
6198 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6199 Entity.getType().getNonReferenceType());
6200 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf8adcdc2014-07-17 05:12:35 +00006201 bool IsStdInitListInit =
6202 Step->Kind == SK_StdInitializerListConstructorCall;
Richard Smith53324112014-07-16 21:33:43 +00006203 CurInit = PerformConstructorInitialization(
6204 S, UseTemporary ? TempEntity : Entity, Kind, Args, *Step,
6205 ConstructorInitRequiresZeroInit,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006206 /*IsListInitialization*/IsStdInitListInit,
6207 /*IsStdInitListInitialization*/IsStdInitListInit,
Richard Smith53324112014-07-16 21:33:43 +00006208 /*LBraceLoc*/SourceLocation(),
6209 /*RBraceLoc*/SourceLocation());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006210 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00006211 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006212
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006213 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006214 step_iterator NextStep = Step;
6215 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006216 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00006217 (NextStep->Kind == SK_ConstructorInitialization ||
Richard Smith53324112014-07-16 21:33:43 +00006218 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006219 // The need for zero-initialization is recorded directly into
6220 // the call to the object's constructor within the next step.
6221 ConstructorInitRequiresZeroInit = true;
6222 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006223 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006224 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00006225 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6226 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006227 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00006228 Kind.getRange().getBegin());
6229
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006230 CurInit = new (S.Context) CXXScalarValueInitExpr(
6231 TSInfo->getType().getNonLValueExprType(S.Context), TSInfo,
6232 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006233 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006234 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006235 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006236 break;
6237 }
Douglas Gregore1314a62009-12-18 05:02:21 +00006238
6239 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00006240 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006241 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00006242 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00006243 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6244 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00006245 if (Result.isInvalid())
6246 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006247 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00006248
6249 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006250 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00006251 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006252 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00006253 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00006254 == Sema::Compatible)
6255 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00006256 if (CurInitExprRes.isInvalid())
6257 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006258 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00006259
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006260 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00006261 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6262 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00006263 CurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00006264 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006265 &Complained)) {
6266 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00006267 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006268 } else if (Complained)
6269 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00006270 break;
6271 }
Eli Friedman78275202009-12-19 08:11:05 +00006272
6273 case SK_StringInit: {
6274 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00006275 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00006276 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00006277 break;
6278 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006279
6280 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006281 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00006282 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00006283 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006284 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006285
6286 case SK_ArrayInit:
6287 // Okay: we checked everything before creating this step. Note that
6288 // this is a GNU extension.
6289 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00006290 << Step->Type << CurInit.get()->getType()
6291 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00006292
6293 // If the destination type is an incomplete array type, update the
6294 // type accordingly.
6295 if (ResultType) {
6296 if (const IncompleteArrayType *IncompleteDest
6297 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6298 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00006299 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00006300 *ResultType = S.Context.getConstantArrayType(
6301 IncompleteDest->getElementType(),
6302 ConstantSource->getSize(),
6303 ArrayType::Normal, 0);
6304 }
6305 }
6306 }
John McCall31168b02011-06-15 23:02:42 +00006307 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006308
Richard Smithebeed412012-02-15 22:38:09 +00006309 case SK_ParenthesizedArrayInit:
6310 // Okay: we checked everything before creating this step. Note that
6311 // this is a GNU extension.
6312 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6313 << CurInit.get()->getSourceRange();
6314 break;
6315
John McCall31168b02011-06-15 23:02:42 +00006316 case SK_PassByIndirectCopyRestore:
6317 case SK_PassByIndirectRestore:
6318 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006319 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
6320 CurInit.get(), Step->Type,
6321 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00006322 break;
6323
6324 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006325 CurInit =
6326 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
6327 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00006328 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006329
6330 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006331 S.Diag(CurInit.get()->getExprLoc(),
6332 diag::warn_cxx98_compat_initializer_list_init)
6333 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00006334
Richard Smithcc1b96d2013-06-12 22:31:48 +00006335 // Materialize the temporary into memory.
6336 MaterializeTemporaryExpr *MTE = new (S.Context)
6337 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00006338 /*BoundToLvalueReference=*/false);
6339
6340 // Maybe lifetime-extend the array temporary's subobjects to match the
6341 // entity's lifetime.
6342 if (const InitializedEntity *ExtendingEntity =
6343 getEntityForTemporaryLifetimeExtension(&Entity))
6344 if (performReferenceExtension(MTE, ExtendingEntity))
6345 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6346 /*IsInitializerList=*/true,
6347 ExtendingEntity->getDecl());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006348
6349 // Wrap it in a construction of a std::initializer_list<T>.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006350 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006351
6352 // Bind the result, in case the library has given initializer_list a
6353 // non-trivial destructor.
6354 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006355 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00006356 break;
6357 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006358
Guy Benyei61054192013-02-07 10:55:47 +00006359 case SK_OCLSamplerInit: {
6360 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006361 "Sampler initialization on non-sampler type.");
Guy Benyei61054192013-02-07 10:55:47 +00006362
6363 QualType SourceType = CurInit.get()->getType();
Guy Benyei61054192013-02-07 10:55:47 +00006364
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006365 if (Entity.isParameterKind()) {
Guy Benyei61054192013-02-07 10:55:47 +00006366 if (!SourceType->isSamplerT())
6367 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6368 << SourceType;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006369 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
Guy Benyei61054192013-02-07 10:55:47 +00006370 llvm_unreachable("Invalid EntityKind!");
6371 }
6372
6373 break;
6374 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006375 case SK_OCLZeroEvent: {
6376 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006377 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006378
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006379 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006380 CK_ZeroToOCLEvent,
6381 CurInit.get()->getValueKind());
6382 break;
6383 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006384 }
6385 }
John McCall1f425642010-11-11 03:21:53 +00006386
6387 // Diagnose non-fatal problems with the completed initialization.
6388 if (Entity.getKind() == InitializedEntity::EK_Member &&
6389 cast<FieldDecl>(Entity.getDecl())->isBitField())
6390 S.CheckBitFieldInitialization(Kind.getLocation(),
6391 cast<FieldDecl>(Entity.getDecl()),
6392 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006393
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006394 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006395}
6396
Richard Smith593f9932012-12-08 02:01:17 +00006397/// Somewhere within T there is an uninitialized reference subobject.
6398/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00006399static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6400 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00006401 if (T->isReferenceType()) {
6402 S.Diag(Loc, diag::err_reference_without_init)
6403 << T.getNonReferenceType();
6404 return true;
6405 }
6406
6407 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6408 if (!RD || !RD->hasUninitializedReferenceMember())
6409 return false;
6410
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006411 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00006412 if (FI->isUnnamedBitfield())
6413 continue;
6414
6415 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6416 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6417 return true;
6418 }
6419 }
6420
Aaron Ballman574705e2014-03-13 15:41:46 +00006421 for (const auto &BI : RD->bases()) {
6422 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00006423 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6424 return true;
6425 }
6426 }
6427
6428 return false;
6429}
6430
6431
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006432//===----------------------------------------------------------------------===//
6433// Diagnose initialization failures
6434//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00006435
6436/// Emit notes associated with an initialization that failed due to a
6437/// "simple" conversion failure.
6438static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6439 Expr *op) {
6440 QualType destType = entity.getType();
6441 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6442 op->getType()->isObjCObjectPointerType()) {
6443
6444 // Emit a possible note about the conversion failing because the
6445 // operand is a message send with a related result type.
6446 S.EmitRelatedResultTypeNote(op);
6447
6448 // Emit a possible note about a return failing because we're
6449 // expecting a related result type.
6450 if (entity.getKind() == InitializedEntity::EK_Result)
6451 S.EmitRelatedResultTypeNoteForReturn(destType);
6452 }
6453}
6454
Richard Smith0449aaf2013-11-21 23:30:57 +00006455static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6456 InitListExpr *InitList) {
6457 QualType DestType = Entity.getType();
6458
6459 QualType E;
6460 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6461 QualType ArrayType = S.Context.getConstantArrayType(
6462 E.withConst(),
6463 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6464 InitList->getNumInits()),
6465 clang::ArrayType::Normal, 0);
6466 InitializedEntity HiddenArray =
6467 InitializedEntity::InitializeTemporary(ArrayType);
6468 return diagnoseListInit(S, HiddenArray, InitList);
6469 }
6470
Richard Smith8d082d12014-09-04 22:13:39 +00006471 if (DestType->isReferenceType()) {
6472 // A list-initialization failure for a reference means that we tried to
6473 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
6474 // inner initialization failed.
6475 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
6476 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
6477 SourceLocation Loc = InitList->getLocStart();
6478 if (auto *D = Entity.getDecl())
6479 Loc = D->getLocation();
6480 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
6481 return;
6482 }
6483
Richard Smith0449aaf2013-11-21 23:30:57 +00006484 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
6485 /*VerifyOnly=*/false);
6486 assert(DiagnoseInitList.HadError() &&
6487 "Inconsistent init list check result.");
6488}
6489
Nico Weber9386c822014-07-23 05:16:10 +00006490/// Prints a fixit for adding a null initializer for |Entity|. Call this only
6491/// right after emitting a diagnostic.
6492static void maybeEmitZeroInitializationFixit(Sema &S,
6493 InitializationSequence &Sequence,
6494 const InitializedEntity &Entity) {
6495 if (Entity.getKind() != InitializedEntity::EK_Variable)
6496 return;
6497
6498 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
6499 if (VD->getInit() || VD->getLocEnd().isMacroID())
6500 return;
6501
6502 QualType VariableTy = VD->getType().getCanonicalType();
6503 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
6504 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
6505
6506 S.Diag(Loc, diag::note_add_initializer)
6507 << VD << FixItHint::CreateInsertion(Loc, Init);
6508}
6509
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006510bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006511 const InitializedEntity &Entity,
6512 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006513 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006514 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006515 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006516
Douglas Gregor1b303932009-12-22 15:35:07 +00006517 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006518 switch (Failure) {
6519 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006520 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006521 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00006522 // Dig out the reference subobject which is uninitialized and diagnose it.
6523 // If this is value-initialization, this could be nested some way within
6524 // the target type.
6525 assert(Kind.getKind() == InitializationKind::IK_Value ||
6526 DestType->isReferenceType());
6527 bool Diagnosed =
6528 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6529 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6530 (void)Diagnosed;
6531 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006532 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006533 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006534 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006535
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006536 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006537 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006538 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006539 case FK_ArrayNeedsInitListOrStringLiteral:
6540 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6541 break;
6542 case FK_ArrayNeedsInitListOrWideStringLiteral:
6543 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6544 break;
6545 case FK_NarrowStringIntoWideCharArray:
6546 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6547 break;
6548 case FK_WideStringIntoCharArray:
6549 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6550 break;
6551 case FK_IncompatWideStringIntoWideChar:
6552 S.Diag(Kind.getLocation(),
6553 diag::err_array_init_incompat_wide_string_into_wchar);
6554 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006555 case FK_ArrayTypeMismatch:
6556 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00006557 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00006558 (Failure == FK_ArrayTypeMismatch
6559 ? diag::err_array_init_different_type
6560 : diag::err_array_init_non_constant_array))
6561 << DestType.getNonReferenceType()
6562 << Args[0]->getType()
6563 << Args[0]->getSourceRange();
6564 break;
6565
John McCalla59dc2f2012-01-05 00:13:19 +00006566 case FK_VariableLengthArrayHasInitializer:
6567 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6568 << Args[0]->getSourceRange();
6569 break;
6570
John McCall16df1e52010-03-30 21:47:33 +00006571 case FK_AddressOfOverloadFailed: {
6572 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006573 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006574 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00006575 true,
6576 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006577 break;
John McCall16df1e52010-03-30 21:47:33 +00006578 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006579
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006580 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00006581 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006582 switch (FailedOverloadResult) {
6583 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00006584 if (Failure == FK_UserConversionOverloadFailed)
6585 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6586 << Args[0]->getType() << DestType
6587 << Args[0]->getSourceRange();
6588 else
6589 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6590 << DestType << Args[0]->getType()
6591 << Args[0]->getSourceRange();
6592
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006593 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006594 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006595
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006596 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00006597 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00006598 DestType.getNonReferenceType(),
6599 diag::err_typecheck_nonviable_condition_incomplete,
6600 Args[0]->getType(), Args[0]->getSourceRange()))
6601 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6602 << Args[0]->getType() << Args[0]->getSourceRange()
6603 << DestType.getNonReferenceType();
6604
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006605 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006606 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006607
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006608 case OR_Deleted: {
6609 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6610 << Args[0]->getType() << DestType.getNonReferenceType()
6611 << Args[0]->getSourceRange();
6612 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006613 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00006614 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6615 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006616 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00006617 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006618 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006619 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006620 }
6621 break;
6622 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006623
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006624 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006625 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006626 }
6627 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006628
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006629 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00006630 if (isa<InitListExpr>(Args[0])) {
6631 S.Diag(Kind.getLocation(),
6632 diag::err_lvalue_reference_bind_to_initlist)
6633 << DestType.getNonReferenceType().isVolatileQualified()
6634 << DestType.getNonReferenceType()
6635 << Args[0]->getSourceRange();
6636 break;
6637 }
6638 // Intentional fallthrough
6639
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006640 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006641 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006642 Failure == FK_NonConstLValueReferenceBindingToTemporary
6643 ? diag::err_lvalue_reference_bind_to_temporary
6644 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00006645 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006646 << DestType.getNonReferenceType()
6647 << Args[0]->getType()
6648 << Args[0]->getSourceRange();
6649 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006650
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006651 case FK_RValueReferenceBindingToLValue:
6652 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00006653 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006654 << Args[0]->getSourceRange();
6655 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006656
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006657 case FK_ReferenceInitDropsQualifiers:
6658 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6659 << DestType.getNonReferenceType()
6660 << Args[0]->getType()
6661 << Args[0]->getSourceRange();
6662 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006663
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006664 case FK_ReferenceInitFailed:
6665 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6666 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00006667 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006668 << Args[0]->getType()
6669 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00006670 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006671 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006672
Douglas Gregorb491ed32011-02-19 21:32:49 +00006673 case FK_ConversionFailed: {
6674 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00006675 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00006676 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006677 << DestType
John McCall086a4642010-11-24 05:12:34 +00006678 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00006679 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006680 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00006681 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6682 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00006683 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00006684 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00006685 }
John Wiegley01296292011-04-08 18:41:53 +00006686
6687 case FK_ConversionFromPropertyFailed:
6688 // No-op. This error has already been reported.
6689 break;
6690
Douglas Gregor51e77d52009-12-10 17:56:55 +00006691 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00006692 SourceRange R;
6693
6694 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00006695 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00006696 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006697 else
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006698 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00006699
Alp Tokerb6cc5922014-05-03 03:45:55 +00006700 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00006701 if (Kind.isCStyleOrFunctionalCast())
6702 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6703 << R;
6704 else
6705 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6706 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006707 break;
6708 }
6709
6710 case FK_ReferenceBindingToInitList:
6711 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6712 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6713 break;
6714
6715 case FK_InitListBadDestinationType:
6716 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6717 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6718 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006719
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006720 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006721 case FK_ConstructorOverloadFailed: {
6722 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006723 if (Args.size())
6724 ArgsRange = SourceRange(Args.front()->getLocStart(),
6725 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006726
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006727 if (Failure == FK_ListConstructorOverloadFailed) {
Nico Weber9709ebf2014-07-08 23:54:25 +00006728 assert(Args.size() == 1 &&
6729 "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006730 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006731 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006732 }
6733
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006734 // FIXME: Using "DestType" for the entity we're printing is probably
6735 // bad.
6736 switch (FailedOverloadResult) {
6737 case OR_Ambiguous:
6738 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6739 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006740 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006741 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006742
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006743 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006744 if (Kind.getKind() == InitializationKind::IK_Default &&
6745 (Entity.getKind() == InitializedEntity::EK_Base ||
6746 Entity.getKind() == InitializedEntity::EK_Member) &&
6747 isa<CXXConstructorDecl>(S.CurContext)) {
6748 // This is implicit default initialization of a member or
6749 // base within a constructor. If no viable function was
6750 // found, notify the user that she needs to explicitly
6751 // initialize this base/member.
6752 CXXConstructorDecl *Constructor
6753 = cast<CXXConstructorDecl>(S.CurContext);
6754 if (Entity.getKind() == InitializedEntity::EK_Base) {
6755 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006756 << (Constructor->getInheritedConstructor() ? 2 :
6757 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006758 << S.Context.getTypeDeclType(Constructor->getParent())
6759 << /*base=*/0
6760 << Entity.getType();
6761
6762 RecordDecl *BaseDecl
6763 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6764 ->getDecl();
6765 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6766 << S.Context.getTagDeclType(BaseDecl);
6767 } else {
6768 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006769 << (Constructor->getInheritedConstructor() ? 2 :
6770 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006771 << S.Context.getTypeDeclType(Constructor->getParent())
6772 << /*member=*/1
6773 << Entity.getName();
Alp Toker2afa8782014-05-28 12:20:14 +00006774 S.Diag(Entity.getDecl()->getLocation(),
6775 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006776
6777 if (const RecordType *Record
6778 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006779 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006780 diag::note_previous_decl)
6781 << S.Context.getTagDeclType(Record->getDecl());
6782 }
6783 break;
6784 }
6785
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006786 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6787 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006788 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006789 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006790
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006791 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006792 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006793 OverloadingResult Ovl
6794 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00006795 if (Ovl != OR_Deleted) {
6796 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6797 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006798 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00006799 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006800 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00006801
6802 // If this is a defaulted or implicitly-declared function, then
6803 // it was implicitly deleted. Make it clear that the deletion was
6804 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00006805 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006806 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00006807 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006808 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00006809 else
6810 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6811 << true << DestType << ArgsRange;
6812
6813 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006814 break;
6815 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006816
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006817 case OR_Success:
6818 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006819 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006820 }
David Blaikie60deeee2012-01-17 08:24:58 +00006821 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006822
Douglas Gregor85dabae2009-12-16 01:38:02 +00006823 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006824 if (Entity.getKind() == InitializedEntity::EK_Member &&
6825 isa<CXXConstructorDecl>(S.CurContext)) {
6826 // This is implicit default-initialization of a const member in
6827 // a constructor. Complain that it needs to be explicitly
6828 // initialized.
6829 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6830 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006831 << (Constructor->getInheritedConstructor() ? 2 :
6832 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006833 << S.Context.getTypeDeclType(Constructor->getParent())
6834 << /*const=*/1
6835 << Entity.getName();
6836 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6837 << Entity.getName();
6838 } else {
6839 S.Diag(Kind.getLocation(), diag::err_default_init_const)
Nico Weber9386c822014-07-23 05:16:10 +00006840 << DestType << (bool)DestType->getAs<RecordType>();
6841 maybeEmitZeroInitializationFixit(S, *this, Entity);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006842 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00006843 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006844
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006845 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00006846 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006847 diag::err_init_incomplete_type);
6848 break;
6849
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006850 case FK_ListInitializationFailed: {
6851 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00006852 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6853 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006854 break;
6855 }
John McCall4124c492011-10-17 18:40:02 +00006856
6857 case FK_PlaceholderType: {
6858 // FIXME: Already diagnosed!
6859 break;
6860 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00006861
Sebastian Redl048a6d72012-04-01 19:54:59 +00006862 case FK_ExplicitConstructor: {
6863 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6864 << Args[0]->getSourceRange();
6865 OverloadCandidateSet::iterator Best;
6866 OverloadingResult Ovl
6867 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00006868 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00006869 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6870 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6871 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6872 break;
6873 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006874 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006875
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006876 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006877 return true;
6878}
Douglas Gregore1314a62009-12-18 05:02:21 +00006879
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006880void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006881 switch (SequenceKind) {
6882 case FailedSequence: {
6883 OS << "Failed sequence: ";
6884 switch (Failure) {
6885 case FK_TooManyInitsForReference:
6886 OS << "too many initializers for reference";
6887 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006888
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006889 case FK_ArrayNeedsInitList:
6890 OS << "array requires initializer list";
6891 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006892
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006893 case FK_ArrayNeedsInitListOrStringLiteral:
6894 OS << "array requires initializer list or string literal";
6895 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006896
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006897 case FK_ArrayNeedsInitListOrWideStringLiteral:
6898 OS << "array requires initializer list or wide string literal";
6899 break;
6900
6901 case FK_NarrowStringIntoWideCharArray:
6902 OS << "narrow string into wide char array";
6903 break;
6904
6905 case FK_WideStringIntoCharArray:
6906 OS << "wide string into char array";
6907 break;
6908
6909 case FK_IncompatWideStringIntoWideChar:
6910 OS << "incompatible wide string into wide char array";
6911 break;
6912
Douglas Gregore2f943b2011-02-22 18:29:51 +00006913 case FK_ArrayTypeMismatch:
6914 OS << "array type mismatch";
6915 break;
6916
6917 case FK_NonConstantArrayInit:
6918 OS << "non-constant array initializer";
6919 break;
6920
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006921 case FK_AddressOfOverloadFailed:
6922 OS << "address of overloaded function failed";
6923 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006924
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006925 case FK_ReferenceInitOverloadFailed:
6926 OS << "overload resolution for reference initialization failed";
6927 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006928
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006929 case FK_NonConstLValueReferenceBindingToTemporary:
6930 OS << "non-const lvalue reference bound to temporary";
6931 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006932
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006933 case FK_NonConstLValueReferenceBindingToUnrelated:
6934 OS << "non-const lvalue reference bound to unrelated type";
6935 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006936
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006937 case FK_RValueReferenceBindingToLValue:
6938 OS << "rvalue reference bound to an lvalue";
6939 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006940
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006941 case FK_ReferenceInitDropsQualifiers:
6942 OS << "reference initialization drops qualifiers";
6943 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006944
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006945 case FK_ReferenceInitFailed:
6946 OS << "reference initialization failed";
6947 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006948
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006949 case FK_ConversionFailed:
6950 OS << "conversion failed";
6951 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006952
John Wiegley01296292011-04-08 18:41:53 +00006953 case FK_ConversionFromPropertyFailed:
6954 OS << "conversion from property failed";
6955 break;
6956
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006957 case FK_TooManyInitsForScalar:
6958 OS << "too many initializers for scalar";
6959 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006960
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006961 case FK_ReferenceBindingToInitList:
6962 OS << "referencing binding to initializer list";
6963 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006964
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006965 case FK_InitListBadDestinationType:
6966 OS << "initializer list for non-aggregate, non-scalar type";
6967 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006968
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006969 case FK_UserConversionOverloadFailed:
6970 OS << "overloading failed for user-defined conversion";
6971 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006972
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006973 case FK_ConstructorOverloadFailed:
6974 OS << "constructor overloading failed";
6975 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006976
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006977 case FK_DefaultInitOfConst:
6978 OS << "default initialization of a const variable";
6979 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006980
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00006981 case FK_Incomplete:
6982 OS << "initialization of incomplete type";
6983 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006984
6985 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006986 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00006987 break;
6988
John McCalla59dc2f2012-01-05 00:13:19 +00006989 case FK_VariableLengthArrayHasInitializer:
6990 OS << "variable length array has an initializer";
6991 break;
6992
John McCall4124c492011-10-17 18:40:02 +00006993 case FK_PlaceholderType:
6994 OS << "initializer expression isn't contextually valid";
6995 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00006996
6997 case FK_ListConstructorOverloadFailed:
6998 OS << "list constructor overloading failed";
6999 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007000
Sebastian Redl048a6d72012-04-01 19:54:59 +00007001 case FK_ExplicitConstructor:
7002 OS << "list copy initialization chose explicit constructor";
7003 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007004 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007005 OS << '\n';
7006 return;
7007 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007008
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007009 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00007010 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007011 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007012
Sebastian Redld201edf2011-06-05 13:59:11 +00007013 case NormalSequence:
7014 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007015 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007016 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007017
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007018 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
7019 if (S != step_begin()) {
7020 OS << " -> ";
7021 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007022
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007023 switch (S->Kind) {
7024 case SK_ResolveAddressOfOverloadedFunction:
7025 OS << "resolve address of overloaded function";
7026 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007027
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007028 case SK_CastDerivedToBaseRValue:
7029 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
7030 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007031
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007032 case SK_CastDerivedToBaseXValue:
7033 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
7034 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007035
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007036 case SK_CastDerivedToBaseLValue:
7037 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
7038 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007039
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007040 case SK_BindReference:
7041 OS << "bind reference to lvalue";
7042 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007043
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007044 case SK_BindReferenceToTemporary:
7045 OS << "bind reference to a temporary";
7046 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007047
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007048 case SK_ExtraneousCopyToTemporary:
7049 OS << "extraneous C++03 copy to temporary";
7050 break;
7051
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007052 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007053 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007054 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007055
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007056 case SK_QualificationConversionRValue:
7057 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00007058 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007059
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007060 case SK_QualificationConversionXValue:
7061 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00007062 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007063
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007064 case SK_QualificationConversionLValue:
7065 OS << "qualification conversion (lvalue)";
7066 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007067
Richard Smith77be48a2014-07-31 06:31:19 +00007068 case SK_AtomicConversion:
7069 OS << "non-atomic-to-atomic conversion";
7070 break;
7071
Jordan Roseb1312a52013-04-11 00:58:58 +00007072 case SK_LValueToRValue:
7073 OS << "load (lvalue to rvalue)";
7074 break;
7075
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007076 case SK_ConversionSequence:
7077 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00007078 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007079 OS << ")";
7080 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007081
Richard Smithaaa0ec42013-09-21 21:19:19 +00007082 case SK_ConversionSequenceNoNarrowing:
7083 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00007084 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00007085 OS << ")";
7086 break;
7087
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007088 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007089 OS << "list aggregate initialization";
7090 break;
7091
Sebastian Redl29526f02011-11-27 16:50:07 +00007092 case SK_UnwrapInitList:
7093 OS << "unwrap reference initializer list";
7094 break;
7095
7096 case SK_RewrapInitList:
7097 OS << "rewrap reference initializer list";
7098 break;
7099
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007100 case SK_ConstructorInitialization:
7101 OS << "constructor initialization";
7102 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007103
Richard Smith53324112014-07-16 21:33:43 +00007104 case SK_ConstructorInitializationFromList:
7105 OS << "list initialization via constructor";
7106 break;
7107
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007108 case SK_ZeroInitialization:
7109 OS << "zero initialization";
7110 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007111
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007112 case SK_CAssignment:
7113 OS << "C assignment";
7114 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007115
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007116 case SK_StringInit:
7117 OS << "string initialization";
7118 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007119
7120 case SK_ObjCObjectConversion:
7121 OS << "Objective-C object conversion";
7122 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007123
7124 case SK_ArrayInit:
7125 OS << "array initialization";
7126 break;
John McCall31168b02011-06-15 23:02:42 +00007127
Richard Smithebeed412012-02-15 22:38:09 +00007128 case SK_ParenthesizedArrayInit:
7129 OS << "parenthesized array initialization";
7130 break;
7131
John McCall31168b02011-06-15 23:02:42 +00007132 case SK_PassByIndirectCopyRestore:
7133 OS << "pass by indirect copy and restore";
7134 break;
7135
7136 case SK_PassByIndirectRestore:
7137 OS << "pass by indirect restore";
7138 break;
7139
7140 case SK_ProduceObjCObject:
7141 OS << "Objective-C object retension";
7142 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007143
7144 case SK_StdInitializerList:
7145 OS << "std::initializer_list from initializer list";
7146 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007147
Richard Smithf8adcdc2014-07-17 05:12:35 +00007148 case SK_StdInitializerListConstructorCall:
7149 OS << "list initialization from std::initializer_list";
7150 break;
7151
Guy Benyei61054192013-02-07 10:55:47 +00007152 case SK_OCLSamplerInit:
7153 OS << "OpenCL sampler_t from integer constant";
7154 break;
7155
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007156 case SK_OCLZeroEvent:
7157 OS << "OpenCL event_t from zero";
7158 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007159 }
Richard Smith6b216962013-02-05 05:52:24 +00007160
7161 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007162 }
Richard Smith6b216962013-02-05 05:52:24 +00007163
7164 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007165}
7166
7167void InitializationSequence::dump() const {
7168 dump(llvm::errs());
7169}
7170
Richard Smithaaa0ec42013-09-21 21:19:19 +00007171static void DiagnoseNarrowingInInitList(Sema &S,
7172 const ImplicitConversionSequence &ICS,
7173 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007174 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007175 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007176 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00007177 switch (ICS.getKind()) {
7178 case ImplicitConversionSequence::StandardConversion:
7179 SCS = &ICS.Standard;
7180 break;
7181 case ImplicitConversionSequence::UserDefinedConversion:
7182 SCS = &ICS.UserDefined.After;
7183 break;
7184 case ImplicitConversionSequence::AmbiguousConversion:
7185 case ImplicitConversionSequence::EllipsisConversion:
7186 case ImplicitConversionSequence::BadConversion:
7187 return;
7188 }
7189
Richard Smith66e05fe2012-01-18 05:21:49 +00007190 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
7191 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00007192 QualType ConstantType;
7193 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
7194 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00007195 case NK_Not_Narrowing:
7196 // No narrowing occurred.
7197 return;
7198
7199 case NK_Type_Narrowing:
7200 // This was a floating-to-integer conversion, which is always considered a
7201 // narrowing conversion even if the value is a constant and can be
7202 // represented exactly as an integer.
7203 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007204 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7205 ? diag::warn_init_list_type_narrowing
7206 : diag::ext_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007207 << PostInit->getSourceRange()
7208 << PreNarrowingType.getLocalUnqualifiedType()
7209 << EntityType.getLocalUnqualifiedType();
7210 break;
7211
7212 case NK_Constant_Narrowing:
7213 // A constant value was narrowed.
7214 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007215 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7216 ? diag::warn_init_list_constant_narrowing
7217 : diag::ext_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007218 << PostInit->getSourceRange()
Richard Smith5614ca72012-03-23 23:55:39 +00007219 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007220 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007221 break;
7222
7223 case NK_Variable_Narrowing:
7224 // A variable's value may have been narrowed.
7225 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007226 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7227 ? diag::warn_init_list_variable_narrowing
7228 : diag::ext_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007229 << PostInit->getSourceRange()
7230 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007231 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007232 break;
7233 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007234
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007235 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007236 llvm::raw_svector_ostream OS(StaticCast);
7237 OS << "static_cast<";
7238 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7239 // It's important to use the typedef's name if there is one so that the
7240 // fixit doesn't break code using types like int64_t.
7241 //
7242 // FIXME: This will break if the typedef requires qualification. But
7243 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007244 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007245 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00007246 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007247 else {
7248 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
7249 // with a broken cast.
7250 return;
7251 }
7252 OS << ">(";
Alp Tokerb0869032014-05-17 01:13:18 +00007253 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007254 << PostInit->getSourceRange()
7255 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
7256 << FixItHint::CreateInsertion(
7257 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007258}
7259
Douglas Gregore1314a62009-12-18 05:02:21 +00007260//===----------------------------------------------------------------------===//
7261// Initialization helper functions
7262//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00007263bool
7264Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7265 ExprResult Init) {
7266 if (Init.isInvalid())
7267 return false;
7268
7269 Expr *InitE = Init.get();
7270 assert(InitE && "No initialization expression");
7271
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00007272 InitializationKind Kind
7273 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007274 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00007275 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00007276}
7277
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007278ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00007279Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7280 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007281 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00007282 bool TopLevelOfInitList,
7283 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00007284 if (Init.isInvalid())
7285 return ExprError();
7286
John McCall1f425642010-11-11 03:21:53 +00007287 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00007288 assert(InitE && "No initialization expression?");
7289
7290 if (EqualLoc.isInvalid())
7291 EqualLoc = InitE->getLocStart();
7292
7293 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00007294 EqualLoc,
7295 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00007296 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007297 Init.get();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007298
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007299 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00007300
Richard Smith66e05fe2012-01-18 05:21:49 +00007301 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00007302}