blob: 30471fbc9ad1c3386178fe017206bb4bddef373a [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.
152 uint64_t StrLength =
153 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
154
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(),
Eli Friedman554eba92011-04-11 00:23:45 +0000192 diag::warn_initializer_string_for_char_array_too_long)
193 << 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()) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000469 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, Loc, Field);
Richard Smith852c9db2013-04-20 22:23:05 +0000470 if (Init < NumInits)
471 ILE->setInit(Init, DIE);
472 else {
473 ILE->updateInit(SemaRef.Context, Init, DIE);
474 RequiresSecondPass = true;
475 }
476 return;
477 }
478
Douglas Gregor2bb07652009-12-22 00:05:34 +0000479 if (Field->getType()->isReferenceType()) {
480 // C++ [dcl.init.aggr]p9:
481 // If an incomplete or empty initializer-list leaves a
482 // member of reference type uninitialized, the program is
483 // ill-formed.
484 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
485 << Field->getType()
486 << ILE->getSyntacticForm()->getSourceRange();
487 SemaRef.Diag(Field->getLocation(),
488 diag::note_uninit_reference_member);
489 hadError = true;
490 return;
491 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000492
Richard Smith454a7cd2014-06-03 08:26:00 +0000493 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
494 /*VerifyOnly*/false);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000495 if (MemberInit.isInvalid()) {
496 hadError = true;
497 return;
498 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000499
Douglas Gregor2bb07652009-12-22 00:05:34 +0000500 if (hadError) {
501 // Do nothing
502 } else if (Init < NumInits) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000503 ILE->setInit(Init, MemberInit.getAs<Expr>());
Richard Smith454a7cd2014-06-03 08:26:00 +0000504 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
505 // Empty initialization requires a constructor call, so
Douglas Gregor2bb07652009-12-22 00:05:34 +0000506 // extend the initializer list to include the constructor
507 // call and make a note that we'll need to take another pass
508 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000509 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000510 RequiresSecondPass = true;
511 }
512 } else if (InitListExpr *InnerILE
513 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Richard Smith454a7cd2014-06-03 08:26:00 +0000514 FillInEmptyInitializations(MemberEntity, InnerILE,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000515 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000516}
517
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000518/// Recursively replaces NULL values within the given initializer list
519/// with expressions that perform value-initialization of the
520/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000521void
Richard Smith454a7cd2014-06-03 08:26:00 +0000522InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000523 InitListExpr *ILE,
524 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000525 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000526 "Should not have void type");
Mike Stump11289f42009-09-09 15:08:12 +0000527
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000528 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000529 const RecordDecl *RDecl = RType->getDecl();
530 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Richard Smith454a7cd2014-06-03 08:26:00 +0000531 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Douglas Gregor2bb07652009-12-22 00:05:34 +0000532 Entity, ILE, RequiresSecondPass);
Richard Smith852c9db2013-04-20 22:23:05 +0000533 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
534 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000535 for (auto *Field : RDecl->fields()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000536 if (Field->hasInClassInitializer()) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000537 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass);
Richard Smith852c9db2013-04-20 22:23:05 +0000538 break;
539 }
540 }
541 } else {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000542 unsigned Init = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000543 for (auto *Field : RDecl->fields()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000544 if (Field->isUnnamedBitfield())
545 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000546
Douglas Gregor2bb07652009-12-22 00:05:34 +0000547 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000548 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000549
Richard Smith454a7cd2014-06-03 08:26:00 +0000550 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000551 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000552 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000553
Douglas Gregor2bb07652009-12-22 00:05:34 +0000554 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000555
Douglas Gregor2bb07652009-12-22 00:05:34 +0000556 // Only look at the first initialization of a union.
Richard Smith852c9db2013-04-20 22:23:05 +0000557 if (RDecl->isUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000558 break;
559 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000560 }
561
562 return;
Mike Stump11289f42009-09-09 15:08:12 +0000563 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000564
565 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000566
Douglas Gregor723796a2009-12-16 06:35:08 +0000567 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000568 unsigned NumInits = ILE->getNumInits();
569 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000570 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000571 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000572 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
573 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000574 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000575 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000576 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000577 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000578 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000579 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000580 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000581 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000582 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000583
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000584 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000585 if (hadError)
586 return;
587
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000588 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
589 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000590 ElementEntity.setElementIndex(Init);
591
Craig Topperc3ec1492014-05-26 06:22:03 +0000592 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000593 if (!InitExpr && !ILE->hasArrayFiller()) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000594 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
595 ElementEntity,
596 /*VerifyOnly*/false);
Douglas Gregor723796a2009-12-16 06:35:08 +0000597 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000598 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000599 return;
600 }
601
602 if (hadError) {
603 // Do nothing
604 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000605 // For arrays, just set the expression used for value-initialization
606 // of the "holes" in the array.
607 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000608 ILE->setArrayFiller(ElementInit.getAs<Expr>());
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000609 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000610 ILE->setInit(Init, ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000611 } else {
612 // For arrays, just set the expression used for value-initialization
613 // of the rest of elements and exit.
614 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000615 ILE->setArrayFiller(ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000616 return;
617 }
618
Richard Smith454a7cd2014-06-03 08:26:00 +0000619 if (!isa<ImplicitValueInitExpr>(ElementInit.get())) {
620 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000621 // extend the initializer list to include the constructor
622 // call and make a note that we'll need to take another pass
623 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000624 ILE->updateInit(SemaRef.Context, Init, ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000625 RequiresSecondPass = true;
626 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000627 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000628 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000629 = dyn_cast_or_null<InitListExpr>(InitExpr))
Richard Smith454a7cd2014-06-03 08:26:00 +0000630 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000631 }
632}
633
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000634
Douglas Gregor723796a2009-12-16 06:35:08 +0000635InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000636 InitListExpr *IL, QualType &T,
Richard Smithde229232013-06-06 11:41:05 +0000637 bool VerifyOnly)
638 : SemaRef(S), VerifyOnly(VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000639 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000640
Richard Smith4e0d2e42013-09-20 20:10:22 +0000641 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000642 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000643 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000644 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000645
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000646 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000647 bool RequiresSecondPass = false;
Richard Smith454a7cd2014-06-03 08:26:00 +0000648 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000649 if (RequiresSecondPass && !hadError)
Richard Smith454a7cd2014-06-03 08:26:00 +0000650 FillInEmptyInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000651 RequiresSecondPass);
652 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000653}
654
655int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000656 // FIXME: use a proper constant
657 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000658 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000659 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000660 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
661 }
662 return maxElements;
663}
664
665int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000666 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000667 int InitializableMembers = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000668 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000669 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000670 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000671
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000672 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000673 return std::min(InitializableMembers, 1);
674 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000675}
676
Richard Smith4e0d2e42013-09-20 20:10:22 +0000677/// Check whether the range of the initializer \p ParentIList from element
678/// \p Index onwards can be used to initialize an object of type \p T. Update
679/// \p Index to indicate how many elements of the list were consumed.
680///
681/// This also fills in \p StructuredList, from element \p StructuredIndex
682/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000683void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000684 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000685 QualType T, unsigned &Index,
686 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000687 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000688 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000689
Steve Narofff8ecff22008-05-01 22:18:59 +0000690 if (T->isArrayType())
691 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000692 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000693 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000694 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000695 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000696 else
David Blaikie83d382b2011-09-23 05:06:16 +0000697 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000698
Eli Friedmane0f832b2008-05-25 13:49:22 +0000699 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000700 if (!VerifyOnly)
701 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
702 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000703 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000704 hadError = true;
705 return;
706 }
707
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000708 // Build a structured initializer list corresponding to this subobject.
709 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000710 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
711 StructuredIndex,
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000712 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregor5741efb2009-03-01 17:12:46 +0000713 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000714 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000715
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000716 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000717 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000718 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000719 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000720 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000721 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000722
Richard Smithde229232013-06-06 11:41:05 +0000723 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000724 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000725
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000726 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000727 // Update the structured sub-object initializer so that it's ending
728 // range corresponds with the end of the last initializer it used.
729 if (EndIndex < ParentIList->getNumInits()) {
730 SourceLocation EndLoc
731 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
732 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
733 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000734
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000735 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000736 if (T->isArrayType() || T->isRecordType()) {
737 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smithde229232013-06-06 11:41:05 +0000738 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000739 << StructuredSubobjectInitList->getSourceRange()
740 << FixItHint::CreateInsertion(
741 StructuredSubobjectInitList->getLocStart(), "{")
742 << FixItHint::CreateInsertion(
743 SemaRef.getLocForEndOfToken(
744 StructuredSubobjectInitList->getLocEnd()),
745 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000746 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000747 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000748}
749
Richard Smith4e0d2e42013-09-20 20:10:22 +0000750/// Check whether the initializer \p IList (that was written with explicit
751/// braces) can be used to initialize an object of type \p T.
752///
753/// This also fills in \p StructuredList with the fully-braced, desugared
754/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000755void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000756 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000757 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000758 bool TopLevelObject) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000759 if (!VerifyOnly) {
760 SyntacticToSemantic[IList] = StructuredList;
761 StructuredList->setSyntacticForm(IList);
762 }
Richard Smith4e0d2e42013-09-20 20:10:22 +0000763
764 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000765 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000766 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000767 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +0000768 QualType ExprTy = T;
769 if (!ExprTy->isArrayType())
770 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000771 IList->setType(ExprTy);
772 StructuredList->setType(ExprTy);
773 }
Eli Friedman85f54972008-05-25 13:22:35 +0000774 if (hadError)
775 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000776
Eli Friedman85f54972008-05-25 13:22:35 +0000777 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000778 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000779 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000780 if (SemaRef.getLangOpts().CPlusPlus ||
781 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000782 IList->getType()->isVectorType())) {
783 hadError = true;
784 }
785 return;
786 }
787
Eli Friedmanbd327452009-05-29 20:20:05 +0000788 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +0000789 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
790 SIF_None) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000791 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000792 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000793 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000794 hadError = true;
795 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000796 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000797 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000798 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000799 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000800 // Don't complain for incomplete types, since we'll get an error
801 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000802 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000803 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000804 CurrentObjectType->isArrayType()? 0 :
805 CurrentObjectType->isVectorType()? 1 :
806 CurrentObjectType->isScalarType()? 2 :
807 CurrentObjectType->isUnionType()? 3 :
808 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000809
810 unsigned DK = diag::warn_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000811 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +0000812 DK = diag::err_excess_initializers;
813 hadError = true;
814 }
David Blaikiebbafb8a2012-03-11 07:00:24 +0000815 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +0000816 DK = diag::err_excess_initializers;
817 hadError = true;
818 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000819
Chris Lattnerb0912a52009-02-24 22:50:46 +0000820 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000821 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000822 }
823 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000824
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000825 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
826 !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000827 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000828 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000829 << FixItHint::CreateRemoval(IList->getLocStart())
830 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000831}
832
Anders Carlsson6cabf312010-01-23 23:23:01 +0000833void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000834 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000835 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000836 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000837 unsigned &Index,
838 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000839 unsigned &StructuredIndex,
840 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000841 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
842 // Explicitly braced initializer for complex type can be real+imaginary
843 // parts.
844 CheckComplexType(Entity, IList, DeclType, Index,
845 StructuredList, StructuredIndex);
846 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000847 CheckScalarType(Entity, IList, DeclType, Index,
848 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000849 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000850 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000851 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +0000852 } else if (DeclType->isRecordType()) {
853 assert(DeclType->isAggregateType() &&
854 "non-aggregate records should be handed in CheckSubElementType");
855 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
856 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
857 SubobjectIsDesignatorContext, Index,
858 StructuredList, StructuredIndex,
859 TopLevelObject);
860 } else if (DeclType->isArrayType()) {
861 llvm::APSInt Zero(
862 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
863 false);
864 CheckArrayType(Entity, IList, DeclType, Zero,
865 SubobjectIsDesignatorContext, Index,
866 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +0000867 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
868 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000869 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000870 if (!VerifyOnly)
871 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
872 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000873 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000874 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000875 CheckReferenceType(Entity, IList, DeclType, Index,
876 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000877 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000878 if (!VerifyOnly)
879 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
880 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000881 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000882 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000883 if (!VerifyOnly)
884 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
885 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000886 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000887 }
888}
889
Anders Carlsson6cabf312010-01-23 23:23:01 +0000890void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000891 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000892 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000893 unsigned &Index,
894 InitListExpr *StructuredList,
895 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000896 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +0000897
898 if (ElemType->isReferenceType())
899 return CheckReferenceType(Entity, IList, ElemType, Index,
900 StructuredList, StructuredIndex);
901
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000902 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smithe20c83d2012-07-07 08:35:56 +0000903 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
Richard Smith4e0d2e42013-09-20 20:10:22 +0000904 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +0000905 = getStructuredSubobjectInit(IList, Index, ElemType,
906 StructuredList, StructuredIndex,
907 SubInitList->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000908 CheckExplicitInitList(Entity, SubInitList, ElemType,
909 InnerStructuredList);
Richard Smithe20c83d2012-07-07 08:35:56 +0000910 ++StructuredIndex;
911 ++Index;
912 return;
913 }
914 assert(SemaRef.getLangOpts().CPlusPlus &&
915 "non-aggregate records are only possible in C++");
916 // C++ initialization is handled later.
Richard Smith8aa561b2014-07-17 23:12:06 +0000917 } else if (auto *VIE = dyn_cast<ImplicitValueInitExpr>(expr)) {
918 // This happens during template instantiation when we see an InitListExpr
919 // that we've already checked once.
920 assert(SemaRef.Context.hasSameType(VIE->getType(), ElemType) &&
921 "found implicit initialization for the wrong type");
NAKAMURA Takumic1551a12014-07-18 01:26:35 +0000922 (void)VIE;
Richard Smith8aa561b2014-07-17 23:12:06 +0000923 if (!VerifyOnly)
924 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
925 ++Index;
926 return;
Richard Smithe20c83d2012-07-07 08:35:56 +0000927 }
928
Eli Friedman4628cf72013-08-19 22:12:56 +0000929 // FIXME: Need to handle atomic aggregate types with implicit init lists.
930 if (ElemType->isScalarType() || ElemType->isAtomicType())
John McCall5decec92011-02-21 07:57:55 +0000931 return CheckScalarType(Entity, IList, ElemType, Index,
932 StructuredList, StructuredIndex);
Anders Carlsson03068aa2009-08-27 17:18:13 +0000933
Eli Friedman4628cf72013-08-19 22:12:56 +0000934 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
935 ElemType->isArrayType()) && "Unexpected type");
936
John McCall5decec92011-02-21 07:57:55 +0000937 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
938 // arrayType can be incomplete if we're initializing a flexible
939 // array member. There's nothing we can do with the completed
940 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000941
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000942 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +0000943 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000944 CheckStringInit(expr, ElemType, arrayType, SemaRef);
945 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +0000946 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000947 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000948 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000949 }
John McCall5decec92011-02-21 07:57:55 +0000950
951 // Fall through for subaggregate initialization.
952
David Blaikiebbafb8a2012-03-11 07:00:24 +0000953 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCall5decec92011-02-21 07:57:55 +0000954 // C++ [dcl.init.aggr]p12:
955 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000956 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000957 // an initializer-list. If the initializer can initialize a
958 // member, the member is initialized. [...]
959
960 // FIXME: Better EqualLoc?
961 InitializationKind Kind =
962 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000963 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCall5decec92011-02-21 07:57:55 +0000964
965 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000966 if (!VerifyOnly) {
Richard Smith0f8ede12011-12-20 04:00:21 +0000967 ExprResult Result =
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000968 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smith0f8ede12011-12-20 04:00:21 +0000969 if (Result.isInvalid())
970 hadError = true;
John McCall5decec92011-02-21 07:57:55 +0000971
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000972 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000973 Result.getAs<Expr>());
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000974 }
John McCall5decec92011-02-21 07:57:55 +0000975 ++Index;
976 return;
977 }
978
979 // Fall through for subaggregate initialization
980 } else {
981 // C99 6.7.8p13:
982 //
983 // The initializer for a structure or union object that has
984 // automatic storage duration shall be either an initializer
985 // list as described below, or a single expression that has
986 // compatible structure or union type. In the latter case, the
987 // initial value of the object, including unnamed members, is
988 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000989 ExprResult ExprRes = expr;
John McCall5decec92011-02-21 07:57:55 +0000990 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000991 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
992 !VerifyOnly)
Eli Friedmanb2a8d462013-09-17 04:07:04 +0000993 != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +0000994 if (ExprRes.isInvalid())
995 hadError = true;
996 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000997 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000998 if (ExprRes.isInvalid())
999 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +00001000 }
1001 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001002 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +00001003 ++Index;
1004 return;
1005 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001006 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +00001007 // Fall through for subaggregate initialization
1008 }
1009
1010 // C++ [dcl.init.aggr]p12:
1011 //
1012 // [...] Otherwise, if the member is itself a non-empty
1013 // subaggregate, brace elision is assumed and the initializer is
1014 // considered for the initialization of the first member of
1015 // the subaggregate.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001016 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00001017 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +00001018 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1019 StructuredIndex);
1020 ++StructuredIndex;
1021 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001022 if (!VerifyOnly) {
1023 // We cannot initialize this element, so let
1024 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001025 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001026 /*TopLevelOfInitList=*/true);
1027 }
John McCall5decec92011-02-21 07:57:55 +00001028 hadError = true;
1029 ++Index;
1030 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +00001031 }
Eli Friedman23a9e312008-05-19 19:16:24 +00001032}
1033
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001034void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1035 InitListExpr *IList, QualType DeclType,
1036 unsigned &Index,
1037 InitListExpr *StructuredList,
1038 unsigned &StructuredIndex) {
1039 assert(Index == 0 && "Index in explicit init list must be zero");
1040
1041 // As an extension, clang supports complex initializers, which initialize
1042 // a complex number component-wise. When an explicit initializer list for
1043 // a complex number contains two two initializers, this extension kicks in:
1044 // it exepcts the initializer list to contain two elements convertible to
1045 // the element type of the complex type. The first element initializes
1046 // the real part, and the second element intitializes the imaginary part.
1047
1048 if (IList->getNumInits() != 2)
1049 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1050 StructuredIndex);
1051
1052 // This is an extension in C. (The builtin _Complex type does not exist
1053 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001054 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001055 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1056 << IList->getSourceRange();
1057
1058 // Initialize the complex number.
1059 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1060 InitializedEntity ElementEntity =
1061 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1062
1063 for (unsigned i = 0; i < 2; ++i) {
1064 ElementEntity.setElementIndex(Index);
1065 CheckSubElementType(ElementEntity, IList, elementType, Index,
1066 StructuredList, StructuredIndex);
1067 }
1068}
1069
1070
Anders Carlsson6cabf312010-01-23 23:23:01 +00001071void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001072 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001073 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001074 InitListExpr *StructuredList,
1075 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001076 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001077 if (!VerifyOnly)
1078 SemaRef.Diag(IList->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001079 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smithc8239732011-10-18 21:39:00 +00001080 diag::warn_cxx98_compat_empty_scalar_initializer :
1081 diag::err_empty_scalar_initializer)
1082 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001083 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001084 ++Index;
1085 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001086 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001087 }
John McCall643169b2010-11-11 00:46:36 +00001088
1089 Expr *expr = IList->getInit(Index);
1090 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001091 // FIXME: This is invalid, and accepting it causes overload resolution
1092 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001093 if (!VerifyOnly)
1094 SemaRef.Diag(SubIList->getLocStart(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001095 diag::ext_many_braces_around_scalar_init)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001096 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001097
1098 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1099 StructuredIndex);
1100 return;
1101 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001102 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001103 SemaRef.Diag(expr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001104 diag::err_designator_for_scalar_init)
1105 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001106 hadError = true;
1107 ++Index;
1108 ++StructuredIndex;
1109 return;
1110 }
1111
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001112 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001113 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001114 hadError = true;
1115 ++Index;
1116 return;
1117 }
1118
John McCall643169b2010-11-11 00:46:36 +00001119 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001120 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001121 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001122
Craig Topperc3ec1492014-05-26 06:22:03 +00001123 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001124
1125 if (Result.isInvalid())
1126 hadError = true; // types weren't compatible.
1127 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001128 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001129
John McCall643169b2010-11-11 00:46:36 +00001130 if (ResultExpr != expr) {
1131 // The type was promoted, update initializer list.
1132 IList->setInit(Index, ResultExpr);
1133 }
1134 }
1135 if (hadError)
1136 ++StructuredIndex;
1137 else
1138 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1139 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001140}
1141
Anders Carlsson6cabf312010-01-23 23:23:01 +00001142void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1143 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001144 unsigned &Index,
1145 InitListExpr *StructuredList,
1146 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001147 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001148 // FIXME: It would be wonderful if we could point at the actual member. In
1149 // general, it would be useful to pass location information down the stack,
1150 // so that we know the location (or decl) of the "current object" being
1151 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001152 if (!VerifyOnly)
1153 SemaRef.Diag(IList->getLocStart(),
1154 diag::err_init_reference_member_uninitialized)
1155 << DeclType
1156 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001157 hadError = true;
1158 ++Index;
1159 ++StructuredIndex;
1160 return;
1161 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001162
1163 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001164 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001165 if (!VerifyOnly)
1166 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1167 << DeclType << IList->getSourceRange();
1168 hadError = true;
1169 ++Index;
1170 ++StructuredIndex;
1171 return;
1172 }
1173
1174 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001175 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001176 hadError = true;
1177 ++Index;
1178 return;
1179 }
1180
1181 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001182 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1183 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001184
1185 if (Result.isInvalid())
1186 hadError = true;
1187
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001188 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001189 IList->setInit(Index, expr);
1190
1191 if (hadError)
1192 ++StructuredIndex;
1193 else
1194 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1195 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001196}
1197
Anders Carlsson6cabf312010-01-23 23:23:01 +00001198void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001199 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001200 unsigned &Index,
1201 InitListExpr *StructuredList,
1202 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001203 const VectorType *VT = DeclType->getAs<VectorType>();
1204 unsigned maxElements = VT->getNumElements();
1205 unsigned numEltsInit = 0;
1206 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001207
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001208 if (Index >= IList->getNumInits()) {
1209 // Make sure the element type can be value-initialized.
1210 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001211 CheckEmptyInitializable(
1212 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1213 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001214 return;
1215 }
1216
David Blaikiebbafb8a2012-03-11 07:00:24 +00001217 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001218 // If the initializing element is a vector, try to copy-initialize
1219 // instead of breaking it apart (which is doomed to failure anyway).
1220 Expr *Init = IList->getInit(Index);
1221 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001222 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001223 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001224 hadError = true;
1225 ++Index;
1226 return;
1227 }
1228
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001229 ExprResult Result =
1230 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1231 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001232
Craig Topperc3ec1492014-05-26 06:22:03 +00001233 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001234 if (Result.isInvalid())
1235 hadError = true; // types weren't compatible.
1236 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001237 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001238
John McCall6a16b2f2010-10-30 00:11:39 +00001239 if (ResultExpr != Init) {
1240 // The type was promoted, update initializer list.
1241 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001242 }
1243 }
John McCall6a16b2f2010-10-30 00:11:39 +00001244 if (hadError)
1245 ++StructuredIndex;
1246 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001247 UpdateStructuredListElement(StructuredList, StructuredIndex,
1248 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001249 ++Index;
1250 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001251 }
Mike Stump11289f42009-09-09 15:08:12 +00001252
John McCall6a16b2f2010-10-30 00:11:39 +00001253 InitializedEntity ElementEntity =
1254 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001255
John McCall6a16b2f2010-10-30 00:11:39 +00001256 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1257 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001258 if (Index >= IList->getNumInits()) {
1259 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001260 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
John McCall6a16b2f2010-10-30 00:11:39 +00001261 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001262 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001263
John McCall6a16b2f2010-10-30 00:11:39 +00001264 ElementEntity.setElementIndex(Index);
1265 CheckSubElementType(ElementEntity, IList, elementType, Index,
1266 StructuredList, StructuredIndex);
1267 }
James Molloy9eef2652014-06-20 14:35:13 +00001268
1269 if (VerifyOnly)
1270 return;
1271
1272 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1273 const VectorType *T = Entity.getType()->getAs<VectorType>();
1274 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1275 T->getVectorKind() == VectorType::NeonPolyVector)) {
1276 // The ability to use vector initializer lists is a GNU vector extension
1277 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1278 // endian machines it works fine, however on big endian machines it
1279 // exhibits surprising behaviour:
1280 //
1281 // uint32x2_t x = {42, 64};
1282 // return vget_lane_u32(x, 0); // Will return 64.
1283 //
1284 // Because of this, explicitly call out that it is non-portable.
1285 //
1286 SemaRef.Diag(IList->getLocStart(),
1287 diag::warn_neon_vector_initializer_non_portable);
1288
1289 const char *typeCode;
1290 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1291
1292 if (elementType->isFloatingType())
1293 typeCode = "f";
1294 else if (elementType->isSignedIntegerType())
1295 typeCode = "s";
1296 else if (elementType->isUnsignedIntegerType())
1297 typeCode = "u";
1298 else
1299 llvm_unreachable("Invalid element type!");
1300
1301 SemaRef.Diag(IList->getLocStart(),
1302 SemaRef.Context.getTypeSize(VT) > 64 ?
1303 diag::note_neon_vector_initializer_non_portable_q :
1304 diag::note_neon_vector_initializer_non_portable)
1305 << typeCode << typeSize;
1306 }
1307
John McCall6a16b2f2010-10-30 00:11:39 +00001308 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001309 }
John McCall6a16b2f2010-10-30 00:11:39 +00001310
1311 InitializedEntity ElementEntity =
1312 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001313
John McCall6a16b2f2010-10-30 00:11:39 +00001314 // OpenCL initializers allows vectors to be constructed from vectors.
1315 for (unsigned i = 0; i < maxElements; ++i) {
1316 // Don't attempt to go past the end of the init list
1317 if (Index >= IList->getNumInits())
1318 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001319
John McCall6a16b2f2010-10-30 00:11:39 +00001320 ElementEntity.setElementIndex(Index);
1321
1322 QualType IType = IList->getInit(Index)->getType();
1323 if (!IType->isVectorType()) {
1324 CheckSubElementType(ElementEntity, IList, elementType, Index,
1325 StructuredList, StructuredIndex);
1326 ++numEltsInit;
1327 } else {
1328 QualType VecType;
1329 const VectorType *IVT = IType->getAs<VectorType>();
1330 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001331
John McCall6a16b2f2010-10-30 00:11:39 +00001332 if (IType->isExtVectorType())
1333 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1334 else
1335 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001336 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001337 CheckSubElementType(ElementEntity, IList, VecType, Index,
1338 StructuredList, StructuredIndex);
1339 numEltsInit += numIElts;
1340 }
1341 }
1342
1343 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001344 if (numEltsInit != maxElements) {
1345 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001346 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001347 diag::err_vector_incorrect_num_initializers)
1348 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1349 hadError = true;
1350 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001351}
1352
Anders Carlsson6cabf312010-01-23 23:23:01 +00001353void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001354 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001355 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001356 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001357 unsigned &Index,
1358 InitListExpr *StructuredList,
1359 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001360 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1361
Steve Narofff8ecff22008-05-01 22:18:59 +00001362 // Check for the special-case of initializing an array with a string.
1363 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001364 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1365 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001366 // We place the string literal directly into the resulting
1367 // initializer list. This is the only place where the structure
1368 // of the structured initializer list doesn't match exactly,
1369 // because doing so would involve allocating one character
1370 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001371 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001372 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1373 UpdateStructuredListElement(StructuredList, StructuredIndex,
1374 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001375 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1376 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001377 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001378 return;
1379 }
1380 }
John McCall66884dd2011-02-21 07:22:22 +00001381 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001382 // Check for VLAs; in standard C it would be possible to check this
1383 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1384 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001385 if (!VerifyOnly)
1386 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1387 diag::err_variable_object_no_init)
1388 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001389 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001390 ++Index;
1391 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001392 return;
1393 }
1394
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001395 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001396 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1397 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001398 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001399 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001400 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001401 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001402 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001403 maxElementsKnown = true;
1404 }
1405
John McCall66884dd2011-02-21 07:22:22 +00001406 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001407 while (Index < IList->getNumInits()) {
1408 Expr *Init = IList->getInit(Index);
1409 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001410 // If we're not the subobject that matches up with the '{' for
1411 // the designator, we shouldn't be handling the
1412 // designator. Return immediately.
1413 if (!SubobjectIsDesignatorContext)
1414 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001415
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001416 // Handle this designated initializer. elementIndex will be
1417 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001418 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001419 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001420 StructuredList, StructuredIndex, true,
1421 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001422 hadError = true;
1423 continue;
1424 }
1425
Douglas Gregor033d1252009-01-23 16:54:12 +00001426 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001427 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001428 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001429 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001430 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001431
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001432 // If the array is of incomplete type, keep track of the number of
1433 // elements in the initializer.
1434 if (!maxElementsKnown && elementIndex > maxElements)
1435 maxElements = elementIndex;
1436
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001437 continue;
1438 }
1439
1440 // If we know the maximum number of elements, and we've already
1441 // hit it, stop consuming elements in the initializer list.
1442 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001443 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001444
Anders Carlsson6cabf312010-01-23 23:23:01 +00001445 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001446 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001447 Entity);
1448 // Check this element.
1449 CheckSubElementType(ElementEntity, IList, elementType, Index,
1450 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001451 ++elementIndex;
1452
1453 // If the array is of incomplete type, keep track of the number of
1454 // elements in the initializer.
1455 if (!maxElementsKnown && elementIndex > maxElements)
1456 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001457 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001458 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001459 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001460 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001461 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001462 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001463 // Sizing an array implicitly to zero is not allowed by ISO C,
1464 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001465 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001466 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001467 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001468
Mike Stump11289f42009-09-09 15:08:12 +00001469 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001470 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001471 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001472 if (!hadError && VerifyOnly) {
1473 // Check if there are any members of the array that get value-initialized.
1474 // If so, check if doing that is possible.
1475 // FIXME: This needs to detect holes left by designated initializers too.
1476 if (maxElementsKnown && elementIndex < maxElements)
Richard Smith454a7cd2014-06-03 08:26:00 +00001477 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1478 SemaRef.Context, 0, Entity),
1479 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001480 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001481}
1482
Eli Friedman3fa64df2011-08-23 22:24:57 +00001483bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1484 Expr *InitExpr,
1485 FieldDecl *Field,
1486 bool TopLevelObject) {
1487 // Handle GNU flexible array initializers.
1488 unsigned FlexArrayDiag;
1489 if (isa<InitListExpr>(InitExpr) &&
1490 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1491 // Empty flexible array init always allowed as an extension
1492 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001493 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001494 // Disallow flexible array init in C++; it is not required for gcc
1495 // compatibility, and it needs work to IRGen correctly in general.
1496 FlexArrayDiag = diag::err_flexible_array_init;
1497 } else if (!TopLevelObject) {
1498 // Disallow flexible array init on non-top-level object
1499 FlexArrayDiag = diag::err_flexible_array_init;
1500 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1501 // Disallow flexible array init on anything which is not a variable.
1502 FlexArrayDiag = diag::err_flexible_array_init;
1503 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1504 // Disallow flexible array init on local variables.
1505 FlexArrayDiag = diag::err_flexible_array_init;
1506 } else {
1507 // Allow other cases.
1508 FlexArrayDiag = diag::ext_flexible_array_init;
1509 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001510
1511 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001512 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001513 FlexArrayDiag)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001514 << InitExpr->getLocStart();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001515 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1516 << Field;
1517 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001518
1519 return FlexArrayDiag != diag::ext_flexible_array_init;
1520}
1521
Anders Carlsson6cabf312010-01-23 23:23:01 +00001522void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001523 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001524 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001525 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001526 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001527 unsigned &Index,
1528 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001529 unsigned &StructuredIndex,
1530 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001531 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001532
Eli Friedman23a9e312008-05-19 19:16:24 +00001533 // If the record is invalid, some of it's members are invalid. To avoid
1534 // confusion, we forgo checking the intializer for the entire record.
1535 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001536 // Assume it was supposed to consume a single initializer.
1537 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001538 hadError = true;
1539 return;
Mike Stump11289f42009-09-09 15:08:12 +00001540 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001541
1542 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001543 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001544
1545 // If there's a default initializer, use it.
1546 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1547 if (VerifyOnly)
1548 return;
1549 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1550 Field != FieldEnd; ++Field) {
1551 if (Field->hasInClassInitializer()) {
1552 StructuredList->setInitializedFieldInUnion(*Field);
1553 // FIXME: Actually build a CXXDefaultInitExpr?
1554 return;
1555 }
1556 }
1557 }
1558
1559 // Value-initialize the first named member of the union.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001560 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1561 Field != FieldEnd; ++Field) {
1562 if (Field->getDeclName()) {
1563 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001564 CheckEmptyInitializable(
1565 InitializedEntity::InitializeMember(*Field, &Entity),
1566 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001567 else
David Blaikie40ed2972012-06-06 20:45:41 +00001568 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001569 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001570 }
1571 }
1572 return;
1573 }
1574
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001575 // If structDecl is a forward declaration, this loop won't do
1576 // anything except look at designated initializers; That's okay,
1577 // because an error should get printed out elsewhere. It might be
1578 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001579 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001580 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001581 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001582 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001583 while (Index < IList->getNumInits()) {
1584 Expr *Init = IList->getInit(Index);
1585
1586 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001587 // If we're not the subobject that matches up with the '{' for
1588 // the designator, we shouldn't be handling the
1589 // designator. Return immediately.
1590 if (!SubobjectIsDesignatorContext)
1591 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001592
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001593 // Handle this designated initializer. Field will be updated to
1594 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001595 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001596 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001597 StructuredList, StructuredIndex,
1598 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001599 hadError = true;
1600
Douglas Gregora9add4e2009-02-12 19:00:39 +00001601 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001602
1603 // Disable check for missing fields when designators are used.
1604 // This matches gcc behaviour.
1605 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001606 continue;
1607 }
1608
1609 if (Field == FieldEnd) {
1610 // We've run out of fields. We're done.
1611 break;
1612 }
1613
Douglas Gregora9add4e2009-02-12 19:00:39 +00001614 // We've already initialized a member of a union. We're done.
1615 if (InitializedSomething && DeclType->isUnionType())
1616 break;
1617
Douglas Gregor91f84212008-12-11 16:49:14 +00001618 // If we've hit the flexible array member at the end, we're done.
1619 if (Field->getType()->isIncompleteArrayType())
1620 break;
1621
Douglas Gregor51695702009-01-29 16:53:55 +00001622 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001623 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001624 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001625 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001626 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001627
Douglas Gregora82064c2011-06-29 21:51:31 +00001628 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001629 bool InvalidUse;
1630 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00001631 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001632 else
David Blaikie40ed2972012-06-06 20:45:41 +00001633 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001634 IList->getInit(Index)->getLocStart());
1635 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001636 ++Index;
1637 ++Field;
1638 hadError = true;
1639 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001640 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001641
Anders Carlsson6cabf312010-01-23 23:23:01 +00001642 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001643 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001644 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1645 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001646 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001647
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001648 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001649 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00001650 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001651 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001652
1653 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001654 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001655
John McCalle40b58e2010-03-11 19:32:38 +00001656 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001657 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1658 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1659 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001660 // It is possible we have one or more unnamed bitfields remaining.
1661 // Find first (if any) named field and emit warning.
1662 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1663 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00001664 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00001665 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00001666 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00001667 break;
1668 }
1669 }
1670 }
1671
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001672 // Check that any remaining fields can be value-initialized.
1673 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1674 !Field->getType()->isIncompleteArrayType()) {
1675 // FIXME: Should check for holes left by designated initializers too.
1676 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00001677 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00001678 CheckEmptyInitializable(
1679 InitializedEntity::InitializeMember(*Field, &Entity),
1680 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001681 }
1682 }
1683
Mike Stump11289f42009-09-09 15:08:12 +00001684 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001685 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001686 return;
1687
David Blaikie40ed2972012-06-06 20:45:41 +00001688 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00001689 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001690 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001691 ++Index;
1692 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001693 }
1694
Anders Carlsson6cabf312010-01-23 23:23:01 +00001695 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001696 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001697
Anders Carlsson6cabf312010-01-23 23:23:01 +00001698 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001699 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001700 StructuredList, StructuredIndex);
1701 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001702 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001703 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001704}
Steve Narofff8ecff22008-05-01 22:18:59 +00001705
Douglas Gregord5846a12009-04-15 06:41:24 +00001706/// \brief Expand a field designator that refers to a member of an
1707/// anonymous struct or union into a series of field designators that
1708/// refers to the field within the appropriate subobject.
1709///
Douglas Gregord5846a12009-04-15 06:41:24 +00001710static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001711 DesignatedInitExpr *DIE,
1712 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001713 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001714 typedef DesignatedInitExpr::Designator Designator;
1715
Douglas Gregord5846a12009-04-15 06:41:24 +00001716 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001717 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001718 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1719 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1720 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00001721 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00001722 DIE->getDesignator(DesigIdx)->getDotLoc(),
1723 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1724 else
Craig Topperc3ec1492014-05-26 06:22:03 +00001725 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1726 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001727 assert(isa<FieldDecl>(*PI));
1728 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001729 }
1730
1731 // Expand the current designator into the set of replacement
1732 // designators, so we have a full subobject path down to where the
1733 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001734 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001735 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001736}
Mike Stump11289f42009-09-09 15:08:12 +00001737
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001738/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001739/// corresponds to FieldName.
1740static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1741 IdentifierInfo *FieldName) {
Argyrios Kyrtzidis54b10292012-09-10 22:04:26 +00001742 if (!FieldName)
Craig Topperc3ec1492014-05-26 06:22:03 +00001743 return nullptr;
Argyrios Kyrtzidis54b10292012-09-10 22:04:26 +00001744
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001745 assert(AnonField->isAnonymousStructOrUnion());
1746 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman6d1bebb2012-02-09 22:16:56 +00001747 while (IndirectFieldDecl *IF =
1748 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidis54b10292012-09-10 22:04:26 +00001749 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001750 return IF;
1751 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001752 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001753 return nullptr;
Douglas Gregord5846a12009-04-15 06:41:24 +00001754}
1755
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001756static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1757 DesignatedInitExpr *DIE) {
1758 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1759 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1760 for (unsigned I = 0; I < NumIndexExprs; ++I)
1761 IndexExprs[I] = DIE->getSubExpr(I + 1);
1762 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001763 DIE->size(), IndexExprs,
1764 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001765 DIE->usesGNUSyntax(), DIE->getInit());
1766}
1767
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001768namespace {
1769
1770// Callback to only accept typo corrections that are for field members of
1771// the given struct or union.
1772class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1773 public:
1774 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1775 : Record(RD) {}
1776
Craig Toppere14c0f82014-03-12 04:55:44 +00001777 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001778 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1779 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1780 }
1781
1782 private:
1783 RecordDecl *Record;
1784};
1785
1786}
1787
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001788/// @brief Check the well-formedness of a C99 designated initializer.
1789///
1790/// Determines whether the designated initializer @p DIE, which
1791/// resides at the given @p Index within the initializer list @p
1792/// IList, is well-formed for a current object of type @p DeclType
1793/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001794/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001795/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001796///
1797/// @param IList The initializer list in which this designated
1798/// initializer occurs.
1799///
Douglas Gregora5324162009-04-15 04:56:10 +00001800/// @param DIE The designated initializer expression.
1801///
1802/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001803///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00001804/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001805/// into which the designation in @p DIE should refer.
1806///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001807/// @param NextField If non-NULL and the first designator in @p DIE is
1808/// a field, this will be set to the field declaration corresponding
1809/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001810///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001811/// @param NextElementIndex If non-NULL and the first designator in @p
1812/// DIE is an array designator or GNU array-range designator, this
1813/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001814///
1815/// @param Index Index into @p IList where the designated initializer
1816/// @p DIE occurs.
1817///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001818/// @param StructuredList The initializer list expression that
1819/// describes all of the subobject initializers in the order they'll
1820/// actually be initialized.
1821///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001822/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001823bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001824InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001825 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001826 DesignatedInitExpr *DIE,
1827 unsigned DesigIdx,
1828 QualType &CurrentObjectType,
1829 RecordDecl::field_iterator *NextField,
1830 llvm::APSInt *NextElementIndex,
1831 unsigned &Index,
1832 InitListExpr *StructuredList,
1833 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001834 bool FinishSubobjectInit,
1835 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001836 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001837 // Check the actual initialization for the designated object type.
1838 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001839
1840 // Temporarily remove the designator expression from the
1841 // initializer list that the child calls see, so that we don't try
1842 // to re-process the designator.
1843 unsigned OldIndex = Index;
1844 IList->setInit(OldIndex, DIE->getInit());
1845
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001846 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001847 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001848
1849 // Restore the designated initializer expression in the syntactic
1850 // form of the initializer list.
1851 if (IList->getInit(OldIndex) != DIE->getInit())
1852 DIE->setInit(IList->getInit(OldIndex));
1853 IList->setInit(OldIndex, DIE);
1854
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001855 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001856 }
1857
Douglas Gregora5324162009-04-15 04:56:10 +00001858 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001859 bool IsFirstDesignator = (DesigIdx == 0);
1860 if (!VerifyOnly) {
1861 assert((IsFirstDesignator || StructuredList) &&
1862 "Need a non-designated initializer list to start from");
1863
1864 // Determine the structural initializer list that corresponds to the
1865 // current subobject.
Benjamin Kramer6b441d62012-02-23 14:48:40 +00001866 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001867 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1868 StructuredList, StructuredIndex,
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001869 SourceRange(D->getLocStart(),
1870 DIE->getLocEnd()));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001871 assert(StructuredList && "Expected a structured initializer list");
1872 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001873
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001874 if (D->isFieldDesignator()) {
1875 // C99 6.7.8p7:
1876 //
1877 // If a designator has the form
1878 //
1879 // . identifier
1880 //
1881 // then the current object (defined below) shall have
1882 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001883 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001884 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001885 if (!RT) {
1886 SourceLocation Loc = D->getDotLoc();
1887 if (Loc.isInvalid())
1888 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001889 if (!VerifyOnly)
1890 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001891 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001892 ++Index;
1893 return true;
1894 }
1895
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001896 // Note: we perform a linear search of the fields here, despite
1897 // the fact that we have a faster lookup method, because we always
1898 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001899 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001900 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001901 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001902 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001903 Field = RT->getDecl()->field_begin(),
1904 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001905 for (; Field != FieldEnd; ++Field) {
1906 if (Field->isUnnamedBitfield())
1907 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001908
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001909 // If we find a field representing an anonymous field, look in the
1910 // IndirectFieldDecl that follow for the designated initializer.
1911 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1912 if (IndirectFieldDecl *IF =
David Blaikie40ed2972012-06-06 20:45:41 +00001913 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001914 // In verify mode, don't modify the original.
1915 if (VerifyOnly)
1916 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001917 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1918 D = DIE->getDesignator(DesigIdx);
1919 break;
1920 }
1921 }
David Blaikie40ed2972012-06-06 20:45:41 +00001922 if (KnownField && KnownField == *Field)
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001923 break;
1924 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001925 break;
1926
1927 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001928 }
1929
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001930 if (Field == FieldEnd) {
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001931 if (VerifyOnly) {
1932 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001933 return true; // No typo correction when just trying this out.
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001934 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001935
Douglas Gregord5846a12009-04-15 06:41:24 +00001936 // There was no normal field in the struct with the designated
1937 // name. Perform another lookup for this name, which may find
1938 // something that we can't designate (e.g., a member function),
1939 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001940 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001941 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Craig Topperc3ec1492014-05-26 06:22:03 +00001942 FieldDecl *ReplacementField = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00001943 if (Lookup.empty()) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001944 // Name lookup didn't find anything. Determine whether this
1945 // was a typo for another field name.
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001946 FieldInitializerValidatorCCC Validator(RT->getDecl());
Richard Smithf9b15102013-08-17 00:46:16 +00001947 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
1948 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Craig Topperc3ec1492014-05-26 06:22:03 +00001949 Sema::LookupMemberName, /*Scope=*/ nullptr, /*SS=*/ nullptr,
1950 Validator, Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00001951 SemaRef.diagnoseTypo(
1952 Corrected,
1953 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
1954 << FieldName << CurrentObjectType);
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001955 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001956 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001957 } else {
1958 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1959 << FieldName << CurrentObjectType;
1960 ++Index;
1961 return true;
1962 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001963 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001964
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001965 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001966 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001967 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001968 << FieldName;
David Blaikieff7d47a2012-12-19 00:45:41 +00001969 SemaRef.Diag(Lookup.front()->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001970 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001971 ++Index;
1972 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001973 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001974
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001975 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001976 // The replacement field comes from typo correction; find it
1977 // in the list of fields.
1978 FieldIndex = 0;
1979 Field = RT->getDecl()->field_begin();
1980 for (; Field != FieldEnd; ++Field) {
1981 if (Field->isUnnamedBitfield())
1982 continue;
1983
David Blaikie40ed2972012-06-06 20:45:41 +00001984 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001985 Field->getIdentifier() == ReplacementField->getIdentifier())
1986 break;
1987
1988 ++FieldIndex;
1989 }
1990 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001991 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001992
1993 // All of the fields of a union are located at the same place in
1994 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001995 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001996 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00001997 if (!VerifyOnly) {
1998 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
1999 if (CurrentField && CurrentField != *Field) {
2000 assert(StructuredList->getNumInits() == 1
2001 && "A union should never have more than one initializer!");
2002
2003 // we're about to throw away an initializer, emit warning
2004 SemaRef.Diag(D->getFieldLoc(),
2005 diag::warn_initializer_overrides)
2006 << D->getSourceRange();
2007 Expr *ExistingInit = StructuredList->getInit(0);
2008 SemaRef.Diag(ExistingInit->getLocStart(),
2009 diag::note_previous_initializer)
2010 << /*FIXME:has side effects=*/0
2011 << ExistingInit->getSourceRange();
2012
2013 // remove existing initializer
2014 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00002015 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002016 }
2017
David Blaikie40ed2972012-06-06 20:45:41 +00002018 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002019 }
Douglas Gregor51695702009-01-29 16:53:55 +00002020 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002021
Douglas Gregora82064c2011-06-29 21:51:31 +00002022 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002023 bool InvalidUse;
2024 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00002025 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002026 else
David Blaikie40ed2972012-06-06 20:45:41 +00002027 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002028 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002029 ++Index;
2030 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002031 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002032
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002033 if (!VerifyOnly) {
2034 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00002035 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00002036
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002037 // Make sure that our non-designated initializer list has space
2038 // for a subobject corresponding to this field.
2039 if (FieldIndex >= StructuredList->getNumInits())
2040 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2041 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002042
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002043 // This designator names a flexible array member.
2044 if (Field->getType()->isIncompleteArrayType()) {
2045 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00002046 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002047 // We can't designate an object within the flexible array
2048 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002049 if (!VerifyOnly) {
2050 DesignatedInitExpr::Designator *NextD
2051 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002052 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002053 diag::err_designator_into_flexible_array_member)
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002054 << SourceRange(NextD->getLocStart(),
2055 DIE->getLocEnd());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002056 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002057 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002058 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002059 Invalid = true;
2060 }
2061
Chris Lattner001b29c2010-10-10 17:49:49 +00002062 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2063 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002064 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002065 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002066 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002067 diag::err_flexible_array_init_needs_braces)
2068 << DIE->getInit()->getSourceRange();
2069 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002070 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002071 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002072 Invalid = true;
2073 }
2074
Eli Friedman3fa64df2011-08-23 22:24:57 +00002075 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00002076 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002077 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002078 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002079
2080 if (Invalid) {
2081 ++Index;
2082 return true;
2083 }
2084
2085 // Initialize the array.
2086 bool prevHadError = hadError;
2087 unsigned newStructuredIndex = FieldIndex;
2088 unsigned OldIndex = Index;
2089 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00002090
2091 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002092 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002093 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002094 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002095
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002096 IList->setInit(OldIndex, DIE);
2097 if (hadError && !prevHadError) {
2098 ++Field;
2099 ++FieldIndex;
2100 if (NextField)
2101 *NextField = Field;
2102 StructuredIndex = FieldIndex;
2103 return true;
2104 }
2105 } else {
2106 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002107 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002108 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002109
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002110 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002111 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002112 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002113 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002114 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002115 true, false))
2116 return true;
2117 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002118
2119 // Find the position of the next field to be initialized in this
2120 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002121 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002122 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002123
2124 // If this the first designator, our caller will continue checking
2125 // the rest of this struct/class/union subobject.
2126 if (IsFirstDesignator) {
2127 if (NextField)
2128 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002129 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002130 return false;
2131 }
2132
Douglas Gregor17bd0942009-01-28 23:36:17 +00002133 if (!FinishSubobjectInit)
2134 return false;
2135
Douglas Gregord5846a12009-04-15 06:41:24 +00002136 // We've already initialized something in the union; we're done.
2137 if (RT->getDecl()->isUnion())
2138 return hadError;
2139
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002140 // Check the remaining fields within this class/struct/union subobject.
2141 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002142
Anders Carlsson6cabf312010-01-23 23:23:01 +00002143 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002144 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002145 return hadError && !prevHadError;
2146 }
2147
2148 // C99 6.7.8p6:
2149 //
2150 // If a designator has the form
2151 //
2152 // [ constant-expression ]
2153 //
2154 // then the current object (defined below) shall have array
2155 // type and the expression shall be an integer constant
2156 // expression. If the array is of unknown size, any
2157 // nonnegative value is valid.
2158 //
2159 // Additionally, cope with the GNU extension that permits
2160 // designators of the form
2161 //
2162 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002163 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002164 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002165 if (!VerifyOnly)
2166 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2167 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002168 ++Index;
2169 return true;
2170 }
2171
Craig Topperc3ec1492014-05-26 06:22:03 +00002172 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002173 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2174 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002175 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002176 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002177 DesignatedEndIndex = DesignatedStartIndex;
2178 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002179 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002180
Mike Stump11289f42009-09-09 15:08:12 +00002181 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002182 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002183 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002184 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002185 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002186
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002187 // Codegen can't handle evaluating array range designators that have side
2188 // effects, because we replicate the AST value for each initialized element.
2189 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2190 // elements with something that has a side effect, so codegen can emit an
2191 // "error unsupported" error instead of miscompiling the app.
2192 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002193 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002194 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002195 }
2196
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002197 if (isa<ConstantArrayType>(AT)) {
2198 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002199 DesignatedStartIndex
2200 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002201 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002202 DesignatedEndIndex
2203 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002204 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2205 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002206 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002207 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002208 diag::err_array_designator_too_large)
2209 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2210 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002211 ++Index;
2212 return true;
2213 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002214 } else {
2215 // Make sure the bit-widths and signedness match.
2216 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002217 DesignatedEndIndex
2218 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002219 else if (DesignatedStartIndex.getBitWidth() <
2220 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002221 DesignatedStartIndex
2222 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002223 DesignatedStartIndex.setIsUnsigned(true);
2224 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002225 }
Mike Stump11289f42009-09-09 15:08:12 +00002226
Eli Friedman1f16b742013-06-11 21:48:11 +00002227 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2228 // We're modifying a string literal init; we have to decompose the string
2229 // so we can modify the individual characters.
2230 ASTContext &Context = SemaRef.Context;
2231 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2232
2233 // Compute the character type
2234 QualType CharTy = AT->getElementType();
2235
2236 // Compute the type of the integer literals.
2237 QualType PromotedCharTy = CharTy;
2238 if (CharTy->isPromotableIntegerType())
2239 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2240 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2241
2242 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2243 // Get the length of the string.
2244 uint64_t StrLen = SL->getLength();
2245 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2246 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2247 StructuredList->resizeInits(Context, StrLen);
2248
2249 // Build a literal for each character in the string, and put them into
2250 // the init list.
2251 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2252 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2253 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002254 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002255 if (CharTy != PromotedCharTy)
2256 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002257 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002258 StructuredList->updateInit(Context, i, Init);
2259 }
2260 } else {
2261 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2262 std::string Str;
2263 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2264
2265 // Get the length of the string.
2266 uint64_t StrLen = Str.size();
2267 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2268 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2269 StructuredList->resizeInits(Context, StrLen);
2270
2271 // Build a literal for each character in the string, and put them into
2272 // the init list.
2273 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2274 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2275 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002276 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002277 if (CharTy != PromotedCharTy)
2278 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002279 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002280 StructuredList->updateInit(Context, i, Init);
2281 }
2282 }
2283 }
2284
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002285 // Make sure that our non-designated initializer list has space
2286 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002287 if (!VerifyOnly &&
2288 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002289 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002290 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002291
Douglas Gregor17bd0942009-01-28 23:36:17 +00002292 // Repeatedly perform subobject initializations in the range
2293 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002294
Douglas Gregor17bd0942009-01-28 23:36:17 +00002295 // Move to the next designator
2296 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2297 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002298
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002299 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002300 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002301
Douglas Gregor17bd0942009-01-28 23:36:17 +00002302 while (DesignatedStartIndex <= DesignatedEndIndex) {
2303 // Recurse to check later designated subobjects.
2304 QualType ElementType = AT->getElementType();
2305 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002306
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002307 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002308 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002309 ElementType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002310 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002311 (DesignatedStartIndex == DesignatedEndIndex),
2312 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002313 return true;
2314
2315 // Move to the next index in the array that we'll be initializing.
2316 ++DesignatedStartIndex;
2317 ElementIndex = DesignatedStartIndex.getZExtValue();
2318 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002319
2320 // If this the first designator, our caller will continue checking
2321 // the rest of this array subobject.
2322 if (IsFirstDesignator) {
2323 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002324 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002325 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002326 return false;
2327 }
Mike Stump11289f42009-09-09 15:08:12 +00002328
Douglas Gregor17bd0942009-01-28 23:36:17 +00002329 if (!FinishSubobjectInit)
2330 return false;
2331
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002332 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002333 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002334 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002335 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002336 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002337 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002338}
2339
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002340// Get the structured initializer list for a subobject of type
2341// @p CurrentObjectType.
2342InitListExpr *
2343InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2344 QualType CurrentObjectType,
2345 InitListExpr *StructuredList,
2346 unsigned StructuredIndex,
2347 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002348 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002349 return nullptr; // No structured list in verification-only mode.
2350 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002351 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002352 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002353 else if (StructuredIndex < StructuredList->getNumInits())
2354 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002355
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002356 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2357 return Result;
2358
2359 if (ExistingInit) {
2360 // We are creating an initializer list that initializes the
2361 // subobjects of the current object, but there was already an
2362 // initialization that completely initialized the current
2363 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002364 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002365 // struct X { int a, b; };
2366 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002367 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002368 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2369 // designated initializer re-initializes the whole
2370 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002371 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002372 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002373 << InitRange;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002374 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002375 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002376 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002377 << ExistingInit->getSourceRange();
2378 }
2379
Mike Stump11289f42009-09-09 15:08:12 +00002380 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002381 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002382 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002383 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002384
Eli Friedman91f5ae52012-02-23 02:25:10 +00002385 QualType ResultType = CurrentObjectType;
2386 if (!ResultType->isArrayType())
2387 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2388 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002389
Douglas Gregor6d00c992009-03-20 23:58:33 +00002390 // Pre-allocate storage for the structured initializer list.
2391 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002392 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002393 bool GotNumInits = false;
2394 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002395 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002396 GotNumInits = true;
2397 } else if (Index < IList->getNumInits()) {
2398 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002399 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002400 GotNumInits = true;
2401 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002402 }
2403
Mike Stump11289f42009-09-09 15:08:12 +00002404 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002405 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2406 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2407 NumElements = CAType->getSize().getZExtValue();
2408 // Simple heuristic so that we don't allocate a very large
2409 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002410 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002411 NumElements = 0;
2412 }
John McCall9dd450b2009-09-21 23:43:11 +00002413 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002414 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002415 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002416 RecordDecl *RDecl = RType->getDecl();
2417 if (RDecl->isUnion())
2418 NumElements = 1;
2419 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002420 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002421 }
2422
Ted Kremenekac034612010-04-13 23:39:13 +00002423 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002424
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002425 // Link this new initializer list into the structured initializer
2426 // lists.
2427 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002428 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002429 else {
2430 Result->setSyntacticForm(IList);
2431 SyntacticToSemantic[IList] = Result;
2432 }
2433
2434 return Result;
2435}
2436
2437/// Update the initializer at index @p StructuredIndex within the
2438/// structured initializer list to the value @p expr.
2439void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2440 unsigned &StructuredIndex,
2441 Expr *expr) {
2442 // No structured initializer list to update
2443 if (!StructuredList)
2444 return;
2445
Ted Kremenekac034612010-04-13 23:39:13 +00002446 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2447 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002448 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002449 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002450 diag::warn_initializer_overrides)
2451 << expr->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002452 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002453 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002454 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002455 << PrevInit->getSourceRange();
2456 }
Mike Stump11289f42009-09-09 15:08:12 +00002457
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002458 ++StructuredIndex;
2459}
2460
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002461/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002462/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002463/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002464/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002465/// failure. Returns the index expression, possibly with an implicit cast
2466/// added, on success. If everything went okay, Value will receive the
2467/// value of the constant expression.
2468static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002469CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002470 SourceLocation Loc = Index->getLocStart();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002471
2472 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002473 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2474 if (Result.isInvalid())
2475 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002476
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002477 if (Value.isSigned() && Value.isNegative())
2478 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002479 << Value.toString(10) << Index->getSourceRange();
2480
Douglas Gregor51650d32009-01-23 21:04:18 +00002481 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002482 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002483}
2484
John McCalldadc5752010-08-24 06:29:42 +00002485ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002486 SourceLocation Loc,
2487 bool GNUSyntax,
2488 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002489 typedef DesignatedInitExpr::Designator ASTDesignator;
2490
2491 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002492 SmallVector<ASTDesignator, 32> Designators;
2493 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002494
2495 // Build designators and check array designator expressions.
2496 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2497 const Designator &D = Desig.getDesignator(Idx);
2498 switch (D.getKind()) {
2499 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002500 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002501 D.getFieldLoc()));
2502 break;
2503
2504 case Designator::ArrayDesignator: {
2505 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2506 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002507 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002508 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002509 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002510 Invalid = true;
2511 else {
2512 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002513 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002514 D.getRBracketLoc()));
2515 InitExpressions.push_back(Index);
2516 }
2517 break;
2518 }
2519
2520 case Designator::ArrayRangeDesignator: {
2521 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2522 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2523 llvm::APSInt StartValue;
2524 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002525 bool StartDependent = StartIndex->isTypeDependent() ||
2526 StartIndex->isValueDependent();
2527 bool EndDependent = EndIndex->isTypeDependent() ||
2528 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002529 if (!StartDependent)
2530 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002531 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002532 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002533 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002534
2535 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002536 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002537 else {
2538 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002539 if (StartDependent || EndDependent) {
2540 // Nothing to compute.
2541 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002542 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002543 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002544 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002545
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002546 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002547 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002548 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002549 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2550 Invalid = true;
2551 } else {
2552 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002553 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002554 D.getEllipsisLoc(),
2555 D.getRBracketLoc()));
2556 InitExpressions.push_back(StartIndex);
2557 InitExpressions.push_back(EndIndex);
2558 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002559 }
2560 break;
2561 }
2562 }
2563 }
2564
2565 if (Invalid || Init.isInvalid())
2566 return ExprError();
2567
2568 // Clear out the expressions within the designation.
2569 Desig.ClearExprs(*this);
2570
2571 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002572 = DesignatedInitExpr::Create(Context,
2573 Designators.data(), Designators.size(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00002574 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002575 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002576
David Blaikiebbafb8a2012-03-11 07:00:24 +00002577 if (!getLangOpts().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002578 Diag(DIE->getLocStart(), diag::ext_designated_init)
2579 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002580
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002581 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002582}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002583
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002584//===----------------------------------------------------------------------===//
2585// Initialization entity
2586//===----------------------------------------------------------------------===//
2587
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002588InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002589 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002590 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002591{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002592 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2593 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002594 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002595 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002596 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002597 Type = VT->getElementType();
2598 } else {
2599 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2600 assert(CT && "Unexpected type");
2601 Kind = EK_ComplexElement;
2602 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002603 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002604}
2605
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002606InitializedEntity
2607InitializedEntity::InitializeBase(ASTContext &Context,
2608 const CXXBaseSpecifier *Base,
2609 bool IsInheritedVirtualBase) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002610 InitializedEntity Result;
2611 Result.Kind = EK_Base;
Craig Topperc3ec1492014-05-26 06:22:03 +00002612 Result.Parent = nullptr;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002613 Result.Base = reinterpret_cast<uintptr_t>(Base);
2614 if (IsInheritedVirtualBase)
2615 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002616
Douglas Gregor1b303932009-12-22 15:35:07 +00002617 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002618 return Result;
2619}
2620
Douglas Gregor85dabae2009-12-16 01:38:02 +00002621DeclarationName InitializedEntity::getName() const {
2622 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002623 case EK_Parameter:
2624 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00002625 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2626 return (D ? D->getDeclName() : DeclarationName());
2627 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002628
2629 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002630 case EK_Member:
2631 return VariableOrMember->getDeclName();
2632
Douglas Gregor19666fb2012-02-15 16:57:26 +00002633 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002634 return DeclarationName(Capture.VarID);
Douglas Gregor19666fb2012-02-15 16:57:26 +00002635
Douglas Gregor85dabae2009-12-16 01:38:02 +00002636 case EK_Result:
2637 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002638 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002639 case EK_Temporary:
2640 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002641 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002642 case EK_ArrayElement:
2643 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002644 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002645 case EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002646 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002647 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002648 return DeclarationName();
2649 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002650
David Blaikie8a40f702012-01-17 06:56:22 +00002651 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002652}
2653
Douglas Gregora4b592a2009-12-19 03:01:41 +00002654DeclaratorDecl *InitializedEntity::getDecl() const {
2655 switch (getKind()) {
2656 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002657 case EK_Member:
2658 return VariableOrMember;
2659
John McCall31168b02011-06-15 23:02:42 +00002660 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002661 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00002662 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2663
Douglas Gregora4b592a2009-12-19 03:01:41 +00002664 case EK_Result:
2665 case EK_Exception:
2666 case EK_New:
2667 case EK_Temporary:
2668 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002669 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002670 case EK_ArrayElement:
2671 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002672 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002673 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002674 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002675 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002676 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00002677 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00002678 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002679
David Blaikie8a40f702012-01-17 06:56:22 +00002680 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002681}
2682
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002683bool InitializedEntity::allowsNRVO() const {
2684 switch (getKind()) {
2685 case EK_Result:
2686 case EK_Exception:
2687 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002688
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002689 case EK_Variable:
2690 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002691 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002692 case EK_Member:
2693 case EK_New:
2694 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002695 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002696 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002697 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002698 case EK_ArrayElement:
2699 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002700 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002701 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002702 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002703 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002704 break;
2705 }
2706
2707 return false;
2708}
2709
Richard Smithe6c01442013-06-05 00:46:14 +00002710unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00002711 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00002712 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2713 for (unsigned I = 0; I != Depth; ++I)
2714 OS << "`-";
2715
2716 switch (getKind()) {
2717 case EK_Variable: OS << "Variable"; break;
2718 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002719 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2720 break;
Richard Smithe6c01442013-06-05 00:46:14 +00002721 case EK_Result: OS << "Result"; break;
2722 case EK_Exception: OS << "Exception"; break;
2723 case EK_Member: OS << "Member"; break;
2724 case EK_New: OS << "New"; break;
2725 case EK_Temporary: OS << "Temporary"; break;
2726 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002727 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00002728 case EK_Base: OS << "Base"; break;
2729 case EK_Delegating: OS << "Delegating"; break;
2730 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2731 case EK_VectorElement: OS << "VectorElement " << Index; break;
2732 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2733 case EK_BlockElement: OS << "Block"; break;
2734 case EK_LambdaCapture:
2735 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002736 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00002737 break;
2738 }
2739
2740 if (Decl *D = getDecl()) {
2741 OS << " ";
2742 cast<NamedDecl>(D)->printQualifiedName(OS);
2743 }
2744
2745 OS << " '" << getType().getAsString() << "'\n";
2746
2747 return Depth + 1;
2748}
2749
2750void InitializedEntity::dump() const {
2751 dumpImpl(llvm::errs());
2752}
2753
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002754//===----------------------------------------------------------------------===//
2755// Initialization sequence
2756//===----------------------------------------------------------------------===//
2757
2758void InitializationSequence::Step::Destroy() {
2759 switch (Kind) {
2760 case SK_ResolveAddressOfOverloadedFunction:
2761 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002762 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002763 case SK_CastDerivedToBaseLValue:
2764 case SK_BindReference:
2765 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002766 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002767 case SK_UserConversion:
2768 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002769 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002770 case SK_QualificationConversionLValue:
Jordan Roseb1312a52013-04-11 00:58:58 +00002771 case SK_LValueToRValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002772 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00002773 case SK_UnwrapInitList:
2774 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002775 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00002776 case SK_ConstructorInitializationFromList:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002777 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002778 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002779 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002780 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002781 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00002782 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002783 case SK_PassByIndirectCopyRestore:
2784 case SK_PassByIndirectRestore:
2785 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002786 case SK_StdInitializerList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00002787 case SK_StdInitializerListConstructorCall:
Guy Benyei61054192013-02-07 10:55:47 +00002788 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002789 case SK_OCLZeroEvent:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002790 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002791
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002792 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00002793 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002794 delete ICS;
2795 }
2796}
2797
Douglas Gregor838fcc32010-03-26 20:14:36 +00002798bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002799 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002800}
2801
2802bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002803 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002804 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002805
Douglas Gregor838fcc32010-03-26 20:14:36 +00002806 switch (getFailureKind()) {
2807 case FK_TooManyInitsForReference:
2808 case FK_ArrayNeedsInitList:
2809 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00002810 case FK_ArrayNeedsInitListOrWideStringLiteral:
2811 case FK_NarrowStringIntoWideCharArray:
2812 case FK_WideStringIntoCharArray:
2813 case FK_IncompatWideStringIntoWideChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002814 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2815 case FK_NonConstLValueReferenceBindingToTemporary:
2816 case FK_NonConstLValueReferenceBindingToUnrelated:
2817 case FK_RValueReferenceBindingToLValue:
2818 case FK_ReferenceInitDropsQualifiers:
2819 case FK_ReferenceInitFailed:
2820 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002821 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002822 case FK_TooManyInitsForScalar:
2823 case FK_ReferenceBindingToInitList:
2824 case FK_InitListBadDestinationType:
2825 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002826 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002827 case FK_ArrayTypeMismatch:
2828 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002829 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002830 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002831 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00002832 case FK_ExplicitConstructor:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002833 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002834
Douglas Gregor838fcc32010-03-26 20:14:36 +00002835 case FK_ReferenceInitOverloadFailed:
2836 case FK_UserConversionOverloadFailed:
2837 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002838 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002839 return FailedOverloadResult == OR_Ambiguous;
2840 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002841
David Blaikie8a40f702012-01-17 06:56:22 +00002842 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00002843}
2844
Douglas Gregorb33eed02010-04-16 22:09:46 +00002845bool InitializationSequence::isConstructorInitialization() const {
2846 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2847}
2848
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002849void
2850InitializationSequence
2851::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2852 DeclAccessPair Found,
2853 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002854 Step S;
2855 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2856 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002857 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002858 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002859 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002860 Steps.push_back(S);
2861}
2862
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002863void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002864 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002865 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002866 switch (VK) {
2867 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2868 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2869 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002870 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002871 S.Type = BaseType;
2872 Steps.push_back(S);
2873}
2874
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002875void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002876 bool BindingTemporary) {
2877 Step S;
2878 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2879 S.Type = T;
2880 Steps.push_back(S);
2881}
2882
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002883void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2884 Step S;
2885 S.Kind = SK_ExtraneousCopyToTemporary;
2886 S.Type = T;
2887 Steps.push_back(S);
2888}
2889
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002890void
2891InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2892 DeclAccessPair FoundDecl,
2893 QualType T,
2894 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002895 Step S;
2896 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002897 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002898 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002899 S.Function.Function = Function;
2900 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002901 Steps.push_back(S);
2902}
2903
2904void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002905 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002906 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002907 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002908 switch (VK) {
2909 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002910 S.Kind = SK_QualificationConversionRValue;
2911 break;
John McCall2536c6d2010-08-25 10:28:54 +00002912 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002913 S.Kind = SK_QualificationConversionXValue;
2914 break;
John McCall2536c6d2010-08-25 10:28:54 +00002915 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002916 S.Kind = SK_QualificationConversionLValue;
2917 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002918 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002919 S.Type = Ty;
2920 Steps.push_back(S);
2921}
2922
Jordan Roseb1312a52013-04-11 00:58:58 +00002923void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2924 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2925
2926 Step S;
2927 S.Kind = SK_LValueToRValue;
2928 S.Type = Ty;
2929 Steps.push_back(S);
2930}
2931
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002932void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00002933 const ImplicitConversionSequence &ICS, QualType T,
2934 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002935 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00002936 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
2937 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002938 S.Type = T;
2939 S.ICS = new ImplicitConversionSequence(ICS);
2940 Steps.push_back(S);
2941}
2942
Douglas Gregor51e77d52009-12-10 17:56:55 +00002943void InitializationSequence::AddListInitializationStep(QualType T) {
2944 Step S;
2945 S.Kind = SK_ListInitialization;
2946 S.Type = T;
2947 Steps.push_back(S);
2948}
2949
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002950void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002951InitializationSequence
2952::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2953 AccessSpecifier Access,
2954 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002955 bool HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002956 bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002957 Step S;
Richard Smithf8adcdc2014-07-17 05:12:35 +00002958 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
Richard Smith53324112014-07-16 21:33:43 +00002959 : SK_ConstructorInitializationFromList
2960 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002961 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002962 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002963 S.Function.Function = Constructor;
2964 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002965 Steps.push_back(S);
2966}
2967
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002968void InitializationSequence::AddZeroInitializationStep(QualType T) {
2969 Step S;
2970 S.Kind = SK_ZeroInitialization;
2971 S.Type = T;
2972 Steps.push_back(S);
2973}
2974
Douglas Gregore1314a62009-12-18 05:02:21 +00002975void InitializationSequence::AddCAssignmentStep(QualType T) {
2976 Step S;
2977 S.Kind = SK_CAssignment;
2978 S.Type = T;
2979 Steps.push_back(S);
2980}
2981
Eli Friedman78275202009-12-19 08:11:05 +00002982void InitializationSequence::AddStringInitStep(QualType T) {
2983 Step S;
2984 S.Kind = SK_StringInit;
2985 S.Type = T;
2986 Steps.push_back(S);
2987}
2988
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002989void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2990 Step S;
2991 S.Kind = SK_ObjCObjectConversion;
2992 S.Type = T;
2993 Steps.push_back(S);
2994}
2995
Douglas Gregore2f943b2011-02-22 18:29:51 +00002996void InitializationSequence::AddArrayInitStep(QualType T) {
2997 Step S;
2998 S.Kind = SK_ArrayInit;
2999 S.Type = T;
3000 Steps.push_back(S);
3001}
3002
Richard Smithebeed412012-02-15 22:38:09 +00003003void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3004 Step S;
3005 S.Kind = SK_ParenthesizedArrayInit;
3006 S.Type = T;
3007 Steps.push_back(S);
3008}
3009
John McCall31168b02011-06-15 23:02:42 +00003010void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3011 bool shouldCopy) {
3012 Step s;
3013 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3014 : SK_PassByIndirectRestore);
3015 s.Type = type;
3016 Steps.push_back(s);
3017}
3018
3019void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3020 Step S;
3021 S.Kind = SK_ProduceObjCObject;
3022 S.Type = T;
3023 Steps.push_back(S);
3024}
3025
Sebastian Redlc1839b12012-01-17 22:49:42 +00003026void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3027 Step S;
3028 S.Kind = SK_StdInitializerList;
3029 S.Type = T;
3030 Steps.push_back(S);
3031}
3032
Guy Benyei61054192013-02-07 10:55:47 +00003033void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3034 Step S;
3035 S.Kind = SK_OCLSamplerInit;
3036 S.Type = T;
3037 Steps.push_back(S);
3038}
3039
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003040void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3041 Step S;
3042 S.Kind = SK_OCLZeroEvent;
3043 S.Type = T;
3044 Steps.push_back(S);
3045}
3046
Sebastian Redl29526f02011-11-27 16:50:07 +00003047void InitializationSequence::RewrapReferenceInitList(QualType T,
3048 InitListExpr *Syntactic) {
3049 assert(Syntactic->getNumInits() == 1 &&
3050 "Can only rewrap trivial init lists.");
3051 Step S;
3052 S.Kind = SK_UnwrapInitList;
3053 S.Type = Syntactic->getInit(0)->getType();
3054 Steps.insert(Steps.begin(), S);
3055
3056 S.Kind = SK_RewrapInitList;
3057 S.Type = T;
3058 S.WrappingSyntacticList = Syntactic;
3059 Steps.push_back(S);
3060}
3061
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003062void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003063 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00003064 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003065 this->Failure = Failure;
3066 this->FailedOverloadResult = Result;
3067}
3068
3069//===----------------------------------------------------------------------===//
3070// Attempt initialization
3071//===----------------------------------------------------------------------===//
3072
John McCall31168b02011-06-15 23:02:42 +00003073static void MaybeProduceObjCObject(Sema &S,
3074 InitializationSequence &Sequence,
3075 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003076 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00003077
3078 /// When initializing a parameter, produce the value if it's marked
3079 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003080 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00003081 if (!Entity.isParameterConsumed())
3082 return;
3083
3084 assert(Entity.getType()->isObjCRetainableType() &&
3085 "consuming an object of unretainable type?");
3086 Sequence.AddProduceObjCObjectStep(Entity.getType());
3087
3088 /// When initializing a return value, if the return type is a
3089 /// retainable type, then returns need to immediately retain the
3090 /// object. If an autorelease is required, it will be done at the
3091 /// last instant.
3092 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3093 if (!Entity.getType()->isObjCRetainableType())
3094 return;
3095
3096 Sequence.AddProduceObjCObjectStep(Entity.getType());
3097 }
3098}
3099
Richard Smithcc1b96d2013-06-12 22:31:48 +00003100static void TryListInitialization(Sema &S,
3101 const InitializedEntity &Entity,
3102 const InitializationKind &Kind,
3103 InitListExpr *InitList,
3104 InitializationSequence &Sequence);
3105
Richard Smithd86812d2012-07-05 08:39:21 +00003106/// \brief When initializing from init list via constructor, handle
3107/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003108///
Richard Smithd86812d2012-07-05 08:39:21 +00003109/// \return true if we have handled initialization of an object of type
3110/// std::initializer_list<T>, false otherwise.
3111static bool TryInitializerListConstruction(Sema &S,
3112 InitListExpr *List,
3113 QualType DestType,
3114 InitializationSequence &Sequence) {
3115 QualType E;
3116 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003117 return false;
3118
Richard Smithcc1b96d2013-06-12 22:31:48 +00003119 if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
3120 Sequence.setIncompleteTypeFailure(E);
3121 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003122 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003123
3124 // Try initializing a temporary array from the init list.
3125 QualType ArrayType = S.Context.getConstantArrayType(
3126 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3127 List->getNumInits()),
3128 clang::ArrayType::Normal, 0);
3129 InitializedEntity HiddenArray =
3130 InitializedEntity::InitializeTemporary(ArrayType);
3131 InitializationKind Kind =
3132 InitializationKind::CreateDirectList(List->getExprLoc());
3133 TryListInitialization(S, HiddenArray, Kind, List, Sequence);
3134 if (Sequence)
3135 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003136 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003137}
3138
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003139static OverloadingResult
3140ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003141 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003142 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003143 ArrayRef<NamedDecl *> Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003144 OverloadCandidateSet::iterator &Best,
3145 bool CopyInitializing, bool AllowExplicit,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003146 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003147 CandidateSet.clear();
3148
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003149 for (ArrayRef<NamedDecl *>::iterator
3150 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003151 NamedDecl *D = *Con;
3152 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3153 bool SuppressUserConversions = false;
3154
3155 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003156 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003157 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3158 if (ConstructorTmpl)
3159 Constructor = cast<CXXConstructorDecl>(
3160 ConstructorTmpl->getTemplatedDecl());
3161 else {
3162 Constructor = cast<CXXConstructorDecl>(D);
3163
Richard Smith6c6ddab2013-09-21 21:23:47 +00003164 // C++11 [over.best.ics]p4:
3165 // However, when considering the argument of a constructor or
3166 // user-defined conversion function that is a candidate:
3167 // -- by 13.3.1.3 when invoked for the copying/moving of a temporary
3168 // in the second step of a class copy-initialization,
3169 // -- by 13.3.1.7 when passing the initializer list as a single
3170 // argument or when the initializer list has exactly one elementand
3171 // a conversion to some class X or reference to (possibly
3172 // cv-qualified) X is considered for the first parameter of a
3173 // constructor of X, or
3174 // -- by 13.3.1.4, 13.3.1.5, or 13.3.1.6 in all cases,
3175 // only standard conversion sequences and ellipsis conversion sequences
3176 // are considered.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003177 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003178 Constructor->isCopyOrMoveConstructor())
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003179 SuppressUserConversions = true;
3180 }
3181
3182 if (!Constructor->isInvalidDecl() &&
3183 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003184 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003185 if (ConstructorTmpl)
3186 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003187 /*ExplicitArgs*/ nullptr, Args,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003188 CandidateSet, SuppressUserConversions);
Douglas Gregor6073dca2012-02-24 23:56:31 +00003189 else {
3190 // C++ [over.match.copy]p1:
3191 // - When initializing a temporary to be bound to the first parameter
3192 // of a constructor that takes a reference to possibly cv-qualified
3193 // T as its first argument, called with a single argument in the
3194 // context of direct-initialization, explicit conversion functions
3195 // are also considered.
3196 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003197 Args.size() == 1 &&
Douglas Gregor6073dca2012-02-24 23:56:31 +00003198 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003199 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003200 SuppressUserConversions,
3201 /*PartialOverloading=*/false,
3202 /*AllowExplicit=*/AllowExplicitConv);
3203 }
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003204 }
3205 }
3206
3207 // Perform overload resolution and return the result.
3208 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3209}
3210
Sebastian Redled2e5322011-12-22 14:44:04 +00003211/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3212/// enumerates the constructors of the initialized entity and performs overload
3213/// resolution to select the best.
Sebastian Redl88e4d492012-02-04 21:27:33 +00003214/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redled2e5322011-12-22 14:44:04 +00003215/// class type.
3216static void TryConstructorInitialization(Sema &S,
3217 const InitializedEntity &Entity,
3218 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003219 MultiExprArg Args, QualType DestType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003220 InitializationSequence &Sequence,
Sebastian Redl88e4d492012-02-04 21:27:33 +00003221 bool InitListSyntax = false) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003222 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Sebastian Redl88e4d492012-02-04 21:27:33 +00003223 "InitListSyntax must come with a single initializer list argument.");
3224
Sebastian Redled2e5322011-12-22 14:44:04 +00003225 // The type we're constructing needs to be complete.
3226 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003227 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003228 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003229 }
3230
3231 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3232 assert(DestRecordType && "Constructor initialization requires record type");
3233 CXXRecordDecl *DestRecordDecl
3234 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3235
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003236 // Build the candidate set directly in the initialization sequence
3237 // structure, so that it will persist if we fail.
3238 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3239
3240 // Determine whether we are allowed to call explicit constructors or
3241 // explicit conversion operators.
Sebastian Redl048a6d72012-04-01 19:54:59 +00003242 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003243 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003244
Sebastian Redled2e5322011-12-22 14:44:04 +00003245 // - Otherwise, if T is a class type, constructors are considered. The
3246 // applicable constructors are enumerated, and the best one is chosen
3247 // through overload resolution.
David Blaikieff7d47a2012-12-19 00:45:41 +00003248 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003249 // The container holding the constructors can under certain conditions
3250 // be changed while iterating (e.g. because of deserialization).
3251 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003252 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redled2e5322011-12-22 14:44:04 +00003253
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003254 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003255 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003256 bool AsInitializerList = false;
3257
3258 // C++11 [over.match.list]p1:
3259 // When objects of non-aggregate type T are list-initialized, overload
3260 // resolution selects the constructor in two phases:
3261 // - Initially, the candidate functions are the initializer-list
3262 // constructors of the class T and the argument list consists of the
3263 // initializer list as a single argument.
3264 if (InitListSyntax) {
Richard Smithd86812d2012-07-05 08:39:21 +00003265 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003266 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003267
3268 // If the initializer list has no elements and T has a default constructor,
3269 // the first phase is omitted.
Richard Smith2be35f52012-12-01 02:35:44 +00003270 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003271 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003272 CandidateSet, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003273 CopyInitialization, AllowExplicit,
3274 /*OnlyListConstructor=*/true,
3275 InitListSyntax);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003276
3277 // Time to unwrap the init list.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003278 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003279 }
3280
3281 // C++11 [over.match.list]p1:
3282 // - If no viable initializer-list constructor is found, overload resolution
3283 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003284 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003285 // elements of the initializer list.
3286 if (Result == OR_No_Viable_Function) {
3287 AsInitializerList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003288 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003289 CandidateSet, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003290 CopyInitialization, AllowExplicit,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003291 /*OnlyListConstructors=*/false,
3292 InitListSyntax);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003293 }
3294 if (Result) {
Sebastian Redl88e4d492012-02-04 21:27:33 +00003295 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003296 InitializationSequence::FK_ListConstructorOverloadFailed :
3297 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003298 Result);
3299 return;
3300 }
3301
Richard Smithd86812d2012-07-05 08:39:21 +00003302 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003303 // If a program calls for the default initialization of an object
3304 // of a const-qualified type T, T shall be a class type with a
3305 // user-provided default constructor.
3306 if (Kind.getKind() == InitializationKind::IK_Default &&
3307 Entity.getType().isConstQualified() &&
Aaron Ballman899b9c62012-07-31 22:40:31 +00003308 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redled2e5322011-12-22 14:44:04 +00003309 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3310 return;
3311 }
3312
Sebastian Redl048a6d72012-04-01 19:54:59 +00003313 // C++11 [over.match.list]p1:
3314 // In copy-list-initialization, if an explicit constructor is chosen, the
3315 // initializer is ill-formed.
3316 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3317 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3318 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3319 return;
3320 }
3321
Sebastian Redled2e5322011-12-22 14:44:04 +00003322 // Add the constructor initialization step. Any cv-qualification conversion is
3323 // subsumed by the initialization.
3324 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redled2e5322011-12-22 14:44:04 +00003325 Sequence.AddConstructorInitializationStep(CtorDecl,
3326 Best->FoundDecl.getAccess(),
3327 DestType, HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003328 InitListSyntax, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003329}
3330
Sebastian Redl29526f02011-11-27 16:50:07 +00003331static bool
3332ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3333 Expr *Initializer,
3334 QualType &SourceType,
3335 QualType &UnqualifiedSourceType,
3336 QualType UnqualifiedTargetType,
3337 InitializationSequence &Sequence) {
3338 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3339 S.Context.OverloadTy) {
3340 DeclAccessPair Found;
3341 bool HadMultipleCandidates = false;
3342 if (FunctionDecl *Fn
3343 = S.ResolveAddressOfOverloadedFunction(Initializer,
3344 UnqualifiedTargetType,
3345 false, Found,
3346 &HadMultipleCandidates)) {
3347 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3348 HadMultipleCandidates);
3349 SourceType = Fn->getType();
3350 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3351 } else if (!UnqualifiedTargetType->isRecordType()) {
3352 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3353 return true;
3354 }
3355 }
3356 return false;
3357}
3358
3359static void TryReferenceInitializationCore(Sema &S,
3360 const InitializedEntity &Entity,
3361 const InitializationKind &Kind,
3362 Expr *Initializer,
3363 QualType cv1T1, QualType T1,
3364 Qualifiers T1Quals,
3365 QualType cv2T2, QualType T2,
3366 Qualifiers T2Quals,
3367 InitializationSequence &Sequence);
3368
Richard Smithd86812d2012-07-05 08:39:21 +00003369static void TryValueInitialization(Sema &S,
3370 const InitializedEntity &Entity,
3371 const InitializationKind &Kind,
3372 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00003373 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00003374
Sebastian Redl29526f02011-11-27 16:50:07 +00003375/// \brief Attempt list initialization of a reference.
3376static void TryReferenceListInitialization(Sema &S,
3377 const InitializedEntity &Entity,
3378 const InitializationKind &Kind,
3379 InitListExpr *InitList,
Richard Smithfaadef72013-06-08 00:02:08 +00003380 InitializationSequence &Sequence) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003381 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003382 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003383 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3384 return;
3385 }
3386
3387 QualType DestType = Entity.getType();
3388 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3389 Qualifiers T1Quals;
3390 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3391
3392 // Reference initialization via an initializer list works thus:
3393 // If the initializer list consists of a single element that is
3394 // reference-related to the referenced type, bind directly to that element
3395 // (possibly creating temporaries).
3396 // Otherwise, initialize a temporary with the initializer list and
3397 // bind to that.
3398 if (InitList->getNumInits() == 1) {
3399 Expr *Initializer = InitList->getInit(0);
3400 QualType cv2T2 = Initializer->getType();
3401 Qualifiers T2Quals;
3402 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3403
3404 // If this fails, creating a temporary wouldn't work either.
3405 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3406 T1, Sequence))
3407 return;
3408
3409 SourceLocation DeclLoc = Initializer->getLocStart();
3410 bool dummy1, dummy2, dummy3;
3411 Sema::ReferenceCompareResult RefRelationship
3412 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3413 dummy2, dummy3);
3414 if (RefRelationship >= Sema::Ref_Related) {
3415 // Try to bind the reference here.
3416 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3417 T1Quals, cv2T2, T2, T2Quals, Sequence);
3418 if (Sequence)
3419 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3420 return;
3421 }
Richard Smith03d93932013-01-15 07:58:29 +00003422
3423 // Update the initializer if we've resolved an overloaded function.
3424 if (Sequence.step_begin() != Sequence.step_end())
3425 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00003426 }
3427
3428 // Not reference-related. Create a temporary and bind to that.
3429 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3430
3431 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3432 if (Sequence) {
3433 if (DestType->isRValueReferenceType() ||
3434 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3435 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3436 else
3437 Sequence.SetFailed(
3438 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3439 }
3440}
3441
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003442/// \brief Attempt list initialization (C++0x [dcl.init.list])
3443static void TryListInitialization(Sema &S,
3444 const InitializedEntity &Entity,
3445 const InitializationKind &Kind,
3446 InitListExpr *InitList,
3447 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003448 QualType DestType = Entity.getType();
3449
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003450 // C++ doesn't allow scalar initialization with more than one argument.
3451 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003452 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003453 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3454 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3455 return;
3456 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003457 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003458 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003459 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003460 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003461 if (DestType->isRecordType()) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003462 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003463 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl4f28b582012-02-19 12:27:43 +00003464 return;
3465 }
3466
Richard Smithd86812d2012-07-05 08:39:21 +00003467 // C++11 [dcl.init.list]p3:
3468 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redl4f28b582012-02-19 12:27:43 +00003469 if (!DestType->isAggregateType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003470 if (S.getLangOpts().CPlusPlus11) {
Richard Smithd86812d2012-07-05 08:39:21 +00003471 // - Otherwise, if the initializer list has no elements and T is a
3472 // class type with a default constructor, the object is
3473 // value-initialized.
3474 if (InitList->getNumInits() == 0) {
3475 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
Richard Smith2be35f52012-12-01 02:35:44 +00003476 if (RD->hasDefaultConstructor()) {
Richard Smithd86812d2012-07-05 08:39:21 +00003477 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3478 return;
3479 }
3480 }
3481
3482 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3483 // an initializer_list object constructed [...]
3484 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3485 return;
3486
3487 // - Otherwise, if T is a class type, constructors are considered.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003488 Expr *InitListAsExpr = InitList;
3489 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smithd86812d2012-07-05 08:39:21 +00003490 Sequence, /*InitListSyntax*/true);
Sebastian Redl4f28b582012-02-19 12:27:43 +00003491 } else
3492 Sequence.SetFailed(
3493 InitializationSequence::FK_InitListBadDestinationType);
3494 return;
3495 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003496 }
Richard Smith089c3162013-09-21 21:55:46 +00003497 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
3498 InitList->getNumInits() == 1 &&
3499 InitList->getInit(0)->getType()->isRecordType()) {
3500 // - Otherwise, if the initializer list has a single element of type E
3501 // [...references are handled above...], the object or reference is
3502 // initialized from that element; if a narrowing conversion is required
3503 // to convert the element to T, the program is ill-formed.
3504 //
3505 // Per core-24034, this is direct-initialization if we were performing
3506 // direct-list-initialization and copy-initialization otherwise.
3507 // We can't use InitListChecker for this, because it always performs
3508 // copy-initialization. This only matters if we might use an 'explicit'
3509 // conversion operator, so we only need to handle the cases where the source
3510 // is of record type.
3511 InitializationKind SubKind =
3512 Kind.getKind() == InitializationKind::IK_DirectList
3513 ? InitializationKind::CreateDirect(Kind.getLocation(),
3514 InitList->getLBraceLoc(),
3515 InitList->getRBraceLoc())
3516 : Kind;
3517 Expr *SubInit[1] = { InitList->getInit(0) };
3518 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3519 /*TopLevelOfInitList*/true);
3520 if (Sequence)
3521 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3522 return;
3523 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003524
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003525 InitListChecker CheckInitList(S, Entity, InitList,
Richard Smithde229232013-06-06 11:41:05 +00003526 DestType, /*VerifyOnly=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003527 if (CheckInitList.HadError()) {
3528 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3529 return;
3530 }
3531
3532 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003533 Sequence.AddListInitializationStep(DestType);
3534}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003535
3536/// \brief Try a reference initialization that involves calling a conversion
3537/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003538static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3539 const InitializedEntity &Entity,
3540 const InitializationKind &Kind,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003541 Expr *Initializer,
3542 bool AllowRValues,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003543 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003544 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003545 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3546 QualType T1 = cv1T1.getUnqualifiedType();
3547 QualType cv2T2 = Initializer->getType();
3548 QualType T2 = cv2T2.getUnqualifiedType();
3549
3550 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003551 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003552 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003553 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003554 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003555 ObjCConversion,
3556 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003557 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003558 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003559 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003560 (void)ObjCLifetimeConversion;
3561
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003562 // Build the candidate set directly in the initialization sequence
3563 // structure, so that it will persist if we fail.
3564 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3565 CandidateSet.clear();
3566
3567 // Determine whether we are allowed to call explicit constructors or
3568 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003569 bool AllowExplicit = Kind.AllowExplicit();
Richard Smith6c6ddab2013-09-21 21:23:47 +00003570 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3571
Craig Topperc3ec1492014-05-26 06:22:03 +00003572 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003573 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3574 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003575 // The type we're converting to is a class type. Enumerate its constructors
3576 // to see if there is a suitable conversion.
3577 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003578
David Blaikieff7d47a2012-12-19 00:45:41 +00003579 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003580 // The container holding the constructors can under certain conditions
3581 // be changed while iterating (e.g. because of deserialization).
3582 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003583 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00003584 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003585 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3586 NamedDecl *D = *CI;
John McCalla0296f72010-03-19 07:35:19 +00003587 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3588
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003589 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003590 CXXConstructorDecl *Constructor = nullptr;
John McCalla0296f72010-03-19 07:35:19 +00003591 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003592 if (ConstructorTmpl)
3593 Constructor = cast<CXXConstructorDecl>(
3594 ConstructorTmpl->getTemplatedDecl());
3595 else
John McCalla0296f72010-03-19 07:35:19 +00003596 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003597
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003598 if (!Constructor->isInvalidDecl() &&
3599 Constructor->isConvertingConstructor(AllowExplicit)) {
3600 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003601 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003602 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003603 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003604 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003605 else
John McCalla0296f72010-03-19 07:35:19 +00003606 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003607 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003608 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003609 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003610 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003611 }
John McCall3696dcb2010-08-17 07:23:57 +00003612 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3613 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003614
Craig Topperc3ec1492014-05-26 06:22:03 +00003615 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003616 if ((T2RecordType = T2->getAs<RecordType>()) &&
3617 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003618 // The type we're converting from is a class type, enumerate its conversion
3619 // functions.
3620 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3621
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003622 std::pair<CXXRecordDecl::conversion_iterator,
3623 CXXRecordDecl::conversion_iterator>
3624 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3625 for (CXXRecordDecl::conversion_iterator
3626 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003627 NamedDecl *D = *I;
3628 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3629 if (isa<UsingShadowDecl>(D))
3630 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003631
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003632 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3633 CXXConversionDecl *Conv;
3634 if (ConvTemplate)
3635 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3636 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003637 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003638
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003639 // If the conversion function doesn't return a reference type,
3640 // it can't be considered for this conversion unless we're allowed to
3641 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003642 // FIXME: Do we need to make sure that we only consider conversion
3643 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003644 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00003645 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003646 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3647 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003648 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003649 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00003650 DestType, CandidateSet,
3651 /*AllowObjCConversionOnExplicit=*/
3652 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003653 else
John McCalla0296f72010-03-19 07:35:19 +00003654 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00003655 Initializer, DestType, CandidateSet,
3656 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003657 }
3658 }
3659 }
John McCall3696dcb2010-08-17 07:23:57 +00003660 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3661 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003662
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003663 SourceLocation DeclLoc = Initializer->getLocStart();
3664
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003665 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003666 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003667 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003668 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003669 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003670
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003671 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00003672 // This is the overload that will be used for this initialization step if we
3673 // use this initialization. Mark it as referenced.
3674 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00003675
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003676 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003677 if (isa<CXXConversionDecl>(Function))
Alp Toker314cc812014-01-25 16:55:45 +00003678 T2 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003679 else
3680 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003681
3682 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003683 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003684 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003685 T2.getNonLValueExprType(S.Context),
3686 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003687
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003688 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003689 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003690 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003691 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003692 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003693 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003694 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003695
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003696 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003697 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003698 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003699 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003700 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003701 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003702 NewDerivedToBase, NewObjCConversion,
3703 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003704 if (NewRefRelationship == Sema::Ref_Incompatible) {
3705 // If the type we've converted to is not reference-related to the
3706 // type we're looking for, then there is another conversion step
3707 // we need to perform to produce a temporary of the right type
3708 // that we'll be binding to.
3709 ImplicitConversionSequence ICS;
3710 ICS.setStandard();
3711 ICS.Standard = Best->FinalConversion;
3712 T2 = ICS.Standard.getToType(2);
3713 Sequence.AddConversionSequenceStep(ICS, T2);
3714 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003715 Sequence.AddDerivedToBaseCastStep(
3716 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003717 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003718 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003719 else if (NewObjCConversion)
3720 Sequence.AddObjCObjectConversionStep(
3721 S.Context.getQualifiedType(T1,
3722 T2.getNonReferenceType().getQualifiers()));
3723
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003724 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003725 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003726
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003727 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3728 return OR_Success;
3729}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003730
Richard Smithc620f552011-10-19 16:55:56 +00003731static void CheckCXX98CompatAccessibleCopy(Sema &S,
3732 const InitializedEntity &Entity,
3733 Expr *CurInitExpr);
3734
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003735/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3736static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003737 const InitializedEntity &Entity,
3738 const InitializationKind &Kind,
3739 Expr *Initializer,
3740 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003741 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003742 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003743 Qualifiers T1Quals;
3744 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003745 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003746 Qualifiers T2Quals;
3747 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003748
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003749 // If the initializer is the address of an overloaded function, try
3750 // to resolve the overloaded function. If all goes well, T2 is the
3751 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003752 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3753 T1, Sequence))
3754 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003755
Sebastian Redl29526f02011-11-27 16:50:07 +00003756 // Delegate everything else to a subfunction.
3757 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3758 T1Quals, cv2T2, T2, T2Quals, Sequence);
3759}
3760
Jordan Roseb1312a52013-04-11 00:58:58 +00003761/// Converts the target of reference initialization so that it has the
3762/// appropriate qualifiers and value kind.
3763///
3764/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3765/// \code
3766/// int x;
3767/// const int &r = x;
3768/// \endcode
3769///
3770/// In this case the reference is binding to a bitfield lvalue, which isn't
3771/// valid. Perform a load to create a lifetime-extended temporary instead.
3772/// \code
3773/// const int &r = someStruct.bitfield;
3774/// \endcode
3775static ExprValueKind
3776convertQualifiersAndValueKindIfNecessary(Sema &S,
3777 InitializationSequence &Sequence,
3778 Expr *Initializer,
3779 QualType cv1T1,
3780 Qualifiers T1Quals,
3781 Qualifiers T2Quals,
3782 bool IsLValueRef) {
John McCalld25db7e2013-05-06 21:39:12 +00003783 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Roseb1312a52013-04-11 00:58:58 +00003784 Initializer->refersToVectorElement();
3785
3786 if (IsNonAddressableType) {
3787 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3788 // lvalue reference to a non-volatile const type, or the reference shall be
3789 // an rvalue reference.
3790 //
3791 // If not, we can't make a temporary and bind to that. Give up and allow the
3792 // error to be diagnosed later.
3793 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3794 assert(Initializer->isGLValue());
3795 return Initializer->getValueKind();
3796 }
3797
3798 // Force a load so we can materialize a temporary.
3799 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3800 return VK_RValue;
3801 }
3802
3803 if (T1Quals != T2Quals) {
3804 Sequence.AddQualificationConversionStep(cv1T1,
3805 Initializer->getValueKind());
3806 }
3807
3808 return Initializer->getValueKind();
3809}
3810
3811
Sebastian Redl29526f02011-11-27 16:50:07 +00003812/// \brief Reference initialization without resolving overloaded functions.
3813static void TryReferenceInitializationCore(Sema &S,
3814 const InitializedEntity &Entity,
3815 const InitializationKind &Kind,
3816 Expr *Initializer,
3817 QualType cv1T1, QualType T1,
3818 Qualifiers T1Quals,
3819 QualType cv2T2, QualType T2,
3820 Qualifiers T2Quals,
3821 InitializationSequence &Sequence) {
3822 QualType DestType = Entity.getType();
3823 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003824 // Compute some basic properties of the types and the initializer.
3825 bool isLValueRef = DestType->isLValueReferenceType();
3826 bool isRValueRef = !isLValueRef;
3827 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003828 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003829 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003830 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003831 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003832 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003833 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003834
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003835 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003836 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003837 // "cv2 T2" as follows:
3838 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003839 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003840 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00003841 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00003842 // there are no function rvalues in C++, rvalue refs to functions are treated
3843 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003844 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003845 bool T1Function = T1->isFunctionType();
3846 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003847 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003848 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003849 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003850 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003851 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003852 // reference-compatible with "cv2 T2," or
3853 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003854 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003855 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003856 // can occur. However, we do pay attention to whether it is a bit-field
3857 // to decide whether we're actually binding to a temporary created from
3858 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003859 if (DerivedToBase)
3860 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003861 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003862 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003863 else if (ObjCConversion)
3864 Sequence.AddObjCObjectConversionStep(
3865 S.Context.getQualifiedType(T1, T2Quals));
3866
Jordan Roseb1312a52013-04-11 00:58:58 +00003867 ExprValueKind ValueKind =
3868 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3869 cv1T1, T1Quals, T2Quals,
3870 isLValueRef);
3871 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003872 return;
3873 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003874
3875 // - has a class type (i.e., T2 is a class type), where T1 is not
3876 // reference-related to T2, and can be implicitly converted to an
3877 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3878 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003879 // applicable conversion functions (13.3.1.6) and choosing the best
3880 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003881 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00003882 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00003883 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3884 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003885 ConvOvlResult = TryRefInitWithConversionFunction(
3886 S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003887 if (ConvOvlResult == OR_Success)
3888 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00003889 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00003890 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003891 InitializationSequence::FK_ReferenceInitOverloadFailed,
3892 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003893 }
3894 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003895
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003896 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003897 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003898 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003899 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003900 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3901 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3902 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003903 Sequence.SetOverloadFailure(
3904 InitializationSequence::FK_ReferenceInitOverloadFailed,
3905 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003906 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003907 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003908 ? (RefRelationship == Sema::Ref_Related
3909 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3910 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3911 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003912
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003913 return;
3914 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003915
Douglas Gregor92e460e2011-01-20 16:44:54 +00003916 // - If the initializer expression
3917 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3918 // "cv1 T1" is reference-compatible with "cv2 T2"
3919 // Note: functions are handled below.
3920 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003921 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003922 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003923 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003924 (InitCategory.isXValue() ||
3925 (InitCategory.isPRValue() && T2->isRecordType()) ||
3926 (InitCategory.isPRValue() && T2->isArrayType()))) {
3927 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3928 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003929 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3930 // compiler the freedom to perform a copy here or bind to the
3931 // object, while C++0x requires that we bind directly to the
3932 // object. Hence, we always bind to the object without making an
3933 // extra copy. However, in C++03 requires that we check for the
3934 // presence of a suitable copy constructor:
3935 //
3936 // The constructor that would be used to make the copy shall
3937 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003938 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003939 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003940 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00003941 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003942 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003943
Douglas Gregor92e460e2011-01-20 16:44:54 +00003944 if (DerivedToBase)
3945 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3946 ValueKind);
3947 else if (ObjCConversion)
3948 Sequence.AddObjCObjectConversionStep(
3949 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003950
Jordan Roseb1312a52013-04-11 00:58:58 +00003951 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3952 Initializer, cv1T1,
3953 T1Quals, T2Quals,
3954 isLValueRef);
3955
3956 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003957 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003958 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003959
3960 // - has a class type (i.e., T2 is a class type), where T1 is not
3961 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003962 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3963 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00003964 //
3965 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00003966 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003967 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003968 ConvOvlResult = TryRefInitWithConversionFunction(
3969 S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003970 if (ConvOvlResult)
3971 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003972 InitializationSequence::FK_ReferenceInitOverloadFailed,
3973 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003974
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003975 return;
3976 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003977
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00003978 if ((RefRelationship == Sema::Ref_Compatible ||
3979 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3980 isRValueRef && InitCategory.isLValue()) {
3981 Sequence.SetFailed(
3982 InitializationSequence::FK_RValueReferenceBindingToLValue);
3983 return;
3984 }
3985
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003986 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3987 return;
3988 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003989
3990 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003991 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00003992 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003993 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003994
John McCallec6f4e92010-06-04 02:29:22 +00003995 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3996
Richard Smith2eabf782013-06-13 00:57:57 +00003997 // FIXME: Why do we use an implicit conversion here rather than trying
3998 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00003999 ImplicitConversionSequence ICS
4000 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00004001 /*SuppressUserConversions=*/false,
4002 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004003 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004004 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4005 /*AllowObjCWritebackConversion=*/false);
4006
4007 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004008 // FIXME: Use the conversion function set stored in ICS to turn
4009 // this into an overloading ambiguity diagnostic. However, we need
4010 // to keep that set as an OverloadCandidateSet rather than as some
4011 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004012 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4013 Sequence.SetOverloadFailure(
4014 InitializationSequence::FK_ReferenceInitOverloadFailed,
4015 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004016 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4017 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004018 else
4019 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004020 return;
John McCall31168b02011-06-15 23:02:42 +00004021 } else {
4022 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004023 }
4024
4025 // [...] If T1 is reference-related to T2, cv1 must be the
4026 // same cv-qualification as, or greater cv-qualification
4027 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004028 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4029 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004030 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00004031 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004032 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4033 return;
4034 }
4035
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004036 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004037 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004038 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004039 InitCategory.isLValue()) {
4040 Sequence.SetFailed(
4041 InitializationSequence::FK_RValueReferenceBindingToLValue);
4042 return;
4043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004044
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004045 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4046 return;
4047}
4048
4049/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004050/// (C++ [dcl.init.string], C99 6.7.8).
4051static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004052 const InitializedEntity &Entity,
4053 const InitializationKind &Kind,
4054 Expr *Initializer,
4055 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004056 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004057}
4058
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004059/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004060static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004061 const InitializedEntity &Entity,
4062 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004063 InitializationSequence &Sequence,
4064 InitListExpr *InitList) {
4065 assert((!InitList || InitList->getNumInits() == 0) &&
4066 "Shouldn't use value-init for non-empty init lists");
4067
Richard Smith1bfe0682012-02-14 21:14:13 +00004068 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004069 //
4070 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004071 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004072
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004073 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004074 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004075
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004076 if (const RecordType *RT = T->getAs<RecordType>()) {
4077 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004078 bool NeedZeroInitialization = true;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004079 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithd86812d2012-07-05 08:39:21 +00004080 // C++98:
4081 // -- if T is a class type (clause 9) with a user-declared constructor
4082 // (12.1), then the default constructor for T is called (and the
4083 // initialization is ill-formed if T has no accessible default
4084 // constructor);
Richard Smith1bfe0682012-02-14 21:14:13 +00004085 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithd86812d2012-07-05 08:39:21 +00004086 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00004087 } else {
4088 // C++11:
4089 // -- if T is a class type (clause 9) with either no default constructor
4090 // (12.1 [class.ctor]) or a default constructor that is user-provided
4091 // or deleted, then the object is default-initialized;
4092 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4093 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithd86812d2012-07-05 08:39:21 +00004094 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00004095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004096
Richard Smith1bfe0682012-02-14 21:14:13 +00004097 // -- if T is a (possibly cv-qualified) non-union class type without a
4098 // user-provided or deleted default constructor, then the object is
4099 // zero-initialized and, if T has a non-trivial default constructor,
4100 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004101 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4102 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004103 if (NeedZeroInitialization)
4104 Sequence.AddZeroInitializationStep(Entity.getType());
4105
Richard Smith593f9932012-12-08 02:01:17 +00004106 // C++03:
4107 // -- if T is a non-union class type without a user-declared constructor,
4108 // then every non-static data member and base class component of T is
4109 // value-initialized;
4110 // [...] A program that calls for [...] value-initialization of an
4111 // entity of reference type is ill-formed.
4112 //
4113 // C++11 doesn't need this handling, because value-initialization does not
4114 // occur recursively there, and the implicit default constructor is
4115 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004116 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004117 ClassDecl->hasUninitializedReferenceMember()) {
4118 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4119 return;
4120 }
4121
Richard Smithd86812d2012-07-05 08:39:21 +00004122 // If this is list-value-initialization, pass the empty init list on when
4123 // building the constructor call. This affects the semantics of a few
4124 // things (such as whether an explicit default constructor can be called).
4125 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004126 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004127 bool InitListSyntax = InitList;
4128
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004129 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4130 InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004131 }
4132 }
4133
Douglas Gregor1b303932009-12-22 15:35:07 +00004134 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004135}
4136
Douglas Gregor85dabae2009-12-16 01:38:02 +00004137/// \brief Attempt default initialization (C++ [dcl.init]p6).
4138static void TryDefaultInitialization(Sema &S,
4139 const InitializedEntity &Entity,
4140 const InitializationKind &Kind,
4141 InitializationSequence &Sequence) {
4142 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004143
Douglas Gregor85dabae2009-12-16 01:38:02 +00004144 // C++ [dcl.init]p6:
4145 // To default-initialize an object of type T means:
4146 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004147 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4148
Douglas Gregor85dabae2009-12-16 01:38:02 +00004149 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4150 // constructor for T is called (and the initialization is ill-formed if
4151 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004152 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004153 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004154 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004155 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004156
Douglas Gregor85dabae2009-12-16 01:38:02 +00004157 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004158
Douglas Gregor85dabae2009-12-16 01:38:02 +00004159 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004160 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004161 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004162 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004163 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004164 return;
4165 }
4166
4167 // If the destination type has a lifetime property, zero-initialize it.
4168 if (DestType.getQualifiers().hasObjCLifetime()) {
4169 Sequence.AddZeroInitializationStep(Entity.getType());
4170 return;
4171 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004172}
4173
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004174/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4175/// which enumerates all conversion functions and performs overload resolution
4176/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004177static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004178 const InitializedEntity &Entity,
4179 const InitializationKind &Kind,
4180 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004181 InitializationSequence &Sequence,
4182 bool TopLevelOfInitList) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004183 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004184 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4185 QualType SourceType = Initializer->getType();
4186 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4187 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004188
Douglas Gregor540c3b02009-12-14 17:27:33 +00004189 // Build the candidate set directly in the initialization sequence
4190 // structure, so that it will persist if we fail.
4191 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4192 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004193
Douglas Gregor540c3b02009-12-14 17:27:33 +00004194 // Determine whether we are allowed to call explicit constructors or
4195 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004196 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004197
Douglas Gregor540c3b02009-12-14 17:27:33 +00004198 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4199 // The type we're converting to is a class type. Enumerate its constructors
4200 // to see if there is a suitable conversion.
4201 CXXRecordDecl *DestRecordDecl
4202 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004203
Douglas Gregord9848152010-04-26 14:36:57 +00004204 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004205 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004206 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie12be6392012-10-18 16:57:32 +00004207 // The container holding the constructors can under certain conditions
4208 // be changed while iterating. To be safe we copy the lookup results
4209 // to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004210 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004211 for (SmallVectorImpl<NamedDecl *>::iterator
David Blaikie12be6392012-10-18 16:57:32 +00004212 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregord9848152010-04-26 14:36:57 +00004213 Con != ConEnd; ++Con) {
4214 NamedDecl *D = *Con;
4215 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004216
Douglas Gregord9848152010-04-26 14:36:57 +00004217 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00004218 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregord9848152010-04-26 14:36:57 +00004219 FunctionTemplateDecl *ConstructorTmpl
4220 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004221 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00004222 Constructor = cast<CXXConstructorDecl>(
4223 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00004224 else
Douglas Gregord9848152010-04-26 14:36:57 +00004225 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004226
Douglas Gregord9848152010-04-26 14:36:57 +00004227 if (!Constructor->isInvalidDecl() &&
4228 Constructor->isConvertingConstructor(AllowExplicit)) {
4229 if (ConstructorTmpl)
4230 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004231 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004232 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004233 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004234 else
4235 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004236 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004237 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004238 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004239 }
Douglas Gregord9848152010-04-26 14:36:57 +00004240 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004241 }
Eli Friedman78275202009-12-19 08:11:05 +00004242
4243 SourceLocation DeclLoc = Initializer->getLocStart();
4244
Douglas Gregor540c3b02009-12-14 17:27:33 +00004245 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4246 // The type we're converting from is a class type, enumerate its conversion
4247 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004248
Eli Friedman4afe9a32009-12-20 22:12:03 +00004249 // We can only enumerate the conversion functions for a complete type; if
4250 // the type isn't complete, simply skip this step.
4251 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4252 CXXRecordDecl *SourceRecordDecl
4253 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004254
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004255 std::pair<CXXRecordDecl::conversion_iterator,
4256 CXXRecordDecl::conversion_iterator>
4257 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4258 for (CXXRecordDecl::conversion_iterator
4259 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004260 NamedDecl *D = *I;
4261 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4262 if (isa<UsingShadowDecl>(D))
4263 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004264
Eli Friedman4afe9a32009-12-20 22:12:03 +00004265 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4266 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004267 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004268 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004269 else
John McCallda4458e2010-03-31 01:36:47 +00004270 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004271
Eli Friedman4afe9a32009-12-20 22:12:03 +00004272 if (AllowExplicit || !Conv->isExplicit()) {
4273 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004274 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004275 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004276 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004277 else
John McCalla0296f72010-03-19 07:35:19 +00004278 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004279 Initializer, DestType, CandidateSet,
4280 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004281 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004282 }
4283 }
4284 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004285
4286 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004287 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004288 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00004289 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004290 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004291 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004292 Result);
4293 return;
4294 }
John McCall0d1da222010-01-12 00:44:57 +00004295
Douglas Gregor540c3b02009-12-14 17:27:33 +00004296 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004297 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004298 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299
Douglas Gregor540c3b02009-12-14 17:27:33 +00004300 if (isa<CXXConstructorDecl>(Function)) {
4301 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004302 // subsumed by the initialization. Per DR5, the created temporary is of the
4303 // cv-unqualified type of the destination.
4304 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4305 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004306 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004307 return;
4308 }
4309
4310 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004311 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004312 if (ConvType->getAs<RecordType>()) {
Richard Smithb24f0672012-02-11 19:22:50 +00004313 // If we're converting to a class type, there may be an copy of
Douglas Gregor5ab11652010-04-17 22:01:05 +00004314 // the resulting temporary object (possible to create an object of
4315 // a base class type). That copy is not a separate conversion, so
4316 // we just make a note of the actual destination type (possibly a
4317 // base class of the type returned by the conversion function) and
4318 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004319 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4320 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004321 return;
4322 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004323
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004324 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4325 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004326
Douglas Gregor5ab11652010-04-17 22:01:05 +00004327 // If the conversion following the call to the conversion function
4328 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004329 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4330 Best->FinalConversion.Third) {
4331 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004332 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004333 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004334 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004335 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004336}
4337
Richard Smithf032001b2013-06-20 02:18:31 +00004338/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4339/// a function with a pointer return type contains a 'return false;' statement.
4340/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4341/// code using that header.
4342///
4343/// Work around this by treating 'return false;' as zero-initializing the result
4344/// if it's used in a pointer-returning function in a system header.
4345static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4346 const InitializedEntity &Entity,
4347 const Expr *Init) {
4348 return S.getLangOpts().CPlusPlus11 &&
4349 Entity.getKind() == InitializedEntity::EK_Result &&
4350 Entity.getType()->isPointerType() &&
4351 isa<CXXBoolLiteralExpr>(Init) &&
4352 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4353 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4354}
4355
John McCall31168b02011-06-15 23:02:42 +00004356/// The non-zero enum values here are indexes into diagnostic alternatives.
4357enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4358
4359/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00004360static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004361 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00004362 // Skip parens.
4363 e = e->IgnoreParens();
4364
4365 // Skip address-of nodes.
4366 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4367 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004368 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4369 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004370
4371 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00004372 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4373 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00004374 case CK_Dependent:
4375 case CK_BitCast:
4376 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00004377 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004378 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004379
4380 case CK_ArrayToPointerDecay:
4381 return IIK_nonscalar;
4382
4383 case CK_NullToPointer:
4384 return IIK_okay;
4385
4386 default:
4387 break;
4388 }
4389
4390 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00004391 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004392 // set isWeakAccess to true, to mean that there will be an implicit
4393 // load which requires a cleanup.
4394 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4395 isWeakAccess = true;
4396
John McCall63f84442011-06-27 23:59:58 +00004397 if (!isAddressOf) return IIK_nonlocal;
4398
John McCall113bee02012-03-10 09:33:50 +00004399 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4400 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00004401
4402 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00004403
4404 // If we have a conditional operator, check both sides.
4405 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004406 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4407 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00004408 return iik;
4409
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004410 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004411
4412 // These are never scalar.
4413 } else if (isa<ArraySubscriptExpr>(e)) {
4414 return IIK_nonscalar;
4415
4416 // Otherwise, it needs to be a null pointer constant.
4417 } else {
4418 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4419 ? IIK_okay : IIK_nonlocal);
4420 }
4421
4422 return IIK_nonlocal;
4423}
4424
4425/// Check whether the given expression is a valid operand for an
4426/// indirect copy/restore.
4427static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4428 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004429 bool isWeakAccess = false;
4430 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4431 // If isWeakAccess to true, there will be an implicit
4432 // load which requires a cleanup.
4433 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4434 S.ExprNeedsCleanups = true;
4435
John McCall31168b02011-06-15 23:02:42 +00004436 if (iik == IIK_okay) return;
4437
4438 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4439 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4440 << src->getSourceRange();
4441}
4442
Douglas Gregore2f943b2011-02-22 18:29:51 +00004443/// \brief Determine whether we have compatible array types for the
4444/// purposes of GNU by-copy array initialization.
4445static bool hasCompatibleArrayTypes(ASTContext &Context,
4446 const ArrayType *Dest,
4447 const ArrayType *Source) {
4448 // If the source and destination array types are equivalent, we're
4449 // done.
4450 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4451 return true;
4452
4453 // Make sure that the element types are the same.
4454 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4455 return false;
4456
4457 // The only mismatch we allow is when the destination is an
4458 // incomplete array type and the source is a constant array type.
4459 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4460}
4461
John McCall31168b02011-06-15 23:02:42 +00004462static bool tryObjCWritebackConversion(Sema &S,
4463 InitializationSequence &Sequence,
4464 const InitializedEntity &Entity,
4465 Expr *Initializer) {
4466 bool ArrayDecay = false;
4467 QualType ArgType = Initializer->getType();
4468 QualType ArgPointee;
4469 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4470 ArrayDecay = true;
4471 ArgPointee = ArgArrayType->getElementType();
4472 ArgType = S.Context.getPointerType(ArgPointee);
4473 }
4474
4475 // Handle write-back conversion.
4476 QualType ConvertedArgType;
4477 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4478 ConvertedArgType))
4479 return false;
4480
4481 // We should copy unless we're passing to an argument explicitly
4482 // marked 'out'.
4483 bool ShouldCopy = true;
4484 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4485 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4486
4487 // Do we need an lvalue conversion?
4488 if (ArrayDecay || Initializer->isGLValue()) {
4489 ImplicitConversionSequence ICS;
4490 ICS.setStandard();
4491 ICS.Standard.setAsIdentityConversion();
4492
4493 QualType ResultType;
4494 if (ArrayDecay) {
4495 ICS.Standard.First = ICK_Array_To_Pointer;
4496 ResultType = S.Context.getPointerType(ArgPointee);
4497 } else {
4498 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4499 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4500 }
4501
4502 Sequence.AddConversionSequenceStep(ICS, ResultType);
4503 }
4504
4505 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4506 return true;
4507}
4508
Guy Benyei61054192013-02-07 10:55:47 +00004509static bool TryOCLSamplerInitialization(Sema &S,
4510 InitializationSequence &Sequence,
4511 QualType DestType,
4512 Expr *Initializer) {
4513 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4514 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4515 return false;
4516
4517 Sequence.AddOCLSamplerInitStep(DestType);
4518 return true;
4519}
4520
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004521//
4522// OpenCL 1.2 spec, s6.12.10
4523//
4524// The event argument can also be used to associate the
4525// async_work_group_copy with a previous async copy allowing
4526// an event to be shared by multiple async copies; otherwise
4527// event should be zero.
4528//
4529static bool TryOCLZeroEventInitialization(Sema &S,
4530 InitializationSequence &Sequence,
4531 QualType DestType,
4532 Expr *Initializer) {
4533 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4534 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4535 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4536 return false;
4537
4538 Sequence.AddOCLZeroEventStep(DestType);
4539 return true;
4540}
4541
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004542InitializationSequence::InitializationSequence(Sema &S,
4543 const InitializedEntity &Entity,
4544 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004545 MultiExprArg Args,
4546 bool TopLevelOfInitList)
Richard Smith100b24a2014-04-17 01:52:14 +00004547 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Richard Smith089c3162013-09-21 21:55:46 +00004548 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
4549}
4550
4551void InitializationSequence::InitializeFrom(Sema &S,
4552 const InitializedEntity &Entity,
4553 const InitializationKind &Kind,
4554 MultiExprArg Args,
4555 bool TopLevelOfInitList) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004556 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004557
John McCall5e77d762013-04-16 07:28:30 +00004558 // Eliminate non-overload placeholder types in the arguments. We
4559 // need to do this before checking whether types are dependent
4560 // because lowering a pseudo-object expression might well give us
4561 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004562 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00004563 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4564 // FIXME: should we be doing this here?
4565 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4566 if (result.isInvalid()) {
4567 SetFailed(FK_PlaceholderType);
4568 return;
4569 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004570 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00004571 }
4572
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004573 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004574 // The semantics of initializers are as follows. The destination type is
4575 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004576 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004577 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004578 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004579 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004580
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004581 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004582 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004583 SequenceKind = DependentSequence;
4584 return;
4585 }
4586
Sebastian Redld201edf2011-06-05 13:59:11 +00004587 // Almost everything is a normal sequence.
4588 setSequenceKind(NormalSequence);
4589
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004590 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00004591 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004592 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004593 Initializer = Args[0];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004594 if (S.getLangOpts().ObjC1) {
4595 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
4596 DestType, Initializer->getType(),
4597 Initializer) ||
4598 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
4599 Args[0] = Initializer;
4600
4601 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004602 if (!isa<InitListExpr>(Initializer))
4603 SourceType = Initializer->getType();
4604 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004605
Sebastian Redl0501c632012-02-12 16:37:36 +00004606 // - If the initializer is a (non-parenthesized) braced-init-list, the
4607 // object is list-initialized (8.5.4).
4608 if (Kind.getKind() != InitializationKind::IK_Direct) {
4609 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4610 TryListInitialization(S, Entity, Kind, InitList, *this);
4611 return;
4612 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004613 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004614
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004615 // - If the destination type is a reference type, see 8.5.3.
4616 if (DestType->isReferenceType()) {
4617 // C++0x [dcl.init.ref]p1:
4618 // A variable declared to be a T& or T&&, that is, "reference to type T"
4619 // (8.3.2), shall be initialized by an object, or function, of type T or
4620 // by an object that can be converted into a T.
4621 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004622 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004623 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004624 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004625 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004626 return;
4627 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004628
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004629 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004630 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004631 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004632 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004633 return;
4634 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004635
Douglas Gregor85dabae2009-12-16 01:38:02 +00004636 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004637 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004638 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004639 return;
4640 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004641
John McCall66884dd2011-02-21 07:22:22 +00004642 // - If the destination type is an array of characters, an array of
4643 // char16_t, an array of char32_t, or an array of wchar_t, and the
4644 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004645 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004646 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004647 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004648 if (Initializer && isa<VariableArrayType>(DestAT)) {
4649 SetFailed(FK_VariableLengthArrayHasInitializer);
4650 return;
4651 }
4652
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004653 if (Initializer) {
4654 switch (IsStringInit(Initializer, DestAT, Context)) {
4655 case SIF_None:
4656 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4657 return;
4658 case SIF_NarrowStringIntoWideChar:
4659 SetFailed(FK_NarrowStringIntoWideCharArray);
4660 return;
4661 case SIF_WideStringIntoChar:
4662 SetFailed(FK_WideStringIntoCharArray);
4663 return;
4664 case SIF_IncompatWideStringIntoWideChar:
4665 SetFailed(FK_IncompatWideStringIntoWideChar);
4666 return;
4667 case SIF_Other:
4668 break;
4669 }
John McCall66884dd2011-02-21 07:22:22 +00004670 }
4671
Douglas Gregore2f943b2011-02-22 18:29:51 +00004672 // Note: as an GNU C extension, we allow initialization of an
4673 // array from a compound literal that creates an array of the same
4674 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004675 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00004676 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4677 Initializer->getType()->isArrayType()) {
4678 const ArrayType *SourceAT
4679 = Context.getAsArrayType(Initializer->getType());
4680 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004681 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004682 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004683 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004684 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004685 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004686 }
Richard Smithebeed412012-02-15 22:38:09 +00004687 }
Richard Smithd86812d2012-07-05 08:39:21 +00004688 // Note: as a GNU C++ extension, we allow list-initialization of a
4689 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004690 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00004691 Entity.getKind() == InitializedEntity::EK_Member &&
4692 Initializer && isa<InitListExpr>(Initializer)) {
4693 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4694 *this);
4695 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004696 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004697 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004698 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4699 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004700 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004701 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004702
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004703 return;
4704 }
Eli Friedman78275202009-12-19 08:11:05 +00004705
John McCall31168b02011-06-15 23:02:42 +00004706 // Determine whether we should consider writeback conversions for
4707 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004708 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004709 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00004710
4711 // We're at the end of the line for C: it's either a write-back conversion
4712 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004713 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004714 // If allowed, check whether this is an Objective-C writeback conversion.
4715 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004716 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004717 return;
4718 }
Guy Benyei61054192013-02-07 10:55:47 +00004719
4720 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4721 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004722
4723 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4724 return;
4725
John McCall31168b02011-06-15 23:02:42 +00004726 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004727 AddCAssignmentStep(DestType);
4728 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004729 return;
4730 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004731
David Blaikiebbafb8a2012-03-11 07:00:24 +00004732 assert(S.getLangOpts().CPlusPlus);
John McCall31168b02011-06-15 23:02:42 +00004733
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004734 // - If the destination type is a (possibly cv-qualified) class type:
4735 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004736 // - If the initialization is direct-initialization, or if it is
4737 // copy-initialization where the cv-unqualified version of the
4738 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004739 // class of the destination, constructors are considered. [...]
4740 if (Kind.getKind() == InitializationKind::IK_Direct ||
4741 (Kind.getKind() == InitializationKind::IK_Copy &&
4742 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4743 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004744 TryConstructorInitialization(S, Entity, Kind, Args,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004745 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004746 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004747 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004748 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004749 // used) to a derived class thereof are enumerated as described in
4750 // 13.3.1.4, and the best one is chosen through overload resolution
4751 // (13.3).
4752 else
Richard Smithaaa0ec42013-09-21 21:19:19 +00004753 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4754 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004755 return;
4756 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004757
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004758 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004759 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004760 return;
4761 }
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004762 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004763
4764 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004765 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004766 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smithaaa0ec42013-09-21 21:19:19 +00004767 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4768 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004769 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004770 return;
4771 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004772
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004773 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004774 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004775 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004776 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004777 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00004778
4779 ImplicitConversionSequence ICS
4780 = S.TryImplicitConversion(Initializer, Entity.getType(),
4781 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004782 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004783 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004784 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4785 allowObjCWritebackConversion);
4786
4787 if (ICS.isStandard() &&
4788 ICS.Standard.Second == ICK_Writeback_Conversion) {
4789 // Objective-C ARC writeback conversion.
4790
4791 // We should copy unless we're passing to an argument explicitly
4792 // marked 'out'.
4793 bool ShouldCopy = true;
4794 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4795 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4796
4797 // If there was an lvalue adjustment, add it as a separate conversion.
4798 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4799 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4800 ImplicitConversionSequence LvalueICS;
4801 LvalueICS.setStandard();
4802 LvalueICS.Standard.setAsIdentityConversion();
4803 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4804 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004805 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004806 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004807
4808 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004809 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004810 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00004811 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4812 AddZeroInitializationStep(Entity.getType());
4813 } else if (Initializer->getType() == Context.OverloadTy &&
4814 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4815 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004816 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004817 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004818 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004819 } else {
Richard Smithaaa0ec42013-09-21 21:19:19 +00004820 AddConversionSequenceStep(ICS, Entity.getType(), TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00004821
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004822 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004823 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004824}
4825
4826InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004827 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004828 StepEnd = Steps.end();
4829 Step != StepEnd; ++Step)
4830 Step->Destroy();
4831}
4832
4833//===----------------------------------------------------------------------===//
4834// Perform initialization
4835//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004836static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004837getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004838 switch(Entity.getKind()) {
4839 case InitializedEntity::EK_Variable:
4840 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004841 case InitializedEntity::EK_Exception:
4842 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004843 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004844 return Sema::AA_Initializing;
4845
4846 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004847 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004848 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4849 return Sema::AA_Sending;
4850
Douglas Gregore1314a62009-12-18 05:02:21 +00004851 return Sema::AA_Passing;
4852
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004853 case InitializedEntity::EK_Parameter_CF_Audited:
4854 if (Entity.getDecl() &&
4855 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4856 return Sema::AA_Sending;
4857
4858 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4859
Douglas Gregore1314a62009-12-18 05:02:21 +00004860 case InitializedEntity::EK_Result:
4861 return Sema::AA_Returning;
4862
Douglas Gregore1314a62009-12-18 05:02:21 +00004863 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00004864 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004865 // FIXME: Can we tell apart casting vs. converting?
4866 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004867
Douglas Gregore1314a62009-12-18 05:02:21 +00004868 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004869 case InitializedEntity::EK_ArrayElement:
4870 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004871 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004872 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004873 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004874 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004875 return Sema::AA_Initializing;
4876 }
4877
David Blaikie8a40f702012-01-17 06:56:22 +00004878 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004879}
4880
Richard Smith27874d62013-01-08 00:08:23 +00004881/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00004882/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004883static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004884 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004885 case InitializedEntity::EK_ArrayElement:
4886 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004887 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004888 case InitializedEntity::EK_New:
4889 case InitializedEntity::EK_Variable:
4890 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004891 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004892 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004893 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004894 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004895 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004896 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004897 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004898 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004899
Douglas Gregore1314a62009-12-18 05:02:21 +00004900 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004901 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00004902 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004903 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004904 return true;
4905 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004906
Douglas Gregore1314a62009-12-18 05:02:21 +00004907 llvm_unreachable("missed an InitializedEntity kind?");
4908}
4909
Douglas Gregor95562572010-04-24 23:45:46 +00004910/// \brief Whether the given entity, when initialized with an object
4911/// created for that initialization, requires destruction.
4912static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4913 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00004914 case InitializedEntity::EK_Result:
4915 case InitializedEntity::EK_New:
4916 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004917 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004918 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004919 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004920 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004921 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00004922 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004923
Richard Smith27874d62013-01-08 00:08:23 +00004924 case InitializedEntity::EK_Member:
Douglas Gregor95562572010-04-24 23:45:46 +00004925 case InitializedEntity::EK_Variable:
4926 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004927 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00004928 case InitializedEntity::EK_Temporary:
4929 case InitializedEntity::EK_ArrayElement:
4930 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004931 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004932 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00004933 return true;
4934 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004935
4936 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004937}
4938
Richard Smithc620f552011-10-19 16:55:56 +00004939/// \brief Look for copy and move constructors and constructor templates, for
4940/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4941static void LookupCopyAndMoveConstructors(Sema &S,
4942 OverloadCandidateSet &CandidateSet,
4943 CXXRecordDecl *Class,
4944 Expr *CurInitExpr) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004945 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004946 // The container holding the constructors can under certain conditions
4947 // be changed while iterating (e.g. because of deserialization).
4948 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004949 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004950 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004951 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4952 NamedDecl *D = *CI;
Craig Topperc3ec1492014-05-26 06:22:03 +00004953 CXXConstructorDecl *Constructor = nullptr;
Richard Smithc620f552011-10-19 16:55:56 +00004954
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004955 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smithc620f552011-10-19 16:55:56 +00004956 // Handle copy/moveconstructors, only.
4957 if (!Constructor || Constructor->isInvalidDecl() ||
4958 !Constructor->isCopyOrMoveConstructor() ||
4959 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4960 continue;
4961
4962 DeclAccessPair FoundDecl
4963 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4964 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004965 CurInitExpr, CandidateSet);
Richard Smithc620f552011-10-19 16:55:56 +00004966 continue;
4967 }
4968
4969 // Handle constructor templates.
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004970 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smithc620f552011-10-19 16:55:56 +00004971 if (ConstructorTmpl->isInvalidDecl())
4972 continue;
4973
4974 Constructor = cast<CXXConstructorDecl>(
4975 ConstructorTmpl->getTemplatedDecl());
4976 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4977 continue;
4978
4979 // FIXME: Do we need to limit this to copy-constructor-like
4980 // candidates?
4981 DeclAccessPair FoundDecl
4982 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
Craig Topperc3ec1492014-05-26 06:22:03 +00004983 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004984 CurInitExpr, CandidateSet, true);
Richard Smithc620f552011-10-19 16:55:56 +00004985 }
4986}
4987
4988/// \brief Get the location at which initialization diagnostics should appear.
4989static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4990 Expr *Initializer) {
4991 switch (Entity.getKind()) {
4992 case InitializedEntity::EK_Result:
4993 return Entity.getReturnLoc();
4994
4995 case InitializedEntity::EK_Exception:
4996 return Entity.getThrowLoc();
4997
4998 case InitializedEntity::EK_Variable:
4999 return Entity.getDecl()->getLocation();
5000
Douglas Gregor19666fb2012-02-15 16:57:26 +00005001 case InitializedEntity::EK_LambdaCapture:
5002 return Entity.getCaptureLoc();
5003
Richard Smithc620f552011-10-19 16:55:56 +00005004 case InitializedEntity::EK_ArrayElement:
5005 case InitializedEntity::EK_Member:
5006 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005007 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00005008 case InitializedEntity::EK_Temporary:
5009 case InitializedEntity::EK_New:
5010 case InitializedEntity::EK_Base:
5011 case InitializedEntity::EK_Delegating:
5012 case InitializedEntity::EK_VectorElement:
5013 case InitializedEntity::EK_ComplexElement:
5014 case InitializedEntity::EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005015 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005016 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00005017 return Initializer->getLocStart();
5018 }
5019 llvm_unreachable("missed an InitializedEntity kind?");
5020}
5021
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005022/// \brief Make a (potentially elidable) temporary copy of the object
5023/// provided by the given initializer by calling the appropriate copy
5024/// constructor.
5025///
5026/// \param S The Sema object used for type-checking.
5027///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005028/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005029/// the type of the initializer expression or a superclass thereof.
5030///
James Dennett634962f2012-06-14 21:40:34 +00005031/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005032///
5033/// \param CurInit The initializer expression.
5034///
5035/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5036/// is permitted in C++03 (but not C++0x) when binding a reference to
5037/// an rvalue.
5038///
5039/// \returns An expression that copies the initializer expression into
5040/// a temporary object, or an error expression if a copy could not be
5041/// created.
John McCalldadc5752010-08-24 06:29:42 +00005042static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005043 QualType T,
5044 const InitializedEntity &Entity,
5045 ExprResult CurInit,
5046 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00005047 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005048 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005049 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005050 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005051 Class = cast<CXXRecordDecl>(Record->getDecl());
5052 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005053 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005054
Douglas Gregor5d369002011-01-21 18:05:27 +00005055 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005056 // When certain criteria are met, an implementation is allowed to
5057 // omit the copy/move construction of a class object, even if the
5058 // copy/move constructor and/or destructor for the object have
5059 // side effects. [...]
5060 // - when a temporary class object that has not been bound to a
5061 // reference (12.2) would be copied/moved to a class object
5062 // with the same cv-unqualified type, the copy/move operation
5063 // can be omitted by constructing the temporary object
5064 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005065 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005066 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00005067 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005068 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00005069 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00005070 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00005071 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005072
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005073 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005074 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005075 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005076
Douglas Gregorf282a762011-01-21 19:38:21 +00005077 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00005078 // Only consider constructors and constructor templates. Per
5079 // C++0x [dcl.init]p16, second bullet to class types, this initialization
5080 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005081 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005082 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005083
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005084 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5085
Douglas Gregore1314a62009-12-18 05:02:21 +00005086 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00005087 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005088 case OR_Success:
5089 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005090
Douglas Gregore1314a62009-12-18 05:02:21 +00005091 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005092 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5093 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5094 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005095 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005096 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005097 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005098 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00005099 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005100 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005101
Douglas Gregore1314a62009-12-18 05:02:21 +00005102 case OR_Ambiguous:
5103 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005104 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005105 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005106 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00005107 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005108
Douglas Gregore1314a62009-12-18 05:02:21 +00005109 case OR_Deleted:
5110 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005111 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005112 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00005113 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00005114 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005115 }
5116
Douglas Gregor5ab11652010-04-17 22:01:05 +00005117 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00005118 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005119 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005120
Anders Carlssona01874b2010-04-21 18:47:17 +00005121 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005122 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005123
5124 if (IsExtraneousCopy) {
5125 // If this is a totally extraneous copy for C++03 reference
5126 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005127 // expression. We don't generate an (elided) copy operation here
5128 // because doing so would require us to pass down a flag to avoid
5129 // infinite recursion, where each step adds another extraneous,
5130 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005131
Douglas Gregor30b52772010-04-18 07:57:34 +00005132 // Instantiate the default arguments of any extra parameters in
5133 // the selected copy constructor, as if we were going to create a
5134 // proper call to the copy constructor.
5135 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5136 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5137 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005138 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005139 break;
5140
5141 // Build the default argument expression; we don't actually care
5142 // if this succeeds or not, because this routine will complain
5143 // if there was a problem.
5144 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5145 }
5146
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005147 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005148 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005149
Douglas Gregor5ab11652010-04-17 22:01:05 +00005150 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005151 // constructor call (we might have derived-to-base conversions, or
5152 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005153 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005154 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005155
Douglas Gregord0ace022010-04-25 00:55:24 +00005156 // Actually perform the constructor call.
5157 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005158 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005159 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005160 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005161 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005162 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005163 CXXConstructExpr::CK_Complete,
5164 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005165
Douglas Gregord0ace022010-04-25 00:55:24 +00005166 // If we're supposed to bind temporaries, do so.
5167 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005168 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005169 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005170}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005171
Richard Smithc620f552011-10-19 16:55:56 +00005172/// \brief Check whether elidable copy construction for binding a reference to
5173/// a temporary would have succeeded if we were building in C++98 mode, for
5174/// -Wc++98-compat.
5175static void CheckCXX98CompatAccessibleCopy(Sema &S,
5176 const InitializedEntity &Entity,
5177 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005178 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005179
5180 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5181 if (!Record)
5182 return;
5183
5184 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005185 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00005186 return;
5187
5188 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00005189 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005190 LookupCopyAndMoveConstructors(
5191 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5192
5193 // Perform overload resolution.
5194 OverloadCandidateSet::iterator Best;
5195 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5196
5197 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5198 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5199 << CurInitExpr->getSourceRange();
5200
5201 switch (OR) {
5202 case OR_Success:
5203 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCall5dadb652012-04-07 03:04:20 +00005204 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005205 // FIXME: Check default arguments as far as that's possible.
5206 break;
5207
5208 case OR_No_Viable_Function:
5209 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005210 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005211 break;
5212
5213 case OR_Ambiguous:
5214 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005215 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005216 break;
5217
5218 case OR_Deleted:
5219 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005220 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005221 break;
5222 }
5223}
5224
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005225void InitializationSequence::PrintInitLocationNote(Sema &S,
5226 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005227 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005228 if (Entity.getDecl()->getLocation().isInvalid())
5229 return;
5230
5231 if (Entity.getDecl()->getDeclName())
5232 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5233 << Entity.getDecl()->getDeclName();
5234 else
5235 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5236 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005237 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5238 Entity.getMethodDecl())
5239 S.Diag(Entity.getMethodDecl()->getLocation(),
5240 diag::note_method_return_type_change)
5241 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005242}
5243
Sebastian Redl112aa822011-07-14 19:07:55 +00005244static bool isReferenceBinding(const InitializationSequence::Step &s) {
5245 return s.Kind == InitializationSequence::SK_BindReference ||
5246 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5247}
5248
Jordan Rose6c0505e2013-05-06 16:48:12 +00005249/// Returns true if the parameters describe a constructor initialization of
5250/// an explicit temporary object, e.g. "Point(x, y)".
5251static bool isExplicitTemporary(const InitializedEntity &Entity,
5252 const InitializationKind &Kind,
5253 unsigned NumArgs) {
5254 switch (Entity.getKind()) {
5255 case InitializedEntity::EK_Temporary:
5256 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005257 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005258 break;
5259 default:
5260 return false;
5261 }
5262
5263 switch (Kind.getKind()) {
5264 case InitializationKind::IK_DirectList:
5265 return true;
5266 // FIXME: Hack to work around cast weirdness.
5267 case InitializationKind::IK_Direct:
5268 case InitializationKind::IK_Value:
5269 return NumArgs != 1;
5270 default:
5271 return false;
5272 }
5273}
5274
Sebastian Redled2e5322011-12-22 14:44:04 +00005275static ExprResult
5276PerformConstructorInitialization(Sema &S,
5277 const InitializedEntity &Entity,
5278 const InitializationKind &Kind,
5279 MultiExprArg Args,
5280 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00005281 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005282 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005283 bool IsStdInitListInitialization,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005284 SourceLocation LBraceLoc,
5285 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005286 unsigned NumArgs = Args.size();
5287 CXXConstructorDecl *Constructor
5288 = cast<CXXConstructorDecl>(Step.Function.Function);
5289 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5290
5291 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005292 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00005293 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5294 ? Kind.getEqualLoc()
5295 : Kind.getLocation();
5296
5297 if (Kind.getKind() == InitializationKind::IK_Default) {
5298 // Force even a trivial, implicit default constructor to be
5299 // semantically checked. We do this explicitly because we don't build
5300 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00005301 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00005302 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00005303 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00005304 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5305 }
5306
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005307 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00005308
Douglas Gregor6073dca2012-02-24 23:56:31 +00005309 // C++ [over.match.copy]p1:
5310 // - When initializing a temporary to be bound to the first parameter
5311 // of a constructor that takes a reference to possibly cv-qualified
5312 // T as its first argument, called with a single argument in the
5313 // context of direct-initialization, explicit conversion functions
5314 // are also considered.
5315 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5316 Args.size() == 1 &&
5317 Constructor->isCopyOrMoveConstructor();
5318
Sebastian Redled2e5322011-12-22 14:44:04 +00005319 // Determine the arguments required to actually perform the constructor
5320 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005321 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005322 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00005323 AllowExplicitConv,
5324 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00005325 return ExprError();
5326
5327
Jordan Rose6c0505e2013-05-06 16:48:12 +00005328 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005329 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedmanfa0df832012-02-02 03:46:19 +00005330 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith22262ab2013-05-04 06:44:46 +00005331 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5332 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005333
5334 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5335 if (!TSInfo)
5336 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005337 SourceRange ParenOrBraceRange =
5338 (Kind.getKind() == InitializationKind::IK_DirectList)
5339 ? SourceRange(LBraceLoc, RBraceLoc)
5340 : Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005341
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005342 CurInit = new (S.Context) CXXTemporaryObjectExpr(
5343 S.Context, Constructor, TSInfo, ConstructorArgs, ParenOrBraceRange,
5344 HadMultipleCandidates, IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005345 IsStdInitListInitialization, ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00005346 } else {
5347 CXXConstructExpr::ConstructionKind ConstructKind =
5348 CXXConstructExpr::CK_Complete;
5349
5350 if (Entity.getKind() == InitializedEntity::EK_Base) {
5351 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5352 CXXConstructExpr::CK_VirtualBase :
5353 CXXConstructExpr::CK_NonVirtualBase;
5354 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5355 ConstructKind = CXXConstructExpr::CK_Delegating;
5356 }
5357
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005358 // Only get the parenthesis or brace range if it is a list initialization or
5359 // direct construction.
5360 SourceRange ParenOrBraceRange;
5361 if (IsListInitialization)
5362 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
5363 else if (Kind.getKind() == InitializationKind::IK_Direct)
5364 ParenOrBraceRange = Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005365
5366 // If the entity allows NRVO, mark the construction as elidable
5367 // unconditionally.
5368 if (Entity.allowsNRVO())
5369 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5370 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005371 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005372 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005373 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005374 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005375 ConstructorInitRequiresZeroInit,
5376 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005377 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005378 else
5379 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5380 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005381 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005382 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005383 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005384 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005385 ConstructorInitRequiresZeroInit,
5386 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005387 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005388 }
5389 if (CurInit.isInvalid())
5390 return ExprError();
5391
5392 // Only check access if all of that succeeded.
5393 S.CheckConstructorAccess(Loc, Constructor, Entity,
5394 Step.Function.FoundDecl.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005395 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5396 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005397
5398 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005399 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00005400
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005401 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00005402}
5403
Richard Smitheb3cad52012-06-04 22:27:30 +00005404/// Determine whether the specified InitializedEntity definitely has a lifetime
5405/// longer than the current full-expression. Conservatively returns false if
5406/// it's unclear.
5407static bool
5408InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5409 const InitializedEntity *Top = &Entity;
5410 while (Top->getParent())
5411 Top = Top->getParent();
5412
5413 switch (Top->getKind()) {
5414 case InitializedEntity::EK_Variable:
5415 case InitializedEntity::EK_Result:
5416 case InitializedEntity::EK_Exception:
5417 case InitializedEntity::EK_Member:
5418 case InitializedEntity::EK_New:
5419 case InitializedEntity::EK_Base:
5420 case InitializedEntity::EK_Delegating:
5421 return true;
5422
5423 case InitializedEntity::EK_ArrayElement:
5424 case InitializedEntity::EK_VectorElement:
5425 case InitializedEntity::EK_BlockElement:
5426 case InitializedEntity::EK_ComplexElement:
5427 // Could not determine what the full initialization is. Assume it might not
5428 // outlive the full-expression.
5429 return false;
5430
5431 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005432 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00005433 case InitializedEntity::EK_Temporary:
5434 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005435 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005436 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00005437 // The entity being initialized might not outlive the full-expression.
5438 return false;
5439 }
5440
5441 llvm_unreachable("unknown entity kind");
5442}
5443
Richard Smithe6c01442013-06-05 00:46:14 +00005444/// Determine the declaration which an initialized entity ultimately refers to,
5445/// for the purpose of lifetime-extending a temporary bound to a reference in
5446/// the initialization of \p Entity.
David Majnemerdaff3702014-05-01 17:50:17 +00005447static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
5448 const InitializedEntity *Entity,
Craig Topperc3ec1492014-05-26 06:22:03 +00005449 const InitializedEntity *FallbackDecl = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00005450 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00005451 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005452 case InitializedEntity::EK_Variable:
5453 // The temporary [...] persists for the lifetime of the reference
David Majnemerdaff3702014-05-01 17:50:17 +00005454 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005455
5456 case InitializedEntity::EK_Member:
5457 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005458 if (Entity->getParent())
5459 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5460 Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00005461
5462 // except:
5463 // -- A temporary bound to a reference member in a constructor's
5464 // ctor-initializer persists until the constructor exits.
David Majnemerdaff3702014-05-01 17:50:17 +00005465 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005466
5467 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005468 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00005469 // -- A temporary bound to a reference parameter in a function call
5470 // persists until the completion of the full-expression containing
5471 // the call.
5472 case InitializedEntity::EK_Result:
5473 // -- The lifetime of a temporary bound to the returned value in a
5474 // function return statement is not extended; the temporary is
5475 // destroyed at the end of the full-expression in the return statement.
5476 case InitializedEntity::EK_New:
5477 // -- A temporary bound to a reference in a new-initializer persists
5478 // until the completion of the full-expression containing the
5479 // new-initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005480 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005481
5482 case InitializedEntity::EK_Temporary:
5483 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005484 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00005485 // We don't yet know the storage duration of the surrounding temporary.
5486 // Assume it's got full-expression duration for now, it will patch up our
5487 // storage duration if that's not correct.
David Majnemerdaff3702014-05-01 17:50:17 +00005488 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005489
5490 case InitializedEntity::EK_ArrayElement:
5491 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005492 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5493 FallbackDecl);
Richard Smithe6c01442013-06-05 00:46:14 +00005494
5495 case InitializedEntity::EK_Base:
5496 case InitializedEntity::EK_Delegating:
5497 // We can reach this case for aggregate initialization in a constructor:
5498 // struct A { int &&r; };
5499 // struct B : A { B() : A{0} {} };
5500 // In this case, use the innermost field decl as the context.
5501 return FallbackDecl;
5502
5503 case InitializedEntity::EK_BlockElement:
5504 case InitializedEntity::EK_LambdaCapture:
5505 case InitializedEntity::EK_Exception:
5506 case InitializedEntity::EK_VectorElement:
5507 case InitializedEntity::EK_ComplexElement:
David Majnemerdaff3702014-05-01 17:50:17 +00005508 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005509 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00005510 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00005511}
5512
David Majnemerdaff3702014-05-01 17:50:17 +00005513static void performLifetimeExtension(Expr *Init,
5514 const InitializedEntity *ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005515
5516/// Update a glvalue expression that is used as the initializer of a reference
5517/// to note that its lifetime is extended.
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005518/// \return \c true if any temporary had its lifetime extended.
David Majnemerdaff3702014-05-01 17:50:17 +00005519static bool
5520performReferenceExtension(Expr *Init,
5521 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00005522 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5523 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5524 // This is just redundant braces around an initializer. Step over it.
5525 Init = ILE->getInit(0);
5526 }
5527 }
5528
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005529 // Walk past any constructs which we can lifetime-extend across.
5530 Expr *Old;
5531 do {
5532 Old = Init;
5533
5534 // Step over any subobject adjustments; we may have a materialized
5535 // temporary inside them.
5536 SmallVector<const Expr *, 2> CommaLHSs;
5537 SmallVector<SubobjectAdjustment, 2> Adjustments;
5538 Init = const_cast<Expr *>(
5539 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5540
5541 // Per current approach for DR1376, look through casts to reference type
5542 // when performing lifetime extension.
5543 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5544 if (CE->getSubExpr()->isGLValue())
5545 Init = CE->getSubExpr();
5546
5547 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5548 // It's unclear if binding a reference to that xvalue extends the array
5549 // temporary.
5550 } while (Init != Old);
5551
Richard Smithe6c01442013-06-05 00:46:14 +00005552 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5553 // Update the storage duration of the materialized temporary.
5554 // FIXME: Rebuild the expression instead of mutating it.
David Majnemerdaff3702014-05-01 17:50:17 +00005555 ME->setExtendingDecl(ExtendingEntity->getDecl(),
5556 ExtendingEntity->allocateManglingNumber());
5557 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005558 return true;
Richard Smithe6c01442013-06-05 00:46:14 +00005559 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005560
5561 return false;
Richard Smithe6c01442013-06-05 00:46:14 +00005562}
5563
5564/// Update a prvalue expression that is going to be materialized as a
5565/// lifetime-extended temporary.
David Majnemerdaff3702014-05-01 17:50:17 +00005566static void performLifetimeExtension(Expr *Init,
5567 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00005568 // Dig out the expression which constructs the extended temporary.
5569 SmallVector<const Expr *, 2> CommaLHSs;
5570 SmallVector<SubobjectAdjustment, 2> Adjustments;
5571 Init = const_cast<Expr *>(
5572 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5573
Richard Smith736a9472013-06-12 20:42:33 +00005574 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5575 Init = BTE->getSubExpr();
5576
Richard Smithcc1b96d2013-06-12 22:31:48 +00005577 if (CXXStdInitializerListExpr *ILE =
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005578 dyn_cast<CXXStdInitializerListExpr>(Init)) {
David Majnemerdaff3702014-05-01 17:50:17 +00005579 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005580 return;
5581 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00005582
Richard Smithe6c01442013-06-05 00:46:14 +00005583 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00005584 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005585 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
David Majnemerdaff3702014-05-01 17:50:17 +00005586 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005587 return;
5588 }
5589
Richard Smithcc1b96d2013-06-12 22:31:48 +00005590 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005591 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5592
5593 // If we lifetime-extend a braced initializer which is initializing an
5594 // aggregate, and that aggregate contains reference members which are
5595 // bound to temporaries, those temporaries are also lifetime-extended.
5596 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5597 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005598 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005599 else {
5600 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005601 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00005602 if (Index >= ILE->getNumInits())
5603 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005604 if (I->isUnnamedBitfield())
5605 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00005606 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00005607 if (I->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005608 performReferenceExtension(SubInit, ExtendingEntity);
Richard Smith8d7f11d2013-06-27 22:54:33 +00005609 else if (isa<InitListExpr>(SubInit) ||
5610 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smithe6c01442013-06-05 00:46:14 +00005611 // This may be either aggregate-initialization of a member or
5612 // initialization of a std::initializer_list object. Either way,
5613 // we should recursively lifetime-extend that initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005614 performLifetimeExtension(SubInit, ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005615 ++Index;
5616 }
5617 }
5618 }
5619 }
5620}
5621
Richard Smithcc1b96d2013-06-12 22:31:48 +00005622static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5623 const Expr *Init, bool IsInitializerList,
5624 const ValueDecl *ExtendingDecl) {
5625 // Warn if a field lifetime-extends a temporary.
5626 if (isa<FieldDecl>(ExtendingDecl)) {
5627 if (IsInitializerList) {
5628 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5629 << /*at end of constructor*/true;
5630 return;
5631 }
5632
5633 bool IsSubobjectMember = false;
5634 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5635 Ent = Ent->getParent()) {
5636 if (Ent->getKind() != InitializedEntity::EK_Base) {
5637 IsSubobjectMember = true;
5638 break;
5639 }
5640 }
5641 S.Diag(Init->getExprLoc(),
5642 diag::warn_bind_ref_member_to_temporary)
5643 << ExtendingDecl << Init->getSourceRange()
5644 << IsSubobjectMember << IsInitializerList;
5645 if (IsSubobjectMember)
5646 S.Diag(ExtendingDecl->getLocation(),
5647 diag::note_ref_subobject_of_member_declared_here);
5648 else
5649 S.Diag(ExtendingDecl->getLocation(),
5650 diag::note_ref_or_ptr_member_declared_here)
5651 << /*is pointer*/false;
5652 }
5653}
5654
Richard Smithaaa0ec42013-09-21 21:19:19 +00005655static void DiagnoseNarrowingInInitList(Sema &S,
5656 const ImplicitConversionSequence &ICS,
5657 QualType PreNarrowingType,
5658 QualType EntityType,
5659 const Expr *PostInit);
5660
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005661ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005662InitializationSequence::Perform(Sema &S,
5663 const InitializedEntity &Entity,
5664 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00005665 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005666 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005667 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005668 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00005669 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005671
Sebastian Redld201edf2011-06-05 13:59:11 +00005672 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005673 // If the declaration is a non-dependent, incomplete array type
5674 // that has an initializer, then its type will be completed once
5675 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00005676 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00005677 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00005678 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005679 if (const IncompleteArrayType *ArrayT
5680 = S.Context.getAsIncompleteArrayType(DeclType)) {
5681 // FIXME: We don't currently have the ability to accurately
5682 // compute the length of an initializer list without
5683 // performing full type-checking of the initializer list
5684 // (since we have to determine where braces are implicitly
5685 // introduced and such). So, we fall back to making the array
5686 // type a dependently-sized array type with no specified
5687 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005688 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005689 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00005690
Douglas Gregor51e77d52009-12-10 17:56:55 +00005691 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00005692 if (DeclaratorDecl *DD = Entity.getDecl()) {
5693 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5694 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00005695 if (IncompleteArrayTypeLoc ArrayLoc =
5696 TL.getAs<IncompleteArrayTypeLoc>())
5697 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00005698 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00005699 }
5700
5701 *ResultType
5702 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005703 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005704 ArrayT->getSizeModifier(),
5705 ArrayT->getIndexTypeCVRQualifiers(),
5706 Brackets);
5707 }
5708
5709 }
5710 }
Sebastian Redla9351792012-02-11 23:51:47 +00005711 if (Kind.getKind() == InitializationKind::IK_Direct &&
5712 !Kind.isExplicitCast()) {
5713 // Rebuild the ParenListExpr.
5714 SourceRange ParenRange = Kind.getParenRange();
5715 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005716 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00005717 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00005718 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00005719 Kind.isExplicitCast() ||
5720 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005721 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005722 }
5723
Sebastian Redld201edf2011-06-05 13:59:11 +00005724 // No steps means no initialization.
5725 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005726 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005727
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005728 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005729 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005730 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00005731 // Produce a C++98 compatibility warning if we are initializing a reference
5732 // from an initializer list. For parameters, we produce a better warning
5733 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005734 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00005735 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5736 << Init->getSourceRange();
5737 }
5738
Richard Smitheb3cad52012-06-04 22:27:30 +00005739 // Diagnose cases where we initialize a pointer to an array temporary, and the
5740 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005741 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00005742 Entity.getType()->isPointerType() &&
5743 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005744 Expr *Init = Args[0];
Richard Smitheb3cad52012-06-04 22:27:30 +00005745 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5746 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5747 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5748 << Init->getSourceRange();
5749 }
5750
Douglas Gregor1b303932009-12-22 15:35:07 +00005751 QualType DestType = Entity.getType().getNonReferenceType();
5752 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00005753 // the same as Entity.getDecl()->getType() in cases involving type merging,
5754 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00005755 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00005756 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00005757 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005758
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005759 ExprResult CurInit((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005760
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005761 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00005762 // grab the only argument out the Args and place it into the "current"
5763 // initializer.
5764 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005765 case SK_ResolveAddressOfOverloadedFunction:
5766 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005767 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005768 case SK_CastDerivedToBaseLValue:
5769 case SK_BindReference:
5770 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005771 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00005772 case SK_UserConversion:
5773 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005774 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005775 case SK_QualificationConversionRValue:
Jordan Roseb1312a52013-04-11 00:58:58 +00005776 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005777 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00005778 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00005779 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00005780 case SK_UnwrapInitList:
5781 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00005782 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00005783 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00005784 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00005785 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00005786 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00005787 case SK_PassByIndirectCopyRestore:
5788 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00005789 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005790 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00005791 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005792 case SK_OCLZeroEvent: {
Douglas Gregore1314a62009-12-18 05:02:21 +00005793 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005794 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00005795 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005796 break;
John McCall34376a62010-12-04 03:47:34 +00005797 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005798
Douglas Gregore1314a62009-12-18 05:02:21 +00005799 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00005800 case SK_ConstructorInitializationFromList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00005801 case SK_StdInitializerListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00005802 case SK_ZeroInitialization:
5803 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005805
5806 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005807 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005808 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005809 for (step_iterator Step = step_begin(), StepEnd = step_end();
5810 Step != StepEnd; ++Step) {
5811 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005812 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005813
John Wiegley01296292011-04-08 18:41:53 +00005814 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005815
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005816 switch (Step->Kind) {
5817 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005818 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005819 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00005820 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00005821 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5822 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005823 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00005824 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00005825 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005826 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005827
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005828 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005829 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005830 case SK_CastDerivedToBaseLValue: {
5831 // We have a derived-to-base cast that produces either an rvalue or an
5832 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005833
John McCallcf142162010-08-07 06:22:56 +00005834 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00005835
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005836 // Casts to inaccessible base classes are allowed with C-style casts.
5837 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5838 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00005839 CurInit.get()->getLocStart(),
5840 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00005841 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00005842 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005843
Douglas Gregor88d292c2010-05-13 16:44:06 +00005844 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5845 QualType T = SourceType;
5846 if (const PointerType *Pointer = T->getAs<PointerType>())
5847 T = Pointer->getPointeeType();
5848 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00005849 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00005850 cast<CXXRecordDecl>(RecordTy->getDecl()));
5851 }
5852
John McCall2536c6d2010-08-25 10:28:54 +00005853 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005854 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005855 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005856 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005857 VK_XValue :
5858 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005859 CurInit =
5860 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
5861 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005862 break;
5863 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005864
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005865 case SK_BindReference:
John McCalld25db7e2013-05-06 21:39:12 +00005866 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5867 if (CurInit.get()->refersToBitField()) {
5868 // We don't necessarily have an unambiguous source bit-field.
5869 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005870 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00005871 << Entity.getType().isVolatileQualified()
John McCalld25db7e2013-05-06 21:39:12 +00005872 << (BitField ? BitField->getDeclName() : DeclarationName())
Craig Topperc3ec1492014-05-26 06:22:03 +00005873 << (BitField != nullptr)
John Wiegley01296292011-04-08 18:41:53 +00005874 << CurInit.get()->getSourceRange();
John McCalld25db7e2013-05-06 21:39:12 +00005875 if (BitField)
5876 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5877
John McCallfaf5fb42010-08-26 23:41:50 +00005878 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005879 }
Anders Carlssona91be642010-01-29 02:47:33 +00005880
John Wiegley01296292011-04-08 18:41:53 +00005881 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00005882 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005883 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5884 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00005885 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005886 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005887 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005888 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005889
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005890 // Reference binding does not have any corresponding ASTs.
5891
5892 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005893 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005894 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005895
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005896 // Even though we didn't materialize a temporary, the binding may still
5897 // extend the lifetime of a temporary. This happens if we bind a reference
5898 // to the result of a cast to reference type.
David Majnemerdaff3702014-05-01 17:50:17 +00005899 if (const InitializedEntity *ExtendingEntity =
5900 getEntityForTemporaryLifetimeExtension(&Entity))
5901 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
5902 warnOnLifetimeExtension(S, Entity, CurInit.get(),
5903 /*IsInitializerList=*/false,
5904 ExtendingEntity->getDecl());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005905
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005906 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005907
Richard Smithe6c01442013-06-05 00:46:14 +00005908 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00005909 // Make sure the "temporary" is actually an rvalue.
5910 assert(CurInit.get()->isRValue() && "not a temporary");
5911
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005912 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005913 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005914 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005915
Douglas Gregorfe314812011-06-21 17:03:29 +00005916 // Materialize the temporary into memory.
Richard Smith736a9472013-06-12 20:42:33 +00005917 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Richard Smithe6c01442013-06-05 00:46:14 +00005918 Entity.getType().getNonReferenceType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00005919 Entity.getType()->isLValueReferenceType());
5920
5921 // Maybe lifetime-extend the temporary's subobjects to match the
5922 // entity's lifetime.
5923 if (const InitializedEntity *ExtendingEntity =
5924 getEntityForTemporaryLifetimeExtension(&Entity))
5925 if (performReferenceExtension(MTE, ExtendingEntity))
5926 warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false,
5927 ExtendingEntity->getDecl());
Douglas Gregor58df5092011-06-22 16:12:01 +00005928
5929 // If we're binding to an Objective-C object that has lifetime, we
Richard Smith736a9472013-06-12 20:42:33 +00005930 // need cleanups. Likewise if we're extending this temporary to automatic
5931 // storage duration -- we need to register its cleanup during the
5932 // full-expression's cleanups.
5933 if ((S.getLangOpts().ObjCAutoRefCount &&
5934 MTE->getType()->isObjCLifetimeType()) ||
5935 (MTE->getStorageDuration() == SD_Automatic &&
5936 MTE->getType().isDestructedType()))
Douglas Gregor58df5092011-06-22 16:12:01 +00005937 S.ExprNeedsCleanups = true;
Richard Smith736a9472013-06-12 20:42:33 +00005938
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005939 CurInit = MTE;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005940 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005941 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005942
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005943 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005944 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005945 /*IsExtraneousCopy=*/true);
5946 break;
5947
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005948 case SK_UserConversion: {
5949 // We have a user-defined conversion that invokes either a constructor
5950 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00005951 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00005952 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00005953 FunctionDecl *Fn = Step->Function.Function;
5954 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005955 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00005956 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00005957 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005958 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005959 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00005960 SourceLocation Loc = CurInit.get()->getLocStart();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005961 CurInit.get(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00005962
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005963 // Determine the arguments required to actually perform the constructor
5964 // call.
John Wiegley01296292011-04-08 18:41:53 +00005965 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005966 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00005967 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005968 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005969 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005970
Richard Smithb24f0672012-02-11 19:22:50 +00005971 // Build an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005972 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005973 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005974 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005975 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005976 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005977 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005978 CXXConstructExpr::CK_Complete,
5979 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005980 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005981 return ExprError();
John McCall760af172010-02-01 03:16:54 +00005982
Anders Carlssona01874b2010-04-21 18:47:17 +00005983 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00005984 FoundFn.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005985 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5986 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005987
John McCalle3027922010-08-25 11:45:40 +00005988 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00005989 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5990 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5991 S.IsDerivedFrom(SourceType, Class))
5992 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005993
Douglas Gregor95562572010-04-24 23:45:46 +00005994 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005995 } else {
5996 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00005997 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00005998 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00005999 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00006000 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6001 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006002
6003 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006004 // derived-to-base conversion? I believe the answer is "no", because
6005 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00006006 ExprResult CurInitExprRes =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006007 S.PerformObjectArgumentInitialization(CurInit.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006008 /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006009 FoundFn, Conversion);
6010 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006011 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006012 CurInit = CurInitExprRes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006013
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006014 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006015 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
6016 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006017 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00006018 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006019
John McCalle3027922010-08-25 11:45:40 +00006020 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006021
Alp Toker314cc812014-01-25 16:55:45 +00006022 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006023 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006024
Sebastian Redl112aa822011-07-14 19:07:55 +00006025 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006026 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
6027
6028 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00006029 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00006030 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006031 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00006032 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00006033 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00006034 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00006035 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00006036 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6037 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00006038 }
6039 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006040
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006041 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6042 CastKind, CurInit.get(), nullptr,
6043 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006044 if (MaybeBindToTemp)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006045 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00006046 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006047 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006048 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006049 break;
6050 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006051
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006052 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006053 case SK_QualificationConversionXValue:
6054 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006055 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00006056 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006057 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006058 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006059 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006060 VK_XValue :
6061 VK_RValue);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006062 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006063 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006064 }
6065
Jordan Roseb1312a52013-04-11 00:58:58 +00006066 case SK_LValueToRValue: {
6067 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006068 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
6069 CK_LValueToRValue, CurInit.get(),
6070 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00006071 break;
6072 }
6073
Richard Smithaaa0ec42013-09-21 21:19:19 +00006074 case SK_ConversionSequence:
6075 case SK_ConversionSequenceNoNarrowing: {
6076 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00006077 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
6078 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00006079 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00006080 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00006081 ExprResult CurInitExprRes =
6082 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00006083 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00006084 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006085 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006086 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00006087
6088 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
6089 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
6090 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
6091 CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006092 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00006093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006094
Douglas Gregor51e77d52009-12-10 17:56:55 +00006095 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00006096 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006097 // If we're not initializing the top-level entity, we need to create an
6098 // InitializeTemporary entity for our target type.
6099 QualType Ty = Step->Type;
6100 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00006101 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00006102 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
6103 InitListChecker PerformInitList(S, InitEntity,
Richard Smithde229232013-06-06 11:41:05 +00006104 InitList, Ty, /*VerifyOnly=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006105 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00006106 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00006107
Richard Smithcc1b96d2013-06-12 22:31:48 +00006108 // Hack: We must update *ResultType if available in order to set the
6109 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
6110 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
6111 if (ResultType &&
6112 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00006113 if ((*ResultType)->isRValueReferenceType())
6114 Ty = S.Context.getRValueReferenceType(Ty);
6115 else if ((*ResultType)->isLValueReferenceType())
6116 Ty = S.Context.getLValueReferenceType(Ty,
6117 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
6118 *ResultType = Ty;
6119 }
6120
6121 InitListExpr *StructuredInitList =
6122 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006123 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00006124 CurInit = shouldBindAsTemporary(InitEntity)
6125 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006126 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006127 break;
6128 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006129
Richard Smith53324112014-07-16 21:33:43 +00006130 case SK_ConstructorInitializationFromList: {
Sebastian Redl5a41f682012-02-12 16:37:24 +00006131 // When an initializer list is passed for a parameter of type "reference
6132 // to object", we don't get an EK_Temporary entity, but instead an
6133 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00006134 // FIXME: This is a hack. What we really should do is create a user
6135 // conversion step for this case, but this makes it considerably more
6136 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00006137 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6138 Entity.getType().getNonReferenceType());
6139 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00006140 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006141 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00006142 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6143 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006144 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00006145 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6146 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006147 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006148 ConstructorInitRequiresZeroInit,
Richard Smith53324112014-07-16 21:33:43 +00006149 /*IsListInitialization*/true,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006150 /*IsStdInitListInit*/false,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006151 InitList->getLBraceLoc(),
6152 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00006153 break;
6154 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006155
Sebastian Redl29526f02011-11-27 16:50:07 +00006156 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006157 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00006158 break;
6159
6160 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006161 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00006162 InitListExpr *Syntactic = Step->WrappingSyntacticList;
6163 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00006164 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00006165 ILE->setSyntacticForm(Syntactic);
6166 ILE->setType(E->getType());
6167 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006168 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00006169 break;
6170 }
6171
Richard Smith53324112014-07-16 21:33:43 +00006172 case SK_ConstructorInitialization:
Richard Smithf8adcdc2014-07-17 05:12:35 +00006173 case SK_StdInitializerListConstructorCall: {
Sebastian Redl99f66162012-02-19 12:27:56 +00006174 // When an initializer list is passed for a parameter of type "reference
6175 // to object", we don't get an EK_Temporary entity, but instead an
6176 // EK_Parameter entity with reference type.
6177 // FIXME: This is a hack. What we really should do is create a user
6178 // conversion step for this case, but this makes it considerably more
6179 // complicated. For now, this will do.
6180 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6181 Entity.getType().getNonReferenceType());
6182 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf8adcdc2014-07-17 05:12:35 +00006183 bool IsStdInitListInit =
6184 Step->Kind == SK_StdInitializerListConstructorCall;
Richard Smith53324112014-07-16 21:33:43 +00006185 CurInit = PerformConstructorInitialization(
6186 S, UseTemporary ? TempEntity : Entity, Kind, Args, *Step,
6187 ConstructorInitRequiresZeroInit,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006188 /*IsListInitialization*/IsStdInitListInit,
6189 /*IsStdInitListInitialization*/IsStdInitListInit,
Richard Smith53324112014-07-16 21:33:43 +00006190 /*LBraceLoc*/SourceLocation(),
6191 /*RBraceLoc*/SourceLocation());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006192 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00006193 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006194
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006195 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006196 step_iterator NextStep = Step;
6197 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006198 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00006199 (NextStep->Kind == SK_ConstructorInitialization ||
Richard Smith53324112014-07-16 21:33:43 +00006200 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006201 // The need for zero-initialization is recorded directly into
6202 // the call to the object's constructor within the next step.
6203 ConstructorInitRequiresZeroInit = true;
6204 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006205 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006206 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00006207 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6208 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006209 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00006210 Kind.getRange().getBegin());
6211
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006212 CurInit = new (S.Context) CXXScalarValueInitExpr(
6213 TSInfo->getType().getNonLValueExprType(S.Context), TSInfo,
6214 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006215 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006216 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006217 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006218 break;
6219 }
Douglas Gregore1314a62009-12-18 05:02:21 +00006220
6221 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00006222 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006223 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00006224 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00006225 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6226 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00006227 if (Result.isInvalid())
6228 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006229 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00006230
6231 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006232 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00006233 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006234 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00006235 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00006236 == Sema::Compatible)
6237 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00006238 if (CurInitExprRes.isInvalid())
6239 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006240 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00006241
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006242 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00006243 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6244 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00006245 CurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00006246 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006247 &Complained)) {
6248 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00006249 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006250 } else if (Complained)
6251 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00006252 break;
6253 }
Eli Friedman78275202009-12-19 08:11:05 +00006254
6255 case SK_StringInit: {
6256 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00006257 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00006258 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00006259 break;
6260 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006261
6262 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006263 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00006264 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00006265 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006266 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006267
6268 case SK_ArrayInit:
6269 // Okay: we checked everything before creating this step. Note that
6270 // this is a GNU extension.
6271 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00006272 << Step->Type << CurInit.get()->getType()
6273 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00006274
6275 // If the destination type is an incomplete array type, update the
6276 // type accordingly.
6277 if (ResultType) {
6278 if (const IncompleteArrayType *IncompleteDest
6279 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6280 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00006281 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00006282 *ResultType = S.Context.getConstantArrayType(
6283 IncompleteDest->getElementType(),
6284 ConstantSource->getSize(),
6285 ArrayType::Normal, 0);
6286 }
6287 }
6288 }
John McCall31168b02011-06-15 23:02:42 +00006289 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006290
Richard Smithebeed412012-02-15 22:38:09 +00006291 case SK_ParenthesizedArrayInit:
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_parens)
6295 << CurInit.get()->getSourceRange();
6296 break;
6297
John McCall31168b02011-06-15 23:02:42 +00006298 case SK_PassByIndirectCopyRestore:
6299 case SK_PassByIndirectRestore:
6300 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006301 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
6302 CurInit.get(), Step->Type,
6303 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00006304 break;
6305
6306 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006307 CurInit =
6308 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
6309 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00006310 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006311
6312 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006313 S.Diag(CurInit.get()->getExprLoc(),
6314 diag::warn_cxx98_compat_initializer_list_init)
6315 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00006316
Richard Smithcc1b96d2013-06-12 22:31:48 +00006317 // Materialize the temporary into memory.
6318 MaterializeTemporaryExpr *MTE = new (S.Context)
6319 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00006320 /*BoundToLvalueReference=*/false);
6321
6322 // Maybe lifetime-extend the array temporary's subobjects to match the
6323 // entity's lifetime.
6324 if (const InitializedEntity *ExtendingEntity =
6325 getEntityForTemporaryLifetimeExtension(&Entity))
6326 if (performReferenceExtension(MTE, ExtendingEntity))
6327 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6328 /*IsInitializerList=*/true,
6329 ExtendingEntity->getDecl());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006330
6331 // Wrap it in a construction of a std::initializer_list<T>.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006332 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006333
6334 // Bind the result, in case the library has given initializer_list a
6335 // non-trivial destructor.
6336 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006337 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00006338 break;
6339 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006340
Guy Benyei61054192013-02-07 10:55:47 +00006341 case SK_OCLSamplerInit: {
6342 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006343 "Sampler initialization on non-sampler type.");
Guy Benyei61054192013-02-07 10:55:47 +00006344
6345 QualType SourceType = CurInit.get()->getType();
Guy Benyei61054192013-02-07 10:55:47 +00006346
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006347 if (Entity.isParameterKind()) {
Guy Benyei61054192013-02-07 10:55:47 +00006348 if (!SourceType->isSamplerT())
6349 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6350 << SourceType;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006351 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
Guy Benyei61054192013-02-07 10:55:47 +00006352 llvm_unreachable("Invalid EntityKind!");
6353 }
6354
6355 break;
6356 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006357 case SK_OCLZeroEvent: {
6358 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006359 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006360
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006361 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006362 CK_ZeroToOCLEvent,
6363 CurInit.get()->getValueKind());
6364 break;
6365 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006366 }
6367 }
John McCall1f425642010-11-11 03:21:53 +00006368
6369 // Diagnose non-fatal problems with the completed initialization.
6370 if (Entity.getKind() == InitializedEntity::EK_Member &&
6371 cast<FieldDecl>(Entity.getDecl())->isBitField())
6372 S.CheckBitFieldInitialization(Kind.getLocation(),
6373 cast<FieldDecl>(Entity.getDecl()),
6374 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006375
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006376 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006377}
6378
Richard Smith593f9932012-12-08 02:01:17 +00006379/// Somewhere within T there is an uninitialized reference subobject.
6380/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00006381static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6382 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00006383 if (T->isReferenceType()) {
6384 S.Diag(Loc, diag::err_reference_without_init)
6385 << T.getNonReferenceType();
6386 return true;
6387 }
6388
6389 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6390 if (!RD || !RD->hasUninitializedReferenceMember())
6391 return false;
6392
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006393 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00006394 if (FI->isUnnamedBitfield())
6395 continue;
6396
6397 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6398 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6399 return true;
6400 }
6401 }
6402
Aaron Ballman574705e2014-03-13 15:41:46 +00006403 for (const auto &BI : RD->bases()) {
6404 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00006405 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6406 return true;
6407 }
6408 }
6409
6410 return false;
6411}
6412
6413
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006414//===----------------------------------------------------------------------===//
6415// Diagnose initialization failures
6416//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00006417
6418/// Emit notes associated with an initialization that failed due to a
6419/// "simple" conversion failure.
6420static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6421 Expr *op) {
6422 QualType destType = entity.getType();
6423 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6424 op->getType()->isObjCObjectPointerType()) {
6425
6426 // Emit a possible note about the conversion failing because the
6427 // operand is a message send with a related result type.
6428 S.EmitRelatedResultTypeNote(op);
6429
6430 // Emit a possible note about a return failing because we're
6431 // expecting a related result type.
6432 if (entity.getKind() == InitializedEntity::EK_Result)
6433 S.EmitRelatedResultTypeNoteForReturn(destType);
6434 }
6435}
6436
Richard Smith0449aaf2013-11-21 23:30:57 +00006437static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6438 InitListExpr *InitList) {
6439 QualType DestType = Entity.getType();
6440
6441 QualType E;
6442 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6443 QualType ArrayType = S.Context.getConstantArrayType(
6444 E.withConst(),
6445 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6446 InitList->getNumInits()),
6447 clang::ArrayType::Normal, 0);
6448 InitializedEntity HiddenArray =
6449 InitializedEntity::InitializeTemporary(ArrayType);
6450 return diagnoseListInit(S, HiddenArray, InitList);
6451 }
6452
6453 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
6454 /*VerifyOnly=*/false);
6455 assert(DiagnoseInitList.HadError() &&
6456 "Inconsistent init list check result.");
6457}
6458
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006459bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006460 const InitializedEntity &Entity,
6461 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006462 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006463 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006464 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006465
Douglas Gregor1b303932009-12-22 15:35:07 +00006466 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006467 switch (Failure) {
6468 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006469 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006470 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00006471 // Dig out the reference subobject which is uninitialized and diagnose it.
6472 // If this is value-initialization, this could be nested some way within
6473 // the target type.
6474 assert(Kind.getKind() == InitializationKind::IK_Value ||
6475 DestType->isReferenceType());
6476 bool Diagnosed =
6477 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6478 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6479 (void)Diagnosed;
6480 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006481 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006482 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006483 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006484
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006485 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006486 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006487 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006488 case FK_ArrayNeedsInitListOrStringLiteral:
6489 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6490 break;
6491 case FK_ArrayNeedsInitListOrWideStringLiteral:
6492 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6493 break;
6494 case FK_NarrowStringIntoWideCharArray:
6495 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6496 break;
6497 case FK_WideStringIntoCharArray:
6498 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6499 break;
6500 case FK_IncompatWideStringIntoWideChar:
6501 S.Diag(Kind.getLocation(),
6502 diag::err_array_init_incompat_wide_string_into_wchar);
6503 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006504 case FK_ArrayTypeMismatch:
6505 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00006506 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00006507 (Failure == FK_ArrayTypeMismatch
6508 ? diag::err_array_init_different_type
6509 : diag::err_array_init_non_constant_array))
6510 << DestType.getNonReferenceType()
6511 << Args[0]->getType()
6512 << Args[0]->getSourceRange();
6513 break;
6514
John McCalla59dc2f2012-01-05 00:13:19 +00006515 case FK_VariableLengthArrayHasInitializer:
6516 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6517 << Args[0]->getSourceRange();
6518 break;
6519
John McCall16df1e52010-03-30 21:47:33 +00006520 case FK_AddressOfOverloadFailed: {
6521 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006522 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006523 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00006524 true,
6525 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006526 break;
John McCall16df1e52010-03-30 21:47:33 +00006527 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006528
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006529 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00006530 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006531 switch (FailedOverloadResult) {
6532 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00006533 if (Failure == FK_UserConversionOverloadFailed)
6534 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6535 << Args[0]->getType() << DestType
6536 << Args[0]->getSourceRange();
6537 else
6538 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6539 << DestType << Args[0]->getType()
6540 << Args[0]->getSourceRange();
6541
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006542 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006543 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006544
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006545 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00006546 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00006547 DestType.getNonReferenceType(),
6548 diag::err_typecheck_nonviable_condition_incomplete,
6549 Args[0]->getType(), Args[0]->getSourceRange()))
6550 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6551 << Args[0]->getType() << Args[0]->getSourceRange()
6552 << DestType.getNonReferenceType();
6553
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006554 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006555 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006556
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006557 case OR_Deleted: {
6558 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6559 << Args[0]->getType() << DestType.getNonReferenceType()
6560 << Args[0]->getSourceRange();
6561 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006562 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00006563 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6564 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006565 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00006566 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006567 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006568 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006569 }
6570 break;
6571 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006572
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006573 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006574 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006575 }
6576 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006577
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006578 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00006579 if (isa<InitListExpr>(Args[0])) {
6580 S.Diag(Kind.getLocation(),
6581 diag::err_lvalue_reference_bind_to_initlist)
6582 << DestType.getNonReferenceType().isVolatileQualified()
6583 << DestType.getNonReferenceType()
6584 << Args[0]->getSourceRange();
6585 break;
6586 }
6587 // Intentional fallthrough
6588
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006589 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006590 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006591 Failure == FK_NonConstLValueReferenceBindingToTemporary
6592 ? diag::err_lvalue_reference_bind_to_temporary
6593 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00006594 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006595 << DestType.getNonReferenceType()
6596 << Args[0]->getType()
6597 << Args[0]->getSourceRange();
6598 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006599
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006600 case FK_RValueReferenceBindingToLValue:
6601 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00006602 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006603 << Args[0]->getSourceRange();
6604 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006605
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006606 case FK_ReferenceInitDropsQualifiers:
6607 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6608 << DestType.getNonReferenceType()
6609 << Args[0]->getType()
6610 << Args[0]->getSourceRange();
6611 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006612
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006613 case FK_ReferenceInitFailed:
6614 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6615 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00006616 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006617 << Args[0]->getType()
6618 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00006619 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006620 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006621
Douglas Gregorb491ed32011-02-19 21:32:49 +00006622 case FK_ConversionFailed: {
6623 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00006624 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00006625 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006626 << DestType
John McCall086a4642010-11-24 05:12:34 +00006627 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00006628 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006629 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00006630 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6631 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00006632 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00006633 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00006634 }
John Wiegley01296292011-04-08 18:41:53 +00006635
6636 case FK_ConversionFromPropertyFailed:
6637 // No-op. This error has already been reported.
6638 break;
6639
Douglas Gregor51e77d52009-12-10 17:56:55 +00006640 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00006641 SourceRange R;
6642
6643 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00006644 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00006645 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006646 else
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006647 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00006648
Alp Tokerb6cc5922014-05-03 03:45:55 +00006649 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00006650 if (Kind.isCStyleOrFunctionalCast())
6651 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6652 << R;
6653 else
6654 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6655 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006656 break;
6657 }
6658
6659 case FK_ReferenceBindingToInitList:
6660 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6661 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6662 break;
6663
6664 case FK_InitListBadDestinationType:
6665 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6666 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6667 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006668
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006669 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006670 case FK_ConstructorOverloadFailed: {
6671 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006672 if (Args.size())
6673 ArgsRange = SourceRange(Args.front()->getLocStart(),
6674 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006675
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006676 if (Failure == FK_ListConstructorOverloadFailed) {
Nico Weber9709ebf2014-07-08 23:54:25 +00006677 assert(Args.size() == 1 &&
6678 "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006679 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006680 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006681 }
6682
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006683 // FIXME: Using "DestType" for the entity we're printing is probably
6684 // bad.
6685 switch (FailedOverloadResult) {
6686 case OR_Ambiguous:
6687 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6688 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006689 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006690 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006691
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006692 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006693 if (Kind.getKind() == InitializationKind::IK_Default &&
6694 (Entity.getKind() == InitializedEntity::EK_Base ||
6695 Entity.getKind() == InitializedEntity::EK_Member) &&
6696 isa<CXXConstructorDecl>(S.CurContext)) {
6697 // This is implicit default initialization of a member or
6698 // base within a constructor. If no viable function was
6699 // found, notify the user that she needs to explicitly
6700 // initialize this base/member.
6701 CXXConstructorDecl *Constructor
6702 = cast<CXXConstructorDecl>(S.CurContext);
6703 if (Entity.getKind() == InitializedEntity::EK_Base) {
6704 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006705 << (Constructor->getInheritedConstructor() ? 2 :
6706 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006707 << S.Context.getTypeDeclType(Constructor->getParent())
6708 << /*base=*/0
6709 << Entity.getType();
6710
6711 RecordDecl *BaseDecl
6712 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6713 ->getDecl();
6714 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6715 << S.Context.getTagDeclType(BaseDecl);
6716 } else {
6717 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006718 << (Constructor->getInheritedConstructor() ? 2 :
6719 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006720 << S.Context.getTypeDeclType(Constructor->getParent())
6721 << /*member=*/1
6722 << Entity.getName();
Alp Toker2afa8782014-05-28 12:20:14 +00006723 S.Diag(Entity.getDecl()->getLocation(),
6724 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006725
6726 if (const RecordType *Record
6727 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006728 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006729 diag::note_previous_decl)
6730 << S.Context.getTagDeclType(Record->getDecl());
6731 }
6732 break;
6733 }
6734
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006735 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6736 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006737 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006738 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006739
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006740 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006741 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006742 OverloadingResult Ovl
6743 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00006744 if (Ovl != OR_Deleted) {
6745 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6746 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006747 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00006748 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006749 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00006750
6751 // If this is a defaulted or implicitly-declared function, then
6752 // it was implicitly deleted. Make it clear that the deletion was
6753 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00006754 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006755 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00006756 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006757 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00006758 else
6759 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6760 << true << DestType << ArgsRange;
6761
6762 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006763 break;
6764 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006765
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006766 case OR_Success:
6767 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006768 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006769 }
David Blaikie60deeee2012-01-17 08:24:58 +00006770 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006771
Douglas Gregor85dabae2009-12-16 01:38:02 +00006772 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006773 if (Entity.getKind() == InitializedEntity::EK_Member &&
6774 isa<CXXConstructorDecl>(S.CurContext)) {
6775 // This is implicit default-initialization of a const member in
6776 // a constructor. Complain that it needs to be explicitly
6777 // initialized.
6778 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6779 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006780 << (Constructor->getInheritedConstructor() ? 2 :
6781 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006782 << S.Context.getTypeDeclType(Constructor->getParent())
6783 << /*const=*/1
6784 << Entity.getName();
6785 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6786 << Entity.getName();
6787 } else {
6788 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6789 << DestType << (bool)DestType->getAs<RecordType>();
6790 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00006791 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006792
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006793 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00006794 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006795 diag::err_init_incomplete_type);
6796 break;
6797
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006798 case FK_ListInitializationFailed: {
6799 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00006800 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6801 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006802 break;
6803 }
John McCall4124c492011-10-17 18:40:02 +00006804
6805 case FK_PlaceholderType: {
6806 // FIXME: Already diagnosed!
6807 break;
6808 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00006809
Sebastian Redl048a6d72012-04-01 19:54:59 +00006810 case FK_ExplicitConstructor: {
6811 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6812 << Args[0]->getSourceRange();
6813 OverloadCandidateSet::iterator Best;
6814 OverloadingResult Ovl
6815 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00006816 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00006817 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6818 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6819 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6820 break;
6821 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006822 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006823
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006824 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006825 return true;
6826}
Douglas Gregore1314a62009-12-18 05:02:21 +00006827
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006828void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006829 switch (SequenceKind) {
6830 case FailedSequence: {
6831 OS << "Failed sequence: ";
6832 switch (Failure) {
6833 case FK_TooManyInitsForReference:
6834 OS << "too many initializers for reference";
6835 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006836
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006837 case FK_ArrayNeedsInitList:
6838 OS << "array requires initializer list";
6839 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006840
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006841 case FK_ArrayNeedsInitListOrStringLiteral:
6842 OS << "array requires initializer list or string literal";
6843 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006844
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006845 case FK_ArrayNeedsInitListOrWideStringLiteral:
6846 OS << "array requires initializer list or wide string literal";
6847 break;
6848
6849 case FK_NarrowStringIntoWideCharArray:
6850 OS << "narrow string into wide char array";
6851 break;
6852
6853 case FK_WideStringIntoCharArray:
6854 OS << "wide string into char array";
6855 break;
6856
6857 case FK_IncompatWideStringIntoWideChar:
6858 OS << "incompatible wide string into wide char array";
6859 break;
6860
Douglas Gregore2f943b2011-02-22 18:29:51 +00006861 case FK_ArrayTypeMismatch:
6862 OS << "array type mismatch";
6863 break;
6864
6865 case FK_NonConstantArrayInit:
6866 OS << "non-constant array initializer";
6867 break;
6868
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006869 case FK_AddressOfOverloadFailed:
6870 OS << "address of overloaded function failed";
6871 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006872
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006873 case FK_ReferenceInitOverloadFailed:
6874 OS << "overload resolution for reference initialization failed";
6875 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006876
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006877 case FK_NonConstLValueReferenceBindingToTemporary:
6878 OS << "non-const lvalue reference bound to temporary";
6879 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006880
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006881 case FK_NonConstLValueReferenceBindingToUnrelated:
6882 OS << "non-const lvalue reference bound to unrelated type";
6883 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006884
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006885 case FK_RValueReferenceBindingToLValue:
6886 OS << "rvalue reference bound to an lvalue";
6887 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006888
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006889 case FK_ReferenceInitDropsQualifiers:
6890 OS << "reference initialization drops qualifiers";
6891 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006892
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006893 case FK_ReferenceInitFailed:
6894 OS << "reference initialization failed";
6895 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006896
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006897 case FK_ConversionFailed:
6898 OS << "conversion failed";
6899 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006900
John Wiegley01296292011-04-08 18:41:53 +00006901 case FK_ConversionFromPropertyFailed:
6902 OS << "conversion from property failed";
6903 break;
6904
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006905 case FK_TooManyInitsForScalar:
6906 OS << "too many initializers for scalar";
6907 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006908
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006909 case FK_ReferenceBindingToInitList:
6910 OS << "referencing binding to initializer list";
6911 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006912
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006913 case FK_InitListBadDestinationType:
6914 OS << "initializer list for non-aggregate, non-scalar type";
6915 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006916
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006917 case FK_UserConversionOverloadFailed:
6918 OS << "overloading failed for user-defined conversion";
6919 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006920
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006921 case FK_ConstructorOverloadFailed:
6922 OS << "constructor overloading failed";
6923 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006924
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006925 case FK_DefaultInitOfConst:
6926 OS << "default initialization of a const variable";
6927 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006928
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00006929 case FK_Incomplete:
6930 OS << "initialization of incomplete type";
6931 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006932
6933 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006934 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00006935 break;
6936
John McCalla59dc2f2012-01-05 00:13:19 +00006937 case FK_VariableLengthArrayHasInitializer:
6938 OS << "variable length array has an initializer";
6939 break;
6940
John McCall4124c492011-10-17 18:40:02 +00006941 case FK_PlaceholderType:
6942 OS << "initializer expression isn't contextually valid";
6943 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00006944
6945 case FK_ListConstructorOverloadFailed:
6946 OS << "list constructor overloading failed";
6947 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006948
Sebastian Redl048a6d72012-04-01 19:54:59 +00006949 case FK_ExplicitConstructor:
6950 OS << "list copy initialization chose explicit constructor";
6951 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006952 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006953 OS << '\n';
6954 return;
6955 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006956
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006957 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00006958 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006959 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006960
Sebastian Redld201edf2011-06-05 13:59:11 +00006961 case NormalSequence:
6962 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006963 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006964 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006965
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006966 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6967 if (S != step_begin()) {
6968 OS << " -> ";
6969 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006970
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006971 switch (S->Kind) {
6972 case SK_ResolveAddressOfOverloadedFunction:
6973 OS << "resolve address of overloaded function";
6974 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006975
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006976 case SK_CastDerivedToBaseRValue:
6977 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6978 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006979
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006980 case SK_CastDerivedToBaseXValue:
6981 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6982 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006983
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006984 case SK_CastDerivedToBaseLValue:
6985 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6986 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006987
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006988 case SK_BindReference:
6989 OS << "bind reference to lvalue";
6990 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006991
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006992 case SK_BindReferenceToTemporary:
6993 OS << "bind reference to a temporary";
6994 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006995
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006996 case SK_ExtraneousCopyToTemporary:
6997 OS << "extraneous C++03 copy to temporary";
6998 break;
6999
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007000 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007001 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007002 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007003
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007004 case SK_QualificationConversionRValue:
7005 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00007006 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007007
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007008 case SK_QualificationConversionXValue:
7009 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00007010 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007011
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007012 case SK_QualificationConversionLValue:
7013 OS << "qualification conversion (lvalue)";
7014 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007015
Jordan Roseb1312a52013-04-11 00:58:58 +00007016 case SK_LValueToRValue:
7017 OS << "load (lvalue to rvalue)";
7018 break;
7019
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007020 case SK_ConversionSequence:
7021 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00007022 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007023 OS << ")";
7024 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007025
Richard Smithaaa0ec42013-09-21 21:19:19 +00007026 case SK_ConversionSequenceNoNarrowing:
7027 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00007028 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00007029 OS << ")";
7030 break;
7031
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007032 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007033 OS << "list aggregate initialization";
7034 break;
7035
Sebastian Redl29526f02011-11-27 16:50:07 +00007036 case SK_UnwrapInitList:
7037 OS << "unwrap reference initializer list";
7038 break;
7039
7040 case SK_RewrapInitList:
7041 OS << "rewrap reference initializer list";
7042 break;
7043
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007044 case SK_ConstructorInitialization:
7045 OS << "constructor initialization";
7046 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007047
Richard Smith53324112014-07-16 21:33:43 +00007048 case SK_ConstructorInitializationFromList:
7049 OS << "list initialization via constructor";
7050 break;
7051
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007052 case SK_ZeroInitialization:
7053 OS << "zero initialization";
7054 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007055
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007056 case SK_CAssignment:
7057 OS << "C assignment";
7058 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007059
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007060 case SK_StringInit:
7061 OS << "string initialization";
7062 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007063
7064 case SK_ObjCObjectConversion:
7065 OS << "Objective-C object conversion";
7066 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007067
7068 case SK_ArrayInit:
7069 OS << "array initialization";
7070 break;
John McCall31168b02011-06-15 23:02:42 +00007071
Richard Smithebeed412012-02-15 22:38:09 +00007072 case SK_ParenthesizedArrayInit:
7073 OS << "parenthesized array initialization";
7074 break;
7075
John McCall31168b02011-06-15 23:02:42 +00007076 case SK_PassByIndirectCopyRestore:
7077 OS << "pass by indirect copy and restore";
7078 break;
7079
7080 case SK_PassByIndirectRestore:
7081 OS << "pass by indirect restore";
7082 break;
7083
7084 case SK_ProduceObjCObject:
7085 OS << "Objective-C object retension";
7086 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007087
7088 case SK_StdInitializerList:
7089 OS << "std::initializer_list from initializer list";
7090 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007091
Richard Smithf8adcdc2014-07-17 05:12:35 +00007092 case SK_StdInitializerListConstructorCall:
7093 OS << "list initialization from std::initializer_list";
7094 break;
7095
Guy Benyei61054192013-02-07 10:55:47 +00007096 case SK_OCLSamplerInit:
7097 OS << "OpenCL sampler_t from integer constant";
7098 break;
7099
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007100 case SK_OCLZeroEvent:
7101 OS << "OpenCL event_t from zero";
7102 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007103 }
Richard Smith6b216962013-02-05 05:52:24 +00007104
7105 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007106 }
Richard Smith6b216962013-02-05 05:52:24 +00007107
7108 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007109}
7110
7111void InitializationSequence::dump() const {
7112 dump(llvm::errs());
7113}
7114
Richard Smithaaa0ec42013-09-21 21:19:19 +00007115static void DiagnoseNarrowingInInitList(Sema &S,
7116 const ImplicitConversionSequence &ICS,
7117 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007118 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007119 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007120 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00007121 switch (ICS.getKind()) {
7122 case ImplicitConversionSequence::StandardConversion:
7123 SCS = &ICS.Standard;
7124 break;
7125 case ImplicitConversionSequence::UserDefinedConversion:
7126 SCS = &ICS.UserDefined.After;
7127 break;
7128 case ImplicitConversionSequence::AmbiguousConversion:
7129 case ImplicitConversionSequence::EllipsisConversion:
7130 case ImplicitConversionSequence::BadConversion:
7131 return;
7132 }
7133
Richard Smith66e05fe2012-01-18 05:21:49 +00007134 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
7135 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00007136 QualType ConstantType;
7137 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
7138 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00007139 case NK_Not_Narrowing:
7140 // No narrowing occurred.
7141 return;
7142
7143 case NK_Type_Narrowing:
7144 // This was a floating-to-integer conversion, which is always considered a
7145 // narrowing conversion even if the value is a constant and can be
7146 // represented exactly as an integer.
7147 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007148 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7149 ? diag::warn_init_list_type_narrowing
7150 : diag::ext_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007151 << PostInit->getSourceRange()
7152 << PreNarrowingType.getLocalUnqualifiedType()
7153 << EntityType.getLocalUnqualifiedType();
7154 break;
7155
7156 case NK_Constant_Narrowing:
7157 // A constant value was narrowed.
7158 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007159 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7160 ? diag::warn_init_list_constant_narrowing
7161 : diag::ext_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007162 << PostInit->getSourceRange()
Richard Smith5614ca72012-03-23 23:55:39 +00007163 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007164 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007165 break;
7166
7167 case NK_Variable_Narrowing:
7168 // A variable's value may have been narrowed.
7169 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007170 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7171 ? diag::warn_init_list_variable_narrowing
7172 : diag::ext_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007173 << PostInit->getSourceRange()
7174 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007175 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007176 break;
7177 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007178
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007179 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007180 llvm::raw_svector_ostream OS(StaticCast);
7181 OS << "static_cast<";
7182 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7183 // It's important to use the typedef's name if there is one so that the
7184 // fixit doesn't break code using types like int64_t.
7185 //
7186 // FIXME: This will break if the typedef requires qualification. But
7187 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007188 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007189 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00007190 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007191 else {
7192 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
7193 // with a broken cast.
7194 return;
7195 }
7196 OS << ">(";
Alp Tokerb0869032014-05-17 01:13:18 +00007197 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007198 << PostInit->getSourceRange()
7199 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
7200 << FixItHint::CreateInsertion(
7201 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007202}
7203
Douglas Gregore1314a62009-12-18 05:02:21 +00007204//===----------------------------------------------------------------------===//
7205// Initialization helper functions
7206//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00007207bool
7208Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7209 ExprResult Init) {
7210 if (Init.isInvalid())
7211 return false;
7212
7213 Expr *InitE = Init.get();
7214 assert(InitE && "No initialization expression");
7215
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00007216 InitializationKind Kind
7217 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007218 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00007219 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00007220}
7221
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007222ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00007223Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7224 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007225 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00007226 bool TopLevelOfInitList,
7227 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00007228 if (Init.isInvalid())
7229 return ExprError();
7230
John McCall1f425642010-11-11 03:21:53 +00007231 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00007232 assert(InitE && "No initialization expression?");
7233
7234 if (EqualLoc.isInvalid())
7235 EqualLoc = InitE->getLocStart();
7236
7237 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00007238 EqualLoc,
7239 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00007240 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007241 Init.get();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007242
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007243 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00007244
Richard Smith66e05fe2012-01-18 05:21:49 +00007245 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00007246}