blob: 1068b3e7e138c2e601990741d96cb95cbba9cb88 [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.
Sebastian Redl88e4d492012-02-04 21:27:33 +00003177/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redled2e5322011-12-22 14:44:04 +00003178/// class type.
3179static void TryConstructorInitialization(Sema &S,
3180 const InitializedEntity &Entity,
3181 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003182 MultiExprArg Args, QualType DestType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003183 InitializationSequence &Sequence,
Sebastian Redl88e4d492012-02-04 21:27:33 +00003184 bool InitListSyntax = false) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003185 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Sebastian Redl88e4d492012-02-04 21:27:33 +00003186 "InitListSyntax must come with a single initializer list argument.");
3187
Sebastian Redled2e5322011-12-22 14:44:04 +00003188 // The type we're constructing needs to be complete.
3189 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003190 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003191 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003192 }
3193
3194 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3195 assert(DestRecordType && "Constructor initialization requires record type");
3196 CXXRecordDecl *DestRecordDecl
3197 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3198
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003199 // Build the candidate set directly in the initialization sequence
3200 // structure, so that it will persist if we fail.
3201 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3202
3203 // Determine whether we are allowed to call explicit constructors or
3204 // explicit conversion operators.
Sebastian Redl048a6d72012-04-01 19:54:59 +00003205 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003206 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003207
Sebastian Redled2e5322011-12-22 14:44:04 +00003208 // - Otherwise, if T is a class type, constructors are considered. The
3209 // applicable constructors are enumerated, and the best one is chosen
3210 // through overload resolution.
David Blaikieff7d47a2012-12-19 00:45:41 +00003211 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003212 // The container holding the constructors can under certain conditions
3213 // be changed while iterating (e.g. because of deserialization).
3214 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003215 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redled2e5322011-12-22 14:44:04 +00003216
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003217 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003218 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003219 bool AsInitializerList = false;
3220
Larisse Voufo19d08672015-01-27 18:47:05 +00003221 // C++11 [over.match.list]p1, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003222 // When objects of non-aggregate type T are list-initialized, such that
3223 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3224 // according to the rules in this section, overload resolution selects
3225 // the constructor in two phases:
3226 //
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003227 // - Initially, the candidate functions are the initializer-list
3228 // constructors of the class T and the argument list consists of the
3229 // initializer list as a single argument.
3230 if (InitListSyntax) {
Richard Smithd86812d2012-07-05 08:39:21 +00003231 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003232 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003233
3234 // If the initializer list has no elements and T has a default constructor,
3235 // the first phase is omitted.
Richard Smith2be35f52012-12-01 02:35:44 +00003236 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003237 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003238 CandidateSet, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003239 CopyInitialization, AllowExplicit,
Larisse Voufo19d08672015-01-27 18:47:05 +00003240 /*OnlyListConstructor=*/true);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003241
3242 // Time to unwrap the init list.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003243 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003244 }
3245
3246 // C++11 [over.match.list]p1:
3247 // - If no viable initializer-list constructor is found, overload resolution
3248 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003249 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003250 // elements of the initializer list.
3251 if (Result == OR_No_Viable_Function) {
3252 AsInitializerList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003253 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003254 CandidateSet, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003255 CopyInitialization, AllowExplicit,
Larisse Voufo19d08672015-01-27 18:47:05 +00003256 /*OnlyListConstructors=*/false);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003257 }
3258 if (Result) {
Sebastian Redl88e4d492012-02-04 21:27:33 +00003259 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003260 InitializationSequence::FK_ListConstructorOverloadFailed :
3261 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003262 Result);
3263 return;
3264 }
3265
Richard Smithd86812d2012-07-05 08:39:21 +00003266 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003267 // If a program calls for the default initialization of an object
3268 // of a const-qualified type T, T shall be a class type with a
3269 // user-provided default constructor.
3270 if (Kind.getKind() == InitializationKind::IK_Default &&
3271 Entity.getType().isConstQualified() &&
Aaron Ballman899b9c62012-07-31 22:40:31 +00003272 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redled2e5322011-12-22 14:44:04 +00003273 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3274 return;
3275 }
3276
Sebastian Redl048a6d72012-04-01 19:54:59 +00003277 // C++11 [over.match.list]p1:
3278 // In copy-list-initialization, if an explicit constructor is chosen, the
3279 // initializer is ill-formed.
3280 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3281 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3282 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3283 return;
3284 }
3285
Sebastian Redled2e5322011-12-22 14:44:04 +00003286 // Add the constructor initialization step. Any cv-qualification conversion is
3287 // subsumed by the initialization.
3288 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redled2e5322011-12-22 14:44:04 +00003289 Sequence.AddConstructorInitializationStep(CtorDecl,
3290 Best->FoundDecl.getAccess(),
3291 DestType, HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003292 InitListSyntax, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003293}
3294
Sebastian Redl29526f02011-11-27 16:50:07 +00003295static bool
3296ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3297 Expr *Initializer,
3298 QualType &SourceType,
3299 QualType &UnqualifiedSourceType,
3300 QualType UnqualifiedTargetType,
3301 InitializationSequence &Sequence) {
3302 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3303 S.Context.OverloadTy) {
3304 DeclAccessPair Found;
3305 bool HadMultipleCandidates = false;
3306 if (FunctionDecl *Fn
3307 = S.ResolveAddressOfOverloadedFunction(Initializer,
3308 UnqualifiedTargetType,
3309 false, Found,
3310 &HadMultipleCandidates)) {
3311 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3312 HadMultipleCandidates);
3313 SourceType = Fn->getType();
3314 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3315 } else if (!UnqualifiedTargetType->isRecordType()) {
3316 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3317 return true;
3318 }
3319 }
3320 return false;
3321}
3322
3323static void TryReferenceInitializationCore(Sema &S,
3324 const InitializedEntity &Entity,
3325 const InitializationKind &Kind,
3326 Expr *Initializer,
3327 QualType cv1T1, QualType T1,
3328 Qualifiers T1Quals,
3329 QualType cv2T2, QualType T2,
3330 Qualifiers T2Quals,
3331 InitializationSequence &Sequence);
3332
Richard Smithd86812d2012-07-05 08:39:21 +00003333static void TryValueInitialization(Sema &S,
3334 const InitializedEntity &Entity,
3335 const InitializationKind &Kind,
3336 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00003337 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00003338
Sebastian Redl29526f02011-11-27 16:50:07 +00003339/// \brief Attempt list initialization of a reference.
3340static void TryReferenceListInitialization(Sema &S,
3341 const InitializedEntity &Entity,
3342 const InitializationKind &Kind,
3343 InitListExpr *InitList,
Richard Smithfaadef72013-06-08 00:02:08 +00003344 InitializationSequence &Sequence) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003345 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003346 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003347 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3348 return;
3349 }
3350
3351 QualType DestType = Entity.getType();
3352 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3353 Qualifiers T1Quals;
3354 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3355
3356 // Reference initialization via an initializer list works thus:
3357 // If the initializer list consists of a single element that is
3358 // reference-related to the referenced type, bind directly to that element
3359 // (possibly creating temporaries).
3360 // Otherwise, initialize a temporary with the initializer list and
3361 // bind to that.
3362 if (InitList->getNumInits() == 1) {
3363 Expr *Initializer = InitList->getInit(0);
3364 QualType cv2T2 = Initializer->getType();
3365 Qualifiers T2Quals;
3366 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3367
3368 // If this fails, creating a temporary wouldn't work either.
3369 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3370 T1, Sequence))
3371 return;
3372
3373 SourceLocation DeclLoc = Initializer->getLocStart();
3374 bool dummy1, dummy2, dummy3;
3375 Sema::ReferenceCompareResult RefRelationship
3376 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3377 dummy2, dummy3);
3378 if (RefRelationship >= Sema::Ref_Related) {
3379 // Try to bind the reference here.
3380 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3381 T1Quals, cv2T2, T2, T2Quals, Sequence);
3382 if (Sequence)
3383 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3384 return;
3385 }
Richard Smith03d93932013-01-15 07:58:29 +00003386
3387 // Update the initializer if we've resolved an overloaded function.
3388 if (Sequence.step_begin() != Sequence.step_end())
3389 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00003390 }
3391
3392 // Not reference-related. Create a temporary and bind to that.
3393 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3394
3395 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3396 if (Sequence) {
3397 if (DestType->isRValueReferenceType() ||
3398 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3399 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3400 else
3401 Sequence.SetFailed(
3402 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3403 }
3404}
3405
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003406/// \brief Attempt list initialization (C++0x [dcl.init.list])
3407static void TryListInitialization(Sema &S,
3408 const InitializedEntity &Entity,
3409 const InitializationKind &Kind,
3410 InitListExpr *InitList,
3411 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003412 QualType DestType = Entity.getType();
3413
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003414 // C++ doesn't allow scalar initialization with more than one argument.
3415 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003416 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003417 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3418 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3419 return;
3420 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003421 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003422 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003423 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003424 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003425
Larisse Voufod2010992015-01-24 23:09:54 +00003426 if (DestType->isRecordType() &&
3427 S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
3428 Sequence.setIncompleteTypeFailure(DestType);
3429 return;
3430 }
Richard Smithd86812d2012-07-05 08:39:21 +00003431
Larisse Voufo19d08672015-01-27 18:47:05 +00003432 // C++11 [dcl.init.list]p3, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003433 // - If T is a class type and the initializer list has a single element of
3434 // type cv U, where U is T or a class derived from T, the object is
3435 // initialized from that element (by copy-initialization for
3436 // copy-list-initialization, or by direct-initialization for
3437 // direct-list-initialization).
3438 // - Otherwise, if T is a character array and the initializer list has a
3439 // single element that is an appropriately-typed string literal
3440 // (8.5.2 [dcl.init.string]), initialization is performed as described
3441 // in that section.
Larisse Voufo19d08672015-01-27 18:47:05 +00003442 // - Otherwise, if T is an aggregate, [...] (continue below).
3443 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
Larisse Voufod2010992015-01-24 23:09:54 +00003444 if (DestType->isRecordType()) {
3445 QualType InitType = InitList->getInit(0)->getType();
3446 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
3447 S.IsDerivedFrom(InitType, DestType)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003448 Expr *InitListAsExpr = InitList;
3449 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smithd86812d2012-07-05 08:39:21 +00003450 Sequence, /*InitListSyntax*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00003451 return;
3452 }
3453 }
3454 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
3455 Expr *SubInit[1] = {InitList->getInit(0)};
3456 if (!isa<VariableArrayType>(DestAT) &&
3457 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
3458 InitializationKind SubKind =
3459 Kind.getKind() == InitializationKind::IK_DirectList
3460 ? InitializationKind::CreateDirect(Kind.getLocation(),
3461 InitList->getLBraceLoc(),
3462 InitList->getRBraceLoc())
3463 : Kind;
3464 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3465 /*TopLevelOfInitList*/ true);
3466
3467 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
3468 // the element is not an appropriately-typed string literal, in which
3469 // case we should proceed as in C++11 (below).
3470 if (Sequence) {
3471 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3472 return;
3473 }
3474 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003475 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003476 }
Larisse Voufod2010992015-01-24 23:09:54 +00003477
3478 // C++11 [dcl.init.list]p3:
3479 // - If T is an aggregate, aggregate initialization is performed.
3480 if (DestType->isRecordType() && !DestType->isAggregateType()) {
3481 if (S.getLangOpts().CPlusPlus11) {
3482 // - Otherwise, if the initializer list has no elements and T is a
3483 // class type with a default constructor, the object is
3484 // value-initialized.
3485 if (InitList->getNumInits() == 0) {
3486 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
3487 if (RD->hasDefaultConstructor()) {
3488 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3489 return;
3490 }
3491 }
3492
3493 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3494 // an initializer_list object constructed [...]
3495 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3496 return;
3497
3498 // - Otherwise, if T is a class type, constructors are considered.
3499 Expr *InitListAsExpr = InitList;
3500 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
3501 Sequence, /*InitListSyntax*/ true);
3502 } else
3503 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
3504 return;
3505 }
3506
Richard Smith089c3162013-09-21 21:55:46 +00003507 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
3508 InitList->getNumInits() == 1 &&
3509 InitList->getInit(0)->getType()->isRecordType()) {
3510 // - Otherwise, if the initializer list has a single element of type E
3511 // [...references are handled above...], the object or reference is
Larisse Voufod2010992015-01-24 23:09:54 +00003512 // initialized from that element (by copy-initialization for
3513 // copy-list-initialization, or by direct-initialization for
3514 // direct-list-initialization); if a narrowing conversion is required
3515 // to convert the element to T, the program is ill-formed.
3516 //
Richard Smith089c3162013-09-21 21:55:46 +00003517 // Per core-24034, this is direct-initialization if we were performing
3518 // direct-list-initialization and copy-initialization otherwise.
3519 // We can't use InitListChecker for this, because it always performs
3520 // copy-initialization. This only matters if we might use an 'explicit'
3521 // conversion operator, so we only need to handle the cases where the source
3522 // is of record type.
3523 InitializationKind SubKind =
3524 Kind.getKind() == InitializationKind::IK_DirectList
3525 ? InitializationKind::CreateDirect(Kind.getLocation(),
3526 InitList->getLBraceLoc(),
3527 InitList->getRBraceLoc())
3528 : Kind;
3529 Expr *SubInit[1] = { InitList->getInit(0) };
3530 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3531 /*TopLevelOfInitList*/true);
3532 if (Sequence)
3533 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3534 return;
3535 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003536
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003537 InitListChecker CheckInitList(S, Entity, InitList,
Richard Smithde229232013-06-06 11:41:05 +00003538 DestType, /*VerifyOnly=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003539 if (CheckInitList.HadError()) {
3540 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3541 return;
3542 }
3543
3544 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003545 Sequence.AddListInitializationStep(DestType);
3546}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003547
3548/// \brief Try a reference initialization that involves calling a conversion
3549/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003550static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3551 const InitializedEntity &Entity,
3552 const InitializationKind &Kind,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003553 Expr *Initializer,
3554 bool AllowRValues,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003555 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003556 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003557 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3558 QualType T1 = cv1T1.getUnqualifiedType();
3559 QualType cv2T2 = Initializer->getType();
3560 QualType T2 = cv2T2.getUnqualifiedType();
3561
3562 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003563 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003564 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003565 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003566 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003567 ObjCConversion,
3568 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003569 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003570 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003571 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003572 (void)ObjCLifetimeConversion;
3573
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003574 // Build the candidate set directly in the initialization sequence
3575 // structure, so that it will persist if we fail.
3576 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3577 CandidateSet.clear();
3578
3579 // Determine whether we are allowed to call explicit constructors or
3580 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003581 bool AllowExplicit = Kind.AllowExplicit();
Richard Smith6c6ddab2013-09-21 21:23:47 +00003582 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3583
Craig Topperc3ec1492014-05-26 06:22:03 +00003584 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003585 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3586 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003587 // The type we're converting to is a class type. Enumerate its constructors
3588 // to see if there is a suitable conversion.
3589 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003590
David Blaikieff7d47a2012-12-19 00:45:41 +00003591 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003592 // The container holding the constructors can under certain conditions
3593 // be changed while iterating (e.g. because of deserialization).
3594 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003595 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00003596 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003597 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3598 NamedDecl *D = *CI;
John McCalla0296f72010-03-19 07:35:19 +00003599 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3600
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003601 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003602 CXXConstructorDecl *Constructor = nullptr;
John McCalla0296f72010-03-19 07:35:19 +00003603 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003604 if (ConstructorTmpl)
3605 Constructor = cast<CXXConstructorDecl>(
3606 ConstructorTmpl->getTemplatedDecl());
3607 else
John McCalla0296f72010-03-19 07:35:19 +00003608 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003609
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003610 if (!Constructor->isInvalidDecl() &&
3611 Constructor->isConvertingConstructor(AllowExplicit)) {
3612 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003613 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003614 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003615 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003616 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003617 else
John McCalla0296f72010-03-19 07:35:19 +00003618 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003619 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003620 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003621 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003622 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003623 }
John McCall3696dcb2010-08-17 07:23:57 +00003624 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3625 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003626
Craig Topperc3ec1492014-05-26 06:22:03 +00003627 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003628 if ((T2RecordType = T2->getAs<RecordType>()) &&
3629 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003630 // The type we're converting from is a class type, enumerate its conversion
3631 // functions.
3632 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3633
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003634 std::pair<CXXRecordDecl::conversion_iterator,
3635 CXXRecordDecl::conversion_iterator>
3636 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3637 for (CXXRecordDecl::conversion_iterator
3638 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003639 NamedDecl *D = *I;
3640 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3641 if (isa<UsingShadowDecl>(D))
3642 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003643
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003644 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3645 CXXConversionDecl *Conv;
3646 if (ConvTemplate)
3647 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3648 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003649 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003650
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003651 // If the conversion function doesn't return a reference type,
3652 // it can't be considered for this conversion unless we're allowed to
3653 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003654 // FIXME: Do we need to make sure that we only consider conversion
3655 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003656 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00003657 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003658 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3659 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003660 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003661 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00003662 DestType, CandidateSet,
3663 /*AllowObjCConversionOnExplicit=*/
3664 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003665 else
John McCalla0296f72010-03-19 07:35:19 +00003666 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00003667 Initializer, DestType, CandidateSet,
3668 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003669 }
3670 }
3671 }
John McCall3696dcb2010-08-17 07:23:57 +00003672 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3673 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003674
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003675 SourceLocation DeclLoc = Initializer->getLocStart();
3676
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003677 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003678 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003679 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003680 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003681 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003682
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003683 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00003684 // This is the overload that will be used for this initialization step if we
3685 // use this initialization. Mark it as referenced.
3686 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00003687
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003688 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003689 if (isa<CXXConversionDecl>(Function))
Alp Toker314cc812014-01-25 16:55:45 +00003690 T2 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003691 else
3692 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003693
3694 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003695 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003696 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003697 T2.getNonLValueExprType(S.Context),
3698 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003699
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003700 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003701 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003702 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003703 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003704 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003705 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003706 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003707
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003708 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003709 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003710 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003711 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003712 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003713 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003714 NewDerivedToBase, NewObjCConversion,
3715 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003716 if (NewRefRelationship == Sema::Ref_Incompatible) {
3717 // If the type we've converted to is not reference-related to the
3718 // type we're looking for, then there is another conversion step
3719 // we need to perform to produce a temporary of the right type
3720 // that we'll be binding to.
3721 ImplicitConversionSequence ICS;
3722 ICS.setStandard();
3723 ICS.Standard = Best->FinalConversion;
3724 T2 = ICS.Standard.getToType(2);
3725 Sequence.AddConversionSequenceStep(ICS, T2);
3726 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003727 Sequence.AddDerivedToBaseCastStep(
3728 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003729 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003730 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003731 else if (NewObjCConversion)
3732 Sequence.AddObjCObjectConversionStep(
3733 S.Context.getQualifiedType(T1,
3734 T2.getNonReferenceType().getQualifiers()));
3735
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003736 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003737 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003738
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003739 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3740 return OR_Success;
3741}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003742
Richard Smithc620f552011-10-19 16:55:56 +00003743static void CheckCXX98CompatAccessibleCopy(Sema &S,
3744 const InitializedEntity &Entity,
3745 Expr *CurInitExpr);
3746
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003747/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3748static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003749 const InitializedEntity &Entity,
3750 const InitializationKind &Kind,
3751 Expr *Initializer,
3752 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003753 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003754 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003755 Qualifiers T1Quals;
3756 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003757 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003758 Qualifiers T2Quals;
3759 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003760
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003761 // If the initializer is the address of an overloaded function, try
3762 // to resolve the overloaded function. If all goes well, T2 is the
3763 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003764 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3765 T1, Sequence))
3766 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003767
Sebastian Redl29526f02011-11-27 16:50:07 +00003768 // Delegate everything else to a subfunction.
3769 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3770 T1Quals, cv2T2, T2, T2Quals, Sequence);
3771}
3772
Jordan Roseb1312a52013-04-11 00:58:58 +00003773/// Converts the target of reference initialization so that it has the
3774/// appropriate qualifiers and value kind.
3775///
3776/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3777/// \code
3778/// int x;
3779/// const int &r = x;
3780/// \endcode
3781///
3782/// In this case the reference is binding to a bitfield lvalue, which isn't
3783/// valid. Perform a load to create a lifetime-extended temporary instead.
3784/// \code
3785/// const int &r = someStruct.bitfield;
3786/// \endcode
3787static ExprValueKind
3788convertQualifiersAndValueKindIfNecessary(Sema &S,
3789 InitializationSequence &Sequence,
3790 Expr *Initializer,
3791 QualType cv1T1,
3792 Qualifiers T1Quals,
3793 Qualifiers T2Quals,
3794 bool IsLValueRef) {
John McCalld25db7e2013-05-06 21:39:12 +00003795 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Roseb1312a52013-04-11 00:58:58 +00003796 Initializer->refersToVectorElement();
3797
3798 if (IsNonAddressableType) {
3799 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3800 // lvalue reference to a non-volatile const type, or the reference shall be
3801 // an rvalue reference.
3802 //
3803 // If not, we can't make a temporary and bind to that. Give up and allow the
3804 // error to be diagnosed later.
3805 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3806 assert(Initializer->isGLValue());
3807 return Initializer->getValueKind();
3808 }
3809
3810 // Force a load so we can materialize a temporary.
3811 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3812 return VK_RValue;
3813 }
3814
3815 if (T1Quals != T2Quals) {
3816 Sequence.AddQualificationConversionStep(cv1T1,
3817 Initializer->getValueKind());
3818 }
3819
3820 return Initializer->getValueKind();
3821}
3822
3823
Sebastian Redl29526f02011-11-27 16:50:07 +00003824/// \brief Reference initialization without resolving overloaded functions.
3825static void TryReferenceInitializationCore(Sema &S,
3826 const InitializedEntity &Entity,
3827 const InitializationKind &Kind,
3828 Expr *Initializer,
3829 QualType cv1T1, QualType T1,
3830 Qualifiers T1Quals,
3831 QualType cv2T2, QualType T2,
3832 Qualifiers T2Quals,
3833 InitializationSequence &Sequence) {
3834 QualType DestType = Entity.getType();
3835 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003836 // Compute some basic properties of the types and the initializer.
3837 bool isLValueRef = DestType->isLValueReferenceType();
3838 bool isRValueRef = !isLValueRef;
3839 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003840 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003841 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003842 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003843 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003844 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003845 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003846
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003847 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003848 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003849 // "cv2 T2" as follows:
3850 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003851 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003852 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00003853 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00003854 // there are no function rvalues in C++, rvalue refs to functions are treated
3855 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003856 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003857 bool T1Function = T1->isFunctionType();
3858 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003859 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003860 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003861 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003862 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003863 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003864 // reference-compatible with "cv2 T2," or
3865 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003866 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003867 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003868 // can occur. However, we do pay attention to whether it is a bit-field
3869 // to decide whether we're actually binding to a temporary created from
3870 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003871 if (DerivedToBase)
3872 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003873 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003874 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003875 else if (ObjCConversion)
3876 Sequence.AddObjCObjectConversionStep(
3877 S.Context.getQualifiedType(T1, T2Quals));
3878
Jordan Roseb1312a52013-04-11 00:58:58 +00003879 ExprValueKind ValueKind =
3880 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3881 cv1T1, T1Quals, T2Quals,
3882 isLValueRef);
3883 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003884 return;
3885 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003886
3887 // - has a class type (i.e., T2 is a class type), where T1 is not
3888 // reference-related to T2, and can be implicitly converted to an
3889 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3890 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003891 // applicable conversion functions (13.3.1.6) and choosing the best
3892 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003893 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00003894 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00003895 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3896 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003897 ConvOvlResult = TryRefInitWithConversionFunction(
3898 S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003899 if (ConvOvlResult == OR_Success)
3900 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00003901 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00003902 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003903 InitializationSequence::FK_ReferenceInitOverloadFailed,
3904 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003905 }
3906 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003907
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003908 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003909 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003910 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003911 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003912 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3913 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3914 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003915 Sequence.SetOverloadFailure(
3916 InitializationSequence::FK_ReferenceInitOverloadFailed,
3917 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003918 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003919 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003920 ? (RefRelationship == Sema::Ref_Related
3921 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3922 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3923 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003924
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003925 return;
3926 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003927
Douglas Gregor92e460e2011-01-20 16:44:54 +00003928 // - If the initializer expression
3929 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3930 // "cv1 T1" is reference-compatible with "cv2 T2"
3931 // Note: functions are handled below.
3932 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003933 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003934 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003935 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003936 (InitCategory.isXValue() ||
3937 (InitCategory.isPRValue() && T2->isRecordType()) ||
3938 (InitCategory.isPRValue() && T2->isArrayType()))) {
3939 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3940 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003941 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3942 // compiler the freedom to perform a copy here or bind to the
3943 // object, while C++0x requires that we bind directly to the
3944 // object. Hence, we always bind to the object without making an
3945 // extra copy. However, in C++03 requires that we check for the
3946 // presence of a suitable copy constructor:
3947 //
3948 // The constructor that would be used to make the copy shall
3949 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003950 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003951 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003952 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00003953 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003954 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003955
Douglas Gregor92e460e2011-01-20 16:44:54 +00003956 if (DerivedToBase)
3957 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3958 ValueKind);
3959 else if (ObjCConversion)
3960 Sequence.AddObjCObjectConversionStep(
3961 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003962
Jordan Roseb1312a52013-04-11 00:58:58 +00003963 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3964 Initializer, cv1T1,
3965 T1Quals, T2Quals,
3966 isLValueRef);
3967
3968 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003969 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003970 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003971
3972 // - has a class type (i.e., T2 is a class type), where T1 is not
3973 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003974 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3975 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00003976 //
3977 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00003978 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003979 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003980 ConvOvlResult = TryRefInitWithConversionFunction(
3981 S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003982 if (ConvOvlResult)
3983 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003984 InitializationSequence::FK_ReferenceInitOverloadFailed,
3985 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003986
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003987 return;
3988 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003989
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00003990 if ((RefRelationship == Sema::Ref_Compatible ||
3991 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3992 isRValueRef && InitCategory.isLValue()) {
3993 Sequence.SetFailed(
3994 InitializationSequence::FK_RValueReferenceBindingToLValue);
3995 return;
3996 }
3997
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003998 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3999 return;
4000 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004001
4002 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004003 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00004004 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004005 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00004006
John McCallec6f4e92010-06-04 02:29:22 +00004007 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4008
Richard Smith2eabf782013-06-13 00:57:57 +00004009 // FIXME: Why do we use an implicit conversion here rather than trying
4010 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00004011 ImplicitConversionSequence ICS
4012 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00004013 /*SuppressUserConversions=*/false,
4014 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004015 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004016 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4017 /*AllowObjCWritebackConversion=*/false);
4018
4019 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004020 // FIXME: Use the conversion function set stored in ICS to turn
4021 // this into an overloading ambiguity diagnostic. However, we need
4022 // to keep that set as an OverloadCandidateSet rather than as some
4023 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004024 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4025 Sequence.SetOverloadFailure(
4026 InitializationSequence::FK_ReferenceInitOverloadFailed,
4027 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004028 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4029 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004030 else
4031 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004032 return;
John McCall31168b02011-06-15 23:02:42 +00004033 } else {
4034 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004035 }
4036
4037 // [...] If T1 is reference-related to T2, cv1 must be the
4038 // same cv-qualification as, or greater cv-qualification
4039 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004040 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4041 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004042 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00004043 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004044 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4045 return;
4046 }
4047
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004048 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004049 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004050 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004051 InitCategory.isLValue()) {
4052 Sequence.SetFailed(
4053 InitializationSequence::FK_RValueReferenceBindingToLValue);
4054 return;
4055 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004056
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004057 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4058 return;
4059}
4060
4061/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004062/// (C++ [dcl.init.string], C99 6.7.8).
4063static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004064 const InitializedEntity &Entity,
4065 const InitializationKind &Kind,
4066 Expr *Initializer,
4067 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004068 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004069}
4070
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004071/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004072static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004073 const InitializedEntity &Entity,
4074 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004075 InitializationSequence &Sequence,
4076 InitListExpr *InitList) {
4077 assert((!InitList || InitList->getNumInits() == 0) &&
4078 "Shouldn't use value-init for non-empty init lists");
4079
Richard Smith1bfe0682012-02-14 21:14:13 +00004080 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004081 //
4082 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004083 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004084
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004085 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004086 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004087
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004088 if (const RecordType *RT = T->getAs<RecordType>()) {
4089 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004090 bool NeedZeroInitialization = true;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004091 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithd86812d2012-07-05 08:39:21 +00004092 // C++98:
4093 // -- if T is a class type (clause 9) with a user-declared constructor
4094 // (12.1), then the default constructor for T is called (and the
4095 // initialization is ill-formed if T has no accessible default
4096 // constructor);
Richard Smith1bfe0682012-02-14 21:14:13 +00004097 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithd86812d2012-07-05 08:39:21 +00004098 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00004099 } else {
4100 // C++11:
4101 // -- if T is a class type (clause 9) with either no default constructor
4102 // (12.1 [class.ctor]) or a default constructor that is user-provided
4103 // or deleted, then the object is default-initialized;
4104 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4105 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithd86812d2012-07-05 08:39:21 +00004106 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00004107 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004108
Richard Smith1bfe0682012-02-14 21:14:13 +00004109 // -- if T is a (possibly cv-qualified) non-union class type without a
4110 // user-provided or deleted default constructor, then the object is
4111 // zero-initialized and, if T has a non-trivial default constructor,
4112 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004113 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4114 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004115 if (NeedZeroInitialization)
4116 Sequence.AddZeroInitializationStep(Entity.getType());
4117
Richard Smith593f9932012-12-08 02:01:17 +00004118 // C++03:
4119 // -- if T is a non-union class type without a user-declared constructor,
4120 // then every non-static data member and base class component of T is
4121 // value-initialized;
4122 // [...] A program that calls for [...] value-initialization of an
4123 // entity of reference type is ill-formed.
4124 //
4125 // C++11 doesn't need this handling, because value-initialization does not
4126 // occur recursively there, and the implicit default constructor is
4127 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004128 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004129 ClassDecl->hasUninitializedReferenceMember()) {
4130 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4131 return;
4132 }
4133
Richard Smithd86812d2012-07-05 08:39:21 +00004134 // If this is list-value-initialization, pass the empty init list on when
4135 // building the constructor call. This affects the semantics of a few
4136 // things (such as whether an explicit default constructor can be called).
4137 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004138 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004139 bool InitListSyntax = InitList;
4140
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004141 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4142 InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004143 }
4144 }
4145
Douglas Gregor1b303932009-12-22 15:35:07 +00004146 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004147}
4148
Douglas Gregor85dabae2009-12-16 01:38:02 +00004149/// \brief Attempt default initialization (C++ [dcl.init]p6).
4150static void TryDefaultInitialization(Sema &S,
4151 const InitializedEntity &Entity,
4152 const InitializationKind &Kind,
4153 InitializationSequence &Sequence) {
4154 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004155
Douglas Gregor85dabae2009-12-16 01:38:02 +00004156 // C++ [dcl.init]p6:
4157 // To default-initialize an object of type T means:
4158 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004159 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4160
Douglas Gregor85dabae2009-12-16 01:38:02 +00004161 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4162 // constructor for T is called (and the initialization is ill-formed if
4163 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004164 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004165 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004166 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004167 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004168
Douglas Gregor85dabae2009-12-16 01:38:02 +00004169 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004170
Douglas Gregor85dabae2009-12-16 01:38:02 +00004171 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004172 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004173 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004174 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004175 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004176 return;
4177 }
4178
4179 // If the destination type has a lifetime property, zero-initialize it.
4180 if (DestType.getQualifiers().hasObjCLifetime()) {
4181 Sequence.AddZeroInitializationStep(Entity.getType());
4182 return;
4183 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004184}
4185
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004186/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4187/// which enumerates all conversion functions and performs overload resolution
4188/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004189static void TryUserDefinedConversion(Sema &S,
Richard Smith77be48a2014-07-31 06:31:19 +00004190 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004191 const InitializationKind &Kind,
4192 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004193 InitializationSequence &Sequence,
4194 bool TopLevelOfInitList) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004195 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4196 QualType SourceType = Initializer->getType();
4197 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4198 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004199
Douglas Gregor540c3b02009-12-14 17:27:33 +00004200 // Build the candidate set directly in the initialization sequence
4201 // structure, so that it will persist if we fail.
4202 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4203 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004204
Douglas Gregor540c3b02009-12-14 17:27:33 +00004205 // Determine whether we are allowed to call explicit constructors or
4206 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004207 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004208
Douglas Gregor540c3b02009-12-14 17:27:33 +00004209 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4210 // The type we're converting to is a class type. Enumerate its constructors
4211 // to see if there is a suitable conversion.
4212 CXXRecordDecl *DestRecordDecl
4213 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004214
Douglas Gregord9848152010-04-26 14:36:57 +00004215 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004216 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004217 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie12be6392012-10-18 16:57:32 +00004218 // The container holding the constructors can under certain conditions
4219 // be changed while iterating. To be safe we copy the lookup results
4220 // to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004221 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004222 for (SmallVectorImpl<NamedDecl *>::iterator
David Blaikie12be6392012-10-18 16:57:32 +00004223 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregord9848152010-04-26 14:36:57 +00004224 Con != ConEnd; ++Con) {
4225 NamedDecl *D = *Con;
4226 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004227
Douglas Gregord9848152010-04-26 14:36:57 +00004228 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00004229 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregord9848152010-04-26 14:36:57 +00004230 FunctionTemplateDecl *ConstructorTmpl
4231 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004232 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00004233 Constructor = cast<CXXConstructorDecl>(
4234 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00004235 else
Douglas Gregord9848152010-04-26 14:36:57 +00004236 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004237
Douglas Gregord9848152010-04-26 14:36:57 +00004238 if (!Constructor->isInvalidDecl() &&
4239 Constructor->isConvertingConstructor(AllowExplicit)) {
4240 if (ConstructorTmpl)
4241 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004242 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004243 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004244 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004245 else
4246 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004247 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004248 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004249 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004250 }
Douglas Gregord9848152010-04-26 14:36:57 +00004251 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004252 }
Eli Friedman78275202009-12-19 08:11:05 +00004253
4254 SourceLocation DeclLoc = Initializer->getLocStart();
4255
Douglas Gregor540c3b02009-12-14 17:27:33 +00004256 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4257 // The type we're converting from is a class type, enumerate its conversion
4258 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004259
Eli Friedman4afe9a32009-12-20 22:12:03 +00004260 // We can only enumerate the conversion functions for a complete type; if
4261 // the type isn't complete, simply skip this step.
4262 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4263 CXXRecordDecl *SourceRecordDecl
4264 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004265
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004266 std::pair<CXXRecordDecl::conversion_iterator,
4267 CXXRecordDecl::conversion_iterator>
4268 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4269 for (CXXRecordDecl::conversion_iterator
4270 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004271 NamedDecl *D = *I;
4272 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4273 if (isa<UsingShadowDecl>(D))
4274 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004275
Eli Friedman4afe9a32009-12-20 22:12:03 +00004276 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4277 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004278 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004279 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004280 else
John McCallda4458e2010-03-31 01:36:47 +00004281 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004282
Eli Friedman4afe9a32009-12-20 22:12:03 +00004283 if (AllowExplicit || !Conv->isExplicit()) {
4284 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004285 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004286 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004287 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004288 else
John McCalla0296f72010-03-19 07:35:19 +00004289 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004290 Initializer, DestType, CandidateSet,
4291 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004292 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004293 }
4294 }
4295 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004296
4297 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004298 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004299 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00004300 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004301 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004302 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004303 Result);
4304 return;
4305 }
John McCall0d1da222010-01-12 00:44:57 +00004306
Douglas Gregor540c3b02009-12-14 17:27:33 +00004307 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004308 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004309 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004310
Douglas Gregor540c3b02009-12-14 17:27:33 +00004311 if (isa<CXXConstructorDecl>(Function)) {
4312 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004313 // subsumed by the initialization. Per DR5, the created temporary is of the
4314 // cv-unqualified type of the destination.
4315 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4316 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004317 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004318 return;
4319 }
4320
4321 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004322 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004323 if (ConvType->getAs<RecordType>()) {
Richard Smithb24f0672012-02-11 19:22:50 +00004324 // If we're converting to a class type, there may be an copy of
Douglas Gregor5ab11652010-04-17 22:01:05 +00004325 // the resulting temporary object (possible to create an object of
4326 // a base class type). That copy is not a separate conversion, so
4327 // we just make a note of the actual destination type (possibly a
4328 // base class of the type returned by the conversion function) and
4329 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004330 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4331 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004332 return;
4333 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004334
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004335 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4336 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004337
Douglas Gregor5ab11652010-04-17 22:01:05 +00004338 // If the conversion following the call to the conversion function
4339 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004340 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4341 Best->FinalConversion.Third) {
4342 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004343 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004344 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004345 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004346 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004347}
4348
Richard Smithf032001b2013-06-20 02:18:31 +00004349/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4350/// a function with a pointer return type contains a 'return false;' statement.
4351/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4352/// code using that header.
4353///
4354/// Work around this by treating 'return false;' as zero-initializing the result
4355/// if it's used in a pointer-returning function in a system header.
4356static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4357 const InitializedEntity &Entity,
4358 const Expr *Init) {
4359 return S.getLangOpts().CPlusPlus11 &&
4360 Entity.getKind() == InitializedEntity::EK_Result &&
4361 Entity.getType()->isPointerType() &&
4362 isa<CXXBoolLiteralExpr>(Init) &&
4363 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4364 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4365}
4366
John McCall31168b02011-06-15 23:02:42 +00004367/// The non-zero enum values here are indexes into diagnostic alternatives.
4368enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4369
4370/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00004371static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004372 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00004373 // Skip parens.
4374 e = e->IgnoreParens();
4375
4376 // Skip address-of nodes.
4377 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4378 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004379 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4380 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004381
4382 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00004383 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4384 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00004385 case CK_Dependent:
4386 case CK_BitCast:
4387 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00004388 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004389 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004390
4391 case CK_ArrayToPointerDecay:
4392 return IIK_nonscalar;
4393
4394 case CK_NullToPointer:
4395 return IIK_okay;
4396
4397 default:
4398 break;
4399 }
4400
4401 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00004402 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004403 // set isWeakAccess to true, to mean that there will be an implicit
4404 // load which requires a cleanup.
4405 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4406 isWeakAccess = true;
4407
John McCall63f84442011-06-27 23:59:58 +00004408 if (!isAddressOf) return IIK_nonlocal;
4409
John McCall113bee02012-03-10 09:33:50 +00004410 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4411 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00004412
4413 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00004414
4415 // If we have a conditional operator, check both sides.
4416 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004417 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4418 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00004419 return iik;
4420
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004421 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004422
4423 // These are never scalar.
4424 } else if (isa<ArraySubscriptExpr>(e)) {
4425 return IIK_nonscalar;
4426
4427 // Otherwise, it needs to be a null pointer constant.
4428 } else {
4429 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4430 ? IIK_okay : IIK_nonlocal);
4431 }
4432
4433 return IIK_nonlocal;
4434}
4435
4436/// Check whether the given expression is a valid operand for an
4437/// indirect copy/restore.
4438static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4439 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004440 bool isWeakAccess = false;
4441 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4442 // If isWeakAccess to true, there will be an implicit
4443 // load which requires a cleanup.
4444 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4445 S.ExprNeedsCleanups = true;
4446
John McCall31168b02011-06-15 23:02:42 +00004447 if (iik == IIK_okay) return;
4448
4449 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4450 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4451 << src->getSourceRange();
4452}
4453
Douglas Gregore2f943b2011-02-22 18:29:51 +00004454/// \brief Determine whether we have compatible array types for the
4455/// purposes of GNU by-copy array initialization.
Larisse Voufod2010992015-01-24 23:09:54 +00004456static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
Douglas Gregore2f943b2011-02-22 18:29:51 +00004457 const ArrayType *Source) {
4458 // If the source and destination array types are equivalent, we're
4459 // done.
4460 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4461 return true;
4462
4463 // Make sure that the element types are the same.
4464 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4465 return false;
4466
4467 // The only mismatch we allow is when the destination is an
4468 // incomplete array type and the source is a constant array type.
4469 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4470}
4471
John McCall31168b02011-06-15 23:02:42 +00004472static bool tryObjCWritebackConversion(Sema &S,
4473 InitializationSequence &Sequence,
4474 const InitializedEntity &Entity,
4475 Expr *Initializer) {
4476 bool ArrayDecay = false;
4477 QualType ArgType = Initializer->getType();
4478 QualType ArgPointee;
4479 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4480 ArrayDecay = true;
4481 ArgPointee = ArgArrayType->getElementType();
4482 ArgType = S.Context.getPointerType(ArgPointee);
4483 }
4484
4485 // Handle write-back conversion.
4486 QualType ConvertedArgType;
4487 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4488 ConvertedArgType))
4489 return false;
4490
4491 // We should copy unless we're passing to an argument explicitly
4492 // marked 'out'.
4493 bool ShouldCopy = true;
4494 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4495 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4496
4497 // Do we need an lvalue conversion?
4498 if (ArrayDecay || Initializer->isGLValue()) {
4499 ImplicitConversionSequence ICS;
4500 ICS.setStandard();
4501 ICS.Standard.setAsIdentityConversion();
4502
4503 QualType ResultType;
4504 if (ArrayDecay) {
4505 ICS.Standard.First = ICK_Array_To_Pointer;
4506 ResultType = S.Context.getPointerType(ArgPointee);
4507 } else {
4508 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4509 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4510 }
4511
4512 Sequence.AddConversionSequenceStep(ICS, ResultType);
4513 }
4514
4515 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4516 return true;
4517}
4518
Guy Benyei61054192013-02-07 10:55:47 +00004519static bool TryOCLSamplerInitialization(Sema &S,
4520 InitializationSequence &Sequence,
4521 QualType DestType,
4522 Expr *Initializer) {
4523 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4524 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4525 return false;
4526
4527 Sequence.AddOCLSamplerInitStep(DestType);
4528 return true;
4529}
4530
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004531//
4532// OpenCL 1.2 spec, s6.12.10
4533//
4534// The event argument can also be used to associate the
4535// async_work_group_copy with a previous async copy allowing
4536// an event to be shared by multiple async copies; otherwise
4537// event should be zero.
4538//
4539static bool TryOCLZeroEventInitialization(Sema &S,
4540 InitializationSequence &Sequence,
4541 QualType DestType,
4542 Expr *Initializer) {
4543 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4544 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4545 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4546 return false;
4547
4548 Sequence.AddOCLZeroEventStep(DestType);
4549 return true;
4550}
4551
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004552InitializationSequence::InitializationSequence(Sema &S,
4553 const InitializedEntity &Entity,
4554 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004555 MultiExprArg Args,
4556 bool TopLevelOfInitList)
Richard Smith100b24a2014-04-17 01:52:14 +00004557 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Richard Smith089c3162013-09-21 21:55:46 +00004558 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
4559}
4560
4561void InitializationSequence::InitializeFrom(Sema &S,
4562 const InitializedEntity &Entity,
4563 const InitializationKind &Kind,
4564 MultiExprArg Args,
4565 bool TopLevelOfInitList) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004566 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004567
John McCall5e77d762013-04-16 07:28:30 +00004568 // Eliminate non-overload placeholder types in the arguments. We
4569 // need to do this before checking whether types are dependent
4570 // because lowering a pseudo-object expression might well give us
4571 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004572 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00004573 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4574 // FIXME: should we be doing this here?
4575 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4576 if (result.isInvalid()) {
4577 SetFailed(FK_PlaceholderType);
4578 return;
4579 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004580 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00004581 }
4582
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004583 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004584 // The semantics of initializers are as follows. The destination type is
4585 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004586 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004587 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004588 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004589 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004590
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004591 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004592 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004593 SequenceKind = DependentSequence;
4594 return;
4595 }
4596
Sebastian Redld201edf2011-06-05 13:59:11 +00004597 // Almost everything is a normal sequence.
4598 setSequenceKind(NormalSequence);
4599
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004600 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00004601 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004602 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004603 Initializer = Args[0];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004604 if (S.getLangOpts().ObjC1) {
4605 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
4606 DestType, Initializer->getType(),
4607 Initializer) ||
4608 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
4609 Args[0] = Initializer;
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004610 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004611 if (!isa<InitListExpr>(Initializer))
4612 SourceType = Initializer->getType();
4613 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004614
Sebastian Redl0501c632012-02-12 16:37:36 +00004615 // - If the initializer is a (non-parenthesized) braced-init-list, the
4616 // object is list-initialized (8.5.4).
4617 if (Kind.getKind() != InitializationKind::IK_Direct) {
4618 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4619 TryListInitialization(S, Entity, Kind, InitList, *this);
4620 return;
4621 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004622 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004623
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004624 // - If the destination type is a reference type, see 8.5.3.
4625 if (DestType->isReferenceType()) {
4626 // C++0x [dcl.init.ref]p1:
4627 // A variable declared to be a T& or T&&, that is, "reference to type T"
4628 // (8.3.2), shall be initialized by an object, or function, of type T or
4629 // by an object that can be converted into a T.
4630 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004631 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004632 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004633 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004634 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004635 return;
4636 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004637
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004638 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004639 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004640 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004641 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004642 return;
4643 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004644
Douglas Gregor85dabae2009-12-16 01:38:02 +00004645 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004646 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004647 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004648 return;
4649 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004650
John McCall66884dd2011-02-21 07:22:22 +00004651 // - If the destination type is an array of characters, an array of
4652 // char16_t, an array of char32_t, or an array of wchar_t, and the
4653 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004654 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004655 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004656 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004657 if (Initializer && isa<VariableArrayType>(DestAT)) {
4658 SetFailed(FK_VariableLengthArrayHasInitializer);
4659 return;
4660 }
4661
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004662 if (Initializer) {
4663 switch (IsStringInit(Initializer, DestAT, Context)) {
4664 case SIF_None:
4665 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4666 return;
4667 case SIF_NarrowStringIntoWideChar:
4668 SetFailed(FK_NarrowStringIntoWideCharArray);
4669 return;
4670 case SIF_WideStringIntoChar:
4671 SetFailed(FK_WideStringIntoCharArray);
4672 return;
4673 case SIF_IncompatWideStringIntoWideChar:
4674 SetFailed(FK_IncompatWideStringIntoWideChar);
4675 return;
4676 case SIF_Other:
4677 break;
4678 }
John McCall66884dd2011-02-21 07:22:22 +00004679 }
4680
Douglas Gregore2f943b2011-02-22 18:29:51 +00004681 // Note: as an GNU C extension, we allow initialization of an
4682 // array from a compound literal that creates an array of the same
4683 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004684 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00004685 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4686 Initializer->getType()->isArrayType()) {
4687 const ArrayType *SourceAT
4688 = Context.getAsArrayType(Initializer->getType());
4689 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004690 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004691 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004692 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004693 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004694 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004695 }
Richard Smithebeed412012-02-15 22:38:09 +00004696 }
Richard Smithd86812d2012-07-05 08:39:21 +00004697 // Note: as a GNU C++ extension, we allow list-initialization of a
4698 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004699 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00004700 Entity.getKind() == InitializedEntity::EK_Member &&
4701 Initializer && isa<InitListExpr>(Initializer)) {
4702 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4703 *this);
4704 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004705 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004706 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004707 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4708 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004709 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004710 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004711
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004712 return;
4713 }
Eli Friedman78275202009-12-19 08:11:05 +00004714
Larisse Voufod2010992015-01-24 23:09:54 +00004715 // Determine whether we should consider writeback conversions for
John McCall31168b02011-06-15 23:02:42 +00004716 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004717 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004718 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00004719
4720 // We're at the end of the line for C: it's either a write-back conversion
4721 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004722 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004723 // If allowed, check whether this is an Objective-C writeback conversion.
4724 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004725 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004726 return;
4727 }
Guy Benyei61054192013-02-07 10:55:47 +00004728
4729 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4730 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004731
4732 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4733 return;
4734
John McCall31168b02011-06-15 23:02:42 +00004735 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004736 AddCAssignmentStep(DestType);
4737 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004738 return;
4739 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004740
David Blaikiebbafb8a2012-03-11 07:00:24 +00004741 assert(S.getLangOpts().CPlusPlus);
John McCall31168b02011-06-15 23:02:42 +00004742
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004743 // - If the destination type is a (possibly cv-qualified) class type:
4744 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004745 // - If the initialization is direct-initialization, or if it is
4746 // copy-initialization where the cv-unqualified version of the
4747 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004748 // class of the destination, constructors are considered. [...]
4749 if (Kind.getKind() == InitializationKind::IK_Direct ||
4750 (Kind.getKind() == InitializationKind::IK_Copy &&
4751 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4752 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004753 TryConstructorInitialization(S, Entity, Kind, Args,
Richard Smith77be48a2014-07-31 06:31:19 +00004754 DestType, *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004755 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004756 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004757 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004758 // used) to a derived class thereof are enumerated as described in
4759 // 13.3.1.4, and the best one is chosen through overload resolution
4760 // (13.3).
4761 else
Richard Smith77be48a2014-07-31 06:31:19 +00004762 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004763 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004764 return;
4765 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004766
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004767 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004768 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004769 return;
4770 }
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004771 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004772
4773 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004774 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004775 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith77be48a2014-07-31 06:31:19 +00004776 // For a conversion to _Atomic(T) from either T or a class type derived
4777 // from T, initialize the T object then convert to _Atomic type.
4778 bool NeedAtomicConversion = false;
4779 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
4780 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
4781 S.IsDerivedFrom(SourceType, Atomic->getValueType())) {
4782 DestType = Atomic->getValueType();
4783 NeedAtomicConversion = true;
4784 }
4785 }
4786
4787 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004788 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004789 MaybeProduceObjCObject(S, *this, Entity);
Richard Smith77be48a2014-07-31 06:31:19 +00004790 if (!Failed() && NeedAtomicConversion)
4791 AddAtomicConversionStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004792 return;
4793 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004794
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004795 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004796 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004797 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004798 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004799 // destination type; no user-defined conversions are considered.
Richard Smith77be48a2014-07-31 06:31:19 +00004800
John McCall31168b02011-06-15 23:02:42 +00004801 ImplicitConversionSequence ICS
Richard Smith77be48a2014-07-31 06:31:19 +00004802 = S.TryImplicitConversion(Initializer, DestType,
John McCall31168b02011-06-15 23:02:42 +00004803 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004804 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004805 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004806 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4807 allowObjCWritebackConversion);
Richard Smith77be48a2014-07-31 06:31:19 +00004808
4809 if (ICS.isStandard() &&
John McCall31168b02011-06-15 23:02:42 +00004810 ICS.Standard.Second == ICK_Writeback_Conversion) {
4811 // Objective-C ARC writeback conversion.
4812
4813 // We should copy unless we're passing to an argument explicitly
4814 // marked 'out'.
4815 bool ShouldCopy = true;
4816 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4817 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4818
4819 // If there was an lvalue adjustment, add it as a separate conversion.
4820 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4821 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4822 ImplicitConversionSequence LvalueICS;
4823 LvalueICS.setStandard();
4824 LvalueICS.Standard.setAsIdentityConversion();
4825 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4826 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004827 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004828 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004829
Richard Smith77be48a2014-07-31 06:31:19 +00004830 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004831 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004832 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00004833 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4834 AddZeroInitializationStep(Entity.getType());
4835 } else if (Initializer->getType() == Context.OverloadTy &&
4836 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4837 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004838 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004839 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004840 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004841 } else {
Richard Smith77be48a2014-07-31 06:31:19 +00004842 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00004843
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004844 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004845 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004846}
4847
4848InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004849 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004850 StepEnd = Steps.end();
4851 Step != StepEnd; ++Step)
4852 Step->Destroy();
4853}
4854
4855//===----------------------------------------------------------------------===//
4856// Perform initialization
4857//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004858static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004859getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004860 switch(Entity.getKind()) {
4861 case InitializedEntity::EK_Variable:
4862 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004863 case InitializedEntity::EK_Exception:
4864 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004865 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004866 return Sema::AA_Initializing;
4867
4868 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004869 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004870 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4871 return Sema::AA_Sending;
4872
Douglas Gregore1314a62009-12-18 05:02:21 +00004873 return Sema::AA_Passing;
4874
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004875 case InitializedEntity::EK_Parameter_CF_Audited:
4876 if (Entity.getDecl() &&
4877 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4878 return Sema::AA_Sending;
4879
4880 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4881
Douglas Gregore1314a62009-12-18 05:02:21 +00004882 case InitializedEntity::EK_Result:
4883 return Sema::AA_Returning;
4884
Douglas Gregore1314a62009-12-18 05:02:21 +00004885 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00004886 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004887 // FIXME: Can we tell apart casting vs. converting?
4888 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004889
Douglas Gregore1314a62009-12-18 05:02:21 +00004890 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004891 case InitializedEntity::EK_ArrayElement:
4892 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004893 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004894 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004895 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004896 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004897 return Sema::AA_Initializing;
4898 }
4899
David Blaikie8a40f702012-01-17 06:56:22 +00004900 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004901}
4902
Richard Smith27874d62013-01-08 00:08:23 +00004903/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00004904/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004905static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004906 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004907 case InitializedEntity::EK_ArrayElement:
4908 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004909 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004910 case InitializedEntity::EK_New:
4911 case InitializedEntity::EK_Variable:
4912 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004913 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004914 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004915 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004916 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004917 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004918 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004919 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004920 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004921
Douglas Gregore1314a62009-12-18 05:02:21 +00004922 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004923 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00004924 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004925 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004926 return true;
4927 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004928
Douglas Gregore1314a62009-12-18 05:02:21 +00004929 llvm_unreachable("missed an InitializedEntity kind?");
4930}
4931
Douglas Gregor95562572010-04-24 23:45:46 +00004932/// \brief Whether the given entity, when initialized with an object
4933/// created for that initialization, requires destruction.
4934static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4935 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00004936 case InitializedEntity::EK_Result:
4937 case InitializedEntity::EK_New:
4938 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004939 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004940 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004941 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004942 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004943 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00004944 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004945
Richard Smith27874d62013-01-08 00:08:23 +00004946 case InitializedEntity::EK_Member:
Douglas Gregor95562572010-04-24 23:45:46 +00004947 case InitializedEntity::EK_Variable:
4948 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004949 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00004950 case InitializedEntity::EK_Temporary:
4951 case InitializedEntity::EK_ArrayElement:
4952 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004953 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004954 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00004955 return true;
4956 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004957
4958 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004959}
4960
Richard Smithc620f552011-10-19 16:55:56 +00004961/// \brief Look for copy and move constructors and constructor templates, for
4962/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4963static void LookupCopyAndMoveConstructors(Sema &S,
4964 OverloadCandidateSet &CandidateSet,
4965 CXXRecordDecl *Class,
4966 Expr *CurInitExpr) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004967 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004968 // The container holding the constructors can under certain conditions
4969 // be changed while iterating (e.g. because of deserialization).
4970 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004971 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004972 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004973 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4974 NamedDecl *D = *CI;
Craig Topperc3ec1492014-05-26 06:22:03 +00004975 CXXConstructorDecl *Constructor = nullptr;
Richard Smithc620f552011-10-19 16:55:56 +00004976
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004977 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smithc620f552011-10-19 16:55:56 +00004978 // Handle copy/moveconstructors, only.
4979 if (!Constructor || Constructor->isInvalidDecl() ||
4980 !Constructor->isCopyOrMoveConstructor() ||
4981 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4982 continue;
4983
4984 DeclAccessPair FoundDecl
4985 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4986 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004987 CurInitExpr, CandidateSet);
Richard Smithc620f552011-10-19 16:55:56 +00004988 continue;
4989 }
4990
4991 // Handle constructor templates.
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004992 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smithc620f552011-10-19 16:55:56 +00004993 if (ConstructorTmpl->isInvalidDecl())
4994 continue;
4995
4996 Constructor = cast<CXXConstructorDecl>(
4997 ConstructorTmpl->getTemplatedDecl());
4998 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4999 continue;
5000
5001 // FIXME: Do we need to limit this to copy-constructor-like
5002 // candidates?
5003 DeclAccessPair FoundDecl
5004 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
Craig Topperc3ec1492014-05-26 06:22:03 +00005005 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005006 CurInitExpr, CandidateSet, true);
Richard Smithc620f552011-10-19 16:55:56 +00005007 }
5008}
5009
5010/// \brief Get the location at which initialization diagnostics should appear.
5011static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5012 Expr *Initializer) {
5013 switch (Entity.getKind()) {
5014 case InitializedEntity::EK_Result:
5015 return Entity.getReturnLoc();
5016
5017 case InitializedEntity::EK_Exception:
5018 return Entity.getThrowLoc();
5019
5020 case InitializedEntity::EK_Variable:
5021 return Entity.getDecl()->getLocation();
5022
Douglas Gregor19666fb2012-02-15 16:57:26 +00005023 case InitializedEntity::EK_LambdaCapture:
5024 return Entity.getCaptureLoc();
5025
Richard Smithc620f552011-10-19 16:55:56 +00005026 case InitializedEntity::EK_ArrayElement:
5027 case InitializedEntity::EK_Member:
5028 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005029 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00005030 case InitializedEntity::EK_Temporary:
5031 case InitializedEntity::EK_New:
5032 case InitializedEntity::EK_Base:
5033 case InitializedEntity::EK_Delegating:
5034 case InitializedEntity::EK_VectorElement:
5035 case InitializedEntity::EK_ComplexElement:
5036 case InitializedEntity::EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005037 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005038 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00005039 return Initializer->getLocStart();
5040 }
5041 llvm_unreachable("missed an InitializedEntity kind?");
5042}
5043
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005044/// \brief Make a (potentially elidable) temporary copy of the object
5045/// provided by the given initializer by calling the appropriate copy
5046/// constructor.
5047///
5048/// \param S The Sema object used for type-checking.
5049///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005050/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005051/// the type of the initializer expression or a superclass thereof.
5052///
James Dennett634962f2012-06-14 21:40:34 +00005053/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005054///
5055/// \param CurInit The initializer expression.
5056///
5057/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5058/// is permitted in C++03 (but not C++0x) when binding a reference to
5059/// an rvalue.
5060///
5061/// \returns An expression that copies the initializer expression into
5062/// a temporary object, or an error expression if a copy could not be
5063/// created.
John McCalldadc5752010-08-24 06:29:42 +00005064static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005065 QualType T,
5066 const InitializedEntity &Entity,
5067 ExprResult CurInit,
5068 bool IsExtraneousCopy) {
Fariborz Jahanian36f7f132015-01-28 22:08:10 +00005069 if (CurInit.isInvalid())
5070 return CurInit;
Douglas Gregor5ab11652010-04-17 22:01:05 +00005071 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005072 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005073 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005074 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005075 Class = cast<CXXRecordDecl>(Record->getDecl());
5076 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005077 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005078
Douglas Gregor5d369002011-01-21 18:05:27 +00005079 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005080 // When certain criteria are met, an implementation is allowed to
5081 // omit the copy/move construction of a class object, even if the
5082 // copy/move constructor and/or destructor for the object have
5083 // side effects. [...]
5084 // - when a temporary class object that has not been bound to a
5085 // reference (12.2) would be copied/moved to a class object
5086 // with the same cv-unqualified type, the copy/move operation
5087 // can be omitted by constructing the temporary object
5088 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005089 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005090 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00005091 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005092 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00005093 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00005094 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00005095 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005096
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005097 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005098 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005099 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005100
Douglas Gregorf282a762011-01-21 19:38:21 +00005101 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00005102 // Only consider constructors and constructor templates. Per
5103 // C++0x [dcl.init]p16, second bullet to class types, this initialization
5104 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005105 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005106 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005107
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005108 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5109
Douglas Gregore1314a62009-12-18 05:02:21 +00005110 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00005111 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005112 case OR_Success:
5113 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005114
Douglas Gregore1314a62009-12-18 05:02:21 +00005115 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005116 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5117 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5118 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005119 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005120 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005121 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005122 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00005123 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005124 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005125
Douglas Gregore1314a62009-12-18 05:02:21 +00005126 case OR_Ambiguous:
5127 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005128 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005129 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005130 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00005131 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005132
Douglas Gregore1314a62009-12-18 05:02:21 +00005133 case OR_Deleted:
5134 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005135 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005136 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00005137 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00005138 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005139 }
5140
Douglas Gregor5ab11652010-04-17 22:01:05 +00005141 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00005142 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005143 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005144
Anders Carlssona01874b2010-04-21 18:47:17 +00005145 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005146 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005147
5148 if (IsExtraneousCopy) {
5149 // If this is a totally extraneous copy for C++03 reference
5150 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005151 // expression. We don't generate an (elided) copy operation here
5152 // because doing so would require us to pass down a flag to avoid
5153 // infinite recursion, where each step adds another extraneous,
5154 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005155
Douglas Gregor30b52772010-04-18 07:57:34 +00005156 // Instantiate the default arguments of any extra parameters in
5157 // the selected copy constructor, as if we were going to create a
5158 // proper call to the copy constructor.
5159 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5160 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5161 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005162 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005163 break;
5164
5165 // Build the default argument expression; we don't actually care
5166 // if this succeeds or not, because this routine will complain
5167 // if there was a problem.
5168 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5169 }
5170
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005171 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005172 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005173
Douglas Gregor5ab11652010-04-17 22:01:05 +00005174 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005175 // constructor call (we might have derived-to-base conversions, or
5176 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005177 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005178 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005179
Douglas Gregord0ace022010-04-25 00:55:24 +00005180 // Actually perform the constructor call.
5181 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005182 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005183 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005184 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005185 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005186 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005187 CXXConstructExpr::CK_Complete,
5188 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005189
Douglas Gregord0ace022010-04-25 00:55:24 +00005190 // If we're supposed to bind temporaries, do so.
5191 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005192 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005193 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005194}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005195
Richard Smithc620f552011-10-19 16:55:56 +00005196/// \brief Check whether elidable copy construction for binding a reference to
5197/// a temporary would have succeeded if we were building in C++98 mode, for
5198/// -Wc++98-compat.
5199static void CheckCXX98CompatAccessibleCopy(Sema &S,
5200 const InitializedEntity &Entity,
5201 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005202 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005203
5204 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5205 if (!Record)
5206 return;
5207
5208 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005209 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00005210 return;
5211
5212 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00005213 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005214 LookupCopyAndMoveConstructors(
5215 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5216
5217 // Perform overload resolution.
5218 OverloadCandidateSet::iterator Best;
5219 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5220
5221 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5222 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5223 << CurInitExpr->getSourceRange();
5224
5225 switch (OR) {
5226 case OR_Success:
5227 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCall5dadb652012-04-07 03:04:20 +00005228 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005229 // FIXME: Check default arguments as far as that's possible.
5230 break;
5231
5232 case OR_No_Viable_Function:
5233 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005234 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005235 break;
5236
5237 case OR_Ambiguous:
5238 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005239 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005240 break;
5241
5242 case OR_Deleted:
5243 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005244 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005245 break;
5246 }
5247}
5248
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005249void InitializationSequence::PrintInitLocationNote(Sema &S,
5250 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005251 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005252 if (Entity.getDecl()->getLocation().isInvalid())
5253 return;
5254
5255 if (Entity.getDecl()->getDeclName())
5256 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5257 << Entity.getDecl()->getDeclName();
5258 else
5259 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5260 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005261 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5262 Entity.getMethodDecl())
5263 S.Diag(Entity.getMethodDecl()->getLocation(),
5264 diag::note_method_return_type_change)
5265 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005266}
5267
Sebastian Redl112aa822011-07-14 19:07:55 +00005268static bool isReferenceBinding(const InitializationSequence::Step &s) {
5269 return s.Kind == InitializationSequence::SK_BindReference ||
5270 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5271}
5272
Jordan Rose6c0505e2013-05-06 16:48:12 +00005273/// Returns true if the parameters describe a constructor initialization of
5274/// an explicit temporary object, e.g. "Point(x, y)".
5275static bool isExplicitTemporary(const InitializedEntity &Entity,
5276 const InitializationKind &Kind,
5277 unsigned NumArgs) {
5278 switch (Entity.getKind()) {
5279 case InitializedEntity::EK_Temporary:
5280 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005281 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005282 break;
5283 default:
5284 return false;
5285 }
5286
5287 switch (Kind.getKind()) {
5288 case InitializationKind::IK_DirectList:
5289 return true;
5290 // FIXME: Hack to work around cast weirdness.
5291 case InitializationKind::IK_Direct:
5292 case InitializationKind::IK_Value:
5293 return NumArgs != 1;
5294 default:
5295 return false;
5296 }
5297}
5298
Sebastian Redled2e5322011-12-22 14:44:04 +00005299static ExprResult
5300PerformConstructorInitialization(Sema &S,
5301 const InitializedEntity &Entity,
5302 const InitializationKind &Kind,
5303 MultiExprArg Args,
5304 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00005305 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005306 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005307 bool IsStdInitListInitialization,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005308 SourceLocation LBraceLoc,
5309 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005310 unsigned NumArgs = Args.size();
5311 CXXConstructorDecl *Constructor
5312 = cast<CXXConstructorDecl>(Step.Function.Function);
5313 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5314
5315 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005316 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00005317 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5318 ? Kind.getEqualLoc()
5319 : Kind.getLocation();
5320
5321 if (Kind.getKind() == InitializationKind::IK_Default) {
5322 // Force even a trivial, implicit default constructor to be
5323 // semantically checked. We do this explicitly because we don't build
5324 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00005325 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00005326 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00005327 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00005328 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5329 }
5330
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005331 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00005332
Douglas Gregor6073dca2012-02-24 23:56:31 +00005333 // C++ [over.match.copy]p1:
5334 // - When initializing a temporary to be bound to the first parameter
5335 // of a constructor that takes a reference to possibly cv-qualified
5336 // T as its first argument, called with a single argument in the
5337 // context of direct-initialization, explicit conversion functions
5338 // are also considered.
5339 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5340 Args.size() == 1 &&
5341 Constructor->isCopyOrMoveConstructor();
5342
Sebastian Redled2e5322011-12-22 14:44:04 +00005343 // Determine the arguments required to actually perform the constructor
5344 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005345 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005346 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00005347 AllowExplicitConv,
5348 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00005349 return ExprError();
5350
5351
Jordan Rose6c0505e2013-05-06 16:48:12 +00005352 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005353 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedmanfa0df832012-02-02 03:46:19 +00005354 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith22262ab2013-05-04 06:44:46 +00005355 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5356 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005357
5358 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5359 if (!TSInfo)
5360 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005361 SourceRange ParenOrBraceRange =
5362 (Kind.getKind() == InitializationKind::IK_DirectList)
5363 ? SourceRange(LBraceLoc, RBraceLoc)
5364 : Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005365
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005366 CurInit = new (S.Context) CXXTemporaryObjectExpr(
5367 S.Context, Constructor, TSInfo, ConstructorArgs, ParenOrBraceRange,
5368 HadMultipleCandidates, IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005369 IsStdInitListInitialization, ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00005370 } else {
5371 CXXConstructExpr::ConstructionKind ConstructKind =
5372 CXXConstructExpr::CK_Complete;
5373
5374 if (Entity.getKind() == InitializedEntity::EK_Base) {
5375 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5376 CXXConstructExpr::CK_VirtualBase :
5377 CXXConstructExpr::CK_NonVirtualBase;
5378 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5379 ConstructKind = CXXConstructExpr::CK_Delegating;
5380 }
5381
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005382 // Only get the parenthesis or brace range if it is a list initialization or
5383 // direct construction.
5384 SourceRange ParenOrBraceRange;
5385 if (IsListInitialization)
5386 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
5387 else if (Kind.getKind() == InitializationKind::IK_Direct)
5388 ParenOrBraceRange = Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005389
5390 // If the entity allows NRVO, mark the construction as elidable
5391 // unconditionally.
5392 if (Entity.allowsNRVO())
5393 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5394 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005395 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005396 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005397 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005398 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005399 ConstructorInitRequiresZeroInit,
5400 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005401 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005402 else
5403 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5404 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005405 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005406 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005407 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005408 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005409 ConstructorInitRequiresZeroInit,
5410 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005411 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005412 }
5413 if (CurInit.isInvalid())
5414 return ExprError();
5415
5416 // Only check access if all of that succeeded.
5417 S.CheckConstructorAccess(Loc, Constructor, Entity,
5418 Step.Function.FoundDecl.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005419 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5420 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005421
5422 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005423 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00005424
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005425 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00005426}
5427
Richard Smitheb3cad52012-06-04 22:27:30 +00005428/// Determine whether the specified InitializedEntity definitely has a lifetime
5429/// longer than the current full-expression. Conservatively returns false if
5430/// it's unclear.
5431static bool
5432InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5433 const InitializedEntity *Top = &Entity;
5434 while (Top->getParent())
5435 Top = Top->getParent();
5436
5437 switch (Top->getKind()) {
5438 case InitializedEntity::EK_Variable:
5439 case InitializedEntity::EK_Result:
5440 case InitializedEntity::EK_Exception:
5441 case InitializedEntity::EK_Member:
5442 case InitializedEntity::EK_New:
5443 case InitializedEntity::EK_Base:
5444 case InitializedEntity::EK_Delegating:
5445 return true;
5446
5447 case InitializedEntity::EK_ArrayElement:
5448 case InitializedEntity::EK_VectorElement:
5449 case InitializedEntity::EK_BlockElement:
5450 case InitializedEntity::EK_ComplexElement:
5451 // Could not determine what the full initialization is. Assume it might not
5452 // outlive the full-expression.
5453 return false;
5454
5455 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005456 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00005457 case InitializedEntity::EK_Temporary:
5458 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005459 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005460 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00005461 // The entity being initialized might not outlive the full-expression.
5462 return false;
5463 }
5464
5465 llvm_unreachable("unknown entity kind");
5466}
5467
Richard Smithe6c01442013-06-05 00:46:14 +00005468/// Determine the declaration which an initialized entity ultimately refers to,
5469/// for the purpose of lifetime-extending a temporary bound to a reference in
5470/// the initialization of \p Entity.
David Majnemerdaff3702014-05-01 17:50:17 +00005471static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
5472 const InitializedEntity *Entity,
Craig Topperc3ec1492014-05-26 06:22:03 +00005473 const InitializedEntity *FallbackDecl = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00005474 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00005475 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005476 case InitializedEntity::EK_Variable:
5477 // The temporary [...] persists for the lifetime of the reference
David Majnemerdaff3702014-05-01 17:50:17 +00005478 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005479
5480 case InitializedEntity::EK_Member:
5481 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005482 if (Entity->getParent())
5483 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5484 Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00005485
5486 // except:
5487 // -- A temporary bound to a reference member in a constructor's
5488 // ctor-initializer persists until the constructor exits.
David Majnemerdaff3702014-05-01 17:50:17 +00005489 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005490
5491 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005492 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00005493 // -- A temporary bound to a reference parameter in a function call
5494 // persists until the completion of the full-expression containing
5495 // the call.
5496 case InitializedEntity::EK_Result:
5497 // -- The lifetime of a temporary bound to the returned value in a
5498 // function return statement is not extended; the temporary is
5499 // destroyed at the end of the full-expression in the return statement.
5500 case InitializedEntity::EK_New:
5501 // -- A temporary bound to a reference in a new-initializer persists
5502 // until the completion of the full-expression containing the
5503 // new-initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005504 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005505
5506 case InitializedEntity::EK_Temporary:
5507 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005508 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00005509 // We don't yet know the storage duration of the surrounding temporary.
5510 // Assume it's got full-expression duration for now, it will patch up our
5511 // storage duration if that's not correct.
David Majnemerdaff3702014-05-01 17:50:17 +00005512 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005513
5514 case InitializedEntity::EK_ArrayElement:
5515 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005516 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5517 FallbackDecl);
Richard Smithe6c01442013-06-05 00:46:14 +00005518
5519 case InitializedEntity::EK_Base:
5520 case InitializedEntity::EK_Delegating:
5521 // We can reach this case for aggregate initialization in a constructor:
5522 // struct A { int &&r; };
5523 // struct B : A { B() : A{0} {} };
5524 // In this case, use the innermost field decl as the context.
5525 return FallbackDecl;
5526
5527 case InitializedEntity::EK_BlockElement:
5528 case InitializedEntity::EK_LambdaCapture:
5529 case InitializedEntity::EK_Exception:
5530 case InitializedEntity::EK_VectorElement:
5531 case InitializedEntity::EK_ComplexElement:
David Majnemerdaff3702014-05-01 17:50:17 +00005532 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005533 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00005534 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00005535}
5536
David Majnemerdaff3702014-05-01 17:50:17 +00005537static void performLifetimeExtension(Expr *Init,
5538 const InitializedEntity *ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005539
5540/// Update a glvalue expression that is used as the initializer of a reference
5541/// to note that its lifetime is extended.
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005542/// \return \c true if any temporary had its lifetime extended.
David Majnemerdaff3702014-05-01 17:50:17 +00005543static bool
5544performReferenceExtension(Expr *Init,
5545 const InitializedEntity *ExtendingEntity) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005546 // Walk past any constructs which we can lifetime-extend across.
5547 Expr *Old;
5548 do {
5549 Old = Init;
5550
Richard Smithdbc82492015-01-10 01:28:13 +00005551 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5552 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5553 // This is just redundant braces around an initializer. Step over it.
5554 Init = ILE->getInit(0);
5555 }
5556 }
5557
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005558 // Step over any subobject adjustments; we may have a materialized
5559 // temporary inside them.
5560 SmallVector<const Expr *, 2> CommaLHSs;
5561 SmallVector<SubobjectAdjustment, 2> Adjustments;
5562 Init = const_cast<Expr *>(
5563 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5564
5565 // Per current approach for DR1376, look through casts to reference type
5566 // when performing lifetime extension.
5567 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5568 if (CE->getSubExpr()->isGLValue())
5569 Init = CE->getSubExpr();
5570
5571 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5572 // It's unclear if binding a reference to that xvalue extends the array
5573 // temporary.
5574 } while (Init != Old);
5575
Richard Smithe6c01442013-06-05 00:46:14 +00005576 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5577 // Update the storage duration of the materialized temporary.
5578 // FIXME: Rebuild the expression instead of mutating it.
David Majnemerdaff3702014-05-01 17:50:17 +00005579 ME->setExtendingDecl(ExtendingEntity->getDecl(),
5580 ExtendingEntity->allocateManglingNumber());
5581 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005582 return true;
Richard Smithe6c01442013-06-05 00:46:14 +00005583 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005584
5585 return false;
Richard Smithe6c01442013-06-05 00:46:14 +00005586}
5587
5588/// Update a prvalue expression that is going to be materialized as a
5589/// lifetime-extended temporary.
David Majnemerdaff3702014-05-01 17:50:17 +00005590static void performLifetimeExtension(Expr *Init,
5591 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00005592 // Dig out the expression which constructs the extended temporary.
5593 SmallVector<const Expr *, 2> CommaLHSs;
5594 SmallVector<SubobjectAdjustment, 2> Adjustments;
5595 Init = const_cast<Expr *>(
5596 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5597
Richard Smith736a9472013-06-12 20:42:33 +00005598 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5599 Init = BTE->getSubExpr();
5600
Richard Smithcc1b96d2013-06-12 22:31:48 +00005601 if (CXXStdInitializerListExpr *ILE =
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005602 dyn_cast<CXXStdInitializerListExpr>(Init)) {
David Majnemerdaff3702014-05-01 17:50:17 +00005603 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005604 return;
5605 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00005606
Richard Smithe6c01442013-06-05 00:46:14 +00005607 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00005608 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005609 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
David Majnemerdaff3702014-05-01 17:50:17 +00005610 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005611 return;
5612 }
5613
Richard Smithcc1b96d2013-06-12 22:31:48 +00005614 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005615 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5616
5617 // If we lifetime-extend a braced initializer which is initializing an
5618 // aggregate, and that aggregate contains reference members which are
5619 // bound to temporaries, those temporaries are also lifetime-extended.
5620 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5621 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005622 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005623 else {
5624 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005625 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00005626 if (Index >= ILE->getNumInits())
5627 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005628 if (I->isUnnamedBitfield())
5629 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00005630 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00005631 if (I->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005632 performReferenceExtension(SubInit, ExtendingEntity);
Richard Smith8d7f11d2013-06-27 22:54:33 +00005633 else if (isa<InitListExpr>(SubInit) ||
5634 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smithe6c01442013-06-05 00:46:14 +00005635 // This may be either aggregate-initialization of a member or
5636 // initialization of a std::initializer_list object. Either way,
5637 // we should recursively lifetime-extend that initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005638 performLifetimeExtension(SubInit, ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005639 ++Index;
5640 }
5641 }
5642 }
5643 }
5644}
5645
Richard Smithcc1b96d2013-06-12 22:31:48 +00005646static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5647 const Expr *Init, bool IsInitializerList,
5648 const ValueDecl *ExtendingDecl) {
5649 // Warn if a field lifetime-extends a temporary.
5650 if (isa<FieldDecl>(ExtendingDecl)) {
5651 if (IsInitializerList) {
5652 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5653 << /*at end of constructor*/true;
5654 return;
5655 }
5656
5657 bool IsSubobjectMember = false;
5658 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5659 Ent = Ent->getParent()) {
5660 if (Ent->getKind() != InitializedEntity::EK_Base) {
5661 IsSubobjectMember = true;
5662 break;
5663 }
5664 }
5665 S.Diag(Init->getExprLoc(),
5666 diag::warn_bind_ref_member_to_temporary)
5667 << ExtendingDecl << Init->getSourceRange()
5668 << IsSubobjectMember << IsInitializerList;
5669 if (IsSubobjectMember)
5670 S.Diag(ExtendingDecl->getLocation(),
5671 diag::note_ref_subobject_of_member_declared_here);
5672 else
5673 S.Diag(ExtendingDecl->getLocation(),
5674 diag::note_ref_or_ptr_member_declared_here)
5675 << /*is pointer*/false;
5676 }
5677}
5678
Richard Smithaaa0ec42013-09-21 21:19:19 +00005679static void DiagnoseNarrowingInInitList(Sema &S,
5680 const ImplicitConversionSequence &ICS,
5681 QualType PreNarrowingType,
5682 QualType EntityType,
5683 const Expr *PostInit);
5684
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005685ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005686InitializationSequence::Perform(Sema &S,
5687 const InitializedEntity &Entity,
5688 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00005689 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005690 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005691 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005692 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00005693 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005694 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005695
Sebastian Redld201edf2011-06-05 13:59:11 +00005696 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005697 // If the declaration is a non-dependent, incomplete array type
5698 // that has an initializer, then its type will be completed once
5699 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00005700 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00005701 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00005702 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005703 if (const IncompleteArrayType *ArrayT
5704 = S.Context.getAsIncompleteArrayType(DeclType)) {
5705 // FIXME: We don't currently have the ability to accurately
5706 // compute the length of an initializer list without
5707 // performing full type-checking of the initializer list
5708 // (since we have to determine where braces are implicitly
5709 // introduced and such). So, we fall back to making the array
5710 // type a dependently-sized array type with no specified
5711 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005712 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005713 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00005714
Douglas Gregor51e77d52009-12-10 17:56:55 +00005715 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00005716 if (DeclaratorDecl *DD = Entity.getDecl()) {
5717 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5718 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00005719 if (IncompleteArrayTypeLoc ArrayLoc =
5720 TL.getAs<IncompleteArrayTypeLoc>())
5721 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00005722 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00005723 }
5724
5725 *ResultType
5726 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005727 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005728 ArrayT->getSizeModifier(),
5729 ArrayT->getIndexTypeCVRQualifiers(),
5730 Brackets);
5731 }
5732
5733 }
5734 }
Sebastian Redla9351792012-02-11 23:51:47 +00005735 if (Kind.getKind() == InitializationKind::IK_Direct &&
5736 !Kind.isExplicitCast()) {
5737 // Rebuild the ParenListExpr.
5738 SourceRange ParenRange = Kind.getParenRange();
5739 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005740 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00005741 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00005742 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00005743 Kind.isExplicitCast() ||
5744 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005745 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005746 }
5747
Sebastian Redld201edf2011-06-05 13:59:11 +00005748 // No steps means no initialization.
5749 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005750 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005751
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005752 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005753 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005754 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00005755 // Produce a C++98 compatibility warning if we are initializing a reference
5756 // from an initializer list. For parameters, we produce a better warning
5757 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005758 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00005759 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5760 << Init->getSourceRange();
5761 }
5762
Richard Smitheb3cad52012-06-04 22:27:30 +00005763 // Diagnose cases where we initialize a pointer to an array temporary, and the
5764 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005765 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00005766 Entity.getType()->isPointerType() &&
5767 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005768 Expr *Init = Args[0];
Richard Smitheb3cad52012-06-04 22:27:30 +00005769 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5770 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5771 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5772 << Init->getSourceRange();
5773 }
5774
Douglas Gregor1b303932009-12-22 15:35:07 +00005775 QualType DestType = Entity.getType().getNonReferenceType();
5776 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00005777 // the same as Entity.getDecl()->getType() in cases involving type merging,
5778 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00005779 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00005780 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00005781 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005782
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005783 ExprResult CurInit((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005784
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005785 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00005786 // grab the only argument out the Args and place it into the "current"
5787 // initializer.
5788 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005789 case SK_ResolveAddressOfOverloadedFunction:
5790 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005791 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005792 case SK_CastDerivedToBaseLValue:
5793 case SK_BindReference:
5794 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005795 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00005796 case SK_UserConversion:
5797 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005798 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005799 case SK_QualificationConversionRValue:
Richard Smith77be48a2014-07-31 06:31:19 +00005800 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00005801 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005802 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00005803 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00005804 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00005805 case SK_UnwrapInitList:
5806 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00005807 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00005808 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00005809 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00005810 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00005811 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00005812 case SK_PassByIndirectCopyRestore:
5813 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00005814 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005815 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00005816 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005817 case SK_OCLZeroEvent: {
Douglas Gregore1314a62009-12-18 05:02:21 +00005818 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005819 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00005820 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005821 break;
John McCall34376a62010-12-04 03:47:34 +00005822 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005823
Douglas Gregore1314a62009-12-18 05:02:21 +00005824 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00005825 case SK_ConstructorInitializationFromList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00005826 case SK_StdInitializerListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00005827 case SK_ZeroInitialization:
5828 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005829 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005830
5831 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005832 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005833 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005834 for (step_iterator Step = step_begin(), StepEnd = step_end();
5835 Step != StepEnd; ++Step) {
5836 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005837 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005838
John Wiegley01296292011-04-08 18:41:53 +00005839 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005840
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005841 switch (Step->Kind) {
5842 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005843 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005844 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00005845 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00005846 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5847 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005848 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00005849 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00005850 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005851 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005852
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005853 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005854 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005855 case SK_CastDerivedToBaseLValue: {
5856 // We have a derived-to-base cast that produces either an rvalue or an
5857 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005858
John McCallcf142162010-08-07 06:22:56 +00005859 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00005860
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005861 // Casts to inaccessible base classes are allowed with C-style casts.
5862 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5863 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00005864 CurInit.get()->getLocStart(),
5865 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00005866 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00005867 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005868
John McCall2536c6d2010-08-25 10:28:54 +00005869 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005870 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005871 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005872 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005873 VK_XValue :
5874 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005875 CurInit =
5876 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
5877 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005878 break;
5879 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005880
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005881 case SK_BindReference:
John McCalld25db7e2013-05-06 21:39:12 +00005882 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5883 if (CurInit.get()->refersToBitField()) {
5884 // We don't necessarily have an unambiguous source bit-field.
5885 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005886 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00005887 << Entity.getType().isVolatileQualified()
John McCalld25db7e2013-05-06 21:39:12 +00005888 << (BitField ? BitField->getDeclName() : DeclarationName())
Craig Topperc3ec1492014-05-26 06:22:03 +00005889 << (BitField != nullptr)
John Wiegley01296292011-04-08 18:41:53 +00005890 << CurInit.get()->getSourceRange();
John McCalld25db7e2013-05-06 21:39:12 +00005891 if (BitField)
5892 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5893
John McCallfaf5fb42010-08-26 23:41:50 +00005894 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005895 }
Anders Carlssona91be642010-01-29 02:47:33 +00005896
John Wiegley01296292011-04-08 18:41:53 +00005897 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00005898 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005899 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5900 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00005901 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005902 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005903 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005904 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005905
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005906 // Reference binding does not have any corresponding ASTs.
5907
5908 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005909 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005910 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005911
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005912 // Even though we didn't materialize a temporary, the binding may still
5913 // extend the lifetime of a temporary. This happens if we bind a reference
5914 // to the result of a cast to reference type.
David Majnemerdaff3702014-05-01 17:50:17 +00005915 if (const InitializedEntity *ExtendingEntity =
5916 getEntityForTemporaryLifetimeExtension(&Entity))
5917 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
5918 warnOnLifetimeExtension(S, Entity, CurInit.get(),
5919 /*IsInitializerList=*/false,
5920 ExtendingEntity->getDecl());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005921
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005922 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005923
Richard Smithe6c01442013-06-05 00:46:14 +00005924 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00005925 // Make sure the "temporary" is actually an rvalue.
5926 assert(CurInit.get()->isRValue() && "not a temporary");
5927
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005928 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005929 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005930 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005931
Douglas Gregorfe314812011-06-21 17:03:29 +00005932 // Materialize the temporary into memory.
Richard Smith736a9472013-06-12 20:42:33 +00005933 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Richard Smithe6c01442013-06-05 00:46:14 +00005934 Entity.getType().getNonReferenceType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00005935 Entity.getType()->isLValueReferenceType());
5936
5937 // Maybe lifetime-extend the temporary's subobjects to match the
5938 // entity's lifetime.
5939 if (const InitializedEntity *ExtendingEntity =
5940 getEntityForTemporaryLifetimeExtension(&Entity))
5941 if (performReferenceExtension(MTE, ExtendingEntity))
5942 warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false,
5943 ExtendingEntity->getDecl());
Douglas Gregor58df5092011-06-22 16:12:01 +00005944
5945 // If we're binding to an Objective-C object that has lifetime, we
Richard Smith736a9472013-06-12 20:42:33 +00005946 // need cleanups. Likewise if we're extending this temporary to automatic
5947 // storage duration -- we need to register its cleanup during the
5948 // full-expression's cleanups.
5949 if ((S.getLangOpts().ObjCAutoRefCount &&
5950 MTE->getType()->isObjCLifetimeType()) ||
5951 (MTE->getStorageDuration() == SD_Automatic &&
5952 MTE->getType().isDestructedType()))
Douglas Gregor58df5092011-06-22 16:12:01 +00005953 S.ExprNeedsCleanups = true;
Richard Smith736a9472013-06-12 20:42:33 +00005954
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005955 CurInit = MTE;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005956 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005957 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005958
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005959 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005960 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005961 /*IsExtraneousCopy=*/true);
5962 break;
5963
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005964 case SK_UserConversion: {
5965 // We have a user-defined conversion that invokes either a constructor
5966 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00005967 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00005968 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00005969 FunctionDecl *Fn = Step->Function.Function;
5970 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005971 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00005972 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00005973 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005974 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005975 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00005976 SourceLocation Loc = CurInit.get()->getLocStart();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005977 CurInit.get(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00005978
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005979 // Determine the arguments required to actually perform the constructor
5980 // call.
John Wiegley01296292011-04-08 18:41:53 +00005981 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005982 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00005983 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005984 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005985 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005986
Richard Smithb24f0672012-02-11 19:22:50 +00005987 // Build an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005988 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005989 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005990 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005991 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005992 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005993 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005994 CXXConstructExpr::CK_Complete,
5995 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005996 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005997 return ExprError();
John McCall760af172010-02-01 03:16:54 +00005998
Anders Carlssona01874b2010-04-21 18:47:17 +00005999 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00006000 FoundFn.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00006001 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6002 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006003
John McCalle3027922010-08-25 11:45:40 +00006004 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00006005 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
6006 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
6007 S.IsDerivedFrom(SourceType, Class))
6008 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006009
Douglas Gregor95562572010-04-24 23:45:46 +00006010 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006011 } else {
6012 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00006013 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00006014 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00006015 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00006016 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6017 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006018
6019 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006020 // derived-to-base conversion? I believe the answer is "no", because
6021 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00006022 ExprResult CurInitExprRes =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006023 S.PerformObjectArgumentInitialization(CurInit.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006024 /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006025 FoundFn, Conversion);
6026 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006027 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006028 CurInit = CurInitExprRes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006029
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006030 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006031 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
6032 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006033 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00006034 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006035
John McCalle3027922010-08-25 11:45:40 +00006036 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006037
Alp Toker314cc812014-01-25 16:55:45 +00006038 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006039 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006040
Sebastian Redl112aa822011-07-14 19:07:55 +00006041 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006042 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
6043
6044 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00006045 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00006046 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006047 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00006048 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00006049 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00006050 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00006051 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00006052 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6053 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00006054 }
6055 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006056
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006057 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6058 CastKind, CurInit.get(), nullptr,
6059 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006060 if (MaybeBindToTemp)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006061 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00006062 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006063 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006064 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006065 break;
6066 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006067
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006068 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006069 case SK_QualificationConversionXValue:
6070 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006071 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00006072 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006073 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006074 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006075 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006076 VK_XValue :
6077 VK_RValue);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006078 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006079 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006080 }
6081
Richard Smith77be48a2014-07-31 06:31:19 +00006082 case SK_AtomicConversion: {
6083 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
6084 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6085 CK_NonAtomicToAtomic, VK_RValue);
6086 break;
6087 }
6088
Jordan Roseb1312a52013-04-11 00:58:58 +00006089 case SK_LValueToRValue: {
6090 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006091 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
6092 CK_LValueToRValue, CurInit.get(),
6093 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00006094 break;
6095 }
6096
Richard Smithaaa0ec42013-09-21 21:19:19 +00006097 case SK_ConversionSequence:
6098 case SK_ConversionSequenceNoNarrowing: {
6099 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00006100 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
6101 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00006102 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00006103 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00006104 ExprResult CurInitExprRes =
6105 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00006106 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00006107 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006108 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006109 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00006110
6111 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
6112 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
6113 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
6114 CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006115 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00006116 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006117
Douglas Gregor51e77d52009-12-10 17:56:55 +00006118 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00006119 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006120 // If we're not initializing the top-level entity, we need to create an
6121 // InitializeTemporary entity for our target type.
6122 QualType Ty = Step->Type;
6123 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00006124 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00006125 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
6126 InitListChecker PerformInitList(S, InitEntity,
Richard Smithde229232013-06-06 11:41:05 +00006127 InitList, Ty, /*VerifyOnly=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006128 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00006129 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00006130
Richard Smithcc1b96d2013-06-12 22:31:48 +00006131 // Hack: We must update *ResultType if available in order to set the
6132 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
6133 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
6134 if (ResultType &&
6135 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00006136 if ((*ResultType)->isRValueReferenceType())
6137 Ty = S.Context.getRValueReferenceType(Ty);
6138 else if ((*ResultType)->isLValueReferenceType())
6139 Ty = S.Context.getLValueReferenceType(Ty,
6140 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
6141 *ResultType = Ty;
6142 }
6143
6144 InitListExpr *StructuredInitList =
6145 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006146 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00006147 CurInit = shouldBindAsTemporary(InitEntity)
6148 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006149 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006150 break;
6151 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006152
Richard Smith53324112014-07-16 21:33:43 +00006153 case SK_ConstructorInitializationFromList: {
Sebastian Redl5a41f682012-02-12 16:37:24 +00006154 // When an initializer list is passed for a parameter of type "reference
6155 // to object", we don't get an EK_Temporary entity, but instead an
6156 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00006157 // FIXME: This is a hack. What we really should do is create a user
6158 // conversion step for this case, but this makes it considerably more
6159 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00006160 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6161 Entity.getType().getNonReferenceType());
6162 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00006163 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006164 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00006165 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6166 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006167 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00006168 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6169 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006170 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006171 ConstructorInitRequiresZeroInit,
Richard Smith53324112014-07-16 21:33:43 +00006172 /*IsListInitialization*/true,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006173 /*IsStdInitListInit*/false,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006174 InitList->getLBraceLoc(),
6175 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00006176 break;
6177 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006178
Sebastian Redl29526f02011-11-27 16:50:07 +00006179 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006180 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00006181 break;
6182
6183 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006184 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00006185 InitListExpr *Syntactic = Step->WrappingSyntacticList;
6186 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00006187 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00006188 ILE->setSyntacticForm(Syntactic);
6189 ILE->setType(E->getType());
6190 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006191 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00006192 break;
6193 }
6194
Richard Smith53324112014-07-16 21:33:43 +00006195 case SK_ConstructorInitialization:
Richard Smithf8adcdc2014-07-17 05:12:35 +00006196 case SK_StdInitializerListConstructorCall: {
Sebastian Redl99f66162012-02-19 12:27:56 +00006197 // When an initializer list is passed for a parameter of type "reference
6198 // to object", we don't get an EK_Temporary entity, but instead an
6199 // EK_Parameter entity with reference type.
6200 // FIXME: This is a hack. What we really should do is create a user
6201 // conversion step for this case, but this makes it considerably more
6202 // complicated. For now, this will do.
6203 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6204 Entity.getType().getNonReferenceType());
6205 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf8adcdc2014-07-17 05:12:35 +00006206 bool IsStdInitListInit =
6207 Step->Kind == SK_StdInitializerListConstructorCall;
Richard Smith53324112014-07-16 21:33:43 +00006208 CurInit = PerformConstructorInitialization(
6209 S, UseTemporary ? TempEntity : Entity, Kind, Args, *Step,
6210 ConstructorInitRequiresZeroInit,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006211 /*IsListInitialization*/IsStdInitListInit,
6212 /*IsStdInitListInitialization*/IsStdInitListInit,
Richard Smith53324112014-07-16 21:33:43 +00006213 /*LBraceLoc*/SourceLocation(),
6214 /*RBraceLoc*/SourceLocation());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006215 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00006216 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006217
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006218 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006219 step_iterator NextStep = Step;
6220 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006221 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00006222 (NextStep->Kind == SK_ConstructorInitialization ||
Richard Smith53324112014-07-16 21:33:43 +00006223 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006224 // The need for zero-initialization is recorded directly into
6225 // the call to the object's constructor within the next step.
6226 ConstructorInitRequiresZeroInit = true;
6227 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006228 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006229 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00006230 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6231 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006232 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00006233 Kind.getRange().getBegin());
6234
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006235 CurInit = new (S.Context) CXXScalarValueInitExpr(
6236 TSInfo->getType().getNonLValueExprType(S.Context), TSInfo,
6237 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006238 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006239 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006240 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006241 break;
6242 }
Douglas Gregore1314a62009-12-18 05:02:21 +00006243
6244 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00006245 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006246 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00006247 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00006248 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6249 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00006250 if (Result.isInvalid())
6251 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006252 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00006253
6254 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006255 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00006256 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006257 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00006258 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00006259 == Sema::Compatible)
6260 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00006261 if (CurInitExprRes.isInvalid())
6262 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006263 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00006264
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006265 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00006266 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6267 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00006268 CurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00006269 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006270 &Complained)) {
6271 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00006272 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006273 } else if (Complained)
6274 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00006275 break;
6276 }
Eli Friedman78275202009-12-19 08:11:05 +00006277
6278 case SK_StringInit: {
6279 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00006280 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00006281 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00006282 break;
6283 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006284
6285 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006286 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00006287 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00006288 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006289 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006290
6291 case SK_ArrayInit:
6292 // Okay: we checked everything before creating this step. Note that
6293 // this is a GNU extension.
6294 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00006295 << Step->Type << CurInit.get()->getType()
6296 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00006297
6298 // If the destination type is an incomplete array type, update the
6299 // type accordingly.
6300 if (ResultType) {
6301 if (const IncompleteArrayType *IncompleteDest
6302 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6303 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00006304 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00006305 *ResultType = S.Context.getConstantArrayType(
6306 IncompleteDest->getElementType(),
6307 ConstantSource->getSize(),
6308 ArrayType::Normal, 0);
6309 }
6310 }
6311 }
John McCall31168b02011-06-15 23:02:42 +00006312 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006313
Richard Smithebeed412012-02-15 22:38:09 +00006314 case SK_ParenthesizedArrayInit:
6315 // Okay: we checked everything before creating this step. Note that
6316 // this is a GNU extension.
6317 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6318 << CurInit.get()->getSourceRange();
6319 break;
6320
John McCall31168b02011-06-15 23:02:42 +00006321 case SK_PassByIndirectCopyRestore:
6322 case SK_PassByIndirectRestore:
6323 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006324 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
6325 CurInit.get(), Step->Type,
6326 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00006327 break;
6328
6329 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006330 CurInit =
6331 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
6332 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00006333 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006334
6335 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006336 S.Diag(CurInit.get()->getExprLoc(),
6337 diag::warn_cxx98_compat_initializer_list_init)
6338 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00006339
Richard Smithcc1b96d2013-06-12 22:31:48 +00006340 // Materialize the temporary into memory.
6341 MaterializeTemporaryExpr *MTE = new (S.Context)
6342 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00006343 /*BoundToLvalueReference=*/false);
6344
6345 // Maybe lifetime-extend the array temporary's subobjects to match the
6346 // entity's lifetime.
6347 if (const InitializedEntity *ExtendingEntity =
6348 getEntityForTemporaryLifetimeExtension(&Entity))
6349 if (performReferenceExtension(MTE, ExtendingEntity))
6350 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6351 /*IsInitializerList=*/true,
6352 ExtendingEntity->getDecl());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006353
6354 // Wrap it in a construction of a std::initializer_list<T>.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006355 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006356
6357 // Bind the result, in case the library has given initializer_list a
6358 // non-trivial destructor.
6359 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006360 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00006361 break;
6362 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006363
Guy Benyei61054192013-02-07 10:55:47 +00006364 case SK_OCLSamplerInit: {
6365 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006366 "Sampler initialization on non-sampler type.");
Guy Benyei61054192013-02-07 10:55:47 +00006367
6368 QualType SourceType = CurInit.get()->getType();
Guy Benyei61054192013-02-07 10:55:47 +00006369
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006370 if (Entity.isParameterKind()) {
Guy Benyei61054192013-02-07 10:55:47 +00006371 if (!SourceType->isSamplerT())
6372 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6373 << SourceType;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006374 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
Guy Benyei61054192013-02-07 10:55:47 +00006375 llvm_unreachable("Invalid EntityKind!");
6376 }
6377
6378 break;
6379 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006380 case SK_OCLZeroEvent: {
6381 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006382 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006383
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006384 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006385 CK_ZeroToOCLEvent,
6386 CurInit.get()->getValueKind());
6387 break;
6388 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006389 }
6390 }
John McCall1f425642010-11-11 03:21:53 +00006391
6392 // Diagnose non-fatal problems with the completed initialization.
6393 if (Entity.getKind() == InitializedEntity::EK_Member &&
6394 cast<FieldDecl>(Entity.getDecl())->isBitField())
6395 S.CheckBitFieldInitialization(Kind.getLocation(),
6396 cast<FieldDecl>(Entity.getDecl()),
6397 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006398
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006399 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006400}
6401
Richard Smith593f9932012-12-08 02:01:17 +00006402/// Somewhere within T there is an uninitialized reference subobject.
6403/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00006404static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6405 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00006406 if (T->isReferenceType()) {
6407 S.Diag(Loc, diag::err_reference_without_init)
6408 << T.getNonReferenceType();
6409 return true;
6410 }
6411
6412 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6413 if (!RD || !RD->hasUninitializedReferenceMember())
6414 return false;
6415
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006416 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00006417 if (FI->isUnnamedBitfield())
6418 continue;
6419
6420 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6421 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6422 return true;
6423 }
6424 }
6425
Aaron Ballman574705e2014-03-13 15:41:46 +00006426 for (const auto &BI : RD->bases()) {
6427 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00006428 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6429 return true;
6430 }
6431 }
6432
6433 return false;
6434}
6435
6436
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006437//===----------------------------------------------------------------------===//
6438// Diagnose initialization failures
6439//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00006440
6441/// Emit notes associated with an initialization that failed due to a
6442/// "simple" conversion failure.
6443static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6444 Expr *op) {
6445 QualType destType = entity.getType();
6446 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6447 op->getType()->isObjCObjectPointerType()) {
6448
6449 // Emit a possible note about the conversion failing because the
6450 // operand is a message send with a related result type.
6451 S.EmitRelatedResultTypeNote(op);
6452
6453 // Emit a possible note about a return failing because we're
6454 // expecting a related result type.
6455 if (entity.getKind() == InitializedEntity::EK_Result)
6456 S.EmitRelatedResultTypeNoteForReturn(destType);
6457 }
6458}
6459
Richard Smith0449aaf2013-11-21 23:30:57 +00006460static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6461 InitListExpr *InitList) {
6462 QualType DestType = Entity.getType();
6463
6464 QualType E;
6465 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6466 QualType ArrayType = S.Context.getConstantArrayType(
6467 E.withConst(),
6468 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6469 InitList->getNumInits()),
6470 clang::ArrayType::Normal, 0);
6471 InitializedEntity HiddenArray =
6472 InitializedEntity::InitializeTemporary(ArrayType);
6473 return diagnoseListInit(S, HiddenArray, InitList);
6474 }
6475
Richard Smith8d082d12014-09-04 22:13:39 +00006476 if (DestType->isReferenceType()) {
6477 // A list-initialization failure for a reference means that we tried to
6478 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
6479 // inner initialization failed.
6480 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
6481 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
6482 SourceLocation Loc = InitList->getLocStart();
6483 if (auto *D = Entity.getDecl())
6484 Loc = D->getLocation();
6485 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
6486 return;
6487 }
6488
Richard Smith0449aaf2013-11-21 23:30:57 +00006489 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
6490 /*VerifyOnly=*/false);
6491 assert(DiagnoseInitList.HadError() &&
6492 "Inconsistent init list check result.");
6493}
6494
Nico Weber9386c822014-07-23 05:16:10 +00006495/// Prints a fixit for adding a null initializer for |Entity|. Call this only
6496/// right after emitting a diagnostic.
6497static void maybeEmitZeroInitializationFixit(Sema &S,
6498 InitializationSequence &Sequence,
6499 const InitializedEntity &Entity) {
6500 if (Entity.getKind() != InitializedEntity::EK_Variable)
6501 return;
6502
6503 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
6504 if (VD->getInit() || VD->getLocEnd().isMacroID())
6505 return;
6506
6507 QualType VariableTy = VD->getType().getCanonicalType();
6508 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
6509 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
6510
6511 S.Diag(Loc, diag::note_add_initializer)
6512 << VD << FixItHint::CreateInsertion(Loc, Init);
6513}
6514
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006515bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006516 const InitializedEntity &Entity,
6517 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006518 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006519 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006520 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006521
Douglas Gregor1b303932009-12-22 15:35:07 +00006522 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006523 switch (Failure) {
6524 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006525 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006526 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00006527 // Dig out the reference subobject which is uninitialized and diagnose it.
6528 // If this is value-initialization, this could be nested some way within
6529 // the target type.
6530 assert(Kind.getKind() == InitializationKind::IK_Value ||
6531 DestType->isReferenceType());
6532 bool Diagnosed =
6533 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6534 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6535 (void)Diagnosed;
6536 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006537 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006538 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006539 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006540
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006541 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006542 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006543 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006544 case FK_ArrayNeedsInitListOrStringLiteral:
6545 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6546 break;
6547 case FK_ArrayNeedsInitListOrWideStringLiteral:
6548 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6549 break;
6550 case FK_NarrowStringIntoWideCharArray:
6551 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6552 break;
6553 case FK_WideStringIntoCharArray:
6554 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6555 break;
6556 case FK_IncompatWideStringIntoWideChar:
6557 S.Diag(Kind.getLocation(),
6558 diag::err_array_init_incompat_wide_string_into_wchar);
6559 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006560 case FK_ArrayTypeMismatch:
6561 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00006562 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00006563 (Failure == FK_ArrayTypeMismatch
6564 ? diag::err_array_init_different_type
6565 : diag::err_array_init_non_constant_array))
6566 << DestType.getNonReferenceType()
6567 << Args[0]->getType()
6568 << Args[0]->getSourceRange();
6569 break;
6570
John McCalla59dc2f2012-01-05 00:13:19 +00006571 case FK_VariableLengthArrayHasInitializer:
6572 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6573 << Args[0]->getSourceRange();
6574 break;
6575
John McCall16df1e52010-03-30 21:47:33 +00006576 case FK_AddressOfOverloadFailed: {
6577 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006578 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006579 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00006580 true,
6581 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006582 break;
John McCall16df1e52010-03-30 21:47:33 +00006583 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006584
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006585 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00006586 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006587 switch (FailedOverloadResult) {
6588 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00006589 if (Failure == FK_UserConversionOverloadFailed)
6590 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6591 << Args[0]->getType() << DestType
6592 << Args[0]->getSourceRange();
6593 else
6594 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6595 << DestType << Args[0]->getType()
6596 << Args[0]->getSourceRange();
6597
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006598 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006599 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006600
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006601 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00006602 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00006603 DestType.getNonReferenceType(),
6604 diag::err_typecheck_nonviable_condition_incomplete,
6605 Args[0]->getType(), Args[0]->getSourceRange()))
6606 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6607 << Args[0]->getType() << Args[0]->getSourceRange()
6608 << DestType.getNonReferenceType();
6609
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006610 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006611 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006612
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006613 case OR_Deleted: {
6614 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6615 << Args[0]->getType() << DestType.getNonReferenceType()
6616 << Args[0]->getSourceRange();
6617 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006618 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00006619 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6620 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006621 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00006622 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006623 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006624 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006625 }
6626 break;
6627 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006628
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006629 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006630 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006631 }
6632 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006633
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006634 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00006635 if (isa<InitListExpr>(Args[0])) {
6636 S.Diag(Kind.getLocation(),
6637 diag::err_lvalue_reference_bind_to_initlist)
6638 << DestType.getNonReferenceType().isVolatileQualified()
6639 << DestType.getNonReferenceType()
6640 << Args[0]->getSourceRange();
6641 break;
6642 }
6643 // Intentional fallthrough
6644
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006645 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006646 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006647 Failure == FK_NonConstLValueReferenceBindingToTemporary
6648 ? diag::err_lvalue_reference_bind_to_temporary
6649 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00006650 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006651 << DestType.getNonReferenceType()
6652 << Args[0]->getType()
6653 << Args[0]->getSourceRange();
6654 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006655
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006656 case FK_RValueReferenceBindingToLValue:
6657 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00006658 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006659 << Args[0]->getSourceRange();
6660 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006661
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006662 case FK_ReferenceInitDropsQualifiers:
6663 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6664 << DestType.getNonReferenceType()
6665 << Args[0]->getType()
6666 << Args[0]->getSourceRange();
6667 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006668
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006669 case FK_ReferenceInitFailed:
6670 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6671 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00006672 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006673 << Args[0]->getType()
6674 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00006675 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006676 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006677
Douglas Gregorb491ed32011-02-19 21:32:49 +00006678 case FK_ConversionFailed: {
6679 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00006680 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00006681 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006682 << DestType
John McCall086a4642010-11-24 05:12:34 +00006683 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00006684 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006685 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00006686 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6687 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00006688 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00006689 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00006690 }
John Wiegley01296292011-04-08 18:41:53 +00006691
6692 case FK_ConversionFromPropertyFailed:
6693 // No-op. This error has already been reported.
6694 break;
6695
Douglas Gregor51e77d52009-12-10 17:56:55 +00006696 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00006697 SourceRange R;
6698
6699 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00006700 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00006701 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006702 else
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006703 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00006704
Alp Tokerb6cc5922014-05-03 03:45:55 +00006705 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00006706 if (Kind.isCStyleOrFunctionalCast())
6707 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6708 << R;
6709 else
6710 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6711 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006712 break;
6713 }
6714
6715 case FK_ReferenceBindingToInitList:
6716 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6717 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6718 break;
6719
6720 case FK_InitListBadDestinationType:
6721 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6722 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6723 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006724
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006725 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006726 case FK_ConstructorOverloadFailed: {
6727 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006728 if (Args.size())
6729 ArgsRange = SourceRange(Args.front()->getLocStart(),
6730 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006731
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006732 if (Failure == FK_ListConstructorOverloadFailed) {
Nico Weber9709ebf2014-07-08 23:54:25 +00006733 assert(Args.size() == 1 &&
6734 "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006735 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006736 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006737 }
6738
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006739 // FIXME: Using "DestType" for the entity we're printing is probably
6740 // bad.
6741 switch (FailedOverloadResult) {
6742 case OR_Ambiguous:
6743 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6744 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006745 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006746 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006747
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006748 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006749 if (Kind.getKind() == InitializationKind::IK_Default &&
6750 (Entity.getKind() == InitializedEntity::EK_Base ||
6751 Entity.getKind() == InitializedEntity::EK_Member) &&
6752 isa<CXXConstructorDecl>(S.CurContext)) {
6753 // This is implicit default initialization of a member or
6754 // base within a constructor. If no viable function was
6755 // found, notify the user that she needs to explicitly
6756 // initialize this base/member.
6757 CXXConstructorDecl *Constructor
6758 = cast<CXXConstructorDecl>(S.CurContext);
6759 if (Entity.getKind() == InitializedEntity::EK_Base) {
6760 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006761 << (Constructor->getInheritedConstructor() ? 2 :
6762 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006763 << S.Context.getTypeDeclType(Constructor->getParent())
6764 << /*base=*/0
6765 << Entity.getType();
6766
6767 RecordDecl *BaseDecl
6768 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6769 ->getDecl();
6770 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6771 << S.Context.getTagDeclType(BaseDecl);
6772 } else {
6773 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006774 << (Constructor->getInheritedConstructor() ? 2 :
6775 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006776 << S.Context.getTypeDeclType(Constructor->getParent())
6777 << /*member=*/1
6778 << Entity.getName();
Alp Toker2afa8782014-05-28 12:20:14 +00006779 S.Diag(Entity.getDecl()->getLocation(),
6780 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006781
6782 if (const RecordType *Record
6783 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006784 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006785 diag::note_previous_decl)
6786 << S.Context.getTagDeclType(Record->getDecl());
6787 }
6788 break;
6789 }
6790
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006791 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6792 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006793 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006794 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006795
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006796 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006797 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006798 OverloadingResult Ovl
6799 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00006800 if (Ovl != OR_Deleted) {
6801 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6802 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006803 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00006804 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006805 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00006806
6807 // If this is a defaulted or implicitly-declared function, then
6808 // it was implicitly deleted. Make it clear that the deletion was
6809 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00006810 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006811 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00006812 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006813 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00006814 else
6815 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6816 << true << DestType << ArgsRange;
6817
6818 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006819 break;
6820 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006821
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006822 case OR_Success:
6823 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006824 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006825 }
David Blaikie60deeee2012-01-17 08:24:58 +00006826 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006827
Douglas Gregor85dabae2009-12-16 01:38:02 +00006828 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006829 if (Entity.getKind() == InitializedEntity::EK_Member &&
6830 isa<CXXConstructorDecl>(S.CurContext)) {
6831 // This is implicit default-initialization of a const member in
6832 // a constructor. Complain that it needs to be explicitly
6833 // initialized.
6834 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6835 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006836 << (Constructor->getInheritedConstructor() ? 2 :
6837 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006838 << S.Context.getTypeDeclType(Constructor->getParent())
6839 << /*const=*/1
6840 << Entity.getName();
6841 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6842 << Entity.getName();
6843 } else {
6844 S.Diag(Kind.getLocation(), diag::err_default_init_const)
Nico Weber9386c822014-07-23 05:16:10 +00006845 << DestType << (bool)DestType->getAs<RecordType>();
6846 maybeEmitZeroInitializationFixit(S, *this, Entity);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006847 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00006848 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006849
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006850 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00006851 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006852 diag::err_init_incomplete_type);
6853 break;
6854
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006855 case FK_ListInitializationFailed: {
6856 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00006857 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6858 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006859 break;
6860 }
John McCall4124c492011-10-17 18:40:02 +00006861
6862 case FK_PlaceholderType: {
6863 // FIXME: Already diagnosed!
6864 break;
6865 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00006866
Sebastian Redl048a6d72012-04-01 19:54:59 +00006867 case FK_ExplicitConstructor: {
6868 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6869 << Args[0]->getSourceRange();
6870 OverloadCandidateSet::iterator Best;
6871 OverloadingResult Ovl
6872 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00006873 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00006874 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6875 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6876 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6877 break;
6878 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006879 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006880
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006881 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006882 return true;
6883}
Douglas Gregore1314a62009-12-18 05:02:21 +00006884
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006885void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006886 switch (SequenceKind) {
6887 case FailedSequence: {
6888 OS << "Failed sequence: ";
6889 switch (Failure) {
6890 case FK_TooManyInitsForReference:
6891 OS << "too many initializers for reference";
6892 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006893
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006894 case FK_ArrayNeedsInitList:
6895 OS << "array requires initializer list";
6896 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006897
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006898 case FK_ArrayNeedsInitListOrStringLiteral:
6899 OS << "array requires initializer list or string literal";
6900 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006901
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006902 case FK_ArrayNeedsInitListOrWideStringLiteral:
6903 OS << "array requires initializer list or wide string literal";
6904 break;
6905
6906 case FK_NarrowStringIntoWideCharArray:
6907 OS << "narrow string into wide char array";
6908 break;
6909
6910 case FK_WideStringIntoCharArray:
6911 OS << "wide string into char array";
6912 break;
6913
6914 case FK_IncompatWideStringIntoWideChar:
6915 OS << "incompatible wide string into wide char array";
6916 break;
6917
Douglas Gregore2f943b2011-02-22 18:29:51 +00006918 case FK_ArrayTypeMismatch:
6919 OS << "array type mismatch";
6920 break;
6921
6922 case FK_NonConstantArrayInit:
6923 OS << "non-constant array initializer";
6924 break;
6925
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006926 case FK_AddressOfOverloadFailed:
6927 OS << "address of overloaded function failed";
6928 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006929
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006930 case FK_ReferenceInitOverloadFailed:
6931 OS << "overload resolution for reference initialization failed";
6932 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006933
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006934 case FK_NonConstLValueReferenceBindingToTemporary:
6935 OS << "non-const lvalue reference bound to temporary";
6936 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006937
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006938 case FK_NonConstLValueReferenceBindingToUnrelated:
6939 OS << "non-const lvalue reference bound to unrelated type";
6940 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006941
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006942 case FK_RValueReferenceBindingToLValue:
6943 OS << "rvalue reference bound to an lvalue";
6944 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006945
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006946 case FK_ReferenceInitDropsQualifiers:
6947 OS << "reference initialization drops qualifiers";
6948 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006949
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006950 case FK_ReferenceInitFailed:
6951 OS << "reference initialization failed";
6952 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006953
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006954 case FK_ConversionFailed:
6955 OS << "conversion failed";
6956 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006957
John Wiegley01296292011-04-08 18:41:53 +00006958 case FK_ConversionFromPropertyFailed:
6959 OS << "conversion from property failed";
6960 break;
6961
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006962 case FK_TooManyInitsForScalar:
6963 OS << "too many initializers for scalar";
6964 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006965
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006966 case FK_ReferenceBindingToInitList:
6967 OS << "referencing binding to initializer list";
6968 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006969
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006970 case FK_InitListBadDestinationType:
6971 OS << "initializer list for non-aggregate, non-scalar type";
6972 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006973
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006974 case FK_UserConversionOverloadFailed:
6975 OS << "overloading failed for user-defined conversion";
6976 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006977
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006978 case FK_ConstructorOverloadFailed:
6979 OS << "constructor overloading failed";
6980 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006981
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006982 case FK_DefaultInitOfConst:
6983 OS << "default initialization of a const variable";
6984 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006985
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00006986 case FK_Incomplete:
6987 OS << "initialization of incomplete type";
6988 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006989
6990 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006991 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00006992 break;
6993
John McCalla59dc2f2012-01-05 00:13:19 +00006994 case FK_VariableLengthArrayHasInitializer:
6995 OS << "variable length array has an initializer";
6996 break;
6997
John McCall4124c492011-10-17 18:40:02 +00006998 case FK_PlaceholderType:
6999 OS << "initializer expression isn't contextually valid";
7000 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00007001
7002 case FK_ListConstructorOverloadFailed:
7003 OS << "list constructor overloading failed";
7004 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007005
Sebastian Redl048a6d72012-04-01 19:54:59 +00007006 case FK_ExplicitConstructor:
7007 OS << "list copy initialization chose explicit constructor";
7008 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007009 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007010 OS << '\n';
7011 return;
7012 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007013
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007014 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00007015 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007016 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007017
Sebastian Redld201edf2011-06-05 13:59:11 +00007018 case NormalSequence:
7019 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007020 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007021 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007022
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007023 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
7024 if (S != step_begin()) {
7025 OS << " -> ";
7026 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007027
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007028 switch (S->Kind) {
7029 case SK_ResolveAddressOfOverloadedFunction:
7030 OS << "resolve address of overloaded function";
7031 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007032
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007033 case SK_CastDerivedToBaseRValue:
7034 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
7035 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007036
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007037 case SK_CastDerivedToBaseXValue:
7038 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
7039 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007040
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007041 case SK_CastDerivedToBaseLValue:
7042 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
7043 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007044
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007045 case SK_BindReference:
7046 OS << "bind reference to lvalue";
7047 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007048
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007049 case SK_BindReferenceToTemporary:
7050 OS << "bind reference to a temporary";
7051 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007052
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007053 case SK_ExtraneousCopyToTemporary:
7054 OS << "extraneous C++03 copy to temporary";
7055 break;
7056
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007057 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007058 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007059 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007060
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007061 case SK_QualificationConversionRValue:
7062 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00007063 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007064
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007065 case SK_QualificationConversionXValue:
7066 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00007067 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007068
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007069 case SK_QualificationConversionLValue:
7070 OS << "qualification conversion (lvalue)";
7071 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007072
Richard Smith77be48a2014-07-31 06:31:19 +00007073 case SK_AtomicConversion:
7074 OS << "non-atomic-to-atomic conversion";
7075 break;
7076
Jordan Roseb1312a52013-04-11 00:58:58 +00007077 case SK_LValueToRValue:
7078 OS << "load (lvalue to rvalue)";
7079 break;
7080
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007081 case SK_ConversionSequence:
7082 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00007083 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007084 OS << ")";
7085 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007086
Richard Smithaaa0ec42013-09-21 21:19:19 +00007087 case SK_ConversionSequenceNoNarrowing:
7088 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00007089 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00007090 OS << ")";
7091 break;
7092
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007093 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007094 OS << "list aggregate initialization";
7095 break;
7096
Sebastian Redl29526f02011-11-27 16:50:07 +00007097 case SK_UnwrapInitList:
7098 OS << "unwrap reference initializer list";
7099 break;
7100
7101 case SK_RewrapInitList:
7102 OS << "rewrap reference initializer list";
7103 break;
7104
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007105 case SK_ConstructorInitialization:
7106 OS << "constructor initialization";
7107 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007108
Richard Smith53324112014-07-16 21:33:43 +00007109 case SK_ConstructorInitializationFromList:
7110 OS << "list initialization via constructor";
7111 break;
7112
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007113 case SK_ZeroInitialization:
7114 OS << "zero initialization";
7115 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007116
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007117 case SK_CAssignment:
7118 OS << "C assignment";
7119 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007120
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007121 case SK_StringInit:
7122 OS << "string initialization";
7123 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007124
7125 case SK_ObjCObjectConversion:
7126 OS << "Objective-C object conversion";
7127 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007128
7129 case SK_ArrayInit:
7130 OS << "array initialization";
7131 break;
John McCall31168b02011-06-15 23:02:42 +00007132
Richard Smithebeed412012-02-15 22:38:09 +00007133 case SK_ParenthesizedArrayInit:
7134 OS << "parenthesized array initialization";
7135 break;
7136
John McCall31168b02011-06-15 23:02:42 +00007137 case SK_PassByIndirectCopyRestore:
7138 OS << "pass by indirect copy and restore";
7139 break;
7140
7141 case SK_PassByIndirectRestore:
7142 OS << "pass by indirect restore";
7143 break;
7144
7145 case SK_ProduceObjCObject:
7146 OS << "Objective-C object retension";
7147 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007148
7149 case SK_StdInitializerList:
7150 OS << "std::initializer_list from initializer list";
7151 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007152
Richard Smithf8adcdc2014-07-17 05:12:35 +00007153 case SK_StdInitializerListConstructorCall:
7154 OS << "list initialization from std::initializer_list";
7155 break;
7156
Guy Benyei61054192013-02-07 10:55:47 +00007157 case SK_OCLSamplerInit:
7158 OS << "OpenCL sampler_t from integer constant";
7159 break;
7160
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007161 case SK_OCLZeroEvent:
7162 OS << "OpenCL event_t from zero";
7163 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007164 }
Richard Smith6b216962013-02-05 05:52:24 +00007165
7166 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007167 }
Richard Smith6b216962013-02-05 05:52:24 +00007168
7169 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007170}
7171
7172void InitializationSequence::dump() const {
7173 dump(llvm::errs());
7174}
7175
Richard Smithaaa0ec42013-09-21 21:19:19 +00007176static void DiagnoseNarrowingInInitList(Sema &S,
7177 const ImplicitConversionSequence &ICS,
7178 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007179 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007180 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007181 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00007182 switch (ICS.getKind()) {
7183 case ImplicitConversionSequence::StandardConversion:
7184 SCS = &ICS.Standard;
7185 break;
7186 case ImplicitConversionSequence::UserDefinedConversion:
7187 SCS = &ICS.UserDefined.After;
7188 break;
7189 case ImplicitConversionSequence::AmbiguousConversion:
7190 case ImplicitConversionSequence::EllipsisConversion:
7191 case ImplicitConversionSequence::BadConversion:
7192 return;
7193 }
7194
Richard Smith66e05fe2012-01-18 05:21:49 +00007195 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
7196 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00007197 QualType ConstantType;
7198 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
7199 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00007200 case NK_Not_Narrowing:
7201 // No narrowing occurred.
7202 return;
7203
7204 case NK_Type_Narrowing:
7205 // This was a floating-to-integer conversion, which is always considered a
7206 // narrowing conversion even if the value is a constant and can be
7207 // represented exactly as an integer.
7208 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007209 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7210 ? diag::warn_init_list_type_narrowing
7211 : diag::ext_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007212 << PostInit->getSourceRange()
7213 << PreNarrowingType.getLocalUnqualifiedType()
7214 << EntityType.getLocalUnqualifiedType();
7215 break;
7216
7217 case NK_Constant_Narrowing:
7218 // A constant value was narrowed.
7219 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007220 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7221 ? diag::warn_init_list_constant_narrowing
7222 : diag::ext_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007223 << PostInit->getSourceRange()
Richard Smith5614ca72012-03-23 23:55:39 +00007224 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007225 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007226 break;
7227
7228 case NK_Variable_Narrowing:
7229 // A variable's value may have been narrowed.
7230 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007231 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7232 ? diag::warn_init_list_variable_narrowing
7233 : diag::ext_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007234 << PostInit->getSourceRange()
7235 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007236 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007237 break;
7238 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007239
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007240 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007241 llvm::raw_svector_ostream OS(StaticCast);
7242 OS << "static_cast<";
7243 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7244 // It's important to use the typedef's name if there is one so that the
7245 // fixit doesn't break code using types like int64_t.
7246 //
7247 // FIXME: This will break if the typedef requires qualification. But
7248 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007249 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007250 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00007251 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007252 else {
7253 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
7254 // with a broken cast.
7255 return;
7256 }
7257 OS << ">(";
Alp Tokerb0869032014-05-17 01:13:18 +00007258 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007259 << PostInit->getSourceRange()
7260 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
7261 << FixItHint::CreateInsertion(
7262 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007263}
7264
Douglas Gregore1314a62009-12-18 05:02:21 +00007265//===----------------------------------------------------------------------===//
7266// Initialization helper functions
7267//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00007268bool
7269Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7270 ExprResult Init) {
7271 if (Init.isInvalid())
7272 return false;
7273
7274 Expr *InitE = Init.get();
7275 assert(InitE && "No initialization expression");
7276
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00007277 InitializationKind Kind
7278 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007279 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00007280 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00007281}
7282
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007283ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00007284Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7285 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007286 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00007287 bool TopLevelOfInitList,
7288 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00007289 if (Init.isInvalid())
7290 return ExprError();
7291
John McCall1f425642010-11-11 03:21:53 +00007292 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00007293 assert(InitE && "No initialization expression?");
7294
7295 if (EqualLoc.isInvalid())
7296 EqualLoc = InitE->getLocStart();
7297
7298 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00007299 EqualLoc,
7300 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00007301 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007302 Init.get();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007303
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007304 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00007305
Richard Smith66e05fe2012-01-18 05:21:49 +00007306 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00007307}