blob: d9f86c6e4fc3307f076ba973e68208ea02df1c78 [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(),
Richard Smith1b98ccc2014-07-19 01:39:17 +0000192 diag::ext_initializer_string_for_char_array_too_long)
Eli Friedman554eba92011-04-11 00:23:45 +0000193 << Str->getSourceRange();
194 }
Mike Stump11289f42009-09-09 15:08:12 +0000195
Eli Friedman893abe42009-05-29 18:22:49 +0000196 // Set the type to the actual size that we are initializing. If we have
197 // something like:
198 // char x[1] = "foo";
199 // then this will set the string literal's type to char[1].
Richard Smith430c23b2013-05-05 16:40:13 +0000200 updateStringLiteralType(Str, DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000201}
202
Chris Lattner0cb78032009-02-24 22:27:37 +0000203//===----------------------------------------------------------------------===//
204// Semantic checking for initializer lists.
205//===----------------------------------------------------------------------===//
206
Douglas Gregorcde232f2009-01-29 01:05:33 +0000207/// @brief Semantic checking for initializer lists.
208///
209/// The InitListChecker class contains a set of routines that each
210/// handle the initialization of a certain kind of entity, e.g.,
211/// arrays, vectors, struct/union types, scalars, etc. The
212/// InitListChecker itself performs a recursive walk of the subobject
213/// structure of the type to be initialized, while stepping through
214/// the initializer list one element at a time. The IList and Index
215/// parameters to each of the Check* routines contain the active
216/// (syntactic) initializer list and the index into that initializer
217/// list that represents the current initializer. Each routine is
218/// responsible for moving that Index forward as it consumes elements.
219///
220/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000221/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000222/// initializer list and the index into that initializer list where we
223/// are copying initializers as we map them over to the semantic
224/// list. Once we have completed our recursive walk of the subobject
225/// structure, we will have constructed a full semantic initializer
226/// list.
227///
228/// C99 designators cause changes in the initializer list traversal,
229/// because they make the initialization "jump" into a specific
230/// subobject and then continue the initialization from that
231/// point. CheckDesignatedInitializer() recursively steps into the
232/// designated subobject and manages backing out the recursion to
233/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000234namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000235class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000236 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000237 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000238 bool VerifyOnly; // no diagnostics, no structure building
Benjamin Kramer6b441d62012-02-23 14:48:40 +0000239 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000240 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000241
Anders Carlsson6cabf312010-01-23 23:23:01 +0000242 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000243 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000244 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000245 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000246 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000247 InitListExpr *IList, QualType &T,
Richard Smith4e0d2e42013-09-20 20:10:22 +0000248 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000249 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000250 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000251 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000252 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000253 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000254 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000255 unsigned &StructuredIndex,
256 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000257 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000258 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000259 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000260 InitListExpr *StructuredList,
261 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000262 void CheckComplexType(const InitializedEntity &Entity,
263 InitListExpr *IList, QualType DeclType,
264 unsigned &Index,
265 InitListExpr *StructuredList,
266 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000267 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000268 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000269 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000270 InitListExpr *StructuredList,
271 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000272 void CheckReferenceType(const InitializedEntity &Entity,
273 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000274 unsigned &Index,
275 InitListExpr *StructuredList,
276 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000277 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000278 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000279 InitListExpr *StructuredList,
280 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000281 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000282 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000283 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000284 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000285 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000286 unsigned &StructuredIndex,
287 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000288 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000289 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000290 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000291 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000292 InitListExpr *StructuredList,
293 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000294 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000295 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000296 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000297 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000298 RecordDecl::field_iterator *NextField,
299 llvm::APSInt *NextElementIndex,
300 unsigned &Index,
301 InitListExpr *StructuredList,
302 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000303 bool FinishSubobjectInit,
304 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000305 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
306 QualType CurrentObjectType,
307 InitListExpr *StructuredList,
308 unsigned StructuredIndex,
309 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000310 void UpdateStructuredListElement(InitListExpr *StructuredList,
311 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000312 Expr *expr);
313 int numArrayElements(QualType DeclType);
314 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000315
Richard Smith454a7cd2014-06-03 08:26:00 +0000316 static ExprResult PerformEmptyInit(Sema &SemaRef,
317 SourceLocation Loc,
318 const InitializedEntity &Entity,
319 bool VerifyOnly);
320 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000321 const InitializedEntity &ParentEntity,
322 InitListExpr *ILE, bool &RequiresSecondPass);
Richard Smith454a7cd2014-06-03 08:26:00 +0000323 void FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000324 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000325 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
326 Expr *InitExpr, FieldDecl *Field,
327 bool TopLevelObject);
Richard Smith454a7cd2014-06-03 08:26:00 +0000328 void CheckEmptyInitializable(const InitializedEntity &Entity,
329 SourceLocation Loc);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000330
Douglas Gregor85df8d82009-01-29 00:45:39 +0000331public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000332 InitListChecker(Sema &S, const InitializedEntity &Entity,
Richard Smithde229232013-06-06 11:41:05 +0000333 InitListExpr *IL, QualType &T, bool VerifyOnly);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000334 bool HadError() { return hadError; }
335
336 // @brief Retrieves the fully-structured initializer list used for
337 // semantic analysis and code generation.
338 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
339};
Chris Lattner9ececce2009-02-24 22:48:58 +0000340} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000341
Richard Smith454a7cd2014-06-03 08:26:00 +0000342ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
343 SourceLocation Loc,
344 const InitializedEntity &Entity,
345 bool VerifyOnly) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000346 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
347 true);
Richard Smith454a7cd2014-06-03 08:26:00 +0000348 MultiExprArg SubInit;
349 Expr *InitExpr;
350 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
351
352 // C++ [dcl.init.aggr]p7:
353 // If there are fewer initializer-clauses in the list than there are
354 // members in the aggregate, then each member not explicitly initialized
355 // ...
Nico Weberbcb70ee2014-07-02 23:51:09 +0000356 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
357 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
358 if (EmptyInitList) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000359 // C++1y / DR1070:
360 // shall be initialized [...] from an empty initializer list.
361 //
362 // We apply the resolution of this DR to C++11 but not C++98, since C++98
363 // does not have useful semantics for initialization from an init list.
364 // We treat this as copy-initialization, because aggregate initialization
365 // always performs copy-initialization on its elements.
366 //
367 // Only do this if we're initializing a class type, to avoid filling in
368 // the initializer list where possible.
369 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
370 InitListExpr(SemaRef.Context, Loc, None, Loc);
371 InitExpr->setType(SemaRef.Context.VoidTy);
372 SubInit = InitExpr;
373 Kind = InitializationKind::CreateCopy(Loc, Loc);
374 } else {
375 // C++03:
376 // shall be value-initialized.
377 }
378
379 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000380 // libstdc++4.6 marks the vector default constructor as explicit in
381 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
382 // stlport does so too. Look for std::__debug for libstdc++, and for
383 // std:: for stlport. This is effectively a compiler-side implementation of
384 // LWG2193.
385 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
386 InitializationSequence::FK_ExplicitConstructor) {
387 OverloadCandidateSet::iterator Best;
388 OverloadingResult O =
389 InitSeq.getFailedCandidateSet()
390 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
391 (void)O;
392 assert(O == OR_Success && "Inconsistent overload resolution");
393 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
394 CXXRecordDecl *R = CtorDecl->getParent();
395
396 if (CtorDecl->getMinRequiredArguments() == 0 &&
397 CtorDecl->isExplicit() && R->getDeclName() &&
398 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
399
400
401 bool IsInStd = false;
402 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
Nico Weber5752ad02014-07-03 00:38:25 +0000403 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000404 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
405 IsInStd = true;
406 }
407
408 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
409 .Cases("basic_string", "deque", "forward_list", true)
410 .Cases("list", "map", "multimap", "multiset", true)
411 .Cases("priority_queue", "queue", "set", "stack", true)
412 .Cases("unordered_map", "unordered_set", "vector", true)
413 .Default(false)) {
414 InitSeq.InitializeFrom(
415 SemaRef, Entity,
416 InitializationKind::CreateValue(Loc, Loc, Loc, true),
417 MultiExprArg(), /*TopLevelOfInitList=*/false);
418 // Emit a warning for this. System header warnings aren't shown
419 // by default, but people working on system headers should see it.
420 if (!VerifyOnly) {
421 SemaRef.Diag(CtorDecl->getLocation(),
422 diag::warn_invalid_initializer_from_system_header);
423 SemaRef.Diag(Entity.getDecl()->getLocation(),
424 diag::note_used_in_initialization_here);
425 }
426 }
427 }
428 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000429 if (!InitSeq) {
430 if (!VerifyOnly) {
431 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
432 if (Entity.getKind() == InitializedEntity::EK_Member)
433 SemaRef.Diag(Entity.getDecl()->getLocation(),
434 diag::note_in_omitted_aggregate_initializer)
435 << /*field*/1 << Entity.getDecl();
436 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
437 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
438 << /*array element*/0 << Entity.getElementIndex();
439 }
440 return ExprError();
441 }
442
443 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
444 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
445}
446
447void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
448 SourceLocation Loc) {
449 assert(VerifyOnly &&
450 "CheckEmptyInitializable is only inteded for verification mode.");
451 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true).isInvalid())
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000452 hadError = true;
453}
454
Richard Smith454a7cd2014-06-03 08:26:00 +0000455void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000456 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000457 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000458 bool &RequiresSecondPass) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000459 SourceLocation Loc = ILE->getLocEnd();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000460 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000461 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000462 = InitializedEntity::InitializeMember(Field, &ParentEntity);
463 if (Init >= NumInits || !ILE->getInit(Init)) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000464 // C++1y [dcl.init.aggr]p7:
465 // If there are fewer initializer-clauses in the list than there are
466 // members in the aggregate, then each member not explicitly initialized
467 // shall be initialized from its brace-or-equal-initializer [...]
Richard Smith852c9db2013-04-20 22:23:05 +0000468 if (Field->hasInClassInitializer()) {
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) {
Richard Smith1b98ccc2014-07-19 01:39:17 +0000791 unsigned DK = diag::ext_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
Richard Smith1b98ccc2014-07-19 01:39:17 +0000810 unsigned DK = diag::ext_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 Smithc4158e862014-07-18 04:47:25 +0000917 } else if (isa<ImplicitValueInitExpr>(expr)) {
Richard Smith8aa561b2014-07-17 23:12:06 +0000918 // This happens during template instantiation when we see an InitListExpr
919 // that we've already checked once.
Richard Smithc4158e862014-07-18 04:47:25 +0000920 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
Richard Smith8aa561b2014-07-17 23:12:06 +0000921 "found implicit initialization for the wrong type");
922 if (!VerifyOnly)
923 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
924 ++Index;
925 return;
Richard Smithe20c83d2012-07-07 08:35:56 +0000926 }
927
Eli Friedman4628cf72013-08-19 22:12:56 +0000928 // FIXME: Need to handle atomic aggregate types with implicit init lists.
929 if (ElemType->isScalarType() || ElemType->isAtomicType())
John McCall5decec92011-02-21 07:57:55 +0000930 return CheckScalarType(Entity, IList, ElemType, Index,
931 StructuredList, StructuredIndex);
Anders Carlsson03068aa2009-08-27 17:18:13 +0000932
Eli Friedman4628cf72013-08-19 22:12:56 +0000933 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
934 ElemType->isArrayType()) && "Unexpected type");
935
John McCall5decec92011-02-21 07:57:55 +0000936 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
937 // arrayType can be incomplete if we're initializing a flexible
938 // array member. There's nothing we can do with the completed
939 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000940
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000941 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +0000942 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000943 CheckStringInit(expr, ElemType, arrayType, SemaRef);
944 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +0000945 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000946 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000947 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000948 }
John McCall5decec92011-02-21 07:57:55 +0000949
950 // Fall through for subaggregate initialization.
951
David Blaikiebbafb8a2012-03-11 07:00:24 +0000952 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCall5decec92011-02-21 07:57:55 +0000953 // C++ [dcl.init.aggr]p12:
954 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000955 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000956 // an initializer-list. If the initializer can initialize a
957 // member, the member is initialized. [...]
958
959 // FIXME: Better EqualLoc?
960 InitializationKind Kind =
961 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000962 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCall5decec92011-02-21 07:57:55 +0000963
964 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000965 if (!VerifyOnly) {
Richard Smith0f8ede12011-12-20 04:00:21 +0000966 ExprResult Result =
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000967 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smith0f8ede12011-12-20 04:00:21 +0000968 if (Result.isInvalid())
969 hadError = true;
John McCall5decec92011-02-21 07:57:55 +0000970
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000971 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000972 Result.getAs<Expr>());
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000973 }
John McCall5decec92011-02-21 07:57:55 +0000974 ++Index;
975 return;
976 }
977
978 // Fall through for subaggregate initialization
979 } else {
980 // C99 6.7.8p13:
981 //
982 // The initializer for a structure or union object that has
983 // automatic storage duration shall be either an initializer
984 // list as described below, or a single expression that has
985 // compatible structure or union type. In the latter case, the
986 // initial value of the object, including unnamed members, is
987 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000988 ExprResult ExprRes = expr;
John McCall5decec92011-02-21 07:57:55 +0000989 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000990 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
991 !VerifyOnly)
Eli Friedmanb2a8d462013-09-17 04:07:04 +0000992 != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +0000993 if (ExprRes.isInvalid())
994 hadError = true;
995 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000996 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000997 if (ExprRes.isInvalid())
998 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +0000999 }
1000 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001001 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +00001002 ++Index;
1003 return;
1004 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001005 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +00001006 // Fall through for subaggregate initialization
1007 }
1008
1009 // C++ [dcl.init.aggr]p12:
1010 //
1011 // [...] Otherwise, if the member is itself a non-empty
1012 // subaggregate, brace elision is assumed and the initializer is
1013 // considered for the initialization of the first member of
1014 // the subaggregate.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001015 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00001016 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +00001017 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1018 StructuredIndex);
1019 ++StructuredIndex;
1020 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001021 if (!VerifyOnly) {
1022 // We cannot initialize this element, so let
1023 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001024 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001025 /*TopLevelOfInitList=*/true);
1026 }
John McCall5decec92011-02-21 07:57:55 +00001027 hadError = true;
1028 ++Index;
1029 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +00001030 }
Eli Friedman23a9e312008-05-19 19:16:24 +00001031}
1032
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001033void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1034 InitListExpr *IList, QualType DeclType,
1035 unsigned &Index,
1036 InitListExpr *StructuredList,
1037 unsigned &StructuredIndex) {
1038 assert(Index == 0 && "Index in explicit init list must be zero");
1039
1040 // As an extension, clang supports complex initializers, which initialize
1041 // a complex number component-wise. When an explicit initializer list for
1042 // a complex number contains two two initializers, this extension kicks in:
1043 // it exepcts the initializer list to contain two elements convertible to
1044 // the element type of the complex type. The first element initializes
1045 // the real part, and the second element intitializes the imaginary part.
1046
1047 if (IList->getNumInits() != 2)
1048 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1049 StructuredIndex);
1050
1051 // This is an extension in C. (The builtin _Complex type does not exist
1052 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001053 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001054 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1055 << IList->getSourceRange();
1056
1057 // Initialize the complex number.
1058 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1059 InitializedEntity ElementEntity =
1060 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1061
1062 for (unsigned i = 0; i < 2; ++i) {
1063 ElementEntity.setElementIndex(Index);
1064 CheckSubElementType(ElementEntity, IList, elementType, Index,
1065 StructuredList, StructuredIndex);
1066 }
1067}
1068
1069
Anders Carlsson6cabf312010-01-23 23:23:01 +00001070void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001071 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001072 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001073 InitListExpr *StructuredList,
1074 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001075 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001076 if (!VerifyOnly)
1077 SemaRef.Diag(IList->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001078 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smithc8239732011-10-18 21:39:00 +00001079 diag::warn_cxx98_compat_empty_scalar_initializer :
1080 diag::err_empty_scalar_initializer)
1081 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001082 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001083 ++Index;
1084 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001085 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001086 }
John McCall643169b2010-11-11 00:46:36 +00001087
1088 Expr *expr = IList->getInit(Index);
1089 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001090 // FIXME: This is invalid, and accepting it causes overload resolution
1091 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001092 if (!VerifyOnly)
1093 SemaRef.Diag(SubIList->getLocStart(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001094 diag::ext_many_braces_around_scalar_init)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001095 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001096
1097 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1098 StructuredIndex);
1099 return;
1100 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001101 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001102 SemaRef.Diag(expr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001103 diag::err_designator_for_scalar_init)
1104 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001105 hadError = true;
1106 ++Index;
1107 ++StructuredIndex;
1108 return;
1109 }
1110
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001111 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001112 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001113 hadError = true;
1114 ++Index;
1115 return;
1116 }
1117
John McCall643169b2010-11-11 00:46:36 +00001118 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001119 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001120 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001121
Craig Topperc3ec1492014-05-26 06:22:03 +00001122 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001123
1124 if (Result.isInvalid())
1125 hadError = true; // types weren't compatible.
1126 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001127 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001128
John McCall643169b2010-11-11 00:46:36 +00001129 if (ResultExpr != expr) {
1130 // The type was promoted, update initializer list.
1131 IList->setInit(Index, ResultExpr);
1132 }
1133 }
1134 if (hadError)
1135 ++StructuredIndex;
1136 else
1137 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1138 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001139}
1140
Anders Carlsson6cabf312010-01-23 23:23:01 +00001141void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1142 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001143 unsigned &Index,
1144 InitListExpr *StructuredList,
1145 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001146 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001147 // FIXME: It would be wonderful if we could point at the actual member. In
1148 // general, it would be useful to pass location information down the stack,
1149 // so that we know the location (or decl) of the "current object" being
1150 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001151 if (!VerifyOnly)
1152 SemaRef.Diag(IList->getLocStart(),
1153 diag::err_init_reference_member_uninitialized)
1154 << DeclType
1155 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001156 hadError = true;
1157 ++Index;
1158 ++StructuredIndex;
1159 return;
1160 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001161
1162 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001163 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001164 if (!VerifyOnly)
1165 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1166 << DeclType << IList->getSourceRange();
1167 hadError = true;
1168 ++Index;
1169 ++StructuredIndex;
1170 return;
1171 }
1172
1173 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001174 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001175 hadError = true;
1176 ++Index;
1177 return;
1178 }
1179
1180 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001181 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1182 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001183
1184 if (Result.isInvalid())
1185 hadError = true;
1186
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001187 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001188 IList->setInit(Index, expr);
1189
1190 if (hadError)
1191 ++StructuredIndex;
1192 else
1193 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1194 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001195}
1196
Anders Carlsson6cabf312010-01-23 23:23:01 +00001197void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001198 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001199 unsigned &Index,
1200 InitListExpr *StructuredList,
1201 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001202 const VectorType *VT = DeclType->getAs<VectorType>();
1203 unsigned maxElements = VT->getNumElements();
1204 unsigned numEltsInit = 0;
1205 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001206
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001207 if (Index >= IList->getNumInits()) {
1208 // Make sure the element type can be value-initialized.
1209 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001210 CheckEmptyInitializable(
1211 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1212 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001213 return;
1214 }
1215
David Blaikiebbafb8a2012-03-11 07:00:24 +00001216 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001217 // If the initializing element is a vector, try to copy-initialize
1218 // instead of breaking it apart (which is doomed to failure anyway).
1219 Expr *Init = IList->getInit(Index);
1220 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001221 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001222 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001223 hadError = true;
1224 ++Index;
1225 return;
1226 }
1227
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001228 ExprResult Result =
1229 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1230 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001231
Craig Topperc3ec1492014-05-26 06:22:03 +00001232 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001233 if (Result.isInvalid())
1234 hadError = true; // types weren't compatible.
1235 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001236 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001237
John McCall6a16b2f2010-10-30 00:11:39 +00001238 if (ResultExpr != Init) {
1239 // The type was promoted, update initializer list.
1240 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001241 }
1242 }
John McCall6a16b2f2010-10-30 00:11:39 +00001243 if (hadError)
1244 ++StructuredIndex;
1245 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001246 UpdateStructuredListElement(StructuredList, StructuredIndex,
1247 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001248 ++Index;
1249 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001250 }
Mike Stump11289f42009-09-09 15:08:12 +00001251
John McCall6a16b2f2010-10-30 00:11:39 +00001252 InitializedEntity ElementEntity =
1253 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001254
John McCall6a16b2f2010-10-30 00:11:39 +00001255 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1256 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001257 if (Index >= IList->getNumInits()) {
1258 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001259 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
John McCall6a16b2f2010-10-30 00:11:39 +00001260 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001261 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001262
John McCall6a16b2f2010-10-30 00:11:39 +00001263 ElementEntity.setElementIndex(Index);
1264 CheckSubElementType(ElementEntity, IList, elementType, Index,
1265 StructuredList, StructuredIndex);
1266 }
James Molloy9eef2652014-06-20 14:35:13 +00001267
1268 if (VerifyOnly)
1269 return;
1270
1271 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1272 const VectorType *T = Entity.getType()->getAs<VectorType>();
1273 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1274 T->getVectorKind() == VectorType::NeonPolyVector)) {
1275 // The ability to use vector initializer lists is a GNU vector extension
1276 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1277 // endian machines it works fine, however on big endian machines it
1278 // exhibits surprising behaviour:
1279 //
1280 // uint32x2_t x = {42, 64};
1281 // return vget_lane_u32(x, 0); // Will return 64.
1282 //
1283 // Because of this, explicitly call out that it is non-portable.
1284 //
1285 SemaRef.Diag(IList->getLocStart(),
1286 diag::warn_neon_vector_initializer_non_portable);
1287
1288 const char *typeCode;
1289 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1290
1291 if (elementType->isFloatingType())
1292 typeCode = "f";
1293 else if (elementType->isSignedIntegerType())
1294 typeCode = "s";
1295 else if (elementType->isUnsignedIntegerType())
1296 typeCode = "u";
1297 else
1298 llvm_unreachable("Invalid element type!");
1299
1300 SemaRef.Diag(IList->getLocStart(),
1301 SemaRef.Context.getTypeSize(VT) > 64 ?
1302 diag::note_neon_vector_initializer_non_portable_q :
1303 diag::note_neon_vector_initializer_non_portable)
1304 << typeCode << typeSize;
1305 }
1306
John McCall6a16b2f2010-10-30 00:11:39 +00001307 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001308 }
John McCall6a16b2f2010-10-30 00:11:39 +00001309
1310 InitializedEntity ElementEntity =
1311 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001312
John McCall6a16b2f2010-10-30 00:11:39 +00001313 // OpenCL initializers allows vectors to be constructed from vectors.
1314 for (unsigned i = 0; i < maxElements; ++i) {
1315 // Don't attempt to go past the end of the init list
1316 if (Index >= IList->getNumInits())
1317 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001318
John McCall6a16b2f2010-10-30 00:11:39 +00001319 ElementEntity.setElementIndex(Index);
1320
1321 QualType IType = IList->getInit(Index)->getType();
1322 if (!IType->isVectorType()) {
1323 CheckSubElementType(ElementEntity, IList, elementType, Index,
1324 StructuredList, StructuredIndex);
1325 ++numEltsInit;
1326 } else {
1327 QualType VecType;
1328 const VectorType *IVT = IType->getAs<VectorType>();
1329 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001330
John McCall6a16b2f2010-10-30 00:11:39 +00001331 if (IType->isExtVectorType())
1332 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1333 else
1334 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001335 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001336 CheckSubElementType(ElementEntity, IList, VecType, Index,
1337 StructuredList, StructuredIndex);
1338 numEltsInit += numIElts;
1339 }
1340 }
1341
1342 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001343 if (numEltsInit != maxElements) {
1344 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001345 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001346 diag::err_vector_incorrect_num_initializers)
1347 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1348 hadError = true;
1349 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001350}
1351
Anders Carlsson6cabf312010-01-23 23:23:01 +00001352void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001353 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001354 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001355 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001356 unsigned &Index,
1357 InitListExpr *StructuredList,
1358 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001359 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1360
Steve Narofff8ecff22008-05-01 22:18:59 +00001361 // Check for the special-case of initializing an array with a string.
1362 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001363 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1364 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001365 // We place the string literal directly into the resulting
1366 // initializer list. This is the only place where the structure
1367 // of the structured initializer list doesn't match exactly,
1368 // because doing so would involve allocating one character
1369 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001370 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001371 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1372 UpdateStructuredListElement(StructuredList, StructuredIndex,
1373 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001374 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1375 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001376 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001377 return;
1378 }
1379 }
John McCall66884dd2011-02-21 07:22:22 +00001380 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001381 // Check for VLAs; in standard C it would be possible to check this
1382 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1383 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001384 if (!VerifyOnly)
1385 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1386 diag::err_variable_object_no_init)
1387 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001388 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001389 ++Index;
1390 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001391 return;
1392 }
1393
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001394 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001395 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1396 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001397 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001398 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001399 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001400 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001401 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001402 maxElementsKnown = true;
1403 }
1404
John McCall66884dd2011-02-21 07:22:22 +00001405 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001406 while (Index < IList->getNumInits()) {
1407 Expr *Init = IList->getInit(Index);
1408 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001409 // If we're not the subobject that matches up with the '{' for
1410 // the designator, we shouldn't be handling the
1411 // designator. Return immediately.
1412 if (!SubobjectIsDesignatorContext)
1413 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001414
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001415 // Handle this designated initializer. elementIndex will be
1416 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001417 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001418 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001419 StructuredList, StructuredIndex, true,
1420 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001421 hadError = true;
1422 continue;
1423 }
1424
Douglas Gregor033d1252009-01-23 16:54:12 +00001425 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001426 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001427 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001428 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001429 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001430
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001431 // If the array is of incomplete type, keep track of the number of
1432 // elements in the initializer.
1433 if (!maxElementsKnown && elementIndex > maxElements)
1434 maxElements = elementIndex;
1435
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001436 continue;
1437 }
1438
1439 // If we know the maximum number of elements, and we've already
1440 // hit it, stop consuming elements in the initializer list.
1441 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001442 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001443
Anders Carlsson6cabf312010-01-23 23:23:01 +00001444 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001445 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001446 Entity);
1447 // Check this element.
1448 CheckSubElementType(ElementEntity, IList, elementType, Index,
1449 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001450 ++elementIndex;
1451
1452 // If the array is of incomplete type, keep track of the number of
1453 // elements in the initializer.
1454 if (!maxElementsKnown && elementIndex > maxElements)
1455 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001456 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001457 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001458 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001459 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001460 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001461 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001462 // Sizing an array implicitly to zero is not allowed by ISO C,
1463 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001464 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001465 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001466 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001467
Mike Stump11289f42009-09-09 15:08:12 +00001468 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001469 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001470 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001471 if (!hadError && VerifyOnly) {
1472 // Check if there are any members of the array that get value-initialized.
1473 // If so, check if doing that is possible.
1474 // FIXME: This needs to detect holes left by designated initializers too.
1475 if (maxElementsKnown && elementIndex < maxElements)
Richard Smith454a7cd2014-06-03 08:26:00 +00001476 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1477 SemaRef.Context, 0, Entity),
1478 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001479 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001480}
1481
Eli Friedman3fa64df2011-08-23 22:24:57 +00001482bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1483 Expr *InitExpr,
1484 FieldDecl *Field,
1485 bool TopLevelObject) {
1486 // Handle GNU flexible array initializers.
1487 unsigned FlexArrayDiag;
1488 if (isa<InitListExpr>(InitExpr) &&
1489 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1490 // Empty flexible array init always allowed as an extension
1491 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001492 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001493 // Disallow flexible array init in C++; it is not required for gcc
1494 // compatibility, and it needs work to IRGen correctly in general.
1495 FlexArrayDiag = diag::err_flexible_array_init;
1496 } else if (!TopLevelObject) {
1497 // Disallow flexible array init on non-top-level object
1498 FlexArrayDiag = diag::err_flexible_array_init;
1499 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1500 // Disallow flexible array init on anything which is not a variable.
1501 FlexArrayDiag = diag::err_flexible_array_init;
1502 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1503 // Disallow flexible array init on local variables.
1504 FlexArrayDiag = diag::err_flexible_array_init;
1505 } else {
1506 // Allow other cases.
1507 FlexArrayDiag = diag::ext_flexible_array_init;
1508 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001509
1510 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001511 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001512 FlexArrayDiag)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001513 << InitExpr->getLocStart();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001514 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1515 << Field;
1516 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001517
1518 return FlexArrayDiag != diag::ext_flexible_array_init;
1519}
1520
Anders Carlsson6cabf312010-01-23 23:23:01 +00001521void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001522 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001523 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001524 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001525 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001526 unsigned &Index,
1527 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001528 unsigned &StructuredIndex,
1529 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001530 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001531
Eli Friedman23a9e312008-05-19 19:16:24 +00001532 // If the record is invalid, some of it's members are invalid. To avoid
1533 // confusion, we forgo checking the intializer for the entire record.
1534 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001535 // Assume it was supposed to consume a single initializer.
1536 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001537 hadError = true;
1538 return;
Mike Stump11289f42009-09-09 15:08:12 +00001539 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001540
1541 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001542 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001543
1544 // If there's a default initializer, use it.
1545 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1546 if (VerifyOnly)
1547 return;
1548 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1549 Field != FieldEnd; ++Field) {
1550 if (Field->hasInClassInitializer()) {
1551 StructuredList->setInitializedFieldInUnion(*Field);
1552 // FIXME: Actually build a CXXDefaultInitExpr?
1553 return;
1554 }
1555 }
1556 }
1557
1558 // Value-initialize the first named member of the union.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001559 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1560 Field != FieldEnd; ++Field) {
1561 if (Field->getDeclName()) {
1562 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001563 CheckEmptyInitializable(
1564 InitializedEntity::InitializeMember(*Field, &Entity),
1565 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001566 else
David Blaikie40ed2972012-06-06 20:45:41 +00001567 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001568 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001569 }
1570 }
1571 return;
1572 }
1573
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001574 // If structDecl is a forward declaration, this loop won't do
1575 // anything except look at designated initializers; That's okay,
1576 // because an error should get printed out elsewhere. It might be
1577 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001578 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001579 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001580 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001581 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001582 while (Index < IList->getNumInits()) {
1583 Expr *Init = IList->getInit(Index);
1584
1585 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001586 // If we're not the subobject that matches up with the '{' for
1587 // the designator, we shouldn't be handling the
1588 // designator. Return immediately.
1589 if (!SubobjectIsDesignatorContext)
1590 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001591
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001592 // Handle this designated initializer. Field will be updated to
1593 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001594 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001595 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001596 StructuredList, StructuredIndex,
1597 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001598 hadError = true;
1599
Douglas Gregora9add4e2009-02-12 19:00:39 +00001600 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001601
1602 // Disable check for missing fields when designators are used.
1603 // This matches gcc behaviour.
1604 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001605 continue;
1606 }
1607
1608 if (Field == FieldEnd) {
1609 // We've run out of fields. We're done.
1610 break;
1611 }
1612
Douglas Gregora9add4e2009-02-12 19:00:39 +00001613 // We've already initialized a member of a union. We're done.
1614 if (InitializedSomething && DeclType->isUnionType())
1615 break;
1616
Douglas Gregor91f84212008-12-11 16:49:14 +00001617 // If we've hit the flexible array member at the end, we're done.
1618 if (Field->getType()->isIncompleteArrayType())
1619 break;
1620
Douglas Gregor51695702009-01-29 16:53:55 +00001621 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001622 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001623 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001624 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001625 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001626
Douglas Gregora82064c2011-06-29 21:51:31 +00001627 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001628 bool InvalidUse;
1629 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00001630 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001631 else
David Blaikie40ed2972012-06-06 20:45:41 +00001632 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001633 IList->getInit(Index)->getLocStart());
1634 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001635 ++Index;
1636 ++Field;
1637 hadError = true;
1638 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001639 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001640
Anders Carlsson6cabf312010-01-23 23:23:01 +00001641 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001642 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001643 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1644 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001645 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001646
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001647 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001648 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00001649 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001650 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001651
1652 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001653 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001654
John McCalle40b58e2010-03-11 19:32:38 +00001655 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001656 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1657 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1658 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001659 // It is possible we have one or more unnamed bitfields remaining.
1660 // Find first (if any) named field and emit warning.
1661 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1662 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00001663 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00001664 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00001665 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00001666 break;
1667 }
1668 }
1669 }
1670
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001671 // Check that any remaining fields can be value-initialized.
1672 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1673 !Field->getType()->isIncompleteArrayType()) {
1674 // FIXME: Should check for holes left by designated initializers too.
1675 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00001676 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00001677 CheckEmptyInitializable(
1678 InitializedEntity::InitializeMember(*Field, &Entity),
1679 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001680 }
1681 }
1682
Mike Stump11289f42009-09-09 15:08:12 +00001683 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001684 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001685 return;
1686
David Blaikie40ed2972012-06-06 20:45:41 +00001687 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00001688 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001689 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001690 ++Index;
1691 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001692 }
1693
Anders Carlsson6cabf312010-01-23 23:23:01 +00001694 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001695 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001696
Anders Carlsson6cabf312010-01-23 23:23:01 +00001697 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001698 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001699 StructuredList, StructuredIndex);
1700 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001701 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001702 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001703}
Steve Narofff8ecff22008-05-01 22:18:59 +00001704
Douglas Gregord5846a12009-04-15 06:41:24 +00001705/// \brief Expand a field designator that refers to a member of an
1706/// anonymous struct or union into a series of field designators that
1707/// refers to the field within the appropriate subobject.
1708///
Douglas Gregord5846a12009-04-15 06:41:24 +00001709static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001710 DesignatedInitExpr *DIE,
1711 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001712 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001713 typedef DesignatedInitExpr::Designator Designator;
1714
Douglas Gregord5846a12009-04-15 06:41:24 +00001715 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001716 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001717 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1718 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1719 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00001720 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00001721 DIE->getDesignator(DesigIdx)->getDotLoc(),
1722 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1723 else
Craig Topperc3ec1492014-05-26 06:22:03 +00001724 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1725 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001726 assert(isa<FieldDecl>(*PI));
1727 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001728 }
1729
1730 // Expand the current designator into the set of replacement
1731 // designators, so we have a full subobject path down to where the
1732 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001733 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001734 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001735}
Mike Stump11289f42009-09-09 15:08:12 +00001736
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001737/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001738/// corresponds to FieldName.
1739static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1740 IdentifierInfo *FieldName) {
Argyrios Kyrtzidis54b10292012-09-10 22:04:26 +00001741 if (!FieldName)
Craig Topperc3ec1492014-05-26 06:22:03 +00001742 return nullptr;
Argyrios Kyrtzidis54b10292012-09-10 22:04:26 +00001743
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001744 assert(AnonField->isAnonymousStructOrUnion());
1745 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman6d1bebb2012-02-09 22:16:56 +00001746 while (IndirectFieldDecl *IF =
1747 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidis54b10292012-09-10 22:04:26 +00001748 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001749 return IF;
1750 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001751 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001752 return nullptr;
Douglas Gregord5846a12009-04-15 06:41:24 +00001753}
1754
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001755static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1756 DesignatedInitExpr *DIE) {
1757 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1758 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1759 for (unsigned I = 0; I < NumIndexExprs; ++I)
1760 IndexExprs[I] = DIE->getSubExpr(I + 1);
1761 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001762 DIE->size(), IndexExprs,
1763 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001764 DIE->usesGNUSyntax(), DIE->getInit());
1765}
1766
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001767namespace {
1768
1769// Callback to only accept typo corrections that are for field members of
1770// the given struct or union.
1771class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1772 public:
1773 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1774 : Record(RD) {}
1775
Craig Toppere14c0f82014-03-12 04:55:44 +00001776 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001777 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1778 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1779 }
1780
1781 private:
1782 RecordDecl *Record;
1783};
1784
1785}
1786
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001787/// @brief Check the well-formedness of a C99 designated initializer.
1788///
1789/// Determines whether the designated initializer @p DIE, which
1790/// resides at the given @p Index within the initializer list @p
1791/// IList, is well-formed for a current object of type @p DeclType
1792/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001793/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001794/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001795///
1796/// @param IList The initializer list in which this designated
1797/// initializer occurs.
1798///
Douglas Gregora5324162009-04-15 04:56:10 +00001799/// @param DIE The designated initializer expression.
1800///
1801/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001802///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00001803/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001804/// into which the designation in @p DIE should refer.
1805///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001806/// @param NextField If non-NULL and the first designator in @p DIE is
1807/// a field, this will be set to the field declaration corresponding
1808/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001809///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001810/// @param NextElementIndex If non-NULL and the first designator in @p
1811/// DIE is an array designator or GNU array-range designator, this
1812/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001813///
1814/// @param Index Index into @p IList where the designated initializer
1815/// @p DIE occurs.
1816///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001817/// @param StructuredList The initializer list expression that
1818/// describes all of the subobject initializers in the order they'll
1819/// actually be initialized.
1820///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001821/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001822bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001823InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001824 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001825 DesignatedInitExpr *DIE,
1826 unsigned DesigIdx,
1827 QualType &CurrentObjectType,
1828 RecordDecl::field_iterator *NextField,
1829 llvm::APSInt *NextElementIndex,
1830 unsigned &Index,
1831 InitListExpr *StructuredList,
1832 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001833 bool FinishSubobjectInit,
1834 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001835 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001836 // Check the actual initialization for the designated object type.
1837 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001838
1839 // Temporarily remove the designator expression from the
1840 // initializer list that the child calls see, so that we don't try
1841 // to re-process the designator.
1842 unsigned OldIndex = Index;
1843 IList->setInit(OldIndex, DIE->getInit());
1844
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001845 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001846 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001847
1848 // Restore the designated initializer expression in the syntactic
1849 // form of the initializer list.
1850 if (IList->getInit(OldIndex) != DIE->getInit())
1851 DIE->setInit(IList->getInit(OldIndex));
1852 IList->setInit(OldIndex, DIE);
1853
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001854 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001855 }
1856
Douglas Gregora5324162009-04-15 04:56:10 +00001857 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001858 bool IsFirstDesignator = (DesigIdx == 0);
1859 if (!VerifyOnly) {
1860 assert((IsFirstDesignator || StructuredList) &&
1861 "Need a non-designated initializer list to start from");
1862
1863 // Determine the structural initializer list that corresponds to the
1864 // current subobject.
Benjamin Kramer6b441d62012-02-23 14:48:40 +00001865 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001866 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1867 StructuredList, StructuredIndex,
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001868 SourceRange(D->getLocStart(),
1869 DIE->getLocEnd()));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001870 assert(StructuredList && "Expected a structured initializer list");
1871 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001872
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001873 if (D->isFieldDesignator()) {
1874 // C99 6.7.8p7:
1875 //
1876 // If a designator has the form
1877 //
1878 // . identifier
1879 //
1880 // then the current object (defined below) shall have
1881 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001882 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001883 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001884 if (!RT) {
1885 SourceLocation Loc = D->getDotLoc();
1886 if (Loc.isInvalid())
1887 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001888 if (!VerifyOnly)
1889 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001890 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001891 ++Index;
1892 return true;
1893 }
1894
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001895 // Note: we perform a linear search of the fields here, despite
1896 // the fact that we have a faster lookup method, because we always
1897 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001898 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001899 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001900 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001901 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001902 Field = RT->getDecl()->field_begin(),
1903 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001904 for (; Field != FieldEnd; ++Field) {
1905 if (Field->isUnnamedBitfield())
1906 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001907
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001908 // If we find a field representing an anonymous field, look in the
1909 // IndirectFieldDecl that follow for the designated initializer.
1910 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1911 if (IndirectFieldDecl *IF =
David Blaikie40ed2972012-06-06 20:45:41 +00001912 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001913 // In verify mode, don't modify the original.
1914 if (VerifyOnly)
1915 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001916 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1917 D = DIE->getDesignator(DesigIdx);
1918 break;
1919 }
1920 }
David Blaikie40ed2972012-06-06 20:45:41 +00001921 if (KnownField && KnownField == *Field)
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001922 break;
1923 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001924 break;
1925
1926 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001927 }
1928
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001929 if (Field == FieldEnd) {
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001930 if (VerifyOnly) {
1931 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001932 return true; // No typo correction when just trying this out.
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001933 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001934
Douglas Gregord5846a12009-04-15 06:41:24 +00001935 // There was no normal field in the struct with the designated
1936 // name. Perform another lookup for this name, which may find
1937 // something that we can't designate (e.g., a member function),
1938 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001939 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001940 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Craig Topperc3ec1492014-05-26 06:22:03 +00001941 FieldDecl *ReplacementField = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00001942 if (Lookup.empty()) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001943 // Name lookup didn't find anything. Determine whether this
1944 // was a typo for another field name.
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001945 FieldInitializerValidatorCCC Validator(RT->getDecl());
Richard Smithf9b15102013-08-17 00:46:16 +00001946 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
1947 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Craig Topperc3ec1492014-05-26 06:22:03 +00001948 Sema::LookupMemberName, /*Scope=*/ nullptr, /*SS=*/ nullptr,
1949 Validator, Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00001950 SemaRef.diagnoseTypo(
1951 Corrected,
1952 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
1953 << FieldName << CurrentObjectType);
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001954 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001955 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001956 } else {
1957 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1958 << FieldName << CurrentObjectType;
1959 ++Index;
1960 return true;
1961 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001962 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001963
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001964 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001965 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001966 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001967 << FieldName;
David Blaikieff7d47a2012-12-19 00:45:41 +00001968 SemaRef.Diag(Lookup.front()->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001969 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001970 ++Index;
1971 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001972 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001973
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001974 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001975 // The replacement field comes from typo correction; find it
1976 // in the list of fields.
1977 FieldIndex = 0;
1978 Field = RT->getDecl()->field_begin();
1979 for (; Field != FieldEnd; ++Field) {
1980 if (Field->isUnnamedBitfield())
1981 continue;
1982
David Blaikie40ed2972012-06-06 20:45:41 +00001983 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001984 Field->getIdentifier() == ReplacementField->getIdentifier())
1985 break;
1986
1987 ++FieldIndex;
1988 }
1989 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001990 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001991
1992 // All of the fields of a union are located at the same place in
1993 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001994 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001995 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00001996 if (!VerifyOnly) {
1997 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
1998 if (CurrentField && CurrentField != *Field) {
1999 assert(StructuredList->getNumInits() == 1
2000 && "A union should never have more than one initializer!");
2001
2002 // we're about to throw away an initializer, emit warning
2003 SemaRef.Diag(D->getFieldLoc(),
2004 diag::warn_initializer_overrides)
2005 << D->getSourceRange();
2006 Expr *ExistingInit = StructuredList->getInit(0);
2007 SemaRef.Diag(ExistingInit->getLocStart(),
2008 diag::note_previous_initializer)
2009 << /*FIXME:has side effects=*/0
2010 << ExistingInit->getSourceRange();
2011
2012 // remove existing initializer
2013 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00002014 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002015 }
2016
David Blaikie40ed2972012-06-06 20:45:41 +00002017 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002018 }
Douglas Gregor51695702009-01-29 16:53:55 +00002019 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002020
Douglas Gregora82064c2011-06-29 21:51:31 +00002021 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002022 bool InvalidUse;
2023 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00002024 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002025 else
David Blaikie40ed2972012-06-06 20:45:41 +00002026 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002027 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002028 ++Index;
2029 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002030 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002031
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002032 if (!VerifyOnly) {
2033 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00002034 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00002035
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002036 // Make sure that our non-designated initializer list has space
2037 // for a subobject corresponding to this field.
2038 if (FieldIndex >= StructuredList->getNumInits())
2039 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2040 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002041
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002042 // This designator names a flexible array member.
2043 if (Field->getType()->isIncompleteArrayType()) {
2044 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00002045 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002046 // We can't designate an object within the flexible array
2047 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002048 if (!VerifyOnly) {
2049 DesignatedInitExpr::Designator *NextD
2050 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002051 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002052 diag::err_designator_into_flexible_array_member)
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002053 << SourceRange(NextD->getLocStart(),
2054 DIE->getLocEnd());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002055 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002056 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002057 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002058 Invalid = true;
2059 }
2060
Chris Lattner001b29c2010-10-10 17:49:49 +00002061 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2062 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002063 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002064 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002065 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002066 diag::err_flexible_array_init_needs_braces)
2067 << DIE->getInit()->getSourceRange();
2068 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002069 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002070 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002071 Invalid = true;
2072 }
2073
Eli Friedman3fa64df2011-08-23 22:24:57 +00002074 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00002075 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002076 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002077 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002078
2079 if (Invalid) {
2080 ++Index;
2081 return true;
2082 }
2083
2084 // Initialize the array.
2085 bool prevHadError = hadError;
2086 unsigned newStructuredIndex = FieldIndex;
2087 unsigned OldIndex = Index;
2088 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00002089
2090 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002091 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002092 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002093 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002094
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002095 IList->setInit(OldIndex, DIE);
2096 if (hadError && !prevHadError) {
2097 ++Field;
2098 ++FieldIndex;
2099 if (NextField)
2100 *NextField = Field;
2101 StructuredIndex = FieldIndex;
2102 return true;
2103 }
2104 } else {
2105 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002106 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002107 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002108
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002109 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002110 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002111 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002112 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002113 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002114 true, false))
2115 return true;
2116 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002117
2118 // Find the position of the next field to be initialized in this
2119 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002120 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002121 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002122
2123 // If this the first designator, our caller will continue checking
2124 // the rest of this struct/class/union subobject.
2125 if (IsFirstDesignator) {
2126 if (NextField)
2127 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002128 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002129 return false;
2130 }
2131
Douglas Gregor17bd0942009-01-28 23:36:17 +00002132 if (!FinishSubobjectInit)
2133 return false;
2134
Douglas Gregord5846a12009-04-15 06:41:24 +00002135 // We've already initialized something in the union; we're done.
2136 if (RT->getDecl()->isUnion())
2137 return hadError;
2138
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002139 // Check the remaining fields within this class/struct/union subobject.
2140 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002141
Anders Carlsson6cabf312010-01-23 23:23:01 +00002142 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002143 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002144 return hadError && !prevHadError;
2145 }
2146
2147 // C99 6.7.8p6:
2148 //
2149 // If a designator has the form
2150 //
2151 // [ constant-expression ]
2152 //
2153 // then the current object (defined below) shall have array
2154 // type and the expression shall be an integer constant
2155 // expression. If the array is of unknown size, any
2156 // nonnegative value is valid.
2157 //
2158 // Additionally, cope with the GNU extension that permits
2159 // designators of the form
2160 //
2161 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002162 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002163 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002164 if (!VerifyOnly)
2165 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2166 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002167 ++Index;
2168 return true;
2169 }
2170
Craig Topperc3ec1492014-05-26 06:22:03 +00002171 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002172 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2173 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002174 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002175 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002176 DesignatedEndIndex = DesignatedStartIndex;
2177 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002178 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002179
Mike Stump11289f42009-09-09 15:08:12 +00002180 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002181 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002182 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002183 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002184 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002185
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002186 // Codegen can't handle evaluating array range designators that have side
2187 // effects, because we replicate the AST value for each initialized element.
2188 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2189 // elements with something that has a side effect, so codegen can emit an
2190 // "error unsupported" error instead of miscompiling the app.
2191 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002192 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002193 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002194 }
2195
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002196 if (isa<ConstantArrayType>(AT)) {
2197 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002198 DesignatedStartIndex
2199 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002200 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002201 DesignatedEndIndex
2202 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002203 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2204 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002205 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002206 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002207 diag::err_array_designator_too_large)
2208 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2209 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002210 ++Index;
2211 return true;
2212 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002213 } else {
2214 // Make sure the bit-widths and signedness match.
2215 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002216 DesignatedEndIndex
2217 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002218 else if (DesignatedStartIndex.getBitWidth() <
2219 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002220 DesignatedStartIndex
2221 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002222 DesignatedStartIndex.setIsUnsigned(true);
2223 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002224 }
Mike Stump11289f42009-09-09 15:08:12 +00002225
Eli Friedman1f16b742013-06-11 21:48:11 +00002226 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2227 // We're modifying a string literal init; we have to decompose the string
2228 // so we can modify the individual characters.
2229 ASTContext &Context = SemaRef.Context;
2230 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2231
2232 // Compute the character type
2233 QualType CharTy = AT->getElementType();
2234
2235 // Compute the type of the integer literals.
2236 QualType PromotedCharTy = CharTy;
2237 if (CharTy->isPromotableIntegerType())
2238 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2239 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2240
2241 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2242 // Get the length of the string.
2243 uint64_t StrLen = SL->getLength();
2244 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2245 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2246 StructuredList->resizeInits(Context, StrLen);
2247
2248 // Build a literal for each character in the string, and put them into
2249 // the init list.
2250 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2251 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2252 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002253 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002254 if (CharTy != PromotedCharTy)
2255 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002256 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002257 StructuredList->updateInit(Context, i, Init);
2258 }
2259 } else {
2260 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2261 std::string Str;
2262 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2263
2264 // Get the length of the string.
2265 uint64_t StrLen = Str.size();
2266 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2267 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2268 StructuredList->resizeInits(Context, StrLen);
2269
2270 // Build a literal for each character in the string, and put them into
2271 // the init list.
2272 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2273 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2274 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002275 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002276 if (CharTy != PromotedCharTy)
2277 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002278 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002279 StructuredList->updateInit(Context, i, Init);
2280 }
2281 }
2282 }
2283
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002284 // Make sure that our non-designated initializer list has space
2285 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002286 if (!VerifyOnly &&
2287 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002288 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002289 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002290
Douglas Gregor17bd0942009-01-28 23:36:17 +00002291 // Repeatedly perform subobject initializations in the range
2292 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002293
Douglas Gregor17bd0942009-01-28 23:36:17 +00002294 // Move to the next designator
2295 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2296 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002297
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002298 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002299 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002300
Douglas Gregor17bd0942009-01-28 23:36:17 +00002301 while (DesignatedStartIndex <= DesignatedEndIndex) {
2302 // Recurse to check later designated subobjects.
2303 QualType ElementType = AT->getElementType();
2304 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002305
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002306 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002307 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002308 ElementType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002309 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002310 (DesignatedStartIndex == DesignatedEndIndex),
2311 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002312 return true;
2313
2314 // Move to the next index in the array that we'll be initializing.
2315 ++DesignatedStartIndex;
2316 ElementIndex = DesignatedStartIndex.getZExtValue();
2317 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002318
2319 // If this the first designator, our caller will continue checking
2320 // the rest of this array subobject.
2321 if (IsFirstDesignator) {
2322 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002323 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002324 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002325 return false;
2326 }
Mike Stump11289f42009-09-09 15:08:12 +00002327
Douglas Gregor17bd0942009-01-28 23:36:17 +00002328 if (!FinishSubobjectInit)
2329 return false;
2330
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002331 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002332 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002333 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002334 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002335 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002336 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002337}
2338
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002339// Get the structured initializer list for a subobject of type
2340// @p CurrentObjectType.
2341InitListExpr *
2342InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2343 QualType CurrentObjectType,
2344 InitListExpr *StructuredList,
2345 unsigned StructuredIndex,
2346 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002347 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002348 return nullptr; // No structured list in verification-only mode.
2349 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002350 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002351 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002352 else if (StructuredIndex < StructuredList->getNumInits())
2353 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002354
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002355 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2356 return Result;
2357
2358 if (ExistingInit) {
2359 // We are creating an initializer list that initializes the
2360 // subobjects of the current object, but there was already an
2361 // initialization that completely initialized the current
2362 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002363 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002364 // struct X { int a, b; };
2365 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002366 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002367 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2368 // designated initializer re-initializes the whole
2369 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002370 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002371 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002372 << InitRange;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002373 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002374 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002375 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002376 << ExistingInit->getSourceRange();
2377 }
2378
Mike Stump11289f42009-09-09 15:08:12 +00002379 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002380 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002381 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002382 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002383
Eli Friedman91f5ae52012-02-23 02:25:10 +00002384 QualType ResultType = CurrentObjectType;
2385 if (!ResultType->isArrayType())
2386 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2387 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002388
Douglas Gregor6d00c992009-03-20 23:58:33 +00002389 // Pre-allocate storage for the structured initializer list.
2390 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002391 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002392 bool GotNumInits = false;
2393 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002394 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002395 GotNumInits = true;
2396 } else if (Index < IList->getNumInits()) {
2397 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002398 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002399 GotNumInits = true;
2400 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002401 }
2402
Mike Stump11289f42009-09-09 15:08:12 +00002403 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002404 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2405 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2406 NumElements = CAType->getSize().getZExtValue();
2407 // Simple heuristic so that we don't allocate a very large
2408 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002409 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002410 NumElements = 0;
2411 }
John McCall9dd450b2009-09-21 23:43:11 +00002412 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002413 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002414 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002415 RecordDecl *RDecl = RType->getDecl();
2416 if (RDecl->isUnion())
2417 NumElements = 1;
2418 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002419 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002420 }
2421
Ted Kremenekac034612010-04-13 23:39:13 +00002422 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002423
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002424 // Link this new initializer list into the structured initializer
2425 // lists.
2426 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002427 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002428 else {
2429 Result->setSyntacticForm(IList);
2430 SyntacticToSemantic[IList] = Result;
2431 }
2432
2433 return Result;
2434}
2435
2436/// Update the initializer at index @p StructuredIndex within the
2437/// structured initializer list to the value @p expr.
2438void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2439 unsigned &StructuredIndex,
2440 Expr *expr) {
2441 // No structured initializer list to update
2442 if (!StructuredList)
2443 return;
2444
Ted Kremenekac034612010-04-13 23:39:13 +00002445 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2446 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002447 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002448 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002449 diag::warn_initializer_overrides)
2450 << expr->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002451 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002452 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002453 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002454 << PrevInit->getSourceRange();
2455 }
Mike Stump11289f42009-09-09 15:08:12 +00002456
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002457 ++StructuredIndex;
2458}
2459
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002460/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002461/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002462/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002463/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002464/// failure. Returns the index expression, possibly with an implicit cast
2465/// added, on success. If everything went okay, Value will receive the
2466/// value of the constant expression.
2467static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002468CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002469 SourceLocation Loc = Index->getLocStart();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002470
2471 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002472 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2473 if (Result.isInvalid())
2474 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002475
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002476 if (Value.isSigned() && Value.isNegative())
2477 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002478 << Value.toString(10) << Index->getSourceRange();
2479
Douglas Gregor51650d32009-01-23 21:04:18 +00002480 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002481 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002482}
2483
John McCalldadc5752010-08-24 06:29:42 +00002484ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002485 SourceLocation Loc,
2486 bool GNUSyntax,
2487 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002488 typedef DesignatedInitExpr::Designator ASTDesignator;
2489
2490 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002491 SmallVector<ASTDesignator, 32> Designators;
2492 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002493
2494 // Build designators and check array designator expressions.
2495 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2496 const Designator &D = Desig.getDesignator(Idx);
2497 switch (D.getKind()) {
2498 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002499 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002500 D.getFieldLoc()));
2501 break;
2502
2503 case Designator::ArrayDesignator: {
2504 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2505 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002506 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002507 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002508 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002509 Invalid = true;
2510 else {
2511 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002512 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002513 D.getRBracketLoc()));
2514 InitExpressions.push_back(Index);
2515 }
2516 break;
2517 }
2518
2519 case Designator::ArrayRangeDesignator: {
2520 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2521 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2522 llvm::APSInt StartValue;
2523 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002524 bool StartDependent = StartIndex->isTypeDependent() ||
2525 StartIndex->isValueDependent();
2526 bool EndDependent = EndIndex->isTypeDependent() ||
2527 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002528 if (!StartDependent)
2529 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002530 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002531 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002532 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002533
2534 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002535 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002536 else {
2537 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002538 if (StartDependent || EndDependent) {
2539 // Nothing to compute.
2540 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002541 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002542 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002543 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002544
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002545 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002546 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002547 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002548 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2549 Invalid = true;
2550 } else {
2551 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002552 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002553 D.getEllipsisLoc(),
2554 D.getRBracketLoc()));
2555 InitExpressions.push_back(StartIndex);
2556 InitExpressions.push_back(EndIndex);
2557 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002558 }
2559 break;
2560 }
2561 }
2562 }
2563
2564 if (Invalid || Init.isInvalid())
2565 return ExprError();
2566
2567 // Clear out the expressions within the designation.
2568 Desig.ClearExprs(*this);
2569
2570 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002571 = DesignatedInitExpr::Create(Context,
2572 Designators.data(), Designators.size(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00002573 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002574 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002575
David Blaikiebbafb8a2012-03-11 07:00:24 +00002576 if (!getLangOpts().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002577 Diag(DIE->getLocStart(), diag::ext_designated_init)
2578 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002579
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002580 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002581}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002582
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002583//===----------------------------------------------------------------------===//
2584// Initialization entity
2585//===----------------------------------------------------------------------===//
2586
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002587InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002588 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002589 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002590{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002591 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2592 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002593 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002594 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002595 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002596 Type = VT->getElementType();
2597 } else {
2598 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2599 assert(CT && "Unexpected type");
2600 Kind = EK_ComplexElement;
2601 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002602 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002603}
2604
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002605InitializedEntity
2606InitializedEntity::InitializeBase(ASTContext &Context,
2607 const CXXBaseSpecifier *Base,
2608 bool IsInheritedVirtualBase) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002609 InitializedEntity Result;
2610 Result.Kind = EK_Base;
Craig Topperc3ec1492014-05-26 06:22:03 +00002611 Result.Parent = nullptr;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002612 Result.Base = reinterpret_cast<uintptr_t>(Base);
2613 if (IsInheritedVirtualBase)
2614 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002615
Douglas Gregor1b303932009-12-22 15:35:07 +00002616 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002617 return Result;
2618}
2619
Douglas Gregor85dabae2009-12-16 01:38:02 +00002620DeclarationName InitializedEntity::getName() const {
2621 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002622 case EK_Parameter:
2623 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00002624 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2625 return (D ? D->getDeclName() : DeclarationName());
2626 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002627
2628 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002629 case EK_Member:
2630 return VariableOrMember->getDeclName();
2631
Douglas Gregor19666fb2012-02-15 16:57:26 +00002632 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002633 return DeclarationName(Capture.VarID);
Douglas Gregor19666fb2012-02-15 16:57:26 +00002634
Douglas Gregor85dabae2009-12-16 01:38:02 +00002635 case EK_Result:
2636 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002637 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002638 case EK_Temporary:
2639 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002640 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002641 case EK_ArrayElement:
2642 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002643 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002644 case EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002645 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002646 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002647 return DeclarationName();
2648 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002649
David Blaikie8a40f702012-01-17 06:56:22 +00002650 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002651}
2652
Douglas Gregora4b592a2009-12-19 03:01:41 +00002653DeclaratorDecl *InitializedEntity::getDecl() const {
2654 switch (getKind()) {
2655 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002656 case EK_Member:
2657 return VariableOrMember;
2658
John McCall31168b02011-06-15 23:02:42 +00002659 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002660 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00002661 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2662
Douglas Gregora4b592a2009-12-19 03:01:41 +00002663 case EK_Result:
2664 case EK_Exception:
2665 case EK_New:
2666 case EK_Temporary:
2667 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002668 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002669 case EK_ArrayElement:
2670 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002671 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002672 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002673 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002674 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002675 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00002676 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00002677 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002678
David Blaikie8a40f702012-01-17 06:56:22 +00002679 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002680}
2681
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002682bool InitializedEntity::allowsNRVO() const {
2683 switch (getKind()) {
2684 case EK_Result:
2685 case EK_Exception:
2686 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002687
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002688 case EK_Variable:
2689 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002690 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002691 case EK_Member:
2692 case EK_New:
2693 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002694 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002695 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002696 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002697 case EK_ArrayElement:
2698 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002699 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002700 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002701 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002702 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002703 break;
2704 }
2705
2706 return false;
2707}
2708
Richard Smithe6c01442013-06-05 00:46:14 +00002709unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00002710 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00002711 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2712 for (unsigned I = 0; I != Depth; ++I)
2713 OS << "`-";
2714
2715 switch (getKind()) {
2716 case EK_Variable: OS << "Variable"; break;
2717 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002718 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2719 break;
Richard Smithe6c01442013-06-05 00:46:14 +00002720 case EK_Result: OS << "Result"; break;
2721 case EK_Exception: OS << "Exception"; break;
2722 case EK_Member: OS << "Member"; break;
2723 case EK_New: OS << "New"; break;
2724 case EK_Temporary: OS << "Temporary"; break;
2725 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002726 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00002727 case EK_Base: OS << "Base"; break;
2728 case EK_Delegating: OS << "Delegating"; break;
2729 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2730 case EK_VectorElement: OS << "VectorElement " << Index; break;
2731 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2732 case EK_BlockElement: OS << "Block"; break;
2733 case EK_LambdaCapture:
2734 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002735 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00002736 break;
2737 }
2738
2739 if (Decl *D = getDecl()) {
2740 OS << " ";
2741 cast<NamedDecl>(D)->printQualifiedName(OS);
2742 }
2743
2744 OS << " '" << getType().getAsString() << "'\n";
2745
2746 return Depth + 1;
2747}
2748
2749void InitializedEntity::dump() const {
2750 dumpImpl(llvm::errs());
2751}
2752
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002753//===----------------------------------------------------------------------===//
2754// Initialization sequence
2755//===----------------------------------------------------------------------===//
2756
2757void InitializationSequence::Step::Destroy() {
2758 switch (Kind) {
2759 case SK_ResolveAddressOfOverloadedFunction:
2760 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002761 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002762 case SK_CastDerivedToBaseLValue:
2763 case SK_BindReference:
2764 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002765 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002766 case SK_UserConversion:
2767 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002768 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002769 case SK_QualificationConversionLValue:
Richard Smith77be48a2014-07-31 06:31:19 +00002770 case SK_AtomicConversion:
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
Richard Smith77be48a2014-07-31 06:31:19 +00002923void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
2924 Step S;
2925 S.Kind = SK_AtomicConversion;
2926 S.Type = Ty;
2927 Steps.push_back(S);
2928}
2929
Jordan Roseb1312a52013-04-11 00:58:58 +00002930void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2931 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2932
2933 Step S;
2934 S.Kind = SK_LValueToRValue;
2935 S.Type = Ty;
2936 Steps.push_back(S);
2937}
2938
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002939void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00002940 const ImplicitConversionSequence &ICS, QualType T,
2941 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002942 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00002943 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
2944 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002945 S.Type = T;
2946 S.ICS = new ImplicitConversionSequence(ICS);
2947 Steps.push_back(S);
2948}
2949
Douglas Gregor51e77d52009-12-10 17:56:55 +00002950void InitializationSequence::AddListInitializationStep(QualType T) {
2951 Step S;
2952 S.Kind = SK_ListInitialization;
2953 S.Type = T;
2954 Steps.push_back(S);
2955}
2956
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002957void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002958InitializationSequence
2959::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2960 AccessSpecifier Access,
2961 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002962 bool HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002963 bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002964 Step S;
Richard Smithf8adcdc2014-07-17 05:12:35 +00002965 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
Richard Smith53324112014-07-16 21:33:43 +00002966 : SK_ConstructorInitializationFromList
2967 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002968 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002969 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002970 S.Function.Function = Constructor;
2971 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002972 Steps.push_back(S);
2973}
2974
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002975void InitializationSequence::AddZeroInitializationStep(QualType T) {
2976 Step S;
2977 S.Kind = SK_ZeroInitialization;
2978 S.Type = T;
2979 Steps.push_back(S);
2980}
2981
Douglas Gregore1314a62009-12-18 05:02:21 +00002982void InitializationSequence::AddCAssignmentStep(QualType T) {
2983 Step S;
2984 S.Kind = SK_CAssignment;
2985 S.Type = T;
2986 Steps.push_back(S);
2987}
2988
Eli Friedman78275202009-12-19 08:11:05 +00002989void InitializationSequence::AddStringInitStep(QualType T) {
2990 Step S;
2991 S.Kind = SK_StringInit;
2992 S.Type = T;
2993 Steps.push_back(S);
2994}
2995
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002996void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2997 Step S;
2998 S.Kind = SK_ObjCObjectConversion;
2999 S.Type = T;
3000 Steps.push_back(S);
3001}
3002
Douglas Gregore2f943b2011-02-22 18:29:51 +00003003void InitializationSequence::AddArrayInitStep(QualType T) {
3004 Step S;
3005 S.Kind = SK_ArrayInit;
3006 S.Type = T;
3007 Steps.push_back(S);
3008}
3009
Richard Smithebeed412012-02-15 22:38:09 +00003010void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3011 Step S;
3012 S.Kind = SK_ParenthesizedArrayInit;
3013 S.Type = T;
3014 Steps.push_back(S);
3015}
3016
John McCall31168b02011-06-15 23:02:42 +00003017void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3018 bool shouldCopy) {
3019 Step s;
3020 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3021 : SK_PassByIndirectRestore);
3022 s.Type = type;
3023 Steps.push_back(s);
3024}
3025
3026void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3027 Step S;
3028 S.Kind = SK_ProduceObjCObject;
3029 S.Type = T;
3030 Steps.push_back(S);
3031}
3032
Sebastian Redlc1839b12012-01-17 22:49:42 +00003033void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3034 Step S;
3035 S.Kind = SK_StdInitializerList;
3036 S.Type = T;
3037 Steps.push_back(S);
3038}
3039
Guy Benyei61054192013-02-07 10:55:47 +00003040void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3041 Step S;
3042 S.Kind = SK_OCLSamplerInit;
3043 S.Type = T;
3044 Steps.push_back(S);
3045}
3046
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003047void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3048 Step S;
3049 S.Kind = SK_OCLZeroEvent;
3050 S.Type = T;
3051 Steps.push_back(S);
3052}
3053
Sebastian Redl29526f02011-11-27 16:50:07 +00003054void InitializationSequence::RewrapReferenceInitList(QualType T,
3055 InitListExpr *Syntactic) {
3056 assert(Syntactic->getNumInits() == 1 &&
3057 "Can only rewrap trivial init lists.");
3058 Step S;
3059 S.Kind = SK_UnwrapInitList;
3060 S.Type = Syntactic->getInit(0)->getType();
3061 Steps.insert(Steps.begin(), S);
3062
3063 S.Kind = SK_RewrapInitList;
3064 S.Type = T;
3065 S.WrappingSyntacticList = Syntactic;
3066 Steps.push_back(S);
3067}
3068
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003069void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003070 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00003071 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003072 this->Failure = Failure;
3073 this->FailedOverloadResult = Result;
3074}
3075
3076//===----------------------------------------------------------------------===//
3077// Attempt initialization
3078//===----------------------------------------------------------------------===//
3079
John McCall31168b02011-06-15 23:02:42 +00003080static void MaybeProduceObjCObject(Sema &S,
3081 InitializationSequence &Sequence,
3082 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003083 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00003084
3085 /// When initializing a parameter, produce the value if it's marked
3086 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003087 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00003088 if (!Entity.isParameterConsumed())
3089 return;
3090
3091 assert(Entity.getType()->isObjCRetainableType() &&
3092 "consuming an object of unretainable type?");
3093 Sequence.AddProduceObjCObjectStep(Entity.getType());
3094
3095 /// When initializing a return value, if the return type is a
3096 /// retainable type, then returns need to immediately retain the
3097 /// object. If an autorelease is required, it will be done at the
3098 /// last instant.
3099 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3100 if (!Entity.getType()->isObjCRetainableType())
3101 return;
3102
3103 Sequence.AddProduceObjCObjectStep(Entity.getType());
3104 }
3105}
3106
Richard Smithcc1b96d2013-06-12 22:31:48 +00003107static void TryListInitialization(Sema &S,
3108 const InitializedEntity &Entity,
3109 const InitializationKind &Kind,
3110 InitListExpr *InitList,
3111 InitializationSequence &Sequence);
3112
Richard Smithd86812d2012-07-05 08:39:21 +00003113/// \brief When initializing from init list via constructor, handle
3114/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003115///
Richard Smithd86812d2012-07-05 08:39:21 +00003116/// \return true if we have handled initialization of an object of type
3117/// std::initializer_list<T>, false otherwise.
3118static bool TryInitializerListConstruction(Sema &S,
3119 InitListExpr *List,
3120 QualType DestType,
3121 InitializationSequence &Sequence) {
3122 QualType E;
3123 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003124 return false;
3125
Richard Smithcc1b96d2013-06-12 22:31:48 +00003126 if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
3127 Sequence.setIncompleteTypeFailure(E);
3128 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003129 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003130
3131 // Try initializing a temporary array from the init list.
3132 QualType ArrayType = S.Context.getConstantArrayType(
3133 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3134 List->getNumInits()),
3135 clang::ArrayType::Normal, 0);
3136 InitializedEntity HiddenArray =
3137 InitializedEntity::InitializeTemporary(ArrayType);
3138 InitializationKind Kind =
3139 InitializationKind::CreateDirectList(List->getExprLoc());
3140 TryListInitialization(S, HiddenArray, Kind, List, Sequence);
3141 if (Sequence)
3142 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003143 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003144}
3145
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003146static OverloadingResult
3147ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003148 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003149 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003150 ArrayRef<NamedDecl *> Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003151 OverloadCandidateSet::iterator &Best,
3152 bool CopyInitializing, bool AllowExplicit,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003153 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003154 CandidateSet.clear();
3155
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003156 for (ArrayRef<NamedDecl *>::iterator
3157 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003158 NamedDecl *D = *Con;
3159 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3160 bool SuppressUserConversions = false;
3161
3162 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003163 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003164 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3165 if (ConstructorTmpl)
3166 Constructor = cast<CXXConstructorDecl>(
3167 ConstructorTmpl->getTemplatedDecl());
3168 else {
3169 Constructor = cast<CXXConstructorDecl>(D);
3170
Richard Smith6c6ddab2013-09-21 21:23:47 +00003171 // C++11 [over.best.ics]p4:
3172 // However, when considering the argument of a constructor or
3173 // user-defined conversion function that is a candidate:
3174 // -- by 13.3.1.3 when invoked for the copying/moving of a temporary
3175 // in the second step of a class copy-initialization,
3176 // -- by 13.3.1.7 when passing the initializer list as a single
3177 // argument or when the initializer list has exactly one elementand
3178 // a conversion to some class X or reference to (possibly
3179 // cv-qualified) X is considered for the first parameter of a
3180 // constructor of X, or
3181 // -- by 13.3.1.4, 13.3.1.5, or 13.3.1.6 in all cases,
3182 // only standard conversion sequences and ellipsis conversion sequences
3183 // are considered.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003184 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003185 Constructor->isCopyOrMoveConstructor())
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003186 SuppressUserConversions = true;
3187 }
3188
3189 if (!Constructor->isInvalidDecl() &&
3190 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003191 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003192 if (ConstructorTmpl)
3193 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003194 /*ExplicitArgs*/ nullptr, Args,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003195 CandidateSet, SuppressUserConversions);
Douglas Gregor6073dca2012-02-24 23:56:31 +00003196 else {
3197 // C++ [over.match.copy]p1:
3198 // - When initializing a temporary to be bound to the first parameter
3199 // of a constructor that takes a reference to possibly cv-qualified
3200 // T as its first argument, called with a single argument in the
3201 // context of direct-initialization, explicit conversion functions
3202 // are also considered.
3203 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003204 Args.size() == 1 &&
Douglas Gregor6073dca2012-02-24 23:56:31 +00003205 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003206 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003207 SuppressUserConversions,
3208 /*PartialOverloading=*/false,
3209 /*AllowExplicit=*/AllowExplicitConv);
3210 }
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003211 }
3212 }
3213
3214 // Perform overload resolution and return the result.
3215 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3216}
3217
Sebastian Redled2e5322011-12-22 14:44:04 +00003218/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3219/// enumerates the constructors of the initialized entity and performs overload
3220/// resolution to select the best.
Sebastian Redl88e4d492012-02-04 21:27:33 +00003221/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redled2e5322011-12-22 14:44:04 +00003222/// class type.
3223static void TryConstructorInitialization(Sema &S,
3224 const InitializedEntity &Entity,
3225 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003226 MultiExprArg Args, QualType DestType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003227 InitializationSequence &Sequence,
Sebastian Redl88e4d492012-02-04 21:27:33 +00003228 bool InitListSyntax = false) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003229 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Sebastian Redl88e4d492012-02-04 21:27:33 +00003230 "InitListSyntax must come with a single initializer list argument.");
3231
Sebastian Redled2e5322011-12-22 14:44:04 +00003232 // The type we're constructing needs to be complete.
3233 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003234 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003235 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003236 }
3237
3238 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3239 assert(DestRecordType && "Constructor initialization requires record type");
3240 CXXRecordDecl *DestRecordDecl
3241 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3242
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003243 // Build the candidate set directly in the initialization sequence
3244 // structure, so that it will persist if we fail.
3245 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3246
3247 // Determine whether we are allowed to call explicit constructors or
3248 // explicit conversion operators.
Sebastian Redl048a6d72012-04-01 19:54:59 +00003249 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003250 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003251
Sebastian Redled2e5322011-12-22 14:44:04 +00003252 // - Otherwise, if T is a class type, constructors are considered. The
3253 // applicable constructors are enumerated, and the best one is chosen
3254 // through overload resolution.
David Blaikieff7d47a2012-12-19 00:45:41 +00003255 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003256 // The container holding the constructors can under certain conditions
3257 // be changed while iterating (e.g. because of deserialization).
3258 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003259 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redled2e5322011-12-22 14:44:04 +00003260
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003261 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003262 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003263 bool AsInitializerList = false;
3264
3265 // C++11 [over.match.list]p1:
3266 // When objects of non-aggregate type T are list-initialized, overload
3267 // resolution selects the constructor in two phases:
3268 // - Initially, the candidate functions are the initializer-list
3269 // constructors of the class T and the argument list consists of the
3270 // initializer list as a single argument.
3271 if (InitListSyntax) {
Richard Smithd86812d2012-07-05 08:39:21 +00003272 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003273 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003274
3275 // If the initializer list has no elements and T has a default constructor,
3276 // the first phase is omitted.
Richard Smith2be35f52012-12-01 02:35:44 +00003277 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003278 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003279 CandidateSet, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003280 CopyInitialization, AllowExplicit,
3281 /*OnlyListConstructor=*/true,
3282 InitListSyntax);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003283
3284 // Time to unwrap the init list.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003285 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003286 }
3287
3288 // C++11 [over.match.list]p1:
3289 // - If no viable initializer-list constructor is found, overload resolution
3290 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003291 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003292 // elements of the initializer list.
3293 if (Result == OR_No_Viable_Function) {
3294 AsInitializerList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003295 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003296 CandidateSet, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003297 CopyInitialization, AllowExplicit,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003298 /*OnlyListConstructors=*/false,
3299 InitListSyntax);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003300 }
3301 if (Result) {
Sebastian Redl88e4d492012-02-04 21:27:33 +00003302 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003303 InitializationSequence::FK_ListConstructorOverloadFailed :
3304 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003305 Result);
3306 return;
3307 }
3308
Richard Smithd86812d2012-07-05 08:39:21 +00003309 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003310 // If a program calls for the default initialization of an object
3311 // of a const-qualified type T, T shall be a class type with a
3312 // user-provided default constructor.
3313 if (Kind.getKind() == InitializationKind::IK_Default &&
3314 Entity.getType().isConstQualified() &&
Aaron Ballman899b9c62012-07-31 22:40:31 +00003315 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redled2e5322011-12-22 14:44:04 +00003316 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3317 return;
3318 }
3319
Sebastian Redl048a6d72012-04-01 19:54:59 +00003320 // C++11 [over.match.list]p1:
3321 // In copy-list-initialization, if an explicit constructor is chosen, the
3322 // initializer is ill-formed.
3323 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3324 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3325 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3326 return;
3327 }
3328
Sebastian Redled2e5322011-12-22 14:44:04 +00003329 // Add the constructor initialization step. Any cv-qualification conversion is
3330 // subsumed by the initialization.
3331 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redled2e5322011-12-22 14:44:04 +00003332 Sequence.AddConstructorInitializationStep(CtorDecl,
3333 Best->FoundDecl.getAccess(),
3334 DestType, HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003335 InitListSyntax, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003336}
3337
Sebastian Redl29526f02011-11-27 16:50:07 +00003338static bool
3339ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3340 Expr *Initializer,
3341 QualType &SourceType,
3342 QualType &UnqualifiedSourceType,
3343 QualType UnqualifiedTargetType,
3344 InitializationSequence &Sequence) {
3345 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3346 S.Context.OverloadTy) {
3347 DeclAccessPair Found;
3348 bool HadMultipleCandidates = false;
3349 if (FunctionDecl *Fn
3350 = S.ResolveAddressOfOverloadedFunction(Initializer,
3351 UnqualifiedTargetType,
3352 false, Found,
3353 &HadMultipleCandidates)) {
3354 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3355 HadMultipleCandidates);
3356 SourceType = Fn->getType();
3357 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3358 } else if (!UnqualifiedTargetType->isRecordType()) {
3359 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3360 return true;
3361 }
3362 }
3363 return false;
3364}
3365
3366static void TryReferenceInitializationCore(Sema &S,
3367 const InitializedEntity &Entity,
3368 const InitializationKind &Kind,
3369 Expr *Initializer,
3370 QualType cv1T1, QualType T1,
3371 Qualifiers T1Quals,
3372 QualType cv2T2, QualType T2,
3373 Qualifiers T2Quals,
3374 InitializationSequence &Sequence);
3375
Richard Smithd86812d2012-07-05 08:39:21 +00003376static void TryValueInitialization(Sema &S,
3377 const InitializedEntity &Entity,
3378 const InitializationKind &Kind,
3379 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00003380 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00003381
Sebastian Redl29526f02011-11-27 16:50:07 +00003382/// \brief Attempt list initialization of a reference.
3383static void TryReferenceListInitialization(Sema &S,
3384 const InitializedEntity &Entity,
3385 const InitializationKind &Kind,
3386 InitListExpr *InitList,
Richard Smithfaadef72013-06-08 00:02:08 +00003387 InitializationSequence &Sequence) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003388 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003389 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003390 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3391 return;
3392 }
3393
3394 QualType DestType = Entity.getType();
3395 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3396 Qualifiers T1Quals;
3397 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3398
3399 // Reference initialization via an initializer list works thus:
3400 // If the initializer list consists of a single element that is
3401 // reference-related to the referenced type, bind directly to that element
3402 // (possibly creating temporaries).
3403 // Otherwise, initialize a temporary with the initializer list and
3404 // bind to that.
3405 if (InitList->getNumInits() == 1) {
3406 Expr *Initializer = InitList->getInit(0);
3407 QualType cv2T2 = Initializer->getType();
3408 Qualifiers T2Quals;
3409 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3410
3411 // If this fails, creating a temporary wouldn't work either.
3412 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3413 T1, Sequence))
3414 return;
3415
3416 SourceLocation DeclLoc = Initializer->getLocStart();
3417 bool dummy1, dummy2, dummy3;
3418 Sema::ReferenceCompareResult RefRelationship
3419 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3420 dummy2, dummy3);
3421 if (RefRelationship >= Sema::Ref_Related) {
3422 // Try to bind the reference here.
3423 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3424 T1Quals, cv2T2, T2, T2Quals, Sequence);
3425 if (Sequence)
3426 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3427 return;
3428 }
Richard Smith03d93932013-01-15 07:58:29 +00003429
3430 // Update the initializer if we've resolved an overloaded function.
3431 if (Sequence.step_begin() != Sequence.step_end())
3432 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00003433 }
3434
3435 // Not reference-related. Create a temporary and bind to that.
3436 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3437
3438 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3439 if (Sequence) {
3440 if (DestType->isRValueReferenceType() ||
3441 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3442 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3443 else
3444 Sequence.SetFailed(
3445 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3446 }
3447}
3448
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003449/// \brief Attempt list initialization (C++0x [dcl.init.list])
3450static void TryListInitialization(Sema &S,
3451 const InitializedEntity &Entity,
3452 const InitializationKind &Kind,
3453 InitListExpr *InitList,
3454 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003455 QualType DestType = Entity.getType();
3456
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003457 // C++ doesn't allow scalar initialization with more than one argument.
3458 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003459 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003460 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3461 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3462 return;
3463 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003464 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003465 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003466 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003467 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003468 if (DestType->isRecordType()) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003469 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003470 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl4f28b582012-02-19 12:27:43 +00003471 return;
3472 }
3473
Richard Smithd86812d2012-07-05 08:39:21 +00003474 // C++11 [dcl.init.list]p3:
3475 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redl4f28b582012-02-19 12:27:43 +00003476 if (!DestType->isAggregateType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003477 if (S.getLangOpts().CPlusPlus11) {
Richard Smithd86812d2012-07-05 08:39:21 +00003478 // - Otherwise, if the initializer list has no elements and T is a
3479 // class type with a default constructor, the object is
3480 // value-initialized.
3481 if (InitList->getNumInits() == 0) {
3482 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
Richard Smith2be35f52012-12-01 02:35:44 +00003483 if (RD->hasDefaultConstructor()) {
Richard Smithd86812d2012-07-05 08:39:21 +00003484 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3485 return;
3486 }
3487 }
3488
3489 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3490 // an initializer_list object constructed [...]
3491 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3492 return;
3493
3494 // - Otherwise, if T is a class type, constructors are considered.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003495 Expr *InitListAsExpr = InitList;
3496 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smithd86812d2012-07-05 08:39:21 +00003497 Sequence, /*InitListSyntax*/true);
Sebastian Redl4f28b582012-02-19 12:27:43 +00003498 } else
3499 Sequence.SetFailed(
3500 InitializationSequence::FK_InitListBadDestinationType);
3501 return;
3502 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003503 }
Richard Smith089c3162013-09-21 21:55:46 +00003504 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
3505 InitList->getNumInits() == 1 &&
3506 InitList->getInit(0)->getType()->isRecordType()) {
3507 // - Otherwise, if the initializer list has a single element of type E
3508 // [...references are handled above...], the object or reference is
3509 // initialized from that element; if a narrowing conversion is required
3510 // to convert the element to T, the program is ill-formed.
3511 //
3512 // Per core-24034, this is direct-initialization if we were performing
3513 // direct-list-initialization and copy-initialization otherwise.
3514 // We can't use InitListChecker for this, because it always performs
3515 // copy-initialization. This only matters if we might use an 'explicit'
3516 // conversion operator, so we only need to handle the cases where the source
3517 // is of record type.
3518 InitializationKind SubKind =
3519 Kind.getKind() == InitializationKind::IK_DirectList
3520 ? InitializationKind::CreateDirect(Kind.getLocation(),
3521 InitList->getLBraceLoc(),
3522 InitList->getRBraceLoc())
3523 : Kind;
3524 Expr *SubInit[1] = { InitList->getInit(0) };
3525 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3526 /*TopLevelOfInitList*/true);
3527 if (Sequence)
3528 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3529 return;
3530 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003531
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003532 InitListChecker CheckInitList(S, Entity, InitList,
Richard Smithde229232013-06-06 11:41:05 +00003533 DestType, /*VerifyOnly=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003534 if (CheckInitList.HadError()) {
3535 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3536 return;
3537 }
3538
3539 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003540 Sequence.AddListInitializationStep(DestType);
3541}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003542
3543/// \brief Try a reference initialization that involves calling a conversion
3544/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003545static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3546 const InitializedEntity &Entity,
3547 const InitializationKind &Kind,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003548 Expr *Initializer,
3549 bool AllowRValues,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003550 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003551 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003552 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3553 QualType T1 = cv1T1.getUnqualifiedType();
3554 QualType cv2T2 = Initializer->getType();
3555 QualType T2 = cv2T2.getUnqualifiedType();
3556
3557 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003558 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003559 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003560 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003561 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003562 ObjCConversion,
3563 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003564 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003565 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003566 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003567 (void)ObjCLifetimeConversion;
3568
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003569 // Build the candidate set directly in the initialization sequence
3570 // structure, so that it will persist if we fail.
3571 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3572 CandidateSet.clear();
3573
3574 // Determine whether we are allowed to call explicit constructors or
3575 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003576 bool AllowExplicit = Kind.AllowExplicit();
Richard Smith6c6ddab2013-09-21 21:23:47 +00003577 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3578
Craig Topperc3ec1492014-05-26 06:22:03 +00003579 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003580 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3581 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003582 // The type we're converting to is a class type. Enumerate its constructors
3583 // to see if there is a suitable conversion.
3584 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003585
David Blaikieff7d47a2012-12-19 00:45:41 +00003586 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003587 // The container holding the constructors can under certain conditions
3588 // be changed while iterating (e.g. because of deserialization).
3589 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003590 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00003591 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003592 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3593 NamedDecl *D = *CI;
John McCalla0296f72010-03-19 07:35:19 +00003594 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3595
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003596 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003597 CXXConstructorDecl *Constructor = nullptr;
John McCalla0296f72010-03-19 07:35:19 +00003598 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003599 if (ConstructorTmpl)
3600 Constructor = cast<CXXConstructorDecl>(
3601 ConstructorTmpl->getTemplatedDecl());
3602 else
John McCalla0296f72010-03-19 07:35:19 +00003603 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003604
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003605 if (!Constructor->isInvalidDecl() &&
3606 Constructor->isConvertingConstructor(AllowExplicit)) {
3607 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003608 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003609 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003610 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003611 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003612 else
John McCalla0296f72010-03-19 07:35:19 +00003613 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003614 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003615 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003616 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003617 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003618 }
John McCall3696dcb2010-08-17 07:23:57 +00003619 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3620 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003621
Craig Topperc3ec1492014-05-26 06:22:03 +00003622 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003623 if ((T2RecordType = T2->getAs<RecordType>()) &&
3624 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003625 // The type we're converting from is a class type, enumerate its conversion
3626 // functions.
3627 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3628
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003629 std::pair<CXXRecordDecl::conversion_iterator,
3630 CXXRecordDecl::conversion_iterator>
3631 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3632 for (CXXRecordDecl::conversion_iterator
3633 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003634 NamedDecl *D = *I;
3635 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3636 if (isa<UsingShadowDecl>(D))
3637 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003638
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003639 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3640 CXXConversionDecl *Conv;
3641 if (ConvTemplate)
3642 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3643 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003644 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003645
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003646 // If the conversion function doesn't return a reference type,
3647 // it can't be considered for this conversion unless we're allowed to
3648 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003649 // FIXME: Do we need to make sure that we only consider conversion
3650 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003651 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00003652 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003653 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3654 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003655 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003656 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00003657 DestType, CandidateSet,
3658 /*AllowObjCConversionOnExplicit=*/
3659 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003660 else
John McCalla0296f72010-03-19 07:35:19 +00003661 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00003662 Initializer, DestType, CandidateSet,
3663 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003664 }
3665 }
3666 }
John McCall3696dcb2010-08-17 07:23:57 +00003667 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3668 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003669
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003670 SourceLocation DeclLoc = Initializer->getLocStart();
3671
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003672 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003673 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003674 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003675 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003676 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003677
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003678 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00003679 // This is the overload that will be used for this initialization step if we
3680 // use this initialization. Mark it as referenced.
3681 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00003682
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003683 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003684 if (isa<CXXConversionDecl>(Function))
Alp Toker314cc812014-01-25 16:55:45 +00003685 T2 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003686 else
3687 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003688
3689 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003690 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003691 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003692 T2.getNonLValueExprType(S.Context),
3693 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003694
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003695 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003696 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003697 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003698 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003699 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003700 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003701 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003702
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003703 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003704 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003705 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003706 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003707 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003708 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003709 NewDerivedToBase, NewObjCConversion,
3710 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003711 if (NewRefRelationship == Sema::Ref_Incompatible) {
3712 // If the type we've converted to is not reference-related to the
3713 // type we're looking for, then there is another conversion step
3714 // we need to perform to produce a temporary of the right type
3715 // that we'll be binding to.
3716 ImplicitConversionSequence ICS;
3717 ICS.setStandard();
3718 ICS.Standard = Best->FinalConversion;
3719 T2 = ICS.Standard.getToType(2);
3720 Sequence.AddConversionSequenceStep(ICS, T2);
3721 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003722 Sequence.AddDerivedToBaseCastStep(
3723 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003724 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003725 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003726 else if (NewObjCConversion)
3727 Sequence.AddObjCObjectConversionStep(
3728 S.Context.getQualifiedType(T1,
3729 T2.getNonReferenceType().getQualifiers()));
3730
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003731 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003732 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003733
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003734 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3735 return OR_Success;
3736}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003737
Richard Smithc620f552011-10-19 16:55:56 +00003738static void CheckCXX98CompatAccessibleCopy(Sema &S,
3739 const InitializedEntity &Entity,
3740 Expr *CurInitExpr);
3741
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003742/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3743static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003744 const InitializedEntity &Entity,
3745 const InitializationKind &Kind,
3746 Expr *Initializer,
3747 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003748 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003749 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003750 Qualifiers T1Quals;
3751 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003752 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003753 Qualifiers T2Quals;
3754 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003755
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003756 // If the initializer is the address of an overloaded function, try
3757 // to resolve the overloaded function. If all goes well, T2 is the
3758 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003759 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3760 T1, Sequence))
3761 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003762
Sebastian Redl29526f02011-11-27 16:50:07 +00003763 // Delegate everything else to a subfunction.
3764 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3765 T1Quals, cv2T2, T2, T2Quals, Sequence);
3766}
3767
Jordan Roseb1312a52013-04-11 00:58:58 +00003768/// Converts the target of reference initialization so that it has the
3769/// appropriate qualifiers and value kind.
3770///
3771/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3772/// \code
3773/// int x;
3774/// const int &r = x;
3775/// \endcode
3776///
3777/// In this case the reference is binding to a bitfield lvalue, which isn't
3778/// valid. Perform a load to create a lifetime-extended temporary instead.
3779/// \code
3780/// const int &r = someStruct.bitfield;
3781/// \endcode
3782static ExprValueKind
3783convertQualifiersAndValueKindIfNecessary(Sema &S,
3784 InitializationSequence &Sequence,
3785 Expr *Initializer,
3786 QualType cv1T1,
3787 Qualifiers T1Quals,
3788 Qualifiers T2Quals,
3789 bool IsLValueRef) {
John McCalld25db7e2013-05-06 21:39:12 +00003790 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Roseb1312a52013-04-11 00:58:58 +00003791 Initializer->refersToVectorElement();
3792
3793 if (IsNonAddressableType) {
3794 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3795 // lvalue reference to a non-volatile const type, or the reference shall be
3796 // an rvalue reference.
3797 //
3798 // If not, we can't make a temporary and bind to that. Give up and allow the
3799 // error to be diagnosed later.
3800 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3801 assert(Initializer->isGLValue());
3802 return Initializer->getValueKind();
3803 }
3804
3805 // Force a load so we can materialize a temporary.
3806 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3807 return VK_RValue;
3808 }
3809
3810 if (T1Quals != T2Quals) {
3811 Sequence.AddQualificationConversionStep(cv1T1,
3812 Initializer->getValueKind());
3813 }
3814
3815 return Initializer->getValueKind();
3816}
3817
3818
Sebastian Redl29526f02011-11-27 16:50:07 +00003819/// \brief Reference initialization without resolving overloaded functions.
3820static void TryReferenceInitializationCore(Sema &S,
3821 const InitializedEntity &Entity,
3822 const InitializationKind &Kind,
3823 Expr *Initializer,
3824 QualType cv1T1, QualType T1,
3825 Qualifiers T1Quals,
3826 QualType cv2T2, QualType T2,
3827 Qualifiers T2Quals,
3828 InitializationSequence &Sequence) {
3829 QualType DestType = Entity.getType();
3830 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003831 // Compute some basic properties of the types and the initializer.
3832 bool isLValueRef = DestType->isLValueReferenceType();
3833 bool isRValueRef = !isLValueRef;
3834 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003835 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003836 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003837 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003838 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003839 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003840 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003841
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003842 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003843 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003844 // "cv2 T2" as follows:
3845 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003846 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003847 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00003848 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00003849 // there are no function rvalues in C++, rvalue refs to functions are treated
3850 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003851 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003852 bool T1Function = T1->isFunctionType();
3853 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003854 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003855 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003856 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003857 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003858 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003859 // reference-compatible with "cv2 T2," or
3860 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003861 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003862 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003863 // can occur. However, we do pay attention to whether it is a bit-field
3864 // to decide whether we're actually binding to a temporary created from
3865 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003866 if (DerivedToBase)
3867 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003868 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003869 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003870 else if (ObjCConversion)
3871 Sequence.AddObjCObjectConversionStep(
3872 S.Context.getQualifiedType(T1, T2Quals));
3873
Jordan Roseb1312a52013-04-11 00:58:58 +00003874 ExprValueKind ValueKind =
3875 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3876 cv1T1, T1Quals, T2Quals,
3877 isLValueRef);
3878 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003879 return;
3880 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003881
3882 // - has a class type (i.e., T2 is a class type), where T1 is not
3883 // reference-related to T2, and can be implicitly converted to an
3884 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3885 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003886 // applicable conversion functions (13.3.1.6) and choosing the best
3887 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003888 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00003889 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00003890 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3891 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003892 ConvOvlResult = TryRefInitWithConversionFunction(
3893 S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003894 if (ConvOvlResult == OR_Success)
3895 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00003896 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00003897 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003898 InitializationSequence::FK_ReferenceInitOverloadFailed,
3899 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003900 }
3901 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003902
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003903 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003904 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003905 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003906 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003907 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3908 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3909 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003910 Sequence.SetOverloadFailure(
3911 InitializationSequence::FK_ReferenceInitOverloadFailed,
3912 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003913 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003914 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003915 ? (RefRelationship == Sema::Ref_Related
3916 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3917 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3918 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003919
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003920 return;
3921 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003922
Douglas Gregor92e460e2011-01-20 16:44:54 +00003923 // - If the initializer expression
3924 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3925 // "cv1 T1" is reference-compatible with "cv2 T2"
3926 // Note: functions are handled below.
3927 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003928 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003929 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003930 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003931 (InitCategory.isXValue() ||
3932 (InitCategory.isPRValue() && T2->isRecordType()) ||
3933 (InitCategory.isPRValue() && T2->isArrayType()))) {
3934 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3935 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003936 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3937 // compiler the freedom to perform a copy here or bind to the
3938 // object, while C++0x requires that we bind directly to the
3939 // object. Hence, we always bind to the object without making an
3940 // extra copy. However, in C++03 requires that we check for the
3941 // presence of a suitable copy constructor:
3942 //
3943 // The constructor that would be used to make the copy shall
3944 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003945 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003946 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003947 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00003948 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003949 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003950
Douglas Gregor92e460e2011-01-20 16:44:54 +00003951 if (DerivedToBase)
3952 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3953 ValueKind);
3954 else if (ObjCConversion)
3955 Sequence.AddObjCObjectConversionStep(
3956 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003957
Jordan Roseb1312a52013-04-11 00:58:58 +00003958 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3959 Initializer, cv1T1,
3960 T1Quals, T2Quals,
3961 isLValueRef);
3962
3963 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003964 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003965 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003966
3967 // - has a class type (i.e., T2 is a class type), where T1 is not
3968 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003969 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3970 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00003971 //
3972 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00003973 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003974 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003975 ConvOvlResult = TryRefInitWithConversionFunction(
3976 S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003977 if (ConvOvlResult)
3978 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003979 InitializationSequence::FK_ReferenceInitOverloadFailed,
3980 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003981
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003982 return;
3983 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003984
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00003985 if ((RefRelationship == Sema::Ref_Compatible ||
3986 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3987 isRValueRef && InitCategory.isLValue()) {
3988 Sequence.SetFailed(
3989 InitializationSequence::FK_RValueReferenceBindingToLValue);
3990 return;
3991 }
3992
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003993 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3994 return;
3995 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003996
3997 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003998 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00003999 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004000 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00004001
John McCallec6f4e92010-06-04 02:29:22 +00004002 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4003
Richard Smith2eabf782013-06-13 00:57:57 +00004004 // FIXME: Why do we use an implicit conversion here rather than trying
4005 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00004006 ImplicitConversionSequence ICS
4007 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00004008 /*SuppressUserConversions=*/false,
4009 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004010 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004011 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4012 /*AllowObjCWritebackConversion=*/false);
4013
4014 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004015 // FIXME: Use the conversion function set stored in ICS to turn
4016 // this into an overloading ambiguity diagnostic. However, we need
4017 // to keep that set as an OverloadCandidateSet rather than as some
4018 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004019 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4020 Sequence.SetOverloadFailure(
4021 InitializationSequence::FK_ReferenceInitOverloadFailed,
4022 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004023 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4024 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004025 else
4026 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004027 return;
John McCall31168b02011-06-15 23:02:42 +00004028 } else {
4029 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004030 }
4031
4032 // [...] If T1 is reference-related to T2, cv1 must be the
4033 // same cv-qualification as, or greater cv-qualification
4034 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004035 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4036 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004037 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00004038 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004039 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4040 return;
4041 }
4042
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004043 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004044 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004045 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004046 InitCategory.isLValue()) {
4047 Sequence.SetFailed(
4048 InitializationSequence::FK_RValueReferenceBindingToLValue);
4049 return;
4050 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004051
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004052 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4053 return;
4054}
4055
4056/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004057/// (C++ [dcl.init.string], C99 6.7.8).
4058static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004059 const InitializedEntity &Entity,
4060 const InitializationKind &Kind,
4061 Expr *Initializer,
4062 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004063 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004064}
4065
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004066/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004067static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004068 const InitializedEntity &Entity,
4069 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004070 InitializationSequence &Sequence,
4071 InitListExpr *InitList) {
4072 assert((!InitList || InitList->getNumInits() == 0) &&
4073 "Shouldn't use value-init for non-empty init lists");
4074
Richard Smith1bfe0682012-02-14 21:14:13 +00004075 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004076 //
4077 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004078 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004079
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004080 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004081 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004082
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004083 if (const RecordType *RT = T->getAs<RecordType>()) {
4084 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004085 bool NeedZeroInitialization = true;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004086 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithd86812d2012-07-05 08:39:21 +00004087 // C++98:
4088 // -- if T is a class type (clause 9) with a user-declared constructor
4089 // (12.1), then the default constructor for T is called (and the
4090 // initialization is ill-formed if T has no accessible default
4091 // constructor);
Richard Smith1bfe0682012-02-14 21:14:13 +00004092 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithd86812d2012-07-05 08:39:21 +00004093 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00004094 } else {
4095 // C++11:
4096 // -- if T is a class type (clause 9) with either no default constructor
4097 // (12.1 [class.ctor]) or a default constructor that is user-provided
4098 // or deleted, then the object is default-initialized;
4099 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4100 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithd86812d2012-07-05 08:39:21 +00004101 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00004102 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004103
Richard Smith1bfe0682012-02-14 21:14:13 +00004104 // -- if T is a (possibly cv-qualified) non-union class type without a
4105 // user-provided or deleted default constructor, then the object is
4106 // zero-initialized and, if T has a non-trivial default constructor,
4107 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004108 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4109 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004110 if (NeedZeroInitialization)
4111 Sequence.AddZeroInitializationStep(Entity.getType());
4112
Richard Smith593f9932012-12-08 02:01:17 +00004113 // C++03:
4114 // -- if T is a non-union class type without a user-declared constructor,
4115 // then every non-static data member and base class component of T is
4116 // value-initialized;
4117 // [...] A program that calls for [...] value-initialization of an
4118 // entity of reference type is ill-formed.
4119 //
4120 // C++11 doesn't need this handling, because value-initialization does not
4121 // occur recursively there, and the implicit default constructor is
4122 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004123 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004124 ClassDecl->hasUninitializedReferenceMember()) {
4125 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4126 return;
4127 }
4128
Richard Smithd86812d2012-07-05 08:39:21 +00004129 // If this is list-value-initialization, pass the empty init list on when
4130 // building the constructor call. This affects the semantics of a few
4131 // things (such as whether an explicit default constructor can be called).
4132 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004133 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004134 bool InitListSyntax = InitList;
4135
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004136 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4137 InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004138 }
4139 }
4140
Douglas Gregor1b303932009-12-22 15:35:07 +00004141 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004142}
4143
Douglas Gregor85dabae2009-12-16 01:38:02 +00004144/// \brief Attempt default initialization (C++ [dcl.init]p6).
4145static void TryDefaultInitialization(Sema &S,
4146 const InitializedEntity &Entity,
4147 const InitializationKind &Kind,
4148 InitializationSequence &Sequence) {
4149 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004150
Douglas Gregor85dabae2009-12-16 01:38:02 +00004151 // C++ [dcl.init]p6:
4152 // To default-initialize an object of type T means:
4153 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004154 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4155
Douglas Gregor85dabae2009-12-16 01:38:02 +00004156 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4157 // constructor for T is called (and the initialization is ill-formed if
4158 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004159 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004160 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004161 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004162 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004163
Douglas Gregor85dabae2009-12-16 01:38:02 +00004164 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004165
Douglas Gregor85dabae2009-12-16 01:38:02 +00004166 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004167 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004168 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004169 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004170 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004171 return;
4172 }
4173
4174 // If the destination type has a lifetime property, zero-initialize it.
4175 if (DestType.getQualifiers().hasObjCLifetime()) {
4176 Sequence.AddZeroInitializationStep(Entity.getType());
4177 return;
4178 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004179}
4180
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004181/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4182/// which enumerates all conversion functions and performs overload resolution
4183/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004184static void TryUserDefinedConversion(Sema &S,
Richard Smith77be48a2014-07-31 06:31:19 +00004185 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004186 const InitializationKind &Kind,
4187 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004188 InitializationSequence &Sequence,
4189 bool TopLevelOfInitList) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004190 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4191 QualType SourceType = Initializer->getType();
4192 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4193 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004194
Douglas Gregor540c3b02009-12-14 17:27:33 +00004195 // Build the candidate set directly in the initialization sequence
4196 // structure, so that it will persist if we fail.
4197 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4198 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004199
Douglas Gregor540c3b02009-12-14 17:27:33 +00004200 // Determine whether we are allowed to call explicit constructors or
4201 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004202 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004203
Douglas Gregor540c3b02009-12-14 17:27:33 +00004204 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4205 // The type we're converting to is a class type. Enumerate its constructors
4206 // to see if there is a suitable conversion.
4207 CXXRecordDecl *DestRecordDecl
4208 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004209
Douglas Gregord9848152010-04-26 14:36:57 +00004210 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004211 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004212 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie12be6392012-10-18 16:57:32 +00004213 // The container holding the constructors can under certain conditions
4214 // be changed while iterating. To be safe we copy the lookup results
4215 // to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004216 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004217 for (SmallVectorImpl<NamedDecl *>::iterator
David Blaikie12be6392012-10-18 16:57:32 +00004218 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregord9848152010-04-26 14:36:57 +00004219 Con != ConEnd; ++Con) {
4220 NamedDecl *D = *Con;
4221 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004222
Douglas Gregord9848152010-04-26 14:36:57 +00004223 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00004224 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregord9848152010-04-26 14:36:57 +00004225 FunctionTemplateDecl *ConstructorTmpl
4226 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004227 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00004228 Constructor = cast<CXXConstructorDecl>(
4229 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00004230 else
Douglas Gregord9848152010-04-26 14:36:57 +00004231 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004232
Douglas Gregord9848152010-04-26 14:36:57 +00004233 if (!Constructor->isInvalidDecl() &&
4234 Constructor->isConvertingConstructor(AllowExplicit)) {
4235 if (ConstructorTmpl)
4236 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004237 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004238 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004239 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004240 else
4241 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004242 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004243 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004244 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004245 }
Douglas Gregord9848152010-04-26 14:36:57 +00004246 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004247 }
Eli Friedman78275202009-12-19 08:11:05 +00004248
4249 SourceLocation DeclLoc = Initializer->getLocStart();
4250
Douglas Gregor540c3b02009-12-14 17:27:33 +00004251 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4252 // The type we're converting from is a class type, enumerate its conversion
4253 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004254
Eli Friedman4afe9a32009-12-20 22:12:03 +00004255 // We can only enumerate the conversion functions for a complete type; if
4256 // the type isn't complete, simply skip this step.
4257 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4258 CXXRecordDecl *SourceRecordDecl
4259 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004260
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004261 std::pair<CXXRecordDecl::conversion_iterator,
4262 CXXRecordDecl::conversion_iterator>
4263 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4264 for (CXXRecordDecl::conversion_iterator
4265 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004266 NamedDecl *D = *I;
4267 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4268 if (isa<UsingShadowDecl>(D))
4269 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004270
Eli Friedman4afe9a32009-12-20 22:12:03 +00004271 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4272 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004273 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004274 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004275 else
John McCallda4458e2010-03-31 01:36:47 +00004276 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004277
Eli Friedman4afe9a32009-12-20 22:12:03 +00004278 if (AllowExplicit || !Conv->isExplicit()) {
4279 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004280 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004281 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004282 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004283 else
John McCalla0296f72010-03-19 07:35:19 +00004284 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004285 Initializer, DestType, CandidateSet,
4286 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004287 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004288 }
4289 }
4290 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004291
4292 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004293 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004294 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00004295 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004296 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004297 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004298 Result);
4299 return;
4300 }
John McCall0d1da222010-01-12 00:44:57 +00004301
Douglas Gregor540c3b02009-12-14 17:27:33 +00004302 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004303 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004304 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004305
Douglas Gregor540c3b02009-12-14 17:27:33 +00004306 if (isa<CXXConstructorDecl>(Function)) {
4307 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004308 // subsumed by the initialization. Per DR5, the created temporary is of the
4309 // cv-unqualified type of the destination.
4310 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4311 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004312 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004313 return;
4314 }
4315
4316 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004317 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004318 if (ConvType->getAs<RecordType>()) {
Richard Smithb24f0672012-02-11 19:22:50 +00004319 // If we're converting to a class type, there may be an copy of
Douglas Gregor5ab11652010-04-17 22:01:05 +00004320 // the resulting temporary object (possible to create an object of
4321 // a base class type). That copy is not a separate conversion, so
4322 // we just make a note of the actual destination type (possibly a
4323 // base class of the type returned by the conversion function) and
4324 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004325 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4326 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004327 return;
4328 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004329
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004330 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4331 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004332
Douglas Gregor5ab11652010-04-17 22:01:05 +00004333 // If the conversion following the call to the conversion function
4334 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004335 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4336 Best->FinalConversion.Third) {
4337 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004338 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004339 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004340 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004341 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004342}
4343
Richard Smithf032001b2013-06-20 02:18:31 +00004344/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4345/// a function with a pointer return type contains a 'return false;' statement.
4346/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4347/// code using that header.
4348///
4349/// Work around this by treating 'return false;' as zero-initializing the result
4350/// if it's used in a pointer-returning function in a system header.
4351static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4352 const InitializedEntity &Entity,
4353 const Expr *Init) {
4354 return S.getLangOpts().CPlusPlus11 &&
4355 Entity.getKind() == InitializedEntity::EK_Result &&
4356 Entity.getType()->isPointerType() &&
4357 isa<CXXBoolLiteralExpr>(Init) &&
4358 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4359 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4360}
4361
John McCall31168b02011-06-15 23:02:42 +00004362/// The non-zero enum values here are indexes into diagnostic alternatives.
4363enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4364
4365/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00004366static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004367 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00004368 // Skip parens.
4369 e = e->IgnoreParens();
4370
4371 // Skip address-of nodes.
4372 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4373 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004374 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4375 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004376
4377 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00004378 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4379 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00004380 case CK_Dependent:
4381 case CK_BitCast:
4382 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00004383 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004384 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004385
4386 case CK_ArrayToPointerDecay:
4387 return IIK_nonscalar;
4388
4389 case CK_NullToPointer:
4390 return IIK_okay;
4391
4392 default:
4393 break;
4394 }
4395
4396 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00004397 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004398 // set isWeakAccess to true, to mean that there will be an implicit
4399 // load which requires a cleanup.
4400 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4401 isWeakAccess = true;
4402
John McCall63f84442011-06-27 23:59:58 +00004403 if (!isAddressOf) return IIK_nonlocal;
4404
John McCall113bee02012-03-10 09:33:50 +00004405 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4406 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00004407
4408 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00004409
4410 // If we have a conditional operator, check both sides.
4411 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004412 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4413 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00004414 return iik;
4415
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004416 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004417
4418 // These are never scalar.
4419 } else if (isa<ArraySubscriptExpr>(e)) {
4420 return IIK_nonscalar;
4421
4422 // Otherwise, it needs to be a null pointer constant.
4423 } else {
4424 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4425 ? IIK_okay : IIK_nonlocal);
4426 }
4427
4428 return IIK_nonlocal;
4429}
4430
4431/// Check whether the given expression is a valid operand for an
4432/// indirect copy/restore.
4433static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4434 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004435 bool isWeakAccess = false;
4436 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4437 // If isWeakAccess to true, there will be an implicit
4438 // load which requires a cleanup.
4439 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4440 S.ExprNeedsCleanups = true;
4441
John McCall31168b02011-06-15 23:02:42 +00004442 if (iik == IIK_okay) return;
4443
4444 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4445 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4446 << src->getSourceRange();
4447}
4448
Douglas Gregore2f943b2011-02-22 18:29:51 +00004449/// \brief Determine whether we have compatible array types for the
4450/// purposes of GNU by-copy array initialization.
4451static bool hasCompatibleArrayTypes(ASTContext &Context,
4452 const ArrayType *Dest,
4453 const ArrayType *Source) {
4454 // If the source and destination array types are equivalent, we're
4455 // done.
4456 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4457 return true;
4458
4459 // Make sure that the element types are the same.
4460 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4461 return false;
4462
4463 // The only mismatch we allow is when the destination is an
4464 // incomplete array type and the source is a constant array type.
4465 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4466}
4467
John McCall31168b02011-06-15 23:02:42 +00004468static bool tryObjCWritebackConversion(Sema &S,
4469 InitializationSequence &Sequence,
4470 const InitializedEntity &Entity,
4471 Expr *Initializer) {
4472 bool ArrayDecay = false;
4473 QualType ArgType = Initializer->getType();
4474 QualType ArgPointee;
4475 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4476 ArrayDecay = true;
4477 ArgPointee = ArgArrayType->getElementType();
4478 ArgType = S.Context.getPointerType(ArgPointee);
4479 }
4480
4481 // Handle write-back conversion.
4482 QualType ConvertedArgType;
4483 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4484 ConvertedArgType))
4485 return false;
4486
4487 // We should copy unless we're passing to an argument explicitly
4488 // marked 'out'.
4489 bool ShouldCopy = true;
4490 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4491 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4492
4493 // Do we need an lvalue conversion?
4494 if (ArrayDecay || Initializer->isGLValue()) {
4495 ImplicitConversionSequence ICS;
4496 ICS.setStandard();
4497 ICS.Standard.setAsIdentityConversion();
4498
4499 QualType ResultType;
4500 if (ArrayDecay) {
4501 ICS.Standard.First = ICK_Array_To_Pointer;
4502 ResultType = S.Context.getPointerType(ArgPointee);
4503 } else {
4504 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4505 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4506 }
4507
4508 Sequence.AddConversionSequenceStep(ICS, ResultType);
4509 }
4510
4511 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4512 return true;
4513}
4514
Guy Benyei61054192013-02-07 10:55:47 +00004515static bool TryOCLSamplerInitialization(Sema &S,
4516 InitializationSequence &Sequence,
4517 QualType DestType,
4518 Expr *Initializer) {
4519 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4520 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4521 return false;
4522
4523 Sequence.AddOCLSamplerInitStep(DestType);
4524 return true;
4525}
4526
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004527//
4528// OpenCL 1.2 spec, s6.12.10
4529//
4530// The event argument can also be used to associate the
4531// async_work_group_copy with a previous async copy allowing
4532// an event to be shared by multiple async copies; otherwise
4533// event should be zero.
4534//
4535static bool TryOCLZeroEventInitialization(Sema &S,
4536 InitializationSequence &Sequence,
4537 QualType DestType,
4538 Expr *Initializer) {
4539 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4540 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4541 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4542 return false;
4543
4544 Sequence.AddOCLZeroEventStep(DestType);
4545 return true;
4546}
4547
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004548InitializationSequence::InitializationSequence(Sema &S,
4549 const InitializedEntity &Entity,
4550 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004551 MultiExprArg Args,
4552 bool TopLevelOfInitList)
Richard Smith100b24a2014-04-17 01:52:14 +00004553 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Richard Smith089c3162013-09-21 21:55:46 +00004554 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
4555}
4556
4557void InitializationSequence::InitializeFrom(Sema &S,
4558 const InitializedEntity &Entity,
4559 const InitializationKind &Kind,
4560 MultiExprArg Args,
4561 bool TopLevelOfInitList) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004562 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004563
John McCall5e77d762013-04-16 07:28:30 +00004564 // Eliminate non-overload placeholder types in the arguments. We
4565 // need to do this before checking whether types are dependent
4566 // because lowering a pseudo-object expression might well give us
4567 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004568 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00004569 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4570 // FIXME: should we be doing this here?
4571 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4572 if (result.isInvalid()) {
4573 SetFailed(FK_PlaceholderType);
4574 return;
4575 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004576 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00004577 }
4578
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004579 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004580 // The semantics of initializers are as follows. The destination type is
4581 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004582 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004583 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004584 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004585 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004586
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004587 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004588 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004589 SequenceKind = DependentSequence;
4590 return;
4591 }
4592
Sebastian Redld201edf2011-06-05 13:59:11 +00004593 // Almost everything is a normal sequence.
4594 setSequenceKind(NormalSequence);
4595
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004596 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00004597 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004598 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004599 Initializer = Args[0];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004600 if (S.getLangOpts().ObjC1) {
4601 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
4602 DestType, Initializer->getType(),
4603 Initializer) ||
4604 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
4605 Args[0] = Initializer;
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004606 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004607 if (!isa<InitListExpr>(Initializer))
4608 SourceType = Initializer->getType();
4609 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004610
Sebastian Redl0501c632012-02-12 16:37:36 +00004611 // - If the initializer is a (non-parenthesized) braced-init-list, the
4612 // object is list-initialized (8.5.4).
4613 if (Kind.getKind() != InitializationKind::IK_Direct) {
4614 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4615 TryListInitialization(S, Entity, Kind, InitList, *this);
4616 return;
4617 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004618 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004619
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004620 // - If the destination type is a reference type, see 8.5.3.
4621 if (DestType->isReferenceType()) {
4622 // C++0x [dcl.init.ref]p1:
4623 // A variable declared to be a T& or T&&, that is, "reference to type T"
4624 // (8.3.2), shall be initialized by an object, or function, of type T or
4625 // by an object that can be converted into a T.
4626 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004627 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004628 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004629 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004630 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004631 return;
4632 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004633
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004634 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004635 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004636 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004637 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004638 return;
4639 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004640
Douglas Gregor85dabae2009-12-16 01:38:02 +00004641 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004642 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004643 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004644 return;
4645 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004646
John McCall66884dd2011-02-21 07:22:22 +00004647 // - If the destination type is an array of characters, an array of
4648 // char16_t, an array of char32_t, or an array of wchar_t, and the
4649 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004650 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004651 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004652 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004653 if (Initializer && isa<VariableArrayType>(DestAT)) {
4654 SetFailed(FK_VariableLengthArrayHasInitializer);
4655 return;
4656 }
4657
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004658 if (Initializer) {
4659 switch (IsStringInit(Initializer, DestAT, Context)) {
4660 case SIF_None:
4661 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4662 return;
4663 case SIF_NarrowStringIntoWideChar:
4664 SetFailed(FK_NarrowStringIntoWideCharArray);
4665 return;
4666 case SIF_WideStringIntoChar:
4667 SetFailed(FK_WideStringIntoCharArray);
4668 return;
4669 case SIF_IncompatWideStringIntoWideChar:
4670 SetFailed(FK_IncompatWideStringIntoWideChar);
4671 return;
4672 case SIF_Other:
4673 break;
4674 }
John McCall66884dd2011-02-21 07:22:22 +00004675 }
4676
Douglas Gregore2f943b2011-02-22 18:29:51 +00004677 // Note: as an GNU C extension, we allow initialization of an
4678 // array from a compound literal that creates an array of the same
4679 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004680 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00004681 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4682 Initializer->getType()->isArrayType()) {
4683 const ArrayType *SourceAT
4684 = Context.getAsArrayType(Initializer->getType());
4685 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004686 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004687 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004688 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004689 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004690 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004691 }
Richard Smithebeed412012-02-15 22:38:09 +00004692 }
Richard Smithd86812d2012-07-05 08:39:21 +00004693 // Note: as a GNU C++ extension, we allow list-initialization of a
4694 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004695 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00004696 Entity.getKind() == InitializedEntity::EK_Member &&
4697 Initializer && isa<InitListExpr>(Initializer)) {
4698 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4699 *this);
4700 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004701 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004702 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004703 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4704 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004705 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004706 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004707
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004708 return;
4709 }
Eli Friedman78275202009-12-19 08:11:05 +00004710
John McCall31168b02011-06-15 23:02:42 +00004711 // Determine whether we should consider writeback conversions for
4712 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004713 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004714 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00004715
4716 // We're at the end of the line for C: it's either a write-back conversion
4717 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004718 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004719 // If allowed, check whether this is an Objective-C writeback conversion.
4720 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004721 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004722 return;
4723 }
Guy Benyei61054192013-02-07 10:55:47 +00004724
4725 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4726 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004727
4728 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4729 return;
4730
John McCall31168b02011-06-15 23:02:42 +00004731 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004732 AddCAssignmentStep(DestType);
4733 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004734 return;
4735 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004736
David Blaikiebbafb8a2012-03-11 07:00:24 +00004737 assert(S.getLangOpts().CPlusPlus);
John McCall31168b02011-06-15 23:02:42 +00004738
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004739 // - If the destination type is a (possibly cv-qualified) class type:
4740 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004741 // - If the initialization is direct-initialization, or if it is
4742 // copy-initialization where the cv-unqualified version of the
4743 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004744 // class of the destination, constructors are considered. [...]
4745 if (Kind.getKind() == InitializationKind::IK_Direct ||
4746 (Kind.getKind() == InitializationKind::IK_Copy &&
4747 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4748 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004749 TryConstructorInitialization(S, Entity, Kind, Args,
Richard Smith77be48a2014-07-31 06:31:19 +00004750 DestType, *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004751 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004752 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004753 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004754 // used) to a derived class thereof are enumerated as described in
4755 // 13.3.1.4, and the best one is chosen through overload resolution
4756 // (13.3).
4757 else
Richard Smith77be48a2014-07-31 06:31:19 +00004758 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004759 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004760 return;
4761 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004762
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004763 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004764 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004765 return;
4766 }
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004767 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004768
4769 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004770 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004771 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith77be48a2014-07-31 06:31:19 +00004772 // For a conversion to _Atomic(T) from either T or a class type derived
4773 // from T, initialize the T object then convert to _Atomic type.
4774 bool NeedAtomicConversion = false;
4775 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
4776 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
4777 S.IsDerivedFrom(SourceType, Atomic->getValueType())) {
4778 DestType = Atomic->getValueType();
4779 NeedAtomicConversion = true;
4780 }
4781 }
4782
4783 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004784 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004785 MaybeProduceObjCObject(S, *this, Entity);
Richard Smith77be48a2014-07-31 06:31:19 +00004786 if (!Failed() && NeedAtomicConversion)
4787 AddAtomicConversionStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004788 return;
4789 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004790
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004791 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004792 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004793 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004794 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004795 // destination type; no user-defined conversions are considered.
Richard Smith77be48a2014-07-31 06:31:19 +00004796
John McCall31168b02011-06-15 23:02:42 +00004797 ImplicitConversionSequence ICS
Richard Smith77be48a2014-07-31 06:31:19 +00004798 = S.TryImplicitConversion(Initializer, DestType,
John McCall31168b02011-06-15 23:02:42 +00004799 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004800 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004801 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004802 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4803 allowObjCWritebackConversion);
Richard Smith77be48a2014-07-31 06:31:19 +00004804
4805 if (ICS.isStandard() &&
John McCall31168b02011-06-15 23:02:42 +00004806 ICS.Standard.Second == ICK_Writeback_Conversion) {
4807 // Objective-C ARC writeback conversion.
4808
4809 // We should copy unless we're passing to an argument explicitly
4810 // marked 'out'.
4811 bool ShouldCopy = true;
4812 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4813 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4814
4815 // If there was an lvalue adjustment, add it as a separate conversion.
4816 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4817 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4818 ImplicitConversionSequence LvalueICS;
4819 LvalueICS.setStandard();
4820 LvalueICS.Standard.setAsIdentityConversion();
4821 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4822 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004823 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004824 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004825
Richard Smith77be48a2014-07-31 06:31:19 +00004826 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004827 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004828 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00004829 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4830 AddZeroInitializationStep(Entity.getType());
4831 } else if (Initializer->getType() == Context.OverloadTy &&
4832 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4833 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004834 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004835 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004836 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004837 } else {
Richard Smith77be48a2014-07-31 06:31:19 +00004838 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00004839
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004840 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004841 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004842}
4843
4844InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004845 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004846 StepEnd = Steps.end();
4847 Step != StepEnd; ++Step)
4848 Step->Destroy();
4849}
4850
4851//===----------------------------------------------------------------------===//
4852// Perform initialization
4853//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004854static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004855getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004856 switch(Entity.getKind()) {
4857 case InitializedEntity::EK_Variable:
4858 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004859 case InitializedEntity::EK_Exception:
4860 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004861 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004862 return Sema::AA_Initializing;
4863
4864 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004865 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004866 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4867 return Sema::AA_Sending;
4868
Douglas Gregore1314a62009-12-18 05:02:21 +00004869 return Sema::AA_Passing;
4870
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004871 case InitializedEntity::EK_Parameter_CF_Audited:
4872 if (Entity.getDecl() &&
4873 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4874 return Sema::AA_Sending;
4875
4876 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4877
Douglas Gregore1314a62009-12-18 05:02:21 +00004878 case InitializedEntity::EK_Result:
4879 return Sema::AA_Returning;
4880
Douglas Gregore1314a62009-12-18 05:02:21 +00004881 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00004882 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004883 // FIXME: Can we tell apart casting vs. converting?
4884 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004885
Douglas Gregore1314a62009-12-18 05:02:21 +00004886 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004887 case InitializedEntity::EK_ArrayElement:
4888 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004889 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004890 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004891 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004892 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004893 return Sema::AA_Initializing;
4894 }
4895
David Blaikie8a40f702012-01-17 06:56:22 +00004896 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004897}
4898
Richard Smith27874d62013-01-08 00:08:23 +00004899/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00004900/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004901static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004902 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004903 case InitializedEntity::EK_ArrayElement:
4904 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004905 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004906 case InitializedEntity::EK_New:
4907 case InitializedEntity::EK_Variable:
4908 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004909 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004910 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004911 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004912 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004913 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004914 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004915 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004916 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004917
Douglas Gregore1314a62009-12-18 05:02:21 +00004918 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004919 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00004920 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004921 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004922 return true;
4923 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004924
Douglas Gregore1314a62009-12-18 05:02:21 +00004925 llvm_unreachable("missed an InitializedEntity kind?");
4926}
4927
Douglas Gregor95562572010-04-24 23:45:46 +00004928/// \brief Whether the given entity, when initialized with an object
4929/// created for that initialization, requires destruction.
4930static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4931 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00004932 case InitializedEntity::EK_Result:
4933 case InitializedEntity::EK_New:
4934 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004935 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004936 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004937 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004938 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004939 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00004940 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004941
Richard Smith27874d62013-01-08 00:08:23 +00004942 case InitializedEntity::EK_Member:
Douglas Gregor95562572010-04-24 23:45:46 +00004943 case InitializedEntity::EK_Variable:
4944 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004945 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00004946 case InitializedEntity::EK_Temporary:
4947 case InitializedEntity::EK_ArrayElement:
4948 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004949 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004950 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00004951 return true;
4952 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004953
4954 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004955}
4956
Richard Smithc620f552011-10-19 16:55:56 +00004957/// \brief Look for copy and move constructors and constructor templates, for
4958/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4959static void LookupCopyAndMoveConstructors(Sema &S,
4960 OverloadCandidateSet &CandidateSet,
4961 CXXRecordDecl *Class,
4962 Expr *CurInitExpr) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004963 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004964 // The container holding the constructors can under certain conditions
4965 // be changed while iterating (e.g. because of deserialization).
4966 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004967 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004968 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004969 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4970 NamedDecl *D = *CI;
Craig Topperc3ec1492014-05-26 06:22:03 +00004971 CXXConstructorDecl *Constructor = nullptr;
Richard Smithc620f552011-10-19 16:55:56 +00004972
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004973 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smithc620f552011-10-19 16:55:56 +00004974 // Handle copy/moveconstructors, only.
4975 if (!Constructor || Constructor->isInvalidDecl() ||
4976 !Constructor->isCopyOrMoveConstructor() ||
4977 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4978 continue;
4979
4980 DeclAccessPair FoundDecl
4981 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4982 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004983 CurInitExpr, CandidateSet);
Richard Smithc620f552011-10-19 16:55:56 +00004984 continue;
4985 }
4986
4987 // Handle constructor templates.
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004988 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smithc620f552011-10-19 16:55:56 +00004989 if (ConstructorTmpl->isInvalidDecl())
4990 continue;
4991
4992 Constructor = cast<CXXConstructorDecl>(
4993 ConstructorTmpl->getTemplatedDecl());
4994 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4995 continue;
4996
4997 // FIXME: Do we need to limit this to copy-constructor-like
4998 // candidates?
4999 DeclAccessPair FoundDecl
5000 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
Craig Topperc3ec1492014-05-26 06:22:03 +00005001 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005002 CurInitExpr, CandidateSet, true);
Richard Smithc620f552011-10-19 16:55:56 +00005003 }
5004}
5005
5006/// \brief Get the location at which initialization diagnostics should appear.
5007static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5008 Expr *Initializer) {
5009 switch (Entity.getKind()) {
5010 case InitializedEntity::EK_Result:
5011 return Entity.getReturnLoc();
5012
5013 case InitializedEntity::EK_Exception:
5014 return Entity.getThrowLoc();
5015
5016 case InitializedEntity::EK_Variable:
5017 return Entity.getDecl()->getLocation();
5018
Douglas Gregor19666fb2012-02-15 16:57:26 +00005019 case InitializedEntity::EK_LambdaCapture:
5020 return Entity.getCaptureLoc();
5021
Richard Smithc620f552011-10-19 16:55:56 +00005022 case InitializedEntity::EK_ArrayElement:
5023 case InitializedEntity::EK_Member:
5024 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005025 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00005026 case InitializedEntity::EK_Temporary:
5027 case InitializedEntity::EK_New:
5028 case InitializedEntity::EK_Base:
5029 case InitializedEntity::EK_Delegating:
5030 case InitializedEntity::EK_VectorElement:
5031 case InitializedEntity::EK_ComplexElement:
5032 case InitializedEntity::EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005033 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005034 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00005035 return Initializer->getLocStart();
5036 }
5037 llvm_unreachable("missed an InitializedEntity kind?");
5038}
5039
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005040/// \brief Make a (potentially elidable) temporary copy of the object
5041/// provided by the given initializer by calling the appropriate copy
5042/// constructor.
5043///
5044/// \param S The Sema object used for type-checking.
5045///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005046/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005047/// the type of the initializer expression or a superclass thereof.
5048///
James Dennett634962f2012-06-14 21:40:34 +00005049/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005050///
5051/// \param CurInit The initializer expression.
5052///
5053/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5054/// is permitted in C++03 (but not C++0x) when binding a reference to
5055/// an rvalue.
5056///
5057/// \returns An expression that copies the initializer expression into
5058/// a temporary object, or an error expression if a copy could not be
5059/// created.
John McCalldadc5752010-08-24 06:29:42 +00005060static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005061 QualType T,
5062 const InitializedEntity &Entity,
5063 ExprResult CurInit,
5064 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00005065 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005066 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005067 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005068 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005069 Class = cast<CXXRecordDecl>(Record->getDecl());
5070 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005071 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005072
Douglas Gregor5d369002011-01-21 18:05:27 +00005073 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005074 // When certain criteria are met, an implementation is allowed to
5075 // omit the copy/move construction of a class object, even if the
5076 // copy/move constructor and/or destructor for the object have
5077 // side effects. [...]
5078 // - when a temporary class object that has not been bound to a
5079 // reference (12.2) would be copied/moved to a class object
5080 // with the same cv-unqualified type, the copy/move operation
5081 // can be omitted by constructing the temporary object
5082 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005083 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005084 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00005085 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005086 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00005087 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00005088 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00005089 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005090
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005091 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005092 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005093 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005094
Douglas Gregorf282a762011-01-21 19:38:21 +00005095 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00005096 // Only consider constructors and constructor templates. Per
5097 // C++0x [dcl.init]p16, second bullet to class types, this initialization
5098 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005099 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005100 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005101
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005102 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5103
Douglas Gregore1314a62009-12-18 05:02:21 +00005104 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00005105 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005106 case OR_Success:
5107 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005108
Douglas Gregore1314a62009-12-18 05:02:21 +00005109 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005110 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5111 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5112 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005113 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005114 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005115 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005116 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00005117 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005118 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005119
Douglas Gregore1314a62009-12-18 05:02:21 +00005120 case OR_Ambiguous:
5121 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005122 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005123 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005124 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00005125 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005126
Douglas Gregore1314a62009-12-18 05:02:21 +00005127 case OR_Deleted:
5128 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005129 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005130 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00005131 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00005132 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005133 }
5134
Douglas Gregor5ab11652010-04-17 22:01:05 +00005135 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00005136 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005137 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005138
Anders Carlssona01874b2010-04-21 18:47:17 +00005139 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005140 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005141
5142 if (IsExtraneousCopy) {
5143 // If this is a totally extraneous copy for C++03 reference
5144 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005145 // expression. We don't generate an (elided) copy operation here
5146 // because doing so would require us to pass down a flag to avoid
5147 // infinite recursion, where each step adds another extraneous,
5148 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005149
Douglas Gregor30b52772010-04-18 07:57:34 +00005150 // Instantiate the default arguments of any extra parameters in
5151 // the selected copy constructor, as if we were going to create a
5152 // proper call to the copy constructor.
5153 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5154 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5155 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005156 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005157 break;
5158
5159 // Build the default argument expression; we don't actually care
5160 // if this succeeds or not, because this routine will complain
5161 // if there was a problem.
5162 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5163 }
5164
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005165 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005166 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005167
Douglas Gregor5ab11652010-04-17 22:01:05 +00005168 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005169 // constructor call (we might have derived-to-base conversions, or
5170 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005171 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005172 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005173
Douglas Gregord0ace022010-04-25 00:55:24 +00005174 // Actually perform the constructor call.
5175 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005176 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005177 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005178 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005179 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005180 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005181 CXXConstructExpr::CK_Complete,
5182 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005183
Douglas Gregord0ace022010-04-25 00:55:24 +00005184 // If we're supposed to bind temporaries, do so.
5185 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005186 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005187 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005188}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005189
Richard Smithc620f552011-10-19 16:55:56 +00005190/// \brief Check whether elidable copy construction for binding a reference to
5191/// a temporary would have succeeded if we were building in C++98 mode, for
5192/// -Wc++98-compat.
5193static void CheckCXX98CompatAccessibleCopy(Sema &S,
5194 const InitializedEntity &Entity,
5195 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005196 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005197
5198 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5199 if (!Record)
5200 return;
5201
5202 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005203 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00005204 return;
5205
5206 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00005207 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005208 LookupCopyAndMoveConstructors(
5209 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5210
5211 // Perform overload resolution.
5212 OverloadCandidateSet::iterator Best;
5213 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5214
5215 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5216 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5217 << CurInitExpr->getSourceRange();
5218
5219 switch (OR) {
5220 case OR_Success:
5221 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCall5dadb652012-04-07 03:04:20 +00005222 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005223 // FIXME: Check default arguments as far as that's possible.
5224 break;
5225
5226 case OR_No_Viable_Function:
5227 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005228 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005229 break;
5230
5231 case OR_Ambiguous:
5232 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005233 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005234 break;
5235
5236 case OR_Deleted:
5237 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005238 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005239 break;
5240 }
5241}
5242
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005243void InitializationSequence::PrintInitLocationNote(Sema &S,
5244 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005245 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005246 if (Entity.getDecl()->getLocation().isInvalid())
5247 return;
5248
5249 if (Entity.getDecl()->getDeclName())
5250 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5251 << Entity.getDecl()->getDeclName();
5252 else
5253 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5254 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005255 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5256 Entity.getMethodDecl())
5257 S.Diag(Entity.getMethodDecl()->getLocation(),
5258 diag::note_method_return_type_change)
5259 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005260}
5261
Sebastian Redl112aa822011-07-14 19:07:55 +00005262static bool isReferenceBinding(const InitializationSequence::Step &s) {
5263 return s.Kind == InitializationSequence::SK_BindReference ||
5264 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5265}
5266
Jordan Rose6c0505e2013-05-06 16:48:12 +00005267/// Returns true if the parameters describe a constructor initialization of
5268/// an explicit temporary object, e.g. "Point(x, y)".
5269static bool isExplicitTemporary(const InitializedEntity &Entity,
5270 const InitializationKind &Kind,
5271 unsigned NumArgs) {
5272 switch (Entity.getKind()) {
5273 case InitializedEntity::EK_Temporary:
5274 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005275 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005276 break;
5277 default:
5278 return false;
5279 }
5280
5281 switch (Kind.getKind()) {
5282 case InitializationKind::IK_DirectList:
5283 return true;
5284 // FIXME: Hack to work around cast weirdness.
5285 case InitializationKind::IK_Direct:
5286 case InitializationKind::IK_Value:
5287 return NumArgs != 1;
5288 default:
5289 return false;
5290 }
5291}
5292
Sebastian Redled2e5322011-12-22 14:44:04 +00005293static ExprResult
5294PerformConstructorInitialization(Sema &S,
5295 const InitializedEntity &Entity,
5296 const InitializationKind &Kind,
5297 MultiExprArg Args,
5298 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00005299 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005300 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005301 bool IsStdInitListInitialization,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005302 SourceLocation LBraceLoc,
5303 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005304 unsigned NumArgs = Args.size();
5305 CXXConstructorDecl *Constructor
5306 = cast<CXXConstructorDecl>(Step.Function.Function);
5307 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5308
5309 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005310 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00005311 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5312 ? Kind.getEqualLoc()
5313 : Kind.getLocation();
5314
5315 if (Kind.getKind() == InitializationKind::IK_Default) {
5316 // Force even a trivial, implicit default constructor to be
5317 // semantically checked. We do this explicitly because we don't build
5318 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00005319 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00005320 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00005321 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00005322 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5323 }
5324
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005325 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00005326
Douglas Gregor6073dca2012-02-24 23:56:31 +00005327 // C++ [over.match.copy]p1:
5328 // - When initializing a temporary to be bound to the first parameter
5329 // of a constructor that takes a reference to possibly cv-qualified
5330 // T as its first argument, called with a single argument in the
5331 // context of direct-initialization, explicit conversion functions
5332 // are also considered.
5333 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5334 Args.size() == 1 &&
5335 Constructor->isCopyOrMoveConstructor();
5336
Sebastian Redled2e5322011-12-22 14:44:04 +00005337 // Determine the arguments required to actually perform the constructor
5338 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005339 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005340 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00005341 AllowExplicitConv,
5342 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00005343 return ExprError();
5344
5345
Jordan Rose6c0505e2013-05-06 16:48:12 +00005346 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005347 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedmanfa0df832012-02-02 03:46:19 +00005348 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith22262ab2013-05-04 06:44:46 +00005349 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5350 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005351
5352 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5353 if (!TSInfo)
5354 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005355 SourceRange ParenOrBraceRange =
5356 (Kind.getKind() == InitializationKind::IK_DirectList)
5357 ? SourceRange(LBraceLoc, RBraceLoc)
5358 : Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005359
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005360 CurInit = new (S.Context) CXXTemporaryObjectExpr(
5361 S.Context, Constructor, TSInfo, ConstructorArgs, ParenOrBraceRange,
5362 HadMultipleCandidates, IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005363 IsStdInitListInitialization, ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00005364 } else {
5365 CXXConstructExpr::ConstructionKind ConstructKind =
5366 CXXConstructExpr::CK_Complete;
5367
5368 if (Entity.getKind() == InitializedEntity::EK_Base) {
5369 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5370 CXXConstructExpr::CK_VirtualBase :
5371 CXXConstructExpr::CK_NonVirtualBase;
5372 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5373 ConstructKind = CXXConstructExpr::CK_Delegating;
5374 }
5375
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005376 // Only get the parenthesis or brace range if it is a list initialization or
5377 // direct construction.
5378 SourceRange ParenOrBraceRange;
5379 if (IsListInitialization)
5380 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
5381 else if (Kind.getKind() == InitializationKind::IK_Direct)
5382 ParenOrBraceRange = Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005383
5384 // If the entity allows NRVO, mark the construction as elidable
5385 // unconditionally.
5386 if (Entity.allowsNRVO())
5387 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5388 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005389 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005390 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005391 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005392 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005393 ConstructorInitRequiresZeroInit,
5394 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005395 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005396 else
5397 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5398 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005399 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005400 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005401 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005402 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005403 ConstructorInitRequiresZeroInit,
5404 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005405 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005406 }
5407 if (CurInit.isInvalid())
5408 return ExprError();
5409
5410 // Only check access if all of that succeeded.
5411 S.CheckConstructorAccess(Loc, Constructor, Entity,
5412 Step.Function.FoundDecl.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005413 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5414 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005415
5416 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005417 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00005418
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005419 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00005420}
5421
Richard Smitheb3cad52012-06-04 22:27:30 +00005422/// Determine whether the specified InitializedEntity definitely has a lifetime
5423/// longer than the current full-expression. Conservatively returns false if
5424/// it's unclear.
5425static bool
5426InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5427 const InitializedEntity *Top = &Entity;
5428 while (Top->getParent())
5429 Top = Top->getParent();
5430
5431 switch (Top->getKind()) {
5432 case InitializedEntity::EK_Variable:
5433 case InitializedEntity::EK_Result:
5434 case InitializedEntity::EK_Exception:
5435 case InitializedEntity::EK_Member:
5436 case InitializedEntity::EK_New:
5437 case InitializedEntity::EK_Base:
5438 case InitializedEntity::EK_Delegating:
5439 return true;
5440
5441 case InitializedEntity::EK_ArrayElement:
5442 case InitializedEntity::EK_VectorElement:
5443 case InitializedEntity::EK_BlockElement:
5444 case InitializedEntity::EK_ComplexElement:
5445 // Could not determine what the full initialization is. Assume it might not
5446 // outlive the full-expression.
5447 return false;
5448
5449 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005450 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00005451 case InitializedEntity::EK_Temporary:
5452 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005453 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005454 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00005455 // The entity being initialized might not outlive the full-expression.
5456 return false;
5457 }
5458
5459 llvm_unreachable("unknown entity kind");
5460}
5461
Richard Smithe6c01442013-06-05 00:46:14 +00005462/// Determine the declaration which an initialized entity ultimately refers to,
5463/// for the purpose of lifetime-extending a temporary bound to a reference in
5464/// the initialization of \p Entity.
David Majnemerdaff3702014-05-01 17:50:17 +00005465static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
5466 const InitializedEntity *Entity,
Craig Topperc3ec1492014-05-26 06:22:03 +00005467 const InitializedEntity *FallbackDecl = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00005468 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00005469 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005470 case InitializedEntity::EK_Variable:
5471 // The temporary [...] persists for the lifetime of the reference
David Majnemerdaff3702014-05-01 17:50:17 +00005472 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005473
5474 case InitializedEntity::EK_Member:
5475 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005476 if (Entity->getParent())
5477 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5478 Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00005479
5480 // except:
5481 // -- A temporary bound to a reference member in a constructor's
5482 // ctor-initializer persists until the constructor exits.
David Majnemerdaff3702014-05-01 17:50:17 +00005483 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005484
5485 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005486 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00005487 // -- A temporary bound to a reference parameter in a function call
5488 // persists until the completion of the full-expression containing
5489 // the call.
5490 case InitializedEntity::EK_Result:
5491 // -- The lifetime of a temporary bound to the returned value in a
5492 // function return statement is not extended; the temporary is
5493 // destroyed at the end of the full-expression in the return statement.
5494 case InitializedEntity::EK_New:
5495 // -- A temporary bound to a reference in a new-initializer persists
5496 // until the completion of the full-expression containing the
5497 // new-initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005498 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005499
5500 case InitializedEntity::EK_Temporary:
5501 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005502 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00005503 // We don't yet know the storage duration of the surrounding temporary.
5504 // Assume it's got full-expression duration for now, it will patch up our
5505 // storage duration if that's not correct.
David Majnemerdaff3702014-05-01 17:50:17 +00005506 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005507
5508 case InitializedEntity::EK_ArrayElement:
5509 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005510 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5511 FallbackDecl);
Richard Smithe6c01442013-06-05 00:46:14 +00005512
5513 case InitializedEntity::EK_Base:
5514 case InitializedEntity::EK_Delegating:
5515 // We can reach this case for aggregate initialization in a constructor:
5516 // struct A { int &&r; };
5517 // struct B : A { B() : A{0} {} };
5518 // In this case, use the innermost field decl as the context.
5519 return FallbackDecl;
5520
5521 case InitializedEntity::EK_BlockElement:
5522 case InitializedEntity::EK_LambdaCapture:
5523 case InitializedEntity::EK_Exception:
5524 case InitializedEntity::EK_VectorElement:
5525 case InitializedEntity::EK_ComplexElement:
David Majnemerdaff3702014-05-01 17:50:17 +00005526 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005527 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00005528 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00005529}
5530
David Majnemerdaff3702014-05-01 17:50:17 +00005531static void performLifetimeExtension(Expr *Init,
5532 const InitializedEntity *ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005533
5534/// Update a glvalue expression that is used as the initializer of a reference
5535/// to note that its lifetime is extended.
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005536/// \return \c true if any temporary had its lifetime extended.
David Majnemerdaff3702014-05-01 17:50:17 +00005537static bool
5538performReferenceExtension(Expr *Init,
5539 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00005540 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5541 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5542 // This is just redundant braces around an initializer. Step over it.
5543 Init = ILE->getInit(0);
5544 }
5545 }
5546
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005547 // Walk past any constructs which we can lifetime-extend across.
5548 Expr *Old;
5549 do {
5550 Old = Init;
5551
5552 // Step over any subobject adjustments; we may have a materialized
5553 // temporary inside them.
5554 SmallVector<const Expr *, 2> CommaLHSs;
5555 SmallVector<SubobjectAdjustment, 2> Adjustments;
5556 Init = const_cast<Expr *>(
5557 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5558
5559 // Per current approach for DR1376, look through casts to reference type
5560 // when performing lifetime extension.
5561 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5562 if (CE->getSubExpr()->isGLValue())
5563 Init = CE->getSubExpr();
5564
5565 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5566 // It's unclear if binding a reference to that xvalue extends the array
5567 // temporary.
5568 } while (Init != Old);
5569
Richard Smithe6c01442013-06-05 00:46:14 +00005570 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5571 // Update the storage duration of the materialized temporary.
5572 // FIXME: Rebuild the expression instead of mutating it.
David Majnemerdaff3702014-05-01 17:50:17 +00005573 ME->setExtendingDecl(ExtendingEntity->getDecl(),
5574 ExtendingEntity->allocateManglingNumber());
5575 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005576 return true;
Richard Smithe6c01442013-06-05 00:46:14 +00005577 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005578
5579 return false;
Richard Smithe6c01442013-06-05 00:46:14 +00005580}
5581
5582/// Update a prvalue expression that is going to be materialized as a
5583/// lifetime-extended temporary.
David Majnemerdaff3702014-05-01 17:50:17 +00005584static void performLifetimeExtension(Expr *Init,
5585 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00005586 // Dig out the expression which constructs the extended temporary.
5587 SmallVector<const Expr *, 2> CommaLHSs;
5588 SmallVector<SubobjectAdjustment, 2> Adjustments;
5589 Init = const_cast<Expr *>(
5590 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5591
Richard Smith736a9472013-06-12 20:42:33 +00005592 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5593 Init = BTE->getSubExpr();
5594
Richard Smithcc1b96d2013-06-12 22:31:48 +00005595 if (CXXStdInitializerListExpr *ILE =
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005596 dyn_cast<CXXStdInitializerListExpr>(Init)) {
David Majnemerdaff3702014-05-01 17:50:17 +00005597 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005598 return;
5599 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00005600
Richard Smithe6c01442013-06-05 00:46:14 +00005601 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00005602 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005603 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
David Majnemerdaff3702014-05-01 17:50:17 +00005604 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005605 return;
5606 }
5607
Richard Smithcc1b96d2013-06-12 22:31:48 +00005608 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005609 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5610
5611 // If we lifetime-extend a braced initializer which is initializing an
5612 // aggregate, and that aggregate contains reference members which are
5613 // bound to temporaries, those temporaries are also lifetime-extended.
5614 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5615 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005616 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005617 else {
5618 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005619 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00005620 if (Index >= ILE->getNumInits())
5621 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005622 if (I->isUnnamedBitfield())
5623 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00005624 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00005625 if (I->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005626 performReferenceExtension(SubInit, ExtendingEntity);
Richard Smith8d7f11d2013-06-27 22:54:33 +00005627 else if (isa<InitListExpr>(SubInit) ||
5628 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smithe6c01442013-06-05 00:46:14 +00005629 // This may be either aggregate-initialization of a member or
5630 // initialization of a std::initializer_list object. Either way,
5631 // we should recursively lifetime-extend that initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005632 performLifetimeExtension(SubInit, ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005633 ++Index;
5634 }
5635 }
5636 }
5637 }
5638}
5639
Richard Smithcc1b96d2013-06-12 22:31:48 +00005640static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5641 const Expr *Init, bool IsInitializerList,
5642 const ValueDecl *ExtendingDecl) {
5643 // Warn if a field lifetime-extends a temporary.
5644 if (isa<FieldDecl>(ExtendingDecl)) {
5645 if (IsInitializerList) {
5646 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5647 << /*at end of constructor*/true;
5648 return;
5649 }
5650
5651 bool IsSubobjectMember = false;
5652 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5653 Ent = Ent->getParent()) {
5654 if (Ent->getKind() != InitializedEntity::EK_Base) {
5655 IsSubobjectMember = true;
5656 break;
5657 }
5658 }
5659 S.Diag(Init->getExprLoc(),
5660 diag::warn_bind_ref_member_to_temporary)
5661 << ExtendingDecl << Init->getSourceRange()
5662 << IsSubobjectMember << IsInitializerList;
5663 if (IsSubobjectMember)
5664 S.Diag(ExtendingDecl->getLocation(),
5665 diag::note_ref_subobject_of_member_declared_here);
5666 else
5667 S.Diag(ExtendingDecl->getLocation(),
5668 diag::note_ref_or_ptr_member_declared_here)
5669 << /*is pointer*/false;
5670 }
5671}
5672
Richard Smithaaa0ec42013-09-21 21:19:19 +00005673static void DiagnoseNarrowingInInitList(Sema &S,
5674 const ImplicitConversionSequence &ICS,
5675 QualType PreNarrowingType,
5676 QualType EntityType,
5677 const Expr *PostInit);
5678
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005679ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005680InitializationSequence::Perform(Sema &S,
5681 const InitializedEntity &Entity,
5682 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00005683 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005684 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005685 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005686 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00005687 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005688 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005689
Sebastian Redld201edf2011-06-05 13:59:11 +00005690 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005691 // If the declaration is a non-dependent, incomplete array type
5692 // that has an initializer, then its type will be completed once
5693 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00005694 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00005695 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00005696 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005697 if (const IncompleteArrayType *ArrayT
5698 = S.Context.getAsIncompleteArrayType(DeclType)) {
5699 // FIXME: We don't currently have the ability to accurately
5700 // compute the length of an initializer list without
5701 // performing full type-checking of the initializer list
5702 // (since we have to determine where braces are implicitly
5703 // introduced and such). So, we fall back to making the array
5704 // type a dependently-sized array type with no specified
5705 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005706 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005707 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00005708
Douglas Gregor51e77d52009-12-10 17:56:55 +00005709 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00005710 if (DeclaratorDecl *DD = Entity.getDecl()) {
5711 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5712 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00005713 if (IncompleteArrayTypeLoc ArrayLoc =
5714 TL.getAs<IncompleteArrayTypeLoc>())
5715 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00005716 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00005717 }
5718
5719 *ResultType
5720 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005721 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005722 ArrayT->getSizeModifier(),
5723 ArrayT->getIndexTypeCVRQualifiers(),
5724 Brackets);
5725 }
5726
5727 }
5728 }
Sebastian Redla9351792012-02-11 23:51:47 +00005729 if (Kind.getKind() == InitializationKind::IK_Direct &&
5730 !Kind.isExplicitCast()) {
5731 // Rebuild the ParenListExpr.
5732 SourceRange ParenRange = Kind.getParenRange();
5733 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005734 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00005735 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00005736 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00005737 Kind.isExplicitCast() ||
5738 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005739 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005740 }
5741
Sebastian Redld201edf2011-06-05 13:59:11 +00005742 // No steps means no initialization.
5743 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005744 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005745
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005746 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005747 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005748 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00005749 // Produce a C++98 compatibility warning if we are initializing a reference
5750 // from an initializer list. For parameters, we produce a better warning
5751 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005752 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00005753 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5754 << Init->getSourceRange();
5755 }
5756
Richard Smitheb3cad52012-06-04 22:27:30 +00005757 // Diagnose cases where we initialize a pointer to an array temporary, and the
5758 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005759 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00005760 Entity.getType()->isPointerType() &&
5761 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005762 Expr *Init = Args[0];
Richard Smitheb3cad52012-06-04 22:27:30 +00005763 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5764 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5765 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5766 << Init->getSourceRange();
5767 }
5768
Douglas Gregor1b303932009-12-22 15:35:07 +00005769 QualType DestType = Entity.getType().getNonReferenceType();
5770 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00005771 // the same as Entity.getDecl()->getType() in cases involving type merging,
5772 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00005773 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00005774 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00005775 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005776
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005777 ExprResult CurInit((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005778
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005779 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00005780 // grab the only argument out the Args and place it into the "current"
5781 // initializer.
5782 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005783 case SK_ResolveAddressOfOverloadedFunction:
5784 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005785 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005786 case SK_CastDerivedToBaseLValue:
5787 case SK_BindReference:
5788 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005789 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00005790 case SK_UserConversion:
5791 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005792 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005793 case SK_QualificationConversionRValue:
Richard Smith77be48a2014-07-31 06:31:19 +00005794 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00005795 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005796 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00005797 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00005798 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00005799 case SK_UnwrapInitList:
5800 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00005801 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00005802 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00005803 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00005804 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00005805 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00005806 case SK_PassByIndirectCopyRestore:
5807 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00005808 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005809 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00005810 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005811 case SK_OCLZeroEvent: {
Douglas Gregore1314a62009-12-18 05:02:21 +00005812 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005813 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00005814 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005815 break;
John McCall34376a62010-12-04 03:47:34 +00005816 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005817
Douglas Gregore1314a62009-12-18 05:02:21 +00005818 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00005819 case SK_ConstructorInitializationFromList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00005820 case SK_StdInitializerListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00005821 case SK_ZeroInitialization:
5822 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005823 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005824
5825 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005826 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005827 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005828 for (step_iterator Step = step_begin(), StepEnd = step_end();
5829 Step != StepEnd; ++Step) {
5830 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005831 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005832
John Wiegley01296292011-04-08 18:41:53 +00005833 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005834
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005835 switch (Step->Kind) {
5836 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005837 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005838 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00005839 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00005840 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5841 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005842 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00005843 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00005844 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005845 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005846
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005847 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005848 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005849 case SK_CastDerivedToBaseLValue: {
5850 // We have a derived-to-base cast that produces either an rvalue or an
5851 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005852
John McCallcf142162010-08-07 06:22:56 +00005853 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00005854
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005855 // Casts to inaccessible base classes are allowed with C-style casts.
5856 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5857 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00005858 CurInit.get()->getLocStart(),
5859 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00005860 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00005861 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005862
Douglas Gregor88d292c2010-05-13 16:44:06 +00005863 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5864 QualType T = SourceType;
5865 if (const PointerType *Pointer = T->getAs<PointerType>())
5866 T = Pointer->getPointeeType();
5867 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00005868 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00005869 cast<CXXRecordDecl>(RecordTy->getDecl()));
5870 }
5871
John McCall2536c6d2010-08-25 10:28:54 +00005872 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005873 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005874 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005875 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005876 VK_XValue :
5877 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005878 CurInit =
5879 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
5880 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005881 break;
5882 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005883
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005884 case SK_BindReference:
John McCalld25db7e2013-05-06 21:39:12 +00005885 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5886 if (CurInit.get()->refersToBitField()) {
5887 // We don't necessarily have an unambiguous source bit-field.
5888 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005889 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00005890 << Entity.getType().isVolatileQualified()
John McCalld25db7e2013-05-06 21:39:12 +00005891 << (BitField ? BitField->getDeclName() : DeclarationName())
Craig Topperc3ec1492014-05-26 06:22:03 +00005892 << (BitField != nullptr)
John Wiegley01296292011-04-08 18:41:53 +00005893 << CurInit.get()->getSourceRange();
John McCalld25db7e2013-05-06 21:39:12 +00005894 if (BitField)
5895 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5896
John McCallfaf5fb42010-08-26 23:41:50 +00005897 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005898 }
Anders Carlssona91be642010-01-29 02:47:33 +00005899
John Wiegley01296292011-04-08 18:41:53 +00005900 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00005901 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005902 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5903 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00005904 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005905 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005906 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005907 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005908
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005909 // Reference binding does not have any corresponding ASTs.
5910
5911 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005912 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005913 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005914
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005915 // Even though we didn't materialize a temporary, the binding may still
5916 // extend the lifetime of a temporary. This happens if we bind a reference
5917 // to the result of a cast to reference type.
David Majnemerdaff3702014-05-01 17:50:17 +00005918 if (const InitializedEntity *ExtendingEntity =
5919 getEntityForTemporaryLifetimeExtension(&Entity))
5920 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
5921 warnOnLifetimeExtension(S, Entity, CurInit.get(),
5922 /*IsInitializerList=*/false,
5923 ExtendingEntity->getDecl());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005924
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005925 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005926
Richard Smithe6c01442013-06-05 00:46:14 +00005927 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00005928 // Make sure the "temporary" is actually an rvalue.
5929 assert(CurInit.get()->isRValue() && "not a temporary");
5930
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005931 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005932 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005933 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005934
Douglas Gregorfe314812011-06-21 17:03:29 +00005935 // Materialize the temporary into memory.
Richard Smith736a9472013-06-12 20:42:33 +00005936 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Richard Smithe6c01442013-06-05 00:46:14 +00005937 Entity.getType().getNonReferenceType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00005938 Entity.getType()->isLValueReferenceType());
5939
5940 // Maybe lifetime-extend the temporary's subobjects to match the
5941 // entity's lifetime.
5942 if (const InitializedEntity *ExtendingEntity =
5943 getEntityForTemporaryLifetimeExtension(&Entity))
5944 if (performReferenceExtension(MTE, ExtendingEntity))
5945 warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false,
5946 ExtendingEntity->getDecl());
Douglas Gregor58df5092011-06-22 16:12:01 +00005947
5948 // If we're binding to an Objective-C object that has lifetime, we
Richard Smith736a9472013-06-12 20:42:33 +00005949 // need cleanups. Likewise if we're extending this temporary to automatic
5950 // storage duration -- we need to register its cleanup during the
5951 // full-expression's cleanups.
5952 if ((S.getLangOpts().ObjCAutoRefCount &&
5953 MTE->getType()->isObjCLifetimeType()) ||
5954 (MTE->getStorageDuration() == SD_Automatic &&
5955 MTE->getType().isDestructedType()))
Douglas Gregor58df5092011-06-22 16:12:01 +00005956 S.ExprNeedsCleanups = true;
Richard Smith736a9472013-06-12 20:42:33 +00005957
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005958 CurInit = MTE;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005959 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005960 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005961
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005962 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005963 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005964 /*IsExtraneousCopy=*/true);
5965 break;
5966
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005967 case SK_UserConversion: {
5968 // We have a user-defined conversion that invokes either a constructor
5969 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00005970 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00005971 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00005972 FunctionDecl *Fn = Step->Function.Function;
5973 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005974 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00005975 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00005976 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005977 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005978 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00005979 SourceLocation Loc = CurInit.get()->getLocStart();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005980 CurInit.get(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00005981
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005982 // Determine the arguments required to actually perform the constructor
5983 // call.
John Wiegley01296292011-04-08 18:41:53 +00005984 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005985 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00005986 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005987 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005988 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005989
Richard Smithb24f0672012-02-11 19:22:50 +00005990 // Build an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005991 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005992 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005993 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005994 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005995 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005996 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005997 CXXConstructExpr::CK_Complete,
5998 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005999 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006000 return ExprError();
John McCall760af172010-02-01 03:16:54 +00006001
Anders Carlssona01874b2010-04-21 18:47:17 +00006002 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00006003 FoundFn.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00006004 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6005 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006006
John McCalle3027922010-08-25 11:45:40 +00006007 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00006008 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
6009 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
6010 S.IsDerivedFrom(SourceType, Class))
6011 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006012
Douglas Gregor95562572010-04-24 23:45:46 +00006013 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006014 } else {
6015 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00006016 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00006017 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00006018 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00006019 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6020 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006021
6022 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006023 // derived-to-base conversion? I believe the answer is "no", because
6024 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00006025 ExprResult CurInitExprRes =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006026 S.PerformObjectArgumentInitialization(CurInit.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006027 /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006028 FoundFn, Conversion);
6029 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006030 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006031 CurInit = CurInitExprRes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006032
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006033 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006034 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
6035 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006036 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00006037 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006038
John McCalle3027922010-08-25 11:45:40 +00006039 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006040
Alp Toker314cc812014-01-25 16:55:45 +00006041 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006042 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006043
Sebastian Redl112aa822011-07-14 19:07:55 +00006044 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006045 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
6046
6047 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00006048 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00006049 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006050 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00006051 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00006052 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00006053 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00006054 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00006055 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6056 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00006057 }
6058 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006059
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006060 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6061 CastKind, CurInit.get(), nullptr,
6062 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006063 if (MaybeBindToTemp)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006064 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00006065 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006066 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006067 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006068 break;
6069 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006070
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006071 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006072 case SK_QualificationConversionXValue:
6073 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006074 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00006075 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006076 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006077 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006078 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006079 VK_XValue :
6080 VK_RValue);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006081 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006082 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006083 }
6084
Richard Smith77be48a2014-07-31 06:31:19 +00006085 case SK_AtomicConversion: {
6086 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
6087 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6088 CK_NonAtomicToAtomic, VK_RValue);
6089 break;
6090 }
6091
Jordan Roseb1312a52013-04-11 00:58:58 +00006092 case SK_LValueToRValue: {
6093 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006094 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
6095 CK_LValueToRValue, CurInit.get(),
6096 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00006097 break;
6098 }
6099
Richard Smithaaa0ec42013-09-21 21:19:19 +00006100 case SK_ConversionSequence:
6101 case SK_ConversionSequenceNoNarrowing: {
6102 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00006103 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
6104 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00006105 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00006106 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00006107 ExprResult CurInitExprRes =
6108 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00006109 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00006110 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006111 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006112 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00006113
6114 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
6115 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
6116 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
6117 CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006118 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00006119 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006120
Douglas Gregor51e77d52009-12-10 17:56:55 +00006121 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00006122 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006123 // If we're not initializing the top-level entity, we need to create an
6124 // InitializeTemporary entity for our target type.
6125 QualType Ty = Step->Type;
6126 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00006127 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00006128 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
6129 InitListChecker PerformInitList(S, InitEntity,
Richard Smithde229232013-06-06 11:41:05 +00006130 InitList, Ty, /*VerifyOnly=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006131 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00006132 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00006133
Richard Smithcc1b96d2013-06-12 22:31:48 +00006134 // Hack: We must update *ResultType if available in order to set the
6135 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
6136 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
6137 if (ResultType &&
6138 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00006139 if ((*ResultType)->isRValueReferenceType())
6140 Ty = S.Context.getRValueReferenceType(Ty);
6141 else if ((*ResultType)->isLValueReferenceType())
6142 Ty = S.Context.getLValueReferenceType(Ty,
6143 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
6144 *ResultType = Ty;
6145 }
6146
6147 InitListExpr *StructuredInitList =
6148 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006149 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00006150 CurInit = shouldBindAsTemporary(InitEntity)
6151 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006152 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006153 break;
6154 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006155
Richard Smith53324112014-07-16 21:33:43 +00006156 case SK_ConstructorInitializationFromList: {
Sebastian Redl5a41f682012-02-12 16:37:24 +00006157 // When an initializer list is passed for a parameter of type "reference
6158 // to object", we don't get an EK_Temporary entity, but instead an
6159 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00006160 // FIXME: This is a hack. What we really should do is create a user
6161 // conversion step for this case, but this makes it considerably more
6162 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00006163 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6164 Entity.getType().getNonReferenceType());
6165 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00006166 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006167 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00006168 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6169 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006170 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00006171 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6172 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006173 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006174 ConstructorInitRequiresZeroInit,
Richard Smith53324112014-07-16 21:33:43 +00006175 /*IsListInitialization*/true,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006176 /*IsStdInitListInit*/false,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006177 InitList->getLBraceLoc(),
6178 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00006179 break;
6180 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006181
Sebastian Redl29526f02011-11-27 16:50:07 +00006182 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006183 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00006184 break;
6185
6186 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006187 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00006188 InitListExpr *Syntactic = Step->WrappingSyntacticList;
6189 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00006190 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00006191 ILE->setSyntacticForm(Syntactic);
6192 ILE->setType(E->getType());
6193 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006194 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00006195 break;
6196 }
6197
Richard Smith53324112014-07-16 21:33:43 +00006198 case SK_ConstructorInitialization:
Richard Smithf8adcdc2014-07-17 05:12:35 +00006199 case SK_StdInitializerListConstructorCall: {
Sebastian Redl99f66162012-02-19 12:27:56 +00006200 // When an initializer list is passed for a parameter of type "reference
6201 // to object", we don't get an EK_Temporary entity, but instead an
6202 // EK_Parameter entity with reference type.
6203 // FIXME: This is a hack. What we really should do is create a user
6204 // conversion step for this case, but this makes it considerably more
6205 // complicated. For now, this will do.
6206 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6207 Entity.getType().getNonReferenceType());
6208 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf8adcdc2014-07-17 05:12:35 +00006209 bool IsStdInitListInit =
6210 Step->Kind == SK_StdInitializerListConstructorCall;
Richard Smith53324112014-07-16 21:33:43 +00006211 CurInit = PerformConstructorInitialization(
6212 S, UseTemporary ? TempEntity : Entity, Kind, Args, *Step,
6213 ConstructorInitRequiresZeroInit,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006214 /*IsListInitialization*/IsStdInitListInit,
6215 /*IsStdInitListInitialization*/IsStdInitListInit,
Richard Smith53324112014-07-16 21:33:43 +00006216 /*LBraceLoc*/SourceLocation(),
6217 /*RBraceLoc*/SourceLocation());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006218 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00006219 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006220
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006221 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006222 step_iterator NextStep = Step;
6223 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006224 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00006225 (NextStep->Kind == SK_ConstructorInitialization ||
Richard Smith53324112014-07-16 21:33:43 +00006226 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006227 // The need for zero-initialization is recorded directly into
6228 // the call to the object's constructor within the next step.
6229 ConstructorInitRequiresZeroInit = true;
6230 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006231 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006232 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00006233 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6234 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006235 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00006236 Kind.getRange().getBegin());
6237
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006238 CurInit = new (S.Context) CXXScalarValueInitExpr(
6239 TSInfo->getType().getNonLValueExprType(S.Context), TSInfo,
6240 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006241 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006242 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006243 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006244 break;
6245 }
Douglas Gregore1314a62009-12-18 05:02:21 +00006246
6247 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00006248 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006249 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00006250 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00006251 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6252 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00006253 if (Result.isInvalid())
6254 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006255 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00006256
6257 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006258 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00006259 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006260 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00006261 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00006262 == Sema::Compatible)
6263 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00006264 if (CurInitExprRes.isInvalid())
6265 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006266 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00006267
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006268 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00006269 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6270 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00006271 CurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00006272 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006273 &Complained)) {
6274 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00006275 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006276 } else if (Complained)
6277 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00006278 break;
6279 }
Eli Friedman78275202009-12-19 08:11:05 +00006280
6281 case SK_StringInit: {
6282 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00006283 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00006284 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00006285 break;
6286 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006287
6288 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006289 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00006290 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00006291 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006292 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006293
6294 case SK_ArrayInit:
6295 // Okay: we checked everything before creating this step. Note that
6296 // this is a GNU extension.
6297 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00006298 << Step->Type << CurInit.get()->getType()
6299 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00006300
6301 // If the destination type is an incomplete array type, update the
6302 // type accordingly.
6303 if (ResultType) {
6304 if (const IncompleteArrayType *IncompleteDest
6305 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6306 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00006307 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00006308 *ResultType = S.Context.getConstantArrayType(
6309 IncompleteDest->getElementType(),
6310 ConstantSource->getSize(),
6311 ArrayType::Normal, 0);
6312 }
6313 }
6314 }
John McCall31168b02011-06-15 23:02:42 +00006315 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006316
Richard Smithebeed412012-02-15 22:38:09 +00006317 case SK_ParenthesizedArrayInit:
6318 // Okay: we checked everything before creating this step. Note that
6319 // this is a GNU extension.
6320 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6321 << CurInit.get()->getSourceRange();
6322 break;
6323
John McCall31168b02011-06-15 23:02:42 +00006324 case SK_PassByIndirectCopyRestore:
6325 case SK_PassByIndirectRestore:
6326 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006327 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
6328 CurInit.get(), Step->Type,
6329 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00006330 break;
6331
6332 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006333 CurInit =
6334 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
6335 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00006336 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006337
6338 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006339 S.Diag(CurInit.get()->getExprLoc(),
6340 diag::warn_cxx98_compat_initializer_list_init)
6341 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00006342
Richard Smithcc1b96d2013-06-12 22:31:48 +00006343 // Materialize the temporary into memory.
6344 MaterializeTemporaryExpr *MTE = new (S.Context)
6345 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00006346 /*BoundToLvalueReference=*/false);
6347
6348 // Maybe lifetime-extend the array temporary's subobjects to match the
6349 // entity's lifetime.
6350 if (const InitializedEntity *ExtendingEntity =
6351 getEntityForTemporaryLifetimeExtension(&Entity))
6352 if (performReferenceExtension(MTE, ExtendingEntity))
6353 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6354 /*IsInitializerList=*/true,
6355 ExtendingEntity->getDecl());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006356
6357 // Wrap it in a construction of a std::initializer_list<T>.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006358 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006359
6360 // Bind the result, in case the library has given initializer_list a
6361 // non-trivial destructor.
6362 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006363 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00006364 break;
6365 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006366
Guy Benyei61054192013-02-07 10:55:47 +00006367 case SK_OCLSamplerInit: {
6368 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006369 "Sampler initialization on non-sampler type.");
Guy Benyei61054192013-02-07 10:55:47 +00006370
6371 QualType SourceType = CurInit.get()->getType();
Guy Benyei61054192013-02-07 10:55:47 +00006372
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006373 if (Entity.isParameterKind()) {
Guy Benyei61054192013-02-07 10:55:47 +00006374 if (!SourceType->isSamplerT())
6375 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6376 << SourceType;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006377 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
Guy Benyei61054192013-02-07 10:55:47 +00006378 llvm_unreachable("Invalid EntityKind!");
6379 }
6380
6381 break;
6382 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006383 case SK_OCLZeroEvent: {
6384 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006385 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006386
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006387 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006388 CK_ZeroToOCLEvent,
6389 CurInit.get()->getValueKind());
6390 break;
6391 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006392 }
6393 }
John McCall1f425642010-11-11 03:21:53 +00006394
6395 // Diagnose non-fatal problems with the completed initialization.
6396 if (Entity.getKind() == InitializedEntity::EK_Member &&
6397 cast<FieldDecl>(Entity.getDecl())->isBitField())
6398 S.CheckBitFieldInitialization(Kind.getLocation(),
6399 cast<FieldDecl>(Entity.getDecl()),
6400 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006401
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006402 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006403}
6404
Richard Smith593f9932012-12-08 02:01:17 +00006405/// Somewhere within T there is an uninitialized reference subobject.
6406/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00006407static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6408 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00006409 if (T->isReferenceType()) {
6410 S.Diag(Loc, diag::err_reference_without_init)
6411 << T.getNonReferenceType();
6412 return true;
6413 }
6414
6415 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6416 if (!RD || !RD->hasUninitializedReferenceMember())
6417 return false;
6418
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006419 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00006420 if (FI->isUnnamedBitfield())
6421 continue;
6422
6423 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6424 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6425 return true;
6426 }
6427 }
6428
Aaron Ballman574705e2014-03-13 15:41:46 +00006429 for (const auto &BI : RD->bases()) {
6430 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00006431 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6432 return true;
6433 }
6434 }
6435
6436 return false;
6437}
6438
6439
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006440//===----------------------------------------------------------------------===//
6441// Diagnose initialization failures
6442//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00006443
6444/// Emit notes associated with an initialization that failed due to a
6445/// "simple" conversion failure.
6446static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6447 Expr *op) {
6448 QualType destType = entity.getType();
6449 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6450 op->getType()->isObjCObjectPointerType()) {
6451
6452 // Emit a possible note about the conversion failing because the
6453 // operand is a message send with a related result type.
6454 S.EmitRelatedResultTypeNote(op);
6455
6456 // Emit a possible note about a return failing because we're
6457 // expecting a related result type.
6458 if (entity.getKind() == InitializedEntity::EK_Result)
6459 S.EmitRelatedResultTypeNoteForReturn(destType);
6460 }
6461}
6462
Richard Smith0449aaf2013-11-21 23:30:57 +00006463static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6464 InitListExpr *InitList) {
6465 QualType DestType = Entity.getType();
6466
6467 QualType E;
6468 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6469 QualType ArrayType = S.Context.getConstantArrayType(
6470 E.withConst(),
6471 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6472 InitList->getNumInits()),
6473 clang::ArrayType::Normal, 0);
6474 InitializedEntity HiddenArray =
6475 InitializedEntity::InitializeTemporary(ArrayType);
6476 return diagnoseListInit(S, HiddenArray, InitList);
6477 }
6478
6479 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
6480 /*VerifyOnly=*/false);
6481 assert(DiagnoseInitList.HadError() &&
6482 "Inconsistent init list check result.");
6483}
6484
Nico Weber9386c822014-07-23 05:16:10 +00006485/// Prints a fixit for adding a null initializer for |Entity|. Call this only
6486/// right after emitting a diagnostic.
6487static void maybeEmitZeroInitializationFixit(Sema &S,
6488 InitializationSequence &Sequence,
6489 const InitializedEntity &Entity) {
6490 if (Entity.getKind() != InitializedEntity::EK_Variable)
6491 return;
6492
6493 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
6494 if (VD->getInit() || VD->getLocEnd().isMacroID())
6495 return;
6496
6497 QualType VariableTy = VD->getType().getCanonicalType();
6498 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
6499 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
6500
6501 S.Diag(Loc, diag::note_add_initializer)
6502 << VD << FixItHint::CreateInsertion(Loc, Init);
6503}
6504
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006505bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006506 const InitializedEntity &Entity,
6507 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006508 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006509 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006510 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006511
Douglas Gregor1b303932009-12-22 15:35:07 +00006512 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006513 switch (Failure) {
6514 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006515 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006516 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00006517 // Dig out the reference subobject which is uninitialized and diagnose it.
6518 // If this is value-initialization, this could be nested some way within
6519 // the target type.
6520 assert(Kind.getKind() == InitializationKind::IK_Value ||
6521 DestType->isReferenceType());
6522 bool Diagnosed =
6523 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6524 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6525 (void)Diagnosed;
6526 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006527 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006528 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006529 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006530
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006531 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006532 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006533 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006534 case FK_ArrayNeedsInitListOrStringLiteral:
6535 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6536 break;
6537 case FK_ArrayNeedsInitListOrWideStringLiteral:
6538 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6539 break;
6540 case FK_NarrowStringIntoWideCharArray:
6541 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6542 break;
6543 case FK_WideStringIntoCharArray:
6544 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6545 break;
6546 case FK_IncompatWideStringIntoWideChar:
6547 S.Diag(Kind.getLocation(),
6548 diag::err_array_init_incompat_wide_string_into_wchar);
6549 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006550 case FK_ArrayTypeMismatch:
6551 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00006552 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00006553 (Failure == FK_ArrayTypeMismatch
6554 ? diag::err_array_init_different_type
6555 : diag::err_array_init_non_constant_array))
6556 << DestType.getNonReferenceType()
6557 << Args[0]->getType()
6558 << Args[0]->getSourceRange();
6559 break;
6560
John McCalla59dc2f2012-01-05 00:13:19 +00006561 case FK_VariableLengthArrayHasInitializer:
6562 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6563 << Args[0]->getSourceRange();
6564 break;
6565
John McCall16df1e52010-03-30 21:47:33 +00006566 case FK_AddressOfOverloadFailed: {
6567 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006568 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006569 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00006570 true,
6571 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006572 break;
John McCall16df1e52010-03-30 21:47:33 +00006573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006574
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006575 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00006576 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006577 switch (FailedOverloadResult) {
6578 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00006579 if (Failure == FK_UserConversionOverloadFailed)
6580 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6581 << Args[0]->getType() << DestType
6582 << Args[0]->getSourceRange();
6583 else
6584 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6585 << DestType << Args[0]->getType()
6586 << Args[0]->getSourceRange();
6587
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006588 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006589 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006590
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006591 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00006592 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00006593 DestType.getNonReferenceType(),
6594 diag::err_typecheck_nonviable_condition_incomplete,
6595 Args[0]->getType(), Args[0]->getSourceRange()))
6596 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6597 << Args[0]->getType() << Args[0]->getSourceRange()
6598 << DestType.getNonReferenceType();
6599
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006600 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006601 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006602
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006603 case OR_Deleted: {
6604 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6605 << Args[0]->getType() << DestType.getNonReferenceType()
6606 << Args[0]->getSourceRange();
6607 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006608 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00006609 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6610 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006611 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00006612 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006613 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006614 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006615 }
6616 break;
6617 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006618
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006619 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006620 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006621 }
6622 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006623
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006624 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00006625 if (isa<InitListExpr>(Args[0])) {
6626 S.Diag(Kind.getLocation(),
6627 diag::err_lvalue_reference_bind_to_initlist)
6628 << DestType.getNonReferenceType().isVolatileQualified()
6629 << DestType.getNonReferenceType()
6630 << Args[0]->getSourceRange();
6631 break;
6632 }
6633 // Intentional fallthrough
6634
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006635 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006636 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006637 Failure == FK_NonConstLValueReferenceBindingToTemporary
6638 ? diag::err_lvalue_reference_bind_to_temporary
6639 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00006640 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006641 << DestType.getNonReferenceType()
6642 << Args[0]->getType()
6643 << Args[0]->getSourceRange();
6644 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006645
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006646 case FK_RValueReferenceBindingToLValue:
6647 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00006648 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006649 << Args[0]->getSourceRange();
6650 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006651
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006652 case FK_ReferenceInitDropsQualifiers:
6653 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6654 << DestType.getNonReferenceType()
6655 << Args[0]->getType()
6656 << Args[0]->getSourceRange();
6657 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006658
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006659 case FK_ReferenceInitFailed:
6660 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6661 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00006662 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006663 << Args[0]->getType()
6664 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00006665 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006666 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006667
Douglas Gregorb491ed32011-02-19 21:32:49 +00006668 case FK_ConversionFailed: {
6669 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00006670 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00006671 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006672 << DestType
John McCall086a4642010-11-24 05:12:34 +00006673 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00006674 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006675 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00006676 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6677 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00006678 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00006679 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00006680 }
John Wiegley01296292011-04-08 18:41:53 +00006681
6682 case FK_ConversionFromPropertyFailed:
6683 // No-op. This error has already been reported.
6684 break;
6685
Douglas Gregor51e77d52009-12-10 17:56:55 +00006686 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00006687 SourceRange R;
6688
6689 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00006690 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00006691 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006692 else
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006693 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00006694
Alp Tokerb6cc5922014-05-03 03:45:55 +00006695 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00006696 if (Kind.isCStyleOrFunctionalCast())
6697 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6698 << R;
6699 else
6700 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6701 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006702 break;
6703 }
6704
6705 case FK_ReferenceBindingToInitList:
6706 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6707 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6708 break;
6709
6710 case FK_InitListBadDestinationType:
6711 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6712 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6713 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006714
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006715 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006716 case FK_ConstructorOverloadFailed: {
6717 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006718 if (Args.size())
6719 ArgsRange = SourceRange(Args.front()->getLocStart(),
6720 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006721
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006722 if (Failure == FK_ListConstructorOverloadFailed) {
Nico Weber9709ebf2014-07-08 23:54:25 +00006723 assert(Args.size() == 1 &&
6724 "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006725 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006726 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006727 }
6728
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006729 // FIXME: Using "DestType" for the entity we're printing is probably
6730 // bad.
6731 switch (FailedOverloadResult) {
6732 case OR_Ambiguous:
6733 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6734 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006735 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006736 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006737
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006738 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006739 if (Kind.getKind() == InitializationKind::IK_Default &&
6740 (Entity.getKind() == InitializedEntity::EK_Base ||
6741 Entity.getKind() == InitializedEntity::EK_Member) &&
6742 isa<CXXConstructorDecl>(S.CurContext)) {
6743 // This is implicit default initialization of a member or
6744 // base within a constructor. If no viable function was
6745 // found, notify the user that she needs to explicitly
6746 // initialize this base/member.
6747 CXXConstructorDecl *Constructor
6748 = cast<CXXConstructorDecl>(S.CurContext);
6749 if (Entity.getKind() == InitializedEntity::EK_Base) {
6750 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006751 << (Constructor->getInheritedConstructor() ? 2 :
6752 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006753 << S.Context.getTypeDeclType(Constructor->getParent())
6754 << /*base=*/0
6755 << Entity.getType();
6756
6757 RecordDecl *BaseDecl
6758 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6759 ->getDecl();
6760 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6761 << S.Context.getTagDeclType(BaseDecl);
6762 } else {
6763 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006764 << (Constructor->getInheritedConstructor() ? 2 :
6765 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006766 << S.Context.getTypeDeclType(Constructor->getParent())
6767 << /*member=*/1
6768 << Entity.getName();
Alp Toker2afa8782014-05-28 12:20:14 +00006769 S.Diag(Entity.getDecl()->getLocation(),
6770 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006771
6772 if (const RecordType *Record
6773 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006774 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006775 diag::note_previous_decl)
6776 << S.Context.getTagDeclType(Record->getDecl());
6777 }
6778 break;
6779 }
6780
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006781 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6782 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006783 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006784 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006785
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006786 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006787 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006788 OverloadingResult Ovl
6789 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00006790 if (Ovl != OR_Deleted) {
6791 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6792 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006793 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00006794 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006795 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00006796
6797 // If this is a defaulted or implicitly-declared function, then
6798 // it was implicitly deleted. Make it clear that the deletion was
6799 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00006800 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006801 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00006802 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006803 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00006804 else
6805 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6806 << true << DestType << ArgsRange;
6807
6808 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006809 break;
6810 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006811
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006812 case OR_Success:
6813 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006814 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006815 }
David Blaikie60deeee2012-01-17 08:24:58 +00006816 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006817
Douglas Gregor85dabae2009-12-16 01:38:02 +00006818 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006819 if (Entity.getKind() == InitializedEntity::EK_Member &&
6820 isa<CXXConstructorDecl>(S.CurContext)) {
6821 // This is implicit default-initialization of a const member in
6822 // a constructor. Complain that it needs to be explicitly
6823 // initialized.
6824 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6825 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006826 << (Constructor->getInheritedConstructor() ? 2 :
6827 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006828 << S.Context.getTypeDeclType(Constructor->getParent())
6829 << /*const=*/1
6830 << Entity.getName();
6831 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6832 << Entity.getName();
6833 } else {
6834 S.Diag(Kind.getLocation(), diag::err_default_init_const)
Nico Weber9386c822014-07-23 05:16:10 +00006835 << DestType << (bool)DestType->getAs<RecordType>();
6836 maybeEmitZeroInitializationFixit(S, *this, Entity);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006837 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00006838 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006839
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006840 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00006841 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006842 diag::err_init_incomplete_type);
6843 break;
6844
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006845 case FK_ListInitializationFailed: {
6846 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00006847 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6848 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006849 break;
6850 }
John McCall4124c492011-10-17 18:40:02 +00006851
6852 case FK_PlaceholderType: {
6853 // FIXME: Already diagnosed!
6854 break;
6855 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00006856
Sebastian Redl048a6d72012-04-01 19:54:59 +00006857 case FK_ExplicitConstructor: {
6858 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6859 << Args[0]->getSourceRange();
6860 OverloadCandidateSet::iterator Best;
6861 OverloadingResult Ovl
6862 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00006863 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00006864 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6865 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6866 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6867 break;
6868 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006869 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006870
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006871 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006872 return true;
6873}
Douglas Gregore1314a62009-12-18 05:02:21 +00006874
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006875void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006876 switch (SequenceKind) {
6877 case FailedSequence: {
6878 OS << "Failed sequence: ";
6879 switch (Failure) {
6880 case FK_TooManyInitsForReference:
6881 OS << "too many initializers for reference";
6882 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006883
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006884 case FK_ArrayNeedsInitList:
6885 OS << "array requires initializer list";
6886 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006887
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006888 case FK_ArrayNeedsInitListOrStringLiteral:
6889 OS << "array requires initializer list or string literal";
6890 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006891
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006892 case FK_ArrayNeedsInitListOrWideStringLiteral:
6893 OS << "array requires initializer list or wide string literal";
6894 break;
6895
6896 case FK_NarrowStringIntoWideCharArray:
6897 OS << "narrow string into wide char array";
6898 break;
6899
6900 case FK_WideStringIntoCharArray:
6901 OS << "wide string into char array";
6902 break;
6903
6904 case FK_IncompatWideStringIntoWideChar:
6905 OS << "incompatible wide string into wide char array";
6906 break;
6907
Douglas Gregore2f943b2011-02-22 18:29:51 +00006908 case FK_ArrayTypeMismatch:
6909 OS << "array type mismatch";
6910 break;
6911
6912 case FK_NonConstantArrayInit:
6913 OS << "non-constant array initializer";
6914 break;
6915
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006916 case FK_AddressOfOverloadFailed:
6917 OS << "address of overloaded function failed";
6918 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006919
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006920 case FK_ReferenceInitOverloadFailed:
6921 OS << "overload resolution for reference initialization failed";
6922 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006923
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006924 case FK_NonConstLValueReferenceBindingToTemporary:
6925 OS << "non-const lvalue reference bound to temporary";
6926 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006927
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006928 case FK_NonConstLValueReferenceBindingToUnrelated:
6929 OS << "non-const lvalue reference bound to unrelated type";
6930 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006931
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006932 case FK_RValueReferenceBindingToLValue:
6933 OS << "rvalue reference bound to an lvalue";
6934 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006935
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006936 case FK_ReferenceInitDropsQualifiers:
6937 OS << "reference initialization drops qualifiers";
6938 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006939
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006940 case FK_ReferenceInitFailed:
6941 OS << "reference initialization failed";
6942 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006943
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006944 case FK_ConversionFailed:
6945 OS << "conversion failed";
6946 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006947
John Wiegley01296292011-04-08 18:41:53 +00006948 case FK_ConversionFromPropertyFailed:
6949 OS << "conversion from property failed";
6950 break;
6951
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006952 case FK_TooManyInitsForScalar:
6953 OS << "too many initializers for scalar";
6954 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006955
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006956 case FK_ReferenceBindingToInitList:
6957 OS << "referencing binding to initializer list";
6958 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006959
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006960 case FK_InitListBadDestinationType:
6961 OS << "initializer list for non-aggregate, non-scalar type";
6962 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006963
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006964 case FK_UserConversionOverloadFailed:
6965 OS << "overloading failed for user-defined conversion";
6966 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006967
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006968 case FK_ConstructorOverloadFailed:
6969 OS << "constructor overloading failed";
6970 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006971
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006972 case FK_DefaultInitOfConst:
6973 OS << "default initialization of a const variable";
6974 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006975
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00006976 case FK_Incomplete:
6977 OS << "initialization of incomplete type";
6978 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006979
6980 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006981 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00006982 break;
6983
John McCalla59dc2f2012-01-05 00:13:19 +00006984 case FK_VariableLengthArrayHasInitializer:
6985 OS << "variable length array has an initializer";
6986 break;
6987
John McCall4124c492011-10-17 18:40:02 +00006988 case FK_PlaceholderType:
6989 OS << "initializer expression isn't contextually valid";
6990 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00006991
6992 case FK_ListConstructorOverloadFailed:
6993 OS << "list constructor overloading failed";
6994 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006995
Sebastian Redl048a6d72012-04-01 19:54:59 +00006996 case FK_ExplicitConstructor:
6997 OS << "list copy initialization chose explicit constructor";
6998 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006999 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007000 OS << '\n';
7001 return;
7002 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007003
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007004 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00007005 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007006 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007007
Sebastian Redld201edf2011-06-05 13:59:11 +00007008 case NormalSequence:
7009 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007010 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007011 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007012
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007013 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
7014 if (S != step_begin()) {
7015 OS << " -> ";
7016 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007017
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007018 switch (S->Kind) {
7019 case SK_ResolveAddressOfOverloadedFunction:
7020 OS << "resolve address of overloaded function";
7021 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007022
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007023 case SK_CastDerivedToBaseRValue:
7024 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
7025 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007026
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007027 case SK_CastDerivedToBaseXValue:
7028 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
7029 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007030
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007031 case SK_CastDerivedToBaseLValue:
7032 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
7033 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007034
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007035 case SK_BindReference:
7036 OS << "bind reference to lvalue";
7037 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007038
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007039 case SK_BindReferenceToTemporary:
7040 OS << "bind reference to a temporary";
7041 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007042
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007043 case SK_ExtraneousCopyToTemporary:
7044 OS << "extraneous C++03 copy to temporary";
7045 break;
7046
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007047 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007048 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007049 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007050
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007051 case SK_QualificationConversionRValue:
7052 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00007053 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007054
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007055 case SK_QualificationConversionXValue:
7056 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00007057 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007058
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007059 case SK_QualificationConversionLValue:
7060 OS << "qualification conversion (lvalue)";
7061 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007062
Richard Smith77be48a2014-07-31 06:31:19 +00007063 case SK_AtomicConversion:
7064 OS << "non-atomic-to-atomic conversion";
7065 break;
7066
Jordan Roseb1312a52013-04-11 00:58:58 +00007067 case SK_LValueToRValue:
7068 OS << "load (lvalue to rvalue)";
7069 break;
7070
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007071 case SK_ConversionSequence:
7072 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00007073 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007074 OS << ")";
7075 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007076
Richard Smithaaa0ec42013-09-21 21:19:19 +00007077 case SK_ConversionSequenceNoNarrowing:
7078 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00007079 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00007080 OS << ")";
7081 break;
7082
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007083 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007084 OS << "list aggregate initialization";
7085 break;
7086
Sebastian Redl29526f02011-11-27 16:50:07 +00007087 case SK_UnwrapInitList:
7088 OS << "unwrap reference initializer list";
7089 break;
7090
7091 case SK_RewrapInitList:
7092 OS << "rewrap reference initializer list";
7093 break;
7094
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007095 case SK_ConstructorInitialization:
7096 OS << "constructor initialization";
7097 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007098
Richard Smith53324112014-07-16 21:33:43 +00007099 case SK_ConstructorInitializationFromList:
7100 OS << "list initialization via constructor";
7101 break;
7102
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007103 case SK_ZeroInitialization:
7104 OS << "zero initialization";
7105 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007106
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007107 case SK_CAssignment:
7108 OS << "C assignment";
7109 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007110
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007111 case SK_StringInit:
7112 OS << "string initialization";
7113 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007114
7115 case SK_ObjCObjectConversion:
7116 OS << "Objective-C object conversion";
7117 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007118
7119 case SK_ArrayInit:
7120 OS << "array initialization";
7121 break;
John McCall31168b02011-06-15 23:02:42 +00007122
Richard Smithebeed412012-02-15 22:38:09 +00007123 case SK_ParenthesizedArrayInit:
7124 OS << "parenthesized array initialization";
7125 break;
7126
John McCall31168b02011-06-15 23:02:42 +00007127 case SK_PassByIndirectCopyRestore:
7128 OS << "pass by indirect copy and restore";
7129 break;
7130
7131 case SK_PassByIndirectRestore:
7132 OS << "pass by indirect restore";
7133 break;
7134
7135 case SK_ProduceObjCObject:
7136 OS << "Objective-C object retension";
7137 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007138
7139 case SK_StdInitializerList:
7140 OS << "std::initializer_list from initializer list";
7141 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007142
Richard Smithf8adcdc2014-07-17 05:12:35 +00007143 case SK_StdInitializerListConstructorCall:
7144 OS << "list initialization from std::initializer_list";
7145 break;
7146
Guy Benyei61054192013-02-07 10:55:47 +00007147 case SK_OCLSamplerInit:
7148 OS << "OpenCL sampler_t from integer constant";
7149 break;
7150
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007151 case SK_OCLZeroEvent:
7152 OS << "OpenCL event_t from zero";
7153 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007154 }
Richard Smith6b216962013-02-05 05:52:24 +00007155
7156 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007157 }
Richard Smith6b216962013-02-05 05:52:24 +00007158
7159 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007160}
7161
7162void InitializationSequence::dump() const {
7163 dump(llvm::errs());
7164}
7165
Richard Smithaaa0ec42013-09-21 21:19:19 +00007166static void DiagnoseNarrowingInInitList(Sema &S,
7167 const ImplicitConversionSequence &ICS,
7168 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007169 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007170 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007171 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00007172 switch (ICS.getKind()) {
7173 case ImplicitConversionSequence::StandardConversion:
7174 SCS = &ICS.Standard;
7175 break;
7176 case ImplicitConversionSequence::UserDefinedConversion:
7177 SCS = &ICS.UserDefined.After;
7178 break;
7179 case ImplicitConversionSequence::AmbiguousConversion:
7180 case ImplicitConversionSequence::EllipsisConversion:
7181 case ImplicitConversionSequence::BadConversion:
7182 return;
7183 }
7184
Richard Smith66e05fe2012-01-18 05:21:49 +00007185 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
7186 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00007187 QualType ConstantType;
7188 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
7189 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00007190 case NK_Not_Narrowing:
7191 // No narrowing occurred.
7192 return;
7193
7194 case NK_Type_Narrowing:
7195 // This was a floating-to-integer conversion, which is always considered a
7196 // narrowing conversion even if the value is a constant and can be
7197 // represented exactly as an integer.
7198 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007199 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7200 ? diag::warn_init_list_type_narrowing
7201 : diag::ext_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007202 << PostInit->getSourceRange()
7203 << PreNarrowingType.getLocalUnqualifiedType()
7204 << EntityType.getLocalUnqualifiedType();
7205 break;
7206
7207 case NK_Constant_Narrowing:
7208 // A constant value was narrowed.
7209 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007210 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7211 ? diag::warn_init_list_constant_narrowing
7212 : diag::ext_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007213 << PostInit->getSourceRange()
Richard Smith5614ca72012-03-23 23:55:39 +00007214 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007215 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007216 break;
7217
7218 case NK_Variable_Narrowing:
7219 // A variable's value may have been narrowed.
7220 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007221 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7222 ? diag::warn_init_list_variable_narrowing
7223 : diag::ext_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007224 << PostInit->getSourceRange()
7225 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007226 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007227 break;
7228 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007229
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007230 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007231 llvm::raw_svector_ostream OS(StaticCast);
7232 OS << "static_cast<";
7233 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7234 // It's important to use the typedef's name if there is one so that the
7235 // fixit doesn't break code using types like int64_t.
7236 //
7237 // FIXME: This will break if the typedef requires qualification. But
7238 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007239 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007240 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00007241 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007242 else {
7243 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
7244 // with a broken cast.
7245 return;
7246 }
7247 OS << ">(";
Alp Tokerb0869032014-05-17 01:13:18 +00007248 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007249 << PostInit->getSourceRange()
7250 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
7251 << FixItHint::CreateInsertion(
7252 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007253}
7254
Douglas Gregore1314a62009-12-18 05:02:21 +00007255//===----------------------------------------------------------------------===//
7256// Initialization helper functions
7257//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00007258bool
7259Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7260 ExprResult Init) {
7261 if (Init.isInvalid())
7262 return false;
7263
7264 Expr *InitE = Init.get();
7265 assert(InitE && "No initialization expression");
7266
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00007267 InitializationKind Kind
7268 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007269 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00007270 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00007271}
7272
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007273ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00007274Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7275 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007276 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00007277 bool TopLevelOfInitList,
7278 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00007279 if (Init.isInvalid())
7280 return ExprError();
7281
John McCall1f425642010-11-11 03:21:53 +00007282 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00007283 assert(InitE && "No initialization expression?");
7284
7285 if (EqualLoc.isInvalid())
7286 EqualLoc = InitE->getLocStart();
7287
7288 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00007289 EqualLoc,
7290 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00007291 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007292 Init.get();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007293
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007294 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00007295
Richard Smith66e05fe2012-01-18 05:21:49 +00007296 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00007297}