blob: bb0a9c11474be6172c4465bf68bcdd3d4928e859 [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) {
Richard Smith520449d2015-02-05 06:15:50 +0000643 // FIXME: Check that IL isn't already the semantic form of some other
644 // InitListExpr. If it is, we'd create a broken AST.
645
Steve Narofff8ecff22008-05-01 22:18:59 +0000646 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000647
Richard Smith4e0d2e42013-09-20 20:10:22 +0000648 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000649 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000650 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000651 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000652
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000653 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000654 bool RequiresSecondPass = false;
Richard Smith454a7cd2014-06-03 08:26:00 +0000655 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000656 if (RequiresSecondPass && !hadError)
Richard Smith454a7cd2014-06-03 08:26:00 +0000657 FillInEmptyInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000658 RequiresSecondPass);
659 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000660}
661
662int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000663 // FIXME: use a proper constant
664 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000665 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000666 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000667 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
668 }
669 return maxElements;
670}
671
672int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000673 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000674 int InitializableMembers = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000675 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000676 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000677 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000678
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000679 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000680 return std::min(InitializableMembers, 1);
681 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000682}
683
Richard Smith4e0d2e42013-09-20 20:10:22 +0000684/// Check whether the range of the initializer \p ParentIList from element
685/// \p Index onwards can be used to initialize an object of type \p T. Update
686/// \p Index to indicate how many elements of the list were consumed.
687///
688/// This also fills in \p StructuredList, from element \p StructuredIndex
689/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000690void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000691 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000692 QualType T, unsigned &Index,
693 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000694 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000695 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000696
Steve Narofff8ecff22008-05-01 22:18:59 +0000697 if (T->isArrayType())
698 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000699 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000700 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000701 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000702 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000703 else
David Blaikie83d382b2011-09-23 05:06:16 +0000704 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000705
Eli Friedmane0f832b2008-05-25 13:49:22 +0000706 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000707 if (!VerifyOnly)
708 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
709 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000710 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000711 hadError = true;
712 return;
713 }
714
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000715 // Build a structured initializer list corresponding to this subobject.
716 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000717 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
718 StructuredIndex,
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000719 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregor5741efb2009-03-01 17:12:46 +0000720 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000721 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000722
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000723 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000724 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000725 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000726 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000727 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000728 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000729
Richard Smithde229232013-06-06 11:41:05 +0000730 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000731 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000732
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000733 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000734 // Update the structured sub-object initializer so that it's ending
735 // range corresponds with the end of the last initializer it used.
736 if (EndIndex < ParentIList->getNumInits()) {
737 SourceLocation EndLoc
738 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
739 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
740 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000741
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000742 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000743 if (T->isArrayType() || T->isRecordType()) {
744 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smithde229232013-06-06 11:41:05 +0000745 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000746 << StructuredSubobjectInitList->getSourceRange()
747 << FixItHint::CreateInsertion(
748 StructuredSubobjectInitList->getLocStart(), "{")
749 << FixItHint::CreateInsertion(
750 SemaRef.getLocForEndOfToken(
751 StructuredSubobjectInitList->getLocEnd()),
752 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000753 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000754 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000755}
756
Richard Smith4e0d2e42013-09-20 20:10:22 +0000757/// Check whether the initializer \p IList (that was written with explicit
758/// braces) can be used to initialize an object of type \p T.
759///
760/// This also fills in \p StructuredList with the fully-braced, desugared
761/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000762void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000763 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000764 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000765 bool TopLevelObject) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000766 if (!VerifyOnly) {
767 SyntacticToSemantic[IList] = StructuredList;
768 StructuredList->setSyntacticForm(IList);
769 }
Richard Smith4e0d2e42013-09-20 20:10:22 +0000770
771 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000772 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000773 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000774 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +0000775 QualType ExprTy = T;
776 if (!ExprTy->isArrayType())
777 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000778 IList->setType(ExprTy);
779 StructuredList->setType(ExprTy);
780 }
Eli Friedman85f54972008-05-25 13:22:35 +0000781 if (hadError)
782 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000783
Eli Friedman85f54972008-05-25 13:22:35 +0000784 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000785 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000786 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000787 if (SemaRef.getLangOpts().CPlusPlus ||
788 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000789 IList->getType()->isVectorType())) {
790 hadError = true;
791 }
792 return;
793 }
794
Eli Friedmanbd327452009-05-29 20:20:05 +0000795 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +0000796 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
797 SIF_None) {
Richard Smith1b98ccc2014-07-19 01:39:17 +0000798 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000799 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000800 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000801 hadError = true;
802 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000803 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000804 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000805 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000806 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000807 // Don't complain for incomplete types, since we'll get an error
808 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000809 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000810 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000811 CurrentObjectType->isArrayType()? 0 :
812 CurrentObjectType->isVectorType()? 1 :
813 CurrentObjectType->isScalarType()? 2 :
814 CurrentObjectType->isUnionType()? 3 :
815 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000816
Richard Smith1b98ccc2014-07-19 01:39:17 +0000817 unsigned DK = diag::ext_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000818 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +0000819 DK = diag::err_excess_initializers;
820 hadError = true;
821 }
David Blaikiebbafb8a2012-03-11 07:00:24 +0000822 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +0000823 DK = diag::err_excess_initializers;
824 hadError = true;
825 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000826
Chris Lattnerb0912a52009-02-24 22:50:46 +0000827 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000828 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000829 }
830 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000831
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000832 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
833 !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000834 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000835 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000836 << FixItHint::CreateRemoval(IList->getLocStart())
837 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000838}
839
Anders Carlsson6cabf312010-01-23 23:23:01 +0000840void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000841 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000842 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000843 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000844 unsigned &Index,
845 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000846 unsigned &StructuredIndex,
847 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000848 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
849 // Explicitly braced initializer for complex type can be real+imaginary
850 // parts.
851 CheckComplexType(Entity, IList, DeclType, Index,
852 StructuredList, StructuredIndex);
853 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000854 CheckScalarType(Entity, IList, DeclType, Index,
855 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000856 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000857 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000858 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +0000859 } else if (DeclType->isRecordType()) {
860 assert(DeclType->isAggregateType() &&
861 "non-aggregate records should be handed in CheckSubElementType");
862 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
863 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
864 SubobjectIsDesignatorContext, Index,
865 StructuredList, StructuredIndex,
866 TopLevelObject);
867 } else if (DeclType->isArrayType()) {
868 llvm::APSInt Zero(
869 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
870 false);
871 CheckArrayType(Entity, IList, DeclType, Zero,
872 SubobjectIsDesignatorContext, Index,
873 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +0000874 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
875 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000876 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000877 if (!VerifyOnly)
878 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
879 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000880 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000881 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000882 CheckReferenceType(Entity, IList, DeclType, Index,
883 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000884 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000885 if (!VerifyOnly)
886 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
887 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000888 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000889 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000890 if (!VerifyOnly)
891 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
892 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000893 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000894 }
895}
896
Anders Carlsson6cabf312010-01-23 23:23:01 +0000897void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000898 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000899 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000900 unsigned &Index,
901 InitListExpr *StructuredList,
902 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000903 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +0000904
905 if (ElemType->isReferenceType())
906 return CheckReferenceType(Entity, IList, ElemType, Index,
907 StructuredList, StructuredIndex);
908
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000909 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smithe20c83d2012-07-07 08:35:56 +0000910 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
Richard Smith4e0d2e42013-09-20 20:10:22 +0000911 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +0000912 = getStructuredSubobjectInit(IList, Index, ElemType,
913 StructuredList, StructuredIndex,
914 SubInitList->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000915 CheckExplicitInitList(Entity, SubInitList, ElemType,
916 InnerStructuredList);
Richard Smithe20c83d2012-07-07 08:35:56 +0000917 ++StructuredIndex;
918 ++Index;
919 return;
920 }
921 assert(SemaRef.getLangOpts().CPlusPlus &&
922 "non-aggregate records are only possible in C++");
923 // C++ initialization is handled later.
Richard Smithc4158e862014-07-18 04:47:25 +0000924 } else if (isa<ImplicitValueInitExpr>(expr)) {
Richard Smith8aa561b2014-07-17 23:12:06 +0000925 // This happens during template instantiation when we see an InitListExpr
926 // that we've already checked once.
Richard Smithc4158e862014-07-18 04:47:25 +0000927 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
Richard Smith8aa561b2014-07-17 23:12:06 +0000928 "found implicit initialization for the wrong type");
929 if (!VerifyOnly)
930 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
931 ++Index;
932 return;
Richard Smithe20c83d2012-07-07 08:35:56 +0000933 }
934
Eli Friedman4628cf72013-08-19 22:12:56 +0000935 // FIXME: Need to handle atomic aggregate types with implicit init lists.
936 if (ElemType->isScalarType() || ElemType->isAtomicType())
John McCall5decec92011-02-21 07:57:55 +0000937 return CheckScalarType(Entity, IList, ElemType, Index,
938 StructuredList, StructuredIndex);
Anders Carlsson03068aa2009-08-27 17:18:13 +0000939
Eli Friedman4628cf72013-08-19 22:12:56 +0000940 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
941 ElemType->isArrayType()) && "Unexpected type");
942
John McCall5decec92011-02-21 07:57:55 +0000943 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
944 // arrayType can be incomplete if we're initializing a flexible
945 // array member. There's nothing we can do with the completed
946 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000947
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000948 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +0000949 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000950 CheckStringInit(expr, ElemType, arrayType, SemaRef);
951 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +0000952 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000953 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000954 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000955 }
John McCall5decec92011-02-21 07:57:55 +0000956
957 // Fall through for subaggregate initialization.
958
David Blaikiebbafb8a2012-03-11 07:00:24 +0000959 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCall5decec92011-02-21 07:57:55 +0000960 // C++ [dcl.init.aggr]p12:
961 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000962 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000963 // an initializer-list. If the initializer can initialize a
964 // member, the member is initialized. [...]
965
966 // FIXME: Better EqualLoc?
967 InitializationKind Kind =
968 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000969 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCall5decec92011-02-21 07:57:55 +0000970
971 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000972 if (!VerifyOnly) {
Richard Smith0f8ede12011-12-20 04:00:21 +0000973 ExprResult Result =
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000974 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smith0f8ede12011-12-20 04:00:21 +0000975 if (Result.isInvalid())
976 hadError = true;
John McCall5decec92011-02-21 07:57:55 +0000977
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000978 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000979 Result.getAs<Expr>());
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000980 }
John McCall5decec92011-02-21 07:57:55 +0000981 ++Index;
982 return;
983 }
984
985 // Fall through for subaggregate initialization
986 } else {
987 // C99 6.7.8p13:
988 //
989 // The initializer for a structure or union object that has
990 // automatic storage duration shall be either an initializer
991 // list as described below, or a single expression that has
992 // compatible structure or union type. In the latter case, the
993 // initial value of the object, including unnamed members, is
994 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000995 ExprResult ExprRes = expr;
John McCall5decec92011-02-21 07:57:55 +0000996 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000997 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
998 !VerifyOnly)
Eli Friedmanb2a8d462013-09-17 04:07:04 +0000999 != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +00001000 if (ExprRes.isInvalid())
1001 hadError = true;
1002 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001003 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001004 if (ExprRes.isInvalid())
1005 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +00001006 }
1007 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001008 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +00001009 ++Index;
1010 return;
1011 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001012 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +00001013 // Fall through for subaggregate initialization
1014 }
1015
1016 // C++ [dcl.init.aggr]p12:
1017 //
1018 // [...] Otherwise, if the member is itself a non-empty
1019 // subaggregate, brace elision is assumed and the initializer is
1020 // considered for the initialization of the first member of
1021 // the subaggregate.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001022 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00001023 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +00001024 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1025 StructuredIndex);
1026 ++StructuredIndex;
1027 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001028 if (!VerifyOnly) {
1029 // We cannot initialize this element, so let
1030 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001031 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001032 /*TopLevelOfInitList=*/true);
1033 }
John McCall5decec92011-02-21 07:57:55 +00001034 hadError = true;
1035 ++Index;
1036 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +00001037 }
Eli Friedman23a9e312008-05-19 19:16:24 +00001038}
1039
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001040void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1041 InitListExpr *IList, QualType DeclType,
1042 unsigned &Index,
1043 InitListExpr *StructuredList,
1044 unsigned &StructuredIndex) {
1045 assert(Index == 0 && "Index in explicit init list must be zero");
1046
1047 // As an extension, clang supports complex initializers, which initialize
1048 // a complex number component-wise. When an explicit initializer list for
1049 // a complex number contains two two initializers, this extension kicks in:
1050 // it exepcts the initializer list to contain two elements convertible to
1051 // the element type of the complex type. The first element initializes
1052 // the real part, and the second element intitializes the imaginary part.
1053
1054 if (IList->getNumInits() != 2)
1055 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1056 StructuredIndex);
1057
1058 // This is an extension in C. (The builtin _Complex type does not exist
1059 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001060 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001061 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1062 << IList->getSourceRange();
1063
1064 // Initialize the complex number.
1065 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1066 InitializedEntity ElementEntity =
1067 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1068
1069 for (unsigned i = 0; i < 2; ++i) {
1070 ElementEntity.setElementIndex(Index);
1071 CheckSubElementType(ElementEntity, IList, elementType, Index,
1072 StructuredList, StructuredIndex);
1073 }
1074}
1075
1076
Anders Carlsson6cabf312010-01-23 23:23:01 +00001077void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001078 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001079 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001080 InitListExpr *StructuredList,
1081 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001082 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001083 if (!VerifyOnly)
1084 SemaRef.Diag(IList->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001085 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smithc8239732011-10-18 21:39:00 +00001086 diag::warn_cxx98_compat_empty_scalar_initializer :
1087 diag::err_empty_scalar_initializer)
1088 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001089 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001090 ++Index;
1091 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001092 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001093 }
John McCall643169b2010-11-11 00:46:36 +00001094
1095 Expr *expr = IList->getInit(Index);
1096 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001097 // FIXME: This is invalid, and accepting it causes overload resolution
1098 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001099 if (!VerifyOnly)
1100 SemaRef.Diag(SubIList->getLocStart(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001101 diag::ext_many_braces_around_scalar_init)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001102 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001103
1104 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1105 StructuredIndex);
1106 return;
1107 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001108 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001109 SemaRef.Diag(expr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001110 diag::err_designator_for_scalar_init)
1111 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001112 hadError = true;
1113 ++Index;
1114 ++StructuredIndex;
1115 return;
1116 }
1117
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001118 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001119 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001120 hadError = true;
1121 ++Index;
1122 return;
1123 }
1124
John McCall643169b2010-11-11 00:46:36 +00001125 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001126 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001127 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001128
Craig Topperc3ec1492014-05-26 06:22:03 +00001129 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001130
1131 if (Result.isInvalid())
1132 hadError = true; // types weren't compatible.
1133 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001134 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001135
John McCall643169b2010-11-11 00:46:36 +00001136 if (ResultExpr != expr) {
1137 // The type was promoted, update initializer list.
1138 IList->setInit(Index, ResultExpr);
1139 }
1140 }
1141 if (hadError)
1142 ++StructuredIndex;
1143 else
1144 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1145 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001146}
1147
Anders Carlsson6cabf312010-01-23 23:23:01 +00001148void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1149 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001150 unsigned &Index,
1151 InitListExpr *StructuredList,
1152 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001153 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001154 // FIXME: It would be wonderful if we could point at the actual member. In
1155 // general, it would be useful to pass location information down the stack,
1156 // so that we know the location (or decl) of the "current object" being
1157 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001158 if (!VerifyOnly)
1159 SemaRef.Diag(IList->getLocStart(),
1160 diag::err_init_reference_member_uninitialized)
1161 << DeclType
1162 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001163 hadError = true;
1164 ++Index;
1165 ++StructuredIndex;
1166 return;
1167 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001168
1169 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001170 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001171 if (!VerifyOnly)
1172 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1173 << DeclType << IList->getSourceRange();
1174 hadError = true;
1175 ++Index;
1176 ++StructuredIndex;
1177 return;
1178 }
1179
1180 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001181 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001182 hadError = true;
1183 ++Index;
1184 return;
1185 }
1186
1187 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001188 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1189 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001190
1191 if (Result.isInvalid())
1192 hadError = true;
1193
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001194 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001195 IList->setInit(Index, expr);
1196
1197 if (hadError)
1198 ++StructuredIndex;
1199 else
1200 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1201 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001202}
1203
Anders Carlsson6cabf312010-01-23 23:23:01 +00001204void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001205 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001206 unsigned &Index,
1207 InitListExpr *StructuredList,
1208 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001209 const VectorType *VT = DeclType->getAs<VectorType>();
1210 unsigned maxElements = VT->getNumElements();
1211 unsigned numEltsInit = 0;
1212 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001213
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001214 if (Index >= IList->getNumInits()) {
1215 // Make sure the element type can be value-initialized.
1216 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001217 CheckEmptyInitializable(
1218 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1219 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001220 return;
1221 }
1222
David Blaikiebbafb8a2012-03-11 07:00:24 +00001223 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001224 // If the initializing element is a vector, try to copy-initialize
1225 // instead of breaking it apart (which is doomed to failure anyway).
1226 Expr *Init = IList->getInit(Index);
1227 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001228 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001229 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001230 hadError = true;
1231 ++Index;
1232 return;
1233 }
1234
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001235 ExprResult Result =
1236 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1237 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001238
Craig Topperc3ec1492014-05-26 06:22:03 +00001239 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001240 if (Result.isInvalid())
1241 hadError = true; // types weren't compatible.
1242 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001243 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001244
John McCall6a16b2f2010-10-30 00:11:39 +00001245 if (ResultExpr != Init) {
1246 // The type was promoted, update initializer list.
1247 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001248 }
1249 }
John McCall6a16b2f2010-10-30 00:11:39 +00001250 if (hadError)
1251 ++StructuredIndex;
1252 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001253 UpdateStructuredListElement(StructuredList, StructuredIndex,
1254 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001255 ++Index;
1256 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001257 }
Mike Stump11289f42009-09-09 15:08:12 +00001258
John McCall6a16b2f2010-10-30 00:11:39 +00001259 InitializedEntity ElementEntity =
1260 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001261
John McCall6a16b2f2010-10-30 00:11:39 +00001262 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1263 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001264 if (Index >= IList->getNumInits()) {
1265 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001266 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
John McCall6a16b2f2010-10-30 00:11:39 +00001267 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001268 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001269
John McCall6a16b2f2010-10-30 00:11:39 +00001270 ElementEntity.setElementIndex(Index);
1271 CheckSubElementType(ElementEntity, IList, elementType, Index,
1272 StructuredList, StructuredIndex);
1273 }
James Molloy9eef2652014-06-20 14:35:13 +00001274
1275 if (VerifyOnly)
1276 return;
1277
1278 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1279 const VectorType *T = Entity.getType()->getAs<VectorType>();
1280 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1281 T->getVectorKind() == VectorType::NeonPolyVector)) {
1282 // The ability to use vector initializer lists is a GNU vector extension
1283 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1284 // endian machines it works fine, however on big endian machines it
1285 // exhibits surprising behaviour:
1286 //
1287 // uint32x2_t x = {42, 64};
1288 // return vget_lane_u32(x, 0); // Will return 64.
1289 //
1290 // Because of this, explicitly call out that it is non-portable.
1291 //
1292 SemaRef.Diag(IList->getLocStart(),
1293 diag::warn_neon_vector_initializer_non_portable);
1294
1295 const char *typeCode;
1296 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1297
1298 if (elementType->isFloatingType())
1299 typeCode = "f";
1300 else if (elementType->isSignedIntegerType())
1301 typeCode = "s";
1302 else if (elementType->isUnsignedIntegerType())
1303 typeCode = "u";
1304 else
1305 llvm_unreachable("Invalid element type!");
1306
1307 SemaRef.Diag(IList->getLocStart(),
1308 SemaRef.Context.getTypeSize(VT) > 64 ?
1309 diag::note_neon_vector_initializer_non_portable_q :
1310 diag::note_neon_vector_initializer_non_portable)
1311 << typeCode << typeSize;
1312 }
1313
John McCall6a16b2f2010-10-30 00:11:39 +00001314 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001315 }
John McCall6a16b2f2010-10-30 00:11:39 +00001316
1317 InitializedEntity ElementEntity =
1318 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001319
John McCall6a16b2f2010-10-30 00:11:39 +00001320 // OpenCL initializers allows vectors to be constructed from vectors.
1321 for (unsigned i = 0; i < maxElements; ++i) {
1322 // Don't attempt to go past the end of the init list
1323 if (Index >= IList->getNumInits())
1324 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001325
John McCall6a16b2f2010-10-30 00:11:39 +00001326 ElementEntity.setElementIndex(Index);
1327
1328 QualType IType = IList->getInit(Index)->getType();
1329 if (!IType->isVectorType()) {
1330 CheckSubElementType(ElementEntity, IList, elementType, Index,
1331 StructuredList, StructuredIndex);
1332 ++numEltsInit;
1333 } else {
1334 QualType VecType;
1335 const VectorType *IVT = IType->getAs<VectorType>();
1336 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001337
John McCall6a16b2f2010-10-30 00:11:39 +00001338 if (IType->isExtVectorType())
1339 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1340 else
1341 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001342 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001343 CheckSubElementType(ElementEntity, IList, VecType, Index,
1344 StructuredList, StructuredIndex);
1345 numEltsInit += numIElts;
1346 }
1347 }
1348
1349 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001350 if (numEltsInit != maxElements) {
1351 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001352 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001353 diag::err_vector_incorrect_num_initializers)
1354 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1355 hadError = true;
1356 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001357}
1358
Anders Carlsson6cabf312010-01-23 23:23:01 +00001359void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001360 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001361 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001362 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001363 unsigned &Index,
1364 InitListExpr *StructuredList,
1365 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001366 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1367
Steve Narofff8ecff22008-05-01 22:18:59 +00001368 // Check for the special-case of initializing an array with a string.
1369 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001370 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1371 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001372 // We place the string literal directly into the resulting
1373 // initializer list. This is the only place where the structure
1374 // of the structured initializer list doesn't match exactly,
1375 // because doing so would involve allocating one character
1376 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001377 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001378 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1379 UpdateStructuredListElement(StructuredList, StructuredIndex,
1380 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001381 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1382 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001383 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001384 return;
1385 }
1386 }
John McCall66884dd2011-02-21 07:22:22 +00001387 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001388 // Check for VLAs; in standard C it would be possible to check this
1389 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1390 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001391 if (!VerifyOnly)
1392 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1393 diag::err_variable_object_no_init)
1394 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001395 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001396 ++Index;
1397 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001398 return;
1399 }
1400
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001401 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001402 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1403 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001404 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001405 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001406 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001407 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001408 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001409 maxElementsKnown = true;
1410 }
1411
John McCall66884dd2011-02-21 07:22:22 +00001412 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001413 while (Index < IList->getNumInits()) {
1414 Expr *Init = IList->getInit(Index);
1415 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001416 // If we're not the subobject that matches up with the '{' for
1417 // the designator, we shouldn't be handling the
1418 // designator. Return immediately.
1419 if (!SubobjectIsDesignatorContext)
1420 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001421
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001422 // Handle this designated initializer. elementIndex will be
1423 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001424 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001425 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001426 StructuredList, StructuredIndex, true,
1427 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001428 hadError = true;
1429 continue;
1430 }
1431
Douglas Gregor033d1252009-01-23 16:54:12 +00001432 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001433 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001434 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001435 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001436 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001437
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001438 // If the array is of incomplete type, keep track of the number of
1439 // elements in the initializer.
1440 if (!maxElementsKnown && elementIndex > maxElements)
1441 maxElements = elementIndex;
1442
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001443 continue;
1444 }
1445
1446 // If we know the maximum number of elements, and we've already
1447 // hit it, stop consuming elements in the initializer list.
1448 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001449 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001450
Anders Carlsson6cabf312010-01-23 23:23:01 +00001451 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001452 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001453 Entity);
1454 // Check this element.
1455 CheckSubElementType(ElementEntity, IList, elementType, Index,
1456 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001457 ++elementIndex;
1458
1459 // If the array is of incomplete type, keep track of the number of
1460 // elements in the initializer.
1461 if (!maxElementsKnown && elementIndex > maxElements)
1462 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001463 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001464 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001465 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001466 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001467 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001468 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001469 // Sizing an array implicitly to zero is not allowed by ISO C,
1470 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001471 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001472 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001473 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001474
Mike Stump11289f42009-09-09 15:08:12 +00001475 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001476 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001477 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001478 if (!hadError && VerifyOnly) {
1479 // Check if there are any members of the array that get value-initialized.
1480 // If so, check if doing that is possible.
1481 // FIXME: This needs to detect holes left by designated initializers too.
1482 if (maxElementsKnown && elementIndex < maxElements)
Richard Smith454a7cd2014-06-03 08:26:00 +00001483 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1484 SemaRef.Context, 0, Entity),
1485 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001486 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001487}
1488
Eli Friedman3fa64df2011-08-23 22:24:57 +00001489bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1490 Expr *InitExpr,
1491 FieldDecl *Field,
1492 bool TopLevelObject) {
1493 // Handle GNU flexible array initializers.
1494 unsigned FlexArrayDiag;
1495 if (isa<InitListExpr>(InitExpr) &&
1496 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1497 // Empty flexible array init always allowed as an extension
1498 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001499 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001500 // Disallow flexible array init in C++; it is not required for gcc
1501 // compatibility, and it needs work to IRGen correctly in general.
1502 FlexArrayDiag = diag::err_flexible_array_init;
1503 } else if (!TopLevelObject) {
1504 // Disallow flexible array init on non-top-level object
1505 FlexArrayDiag = diag::err_flexible_array_init;
1506 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1507 // Disallow flexible array init on anything which is not a variable.
1508 FlexArrayDiag = diag::err_flexible_array_init;
1509 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1510 // Disallow flexible array init on local variables.
1511 FlexArrayDiag = diag::err_flexible_array_init;
1512 } else {
1513 // Allow other cases.
1514 FlexArrayDiag = diag::ext_flexible_array_init;
1515 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001516
1517 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001518 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001519 FlexArrayDiag)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001520 << InitExpr->getLocStart();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001521 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1522 << Field;
1523 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001524
1525 return FlexArrayDiag != diag::ext_flexible_array_init;
1526}
1527
Anders Carlsson6cabf312010-01-23 23:23:01 +00001528void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001529 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001530 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001531 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001532 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001533 unsigned &Index,
1534 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001535 unsigned &StructuredIndex,
1536 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001537 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001538
Eli Friedman23a9e312008-05-19 19:16:24 +00001539 // If the record is invalid, some of it's members are invalid. To avoid
1540 // confusion, we forgo checking the intializer for the entire record.
1541 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001542 // Assume it was supposed to consume a single initializer.
1543 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001544 hadError = true;
1545 return;
Mike Stump11289f42009-09-09 15:08:12 +00001546 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001547
1548 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001549 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001550
1551 // If there's a default initializer, use it.
1552 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1553 if (VerifyOnly)
1554 return;
1555 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1556 Field != FieldEnd; ++Field) {
1557 if (Field->hasInClassInitializer()) {
1558 StructuredList->setInitializedFieldInUnion(*Field);
1559 // FIXME: Actually build a CXXDefaultInitExpr?
1560 return;
1561 }
1562 }
1563 }
1564
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001565 // Value-initialize the first member of the union that isn't an unnamed
1566 // bitfield.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001567 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1568 Field != FieldEnd; ++Field) {
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001569 if (!Field->isUnnamedBitfield()) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001570 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001571 CheckEmptyInitializable(
1572 InitializedEntity::InitializeMember(*Field, &Entity),
1573 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001574 else
David Blaikie40ed2972012-06-06 20:45:41 +00001575 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001576 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001577 }
1578 }
1579 return;
1580 }
1581
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001582 // If structDecl is a forward declaration, this loop won't do
1583 // anything except look at designated initializers; That's okay,
1584 // because an error should get printed out elsewhere. It might be
1585 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001586 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001587 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001588 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001589 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001590 while (Index < IList->getNumInits()) {
1591 Expr *Init = IList->getInit(Index);
1592
1593 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001594 // If we're not the subobject that matches up with the '{' for
1595 // the designator, we shouldn't be handling the
1596 // designator. Return immediately.
1597 if (!SubobjectIsDesignatorContext)
1598 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001599
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001600 // Handle this designated initializer. Field will be updated to
1601 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001602 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001603 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001604 StructuredList, StructuredIndex,
1605 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001606 hadError = true;
1607
Douglas Gregora9add4e2009-02-12 19:00:39 +00001608 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001609
1610 // Disable check for missing fields when designators are used.
1611 // This matches gcc behaviour.
1612 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001613 continue;
1614 }
1615
1616 if (Field == FieldEnd) {
1617 // We've run out of fields. We're done.
1618 break;
1619 }
1620
Douglas Gregora9add4e2009-02-12 19:00:39 +00001621 // We've already initialized a member of a union. We're done.
1622 if (InitializedSomething && DeclType->isUnionType())
1623 break;
1624
Douglas Gregor91f84212008-12-11 16:49:14 +00001625 // If we've hit the flexible array member at the end, we're done.
1626 if (Field->getType()->isIncompleteArrayType())
1627 break;
1628
Douglas Gregor51695702009-01-29 16:53:55 +00001629 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001630 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001631 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001632 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001633 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001634
Douglas Gregora82064c2011-06-29 21:51:31 +00001635 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001636 bool InvalidUse;
1637 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00001638 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001639 else
David Blaikie40ed2972012-06-06 20:45:41 +00001640 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001641 IList->getInit(Index)->getLocStart());
1642 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001643 ++Index;
1644 ++Field;
1645 hadError = true;
1646 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001647 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001648
Anders Carlsson6cabf312010-01-23 23:23:01 +00001649 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001650 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001651 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1652 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001653 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001654
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001655 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001656 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00001657 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001658 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001659
1660 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001661 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001662
John McCalle40b58e2010-03-11 19:32:38 +00001663 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001664 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1665 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1666 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001667 // It is possible we have one or more unnamed bitfields remaining.
1668 // Find first (if any) named field and emit warning.
1669 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1670 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00001671 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00001672 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00001673 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00001674 break;
1675 }
1676 }
1677 }
1678
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001679 // Check that any remaining fields can be value-initialized.
1680 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1681 !Field->getType()->isIncompleteArrayType()) {
1682 // FIXME: Should check for holes left by designated initializers too.
1683 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00001684 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00001685 CheckEmptyInitializable(
1686 InitializedEntity::InitializeMember(*Field, &Entity),
1687 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001688 }
1689 }
1690
Mike Stump11289f42009-09-09 15:08:12 +00001691 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001692 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001693 return;
1694
David Blaikie40ed2972012-06-06 20:45:41 +00001695 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00001696 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001697 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001698 ++Index;
1699 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001700 }
1701
Anders Carlsson6cabf312010-01-23 23:23:01 +00001702 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001703 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001704
Anders Carlsson6cabf312010-01-23 23:23:01 +00001705 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001706 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001707 StructuredList, StructuredIndex);
1708 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001709 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001710 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001711}
Steve Narofff8ecff22008-05-01 22:18:59 +00001712
Douglas Gregord5846a12009-04-15 06:41:24 +00001713/// \brief Expand a field designator that refers to a member of an
1714/// anonymous struct or union into a series of field designators that
1715/// refers to the field within the appropriate subobject.
1716///
Douglas Gregord5846a12009-04-15 06:41:24 +00001717static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001718 DesignatedInitExpr *DIE,
1719 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001720 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001721 typedef DesignatedInitExpr::Designator Designator;
1722
Douglas Gregord5846a12009-04-15 06:41:24 +00001723 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001724 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001725 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1726 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1727 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00001728 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00001729 DIE->getDesignator(DesigIdx)->getDotLoc(),
1730 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1731 else
Craig Topperc3ec1492014-05-26 06:22:03 +00001732 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1733 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001734 assert(isa<FieldDecl>(*PI));
1735 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001736 }
1737
1738 // Expand the current designator into the set of replacement
1739 // designators, so we have a full subobject path down to where the
1740 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001741 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001742 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001743}
Mike Stump11289f42009-09-09 15:08:12 +00001744
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001745static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1746 DesignatedInitExpr *DIE) {
1747 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1748 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1749 for (unsigned I = 0; I < NumIndexExprs; ++I)
1750 IndexExprs[I] = DIE->getSubExpr(I + 1);
1751 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001752 DIE->size(), IndexExprs,
1753 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001754 DIE->usesGNUSyntax(), DIE->getInit());
1755}
1756
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001757namespace {
1758
1759// Callback to only accept typo corrections that are for field members of
1760// the given struct or union.
1761class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1762 public:
1763 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1764 : Record(RD) {}
1765
Craig Toppere14c0f82014-03-12 04:55:44 +00001766 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001767 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1768 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1769 }
1770
1771 private:
1772 RecordDecl *Record;
1773};
1774
1775}
1776
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001777/// @brief Check the well-formedness of a C99 designated initializer.
1778///
1779/// Determines whether the designated initializer @p DIE, which
1780/// resides at the given @p Index within the initializer list @p
1781/// IList, is well-formed for a current object of type @p DeclType
1782/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001783/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001784/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001785///
1786/// @param IList The initializer list in which this designated
1787/// initializer occurs.
1788///
Douglas Gregora5324162009-04-15 04:56:10 +00001789/// @param DIE The designated initializer expression.
1790///
1791/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001792///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00001793/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001794/// into which the designation in @p DIE should refer.
1795///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001796/// @param NextField If non-NULL and the first designator in @p DIE is
1797/// a field, this will be set to the field declaration corresponding
1798/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001799///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001800/// @param NextElementIndex If non-NULL and the first designator in @p
1801/// DIE is an array designator or GNU array-range designator, this
1802/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001803///
1804/// @param Index Index into @p IList where the designated initializer
1805/// @p DIE occurs.
1806///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001807/// @param StructuredList The initializer list expression that
1808/// describes all of the subobject initializers in the order they'll
1809/// actually be initialized.
1810///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001811/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001812bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001813InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001814 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001815 DesignatedInitExpr *DIE,
1816 unsigned DesigIdx,
1817 QualType &CurrentObjectType,
1818 RecordDecl::field_iterator *NextField,
1819 llvm::APSInt *NextElementIndex,
1820 unsigned &Index,
1821 InitListExpr *StructuredList,
1822 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001823 bool FinishSubobjectInit,
1824 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001825 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001826 // Check the actual initialization for the designated object type.
1827 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001828
1829 // Temporarily remove the designator expression from the
1830 // initializer list that the child calls see, so that we don't try
1831 // to re-process the designator.
1832 unsigned OldIndex = Index;
1833 IList->setInit(OldIndex, DIE->getInit());
1834
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001835 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001836 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001837
1838 // Restore the designated initializer expression in the syntactic
1839 // form of the initializer list.
1840 if (IList->getInit(OldIndex) != DIE->getInit())
1841 DIE->setInit(IList->getInit(OldIndex));
1842 IList->setInit(OldIndex, DIE);
1843
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001844 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001845 }
1846
Douglas Gregora5324162009-04-15 04:56:10 +00001847 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001848 bool IsFirstDesignator = (DesigIdx == 0);
1849 if (!VerifyOnly) {
1850 assert((IsFirstDesignator || StructuredList) &&
1851 "Need a non-designated initializer list to start from");
1852
1853 // Determine the structural initializer list that corresponds to the
1854 // current subobject.
Benjamin Kramer6b441d62012-02-23 14:48:40 +00001855 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001856 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1857 StructuredList, StructuredIndex,
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001858 SourceRange(D->getLocStart(),
1859 DIE->getLocEnd()));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001860 assert(StructuredList && "Expected a structured initializer list");
1861 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001862
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001863 if (D->isFieldDesignator()) {
1864 // C99 6.7.8p7:
1865 //
1866 // If a designator has the form
1867 //
1868 // . identifier
1869 //
1870 // then the current object (defined below) shall have
1871 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001872 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001873 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001874 if (!RT) {
1875 SourceLocation Loc = D->getDotLoc();
1876 if (Loc.isInvalid())
1877 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001878 if (!VerifyOnly)
1879 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001880 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001881 ++Index;
1882 return true;
1883 }
1884
Douglas Gregord5846a12009-04-15 06:41:24 +00001885 FieldDecl *KnownField = D->getField();
David Majnemer36ef8982014-08-11 18:33:59 +00001886 if (!KnownField) {
1887 IdentifierInfo *FieldName = D->getFieldName();
1888 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1889 for (NamedDecl *ND : Lookup) {
1890 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
1891 KnownField = FD;
1892 break;
1893 }
1894 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001895 // In verify mode, don't modify the original.
1896 if (VerifyOnly)
1897 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
David Majnemer36ef8982014-08-11 18:33:59 +00001898 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001899 D = DIE->getDesignator(DesigIdx);
David Majnemer36ef8982014-08-11 18:33:59 +00001900 KnownField = cast<FieldDecl>(*IFD->chain_begin());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001901 break;
1902 }
1903 }
David Majnemer36ef8982014-08-11 18:33:59 +00001904 if (!KnownField) {
1905 if (VerifyOnly) {
1906 ++Index;
1907 return true; // No typo correction when just trying this out.
1908 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001909
David Majnemer36ef8982014-08-11 18:33:59 +00001910 // Name lookup found something, but it wasn't a field.
1911 if (!Lookup.empty()) {
1912 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1913 << FieldName;
1914 SemaRef.Diag(Lookup.front()->getLocation(),
1915 diag::note_field_designator_found);
1916 ++Index;
1917 return true;
1918 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001919
David Majnemer36ef8982014-08-11 18:33:59 +00001920 // Name lookup didn't find anything.
1921 // Determine whether this was a typo for another field name.
Richard Smithf9b15102013-08-17 00:46:16 +00001922 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
1923 DeclarationNameInfo(FieldName, D->getFieldLoc()),
David Majnemer36ef8982014-08-11 18:33:59 +00001924 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001925 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
1926 Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00001927 SemaRef.diagnoseTypo(
1928 Corrected,
1929 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
David Majnemer36ef8982014-08-11 18:33:59 +00001930 << FieldName << CurrentObjectType);
1931 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001932 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001933 } else {
David Majnemer36ef8982014-08-11 18:33:59 +00001934 // Typo correction didn't find anything.
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001935 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1936 << FieldName << CurrentObjectType;
1937 ++Index;
1938 return true;
1939 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001940 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001941 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001942
David Majnemer58e4ea92014-08-23 01:48:50 +00001943 unsigned FieldIndex = 0;
1944 for (auto *FI : RT->getDecl()->fields()) {
1945 if (FI->isUnnamedBitfield())
1946 continue;
1947 if (KnownField == FI)
1948 break;
1949 ++FieldIndex;
1950 }
1951
David Majnemer36ef8982014-08-11 18:33:59 +00001952 RecordDecl::field_iterator Field =
1953 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
1954
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001955 // All of the fields of a union are located at the same place in
1956 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001957 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001958 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00001959 if (!VerifyOnly) {
1960 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
1961 if (CurrentField && CurrentField != *Field) {
1962 assert(StructuredList->getNumInits() == 1
1963 && "A union should never have more than one initializer!");
1964
1965 // we're about to throw away an initializer, emit warning
1966 SemaRef.Diag(D->getFieldLoc(),
1967 diag::warn_initializer_overrides)
1968 << D->getSourceRange();
1969 Expr *ExistingInit = StructuredList->getInit(0);
1970 SemaRef.Diag(ExistingInit->getLocStart(),
1971 diag::note_previous_initializer)
1972 << /*FIXME:has side effects=*/0
1973 << ExistingInit->getSourceRange();
1974
1975 // remove existing initializer
1976 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00001977 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00001978 }
1979
David Blaikie40ed2972012-06-06 20:45:41 +00001980 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00001981 }
Douglas Gregor51695702009-01-29 16:53:55 +00001982 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001983
Douglas Gregora82064c2011-06-29 21:51:31 +00001984 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001985 bool InvalidUse;
1986 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00001987 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001988 else
David Blaikie40ed2972012-06-06 20:45:41 +00001989 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001990 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001991 ++Index;
1992 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001993 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001994
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001995 if (!VerifyOnly) {
1996 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00001997 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001998
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001999 // Make sure that our non-designated initializer list has space
2000 // for a subobject corresponding to this field.
2001 if (FieldIndex >= StructuredList->getNumInits())
2002 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2003 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002004
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002005 // This designator names a flexible array member.
2006 if (Field->getType()->isIncompleteArrayType()) {
2007 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00002008 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002009 // We can't designate an object within the flexible array
2010 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002011 if (!VerifyOnly) {
2012 DesignatedInitExpr::Designator *NextD
2013 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002014 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002015 diag::err_designator_into_flexible_array_member)
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002016 << SourceRange(NextD->getLocStart(),
2017 DIE->getLocEnd());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002018 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002019 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002020 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002021 Invalid = true;
2022 }
2023
Chris Lattner001b29c2010-10-10 17:49:49 +00002024 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2025 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002026 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002027 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002028 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002029 diag::err_flexible_array_init_needs_braces)
2030 << DIE->getInit()->getSourceRange();
2031 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002032 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002033 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002034 Invalid = true;
2035 }
2036
Eli Friedman3fa64df2011-08-23 22:24:57 +00002037 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00002038 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002039 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002040 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002041
2042 if (Invalid) {
2043 ++Index;
2044 return true;
2045 }
2046
2047 // Initialize the array.
2048 bool prevHadError = hadError;
2049 unsigned newStructuredIndex = FieldIndex;
2050 unsigned OldIndex = Index;
2051 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00002052
2053 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002054 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002055 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002056 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002057
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002058 IList->setInit(OldIndex, DIE);
2059 if (hadError && !prevHadError) {
2060 ++Field;
2061 ++FieldIndex;
2062 if (NextField)
2063 *NextField = Field;
2064 StructuredIndex = FieldIndex;
2065 return true;
2066 }
2067 } else {
2068 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002069 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002070 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002071
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002072 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002073 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002074 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002075 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002076 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002077 true, false))
2078 return true;
2079 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002080
2081 // Find the position of the next field to be initialized in this
2082 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002083 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002084 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002085
2086 // If this the first designator, our caller will continue checking
2087 // the rest of this struct/class/union subobject.
2088 if (IsFirstDesignator) {
2089 if (NextField)
2090 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002091 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002092 return false;
2093 }
2094
Douglas Gregor17bd0942009-01-28 23:36:17 +00002095 if (!FinishSubobjectInit)
2096 return false;
2097
Douglas Gregord5846a12009-04-15 06:41:24 +00002098 // We've already initialized something in the union; we're done.
2099 if (RT->getDecl()->isUnion())
2100 return hadError;
2101
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002102 // Check the remaining fields within this class/struct/union subobject.
2103 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002104
Anders Carlsson6cabf312010-01-23 23:23:01 +00002105 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002106 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002107 return hadError && !prevHadError;
2108 }
2109
2110 // C99 6.7.8p6:
2111 //
2112 // If a designator has the form
2113 //
2114 // [ constant-expression ]
2115 //
2116 // then the current object (defined below) shall have array
2117 // type and the expression shall be an integer constant
2118 // expression. If the array is of unknown size, any
2119 // nonnegative value is valid.
2120 //
2121 // Additionally, cope with the GNU extension that permits
2122 // designators of the form
2123 //
2124 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002125 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002126 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002127 if (!VerifyOnly)
2128 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2129 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002130 ++Index;
2131 return true;
2132 }
2133
Craig Topperc3ec1492014-05-26 06:22:03 +00002134 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002135 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2136 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002137 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002138 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002139 DesignatedEndIndex = DesignatedStartIndex;
2140 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002141 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002142
Mike Stump11289f42009-09-09 15:08:12 +00002143 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002144 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002145 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002146 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002147 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002148
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002149 // Codegen can't handle evaluating array range designators that have side
2150 // effects, because we replicate the AST value for each initialized element.
2151 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2152 // elements with something that has a side effect, so codegen can emit an
2153 // "error unsupported" error instead of miscompiling the app.
2154 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002155 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002156 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002157 }
2158
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002159 if (isa<ConstantArrayType>(AT)) {
2160 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002161 DesignatedStartIndex
2162 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002163 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002164 DesignatedEndIndex
2165 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002166 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2167 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002168 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002169 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002170 diag::err_array_designator_too_large)
2171 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2172 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002173 ++Index;
2174 return true;
2175 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002176 } else {
2177 // Make sure the bit-widths and signedness match.
2178 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002179 DesignatedEndIndex
2180 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002181 else if (DesignatedStartIndex.getBitWidth() <
2182 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002183 DesignatedStartIndex
2184 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002185 DesignatedStartIndex.setIsUnsigned(true);
2186 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002187 }
Mike Stump11289f42009-09-09 15:08:12 +00002188
Eli Friedman1f16b742013-06-11 21:48:11 +00002189 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2190 // We're modifying a string literal init; we have to decompose the string
2191 // so we can modify the individual characters.
2192 ASTContext &Context = SemaRef.Context;
2193 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2194
2195 // Compute the character type
2196 QualType CharTy = AT->getElementType();
2197
2198 // Compute the type of the integer literals.
2199 QualType PromotedCharTy = CharTy;
2200 if (CharTy->isPromotableIntegerType())
2201 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2202 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2203
2204 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2205 // Get the length of the string.
2206 uint64_t StrLen = SL->getLength();
2207 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2208 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2209 StructuredList->resizeInits(Context, StrLen);
2210
2211 // Build a literal for each character in the string, and put them into
2212 // the init list.
2213 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2214 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2215 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002216 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002217 if (CharTy != PromotedCharTy)
2218 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002219 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002220 StructuredList->updateInit(Context, i, Init);
2221 }
2222 } else {
2223 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2224 std::string Str;
2225 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2226
2227 // Get the length of the string.
2228 uint64_t StrLen = Str.size();
2229 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2230 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2231 StructuredList->resizeInits(Context, StrLen);
2232
2233 // Build a literal for each character in the string, and put them into
2234 // the init list.
2235 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2236 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2237 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002238 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002239 if (CharTy != PromotedCharTy)
2240 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002241 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002242 StructuredList->updateInit(Context, i, Init);
2243 }
2244 }
2245 }
2246
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002247 // Make sure that our non-designated initializer list has space
2248 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002249 if (!VerifyOnly &&
2250 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002251 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002252 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002253
Douglas Gregor17bd0942009-01-28 23:36:17 +00002254 // Repeatedly perform subobject initializations in the range
2255 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002256
Douglas Gregor17bd0942009-01-28 23:36:17 +00002257 // Move to the next designator
2258 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2259 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002260
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002261 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002262 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002263
Douglas Gregor17bd0942009-01-28 23:36:17 +00002264 while (DesignatedStartIndex <= DesignatedEndIndex) {
2265 // Recurse to check later designated subobjects.
2266 QualType ElementType = AT->getElementType();
2267 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002268
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002269 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002270 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002271 ElementType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002272 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002273 (DesignatedStartIndex == DesignatedEndIndex),
2274 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002275 return true;
2276
2277 // Move to the next index in the array that we'll be initializing.
2278 ++DesignatedStartIndex;
2279 ElementIndex = DesignatedStartIndex.getZExtValue();
2280 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002281
2282 // If this the first designator, our caller will continue checking
2283 // the rest of this array subobject.
2284 if (IsFirstDesignator) {
2285 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002286 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002287 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002288 return false;
2289 }
Mike Stump11289f42009-09-09 15:08:12 +00002290
Douglas Gregor17bd0942009-01-28 23:36:17 +00002291 if (!FinishSubobjectInit)
2292 return false;
2293
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002294 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002295 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002296 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002297 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002298 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002299 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002300}
2301
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002302// Get the structured initializer list for a subobject of type
2303// @p CurrentObjectType.
2304InitListExpr *
2305InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2306 QualType CurrentObjectType,
2307 InitListExpr *StructuredList,
2308 unsigned StructuredIndex,
2309 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002310 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002311 return nullptr; // No structured list in verification-only mode.
2312 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002313 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002314 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002315 else if (StructuredIndex < StructuredList->getNumInits())
2316 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002317
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002318 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2319 return Result;
2320
2321 if (ExistingInit) {
2322 // We are creating an initializer list that initializes the
2323 // subobjects of the current object, but there was already an
2324 // initialization that completely initialized the current
2325 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002326 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002327 // struct X { int a, b; };
2328 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002329 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002330 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2331 // designated initializer re-initializes the whole
2332 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002333 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002334 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002335 << InitRange;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002336 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002337 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002338 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002339 << ExistingInit->getSourceRange();
2340 }
2341
Mike Stump11289f42009-09-09 15:08:12 +00002342 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002343 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002344 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002345 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002346
Eli Friedman91f5ae52012-02-23 02:25:10 +00002347 QualType ResultType = CurrentObjectType;
2348 if (!ResultType->isArrayType())
2349 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2350 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002351
Douglas Gregor6d00c992009-03-20 23:58:33 +00002352 // Pre-allocate storage for the structured initializer list.
2353 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002354 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002355 bool GotNumInits = false;
2356 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002357 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002358 GotNumInits = true;
2359 } else if (Index < IList->getNumInits()) {
2360 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002361 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002362 GotNumInits = true;
2363 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002364 }
2365
Mike Stump11289f42009-09-09 15:08:12 +00002366 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002367 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2368 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2369 NumElements = CAType->getSize().getZExtValue();
2370 // Simple heuristic so that we don't allocate a very large
2371 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002372 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002373 NumElements = 0;
2374 }
John McCall9dd450b2009-09-21 23:43:11 +00002375 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002376 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002377 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002378 RecordDecl *RDecl = RType->getDecl();
2379 if (RDecl->isUnion())
2380 NumElements = 1;
2381 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002382 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002383 }
2384
Ted Kremenekac034612010-04-13 23:39:13 +00002385 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002386
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002387 // Link this new initializer list into the structured initializer
2388 // lists.
2389 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002390 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002391 else {
2392 Result->setSyntacticForm(IList);
2393 SyntacticToSemantic[IList] = Result;
2394 }
2395
2396 return Result;
2397}
2398
2399/// Update the initializer at index @p StructuredIndex within the
2400/// structured initializer list to the value @p expr.
2401void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2402 unsigned &StructuredIndex,
2403 Expr *expr) {
2404 // No structured initializer list to update
2405 if (!StructuredList)
2406 return;
2407
Ted Kremenekac034612010-04-13 23:39:13 +00002408 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2409 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002410 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002411 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002412 diag::warn_initializer_overrides)
2413 << expr->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002414 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002415 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002416 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002417 << PrevInit->getSourceRange();
2418 }
Mike Stump11289f42009-09-09 15:08:12 +00002419
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002420 ++StructuredIndex;
2421}
2422
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002423/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002424/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002425/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002426/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002427/// failure. Returns the index expression, possibly with an implicit cast
2428/// added, on success. If everything went okay, Value will receive the
2429/// value of the constant expression.
2430static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002431CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002432 SourceLocation Loc = Index->getLocStart();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002433
2434 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002435 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2436 if (Result.isInvalid())
2437 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002438
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002439 if (Value.isSigned() && Value.isNegative())
2440 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002441 << Value.toString(10) << Index->getSourceRange();
2442
Douglas Gregor51650d32009-01-23 21:04:18 +00002443 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002444 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002445}
2446
John McCalldadc5752010-08-24 06:29:42 +00002447ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002448 SourceLocation Loc,
2449 bool GNUSyntax,
2450 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002451 typedef DesignatedInitExpr::Designator ASTDesignator;
2452
2453 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002454 SmallVector<ASTDesignator, 32> Designators;
2455 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002456
2457 // Build designators and check array designator expressions.
2458 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2459 const Designator &D = Desig.getDesignator(Idx);
2460 switch (D.getKind()) {
2461 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002462 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002463 D.getFieldLoc()));
2464 break;
2465
2466 case Designator::ArrayDesignator: {
2467 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2468 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002469 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002470 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002471 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002472 Invalid = true;
2473 else {
2474 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002475 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002476 D.getRBracketLoc()));
2477 InitExpressions.push_back(Index);
2478 }
2479 break;
2480 }
2481
2482 case Designator::ArrayRangeDesignator: {
2483 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2484 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2485 llvm::APSInt StartValue;
2486 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002487 bool StartDependent = StartIndex->isTypeDependent() ||
2488 StartIndex->isValueDependent();
2489 bool EndDependent = EndIndex->isTypeDependent() ||
2490 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002491 if (!StartDependent)
2492 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002493 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002494 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002495 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002496
2497 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002498 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002499 else {
2500 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002501 if (StartDependent || EndDependent) {
2502 // Nothing to compute.
2503 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002504 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002505 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002506 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002507
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002508 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002509 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002510 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002511 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2512 Invalid = true;
2513 } else {
2514 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002515 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002516 D.getEllipsisLoc(),
2517 D.getRBracketLoc()));
2518 InitExpressions.push_back(StartIndex);
2519 InitExpressions.push_back(EndIndex);
2520 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002521 }
2522 break;
2523 }
2524 }
2525 }
2526
2527 if (Invalid || Init.isInvalid())
2528 return ExprError();
2529
2530 // Clear out the expressions within the designation.
2531 Desig.ClearExprs(*this);
2532
2533 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002534 = DesignatedInitExpr::Create(Context,
2535 Designators.data(), Designators.size(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00002536 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002537 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002538
David Blaikiebbafb8a2012-03-11 07:00:24 +00002539 if (!getLangOpts().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002540 Diag(DIE->getLocStart(), diag::ext_designated_init)
2541 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002542
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002543 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002544}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002545
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002546//===----------------------------------------------------------------------===//
2547// Initialization entity
2548//===----------------------------------------------------------------------===//
2549
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002550InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002551 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002552 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002553{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002554 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2555 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002556 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002557 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002558 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002559 Type = VT->getElementType();
2560 } else {
2561 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2562 assert(CT && "Unexpected type");
2563 Kind = EK_ComplexElement;
2564 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002565 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002566}
2567
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002568InitializedEntity
2569InitializedEntity::InitializeBase(ASTContext &Context,
2570 const CXXBaseSpecifier *Base,
2571 bool IsInheritedVirtualBase) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002572 InitializedEntity Result;
2573 Result.Kind = EK_Base;
Craig Topperc3ec1492014-05-26 06:22:03 +00002574 Result.Parent = nullptr;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002575 Result.Base = reinterpret_cast<uintptr_t>(Base);
2576 if (IsInheritedVirtualBase)
2577 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002578
Douglas Gregor1b303932009-12-22 15:35:07 +00002579 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002580 return Result;
2581}
2582
Douglas Gregor85dabae2009-12-16 01:38:02 +00002583DeclarationName InitializedEntity::getName() const {
2584 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002585 case EK_Parameter:
2586 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00002587 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2588 return (D ? D->getDeclName() : DeclarationName());
2589 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002590
2591 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002592 case EK_Member:
2593 return VariableOrMember->getDeclName();
2594
Douglas Gregor19666fb2012-02-15 16:57:26 +00002595 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002596 return DeclarationName(Capture.VarID);
Douglas Gregor19666fb2012-02-15 16:57:26 +00002597
Douglas Gregor85dabae2009-12-16 01:38:02 +00002598 case EK_Result:
2599 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002600 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002601 case EK_Temporary:
2602 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002603 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002604 case EK_ArrayElement:
2605 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002606 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002607 case EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002608 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002609 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002610 return DeclarationName();
2611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002612
David Blaikie8a40f702012-01-17 06:56:22 +00002613 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002614}
2615
Douglas Gregora4b592a2009-12-19 03:01:41 +00002616DeclaratorDecl *InitializedEntity::getDecl() const {
2617 switch (getKind()) {
2618 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002619 case EK_Member:
2620 return VariableOrMember;
2621
John McCall31168b02011-06-15 23:02:42 +00002622 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002623 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00002624 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2625
Douglas Gregora4b592a2009-12-19 03:01:41 +00002626 case EK_Result:
2627 case EK_Exception:
2628 case EK_New:
2629 case EK_Temporary:
2630 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002631 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002632 case EK_ArrayElement:
2633 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002634 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002635 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002636 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002637 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002638 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00002639 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00002640 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002641
David Blaikie8a40f702012-01-17 06:56:22 +00002642 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002643}
2644
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002645bool InitializedEntity::allowsNRVO() const {
2646 switch (getKind()) {
2647 case EK_Result:
2648 case EK_Exception:
2649 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002650
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002651 case EK_Variable:
2652 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002653 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002654 case EK_Member:
2655 case EK_New:
2656 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002657 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002658 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002659 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002660 case EK_ArrayElement:
2661 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002662 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002663 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002664 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002665 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002666 break;
2667 }
2668
2669 return false;
2670}
2671
Richard Smithe6c01442013-06-05 00:46:14 +00002672unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00002673 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00002674 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2675 for (unsigned I = 0; I != Depth; ++I)
2676 OS << "`-";
2677
2678 switch (getKind()) {
2679 case EK_Variable: OS << "Variable"; break;
2680 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002681 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2682 break;
Richard Smithe6c01442013-06-05 00:46:14 +00002683 case EK_Result: OS << "Result"; break;
2684 case EK_Exception: OS << "Exception"; break;
2685 case EK_Member: OS << "Member"; break;
2686 case EK_New: OS << "New"; break;
2687 case EK_Temporary: OS << "Temporary"; break;
2688 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002689 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00002690 case EK_Base: OS << "Base"; break;
2691 case EK_Delegating: OS << "Delegating"; break;
2692 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2693 case EK_VectorElement: OS << "VectorElement " << Index; break;
2694 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2695 case EK_BlockElement: OS << "Block"; break;
2696 case EK_LambdaCapture:
2697 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002698 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00002699 break;
2700 }
2701
2702 if (Decl *D = getDecl()) {
2703 OS << " ";
2704 cast<NamedDecl>(D)->printQualifiedName(OS);
2705 }
2706
2707 OS << " '" << getType().getAsString() << "'\n";
2708
2709 return Depth + 1;
2710}
2711
2712void InitializedEntity::dump() const {
2713 dumpImpl(llvm::errs());
2714}
2715
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002716//===----------------------------------------------------------------------===//
2717// Initialization sequence
2718//===----------------------------------------------------------------------===//
2719
2720void InitializationSequence::Step::Destroy() {
2721 switch (Kind) {
2722 case SK_ResolveAddressOfOverloadedFunction:
2723 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002724 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002725 case SK_CastDerivedToBaseLValue:
2726 case SK_BindReference:
2727 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002728 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002729 case SK_UserConversion:
2730 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002731 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002732 case SK_QualificationConversionLValue:
Richard Smith77be48a2014-07-31 06:31:19 +00002733 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00002734 case SK_LValueToRValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002735 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00002736 case SK_UnwrapInitList:
2737 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002738 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00002739 case SK_ConstructorInitializationFromList:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002740 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002741 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002742 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002743 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002744 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00002745 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002746 case SK_PassByIndirectCopyRestore:
2747 case SK_PassByIndirectRestore:
2748 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002749 case SK_StdInitializerList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00002750 case SK_StdInitializerListConstructorCall:
Guy Benyei61054192013-02-07 10:55:47 +00002751 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002752 case SK_OCLZeroEvent:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002753 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002754
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002755 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00002756 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002757 delete ICS;
2758 }
2759}
2760
Douglas Gregor838fcc32010-03-26 20:14:36 +00002761bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002762 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002763}
2764
2765bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002766 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002767 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002768
Douglas Gregor838fcc32010-03-26 20:14:36 +00002769 switch (getFailureKind()) {
2770 case FK_TooManyInitsForReference:
2771 case FK_ArrayNeedsInitList:
2772 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00002773 case FK_ArrayNeedsInitListOrWideStringLiteral:
2774 case FK_NarrowStringIntoWideCharArray:
2775 case FK_WideStringIntoCharArray:
2776 case FK_IncompatWideStringIntoWideChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002777 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2778 case FK_NonConstLValueReferenceBindingToTemporary:
2779 case FK_NonConstLValueReferenceBindingToUnrelated:
2780 case FK_RValueReferenceBindingToLValue:
2781 case FK_ReferenceInitDropsQualifiers:
2782 case FK_ReferenceInitFailed:
2783 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002784 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002785 case FK_TooManyInitsForScalar:
2786 case FK_ReferenceBindingToInitList:
2787 case FK_InitListBadDestinationType:
2788 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002789 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002790 case FK_ArrayTypeMismatch:
2791 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002792 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002793 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002794 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00002795 case FK_ExplicitConstructor:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002796 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002797
Douglas Gregor838fcc32010-03-26 20:14:36 +00002798 case FK_ReferenceInitOverloadFailed:
2799 case FK_UserConversionOverloadFailed:
2800 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002801 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002802 return FailedOverloadResult == OR_Ambiguous;
2803 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002804
David Blaikie8a40f702012-01-17 06:56:22 +00002805 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00002806}
2807
Douglas Gregorb33eed02010-04-16 22:09:46 +00002808bool InitializationSequence::isConstructorInitialization() const {
2809 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2810}
2811
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002812void
2813InitializationSequence
2814::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2815 DeclAccessPair Found,
2816 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002817 Step S;
2818 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2819 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002820 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002821 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002822 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002823 Steps.push_back(S);
2824}
2825
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002826void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002827 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002828 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002829 switch (VK) {
2830 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2831 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2832 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002833 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002834 S.Type = BaseType;
2835 Steps.push_back(S);
2836}
2837
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002838void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002839 bool BindingTemporary) {
2840 Step S;
2841 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2842 S.Type = T;
2843 Steps.push_back(S);
2844}
2845
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002846void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2847 Step S;
2848 S.Kind = SK_ExtraneousCopyToTemporary;
2849 S.Type = T;
2850 Steps.push_back(S);
2851}
2852
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002853void
2854InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2855 DeclAccessPair FoundDecl,
2856 QualType T,
2857 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002858 Step S;
2859 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002860 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002861 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002862 S.Function.Function = Function;
2863 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002864 Steps.push_back(S);
2865}
2866
2867void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002868 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002869 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002870 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002871 switch (VK) {
2872 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002873 S.Kind = SK_QualificationConversionRValue;
2874 break;
John McCall2536c6d2010-08-25 10:28:54 +00002875 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002876 S.Kind = SK_QualificationConversionXValue;
2877 break;
John McCall2536c6d2010-08-25 10:28:54 +00002878 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002879 S.Kind = SK_QualificationConversionLValue;
2880 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002881 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002882 S.Type = Ty;
2883 Steps.push_back(S);
2884}
2885
Richard Smith77be48a2014-07-31 06:31:19 +00002886void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
2887 Step S;
2888 S.Kind = SK_AtomicConversion;
2889 S.Type = Ty;
2890 Steps.push_back(S);
2891}
2892
Jordan Roseb1312a52013-04-11 00:58:58 +00002893void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2894 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2895
2896 Step S;
2897 S.Kind = SK_LValueToRValue;
2898 S.Type = Ty;
2899 Steps.push_back(S);
2900}
2901
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002902void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00002903 const ImplicitConversionSequence &ICS, QualType T,
2904 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002905 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00002906 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
2907 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002908 S.Type = T;
2909 S.ICS = new ImplicitConversionSequence(ICS);
2910 Steps.push_back(S);
2911}
2912
Douglas Gregor51e77d52009-12-10 17:56:55 +00002913void InitializationSequence::AddListInitializationStep(QualType T) {
2914 Step S;
2915 S.Kind = SK_ListInitialization;
2916 S.Type = T;
2917 Steps.push_back(S);
2918}
2919
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002920void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002921InitializationSequence
2922::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2923 AccessSpecifier Access,
2924 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002925 bool HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002926 bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002927 Step S;
Richard Smithf8adcdc2014-07-17 05:12:35 +00002928 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
Richard Smith53324112014-07-16 21:33:43 +00002929 : SK_ConstructorInitializationFromList
2930 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002931 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002932 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002933 S.Function.Function = Constructor;
2934 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002935 Steps.push_back(S);
2936}
2937
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002938void InitializationSequence::AddZeroInitializationStep(QualType T) {
2939 Step S;
2940 S.Kind = SK_ZeroInitialization;
2941 S.Type = T;
2942 Steps.push_back(S);
2943}
2944
Douglas Gregore1314a62009-12-18 05:02:21 +00002945void InitializationSequence::AddCAssignmentStep(QualType T) {
2946 Step S;
2947 S.Kind = SK_CAssignment;
2948 S.Type = T;
2949 Steps.push_back(S);
2950}
2951
Eli Friedman78275202009-12-19 08:11:05 +00002952void InitializationSequence::AddStringInitStep(QualType T) {
2953 Step S;
2954 S.Kind = SK_StringInit;
2955 S.Type = T;
2956 Steps.push_back(S);
2957}
2958
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002959void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2960 Step S;
2961 S.Kind = SK_ObjCObjectConversion;
2962 S.Type = T;
2963 Steps.push_back(S);
2964}
2965
Douglas Gregore2f943b2011-02-22 18:29:51 +00002966void InitializationSequence::AddArrayInitStep(QualType T) {
2967 Step S;
2968 S.Kind = SK_ArrayInit;
2969 S.Type = T;
2970 Steps.push_back(S);
2971}
2972
Richard Smithebeed412012-02-15 22:38:09 +00002973void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2974 Step S;
2975 S.Kind = SK_ParenthesizedArrayInit;
2976 S.Type = T;
2977 Steps.push_back(S);
2978}
2979
John McCall31168b02011-06-15 23:02:42 +00002980void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2981 bool shouldCopy) {
2982 Step s;
2983 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2984 : SK_PassByIndirectRestore);
2985 s.Type = type;
2986 Steps.push_back(s);
2987}
2988
2989void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2990 Step S;
2991 S.Kind = SK_ProduceObjCObject;
2992 S.Type = T;
2993 Steps.push_back(S);
2994}
2995
Sebastian Redlc1839b12012-01-17 22:49:42 +00002996void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2997 Step S;
2998 S.Kind = SK_StdInitializerList;
2999 S.Type = T;
3000 Steps.push_back(S);
3001}
3002
Guy Benyei61054192013-02-07 10:55:47 +00003003void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3004 Step S;
3005 S.Kind = SK_OCLSamplerInit;
3006 S.Type = T;
3007 Steps.push_back(S);
3008}
3009
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003010void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3011 Step S;
3012 S.Kind = SK_OCLZeroEvent;
3013 S.Type = T;
3014 Steps.push_back(S);
3015}
3016
Sebastian Redl29526f02011-11-27 16:50:07 +00003017void InitializationSequence::RewrapReferenceInitList(QualType T,
3018 InitListExpr *Syntactic) {
3019 assert(Syntactic->getNumInits() == 1 &&
3020 "Can only rewrap trivial init lists.");
3021 Step S;
3022 S.Kind = SK_UnwrapInitList;
3023 S.Type = Syntactic->getInit(0)->getType();
3024 Steps.insert(Steps.begin(), S);
3025
3026 S.Kind = SK_RewrapInitList;
3027 S.Type = T;
3028 S.WrappingSyntacticList = Syntactic;
3029 Steps.push_back(S);
3030}
3031
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003032void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003033 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00003034 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003035 this->Failure = Failure;
3036 this->FailedOverloadResult = Result;
3037}
3038
3039//===----------------------------------------------------------------------===//
3040// Attempt initialization
3041//===----------------------------------------------------------------------===//
3042
John McCall31168b02011-06-15 23:02:42 +00003043static void MaybeProduceObjCObject(Sema &S,
3044 InitializationSequence &Sequence,
3045 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003046 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00003047
3048 /// When initializing a parameter, produce the value if it's marked
3049 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003050 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00003051 if (!Entity.isParameterConsumed())
3052 return;
3053
3054 assert(Entity.getType()->isObjCRetainableType() &&
3055 "consuming an object of unretainable type?");
3056 Sequence.AddProduceObjCObjectStep(Entity.getType());
3057
3058 /// When initializing a return value, if the return type is a
3059 /// retainable type, then returns need to immediately retain the
3060 /// object. If an autorelease is required, it will be done at the
3061 /// last instant.
3062 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3063 if (!Entity.getType()->isObjCRetainableType())
3064 return;
3065
3066 Sequence.AddProduceObjCObjectStep(Entity.getType());
3067 }
3068}
3069
Richard Smithcc1b96d2013-06-12 22:31:48 +00003070static void TryListInitialization(Sema &S,
3071 const InitializedEntity &Entity,
3072 const InitializationKind &Kind,
3073 InitListExpr *InitList,
3074 InitializationSequence &Sequence);
3075
Richard Smithd86812d2012-07-05 08:39:21 +00003076/// \brief When initializing from init list via constructor, handle
3077/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003078///
Richard Smithd86812d2012-07-05 08:39:21 +00003079/// \return true if we have handled initialization of an object of type
3080/// std::initializer_list<T>, false otherwise.
3081static bool TryInitializerListConstruction(Sema &S,
3082 InitListExpr *List,
3083 QualType DestType,
3084 InitializationSequence &Sequence) {
3085 QualType E;
3086 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003087 return false;
3088
Richard Smithcc1b96d2013-06-12 22:31:48 +00003089 if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
3090 Sequence.setIncompleteTypeFailure(E);
3091 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003092 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003093
3094 // Try initializing a temporary array from the init list.
3095 QualType ArrayType = S.Context.getConstantArrayType(
3096 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3097 List->getNumInits()),
3098 clang::ArrayType::Normal, 0);
3099 InitializedEntity HiddenArray =
3100 InitializedEntity::InitializeTemporary(ArrayType);
3101 InitializationKind Kind =
3102 InitializationKind::CreateDirectList(List->getExprLoc());
3103 TryListInitialization(S, HiddenArray, Kind, List, Sequence);
3104 if (Sequence)
3105 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003106 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003107}
3108
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003109static OverloadingResult
3110ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003111 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003112 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003113 ArrayRef<NamedDecl *> Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003114 OverloadCandidateSet::iterator &Best,
3115 bool CopyInitializing, bool AllowExplicit,
Larisse Voufo19d08672015-01-27 18:47:05 +00003116 bool OnlyListConstructors) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003117 CandidateSet.clear();
3118
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003119 for (ArrayRef<NamedDecl *>::iterator
3120 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003121 NamedDecl *D = *Con;
3122 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3123 bool SuppressUserConversions = false;
3124
3125 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003126 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003127 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3128 if (ConstructorTmpl)
3129 Constructor = cast<CXXConstructorDecl>(
3130 ConstructorTmpl->getTemplatedDecl());
3131 else {
3132 Constructor = cast<CXXConstructorDecl>(D);
3133
Richard Smith6c6ddab2013-09-21 21:23:47 +00003134 // C++11 [over.best.ics]p4:
Larisse Voufo19d08672015-01-27 18:47:05 +00003135 // ... and the constructor or user-defined conversion function is a
3136 // candidate by
3137 // — 13.3.1.3, when the argument is the temporary in the second step
3138 // of a class copy-initialization, or
3139 // — 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases),
3140 // user-defined conversion sequences are not considered.
3141 if (CopyInitializing && Constructor->isCopyOrMoveConstructor())
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003142 SuppressUserConversions = true;
3143 }
3144
3145 if (!Constructor->isInvalidDecl() &&
3146 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003147 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003148 if (ConstructorTmpl)
3149 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003150 /*ExplicitArgs*/ nullptr, Args,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003151 CandidateSet, SuppressUserConversions);
Douglas Gregor6073dca2012-02-24 23:56:31 +00003152 else {
3153 // C++ [over.match.copy]p1:
3154 // - When initializing a temporary to be bound to the first parameter
3155 // of a constructor that takes a reference to possibly cv-qualified
3156 // T as its first argument, called with a single argument in the
3157 // context of direct-initialization, explicit conversion functions
3158 // are also considered.
3159 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003160 Args.size() == 1 &&
Douglas Gregor6073dca2012-02-24 23:56:31 +00003161 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003162 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003163 SuppressUserConversions,
3164 /*PartialOverloading=*/false,
3165 /*AllowExplicit=*/AllowExplicitConv);
3166 }
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003167 }
3168 }
3169
3170 // Perform overload resolution and return the result.
3171 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3172}
3173
Sebastian Redled2e5322011-12-22 14:44:04 +00003174/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3175/// enumerates the constructors of the initialized entity and performs overload
3176/// resolution to select the best.
Richard Smithed83ebd2015-02-05 07:02:11 +00003177/// \param InitListSyntax Is this list-initialization?
3178/// \param IsInitListCopy Is this non-list-initialization resulting from a
3179/// list-initialization from {x} where x is the same
3180/// type as the entity?
Sebastian Redled2e5322011-12-22 14:44:04 +00003181static void TryConstructorInitialization(Sema &S,
3182 const InitializedEntity &Entity,
3183 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003184 MultiExprArg Args, QualType DestType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003185 InitializationSequence &Sequence,
Richard Smithed83ebd2015-02-05 07:02:11 +00003186 bool IsListInit = false,
3187 bool IsInitListCopy = false) {
3188 assert((!IsListInit || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3189 "IsListInit must come with a single initializer list argument.");
Sebastian Redl88e4d492012-02-04 21:27:33 +00003190
Sebastian Redled2e5322011-12-22 14:44:04 +00003191 // The type we're constructing needs to be complete.
3192 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003193 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003194 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003195 }
3196
3197 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3198 assert(DestRecordType && "Constructor initialization requires record type");
3199 CXXRecordDecl *DestRecordDecl
3200 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3201
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003202 // Build the candidate set directly in the initialization sequence
3203 // structure, so that it will persist if we fail.
3204 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3205
3206 // Determine whether we are allowed to call explicit constructors or
3207 // explicit conversion operators.
Richard Smithed83ebd2015-02-05 07:02:11 +00003208 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003209 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003210
Sebastian Redled2e5322011-12-22 14:44:04 +00003211 // - Otherwise, if T is a class type, constructors are considered. The
3212 // applicable constructors are enumerated, and the best one is chosen
3213 // through overload resolution.
David Blaikieff7d47a2012-12-19 00:45:41 +00003214 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003215 // The container holding the constructors can under certain conditions
3216 // be changed while iterating (e.g. because of deserialization).
3217 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003218 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redled2e5322011-12-22 14:44:04 +00003219
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003220 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003221 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003222 bool AsInitializerList = false;
3223
Larisse Voufo19d08672015-01-27 18:47:05 +00003224 // C++11 [over.match.list]p1, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003225 // When objects of non-aggregate type T are list-initialized, such that
3226 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3227 // according to the rules in this section, overload resolution selects
3228 // the constructor in two phases:
3229 //
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003230 // - Initially, the candidate functions are the initializer-list
3231 // constructors of the class T and the argument list consists of the
3232 // initializer list as a single argument.
Richard Smithed83ebd2015-02-05 07:02:11 +00003233 if (IsListInit) {
Richard Smithd86812d2012-07-05 08:39:21 +00003234 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003235 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003236
3237 // If the initializer list has no elements and T has a default constructor,
3238 // the first phase is omitted.
Richard Smith2be35f52012-12-01 02:35:44 +00003239 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003240 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003241 CandidateSet, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003242 CopyInitialization, AllowExplicit,
Larisse Voufo19d08672015-01-27 18:47:05 +00003243 /*OnlyListConstructor=*/true);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003244
3245 // Time to unwrap the init list.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003246 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003247 }
3248
3249 // C++11 [over.match.list]p1:
3250 // - If no viable initializer-list constructor is found, overload resolution
3251 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003252 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003253 // elements of the initializer list.
3254 if (Result == OR_No_Viable_Function) {
3255 AsInitializerList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003256 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003257 CandidateSet, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003258 CopyInitialization, AllowExplicit,
Larisse Voufo19d08672015-01-27 18:47:05 +00003259 /*OnlyListConstructors=*/false);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003260 }
3261 if (Result) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003262 Sequence.SetOverloadFailure(IsListInit ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003263 InitializationSequence::FK_ListConstructorOverloadFailed :
3264 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003265 Result);
3266 return;
3267 }
3268
Richard Smithd86812d2012-07-05 08:39:21 +00003269 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003270 // If a program calls for the default initialization of an object
3271 // of a const-qualified type T, T shall be a class type with a
3272 // user-provided default constructor.
3273 if (Kind.getKind() == InitializationKind::IK_Default &&
3274 Entity.getType().isConstQualified() &&
Aaron Ballman899b9c62012-07-31 22:40:31 +00003275 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redled2e5322011-12-22 14:44:04 +00003276 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3277 return;
3278 }
3279
Sebastian Redl048a6d72012-04-01 19:54:59 +00003280 // C++11 [over.match.list]p1:
3281 // In copy-list-initialization, if an explicit constructor is chosen, the
3282 // initializer is ill-formed.
3283 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Richard Smithed83ebd2015-02-05 07:02:11 +00003284 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
Sebastian Redl048a6d72012-04-01 19:54:59 +00003285 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3286 return;
3287 }
3288
Sebastian Redled2e5322011-12-22 14:44:04 +00003289 // Add the constructor initialization step. Any cv-qualification conversion is
3290 // subsumed by the initialization.
3291 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Richard Smithed83ebd2015-02-05 07:02:11 +00003292 Sequence.AddConstructorInitializationStep(
3293 CtorDecl, Best->FoundDecl.getAccess(), DestType, HadMultipleCandidates,
3294 IsListInit | IsInitListCopy, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003295}
3296
Sebastian Redl29526f02011-11-27 16:50:07 +00003297static bool
3298ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3299 Expr *Initializer,
3300 QualType &SourceType,
3301 QualType &UnqualifiedSourceType,
3302 QualType UnqualifiedTargetType,
3303 InitializationSequence &Sequence) {
3304 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3305 S.Context.OverloadTy) {
3306 DeclAccessPair Found;
3307 bool HadMultipleCandidates = false;
3308 if (FunctionDecl *Fn
3309 = S.ResolveAddressOfOverloadedFunction(Initializer,
3310 UnqualifiedTargetType,
3311 false, Found,
3312 &HadMultipleCandidates)) {
3313 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3314 HadMultipleCandidates);
3315 SourceType = Fn->getType();
3316 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3317 } else if (!UnqualifiedTargetType->isRecordType()) {
3318 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3319 return true;
3320 }
3321 }
3322 return false;
3323}
3324
3325static void TryReferenceInitializationCore(Sema &S,
3326 const InitializedEntity &Entity,
3327 const InitializationKind &Kind,
3328 Expr *Initializer,
3329 QualType cv1T1, QualType T1,
3330 Qualifiers T1Quals,
3331 QualType cv2T2, QualType T2,
3332 Qualifiers T2Quals,
3333 InitializationSequence &Sequence);
3334
Richard Smithd86812d2012-07-05 08:39:21 +00003335static void TryValueInitialization(Sema &S,
3336 const InitializedEntity &Entity,
3337 const InitializationKind &Kind,
3338 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00003339 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00003340
Sebastian Redl29526f02011-11-27 16:50:07 +00003341/// \brief Attempt list initialization of a reference.
3342static void TryReferenceListInitialization(Sema &S,
3343 const InitializedEntity &Entity,
3344 const InitializationKind &Kind,
3345 InitListExpr *InitList,
Richard Smithfaadef72013-06-08 00:02:08 +00003346 InitializationSequence &Sequence) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003347 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003348 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003349 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3350 return;
3351 }
3352
3353 QualType DestType = Entity.getType();
3354 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3355 Qualifiers T1Quals;
3356 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3357
3358 // Reference initialization via an initializer list works thus:
3359 // If the initializer list consists of a single element that is
3360 // reference-related to the referenced type, bind directly to that element
3361 // (possibly creating temporaries).
3362 // Otherwise, initialize a temporary with the initializer list and
3363 // bind to that.
3364 if (InitList->getNumInits() == 1) {
3365 Expr *Initializer = InitList->getInit(0);
3366 QualType cv2T2 = Initializer->getType();
3367 Qualifiers T2Quals;
3368 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3369
3370 // If this fails, creating a temporary wouldn't work either.
3371 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3372 T1, Sequence))
3373 return;
3374
3375 SourceLocation DeclLoc = Initializer->getLocStart();
3376 bool dummy1, dummy2, dummy3;
3377 Sema::ReferenceCompareResult RefRelationship
3378 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3379 dummy2, dummy3);
3380 if (RefRelationship >= Sema::Ref_Related) {
3381 // Try to bind the reference here.
3382 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3383 T1Quals, cv2T2, T2, T2Quals, Sequence);
3384 if (Sequence)
3385 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3386 return;
3387 }
Richard Smith03d93932013-01-15 07:58:29 +00003388
3389 // Update the initializer if we've resolved an overloaded function.
3390 if (Sequence.step_begin() != Sequence.step_end())
3391 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00003392 }
3393
3394 // Not reference-related. Create a temporary and bind to that.
3395 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3396
3397 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3398 if (Sequence) {
3399 if (DestType->isRValueReferenceType() ||
3400 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3401 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3402 else
3403 Sequence.SetFailed(
3404 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3405 }
3406}
3407
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003408/// \brief Attempt list initialization (C++0x [dcl.init.list])
3409static void TryListInitialization(Sema &S,
3410 const InitializedEntity &Entity,
3411 const InitializationKind &Kind,
3412 InitListExpr *InitList,
3413 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003414 QualType DestType = Entity.getType();
3415
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003416 // C++ doesn't allow scalar initialization with more than one argument.
3417 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003418 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003419 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3420 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3421 return;
3422 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003423 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003424 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003425 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003426 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003427
Larisse Voufod2010992015-01-24 23:09:54 +00003428 if (DestType->isRecordType() &&
3429 S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
3430 Sequence.setIncompleteTypeFailure(DestType);
3431 return;
3432 }
Richard Smithd86812d2012-07-05 08:39:21 +00003433
Larisse Voufo19d08672015-01-27 18:47:05 +00003434 // C++11 [dcl.init.list]p3, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003435 // - If T is a class type and the initializer list has a single element of
3436 // type cv U, where U is T or a class derived from T, the object is
3437 // initialized from that element (by copy-initialization for
3438 // copy-list-initialization, or by direct-initialization for
3439 // direct-list-initialization).
3440 // - Otherwise, if T is a character array and the initializer list has a
3441 // single element that is an appropriately-typed string literal
3442 // (8.5.2 [dcl.init.string]), initialization is performed as described
3443 // in that section.
Larisse Voufo19d08672015-01-27 18:47:05 +00003444 // - Otherwise, if T is an aggregate, [...] (continue below).
3445 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
Larisse Voufod2010992015-01-24 23:09:54 +00003446 if (DestType->isRecordType()) {
3447 QualType InitType = InitList->getInit(0)->getType();
3448 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
3449 S.IsDerivedFrom(InitType, DestType)) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003450 Expr *InitAsExpr = InitList->getInit(0);
3451 TryConstructorInitialization(S, Entity, Kind, InitAsExpr, DestType,
3452 Sequence, /*InitListSyntax*/ false,
3453 /*IsInitListCopy*/ true);
Larisse Voufod2010992015-01-24 23:09:54 +00003454 return;
3455 }
3456 }
3457 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
3458 Expr *SubInit[1] = {InitList->getInit(0)};
3459 if (!isa<VariableArrayType>(DestAT) &&
3460 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
3461 InitializationKind SubKind =
3462 Kind.getKind() == InitializationKind::IK_DirectList
3463 ? InitializationKind::CreateDirect(Kind.getLocation(),
3464 InitList->getLBraceLoc(),
3465 InitList->getRBraceLoc())
3466 : Kind;
3467 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3468 /*TopLevelOfInitList*/ true);
3469
3470 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
3471 // the element is not an appropriately-typed string literal, in which
3472 // case we should proceed as in C++11 (below).
3473 if (Sequence) {
3474 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3475 return;
3476 }
3477 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003478 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003479 }
Larisse Voufod2010992015-01-24 23:09:54 +00003480
3481 // C++11 [dcl.init.list]p3:
3482 // - If T is an aggregate, aggregate initialization is performed.
3483 if (DestType->isRecordType() && !DestType->isAggregateType()) {
3484 if (S.getLangOpts().CPlusPlus11) {
3485 // - Otherwise, if the initializer list has no elements and T is a
3486 // class type with a default constructor, the object is
3487 // value-initialized.
3488 if (InitList->getNumInits() == 0) {
3489 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
3490 if (RD->hasDefaultConstructor()) {
3491 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3492 return;
3493 }
3494 }
3495
3496 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3497 // an initializer_list object constructed [...]
3498 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3499 return;
3500
3501 // - Otherwise, if T is a class type, constructors are considered.
3502 Expr *InitListAsExpr = InitList;
3503 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
3504 Sequence, /*InitListSyntax*/ true);
3505 } else
3506 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
3507 return;
3508 }
3509
Richard Smith089c3162013-09-21 21:55:46 +00003510 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
3511 InitList->getNumInits() == 1 &&
3512 InitList->getInit(0)->getType()->isRecordType()) {
3513 // - Otherwise, if the initializer list has a single element of type E
3514 // [...references are handled above...], the object or reference is
Larisse Voufod2010992015-01-24 23:09:54 +00003515 // initialized from that element (by copy-initialization for
3516 // copy-list-initialization, or by direct-initialization for
3517 // direct-list-initialization); if a narrowing conversion is required
3518 // to convert the element to T, the program is ill-formed.
3519 //
Richard Smith089c3162013-09-21 21:55:46 +00003520 // Per core-24034, this is direct-initialization if we were performing
3521 // direct-list-initialization and copy-initialization otherwise.
3522 // We can't use InitListChecker for this, because it always performs
3523 // copy-initialization. This only matters if we might use an 'explicit'
3524 // conversion operator, so we only need to handle the cases where the source
3525 // is of record type.
3526 InitializationKind SubKind =
3527 Kind.getKind() == InitializationKind::IK_DirectList
3528 ? InitializationKind::CreateDirect(Kind.getLocation(),
3529 InitList->getLBraceLoc(),
3530 InitList->getRBraceLoc())
3531 : Kind;
3532 Expr *SubInit[1] = { InitList->getInit(0) };
3533 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3534 /*TopLevelOfInitList*/true);
3535 if (Sequence)
3536 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3537 return;
3538 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003539
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003540 InitListChecker CheckInitList(S, Entity, InitList,
Richard Smithde229232013-06-06 11:41:05 +00003541 DestType, /*VerifyOnly=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003542 if (CheckInitList.HadError()) {
3543 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3544 return;
3545 }
3546
3547 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003548 Sequence.AddListInitializationStep(DestType);
3549}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003550
3551/// \brief Try a reference initialization that involves calling a conversion
3552/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003553static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3554 const InitializedEntity &Entity,
3555 const InitializationKind &Kind,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003556 Expr *Initializer,
3557 bool AllowRValues,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003558 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003559 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003560 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3561 QualType T1 = cv1T1.getUnqualifiedType();
3562 QualType cv2T2 = Initializer->getType();
3563 QualType T2 = cv2T2.getUnqualifiedType();
3564
3565 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003566 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003567 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003568 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003569 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003570 ObjCConversion,
3571 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003572 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003573 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003574 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003575 (void)ObjCLifetimeConversion;
3576
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003577 // Build the candidate set directly in the initialization sequence
3578 // structure, so that it will persist if we fail.
3579 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3580 CandidateSet.clear();
3581
3582 // Determine whether we are allowed to call explicit constructors or
3583 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003584 bool AllowExplicit = Kind.AllowExplicit();
Richard Smith6c6ddab2013-09-21 21:23:47 +00003585 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3586
Craig Topperc3ec1492014-05-26 06:22:03 +00003587 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003588 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3589 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003590 // The type we're converting to is a class type. Enumerate its constructors
3591 // to see if there is a suitable conversion.
3592 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003593
David Blaikieff7d47a2012-12-19 00:45:41 +00003594 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003595 // The container holding the constructors can under certain conditions
3596 // be changed while iterating (e.g. because of deserialization).
3597 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003598 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00003599 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003600 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3601 NamedDecl *D = *CI;
John McCalla0296f72010-03-19 07:35:19 +00003602 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3603
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003604 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003605 CXXConstructorDecl *Constructor = nullptr;
John McCalla0296f72010-03-19 07:35:19 +00003606 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003607 if (ConstructorTmpl)
3608 Constructor = cast<CXXConstructorDecl>(
3609 ConstructorTmpl->getTemplatedDecl());
3610 else
John McCalla0296f72010-03-19 07:35:19 +00003611 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003612
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003613 if (!Constructor->isInvalidDecl() &&
3614 Constructor->isConvertingConstructor(AllowExplicit)) {
3615 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003616 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003617 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003618 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003619 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003620 else
John McCalla0296f72010-03-19 07:35:19 +00003621 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003622 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003623 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003624 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003625 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003626 }
John McCall3696dcb2010-08-17 07:23:57 +00003627 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3628 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003629
Craig Topperc3ec1492014-05-26 06:22:03 +00003630 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003631 if ((T2RecordType = T2->getAs<RecordType>()) &&
3632 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003633 // The type we're converting from is a class type, enumerate its conversion
3634 // functions.
3635 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3636
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003637 std::pair<CXXRecordDecl::conversion_iterator,
3638 CXXRecordDecl::conversion_iterator>
3639 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3640 for (CXXRecordDecl::conversion_iterator
3641 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003642 NamedDecl *D = *I;
3643 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3644 if (isa<UsingShadowDecl>(D))
3645 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003646
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003647 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3648 CXXConversionDecl *Conv;
3649 if (ConvTemplate)
3650 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3651 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003652 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003653
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003654 // If the conversion function doesn't return a reference type,
3655 // it can't be considered for this conversion unless we're allowed to
3656 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003657 // FIXME: Do we need to make sure that we only consider conversion
3658 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003659 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00003660 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003661 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3662 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003663 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003664 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00003665 DestType, CandidateSet,
3666 /*AllowObjCConversionOnExplicit=*/
3667 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003668 else
John McCalla0296f72010-03-19 07:35:19 +00003669 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00003670 Initializer, DestType, CandidateSet,
3671 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003672 }
3673 }
3674 }
John McCall3696dcb2010-08-17 07:23:57 +00003675 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3676 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003677
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003678 SourceLocation DeclLoc = Initializer->getLocStart();
3679
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003680 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003681 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003682 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003683 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003684 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003685
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003686 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00003687 // This is the overload that will be used for this initialization step if we
3688 // use this initialization. Mark it as referenced.
3689 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00003690
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003691 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003692 if (isa<CXXConversionDecl>(Function))
Alp Toker314cc812014-01-25 16:55:45 +00003693 T2 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003694 else
3695 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003696
3697 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003698 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003699 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003700 T2.getNonLValueExprType(S.Context),
3701 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003702
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003703 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003704 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003705 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003706 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003707 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003708 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003709 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003710
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003711 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003712 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003713 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003714 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003715 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003716 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003717 NewDerivedToBase, NewObjCConversion,
3718 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003719 if (NewRefRelationship == Sema::Ref_Incompatible) {
3720 // If the type we've converted to is not reference-related to the
3721 // type we're looking for, then there is another conversion step
3722 // we need to perform to produce a temporary of the right type
3723 // that we'll be binding to.
3724 ImplicitConversionSequence ICS;
3725 ICS.setStandard();
3726 ICS.Standard = Best->FinalConversion;
3727 T2 = ICS.Standard.getToType(2);
3728 Sequence.AddConversionSequenceStep(ICS, T2);
3729 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003730 Sequence.AddDerivedToBaseCastStep(
3731 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003732 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003733 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003734 else if (NewObjCConversion)
3735 Sequence.AddObjCObjectConversionStep(
3736 S.Context.getQualifiedType(T1,
3737 T2.getNonReferenceType().getQualifiers()));
3738
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003739 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003740 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003741
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003742 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3743 return OR_Success;
3744}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003745
Richard Smithc620f552011-10-19 16:55:56 +00003746static void CheckCXX98CompatAccessibleCopy(Sema &S,
3747 const InitializedEntity &Entity,
3748 Expr *CurInitExpr);
3749
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003750/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3751static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003752 const InitializedEntity &Entity,
3753 const InitializationKind &Kind,
3754 Expr *Initializer,
3755 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003756 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003757 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003758 Qualifiers T1Quals;
3759 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003760 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003761 Qualifiers T2Quals;
3762 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003763
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003764 // If the initializer is the address of an overloaded function, try
3765 // to resolve the overloaded function. If all goes well, T2 is the
3766 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003767 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3768 T1, Sequence))
3769 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003770
Sebastian Redl29526f02011-11-27 16:50:07 +00003771 // Delegate everything else to a subfunction.
3772 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3773 T1Quals, cv2T2, T2, T2Quals, Sequence);
3774}
3775
Jordan Roseb1312a52013-04-11 00:58:58 +00003776/// Converts the target of reference initialization so that it has the
3777/// appropriate qualifiers and value kind.
3778///
3779/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3780/// \code
3781/// int x;
3782/// const int &r = x;
3783/// \endcode
3784///
3785/// In this case the reference is binding to a bitfield lvalue, which isn't
3786/// valid. Perform a load to create a lifetime-extended temporary instead.
3787/// \code
3788/// const int &r = someStruct.bitfield;
3789/// \endcode
3790static ExprValueKind
3791convertQualifiersAndValueKindIfNecessary(Sema &S,
3792 InitializationSequence &Sequence,
3793 Expr *Initializer,
3794 QualType cv1T1,
3795 Qualifiers T1Quals,
3796 Qualifiers T2Quals,
3797 bool IsLValueRef) {
John McCalld25db7e2013-05-06 21:39:12 +00003798 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Roseb1312a52013-04-11 00:58:58 +00003799 Initializer->refersToVectorElement();
3800
3801 if (IsNonAddressableType) {
3802 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3803 // lvalue reference to a non-volatile const type, or the reference shall be
3804 // an rvalue reference.
3805 //
3806 // If not, we can't make a temporary and bind to that. Give up and allow the
3807 // error to be diagnosed later.
3808 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3809 assert(Initializer->isGLValue());
3810 return Initializer->getValueKind();
3811 }
3812
3813 // Force a load so we can materialize a temporary.
3814 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3815 return VK_RValue;
3816 }
3817
3818 if (T1Quals != T2Quals) {
3819 Sequence.AddQualificationConversionStep(cv1T1,
3820 Initializer->getValueKind());
3821 }
3822
3823 return Initializer->getValueKind();
3824}
3825
3826
Sebastian Redl29526f02011-11-27 16:50:07 +00003827/// \brief Reference initialization without resolving overloaded functions.
3828static void TryReferenceInitializationCore(Sema &S,
3829 const InitializedEntity &Entity,
3830 const InitializationKind &Kind,
3831 Expr *Initializer,
3832 QualType cv1T1, QualType T1,
3833 Qualifiers T1Quals,
3834 QualType cv2T2, QualType T2,
3835 Qualifiers T2Quals,
3836 InitializationSequence &Sequence) {
3837 QualType DestType = Entity.getType();
3838 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003839 // Compute some basic properties of the types and the initializer.
3840 bool isLValueRef = DestType->isLValueReferenceType();
3841 bool isRValueRef = !isLValueRef;
3842 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003843 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003844 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003845 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003846 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003847 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003848 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003849
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003850 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003851 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003852 // "cv2 T2" as follows:
3853 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003854 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003855 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00003856 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00003857 // there are no function rvalues in C++, rvalue refs to functions are treated
3858 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003859 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003860 bool T1Function = T1->isFunctionType();
3861 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003862 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003863 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003864 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003865 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003866 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003867 // reference-compatible with "cv2 T2," or
3868 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003869 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003870 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003871 // can occur. However, we do pay attention to whether it is a bit-field
3872 // to decide whether we're actually binding to a temporary created from
3873 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003874 if (DerivedToBase)
3875 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003876 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003877 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003878 else if (ObjCConversion)
3879 Sequence.AddObjCObjectConversionStep(
3880 S.Context.getQualifiedType(T1, T2Quals));
3881
Jordan Roseb1312a52013-04-11 00:58:58 +00003882 ExprValueKind ValueKind =
3883 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3884 cv1T1, T1Quals, T2Quals,
3885 isLValueRef);
3886 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003887 return;
3888 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003889
3890 // - has a class type (i.e., T2 is a class type), where T1 is not
3891 // reference-related to T2, and can be implicitly converted to an
3892 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3893 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003894 // applicable conversion functions (13.3.1.6) and choosing the best
3895 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003896 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00003897 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00003898 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3899 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003900 ConvOvlResult = TryRefInitWithConversionFunction(
3901 S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003902 if (ConvOvlResult == OR_Success)
3903 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00003904 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00003905 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003906 InitializationSequence::FK_ReferenceInitOverloadFailed,
3907 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003908 }
3909 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003910
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003911 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003912 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003913 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003914 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003915 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3916 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3917 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003918 Sequence.SetOverloadFailure(
3919 InitializationSequence::FK_ReferenceInitOverloadFailed,
3920 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003921 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003922 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003923 ? (RefRelationship == Sema::Ref_Related
3924 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3925 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3926 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003927
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003928 return;
3929 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003930
Douglas Gregor92e460e2011-01-20 16:44:54 +00003931 // - If the initializer expression
3932 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3933 // "cv1 T1" is reference-compatible with "cv2 T2"
3934 // Note: functions are handled below.
3935 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003936 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003937 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003938 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003939 (InitCategory.isXValue() ||
3940 (InitCategory.isPRValue() && T2->isRecordType()) ||
3941 (InitCategory.isPRValue() && T2->isArrayType()))) {
3942 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3943 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003944 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3945 // compiler the freedom to perform a copy here or bind to the
3946 // object, while C++0x requires that we bind directly to the
3947 // object. Hence, we always bind to the object without making an
3948 // extra copy. However, in C++03 requires that we check for the
3949 // presence of a suitable copy constructor:
3950 //
3951 // The constructor that would be used to make the copy shall
3952 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003953 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003954 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003955 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00003956 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003957 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003958
Douglas Gregor92e460e2011-01-20 16:44:54 +00003959 if (DerivedToBase)
3960 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3961 ValueKind);
3962 else if (ObjCConversion)
3963 Sequence.AddObjCObjectConversionStep(
3964 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003965
Jordan Roseb1312a52013-04-11 00:58:58 +00003966 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3967 Initializer, cv1T1,
3968 T1Quals, T2Quals,
3969 isLValueRef);
3970
3971 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003972 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003973 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003974
3975 // - has a class type (i.e., T2 is a class type), where T1 is not
3976 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003977 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3978 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00003979 //
3980 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00003981 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003982 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003983 ConvOvlResult = TryRefInitWithConversionFunction(
3984 S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003985 if (ConvOvlResult)
3986 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003987 InitializationSequence::FK_ReferenceInitOverloadFailed,
3988 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003989
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003990 return;
3991 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003992
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00003993 if ((RefRelationship == Sema::Ref_Compatible ||
3994 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3995 isRValueRef && InitCategory.isLValue()) {
3996 Sequence.SetFailed(
3997 InitializationSequence::FK_RValueReferenceBindingToLValue);
3998 return;
3999 }
4000
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004001 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4002 return;
4003 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004004
4005 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004006 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00004007 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004008 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00004009
John McCallec6f4e92010-06-04 02:29:22 +00004010 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4011
Richard Smith2eabf782013-06-13 00:57:57 +00004012 // FIXME: Why do we use an implicit conversion here rather than trying
4013 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00004014 ImplicitConversionSequence ICS
4015 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00004016 /*SuppressUserConversions=*/false,
4017 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004018 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004019 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4020 /*AllowObjCWritebackConversion=*/false);
4021
4022 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004023 // FIXME: Use the conversion function set stored in ICS to turn
4024 // this into an overloading ambiguity diagnostic. However, we need
4025 // to keep that set as an OverloadCandidateSet rather than as some
4026 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004027 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4028 Sequence.SetOverloadFailure(
4029 InitializationSequence::FK_ReferenceInitOverloadFailed,
4030 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004031 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4032 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004033 else
4034 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004035 return;
John McCall31168b02011-06-15 23:02:42 +00004036 } else {
4037 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004038 }
4039
4040 // [...] If T1 is reference-related to T2, cv1 must be the
4041 // same cv-qualification as, or greater cv-qualification
4042 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004043 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4044 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004045 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00004046 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004047 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4048 return;
4049 }
4050
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004051 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004052 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004053 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004054 InitCategory.isLValue()) {
4055 Sequence.SetFailed(
4056 InitializationSequence::FK_RValueReferenceBindingToLValue);
4057 return;
4058 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004059
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004060 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4061 return;
4062}
4063
4064/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004065/// (C++ [dcl.init.string], C99 6.7.8).
4066static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004067 const InitializedEntity &Entity,
4068 const InitializationKind &Kind,
4069 Expr *Initializer,
4070 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004071 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004072}
4073
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004074/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004075static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004076 const InitializedEntity &Entity,
4077 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004078 InitializationSequence &Sequence,
4079 InitListExpr *InitList) {
4080 assert((!InitList || InitList->getNumInits() == 0) &&
4081 "Shouldn't use value-init for non-empty init lists");
4082
Richard Smith1bfe0682012-02-14 21:14:13 +00004083 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004084 //
4085 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004086 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004087
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004088 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004089 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004090
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004091 if (const RecordType *RT = T->getAs<RecordType>()) {
4092 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004093 bool NeedZeroInitialization = true;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004094 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithd86812d2012-07-05 08:39:21 +00004095 // C++98:
4096 // -- if T is a class type (clause 9) with a user-declared constructor
4097 // (12.1), then the default constructor for T is called (and the
4098 // initialization is ill-formed if T has no accessible default
4099 // constructor);
Richard Smith1bfe0682012-02-14 21:14:13 +00004100 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithd86812d2012-07-05 08:39:21 +00004101 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00004102 } else {
4103 // C++11:
4104 // -- if T is a class type (clause 9) with either no default constructor
4105 // (12.1 [class.ctor]) or a default constructor that is user-provided
4106 // or deleted, then the object is default-initialized;
4107 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4108 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithd86812d2012-07-05 08:39:21 +00004109 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00004110 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004111
Richard Smith1bfe0682012-02-14 21:14:13 +00004112 // -- if T is a (possibly cv-qualified) non-union class type without a
4113 // user-provided or deleted default constructor, then the object is
4114 // zero-initialized and, if T has a non-trivial default constructor,
4115 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004116 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4117 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004118 if (NeedZeroInitialization)
4119 Sequence.AddZeroInitializationStep(Entity.getType());
4120
Richard Smith593f9932012-12-08 02:01:17 +00004121 // C++03:
4122 // -- if T is a non-union class type without a user-declared constructor,
4123 // then every non-static data member and base class component of T is
4124 // value-initialized;
4125 // [...] A program that calls for [...] value-initialization of an
4126 // entity of reference type is ill-formed.
4127 //
4128 // C++11 doesn't need this handling, because value-initialization does not
4129 // occur recursively there, and the implicit default constructor is
4130 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004131 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004132 ClassDecl->hasUninitializedReferenceMember()) {
4133 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4134 return;
4135 }
4136
Richard Smithd86812d2012-07-05 08:39:21 +00004137 // If this is list-value-initialization, pass the empty init list on when
4138 // building the constructor call. This affects the semantics of a few
4139 // things (such as whether an explicit default constructor can be called).
4140 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004141 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004142 bool InitListSyntax = InitList;
4143
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004144 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4145 InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004146 }
4147 }
4148
Douglas Gregor1b303932009-12-22 15:35:07 +00004149 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004150}
4151
Douglas Gregor85dabae2009-12-16 01:38:02 +00004152/// \brief Attempt default initialization (C++ [dcl.init]p6).
4153static void TryDefaultInitialization(Sema &S,
4154 const InitializedEntity &Entity,
4155 const InitializationKind &Kind,
4156 InitializationSequence &Sequence) {
4157 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004158
Douglas Gregor85dabae2009-12-16 01:38:02 +00004159 // C++ [dcl.init]p6:
4160 // To default-initialize an object of type T means:
4161 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004162 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4163
Douglas Gregor85dabae2009-12-16 01:38:02 +00004164 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4165 // constructor for T is called (and the initialization is ill-formed if
4166 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004167 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004168 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004169 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004170 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004171
Douglas Gregor85dabae2009-12-16 01:38:02 +00004172 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004173
Douglas Gregor85dabae2009-12-16 01:38:02 +00004174 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004175 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004176 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004177 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004178 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004179 return;
4180 }
4181
4182 // If the destination type has a lifetime property, zero-initialize it.
4183 if (DestType.getQualifiers().hasObjCLifetime()) {
4184 Sequence.AddZeroInitializationStep(Entity.getType());
4185 return;
4186 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004187}
4188
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004189/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4190/// which enumerates all conversion functions and performs overload resolution
4191/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004192static void TryUserDefinedConversion(Sema &S,
Richard Smith77be48a2014-07-31 06:31:19 +00004193 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004194 const InitializationKind &Kind,
4195 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004196 InitializationSequence &Sequence,
4197 bool TopLevelOfInitList) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004198 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4199 QualType SourceType = Initializer->getType();
4200 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4201 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004202
Douglas Gregor540c3b02009-12-14 17:27:33 +00004203 // Build the candidate set directly in the initialization sequence
4204 // structure, so that it will persist if we fail.
4205 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4206 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004207
Douglas Gregor540c3b02009-12-14 17:27:33 +00004208 // Determine whether we are allowed to call explicit constructors or
4209 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004210 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004211
Douglas Gregor540c3b02009-12-14 17:27:33 +00004212 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4213 // The type we're converting to is a class type. Enumerate its constructors
4214 // to see if there is a suitable conversion.
4215 CXXRecordDecl *DestRecordDecl
4216 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004217
Douglas Gregord9848152010-04-26 14:36:57 +00004218 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004219 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004220 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie12be6392012-10-18 16:57:32 +00004221 // The container holding the constructors can under certain conditions
4222 // be changed while iterating. To be safe we copy the lookup results
4223 // to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004224 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004225 for (SmallVectorImpl<NamedDecl *>::iterator
David Blaikie12be6392012-10-18 16:57:32 +00004226 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregord9848152010-04-26 14:36:57 +00004227 Con != ConEnd; ++Con) {
4228 NamedDecl *D = *Con;
4229 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004230
Douglas Gregord9848152010-04-26 14:36:57 +00004231 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00004232 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregord9848152010-04-26 14:36:57 +00004233 FunctionTemplateDecl *ConstructorTmpl
4234 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004235 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00004236 Constructor = cast<CXXConstructorDecl>(
4237 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00004238 else
Douglas Gregord9848152010-04-26 14:36:57 +00004239 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004240
Douglas Gregord9848152010-04-26 14:36:57 +00004241 if (!Constructor->isInvalidDecl() &&
4242 Constructor->isConvertingConstructor(AllowExplicit)) {
4243 if (ConstructorTmpl)
4244 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004245 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004246 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004247 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004248 else
4249 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004250 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004251 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004252 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004253 }
Douglas Gregord9848152010-04-26 14:36:57 +00004254 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004255 }
Eli Friedman78275202009-12-19 08:11:05 +00004256
4257 SourceLocation DeclLoc = Initializer->getLocStart();
4258
Douglas Gregor540c3b02009-12-14 17:27:33 +00004259 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4260 // The type we're converting from is a class type, enumerate its conversion
4261 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004262
Eli Friedman4afe9a32009-12-20 22:12:03 +00004263 // We can only enumerate the conversion functions for a complete type; if
4264 // the type isn't complete, simply skip this step.
4265 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4266 CXXRecordDecl *SourceRecordDecl
4267 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004268
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004269 std::pair<CXXRecordDecl::conversion_iterator,
4270 CXXRecordDecl::conversion_iterator>
4271 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4272 for (CXXRecordDecl::conversion_iterator
4273 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004274 NamedDecl *D = *I;
4275 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4276 if (isa<UsingShadowDecl>(D))
4277 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004278
Eli Friedman4afe9a32009-12-20 22:12:03 +00004279 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4280 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004281 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004282 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004283 else
John McCallda4458e2010-03-31 01:36:47 +00004284 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004285
Eli Friedman4afe9a32009-12-20 22:12:03 +00004286 if (AllowExplicit || !Conv->isExplicit()) {
4287 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004288 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004289 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004290 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004291 else
John McCalla0296f72010-03-19 07:35:19 +00004292 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004293 Initializer, DestType, CandidateSet,
4294 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004295 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004296 }
4297 }
4298 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299
4300 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004301 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004302 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00004303 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004304 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004305 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004306 Result);
4307 return;
4308 }
John McCall0d1da222010-01-12 00:44:57 +00004309
Douglas Gregor540c3b02009-12-14 17:27:33 +00004310 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004311 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004312 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313
Douglas Gregor540c3b02009-12-14 17:27:33 +00004314 if (isa<CXXConstructorDecl>(Function)) {
4315 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004316 // subsumed by the initialization. Per DR5, the created temporary is of the
4317 // cv-unqualified type of the destination.
4318 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4319 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004320 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004321 return;
4322 }
4323
4324 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004325 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004326 if (ConvType->getAs<RecordType>()) {
Richard Smithb24f0672012-02-11 19:22:50 +00004327 // If we're converting to a class type, there may be an copy of
Douglas Gregor5ab11652010-04-17 22:01:05 +00004328 // the resulting temporary object (possible to create an object of
4329 // a base class type). That copy is not a separate conversion, so
4330 // we just make a note of the actual destination type (possibly a
4331 // base class of the type returned by the conversion function) and
4332 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004333 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4334 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004335 return;
4336 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004337
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004338 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4339 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004340
Douglas Gregor5ab11652010-04-17 22:01:05 +00004341 // If the conversion following the call to the conversion function
4342 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004343 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4344 Best->FinalConversion.Third) {
4345 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004346 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004347 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004348 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004349 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004350}
4351
Richard Smithf032001b2013-06-20 02:18:31 +00004352/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4353/// a function with a pointer return type contains a 'return false;' statement.
4354/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4355/// code using that header.
4356///
4357/// Work around this by treating 'return false;' as zero-initializing the result
4358/// if it's used in a pointer-returning function in a system header.
4359static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4360 const InitializedEntity &Entity,
4361 const Expr *Init) {
4362 return S.getLangOpts().CPlusPlus11 &&
4363 Entity.getKind() == InitializedEntity::EK_Result &&
4364 Entity.getType()->isPointerType() &&
4365 isa<CXXBoolLiteralExpr>(Init) &&
4366 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4367 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4368}
4369
John McCall31168b02011-06-15 23:02:42 +00004370/// The non-zero enum values here are indexes into diagnostic alternatives.
4371enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4372
4373/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00004374static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004375 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00004376 // Skip parens.
4377 e = e->IgnoreParens();
4378
4379 // Skip address-of nodes.
4380 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4381 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004382 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4383 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004384
4385 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00004386 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4387 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00004388 case CK_Dependent:
4389 case CK_BitCast:
4390 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00004391 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004392 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004393
4394 case CK_ArrayToPointerDecay:
4395 return IIK_nonscalar;
4396
4397 case CK_NullToPointer:
4398 return IIK_okay;
4399
4400 default:
4401 break;
4402 }
4403
4404 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00004405 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004406 // set isWeakAccess to true, to mean that there will be an implicit
4407 // load which requires a cleanup.
4408 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4409 isWeakAccess = true;
4410
John McCall63f84442011-06-27 23:59:58 +00004411 if (!isAddressOf) return IIK_nonlocal;
4412
John McCall113bee02012-03-10 09:33:50 +00004413 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4414 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00004415
4416 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00004417
4418 // If we have a conditional operator, check both sides.
4419 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004420 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4421 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00004422 return iik;
4423
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004424 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004425
4426 // These are never scalar.
4427 } else if (isa<ArraySubscriptExpr>(e)) {
4428 return IIK_nonscalar;
4429
4430 // Otherwise, it needs to be a null pointer constant.
4431 } else {
4432 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4433 ? IIK_okay : IIK_nonlocal);
4434 }
4435
4436 return IIK_nonlocal;
4437}
4438
4439/// Check whether the given expression is a valid operand for an
4440/// indirect copy/restore.
4441static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4442 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004443 bool isWeakAccess = false;
4444 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4445 // If isWeakAccess to true, there will be an implicit
4446 // load which requires a cleanup.
4447 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4448 S.ExprNeedsCleanups = true;
4449
John McCall31168b02011-06-15 23:02:42 +00004450 if (iik == IIK_okay) return;
4451
4452 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4453 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4454 << src->getSourceRange();
4455}
4456
Douglas Gregore2f943b2011-02-22 18:29:51 +00004457/// \brief Determine whether we have compatible array types for the
4458/// purposes of GNU by-copy array initialization.
Larisse Voufod2010992015-01-24 23:09:54 +00004459static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
Douglas Gregore2f943b2011-02-22 18:29:51 +00004460 const ArrayType *Source) {
4461 // If the source and destination array types are equivalent, we're
4462 // done.
4463 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4464 return true;
4465
4466 // Make sure that the element types are the same.
4467 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4468 return false;
4469
4470 // The only mismatch we allow is when the destination is an
4471 // incomplete array type and the source is a constant array type.
4472 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4473}
4474
John McCall31168b02011-06-15 23:02:42 +00004475static bool tryObjCWritebackConversion(Sema &S,
4476 InitializationSequence &Sequence,
4477 const InitializedEntity &Entity,
4478 Expr *Initializer) {
4479 bool ArrayDecay = false;
4480 QualType ArgType = Initializer->getType();
4481 QualType ArgPointee;
4482 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4483 ArrayDecay = true;
4484 ArgPointee = ArgArrayType->getElementType();
4485 ArgType = S.Context.getPointerType(ArgPointee);
4486 }
4487
4488 // Handle write-back conversion.
4489 QualType ConvertedArgType;
4490 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4491 ConvertedArgType))
4492 return false;
4493
4494 // We should copy unless we're passing to an argument explicitly
4495 // marked 'out'.
4496 bool ShouldCopy = true;
4497 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4498 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4499
4500 // Do we need an lvalue conversion?
4501 if (ArrayDecay || Initializer->isGLValue()) {
4502 ImplicitConversionSequence ICS;
4503 ICS.setStandard();
4504 ICS.Standard.setAsIdentityConversion();
4505
4506 QualType ResultType;
4507 if (ArrayDecay) {
4508 ICS.Standard.First = ICK_Array_To_Pointer;
4509 ResultType = S.Context.getPointerType(ArgPointee);
4510 } else {
4511 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4512 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4513 }
4514
4515 Sequence.AddConversionSequenceStep(ICS, ResultType);
4516 }
4517
4518 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4519 return true;
4520}
4521
Guy Benyei61054192013-02-07 10:55:47 +00004522static bool TryOCLSamplerInitialization(Sema &S,
4523 InitializationSequence &Sequence,
4524 QualType DestType,
4525 Expr *Initializer) {
4526 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4527 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4528 return false;
4529
4530 Sequence.AddOCLSamplerInitStep(DestType);
4531 return true;
4532}
4533
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004534//
4535// OpenCL 1.2 spec, s6.12.10
4536//
4537// The event argument can also be used to associate the
4538// async_work_group_copy with a previous async copy allowing
4539// an event to be shared by multiple async copies; otherwise
4540// event should be zero.
4541//
4542static bool TryOCLZeroEventInitialization(Sema &S,
4543 InitializationSequence &Sequence,
4544 QualType DestType,
4545 Expr *Initializer) {
4546 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4547 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4548 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4549 return false;
4550
4551 Sequence.AddOCLZeroEventStep(DestType);
4552 return true;
4553}
4554
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004555InitializationSequence::InitializationSequence(Sema &S,
4556 const InitializedEntity &Entity,
4557 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004558 MultiExprArg Args,
4559 bool TopLevelOfInitList)
Richard Smith100b24a2014-04-17 01:52:14 +00004560 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Richard Smith089c3162013-09-21 21:55:46 +00004561 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
4562}
4563
4564void InitializationSequence::InitializeFrom(Sema &S,
4565 const InitializedEntity &Entity,
4566 const InitializationKind &Kind,
4567 MultiExprArg Args,
4568 bool TopLevelOfInitList) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004569 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004570
John McCall5e77d762013-04-16 07:28:30 +00004571 // Eliminate non-overload placeholder types in the arguments. We
4572 // need to do this before checking whether types are dependent
4573 // because lowering a pseudo-object expression might well give us
4574 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004575 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00004576 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4577 // FIXME: should we be doing this here?
4578 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4579 if (result.isInvalid()) {
4580 SetFailed(FK_PlaceholderType);
4581 return;
4582 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004583 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00004584 }
4585
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004586 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004587 // The semantics of initializers are as follows. The destination type is
4588 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004589 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004590 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004591 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004592 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004593
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004594 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004595 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004596 SequenceKind = DependentSequence;
4597 return;
4598 }
4599
Sebastian Redld201edf2011-06-05 13:59:11 +00004600 // Almost everything is a normal sequence.
4601 setSequenceKind(NormalSequence);
4602
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004603 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00004604 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004605 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004606 Initializer = Args[0];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004607 if (S.getLangOpts().ObjC1) {
4608 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
4609 DestType, Initializer->getType(),
4610 Initializer) ||
4611 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
4612 Args[0] = Initializer;
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004613 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004614 if (!isa<InitListExpr>(Initializer))
4615 SourceType = Initializer->getType();
4616 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004617
Sebastian Redl0501c632012-02-12 16:37:36 +00004618 // - If the initializer is a (non-parenthesized) braced-init-list, the
4619 // object is list-initialized (8.5.4).
4620 if (Kind.getKind() != InitializationKind::IK_Direct) {
4621 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4622 TryListInitialization(S, Entity, Kind, InitList, *this);
4623 return;
4624 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004625 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004626
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004627 // - If the destination type is a reference type, see 8.5.3.
4628 if (DestType->isReferenceType()) {
4629 // C++0x [dcl.init.ref]p1:
4630 // A variable declared to be a T& or T&&, that is, "reference to type T"
4631 // (8.3.2), shall be initialized by an object, or function, of type T or
4632 // by an object that can be converted into a T.
4633 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004634 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004635 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004636 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004637 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004638 return;
4639 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004640
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004641 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004642 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004643 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004644 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004645 return;
4646 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004647
Douglas Gregor85dabae2009-12-16 01:38:02 +00004648 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004649 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004650 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004651 return;
4652 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004653
John McCall66884dd2011-02-21 07:22:22 +00004654 // - If the destination type is an array of characters, an array of
4655 // char16_t, an array of char32_t, or an array of wchar_t, and the
4656 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004657 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004658 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004659 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004660 if (Initializer && isa<VariableArrayType>(DestAT)) {
4661 SetFailed(FK_VariableLengthArrayHasInitializer);
4662 return;
4663 }
4664
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004665 if (Initializer) {
4666 switch (IsStringInit(Initializer, DestAT, Context)) {
4667 case SIF_None:
4668 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4669 return;
4670 case SIF_NarrowStringIntoWideChar:
4671 SetFailed(FK_NarrowStringIntoWideCharArray);
4672 return;
4673 case SIF_WideStringIntoChar:
4674 SetFailed(FK_WideStringIntoCharArray);
4675 return;
4676 case SIF_IncompatWideStringIntoWideChar:
4677 SetFailed(FK_IncompatWideStringIntoWideChar);
4678 return;
4679 case SIF_Other:
4680 break;
4681 }
John McCall66884dd2011-02-21 07:22:22 +00004682 }
4683
Douglas Gregore2f943b2011-02-22 18:29:51 +00004684 // Note: as an GNU C extension, we allow initialization of an
4685 // array from a compound literal that creates an array of the same
4686 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004687 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00004688 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4689 Initializer->getType()->isArrayType()) {
4690 const ArrayType *SourceAT
4691 = Context.getAsArrayType(Initializer->getType());
4692 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004693 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004694 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004695 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004696 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004697 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004698 }
Richard Smithebeed412012-02-15 22:38:09 +00004699 }
Richard Smithd86812d2012-07-05 08:39:21 +00004700 // Note: as a GNU C++ extension, we allow list-initialization of a
4701 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004702 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00004703 Entity.getKind() == InitializedEntity::EK_Member &&
4704 Initializer && isa<InitListExpr>(Initializer)) {
4705 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4706 *this);
4707 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004708 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004709 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004710 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4711 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004712 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004713 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004714
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004715 return;
4716 }
Eli Friedman78275202009-12-19 08:11:05 +00004717
Larisse Voufod2010992015-01-24 23:09:54 +00004718 // Determine whether we should consider writeback conversions for
John McCall31168b02011-06-15 23:02:42 +00004719 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004720 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004721 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00004722
4723 // We're at the end of the line for C: it's either a write-back conversion
4724 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004725 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004726 // If allowed, check whether this is an Objective-C writeback conversion.
4727 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004728 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004729 return;
4730 }
Guy Benyei61054192013-02-07 10:55:47 +00004731
4732 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4733 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004734
4735 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4736 return;
4737
John McCall31168b02011-06-15 23:02:42 +00004738 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004739 AddCAssignmentStep(DestType);
4740 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004741 return;
4742 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004743
David Blaikiebbafb8a2012-03-11 07:00:24 +00004744 assert(S.getLangOpts().CPlusPlus);
John McCall31168b02011-06-15 23:02:42 +00004745
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004746 // - If the destination type is a (possibly cv-qualified) class type:
4747 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004748 // - If the initialization is direct-initialization, or if it is
4749 // copy-initialization where the cv-unqualified version of the
4750 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004751 // class of the destination, constructors are considered. [...]
4752 if (Kind.getKind() == InitializationKind::IK_Direct ||
4753 (Kind.getKind() == InitializationKind::IK_Copy &&
4754 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4755 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004756 TryConstructorInitialization(S, Entity, Kind, Args,
Richard Smith77be48a2014-07-31 06:31:19 +00004757 DestType, *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004758 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004759 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004760 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004761 // used) to a derived class thereof are enumerated as described in
4762 // 13.3.1.4, and the best one is chosen through overload resolution
4763 // (13.3).
4764 else
Richard Smith77be48a2014-07-31 06:31:19 +00004765 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004766 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004767 return;
4768 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004769
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004770 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004771 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004772 return;
4773 }
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004774 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004775
4776 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004777 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004778 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith77be48a2014-07-31 06:31:19 +00004779 // For a conversion to _Atomic(T) from either T or a class type derived
4780 // from T, initialize the T object then convert to _Atomic type.
4781 bool NeedAtomicConversion = false;
4782 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
4783 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
4784 S.IsDerivedFrom(SourceType, Atomic->getValueType())) {
4785 DestType = Atomic->getValueType();
4786 NeedAtomicConversion = true;
4787 }
4788 }
4789
4790 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004791 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004792 MaybeProduceObjCObject(S, *this, Entity);
Richard Smith77be48a2014-07-31 06:31:19 +00004793 if (!Failed() && NeedAtomicConversion)
4794 AddAtomicConversionStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004795 return;
4796 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004797
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004798 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004799 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004800 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004801 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004802 // destination type; no user-defined conversions are considered.
Richard Smith77be48a2014-07-31 06:31:19 +00004803
John McCall31168b02011-06-15 23:02:42 +00004804 ImplicitConversionSequence ICS
Richard Smith77be48a2014-07-31 06:31:19 +00004805 = S.TryImplicitConversion(Initializer, DestType,
John McCall31168b02011-06-15 23:02:42 +00004806 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004807 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004808 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004809 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4810 allowObjCWritebackConversion);
Richard Smith77be48a2014-07-31 06:31:19 +00004811
4812 if (ICS.isStandard() &&
John McCall31168b02011-06-15 23:02:42 +00004813 ICS.Standard.Second == ICK_Writeback_Conversion) {
4814 // Objective-C ARC writeback conversion.
4815
4816 // We should copy unless we're passing to an argument explicitly
4817 // marked 'out'.
4818 bool ShouldCopy = true;
4819 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4820 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4821
4822 // If there was an lvalue adjustment, add it as a separate conversion.
4823 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4824 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4825 ImplicitConversionSequence LvalueICS;
4826 LvalueICS.setStandard();
4827 LvalueICS.Standard.setAsIdentityConversion();
4828 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4829 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004830 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004831 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004832
Richard Smith77be48a2014-07-31 06:31:19 +00004833 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004834 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004835 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00004836 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4837 AddZeroInitializationStep(Entity.getType());
4838 } else if (Initializer->getType() == Context.OverloadTy &&
4839 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4840 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004841 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004842 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004843 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004844 } else {
Richard Smith77be48a2014-07-31 06:31:19 +00004845 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00004846
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004847 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004848 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004849}
4850
4851InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004852 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004853 StepEnd = Steps.end();
4854 Step != StepEnd; ++Step)
4855 Step->Destroy();
4856}
4857
4858//===----------------------------------------------------------------------===//
4859// Perform initialization
4860//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004861static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004862getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004863 switch(Entity.getKind()) {
4864 case InitializedEntity::EK_Variable:
4865 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004866 case InitializedEntity::EK_Exception:
4867 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004868 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004869 return Sema::AA_Initializing;
4870
4871 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004872 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004873 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4874 return Sema::AA_Sending;
4875
Douglas Gregore1314a62009-12-18 05:02:21 +00004876 return Sema::AA_Passing;
4877
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004878 case InitializedEntity::EK_Parameter_CF_Audited:
4879 if (Entity.getDecl() &&
4880 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4881 return Sema::AA_Sending;
4882
4883 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4884
Douglas Gregore1314a62009-12-18 05:02:21 +00004885 case InitializedEntity::EK_Result:
4886 return Sema::AA_Returning;
4887
Douglas Gregore1314a62009-12-18 05:02:21 +00004888 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00004889 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004890 // FIXME: Can we tell apart casting vs. converting?
4891 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004892
Douglas Gregore1314a62009-12-18 05:02:21 +00004893 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004894 case InitializedEntity::EK_ArrayElement:
4895 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004896 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004897 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004898 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004899 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004900 return Sema::AA_Initializing;
4901 }
4902
David Blaikie8a40f702012-01-17 06:56:22 +00004903 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004904}
4905
Richard Smith27874d62013-01-08 00:08:23 +00004906/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00004907/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004908static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004909 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004910 case InitializedEntity::EK_ArrayElement:
4911 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004912 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004913 case InitializedEntity::EK_New:
4914 case InitializedEntity::EK_Variable:
4915 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004916 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004917 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004918 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004919 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004920 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004921 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004922 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004923 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004924
Douglas Gregore1314a62009-12-18 05:02:21 +00004925 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004926 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00004927 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004928 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004929 return true;
4930 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004931
Douglas Gregore1314a62009-12-18 05:02:21 +00004932 llvm_unreachable("missed an InitializedEntity kind?");
4933}
4934
Douglas Gregor95562572010-04-24 23:45:46 +00004935/// \brief Whether the given entity, when initialized with an object
4936/// created for that initialization, requires destruction.
4937static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4938 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00004939 case InitializedEntity::EK_Result:
4940 case InitializedEntity::EK_New:
4941 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004942 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004943 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004944 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004945 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004946 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00004947 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004948
Richard Smith27874d62013-01-08 00:08:23 +00004949 case InitializedEntity::EK_Member:
Douglas Gregor95562572010-04-24 23:45:46 +00004950 case InitializedEntity::EK_Variable:
4951 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004952 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00004953 case InitializedEntity::EK_Temporary:
4954 case InitializedEntity::EK_ArrayElement:
4955 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004956 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004957 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00004958 return true;
4959 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004960
4961 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004962}
4963
Richard Smithc620f552011-10-19 16:55:56 +00004964/// \brief Look for copy and move constructors and constructor templates, for
4965/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4966static void LookupCopyAndMoveConstructors(Sema &S,
4967 OverloadCandidateSet &CandidateSet,
4968 CXXRecordDecl *Class,
4969 Expr *CurInitExpr) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004970 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004971 // The container holding the constructors can under certain conditions
4972 // be changed while iterating (e.g. because of deserialization).
4973 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004974 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004975 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004976 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4977 NamedDecl *D = *CI;
Craig Topperc3ec1492014-05-26 06:22:03 +00004978 CXXConstructorDecl *Constructor = nullptr;
Richard Smithc620f552011-10-19 16:55:56 +00004979
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004980 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smithc620f552011-10-19 16:55:56 +00004981 // Handle copy/moveconstructors, only.
4982 if (!Constructor || Constructor->isInvalidDecl() ||
4983 !Constructor->isCopyOrMoveConstructor() ||
4984 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4985 continue;
4986
4987 DeclAccessPair FoundDecl
4988 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4989 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004990 CurInitExpr, CandidateSet);
Richard Smithc620f552011-10-19 16:55:56 +00004991 continue;
4992 }
4993
4994 // Handle constructor templates.
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004995 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smithc620f552011-10-19 16:55:56 +00004996 if (ConstructorTmpl->isInvalidDecl())
4997 continue;
4998
4999 Constructor = cast<CXXConstructorDecl>(
5000 ConstructorTmpl->getTemplatedDecl());
5001 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
5002 continue;
5003
5004 // FIXME: Do we need to limit this to copy-constructor-like
5005 // candidates?
5006 DeclAccessPair FoundDecl
5007 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
Craig Topperc3ec1492014-05-26 06:22:03 +00005008 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005009 CurInitExpr, CandidateSet, true);
Richard Smithc620f552011-10-19 16:55:56 +00005010 }
5011}
5012
5013/// \brief Get the location at which initialization diagnostics should appear.
5014static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5015 Expr *Initializer) {
5016 switch (Entity.getKind()) {
5017 case InitializedEntity::EK_Result:
5018 return Entity.getReturnLoc();
5019
5020 case InitializedEntity::EK_Exception:
5021 return Entity.getThrowLoc();
5022
5023 case InitializedEntity::EK_Variable:
5024 return Entity.getDecl()->getLocation();
5025
Douglas Gregor19666fb2012-02-15 16:57:26 +00005026 case InitializedEntity::EK_LambdaCapture:
5027 return Entity.getCaptureLoc();
5028
Richard Smithc620f552011-10-19 16:55:56 +00005029 case InitializedEntity::EK_ArrayElement:
5030 case InitializedEntity::EK_Member:
5031 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005032 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00005033 case InitializedEntity::EK_Temporary:
5034 case InitializedEntity::EK_New:
5035 case InitializedEntity::EK_Base:
5036 case InitializedEntity::EK_Delegating:
5037 case InitializedEntity::EK_VectorElement:
5038 case InitializedEntity::EK_ComplexElement:
5039 case InitializedEntity::EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005040 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005041 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00005042 return Initializer->getLocStart();
5043 }
5044 llvm_unreachable("missed an InitializedEntity kind?");
5045}
5046
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005047/// \brief Make a (potentially elidable) temporary copy of the object
5048/// provided by the given initializer by calling the appropriate copy
5049/// constructor.
5050///
5051/// \param S The Sema object used for type-checking.
5052///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005053/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005054/// the type of the initializer expression or a superclass thereof.
5055///
James Dennett634962f2012-06-14 21:40:34 +00005056/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005057///
5058/// \param CurInit The initializer expression.
5059///
5060/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5061/// is permitted in C++03 (but not C++0x) when binding a reference to
5062/// an rvalue.
5063///
5064/// \returns An expression that copies the initializer expression into
5065/// a temporary object, or an error expression if a copy could not be
5066/// created.
John McCalldadc5752010-08-24 06:29:42 +00005067static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005068 QualType T,
5069 const InitializedEntity &Entity,
5070 ExprResult CurInit,
5071 bool IsExtraneousCopy) {
Fariborz Jahanian36f7f132015-01-28 22:08:10 +00005072 if (CurInit.isInvalid())
5073 return CurInit;
Douglas Gregor5ab11652010-04-17 22:01:05 +00005074 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005075 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005076 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005077 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005078 Class = cast<CXXRecordDecl>(Record->getDecl());
5079 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005080 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005081
Douglas Gregor5d369002011-01-21 18:05:27 +00005082 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005083 // When certain criteria are met, an implementation is allowed to
5084 // omit the copy/move construction of a class object, even if the
5085 // copy/move constructor and/or destructor for the object have
5086 // side effects. [...]
5087 // - when a temporary class object that has not been bound to a
5088 // reference (12.2) would be copied/moved to a class object
5089 // with the same cv-unqualified type, the copy/move operation
5090 // can be omitted by constructing the temporary object
5091 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005092 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005093 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00005094 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005095 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00005096 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00005097 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00005098 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005099
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005100 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005101 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005102 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005103
Douglas Gregorf282a762011-01-21 19:38:21 +00005104 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00005105 // Only consider constructors and constructor templates. Per
5106 // C++0x [dcl.init]p16, second bullet to class types, this initialization
5107 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005108 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005109 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005110
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005111 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5112
Douglas Gregore1314a62009-12-18 05:02:21 +00005113 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00005114 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005115 case OR_Success:
5116 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005117
Douglas Gregore1314a62009-12-18 05:02:21 +00005118 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005119 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5120 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5121 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005122 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005123 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005124 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005125 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00005126 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005127 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005128
Douglas Gregore1314a62009-12-18 05:02:21 +00005129 case OR_Ambiguous:
5130 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005131 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005132 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005133 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00005134 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005135
Douglas Gregore1314a62009-12-18 05:02:21 +00005136 case OR_Deleted:
5137 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005138 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005139 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00005140 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00005141 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005142 }
5143
Douglas Gregor5ab11652010-04-17 22:01:05 +00005144 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00005145 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005146 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005147
Anders Carlssona01874b2010-04-21 18:47:17 +00005148 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005149 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005150
5151 if (IsExtraneousCopy) {
5152 // If this is a totally extraneous copy for C++03 reference
5153 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005154 // expression. We don't generate an (elided) copy operation here
5155 // because doing so would require us to pass down a flag to avoid
5156 // infinite recursion, where each step adds another extraneous,
5157 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005158
Douglas Gregor30b52772010-04-18 07:57:34 +00005159 // Instantiate the default arguments of any extra parameters in
5160 // the selected copy constructor, as if we were going to create a
5161 // proper call to the copy constructor.
5162 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5163 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5164 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005165 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005166 break;
5167
5168 // Build the default argument expression; we don't actually care
5169 // if this succeeds or not, because this routine will complain
5170 // if there was a problem.
5171 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5172 }
5173
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005174 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005175 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005176
Douglas Gregor5ab11652010-04-17 22:01:05 +00005177 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005178 // constructor call (we might have derived-to-base conversions, or
5179 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005180 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005181 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005182
Douglas Gregord0ace022010-04-25 00:55:24 +00005183 // Actually perform the constructor call.
5184 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005185 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005186 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005187 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005188 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005189 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005190 CXXConstructExpr::CK_Complete,
5191 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005192
Douglas Gregord0ace022010-04-25 00:55:24 +00005193 // If we're supposed to bind temporaries, do so.
5194 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005195 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005196 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005197}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005198
Richard Smithc620f552011-10-19 16:55:56 +00005199/// \brief Check whether elidable copy construction for binding a reference to
5200/// a temporary would have succeeded if we were building in C++98 mode, for
5201/// -Wc++98-compat.
5202static void CheckCXX98CompatAccessibleCopy(Sema &S,
5203 const InitializedEntity &Entity,
5204 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005205 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005206
5207 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5208 if (!Record)
5209 return;
5210
5211 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005212 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00005213 return;
5214
5215 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00005216 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005217 LookupCopyAndMoveConstructors(
5218 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5219
5220 // Perform overload resolution.
5221 OverloadCandidateSet::iterator Best;
5222 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5223
5224 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5225 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5226 << CurInitExpr->getSourceRange();
5227
5228 switch (OR) {
5229 case OR_Success:
5230 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCall5dadb652012-04-07 03:04:20 +00005231 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005232 // FIXME: Check default arguments as far as that's possible.
5233 break;
5234
5235 case OR_No_Viable_Function:
5236 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005237 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005238 break;
5239
5240 case OR_Ambiguous:
5241 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005242 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005243 break;
5244
5245 case OR_Deleted:
5246 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005247 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005248 break;
5249 }
5250}
5251
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005252void InitializationSequence::PrintInitLocationNote(Sema &S,
5253 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005254 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005255 if (Entity.getDecl()->getLocation().isInvalid())
5256 return;
5257
5258 if (Entity.getDecl()->getDeclName())
5259 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5260 << Entity.getDecl()->getDeclName();
5261 else
5262 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5263 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005264 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5265 Entity.getMethodDecl())
5266 S.Diag(Entity.getMethodDecl()->getLocation(),
5267 diag::note_method_return_type_change)
5268 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005269}
5270
Sebastian Redl112aa822011-07-14 19:07:55 +00005271static bool isReferenceBinding(const InitializationSequence::Step &s) {
5272 return s.Kind == InitializationSequence::SK_BindReference ||
5273 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5274}
5275
Jordan Rose6c0505e2013-05-06 16:48:12 +00005276/// Returns true if the parameters describe a constructor initialization of
5277/// an explicit temporary object, e.g. "Point(x, y)".
5278static bool isExplicitTemporary(const InitializedEntity &Entity,
5279 const InitializationKind &Kind,
5280 unsigned NumArgs) {
5281 switch (Entity.getKind()) {
5282 case InitializedEntity::EK_Temporary:
5283 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005284 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005285 break;
5286 default:
5287 return false;
5288 }
5289
5290 switch (Kind.getKind()) {
5291 case InitializationKind::IK_DirectList:
5292 return true;
5293 // FIXME: Hack to work around cast weirdness.
5294 case InitializationKind::IK_Direct:
5295 case InitializationKind::IK_Value:
5296 return NumArgs != 1;
5297 default:
5298 return false;
5299 }
5300}
5301
Sebastian Redled2e5322011-12-22 14:44:04 +00005302static ExprResult
5303PerformConstructorInitialization(Sema &S,
5304 const InitializedEntity &Entity,
5305 const InitializationKind &Kind,
5306 MultiExprArg Args,
5307 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00005308 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005309 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005310 bool IsStdInitListInitialization,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005311 SourceLocation LBraceLoc,
5312 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005313 unsigned NumArgs = Args.size();
5314 CXXConstructorDecl *Constructor
5315 = cast<CXXConstructorDecl>(Step.Function.Function);
5316 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5317
5318 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005319 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00005320 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5321 ? Kind.getEqualLoc()
5322 : Kind.getLocation();
5323
5324 if (Kind.getKind() == InitializationKind::IK_Default) {
5325 // Force even a trivial, implicit default constructor to be
5326 // semantically checked. We do this explicitly because we don't build
5327 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00005328 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00005329 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00005330 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00005331 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5332 }
5333
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005334 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00005335
Douglas Gregor6073dca2012-02-24 23:56:31 +00005336 // C++ [over.match.copy]p1:
5337 // - When initializing a temporary to be bound to the first parameter
5338 // of a constructor that takes a reference to possibly cv-qualified
5339 // T as its first argument, called with a single argument in the
5340 // context of direct-initialization, explicit conversion functions
5341 // are also considered.
5342 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5343 Args.size() == 1 &&
5344 Constructor->isCopyOrMoveConstructor();
5345
Sebastian Redled2e5322011-12-22 14:44:04 +00005346 // Determine the arguments required to actually perform the constructor
5347 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005348 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005349 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00005350 AllowExplicitConv,
5351 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00005352 return ExprError();
5353
5354
Jordan Rose6c0505e2013-05-06 16:48:12 +00005355 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005356 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedmanfa0df832012-02-02 03:46:19 +00005357 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith22262ab2013-05-04 06:44:46 +00005358 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5359 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005360
5361 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5362 if (!TSInfo)
5363 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005364 SourceRange ParenOrBraceRange =
5365 (Kind.getKind() == InitializationKind::IK_DirectList)
5366 ? SourceRange(LBraceLoc, RBraceLoc)
5367 : Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005368
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005369 CurInit = new (S.Context) CXXTemporaryObjectExpr(
5370 S.Context, Constructor, TSInfo, ConstructorArgs, ParenOrBraceRange,
5371 HadMultipleCandidates, IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005372 IsStdInitListInitialization, ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00005373 } else {
5374 CXXConstructExpr::ConstructionKind ConstructKind =
5375 CXXConstructExpr::CK_Complete;
5376
5377 if (Entity.getKind() == InitializedEntity::EK_Base) {
5378 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5379 CXXConstructExpr::CK_VirtualBase :
5380 CXXConstructExpr::CK_NonVirtualBase;
5381 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5382 ConstructKind = CXXConstructExpr::CK_Delegating;
5383 }
5384
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005385 // Only get the parenthesis or brace range if it is a list initialization or
5386 // direct construction.
5387 SourceRange ParenOrBraceRange;
5388 if (IsListInitialization)
5389 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
5390 else if (Kind.getKind() == InitializationKind::IK_Direct)
5391 ParenOrBraceRange = Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005392
5393 // If the entity allows NRVO, mark the construction as elidable
5394 // unconditionally.
5395 if (Entity.allowsNRVO())
5396 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5397 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005398 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005399 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005400 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005401 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005402 ConstructorInitRequiresZeroInit,
5403 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005404 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005405 else
5406 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5407 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005408 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005409 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005410 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005411 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005412 ConstructorInitRequiresZeroInit,
5413 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005414 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005415 }
5416 if (CurInit.isInvalid())
5417 return ExprError();
5418
5419 // Only check access if all of that succeeded.
5420 S.CheckConstructorAccess(Loc, Constructor, Entity,
5421 Step.Function.FoundDecl.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005422 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5423 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005424
5425 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005426 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00005427
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005428 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00005429}
5430
Richard Smitheb3cad52012-06-04 22:27:30 +00005431/// Determine whether the specified InitializedEntity definitely has a lifetime
5432/// longer than the current full-expression. Conservatively returns false if
5433/// it's unclear.
5434static bool
5435InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5436 const InitializedEntity *Top = &Entity;
5437 while (Top->getParent())
5438 Top = Top->getParent();
5439
5440 switch (Top->getKind()) {
5441 case InitializedEntity::EK_Variable:
5442 case InitializedEntity::EK_Result:
5443 case InitializedEntity::EK_Exception:
5444 case InitializedEntity::EK_Member:
5445 case InitializedEntity::EK_New:
5446 case InitializedEntity::EK_Base:
5447 case InitializedEntity::EK_Delegating:
5448 return true;
5449
5450 case InitializedEntity::EK_ArrayElement:
5451 case InitializedEntity::EK_VectorElement:
5452 case InitializedEntity::EK_BlockElement:
5453 case InitializedEntity::EK_ComplexElement:
5454 // Could not determine what the full initialization is. Assume it might not
5455 // outlive the full-expression.
5456 return false;
5457
5458 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005459 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00005460 case InitializedEntity::EK_Temporary:
5461 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005462 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005463 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00005464 // The entity being initialized might not outlive the full-expression.
5465 return false;
5466 }
5467
5468 llvm_unreachable("unknown entity kind");
5469}
5470
Richard Smithe6c01442013-06-05 00:46:14 +00005471/// Determine the declaration which an initialized entity ultimately refers to,
5472/// for the purpose of lifetime-extending a temporary bound to a reference in
5473/// the initialization of \p Entity.
David Majnemerdaff3702014-05-01 17:50:17 +00005474static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
5475 const InitializedEntity *Entity,
Craig Topperc3ec1492014-05-26 06:22:03 +00005476 const InitializedEntity *FallbackDecl = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00005477 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00005478 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005479 case InitializedEntity::EK_Variable:
5480 // The temporary [...] persists for the lifetime of the reference
David Majnemerdaff3702014-05-01 17:50:17 +00005481 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005482
5483 case InitializedEntity::EK_Member:
5484 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005485 if (Entity->getParent())
5486 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5487 Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00005488
5489 // except:
5490 // -- A temporary bound to a reference member in a constructor's
5491 // ctor-initializer persists until the constructor exits.
David Majnemerdaff3702014-05-01 17:50:17 +00005492 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005493
5494 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005495 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00005496 // -- A temporary bound to a reference parameter in a function call
5497 // persists until the completion of the full-expression containing
5498 // the call.
5499 case InitializedEntity::EK_Result:
5500 // -- The lifetime of a temporary bound to the returned value in a
5501 // function return statement is not extended; the temporary is
5502 // destroyed at the end of the full-expression in the return statement.
5503 case InitializedEntity::EK_New:
5504 // -- A temporary bound to a reference in a new-initializer persists
5505 // until the completion of the full-expression containing the
5506 // new-initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005507 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005508
5509 case InitializedEntity::EK_Temporary:
5510 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005511 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00005512 // We don't yet know the storage duration of the surrounding temporary.
5513 // Assume it's got full-expression duration for now, it will patch up our
5514 // storage duration if that's not correct.
David Majnemerdaff3702014-05-01 17:50:17 +00005515 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005516
5517 case InitializedEntity::EK_ArrayElement:
5518 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005519 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5520 FallbackDecl);
Richard Smithe6c01442013-06-05 00:46:14 +00005521
5522 case InitializedEntity::EK_Base:
5523 case InitializedEntity::EK_Delegating:
5524 // We can reach this case for aggregate initialization in a constructor:
5525 // struct A { int &&r; };
5526 // struct B : A { B() : A{0} {} };
5527 // In this case, use the innermost field decl as the context.
5528 return FallbackDecl;
5529
5530 case InitializedEntity::EK_BlockElement:
5531 case InitializedEntity::EK_LambdaCapture:
5532 case InitializedEntity::EK_Exception:
5533 case InitializedEntity::EK_VectorElement:
5534 case InitializedEntity::EK_ComplexElement:
David Majnemerdaff3702014-05-01 17:50:17 +00005535 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005536 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00005537 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00005538}
5539
David Majnemerdaff3702014-05-01 17:50:17 +00005540static void performLifetimeExtension(Expr *Init,
5541 const InitializedEntity *ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005542
5543/// Update a glvalue expression that is used as the initializer of a reference
5544/// to note that its lifetime is extended.
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005545/// \return \c true if any temporary had its lifetime extended.
David Majnemerdaff3702014-05-01 17:50:17 +00005546static bool
5547performReferenceExtension(Expr *Init,
5548 const InitializedEntity *ExtendingEntity) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005549 // Walk past any constructs which we can lifetime-extend across.
5550 Expr *Old;
5551 do {
5552 Old = Init;
5553
Richard Smithdbc82492015-01-10 01:28:13 +00005554 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5555 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5556 // This is just redundant braces around an initializer. Step over it.
5557 Init = ILE->getInit(0);
5558 }
5559 }
5560
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005561 // Step over any subobject adjustments; we may have a materialized
5562 // temporary inside them.
5563 SmallVector<const Expr *, 2> CommaLHSs;
5564 SmallVector<SubobjectAdjustment, 2> Adjustments;
5565 Init = const_cast<Expr *>(
5566 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5567
5568 // Per current approach for DR1376, look through casts to reference type
5569 // when performing lifetime extension.
5570 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5571 if (CE->getSubExpr()->isGLValue())
5572 Init = CE->getSubExpr();
5573
5574 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5575 // It's unclear if binding a reference to that xvalue extends the array
5576 // temporary.
5577 } while (Init != Old);
5578
Richard Smithe6c01442013-06-05 00:46:14 +00005579 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5580 // Update the storage duration of the materialized temporary.
5581 // FIXME: Rebuild the expression instead of mutating it.
David Majnemerdaff3702014-05-01 17:50:17 +00005582 ME->setExtendingDecl(ExtendingEntity->getDecl(),
5583 ExtendingEntity->allocateManglingNumber());
5584 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005585 return true;
Richard Smithe6c01442013-06-05 00:46:14 +00005586 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005587
5588 return false;
Richard Smithe6c01442013-06-05 00:46:14 +00005589}
5590
5591/// Update a prvalue expression that is going to be materialized as a
5592/// lifetime-extended temporary.
David Majnemerdaff3702014-05-01 17:50:17 +00005593static void performLifetimeExtension(Expr *Init,
5594 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00005595 // Dig out the expression which constructs the extended temporary.
5596 SmallVector<const Expr *, 2> CommaLHSs;
5597 SmallVector<SubobjectAdjustment, 2> Adjustments;
5598 Init = const_cast<Expr *>(
5599 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5600
Richard Smith736a9472013-06-12 20:42:33 +00005601 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5602 Init = BTE->getSubExpr();
5603
Richard Smithcc1b96d2013-06-12 22:31:48 +00005604 if (CXXStdInitializerListExpr *ILE =
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005605 dyn_cast<CXXStdInitializerListExpr>(Init)) {
David Majnemerdaff3702014-05-01 17:50:17 +00005606 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005607 return;
5608 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00005609
Richard Smithe6c01442013-06-05 00:46:14 +00005610 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00005611 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005612 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
David Majnemerdaff3702014-05-01 17:50:17 +00005613 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005614 return;
5615 }
5616
Richard Smithcc1b96d2013-06-12 22:31:48 +00005617 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005618 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5619
5620 // If we lifetime-extend a braced initializer which is initializing an
5621 // aggregate, and that aggregate contains reference members which are
5622 // bound to temporaries, those temporaries are also lifetime-extended.
5623 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5624 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005625 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005626 else {
5627 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005628 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00005629 if (Index >= ILE->getNumInits())
5630 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005631 if (I->isUnnamedBitfield())
5632 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00005633 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00005634 if (I->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005635 performReferenceExtension(SubInit, ExtendingEntity);
Richard Smith8d7f11d2013-06-27 22:54:33 +00005636 else if (isa<InitListExpr>(SubInit) ||
5637 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smithe6c01442013-06-05 00:46:14 +00005638 // This may be either aggregate-initialization of a member or
5639 // initialization of a std::initializer_list object. Either way,
5640 // we should recursively lifetime-extend that initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005641 performLifetimeExtension(SubInit, ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005642 ++Index;
5643 }
5644 }
5645 }
5646 }
5647}
5648
Richard Smithcc1b96d2013-06-12 22:31:48 +00005649static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5650 const Expr *Init, bool IsInitializerList,
5651 const ValueDecl *ExtendingDecl) {
5652 // Warn if a field lifetime-extends a temporary.
5653 if (isa<FieldDecl>(ExtendingDecl)) {
5654 if (IsInitializerList) {
5655 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5656 << /*at end of constructor*/true;
5657 return;
5658 }
5659
5660 bool IsSubobjectMember = false;
5661 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5662 Ent = Ent->getParent()) {
5663 if (Ent->getKind() != InitializedEntity::EK_Base) {
5664 IsSubobjectMember = true;
5665 break;
5666 }
5667 }
5668 S.Diag(Init->getExprLoc(),
5669 diag::warn_bind_ref_member_to_temporary)
5670 << ExtendingDecl << Init->getSourceRange()
5671 << IsSubobjectMember << IsInitializerList;
5672 if (IsSubobjectMember)
5673 S.Diag(ExtendingDecl->getLocation(),
5674 diag::note_ref_subobject_of_member_declared_here);
5675 else
5676 S.Diag(ExtendingDecl->getLocation(),
5677 diag::note_ref_or_ptr_member_declared_here)
5678 << /*is pointer*/false;
5679 }
5680}
5681
Richard Smithaaa0ec42013-09-21 21:19:19 +00005682static void DiagnoseNarrowingInInitList(Sema &S,
5683 const ImplicitConversionSequence &ICS,
5684 QualType PreNarrowingType,
5685 QualType EntityType,
5686 const Expr *PostInit);
5687
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005688ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005689InitializationSequence::Perform(Sema &S,
5690 const InitializedEntity &Entity,
5691 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00005692 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005693 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005694 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005695 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00005696 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005697 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005698
Sebastian Redld201edf2011-06-05 13:59:11 +00005699 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005700 // If the declaration is a non-dependent, incomplete array type
5701 // that has an initializer, then its type will be completed once
5702 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00005703 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00005704 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00005705 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005706 if (const IncompleteArrayType *ArrayT
5707 = S.Context.getAsIncompleteArrayType(DeclType)) {
5708 // FIXME: We don't currently have the ability to accurately
5709 // compute the length of an initializer list without
5710 // performing full type-checking of the initializer list
5711 // (since we have to determine where braces are implicitly
5712 // introduced and such). So, we fall back to making the array
5713 // type a dependently-sized array type with no specified
5714 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005715 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005716 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00005717
Douglas Gregor51e77d52009-12-10 17:56:55 +00005718 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00005719 if (DeclaratorDecl *DD = Entity.getDecl()) {
5720 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5721 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00005722 if (IncompleteArrayTypeLoc ArrayLoc =
5723 TL.getAs<IncompleteArrayTypeLoc>())
5724 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00005725 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00005726 }
5727
5728 *ResultType
5729 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005730 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005731 ArrayT->getSizeModifier(),
5732 ArrayT->getIndexTypeCVRQualifiers(),
5733 Brackets);
5734 }
5735
5736 }
5737 }
Sebastian Redla9351792012-02-11 23:51:47 +00005738 if (Kind.getKind() == InitializationKind::IK_Direct &&
5739 !Kind.isExplicitCast()) {
5740 // Rebuild the ParenListExpr.
5741 SourceRange ParenRange = Kind.getParenRange();
5742 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005743 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00005744 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00005745 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00005746 Kind.isExplicitCast() ||
5747 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005748 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005749 }
5750
Sebastian Redld201edf2011-06-05 13:59:11 +00005751 // No steps means no initialization.
5752 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005753 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005754
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005755 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005756 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005757 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00005758 // Produce a C++98 compatibility warning if we are initializing a reference
5759 // from an initializer list. For parameters, we produce a better warning
5760 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005761 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00005762 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5763 << Init->getSourceRange();
5764 }
5765
Richard Smitheb3cad52012-06-04 22:27:30 +00005766 // Diagnose cases where we initialize a pointer to an array temporary, and the
5767 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005768 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00005769 Entity.getType()->isPointerType() &&
5770 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005771 Expr *Init = Args[0];
Richard Smitheb3cad52012-06-04 22:27:30 +00005772 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5773 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5774 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5775 << Init->getSourceRange();
5776 }
5777
Douglas Gregor1b303932009-12-22 15:35:07 +00005778 QualType DestType = Entity.getType().getNonReferenceType();
5779 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00005780 // the same as Entity.getDecl()->getType() in cases involving type merging,
5781 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00005782 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00005783 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00005784 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005785
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005786 ExprResult CurInit((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005787
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005788 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00005789 // grab the only argument out the Args and place it into the "current"
5790 // initializer.
5791 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005792 case SK_ResolveAddressOfOverloadedFunction:
5793 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005794 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005795 case SK_CastDerivedToBaseLValue:
5796 case SK_BindReference:
5797 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005798 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00005799 case SK_UserConversion:
5800 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005801 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005802 case SK_QualificationConversionRValue:
Richard Smith77be48a2014-07-31 06:31:19 +00005803 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00005804 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005805 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00005806 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00005807 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00005808 case SK_UnwrapInitList:
5809 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00005810 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00005811 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00005812 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00005813 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00005814 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00005815 case SK_PassByIndirectCopyRestore:
5816 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00005817 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005818 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00005819 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005820 case SK_OCLZeroEvent: {
Douglas Gregore1314a62009-12-18 05:02:21 +00005821 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005822 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00005823 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005824 break;
John McCall34376a62010-12-04 03:47:34 +00005825 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005826
Douglas Gregore1314a62009-12-18 05:02:21 +00005827 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00005828 case SK_ConstructorInitializationFromList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00005829 case SK_StdInitializerListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00005830 case SK_ZeroInitialization:
5831 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005832 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005833
5834 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005835 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005836 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005837 for (step_iterator Step = step_begin(), StepEnd = step_end();
5838 Step != StepEnd; ++Step) {
5839 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005840 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005841
John Wiegley01296292011-04-08 18:41:53 +00005842 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005843
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005844 switch (Step->Kind) {
5845 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005846 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005847 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00005848 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00005849 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5850 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005851 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00005852 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00005853 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005854 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005855
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005856 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005857 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005858 case SK_CastDerivedToBaseLValue: {
5859 // We have a derived-to-base cast that produces either an rvalue or an
5860 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005861
John McCallcf142162010-08-07 06:22:56 +00005862 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00005863
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005864 // Casts to inaccessible base classes are allowed with C-style casts.
5865 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5866 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00005867 CurInit.get()->getLocStart(),
5868 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00005869 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00005870 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005871
John McCall2536c6d2010-08-25 10:28:54 +00005872 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005873 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005874 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005875 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005876 VK_XValue :
5877 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005878 CurInit =
5879 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
5880 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005881 break;
5882 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005883
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005884 case SK_BindReference:
John McCalld25db7e2013-05-06 21:39:12 +00005885 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5886 if (CurInit.get()->refersToBitField()) {
5887 // We don't necessarily have an unambiguous source bit-field.
5888 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005889 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00005890 << Entity.getType().isVolatileQualified()
John McCalld25db7e2013-05-06 21:39:12 +00005891 << (BitField ? BitField->getDeclName() : DeclarationName())
Craig Topperc3ec1492014-05-26 06:22:03 +00005892 << (BitField != nullptr)
John Wiegley01296292011-04-08 18:41:53 +00005893 << CurInit.get()->getSourceRange();
John McCalld25db7e2013-05-06 21:39:12 +00005894 if (BitField)
5895 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5896
John McCallfaf5fb42010-08-26 23:41:50 +00005897 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005898 }
Anders Carlssona91be642010-01-29 02:47:33 +00005899
John Wiegley01296292011-04-08 18:41:53 +00005900 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00005901 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005902 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5903 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00005904 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005905 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005906 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005907 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005908
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005909 // Reference binding does not have any corresponding ASTs.
5910
5911 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005912 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005913 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005914
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005915 // Even though we didn't materialize a temporary, the binding may still
5916 // extend the lifetime of a temporary. This happens if we bind a reference
5917 // to the result of a cast to reference type.
David Majnemerdaff3702014-05-01 17:50:17 +00005918 if (const InitializedEntity *ExtendingEntity =
5919 getEntityForTemporaryLifetimeExtension(&Entity))
5920 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
5921 warnOnLifetimeExtension(S, Entity, CurInit.get(),
5922 /*IsInitializerList=*/false,
5923 ExtendingEntity->getDecl());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005924
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005925 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005926
Richard Smithe6c01442013-06-05 00:46:14 +00005927 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00005928 // Make sure the "temporary" is actually an rvalue.
5929 assert(CurInit.get()->isRValue() && "not a temporary");
5930
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005931 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005932 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005933 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005934
Douglas Gregorfe314812011-06-21 17:03:29 +00005935 // Materialize the temporary into memory.
Richard Smith736a9472013-06-12 20:42:33 +00005936 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Richard Smithe6c01442013-06-05 00:46:14 +00005937 Entity.getType().getNonReferenceType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00005938 Entity.getType()->isLValueReferenceType());
5939
5940 // Maybe lifetime-extend the temporary's subobjects to match the
5941 // entity's lifetime.
5942 if (const InitializedEntity *ExtendingEntity =
5943 getEntityForTemporaryLifetimeExtension(&Entity))
5944 if (performReferenceExtension(MTE, ExtendingEntity))
5945 warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false,
5946 ExtendingEntity->getDecl());
Douglas Gregor58df5092011-06-22 16:12:01 +00005947
5948 // If we're binding to an Objective-C object that has lifetime, we
Richard Smith736a9472013-06-12 20:42:33 +00005949 // need cleanups. Likewise if we're extending this temporary to automatic
5950 // storage duration -- we need to register its cleanup during the
5951 // full-expression's cleanups.
5952 if ((S.getLangOpts().ObjCAutoRefCount &&
5953 MTE->getType()->isObjCLifetimeType()) ||
5954 (MTE->getStorageDuration() == SD_Automatic &&
5955 MTE->getType().isDestructedType()))
Douglas Gregor58df5092011-06-22 16:12:01 +00005956 S.ExprNeedsCleanups = true;
Richard Smith736a9472013-06-12 20:42:33 +00005957
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005958 CurInit = MTE;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005959 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005960 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005961
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005962 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005963 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005964 /*IsExtraneousCopy=*/true);
5965 break;
5966
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005967 case SK_UserConversion: {
5968 // We have a user-defined conversion that invokes either a constructor
5969 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00005970 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00005971 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00005972 FunctionDecl *Fn = Step->Function.Function;
5973 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005974 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00005975 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00005976 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005977 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005978 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00005979 SourceLocation Loc = CurInit.get()->getLocStart();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005980 CurInit.get(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00005981
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005982 // Determine the arguments required to actually perform the constructor
5983 // call.
John Wiegley01296292011-04-08 18:41:53 +00005984 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005985 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00005986 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005987 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005988 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005989
Richard Smithb24f0672012-02-11 19:22:50 +00005990 // Build an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005991 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005992 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005993 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005994 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005995 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005996 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005997 CXXConstructExpr::CK_Complete,
5998 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005999 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006000 return ExprError();
John McCall760af172010-02-01 03:16:54 +00006001
Anders Carlssona01874b2010-04-21 18:47:17 +00006002 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00006003 FoundFn.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00006004 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6005 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006006
John McCalle3027922010-08-25 11:45:40 +00006007 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00006008 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
6009 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
6010 S.IsDerivedFrom(SourceType, Class))
6011 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006012
Douglas Gregor95562572010-04-24 23:45:46 +00006013 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006014 } else {
6015 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00006016 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00006017 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00006018 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00006019 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6020 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006021
6022 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006023 // derived-to-base conversion? I believe the answer is "no", because
6024 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00006025 ExprResult CurInitExprRes =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006026 S.PerformObjectArgumentInitialization(CurInit.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006027 /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006028 FoundFn, Conversion);
6029 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006030 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006031 CurInit = CurInitExprRes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006032
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006033 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006034 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
6035 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006036 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00006037 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006038
John McCalle3027922010-08-25 11:45:40 +00006039 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006040
Alp Toker314cc812014-01-25 16:55:45 +00006041 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006042 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006043
Sebastian Redl112aa822011-07-14 19:07:55 +00006044 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006045 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
6046
6047 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00006048 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00006049 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006050 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00006051 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00006052 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00006053 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00006054 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00006055 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6056 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00006057 }
6058 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006059
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006060 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6061 CastKind, CurInit.get(), nullptr,
6062 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006063 if (MaybeBindToTemp)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006064 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00006065 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006066 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006067 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006068 break;
6069 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006070
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006071 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006072 case SK_QualificationConversionXValue:
6073 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006074 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00006075 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006076 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006077 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006078 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006079 VK_XValue :
6080 VK_RValue);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006081 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006082 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006083 }
6084
Richard Smith77be48a2014-07-31 06:31:19 +00006085 case SK_AtomicConversion: {
6086 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
6087 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6088 CK_NonAtomicToAtomic, VK_RValue);
6089 break;
6090 }
6091
Jordan Roseb1312a52013-04-11 00:58:58 +00006092 case SK_LValueToRValue: {
6093 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006094 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
6095 CK_LValueToRValue, CurInit.get(),
6096 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00006097 break;
6098 }
6099
Richard Smithaaa0ec42013-09-21 21:19:19 +00006100 case SK_ConversionSequence:
6101 case SK_ConversionSequenceNoNarrowing: {
6102 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00006103 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
6104 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00006105 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00006106 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00006107 ExprResult CurInitExprRes =
6108 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00006109 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00006110 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006111 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006112 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00006113
6114 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
6115 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
6116 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
6117 CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006118 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00006119 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006120
Douglas Gregor51e77d52009-12-10 17:56:55 +00006121 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00006122 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006123 // If we're not initializing the top-level entity, we need to create an
6124 // InitializeTemporary entity for our target type.
6125 QualType Ty = Step->Type;
6126 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00006127 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00006128 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
6129 InitListChecker PerformInitList(S, InitEntity,
Richard Smithde229232013-06-06 11:41:05 +00006130 InitList, Ty, /*VerifyOnly=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006131 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00006132 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00006133
Richard Smithcc1b96d2013-06-12 22:31:48 +00006134 // Hack: We must update *ResultType if available in order to set the
6135 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
6136 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
6137 if (ResultType &&
6138 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00006139 if ((*ResultType)->isRValueReferenceType())
6140 Ty = S.Context.getRValueReferenceType(Ty);
6141 else if ((*ResultType)->isLValueReferenceType())
6142 Ty = S.Context.getLValueReferenceType(Ty,
6143 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
6144 *ResultType = Ty;
6145 }
6146
6147 InitListExpr *StructuredInitList =
6148 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006149 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00006150 CurInit = shouldBindAsTemporary(InitEntity)
6151 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006152 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006153 break;
6154 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006155
Richard Smith53324112014-07-16 21:33:43 +00006156 case SK_ConstructorInitializationFromList: {
Sebastian Redl5a41f682012-02-12 16:37:24 +00006157 // When an initializer list is passed for a parameter of type "reference
6158 // to object", we don't get an EK_Temporary entity, but instead an
6159 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00006160 // FIXME: This is a hack. What we really should do is create a user
6161 // conversion step for this case, but this makes it considerably more
6162 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00006163 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6164 Entity.getType().getNonReferenceType());
6165 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00006166 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006167 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00006168 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6169 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006170 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00006171 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6172 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006173 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006174 ConstructorInitRequiresZeroInit,
Richard Smith53324112014-07-16 21:33:43 +00006175 /*IsListInitialization*/true,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006176 /*IsStdInitListInit*/false,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006177 InitList->getLBraceLoc(),
6178 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00006179 break;
6180 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006181
Sebastian Redl29526f02011-11-27 16:50:07 +00006182 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006183 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00006184 break;
6185
6186 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006187 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00006188 InitListExpr *Syntactic = Step->WrappingSyntacticList;
6189 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00006190 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00006191 ILE->setSyntacticForm(Syntactic);
6192 ILE->setType(E->getType());
6193 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006194 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00006195 break;
6196 }
6197
Richard Smith53324112014-07-16 21:33:43 +00006198 case SK_ConstructorInitialization:
Richard Smithf8adcdc2014-07-17 05:12:35 +00006199 case SK_StdInitializerListConstructorCall: {
Sebastian Redl99f66162012-02-19 12:27:56 +00006200 // When an initializer list is passed for a parameter of type "reference
6201 // to object", we don't get an EK_Temporary entity, but instead an
6202 // EK_Parameter entity with reference type.
6203 // FIXME: This is a hack. What we really should do is create a user
6204 // conversion step for this case, but this makes it considerably more
6205 // complicated. For now, this will do.
6206 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6207 Entity.getType().getNonReferenceType());
6208 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf8adcdc2014-07-17 05:12:35 +00006209 bool IsStdInitListInit =
6210 Step->Kind == SK_StdInitializerListConstructorCall;
Richard Smith53324112014-07-16 21:33:43 +00006211 CurInit = PerformConstructorInitialization(
6212 S, UseTemporary ? TempEntity : Entity, Kind, Args, *Step,
6213 ConstructorInitRequiresZeroInit,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006214 /*IsListInitialization*/IsStdInitListInit,
6215 /*IsStdInitListInitialization*/IsStdInitListInit,
Richard Smith53324112014-07-16 21:33:43 +00006216 /*LBraceLoc*/SourceLocation(),
6217 /*RBraceLoc*/SourceLocation());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006218 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00006219 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006220
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006221 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006222 step_iterator NextStep = Step;
6223 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006224 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00006225 (NextStep->Kind == SK_ConstructorInitialization ||
Richard Smith53324112014-07-16 21:33:43 +00006226 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006227 // The need for zero-initialization is recorded directly into
6228 // the call to the object's constructor within the next step.
6229 ConstructorInitRequiresZeroInit = true;
6230 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006231 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006232 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00006233 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6234 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006235 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00006236 Kind.getRange().getBegin());
6237
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006238 CurInit = new (S.Context) CXXScalarValueInitExpr(
6239 TSInfo->getType().getNonLValueExprType(S.Context), TSInfo,
6240 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006241 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006242 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006243 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006244 break;
6245 }
Douglas Gregore1314a62009-12-18 05:02:21 +00006246
6247 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00006248 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006249 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00006250 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00006251 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6252 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00006253 if (Result.isInvalid())
6254 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006255 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00006256
6257 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006258 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00006259 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006260 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00006261 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00006262 == Sema::Compatible)
6263 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00006264 if (CurInitExprRes.isInvalid())
6265 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006266 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00006267
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006268 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00006269 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6270 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00006271 CurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00006272 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006273 &Complained)) {
6274 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00006275 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006276 } else if (Complained)
6277 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00006278 break;
6279 }
Eli Friedman78275202009-12-19 08:11:05 +00006280
6281 case SK_StringInit: {
6282 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00006283 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00006284 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00006285 break;
6286 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006287
6288 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006289 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00006290 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00006291 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006292 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006293
6294 case SK_ArrayInit:
6295 // Okay: we checked everything before creating this step. Note that
6296 // this is a GNU extension.
6297 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00006298 << Step->Type << CurInit.get()->getType()
6299 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00006300
6301 // If the destination type is an incomplete array type, update the
6302 // type accordingly.
6303 if (ResultType) {
6304 if (const IncompleteArrayType *IncompleteDest
6305 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6306 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00006307 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00006308 *ResultType = S.Context.getConstantArrayType(
6309 IncompleteDest->getElementType(),
6310 ConstantSource->getSize(),
6311 ArrayType::Normal, 0);
6312 }
6313 }
6314 }
John McCall31168b02011-06-15 23:02:42 +00006315 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006316
Richard Smithebeed412012-02-15 22:38:09 +00006317 case SK_ParenthesizedArrayInit:
6318 // Okay: we checked everything before creating this step. Note that
6319 // this is a GNU extension.
6320 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6321 << CurInit.get()->getSourceRange();
6322 break;
6323
John McCall31168b02011-06-15 23:02:42 +00006324 case SK_PassByIndirectCopyRestore:
6325 case SK_PassByIndirectRestore:
6326 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006327 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
6328 CurInit.get(), Step->Type,
6329 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00006330 break;
6331
6332 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006333 CurInit =
6334 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
6335 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00006336 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006337
6338 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006339 S.Diag(CurInit.get()->getExprLoc(),
6340 diag::warn_cxx98_compat_initializer_list_init)
6341 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00006342
Richard Smithcc1b96d2013-06-12 22:31:48 +00006343 // Materialize the temporary into memory.
6344 MaterializeTemporaryExpr *MTE = new (S.Context)
6345 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00006346 /*BoundToLvalueReference=*/false);
6347
6348 // Maybe lifetime-extend the array temporary's subobjects to match the
6349 // entity's lifetime.
6350 if (const InitializedEntity *ExtendingEntity =
6351 getEntityForTemporaryLifetimeExtension(&Entity))
6352 if (performReferenceExtension(MTE, ExtendingEntity))
6353 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6354 /*IsInitializerList=*/true,
6355 ExtendingEntity->getDecl());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006356
6357 // Wrap it in a construction of a std::initializer_list<T>.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006358 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006359
6360 // Bind the result, in case the library has given initializer_list a
6361 // non-trivial destructor.
6362 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006363 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00006364 break;
6365 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006366
Guy Benyei61054192013-02-07 10:55:47 +00006367 case SK_OCLSamplerInit: {
6368 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006369 "Sampler initialization on non-sampler type.");
Guy Benyei61054192013-02-07 10:55:47 +00006370
6371 QualType SourceType = CurInit.get()->getType();
Guy Benyei61054192013-02-07 10:55:47 +00006372
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006373 if (Entity.isParameterKind()) {
Guy Benyei61054192013-02-07 10:55:47 +00006374 if (!SourceType->isSamplerT())
6375 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6376 << SourceType;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006377 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
Guy Benyei61054192013-02-07 10:55:47 +00006378 llvm_unreachable("Invalid EntityKind!");
6379 }
6380
6381 break;
6382 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006383 case SK_OCLZeroEvent: {
6384 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006385 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006386
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006387 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006388 CK_ZeroToOCLEvent,
6389 CurInit.get()->getValueKind());
6390 break;
6391 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006392 }
6393 }
John McCall1f425642010-11-11 03:21:53 +00006394
6395 // Diagnose non-fatal problems with the completed initialization.
6396 if (Entity.getKind() == InitializedEntity::EK_Member &&
6397 cast<FieldDecl>(Entity.getDecl())->isBitField())
6398 S.CheckBitFieldInitialization(Kind.getLocation(),
6399 cast<FieldDecl>(Entity.getDecl()),
6400 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006401
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006402 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006403}
6404
Richard Smith593f9932012-12-08 02:01:17 +00006405/// Somewhere within T there is an uninitialized reference subobject.
6406/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00006407static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6408 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00006409 if (T->isReferenceType()) {
6410 S.Diag(Loc, diag::err_reference_without_init)
6411 << T.getNonReferenceType();
6412 return true;
6413 }
6414
6415 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6416 if (!RD || !RD->hasUninitializedReferenceMember())
6417 return false;
6418
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006419 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00006420 if (FI->isUnnamedBitfield())
6421 continue;
6422
6423 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6424 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6425 return true;
6426 }
6427 }
6428
Aaron Ballman574705e2014-03-13 15:41:46 +00006429 for (const auto &BI : RD->bases()) {
6430 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00006431 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6432 return true;
6433 }
6434 }
6435
6436 return false;
6437}
6438
6439
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006440//===----------------------------------------------------------------------===//
6441// Diagnose initialization failures
6442//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00006443
6444/// Emit notes associated with an initialization that failed due to a
6445/// "simple" conversion failure.
6446static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6447 Expr *op) {
6448 QualType destType = entity.getType();
6449 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6450 op->getType()->isObjCObjectPointerType()) {
6451
6452 // Emit a possible note about the conversion failing because the
6453 // operand is a message send with a related result type.
6454 S.EmitRelatedResultTypeNote(op);
6455
6456 // Emit a possible note about a return failing because we're
6457 // expecting a related result type.
6458 if (entity.getKind() == InitializedEntity::EK_Result)
6459 S.EmitRelatedResultTypeNoteForReturn(destType);
6460 }
6461}
6462
Richard Smith0449aaf2013-11-21 23:30:57 +00006463static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6464 InitListExpr *InitList) {
6465 QualType DestType = Entity.getType();
6466
6467 QualType E;
6468 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6469 QualType ArrayType = S.Context.getConstantArrayType(
6470 E.withConst(),
6471 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6472 InitList->getNumInits()),
6473 clang::ArrayType::Normal, 0);
6474 InitializedEntity HiddenArray =
6475 InitializedEntity::InitializeTemporary(ArrayType);
6476 return diagnoseListInit(S, HiddenArray, InitList);
6477 }
6478
Richard Smith8d082d12014-09-04 22:13:39 +00006479 if (DestType->isReferenceType()) {
6480 // A list-initialization failure for a reference means that we tried to
6481 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
6482 // inner initialization failed.
6483 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
6484 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
6485 SourceLocation Loc = InitList->getLocStart();
6486 if (auto *D = Entity.getDecl())
6487 Loc = D->getLocation();
6488 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
6489 return;
6490 }
6491
Richard Smith0449aaf2013-11-21 23:30:57 +00006492 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
6493 /*VerifyOnly=*/false);
6494 assert(DiagnoseInitList.HadError() &&
6495 "Inconsistent init list check result.");
6496}
6497
Nico Weber9386c822014-07-23 05:16:10 +00006498/// Prints a fixit for adding a null initializer for |Entity|. Call this only
6499/// right after emitting a diagnostic.
6500static void maybeEmitZeroInitializationFixit(Sema &S,
6501 InitializationSequence &Sequence,
6502 const InitializedEntity &Entity) {
6503 if (Entity.getKind() != InitializedEntity::EK_Variable)
6504 return;
6505
6506 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
6507 if (VD->getInit() || VD->getLocEnd().isMacroID())
6508 return;
6509
6510 QualType VariableTy = VD->getType().getCanonicalType();
6511 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
6512 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
6513
6514 S.Diag(Loc, diag::note_add_initializer)
6515 << VD << FixItHint::CreateInsertion(Loc, Init);
6516}
6517
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006518bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006519 const InitializedEntity &Entity,
6520 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006521 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006522 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006523 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006524
Douglas Gregor1b303932009-12-22 15:35:07 +00006525 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006526 switch (Failure) {
6527 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006528 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006529 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00006530 // Dig out the reference subobject which is uninitialized and diagnose it.
6531 // If this is value-initialization, this could be nested some way within
6532 // the target type.
6533 assert(Kind.getKind() == InitializationKind::IK_Value ||
6534 DestType->isReferenceType());
6535 bool Diagnosed =
6536 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6537 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6538 (void)Diagnosed;
6539 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006540 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006541 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006542 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006543
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006544 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006545 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006546 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006547 case FK_ArrayNeedsInitListOrStringLiteral:
6548 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6549 break;
6550 case FK_ArrayNeedsInitListOrWideStringLiteral:
6551 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6552 break;
6553 case FK_NarrowStringIntoWideCharArray:
6554 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6555 break;
6556 case FK_WideStringIntoCharArray:
6557 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6558 break;
6559 case FK_IncompatWideStringIntoWideChar:
6560 S.Diag(Kind.getLocation(),
6561 diag::err_array_init_incompat_wide_string_into_wchar);
6562 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006563 case FK_ArrayTypeMismatch:
6564 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00006565 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00006566 (Failure == FK_ArrayTypeMismatch
6567 ? diag::err_array_init_different_type
6568 : diag::err_array_init_non_constant_array))
6569 << DestType.getNonReferenceType()
6570 << Args[0]->getType()
6571 << Args[0]->getSourceRange();
6572 break;
6573
John McCalla59dc2f2012-01-05 00:13:19 +00006574 case FK_VariableLengthArrayHasInitializer:
6575 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6576 << Args[0]->getSourceRange();
6577 break;
6578
John McCall16df1e52010-03-30 21:47:33 +00006579 case FK_AddressOfOverloadFailed: {
6580 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006581 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006582 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00006583 true,
6584 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006585 break;
John McCall16df1e52010-03-30 21:47:33 +00006586 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006587
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006588 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00006589 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006590 switch (FailedOverloadResult) {
6591 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00006592 if (Failure == FK_UserConversionOverloadFailed)
6593 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6594 << Args[0]->getType() << DestType
6595 << Args[0]->getSourceRange();
6596 else
6597 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6598 << DestType << Args[0]->getType()
6599 << Args[0]->getSourceRange();
6600
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006601 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006602 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006603
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006604 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00006605 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00006606 DestType.getNonReferenceType(),
6607 diag::err_typecheck_nonviable_condition_incomplete,
6608 Args[0]->getType(), Args[0]->getSourceRange()))
6609 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6610 << Args[0]->getType() << Args[0]->getSourceRange()
6611 << DestType.getNonReferenceType();
6612
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006613 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006614 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006615
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006616 case OR_Deleted: {
6617 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6618 << Args[0]->getType() << DestType.getNonReferenceType()
6619 << Args[0]->getSourceRange();
6620 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006621 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00006622 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6623 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006624 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00006625 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006626 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006627 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006628 }
6629 break;
6630 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006631
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006632 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006633 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006634 }
6635 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006636
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006637 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00006638 if (isa<InitListExpr>(Args[0])) {
6639 S.Diag(Kind.getLocation(),
6640 diag::err_lvalue_reference_bind_to_initlist)
6641 << DestType.getNonReferenceType().isVolatileQualified()
6642 << DestType.getNonReferenceType()
6643 << Args[0]->getSourceRange();
6644 break;
6645 }
6646 // Intentional fallthrough
6647
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006648 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006649 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006650 Failure == FK_NonConstLValueReferenceBindingToTemporary
6651 ? diag::err_lvalue_reference_bind_to_temporary
6652 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00006653 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006654 << DestType.getNonReferenceType()
6655 << Args[0]->getType()
6656 << Args[0]->getSourceRange();
6657 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006658
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006659 case FK_RValueReferenceBindingToLValue:
6660 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00006661 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006662 << Args[0]->getSourceRange();
6663 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006664
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006665 case FK_ReferenceInitDropsQualifiers:
6666 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6667 << DestType.getNonReferenceType()
6668 << Args[0]->getType()
6669 << Args[0]->getSourceRange();
6670 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006671
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006672 case FK_ReferenceInitFailed:
6673 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6674 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00006675 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006676 << Args[0]->getType()
6677 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00006678 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006679 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006680
Douglas Gregorb491ed32011-02-19 21:32:49 +00006681 case FK_ConversionFailed: {
6682 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00006683 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00006684 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006685 << DestType
John McCall086a4642010-11-24 05:12:34 +00006686 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00006687 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006688 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00006689 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6690 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00006691 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00006692 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00006693 }
John Wiegley01296292011-04-08 18:41:53 +00006694
6695 case FK_ConversionFromPropertyFailed:
6696 // No-op. This error has already been reported.
6697 break;
6698
Douglas Gregor51e77d52009-12-10 17:56:55 +00006699 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00006700 SourceRange R;
6701
6702 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00006703 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00006704 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006705 else
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006706 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00006707
Alp Tokerb6cc5922014-05-03 03:45:55 +00006708 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00006709 if (Kind.isCStyleOrFunctionalCast())
6710 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6711 << R;
6712 else
6713 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6714 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006715 break;
6716 }
6717
6718 case FK_ReferenceBindingToInitList:
6719 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6720 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6721 break;
6722
6723 case FK_InitListBadDestinationType:
6724 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6725 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6726 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006727
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006728 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006729 case FK_ConstructorOverloadFailed: {
6730 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006731 if (Args.size())
6732 ArgsRange = SourceRange(Args.front()->getLocStart(),
6733 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006734
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006735 if (Failure == FK_ListConstructorOverloadFailed) {
Nico Weber9709ebf2014-07-08 23:54:25 +00006736 assert(Args.size() == 1 &&
6737 "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006738 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006739 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006740 }
6741
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006742 // FIXME: Using "DestType" for the entity we're printing is probably
6743 // bad.
6744 switch (FailedOverloadResult) {
6745 case OR_Ambiguous:
6746 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6747 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006748 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006749 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006750
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006751 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006752 if (Kind.getKind() == InitializationKind::IK_Default &&
6753 (Entity.getKind() == InitializedEntity::EK_Base ||
6754 Entity.getKind() == InitializedEntity::EK_Member) &&
6755 isa<CXXConstructorDecl>(S.CurContext)) {
6756 // This is implicit default initialization of a member or
6757 // base within a constructor. If no viable function was
6758 // found, notify the user that she needs to explicitly
6759 // initialize this base/member.
6760 CXXConstructorDecl *Constructor
6761 = cast<CXXConstructorDecl>(S.CurContext);
6762 if (Entity.getKind() == InitializedEntity::EK_Base) {
6763 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006764 << (Constructor->getInheritedConstructor() ? 2 :
6765 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006766 << S.Context.getTypeDeclType(Constructor->getParent())
6767 << /*base=*/0
6768 << Entity.getType();
6769
6770 RecordDecl *BaseDecl
6771 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6772 ->getDecl();
6773 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6774 << S.Context.getTagDeclType(BaseDecl);
6775 } else {
6776 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006777 << (Constructor->getInheritedConstructor() ? 2 :
6778 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006779 << S.Context.getTypeDeclType(Constructor->getParent())
6780 << /*member=*/1
6781 << Entity.getName();
Alp Toker2afa8782014-05-28 12:20:14 +00006782 S.Diag(Entity.getDecl()->getLocation(),
6783 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006784
6785 if (const RecordType *Record
6786 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006787 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006788 diag::note_previous_decl)
6789 << S.Context.getTagDeclType(Record->getDecl());
6790 }
6791 break;
6792 }
6793
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006794 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6795 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006796 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006797 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006798
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006799 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006800 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006801 OverloadingResult Ovl
6802 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00006803 if (Ovl != OR_Deleted) {
6804 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6805 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006806 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00006807 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006808 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00006809
6810 // If this is a defaulted or implicitly-declared function, then
6811 // it was implicitly deleted. Make it clear that the deletion was
6812 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00006813 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006814 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00006815 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006816 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00006817 else
6818 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6819 << true << DestType << ArgsRange;
6820
6821 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006822 break;
6823 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006824
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006825 case OR_Success:
6826 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006827 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006828 }
David Blaikie60deeee2012-01-17 08:24:58 +00006829 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006830
Douglas Gregor85dabae2009-12-16 01:38:02 +00006831 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006832 if (Entity.getKind() == InitializedEntity::EK_Member &&
6833 isa<CXXConstructorDecl>(S.CurContext)) {
6834 // This is implicit default-initialization of a const member in
6835 // a constructor. Complain that it needs to be explicitly
6836 // initialized.
6837 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6838 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006839 << (Constructor->getInheritedConstructor() ? 2 :
6840 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006841 << S.Context.getTypeDeclType(Constructor->getParent())
6842 << /*const=*/1
6843 << Entity.getName();
6844 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6845 << Entity.getName();
6846 } else {
6847 S.Diag(Kind.getLocation(), diag::err_default_init_const)
Nico Weber9386c822014-07-23 05:16:10 +00006848 << DestType << (bool)DestType->getAs<RecordType>();
6849 maybeEmitZeroInitializationFixit(S, *this, Entity);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006850 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00006851 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006852
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006853 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00006854 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006855 diag::err_init_incomplete_type);
6856 break;
6857
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006858 case FK_ListInitializationFailed: {
6859 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00006860 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6861 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006862 break;
6863 }
John McCall4124c492011-10-17 18:40:02 +00006864
6865 case FK_PlaceholderType: {
6866 // FIXME: Already diagnosed!
6867 break;
6868 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00006869
Sebastian Redl048a6d72012-04-01 19:54:59 +00006870 case FK_ExplicitConstructor: {
6871 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6872 << Args[0]->getSourceRange();
6873 OverloadCandidateSet::iterator Best;
6874 OverloadingResult Ovl
6875 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00006876 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00006877 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6878 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6879 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6880 break;
6881 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006882 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006883
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006884 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006885 return true;
6886}
Douglas Gregore1314a62009-12-18 05:02:21 +00006887
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006888void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006889 switch (SequenceKind) {
6890 case FailedSequence: {
6891 OS << "Failed sequence: ";
6892 switch (Failure) {
6893 case FK_TooManyInitsForReference:
6894 OS << "too many initializers for reference";
6895 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006896
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006897 case FK_ArrayNeedsInitList:
6898 OS << "array requires initializer list";
6899 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006900
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006901 case FK_ArrayNeedsInitListOrStringLiteral:
6902 OS << "array requires initializer list or string literal";
6903 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006904
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006905 case FK_ArrayNeedsInitListOrWideStringLiteral:
6906 OS << "array requires initializer list or wide string literal";
6907 break;
6908
6909 case FK_NarrowStringIntoWideCharArray:
6910 OS << "narrow string into wide char array";
6911 break;
6912
6913 case FK_WideStringIntoCharArray:
6914 OS << "wide string into char array";
6915 break;
6916
6917 case FK_IncompatWideStringIntoWideChar:
6918 OS << "incompatible wide string into wide char array";
6919 break;
6920
Douglas Gregore2f943b2011-02-22 18:29:51 +00006921 case FK_ArrayTypeMismatch:
6922 OS << "array type mismatch";
6923 break;
6924
6925 case FK_NonConstantArrayInit:
6926 OS << "non-constant array initializer";
6927 break;
6928
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006929 case FK_AddressOfOverloadFailed:
6930 OS << "address of overloaded function failed";
6931 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006932
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006933 case FK_ReferenceInitOverloadFailed:
6934 OS << "overload resolution for reference initialization failed";
6935 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006936
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006937 case FK_NonConstLValueReferenceBindingToTemporary:
6938 OS << "non-const lvalue reference bound to temporary";
6939 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006940
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006941 case FK_NonConstLValueReferenceBindingToUnrelated:
6942 OS << "non-const lvalue reference bound to unrelated type";
6943 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006944
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006945 case FK_RValueReferenceBindingToLValue:
6946 OS << "rvalue reference bound to an lvalue";
6947 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006948
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006949 case FK_ReferenceInitDropsQualifiers:
6950 OS << "reference initialization drops qualifiers";
6951 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006952
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006953 case FK_ReferenceInitFailed:
6954 OS << "reference initialization failed";
6955 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006956
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006957 case FK_ConversionFailed:
6958 OS << "conversion failed";
6959 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006960
John Wiegley01296292011-04-08 18:41:53 +00006961 case FK_ConversionFromPropertyFailed:
6962 OS << "conversion from property failed";
6963 break;
6964
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006965 case FK_TooManyInitsForScalar:
6966 OS << "too many initializers for scalar";
6967 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006968
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006969 case FK_ReferenceBindingToInitList:
6970 OS << "referencing binding to initializer list";
6971 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006972
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006973 case FK_InitListBadDestinationType:
6974 OS << "initializer list for non-aggregate, non-scalar type";
6975 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006976
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006977 case FK_UserConversionOverloadFailed:
6978 OS << "overloading failed for user-defined conversion";
6979 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006980
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006981 case FK_ConstructorOverloadFailed:
6982 OS << "constructor overloading failed";
6983 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006984
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006985 case FK_DefaultInitOfConst:
6986 OS << "default initialization of a const variable";
6987 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006988
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00006989 case FK_Incomplete:
6990 OS << "initialization of incomplete type";
6991 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006992
6993 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006994 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00006995 break;
6996
John McCalla59dc2f2012-01-05 00:13:19 +00006997 case FK_VariableLengthArrayHasInitializer:
6998 OS << "variable length array has an initializer";
6999 break;
7000
John McCall4124c492011-10-17 18:40:02 +00007001 case FK_PlaceholderType:
7002 OS << "initializer expression isn't contextually valid";
7003 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00007004
7005 case FK_ListConstructorOverloadFailed:
7006 OS << "list constructor overloading failed";
7007 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007008
Sebastian Redl048a6d72012-04-01 19:54:59 +00007009 case FK_ExplicitConstructor:
7010 OS << "list copy initialization chose explicit constructor";
7011 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007012 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007013 OS << '\n';
7014 return;
7015 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007016
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007017 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00007018 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007019 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007020
Sebastian Redld201edf2011-06-05 13:59:11 +00007021 case NormalSequence:
7022 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007023 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007024 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007025
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007026 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
7027 if (S != step_begin()) {
7028 OS << " -> ";
7029 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007030
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007031 switch (S->Kind) {
7032 case SK_ResolveAddressOfOverloadedFunction:
7033 OS << "resolve address of overloaded function";
7034 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007035
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007036 case SK_CastDerivedToBaseRValue:
7037 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
7038 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007039
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007040 case SK_CastDerivedToBaseXValue:
7041 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
7042 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007043
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007044 case SK_CastDerivedToBaseLValue:
7045 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
7046 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007047
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007048 case SK_BindReference:
7049 OS << "bind reference to lvalue";
7050 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007051
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007052 case SK_BindReferenceToTemporary:
7053 OS << "bind reference to a temporary";
7054 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007055
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007056 case SK_ExtraneousCopyToTemporary:
7057 OS << "extraneous C++03 copy to temporary";
7058 break;
7059
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007060 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007061 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007062 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007063
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007064 case SK_QualificationConversionRValue:
7065 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00007066 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007067
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007068 case SK_QualificationConversionXValue:
7069 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00007070 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007071
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007072 case SK_QualificationConversionLValue:
7073 OS << "qualification conversion (lvalue)";
7074 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007075
Richard Smith77be48a2014-07-31 06:31:19 +00007076 case SK_AtomicConversion:
7077 OS << "non-atomic-to-atomic conversion";
7078 break;
7079
Jordan Roseb1312a52013-04-11 00:58:58 +00007080 case SK_LValueToRValue:
7081 OS << "load (lvalue to rvalue)";
7082 break;
7083
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007084 case SK_ConversionSequence:
7085 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00007086 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007087 OS << ")";
7088 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007089
Richard Smithaaa0ec42013-09-21 21:19:19 +00007090 case SK_ConversionSequenceNoNarrowing:
7091 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00007092 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00007093 OS << ")";
7094 break;
7095
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007096 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007097 OS << "list aggregate initialization";
7098 break;
7099
Sebastian Redl29526f02011-11-27 16:50:07 +00007100 case SK_UnwrapInitList:
7101 OS << "unwrap reference initializer list";
7102 break;
7103
7104 case SK_RewrapInitList:
7105 OS << "rewrap reference initializer list";
7106 break;
7107
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007108 case SK_ConstructorInitialization:
7109 OS << "constructor initialization";
7110 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007111
Richard Smith53324112014-07-16 21:33:43 +00007112 case SK_ConstructorInitializationFromList:
7113 OS << "list initialization via constructor";
7114 break;
7115
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007116 case SK_ZeroInitialization:
7117 OS << "zero initialization";
7118 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007119
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007120 case SK_CAssignment:
7121 OS << "C assignment";
7122 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007123
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007124 case SK_StringInit:
7125 OS << "string initialization";
7126 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007127
7128 case SK_ObjCObjectConversion:
7129 OS << "Objective-C object conversion";
7130 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007131
7132 case SK_ArrayInit:
7133 OS << "array initialization";
7134 break;
John McCall31168b02011-06-15 23:02:42 +00007135
Richard Smithebeed412012-02-15 22:38:09 +00007136 case SK_ParenthesizedArrayInit:
7137 OS << "parenthesized array initialization";
7138 break;
7139
John McCall31168b02011-06-15 23:02:42 +00007140 case SK_PassByIndirectCopyRestore:
7141 OS << "pass by indirect copy and restore";
7142 break;
7143
7144 case SK_PassByIndirectRestore:
7145 OS << "pass by indirect restore";
7146 break;
7147
7148 case SK_ProduceObjCObject:
7149 OS << "Objective-C object retension";
7150 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007151
7152 case SK_StdInitializerList:
7153 OS << "std::initializer_list from initializer list";
7154 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007155
Richard Smithf8adcdc2014-07-17 05:12:35 +00007156 case SK_StdInitializerListConstructorCall:
7157 OS << "list initialization from std::initializer_list";
7158 break;
7159
Guy Benyei61054192013-02-07 10:55:47 +00007160 case SK_OCLSamplerInit:
7161 OS << "OpenCL sampler_t from integer constant";
7162 break;
7163
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007164 case SK_OCLZeroEvent:
7165 OS << "OpenCL event_t from zero";
7166 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007167 }
Richard Smith6b216962013-02-05 05:52:24 +00007168
7169 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007170 }
Richard Smith6b216962013-02-05 05:52:24 +00007171
7172 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007173}
7174
7175void InitializationSequence::dump() const {
7176 dump(llvm::errs());
7177}
7178
Richard Smithaaa0ec42013-09-21 21:19:19 +00007179static void DiagnoseNarrowingInInitList(Sema &S,
7180 const ImplicitConversionSequence &ICS,
7181 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007182 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007183 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007184 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00007185 switch (ICS.getKind()) {
7186 case ImplicitConversionSequence::StandardConversion:
7187 SCS = &ICS.Standard;
7188 break;
7189 case ImplicitConversionSequence::UserDefinedConversion:
7190 SCS = &ICS.UserDefined.After;
7191 break;
7192 case ImplicitConversionSequence::AmbiguousConversion:
7193 case ImplicitConversionSequence::EllipsisConversion:
7194 case ImplicitConversionSequence::BadConversion:
7195 return;
7196 }
7197
Richard Smith66e05fe2012-01-18 05:21:49 +00007198 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
7199 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00007200 QualType ConstantType;
7201 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
7202 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00007203 case NK_Not_Narrowing:
7204 // No narrowing occurred.
7205 return;
7206
7207 case NK_Type_Narrowing:
7208 // This was a floating-to-integer conversion, which is always considered a
7209 // narrowing conversion even if the value is a constant and can be
7210 // represented exactly as an integer.
7211 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007212 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7213 ? diag::warn_init_list_type_narrowing
7214 : diag::ext_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007215 << PostInit->getSourceRange()
7216 << PreNarrowingType.getLocalUnqualifiedType()
7217 << EntityType.getLocalUnqualifiedType();
7218 break;
7219
7220 case NK_Constant_Narrowing:
7221 // A constant value was narrowed.
7222 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007223 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7224 ? diag::warn_init_list_constant_narrowing
7225 : diag::ext_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007226 << PostInit->getSourceRange()
Richard Smith5614ca72012-03-23 23:55:39 +00007227 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007228 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007229 break;
7230
7231 case NK_Variable_Narrowing:
7232 // A variable's value may have been narrowed.
7233 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007234 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7235 ? diag::warn_init_list_variable_narrowing
7236 : diag::ext_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007237 << PostInit->getSourceRange()
7238 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007239 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007240 break;
7241 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007242
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007243 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007244 llvm::raw_svector_ostream OS(StaticCast);
7245 OS << "static_cast<";
7246 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7247 // It's important to use the typedef's name if there is one so that the
7248 // fixit doesn't break code using types like int64_t.
7249 //
7250 // FIXME: This will break if the typedef requires qualification. But
7251 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007252 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007253 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00007254 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007255 else {
7256 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
7257 // with a broken cast.
7258 return;
7259 }
7260 OS << ">(";
Alp Tokerb0869032014-05-17 01:13:18 +00007261 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007262 << PostInit->getSourceRange()
7263 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
7264 << FixItHint::CreateInsertion(
7265 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007266}
7267
Douglas Gregore1314a62009-12-18 05:02:21 +00007268//===----------------------------------------------------------------------===//
7269// Initialization helper functions
7270//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00007271bool
7272Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7273 ExprResult Init) {
7274 if (Init.isInvalid())
7275 return false;
7276
7277 Expr *InitE = Init.get();
7278 assert(InitE && "No initialization expression");
7279
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00007280 InitializationKind Kind
7281 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007282 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00007283 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00007284}
7285
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007286ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00007287Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7288 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007289 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00007290 bool TopLevelOfInitList,
7291 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00007292 if (Init.isInvalid())
7293 return ExprError();
7294
John McCall1f425642010-11-11 03:21:53 +00007295 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00007296 assert(InitE && "No initialization expression?");
7297
7298 if (EqualLoc.isInvalid())
7299 EqualLoc = InitE->getLocStart();
7300
7301 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00007302 EqualLoc,
7303 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00007304 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007305 Init.get();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007306
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007307 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00007308
Richard Smith66e05fe2012-01-18 05:21:49 +00007309 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00007310}