blob: 3dfeb8ecd30b50b271dd6a1a48ad798feb9b883e [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Sema/Designator.h"
21#include "clang/Sema/Lookup.h"
22#include "clang/Sema/SemaInternal.h"
Sebastian Redlc1839b12012-01-17 22:49:42 +000023#include "llvm/ADT/APInt.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000024#include "llvm/ADT/SmallString.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000025#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000026#include "llvm/Support/raw_ostream.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000027#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000028using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000029
Chris Lattner0cb78032009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000034/// \brief Check whether T is compatible with a wide character type (wchar_t,
35/// char16_t or char32_t).
36static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
37 if (Context.typesAreCompatible(Context.getWideCharType(), T))
38 return true;
39 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
40 return Context.typesAreCompatible(Context.Char16Ty, T) ||
41 Context.typesAreCompatible(Context.Char32Ty, T);
42 }
43 return false;
44}
45
46enum StringInitFailureKind {
47 SIF_None,
48 SIF_NarrowStringIntoWideChar,
49 SIF_WideStringIntoChar,
50 SIF_IncompatWideStringIntoWideChar,
51 SIF_Other
52};
53
54/// \brief Check whether the array of type AT can be initialized by the Init
55/// expression by means of string initialization. Returns SIF_None if so,
56/// otherwise returns a StringInitFailureKind that describes why the
57/// initialization would not work.
58static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
59 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000060 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000061 return SIF_Other;
Eli Friedman893abe42009-05-29 18:22:49 +000062
Chris Lattnera9196812009-02-26 23:26:43 +000063 // See if this is a string literal or @encode.
64 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000065
Chris Lattnera9196812009-02-26 23:26:43 +000066 // Handle @encode, which is a narrow string.
67 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000068 return SIF_None;
Chris Lattnera9196812009-02-26 23:26:43 +000069
70 // Otherwise we can only handle string literals.
71 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Craig Topperc3ec1492014-05-26 06:22:03 +000072 if (!SL)
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000073 return SIF_Other;
Eli Friedman42a84652009-05-31 10:54:53 +000074
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000075 const QualType ElemTy =
76 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
Douglas Gregorfb65e592011-07-27 05:40:30 +000077
78 switch (SL->getKind()) {
79 case StringLiteral::Ascii:
80 case StringLiteral::UTF8:
81 // char array can be initialized with a narrow string.
82 // Only allow char x[] = "foo"; not char x[] = L"foo";
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000083 if (ElemTy->isCharType())
84 return SIF_None;
85 if (IsWideCharCompatible(ElemTy, Context))
86 return SIF_NarrowStringIntoWideChar;
87 return SIF_Other;
88 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
89 // "An array with element type compatible with a qualified or unqualified
90 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
91 // string literal with the corresponding encoding prefix (L, u, or U,
92 // respectively), optionally enclosed in braces.
Douglas Gregorfb65e592011-07-27 05:40:30 +000093 case StringLiteral::UTF16:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000094 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
95 return SIF_None;
96 if (ElemTy->isCharType())
97 return SIF_WideStringIntoChar;
98 if (IsWideCharCompatible(ElemTy, Context))
99 return SIF_IncompatWideStringIntoWideChar;
100 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000101 case StringLiteral::UTF32:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000102 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
103 return SIF_None;
104 if (ElemTy->isCharType())
105 return SIF_WideStringIntoChar;
106 if (IsWideCharCompatible(ElemTy, Context))
107 return SIF_IncompatWideStringIntoWideChar;
108 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000109 case StringLiteral::Wide:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000110 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
111 return SIF_None;
112 if (ElemTy->isCharType())
113 return SIF_WideStringIntoChar;
114 if (IsWideCharCompatible(ElemTy, Context))
115 return SIF_IncompatWideStringIntoWideChar;
116 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000117 }
Mike Stump11289f42009-09-09 15:08:12 +0000118
Douglas Gregorfb65e592011-07-27 05:40:30 +0000119 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +0000120}
121
Hans Wennborg950f3182013-05-16 09:22:40 +0000122static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
123 ASTContext &Context) {
John McCall66884dd2011-02-21 07:22:22 +0000124 const ArrayType *arrayType = Context.getAsArrayType(declType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000125 if (!arrayType)
Hans Wennborg950f3182013-05-16 09:22:40 +0000126 return SIF_Other;
127 return IsStringInit(init, arrayType, Context);
John McCall66884dd2011-02-21 07:22:22 +0000128}
129
Richard Smith430c23b2013-05-05 16:40:13 +0000130/// Update the type of a string literal, including any surrounding parentheses,
131/// to match the type of the object which it is initializing.
132static void updateStringLiteralType(Expr *E, QualType Ty) {
Richard Smithd74b16062013-05-06 00:35:47 +0000133 while (true) {
Richard Smith430c23b2013-05-05 16:40:13 +0000134 E->setType(Ty);
Richard Smithd74b16062013-05-06 00:35:47 +0000135 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
136 break;
137 else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
138 E = PE->getSubExpr();
139 else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
140 E = UO->getSubExpr();
141 else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
142 E = GSE->getResultExpr();
143 else
144 llvm_unreachable("unexpected expr in string literal init");
Richard Smith430c23b2013-05-05 16:40:13 +0000145 }
Richard Smith430c23b2013-05-05 16:40:13 +0000146}
147
John McCall5decec92011-02-21 07:57:55 +0000148static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
149 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000150 // Get the length of the string as parsed.
151 uint64_t StrLength =
152 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
153
Mike Stump11289f42009-09-09 15:08:12 +0000154
Chris Lattner0cb78032009-02-24 22:27:37 +0000155 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000156 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000157 // being initialized to a string literal.
Benjamin Kramere0731772012-08-04 17:00:46 +0000158 llvm::APInt ConstVal(32, StrLength);
Chris Lattner0cb78032009-02-24 22:27:37 +0000159 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000160 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
161 ConstVal,
162 ArrayType::Normal, 0);
Richard Smith430c23b2013-05-05 16:40:13 +0000163 updateStringLiteralType(Str, DeclT);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000164 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000165 }
Mike Stump11289f42009-09-09 15:08:12 +0000166
Eli Friedman893abe42009-05-29 18:22:49 +0000167 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000168
Eli Friedman554eba92011-04-11 00:23:45 +0000169 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000170 // the size may be smaller or larger than the string we are initializing.
171 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000172 if (S.getLangOpts().CPlusPlus) {
Richard Smith430c23b2013-05-05 16:40:13 +0000173 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000174 // For Pascal strings it's OK to strip off the terminating null character,
175 // so the example below is valid:
176 //
177 // unsigned char a[2] = "\pa";
178 if (SL->isPascal())
179 StrLength--;
180 }
181
Eli Friedman554eba92011-04-11 00:23:45 +0000182 // [dcl.init.string]p2
183 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000184 S.Diag(Str->getLocStart(),
Eli Friedman554eba92011-04-11 00:23:45 +0000185 diag::err_initializer_string_for_char_array_too_long)
186 << Str->getSourceRange();
187 } else {
188 // C99 6.7.8p14.
189 if (StrLength-1 > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000190 S.Diag(Str->getLocStart(),
Eli Friedman554eba92011-04-11 00:23:45 +0000191 diag::warn_initializer_string_for_char_array_too_long)
192 << Str->getSourceRange();
193 }
Mike Stump11289f42009-09-09 15:08:12 +0000194
Eli Friedman893abe42009-05-29 18:22:49 +0000195 // Set the type to the actual size that we are initializing. If we have
196 // something like:
197 // char x[1] = "foo";
198 // then this will set the string literal's type to char[1].
Richard Smith430c23b2013-05-05 16:40:13 +0000199 updateStringLiteralType(Str, DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000200}
201
Chris Lattner0cb78032009-02-24 22:27:37 +0000202//===----------------------------------------------------------------------===//
203// Semantic checking for initializer lists.
204//===----------------------------------------------------------------------===//
205
Douglas Gregorcde232f2009-01-29 01:05:33 +0000206/// @brief Semantic checking for initializer lists.
207///
208/// The InitListChecker class contains a set of routines that each
209/// handle the initialization of a certain kind of entity, e.g.,
210/// arrays, vectors, struct/union types, scalars, etc. The
211/// InitListChecker itself performs a recursive walk of the subobject
212/// structure of the type to be initialized, while stepping through
213/// the initializer list one element at a time. The IList and Index
214/// parameters to each of the Check* routines contain the active
215/// (syntactic) initializer list and the index into that initializer
216/// list that represents the current initializer. Each routine is
217/// responsible for moving that Index forward as it consumes elements.
218///
219/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000220/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000221/// initializer list and the index into that initializer list where we
222/// are copying initializers as we map them over to the semantic
223/// list. Once we have completed our recursive walk of the subobject
224/// structure, we will have constructed a full semantic initializer
225/// list.
226///
227/// C99 designators cause changes in the initializer list traversal,
228/// because they make the initialization "jump" into a specific
229/// subobject and then continue the initialization from that
230/// point. CheckDesignatedInitializer() recursively steps into the
231/// designated subobject and manages backing out the recursion to
232/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000233namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000234class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000235 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000236 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000237 bool VerifyOnly; // no diagnostics, no structure building
Benjamin Kramer6b441d62012-02-23 14:48:40 +0000238 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000239 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000240
Anders Carlsson6cabf312010-01-23 23:23:01 +0000241 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000242 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000243 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000244 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000245 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000246 InitListExpr *IList, QualType &T,
Richard Smith4e0d2e42013-09-20 20:10:22 +0000247 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000248 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000249 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000250 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000251 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000252 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000253 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000254 unsigned &StructuredIndex,
255 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000256 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000257 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000258 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000259 InitListExpr *StructuredList,
260 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000261 void CheckComplexType(const InitializedEntity &Entity,
262 InitListExpr *IList, QualType DeclType,
263 unsigned &Index,
264 InitListExpr *StructuredList,
265 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000266 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000267 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000268 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000269 InitListExpr *StructuredList,
270 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000271 void CheckReferenceType(const InitializedEntity &Entity,
272 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000273 unsigned &Index,
274 InitListExpr *StructuredList,
275 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000276 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000277 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000278 InitListExpr *StructuredList,
279 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000280 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000281 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000282 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000283 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000284 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000285 unsigned &StructuredIndex,
286 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000287 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000288 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000289 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000290 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000291 InitListExpr *StructuredList,
292 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000293 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000294 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000295 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000296 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000297 RecordDecl::field_iterator *NextField,
298 llvm::APSInt *NextElementIndex,
299 unsigned &Index,
300 InitListExpr *StructuredList,
301 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000302 bool FinishSubobjectInit,
303 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000304 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
305 QualType CurrentObjectType,
306 InitListExpr *StructuredList,
307 unsigned StructuredIndex,
308 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000309 void UpdateStructuredListElement(InitListExpr *StructuredList,
310 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000311 Expr *expr);
312 int numArrayElements(QualType DeclType);
313 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000314
Richard Smith454a7cd2014-06-03 08:26:00 +0000315 static ExprResult PerformEmptyInit(Sema &SemaRef,
316 SourceLocation Loc,
317 const InitializedEntity &Entity,
318 bool VerifyOnly);
319 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000320 const InitializedEntity &ParentEntity,
321 InitListExpr *ILE, bool &RequiresSecondPass);
Richard Smith454a7cd2014-06-03 08:26:00 +0000322 void FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000323 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000324 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
325 Expr *InitExpr, FieldDecl *Field,
326 bool TopLevelObject);
Richard Smith454a7cd2014-06-03 08:26:00 +0000327 void CheckEmptyInitializable(const InitializedEntity &Entity,
328 SourceLocation Loc);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000329
Douglas Gregor85df8d82009-01-29 00:45:39 +0000330public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000331 InitListChecker(Sema &S, const InitializedEntity &Entity,
Richard Smithde229232013-06-06 11:41:05 +0000332 InitListExpr *IL, QualType &T, bool VerifyOnly);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000333 bool HadError() { return hadError; }
334
335 // @brief Retrieves the fully-structured initializer list used for
336 // semantic analysis and code generation.
337 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
338};
Chris Lattner9ececce2009-02-24 22:48:58 +0000339} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000340
Richard Smith454a7cd2014-06-03 08:26:00 +0000341ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
342 SourceLocation Loc,
343 const InitializedEntity &Entity,
344 bool VerifyOnly) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000345 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
346 true);
Richard Smith454a7cd2014-06-03 08:26:00 +0000347 MultiExprArg SubInit;
348 Expr *InitExpr;
349 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
350
351 // C++ [dcl.init.aggr]p7:
352 // If there are fewer initializer-clauses in the list than there are
353 // members in the aggregate, then each member not explicitly initialized
354 // ...
355 if (SemaRef.getLangOpts().CPlusPlus11 &&
356 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType()) {
357 // C++1y / DR1070:
358 // shall be initialized [...] from an empty initializer list.
359 //
360 // We apply the resolution of this DR to C++11 but not C++98, since C++98
361 // does not have useful semantics for initialization from an init list.
362 // We treat this as copy-initialization, because aggregate initialization
363 // always performs copy-initialization on its elements.
364 //
365 // Only do this if we're initializing a class type, to avoid filling in
366 // the initializer list where possible.
367 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
368 InitListExpr(SemaRef.Context, Loc, None, Loc);
369 InitExpr->setType(SemaRef.Context.VoidTy);
370 SubInit = InitExpr;
371 Kind = InitializationKind::CreateCopy(Loc, Loc);
372 } else {
373 // C++03:
374 // shall be value-initialized.
375 }
376
377 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
378 if (!InitSeq) {
379 if (!VerifyOnly) {
380 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
381 if (Entity.getKind() == InitializedEntity::EK_Member)
382 SemaRef.Diag(Entity.getDecl()->getLocation(),
383 diag::note_in_omitted_aggregate_initializer)
384 << /*field*/1 << Entity.getDecl();
385 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
386 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
387 << /*array element*/0 << Entity.getElementIndex();
388 }
389 return ExprError();
390 }
391
392 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
393 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
394}
395
396void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
397 SourceLocation Loc) {
398 assert(VerifyOnly &&
399 "CheckEmptyInitializable is only inteded for verification mode.");
400 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true).isInvalid())
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000401 hadError = true;
402}
403
Richard Smith454a7cd2014-06-03 08:26:00 +0000404void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000405 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000406 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000407 bool &RequiresSecondPass) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000408 SourceLocation Loc = ILE->getLocEnd();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000409 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000410 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000411 = InitializedEntity::InitializeMember(Field, &ParentEntity);
412 if (Init >= NumInits || !ILE->getInit(Init)) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000413 // C++1y [dcl.init.aggr]p7:
414 // If there are fewer initializer-clauses in the list than there are
415 // members in the aggregate, then each member not explicitly initialized
416 // shall be initialized from its brace-or-equal-initializer [...]
Richard Smith852c9db2013-04-20 22:23:05 +0000417 if (Field->hasInClassInitializer()) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000418 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, Loc, Field);
Richard Smith852c9db2013-04-20 22:23:05 +0000419 if (Init < NumInits)
420 ILE->setInit(Init, DIE);
421 else {
422 ILE->updateInit(SemaRef.Context, Init, DIE);
423 RequiresSecondPass = true;
424 }
425 return;
426 }
427
Douglas Gregor2bb07652009-12-22 00:05:34 +0000428 if (Field->getType()->isReferenceType()) {
429 // C++ [dcl.init.aggr]p9:
430 // If an incomplete or empty initializer-list leaves a
431 // member of reference type uninitialized, the program is
432 // ill-formed.
433 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
434 << Field->getType()
435 << ILE->getSyntacticForm()->getSourceRange();
436 SemaRef.Diag(Field->getLocation(),
437 diag::note_uninit_reference_member);
438 hadError = true;
439 return;
440 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000441
Richard Smith454a7cd2014-06-03 08:26:00 +0000442 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
443 /*VerifyOnly*/false);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000444 if (MemberInit.isInvalid()) {
445 hadError = true;
446 return;
447 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000448
Douglas Gregor2bb07652009-12-22 00:05:34 +0000449 if (hadError) {
450 // Do nothing
451 } else if (Init < NumInits) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000452 ILE->setInit(Init, MemberInit.getAs<Expr>());
Richard Smith454a7cd2014-06-03 08:26:00 +0000453 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
454 // Empty initialization requires a constructor call, so
Douglas Gregor2bb07652009-12-22 00:05:34 +0000455 // extend the initializer list to include the constructor
456 // call and make a note that we'll need to take another pass
457 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000458 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000459 RequiresSecondPass = true;
460 }
461 } else if (InitListExpr *InnerILE
462 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Richard Smith454a7cd2014-06-03 08:26:00 +0000463 FillInEmptyInitializations(MemberEntity, InnerILE,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000464 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000465}
466
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000467/// Recursively replaces NULL values within the given initializer list
468/// with expressions that perform value-initialization of the
469/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000470void
Richard Smith454a7cd2014-06-03 08:26:00 +0000471InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000472 InitListExpr *ILE,
473 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000474 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000475 "Should not have void type");
Mike Stump11289f42009-09-09 15:08:12 +0000476
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000477 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000478 const RecordDecl *RDecl = RType->getDecl();
479 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Richard Smith454a7cd2014-06-03 08:26:00 +0000480 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Douglas Gregor2bb07652009-12-22 00:05:34 +0000481 Entity, ILE, RequiresSecondPass);
Richard Smith852c9db2013-04-20 22:23:05 +0000482 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
483 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000484 for (auto *Field : RDecl->fields()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000485 if (Field->hasInClassInitializer()) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000486 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass);
Richard Smith852c9db2013-04-20 22:23:05 +0000487 break;
488 }
489 }
490 } else {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000491 unsigned Init = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000492 for (auto *Field : RDecl->fields()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000493 if (Field->isUnnamedBitfield())
494 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000495
Douglas Gregor2bb07652009-12-22 00:05:34 +0000496 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000497 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000498
Richard Smith454a7cd2014-06-03 08:26:00 +0000499 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000500 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000501 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000502
Douglas Gregor2bb07652009-12-22 00:05:34 +0000503 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000504
Douglas Gregor2bb07652009-12-22 00:05:34 +0000505 // Only look at the first initialization of a union.
Richard Smith852c9db2013-04-20 22:23:05 +0000506 if (RDecl->isUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000507 break;
508 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000509 }
510
511 return;
Mike Stump11289f42009-09-09 15:08:12 +0000512 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000513
514 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000515
Douglas Gregor723796a2009-12-16 06:35:08 +0000516 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000517 unsigned NumInits = ILE->getNumInits();
518 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000519 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000520 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000521 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
522 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000523 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000524 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000525 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000526 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000527 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000528 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000529 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000530 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000531 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000532
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000533 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000534 if (hadError)
535 return;
536
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000537 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
538 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000539 ElementEntity.setElementIndex(Init);
540
Craig Topperc3ec1492014-05-26 06:22:03 +0000541 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000542 if (!InitExpr && !ILE->hasArrayFiller()) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000543 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
544 ElementEntity,
545 /*VerifyOnly*/false);
Douglas Gregor723796a2009-12-16 06:35:08 +0000546 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000547 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000548 return;
549 }
550
551 if (hadError) {
552 // Do nothing
553 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000554 // For arrays, just set the expression used for value-initialization
555 // of the "holes" in the array.
556 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000557 ILE->setArrayFiller(ElementInit.getAs<Expr>());
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000558 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000559 ILE->setInit(Init, ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000560 } else {
561 // For arrays, just set the expression used for value-initialization
562 // of the rest of elements and exit.
563 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000564 ILE->setArrayFiller(ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000565 return;
566 }
567
Richard Smith454a7cd2014-06-03 08:26:00 +0000568 if (!isa<ImplicitValueInitExpr>(ElementInit.get())) {
569 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000570 // extend the initializer list to include the constructor
571 // call and make a note that we'll need to take another pass
572 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000573 ILE->updateInit(SemaRef.Context, Init, ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000574 RequiresSecondPass = true;
575 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000576 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000577 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000578 = dyn_cast_or_null<InitListExpr>(InitExpr))
Richard Smith454a7cd2014-06-03 08:26:00 +0000579 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000580 }
581}
582
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000583
Douglas Gregor723796a2009-12-16 06:35:08 +0000584InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000585 InitListExpr *IL, QualType &T,
Richard Smithde229232013-06-06 11:41:05 +0000586 bool VerifyOnly)
587 : SemaRef(S), VerifyOnly(VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000588 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000589
Richard Smith4e0d2e42013-09-20 20:10:22 +0000590 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000591 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000592 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000593 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000594
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000595 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000596 bool RequiresSecondPass = false;
Richard Smith454a7cd2014-06-03 08:26:00 +0000597 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000598 if (RequiresSecondPass && !hadError)
Richard Smith454a7cd2014-06-03 08:26:00 +0000599 FillInEmptyInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000600 RequiresSecondPass);
601 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000602}
603
604int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000605 // FIXME: use a proper constant
606 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000607 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000608 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000609 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
610 }
611 return maxElements;
612}
613
614int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000615 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000616 int InitializableMembers = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000617 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000618 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000619 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000620
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000621 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000622 return std::min(InitializableMembers, 1);
623 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000624}
625
Richard Smith4e0d2e42013-09-20 20:10:22 +0000626/// Check whether the range of the initializer \p ParentIList from element
627/// \p Index onwards can be used to initialize an object of type \p T. Update
628/// \p Index to indicate how many elements of the list were consumed.
629///
630/// This also fills in \p StructuredList, from element \p StructuredIndex
631/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000632void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000633 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000634 QualType T, unsigned &Index,
635 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000636 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000637 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000638
Steve Narofff8ecff22008-05-01 22:18:59 +0000639 if (T->isArrayType())
640 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000641 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000642 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000643 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000644 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000645 else
David Blaikie83d382b2011-09-23 05:06:16 +0000646 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000647
Eli Friedmane0f832b2008-05-25 13:49:22 +0000648 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000649 if (!VerifyOnly)
650 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
651 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000652 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000653 hadError = true;
654 return;
655 }
656
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000657 // Build a structured initializer list corresponding to this subobject.
658 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000659 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
660 StructuredIndex,
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000661 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregor5741efb2009-03-01 17:12:46 +0000662 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000663 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000664
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000665 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000666 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000667 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000668 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000669 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000670 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000671
Richard Smithde229232013-06-06 11:41:05 +0000672 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000673 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000674
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000675 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000676 // Update the structured sub-object initializer so that it's ending
677 // range corresponds with the end of the last initializer it used.
678 if (EndIndex < ParentIList->getNumInits()) {
679 SourceLocation EndLoc
680 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
681 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
682 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000683
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000684 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000685 if (T->isArrayType() || T->isRecordType()) {
686 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smithde229232013-06-06 11:41:05 +0000687 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000688 << StructuredSubobjectInitList->getSourceRange()
689 << FixItHint::CreateInsertion(
690 StructuredSubobjectInitList->getLocStart(), "{")
691 << FixItHint::CreateInsertion(
692 SemaRef.getLocForEndOfToken(
693 StructuredSubobjectInitList->getLocEnd()),
694 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000695 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000696 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000697}
698
Richard Smith4e0d2e42013-09-20 20:10:22 +0000699/// Check whether the initializer \p IList (that was written with explicit
700/// braces) can be used to initialize an object of type \p T.
701///
702/// This also fills in \p StructuredList with the fully-braced, desugared
703/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000704void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000705 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000706 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000707 bool TopLevelObject) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000708 if (!VerifyOnly) {
709 SyntacticToSemantic[IList] = StructuredList;
710 StructuredList->setSyntacticForm(IList);
711 }
Richard Smith4e0d2e42013-09-20 20:10:22 +0000712
713 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000715 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000716 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +0000717 QualType ExprTy = T;
718 if (!ExprTy->isArrayType())
719 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000720 IList->setType(ExprTy);
721 StructuredList->setType(ExprTy);
722 }
Eli Friedman85f54972008-05-25 13:22:35 +0000723 if (hadError)
724 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000725
Eli Friedman85f54972008-05-25 13:22:35 +0000726 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000727 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000728 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000729 if (SemaRef.getLangOpts().CPlusPlus ||
730 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000731 IList->getType()->isVectorType())) {
732 hadError = true;
733 }
734 return;
735 }
736
Eli Friedmanbd327452009-05-29 20:20:05 +0000737 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +0000738 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
739 SIF_None) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000740 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000741 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000742 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000743 hadError = true;
744 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000745 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000746 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000747 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000748 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000749 // Don't complain for incomplete types, since we'll get an error
750 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000751 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000752 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000753 CurrentObjectType->isArrayType()? 0 :
754 CurrentObjectType->isVectorType()? 1 :
755 CurrentObjectType->isScalarType()? 2 :
756 CurrentObjectType->isUnionType()? 3 :
757 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000758
759 unsigned DK = diag::warn_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000760 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +0000761 DK = diag::err_excess_initializers;
762 hadError = true;
763 }
David Blaikiebbafb8a2012-03-11 07:00:24 +0000764 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +0000765 DK = diag::err_excess_initializers;
766 hadError = true;
767 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000768
Chris Lattnerb0912a52009-02-24 22:50:46 +0000769 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000770 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000771 }
772 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000773
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000774 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
775 !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000776 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000777 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000778 << FixItHint::CreateRemoval(IList->getLocStart())
779 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000780}
781
Anders Carlsson6cabf312010-01-23 23:23:01 +0000782void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000783 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000784 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000785 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000786 unsigned &Index,
787 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000788 unsigned &StructuredIndex,
789 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000790 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
791 // Explicitly braced initializer for complex type can be real+imaginary
792 // parts.
793 CheckComplexType(Entity, IList, DeclType, Index,
794 StructuredList, StructuredIndex);
795 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000796 CheckScalarType(Entity, IList, DeclType, Index,
797 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000798 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000799 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000800 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +0000801 } else if (DeclType->isRecordType()) {
802 assert(DeclType->isAggregateType() &&
803 "non-aggregate records should be handed in CheckSubElementType");
804 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
805 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
806 SubobjectIsDesignatorContext, Index,
807 StructuredList, StructuredIndex,
808 TopLevelObject);
809 } else if (DeclType->isArrayType()) {
810 llvm::APSInt Zero(
811 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
812 false);
813 CheckArrayType(Entity, IList, DeclType, Zero,
814 SubobjectIsDesignatorContext, Index,
815 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +0000816 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
817 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000818 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000819 if (!VerifyOnly)
820 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
821 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000822 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000823 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000824 CheckReferenceType(Entity, IList, DeclType, Index,
825 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000826 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000827 if (!VerifyOnly)
828 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
829 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000830 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000831 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000832 if (!VerifyOnly)
833 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
834 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000835 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000836 }
837}
838
Anders Carlsson6cabf312010-01-23 23:23:01 +0000839void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000840 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000841 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000842 unsigned &Index,
843 InitListExpr *StructuredList,
844 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000845 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +0000846
847 if (ElemType->isReferenceType())
848 return CheckReferenceType(Entity, IList, ElemType, Index,
849 StructuredList, StructuredIndex);
850
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000851 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smithe20c83d2012-07-07 08:35:56 +0000852 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
Richard Smith4e0d2e42013-09-20 20:10:22 +0000853 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +0000854 = getStructuredSubobjectInit(IList, Index, ElemType,
855 StructuredList, StructuredIndex,
856 SubInitList->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000857 CheckExplicitInitList(Entity, SubInitList, ElemType,
858 InnerStructuredList);
Richard Smithe20c83d2012-07-07 08:35:56 +0000859 ++StructuredIndex;
860 ++Index;
861 return;
862 }
863 assert(SemaRef.getLangOpts().CPlusPlus &&
864 "non-aggregate records are only possible in C++");
865 // C++ initialization is handled later.
866 }
867
Eli Friedman4628cf72013-08-19 22:12:56 +0000868 // FIXME: Need to handle atomic aggregate types with implicit init lists.
869 if (ElemType->isScalarType() || ElemType->isAtomicType())
John McCall5decec92011-02-21 07:57:55 +0000870 return CheckScalarType(Entity, IList, ElemType, Index,
871 StructuredList, StructuredIndex);
Anders Carlsson03068aa2009-08-27 17:18:13 +0000872
Eli Friedman4628cf72013-08-19 22:12:56 +0000873 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
874 ElemType->isArrayType()) && "Unexpected type");
875
John McCall5decec92011-02-21 07:57:55 +0000876 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
877 // arrayType can be incomplete if we're initializing a flexible
878 // array member. There's nothing we can do with the completed
879 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000880
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000881 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +0000882 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000883 CheckStringInit(expr, ElemType, arrayType, SemaRef);
884 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +0000885 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000886 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000887 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000888 }
John McCall5decec92011-02-21 07:57:55 +0000889
890 // Fall through for subaggregate initialization.
891
David Blaikiebbafb8a2012-03-11 07:00:24 +0000892 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCall5decec92011-02-21 07:57:55 +0000893 // C++ [dcl.init.aggr]p12:
894 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000895 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000896 // an initializer-list. If the initializer can initialize a
897 // member, the member is initialized. [...]
898
899 // FIXME: Better EqualLoc?
900 InitializationKind Kind =
901 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000902 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCall5decec92011-02-21 07:57:55 +0000903
904 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000905 if (!VerifyOnly) {
Richard Smith0f8ede12011-12-20 04:00:21 +0000906 ExprResult Result =
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000907 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smith0f8ede12011-12-20 04:00:21 +0000908 if (Result.isInvalid())
909 hadError = true;
John McCall5decec92011-02-21 07:57:55 +0000910
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000911 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000912 Result.getAs<Expr>());
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000913 }
John McCall5decec92011-02-21 07:57:55 +0000914 ++Index;
915 return;
916 }
917
918 // Fall through for subaggregate initialization
919 } else {
920 // C99 6.7.8p13:
921 //
922 // The initializer for a structure or union object that has
923 // automatic storage duration shall be either an initializer
924 // list as described below, or a single expression that has
925 // compatible structure or union type. In the latter case, the
926 // initial value of the object, including unnamed members, is
927 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000928 ExprResult ExprRes = expr;
John McCall5decec92011-02-21 07:57:55 +0000929 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000930 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
931 !VerifyOnly)
Eli Friedmanb2a8d462013-09-17 04:07:04 +0000932 != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +0000933 if (ExprRes.isInvalid())
934 hadError = true;
935 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000936 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000937 if (ExprRes.isInvalid())
938 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +0000939 }
940 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000941 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000942 ++Index;
943 return;
944 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000945 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +0000946 // Fall through for subaggregate initialization
947 }
948
949 // C++ [dcl.init.aggr]p12:
950 //
951 // [...] Otherwise, if the member is itself a non-empty
952 // subaggregate, brace elision is assumed and the initializer is
953 // considered for the initialization of the first member of
954 // the subaggregate.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000955 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +0000956 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +0000957 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
958 StructuredIndex);
959 ++StructuredIndex;
960 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000961 if (!VerifyOnly) {
962 // We cannot initialize this element, so let
963 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000964 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000965 /*TopLevelOfInitList=*/true);
966 }
John McCall5decec92011-02-21 07:57:55 +0000967 hadError = true;
968 ++Index;
969 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000970 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000971}
972
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000973void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
974 InitListExpr *IList, QualType DeclType,
975 unsigned &Index,
976 InitListExpr *StructuredList,
977 unsigned &StructuredIndex) {
978 assert(Index == 0 && "Index in explicit init list must be zero");
979
980 // As an extension, clang supports complex initializers, which initialize
981 // a complex number component-wise. When an explicit initializer list for
982 // a complex number contains two two initializers, this extension kicks in:
983 // it exepcts the initializer list to contain two elements convertible to
984 // the element type of the complex type. The first element initializes
985 // the real part, and the second element intitializes the imaginary part.
986
987 if (IList->getNumInits() != 2)
988 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
989 StructuredIndex);
990
991 // This is an extension in C. (The builtin _Complex type does not exist
992 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000993 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000994 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
995 << IList->getSourceRange();
996
997 // Initialize the complex number.
998 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
999 InitializedEntity ElementEntity =
1000 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1001
1002 for (unsigned i = 0; i < 2; ++i) {
1003 ElementEntity.setElementIndex(Index);
1004 CheckSubElementType(ElementEntity, IList, elementType, Index,
1005 StructuredList, StructuredIndex);
1006 }
1007}
1008
1009
Anders Carlsson6cabf312010-01-23 23:23:01 +00001010void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001011 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001012 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001013 InitListExpr *StructuredList,
1014 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001015 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001016 if (!VerifyOnly)
1017 SemaRef.Diag(IList->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001018 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smithc8239732011-10-18 21:39:00 +00001019 diag::warn_cxx98_compat_empty_scalar_initializer :
1020 diag::err_empty_scalar_initializer)
1021 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001022 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001023 ++Index;
1024 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001025 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001026 }
John McCall643169b2010-11-11 00:46:36 +00001027
1028 Expr *expr = IList->getInit(Index);
1029 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001030 // FIXME: This is invalid, and accepting it causes overload resolution
1031 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001032 if (!VerifyOnly)
1033 SemaRef.Diag(SubIList->getLocStart(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001034 diag::ext_many_braces_around_scalar_init)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001035 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001036
1037 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1038 StructuredIndex);
1039 return;
1040 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001041 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001042 SemaRef.Diag(expr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001043 diag::err_designator_for_scalar_init)
1044 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001045 hadError = true;
1046 ++Index;
1047 ++StructuredIndex;
1048 return;
1049 }
1050
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001051 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001052 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001053 hadError = true;
1054 ++Index;
1055 return;
1056 }
1057
John McCall643169b2010-11-11 00:46:36 +00001058 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001059 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001060 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001061
Craig Topperc3ec1492014-05-26 06:22:03 +00001062 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001063
1064 if (Result.isInvalid())
1065 hadError = true; // types weren't compatible.
1066 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001067 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001068
John McCall643169b2010-11-11 00:46:36 +00001069 if (ResultExpr != expr) {
1070 // The type was promoted, update initializer list.
1071 IList->setInit(Index, ResultExpr);
1072 }
1073 }
1074 if (hadError)
1075 ++StructuredIndex;
1076 else
1077 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1078 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001079}
1080
Anders Carlsson6cabf312010-01-23 23:23:01 +00001081void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1082 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001083 unsigned &Index,
1084 InitListExpr *StructuredList,
1085 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001086 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001087 // FIXME: It would be wonderful if we could point at the actual member. In
1088 // general, it would be useful to pass location information down the stack,
1089 // so that we know the location (or decl) of the "current object" being
1090 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001091 if (!VerifyOnly)
1092 SemaRef.Diag(IList->getLocStart(),
1093 diag::err_init_reference_member_uninitialized)
1094 << DeclType
1095 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001096 hadError = true;
1097 ++Index;
1098 ++StructuredIndex;
1099 return;
1100 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001101
1102 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001103 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001104 if (!VerifyOnly)
1105 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1106 << DeclType << IList->getSourceRange();
1107 hadError = true;
1108 ++Index;
1109 ++StructuredIndex;
1110 return;
1111 }
1112
1113 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001114 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001115 hadError = true;
1116 ++Index;
1117 return;
1118 }
1119
1120 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001121 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1122 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001123
1124 if (Result.isInvalid())
1125 hadError = true;
1126
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001127 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001128 IList->setInit(Index, expr);
1129
1130 if (hadError)
1131 ++StructuredIndex;
1132 else
1133 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1134 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001135}
1136
Anders Carlsson6cabf312010-01-23 23:23:01 +00001137void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001138 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001139 unsigned &Index,
1140 InitListExpr *StructuredList,
1141 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001142 const VectorType *VT = DeclType->getAs<VectorType>();
1143 unsigned maxElements = VT->getNumElements();
1144 unsigned numEltsInit = 0;
1145 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001146
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001147 if (Index >= IList->getNumInits()) {
1148 // Make sure the element type can be value-initialized.
1149 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001150 CheckEmptyInitializable(
1151 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1152 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001153 return;
1154 }
1155
David Blaikiebbafb8a2012-03-11 07:00:24 +00001156 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001157 // If the initializing element is a vector, try to copy-initialize
1158 // instead of breaking it apart (which is doomed to failure anyway).
1159 Expr *Init = IList->getInit(Index);
1160 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001161 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001162 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001163 hadError = true;
1164 ++Index;
1165 return;
1166 }
1167
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001168 ExprResult Result =
1169 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1170 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001171
Craig Topperc3ec1492014-05-26 06:22:03 +00001172 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001173 if (Result.isInvalid())
1174 hadError = true; // types weren't compatible.
1175 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001176 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001177
John McCall6a16b2f2010-10-30 00:11:39 +00001178 if (ResultExpr != Init) {
1179 // The type was promoted, update initializer list.
1180 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001181 }
1182 }
John McCall6a16b2f2010-10-30 00:11:39 +00001183 if (hadError)
1184 ++StructuredIndex;
1185 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001186 UpdateStructuredListElement(StructuredList, StructuredIndex,
1187 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001188 ++Index;
1189 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001190 }
Mike Stump11289f42009-09-09 15:08:12 +00001191
John McCall6a16b2f2010-10-30 00:11:39 +00001192 InitializedEntity ElementEntity =
1193 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001194
John McCall6a16b2f2010-10-30 00:11:39 +00001195 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1196 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001197 if (Index >= IList->getNumInits()) {
1198 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001199 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
John McCall6a16b2f2010-10-30 00:11:39 +00001200 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001201 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001202
John McCall6a16b2f2010-10-30 00:11:39 +00001203 ElementEntity.setElementIndex(Index);
1204 CheckSubElementType(ElementEntity, IList, elementType, Index,
1205 StructuredList, StructuredIndex);
1206 }
1207 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001208 }
John McCall6a16b2f2010-10-30 00:11:39 +00001209
1210 InitializedEntity ElementEntity =
1211 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001212
John McCall6a16b2f2010-10-30 00:11:39 +00001213 // OpenCL initializers allows vectors to be constructed from vectors.
1214 for (unsigned i = 0; i < maxElements; ++i) {
1215 // Don't attempt to go past the end of the init list
1216 if (Index >= IList->getNumInits())
1217 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001218
John McCall6a16b2f2010-10-30 00:11:39 +00001219 ElementEntity.setElementIndex(Index);
1220
1221 QualType IType = IList->getInit(Index)->getType();
1222 if (!IType->isVectorType()) {
1223 CheckSubElementType(ElementEntity, IList, elementType, Index,
1224 StructuredList, StructuredIndex);
1225 ++numEltsInit;
1226 } else {
1227 QualType VecType;
1228 const VectorType *IVT = IType->getAs<VectorType>();
1229 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001230
John McCall6a16b2f2010-10-30 00:11:39 +00001231 if (IType->isExtVectorType())
1232 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1233 else
1234 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001235 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001236 CheckSubElementType(ElementEntity, IList, VecType, Index,
1237 StructuredList, StructuredIndex);
1238 numEltsInit += numIElts;
1239 }
1240 }
1241
1242 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001243 if (numEltsInit != maxElements) {
1244 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001245 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001246 diag::err_vector_incorrect_num_initializers)
1247 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1248 hadError = true;
1249 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001250}
1251
Anders Carlsson6cabf312010-01-23 23:23:01 +00001252void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001253 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001254 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001255 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001256 unsigned &Index,
1257 InitListExpr *StructuredList,
1258 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001259 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1260
Steve Narofff8ecff22008-05-01 22:18:59 +00001261 // Check for the special-case of initializing an array with a string.
1262 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001263 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1264 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001265 // We place the string literal directly into the resulting
1266 // initializer list. This is the only place where the structure
1267 // of the structured initializer list doesn't match exactly,
1268 // because doing so would involve allocating one character
1269 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001270 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001271 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1272 UpdateStructuredListElement(StructuredList, StructuredIndex,
1273 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001274 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1275 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001276 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001277 return;
1278 }
1279 }
John McCall66884dd2011-02-21 07:22:22 +00001280 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001281 // Check for VLAs; in standard C it would be possible to check this
1282 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1283 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001284 if (!VerifyOnly)
1285 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1286 diag::err_variable_object_no_init)
1287 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001288 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001289 ++Index;
1290 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001291 return;
1292 }
1293
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001294 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001295 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1296 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001297 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001298 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001299 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001300 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001301 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001302 maxElementsKnown = true;
1303 }
1304
John McCall66884dd2011-02-21 07:22:22 +00001305 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001306 while (Index < IList->getNumInits()) {
1307 Expr *Init = IList->getInit(Index);
1308 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001309 // If we're not the subobject that matches up with the '{' for
1310 // the designator, we shouldn't be handling the
1311 // designator. Return immediately.
1312 if (!SubobjectIsDesignatorContext)
1313 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001314
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001315 // Handle this designated initializer. elementIndex will be
1316 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001317 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001318 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001319 StructuredList, StructuredIndex, true,
1320 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001321 hadError = true;
1322 continue;
1323 }
1324
Douglas Gregor033d1252009-01-23 16:54:12 +00001325 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001326 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001327 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001328 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001329 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001330
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001331 // If the array is of incomplete type, keep track of the number of
1332 // elements in the initializer.
1333 if (!maxElementsKnown && elementIndex > maxElements)
1334 maxElements = elementIndex;
1335
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001336 continue;
1337 }
1338
1339 // If we know the maximum number of elements, and we've already
1340 // hit it, stop consuming elements in the initializer list.
1341 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001342 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001343
Anders Carlsson6cabf312010-01-23 23:23:01 +00001344 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001345 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001346 Entity);
1347 // Check this element.
1348 CheckSubElementType(ElementEntity, IList, elementType, Index,
1349 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001350 ++elementIndex;
1351
1352 // If the array is of incomplete type, keep track of the number of
1353 // elements in the initializer.
1354 if (!maxElementsKnown && elementIndex > maxElements)
1355 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001356 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001357 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001358 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001359 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001360 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001361 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001362 // Sizing an array implicitly to zero is not allowed by ISO C,
1363 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001364 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001365 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001366 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001367
Mike Stump11289f42009-09-09 15:08:12 +00001368 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001369 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001370 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001371 if (!hadError && VerifyOnly) {
1372 // Check if there are any members of the array that get value-initialized.
1373 // If so, check if doing that is possible.
1374 // FIXME: This needs to detect holes left by designated initializers too.
1375 if (maxElementsKnown && elementIndex < maxElements)
Richard Smith454a7cd2014-06-03 08:26:00 +00001376 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1377 SemaRef.Context, 0, Entity),
1378 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001379 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001380}
1381
Eli Friedman3fa64df2011-08-23 22:24:57 +00001382bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1383 Expr *InitExpr,
1384 FieldDecl *Field,
1385 bool TopLevelObject) {
1386 // Handle GNU flexible array initializers.
1387 unsigned FlexArrayDiag;
1388 if (isa<InitListExpr>(InitExpr) &&
1389 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1390 // Empty flexible array init always allowed as an extension
1391 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001392 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001393 // Disallow flexible array init in C++; it is not required for gcc
1394 // compatibility, and it needs work to IRGen correctly in general.
1395 FlexArrayDiag = diag::err_flexible_array_init;
1396 } else if (!TopLevelObject) {
1397 // Disallow flexible array init on non-top-level object
1398 FlexArrayDiag = diag::err_flexible_array_init;
1399 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1400 // Disallow flexible array init on anything which is not a variable.
1401 FlexArrayDiag = diag::err_flexible_array_init;
1402 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1403 // Disallow flexible array init on local variables.
1404 FlexArrayDiag = diag::err_flexible_array_init;
1405 } else {
1406 // Allow other cases.
1407 FlexArrayDiag = diag::ext_flexible_array_init;
1408 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001409
1410 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001411 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001412 FlexArrayDiag)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001413 << InitExpr->getLocStart();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001414 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1415 << Field;
1416 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001417
1418 return FlexArrayDiag != diag::ext_flexible_array_init;
1419}
1420
Anders Carlsson6cabf312010-01-23 23:23:01 +00001421void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001422 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001423 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001424 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001425 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001426 unsigned &Index,
1427 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001428 unsigned &StructuredIndex,
1429 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001430 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001431
Eli Friedman23a9e312008-05-19 19:16:24 +00001432 // If the record is invalid, some of it's members are invalid. To avoid
1433 // confusion, we forgo checking the intializer for the entire record.
1434 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001435 // Assume it was supposed to consume a single initializer.
1436 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001437 hadError = true;
1438 return;
Mike Stump11289f42009-09-09 15:08:12 +00001439 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001440
1441 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001442 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001443
1444 // If there's a default initializer, use it.
1445 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1446 if (VerifyOnly)
1447 return;
1448 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1449 Field != FieldEnd; ++Field) {
1450 if (Field->hasInClassInitializer()) {
1451 StructuredList->setInitializedFieldInUnion(*Field);
1452 // FIXME: Actually build a CXXDefaultInitExpr?
1453 return;
1454 }
1455 }
1456 }
1457
1458 // Value-initialize the first named member of the union.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001459 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1460 Field != FieldEnd; ++Field) {
1461 if (Field->getDeclName()) {
1462 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001463 CheckEmptyInitializable(
1464 InitializedEntity::InitializeMember(*Field, &Entity),
1465 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001466 else
David Blaikie40ed2972012-06-06 20:45:41 +00001467 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001468 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001469 }
1470 }
1471 return;
1472 }
1473
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001474 // If structDecl is a forward declaration, this loop won't do
1475 // anything except look at designated initializers; That's okay,
1476 // because an error should get printed out elsewhere. It might be
1477 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001478 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001479 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001480 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001481 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001482 while (Index < IList->getNumInits()) {
1483 Expr *Init = IList->getInit(Index);
1484
1485 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001486 // If we're not the subobject that matches up with the '{' for
1487 // the designator, we shouldn't be handling the
1488 // designator. Return immediately.
1489 if (!SubobjectIsDesignatorContext)
1490 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001491
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001492 // Handle this designated initializer. Field will be updated to
1493 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001494 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001495 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001496 StructuredList, StructuredIndex,
1497 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001498 hadError = true;
1499
Douglas Gregora9add4e2009-02-12 19:00:39 +00001500 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001501
1502 // Disable check for missing fields when designators are used.
1503 // This matches gcc behaviour.
1504 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001505 continue;
1506 }
1507
1508 if (Field == FieldEnd) {
1509 // We've run out of fields. We're done.
1510 break;
1511 }
1512
Douglas Gregora9add4e2009-02-12 19:00:39 +00001513 // We've already initialized a member of a union. We're done.
1514 if (InitializedSomething && DeclType->isUnionType())
1515 break;
1516
Douglas Gregor91f84212008-12-11 16:49:14 +00001517 // If we've hit the flexible array member at the end, we're done.
1518 if (Field->getType()->isIncompleteArrayType())
1519 break;
1520
Douglas Gregor51695702009-01-29 16:53:55 +00001521 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001522 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001523 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001524 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001525 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001526
Douglas Gregora82064c2011-06-29 21:51:31 +00001527 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001528 bool InvalidUse;
1529 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00001530 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001531 else
David Blaikie40ed2972012-06-06 20:45:41 +00001532 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001533 IList->getInit(Index)->getLocStart());
1534 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001535 ++Index;
1536 ++Field;
1537 hadError = true;
1538 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001539 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001540
Anders Carlsson6cabf312010-01-23 23:23:01 +00001541 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001542 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001543 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1544 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001545 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001546
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001547 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001548 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00001549 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001550 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001551
1552 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001553 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001554
John McCalle40b58e2010-03-11 19:32:38 +00001555 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001556 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1557 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1558 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001559 // It is possible we have one or more unnamed bitfields remaining.
1560 // Find first (if any) named field and emit warning.
1561 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1562 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00001563 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00001564 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00001565 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00001566 break;
1567 }
1568 }
1569 }
1570
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001571 // Check that any remaining fields can be value-initialized.
1572 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1573 !Field->getType()->isIncompleteArrayType()) {
1574 // FIXME: Should check for holes left by designated initializers too.
1575 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00001576 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00001577 CheckEmptyInitializable(
1578 InitializedEntity::InitializeMember(*Field, &Entity),
1579 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001580 }
1581 }
1582
Mike Stump11289f42009-09-09 15:08:12 +00001583 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001584 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001585 return;
1586
David Blaikie40ed2972012-06-06 20:45:41 +00001587 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00001588 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001589 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001590 ++Index;
1591 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001592 }
1593
Anders Carlsson6cabf312010-01-23 23:23:01 +00001594 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001595 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001596
Anders Carlsson6cabf312010-01-23 23:23:01 +00001597 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001598 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001599 StructuredList, StructuredIndex);
1600 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001601 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001602 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001603}
Steve Narofff8ecff22008-05-01 22:18:59 +00001604
Douglas Gregord5846a12009-04-15 06:41:24 +00001605/// \brief Expand a field designator that refers to a member of an
1606/// anonymous struct or union into a series of field designators that
1607/// refers to the field within the appropriate subobject.
1608///
Douglas Gregord5846a12009-04-15 06:41:24 +00001609static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001610 DesignatedInitExpr *DIE,
1611 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001612 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001613 typedef DesignatedInitExpr::Designator Designator;
1614
Douglas Gregord5846a12009-04-15 06:41:24 +00001615 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001616 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001617 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1618 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1619 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00001620 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00001621 DIE->getDesignator(DesigIdx)->getDotLoc(),
1622 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1623 else
Craig Topperc3ec1492014-05-26 06:22:03 +00001624 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1625 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001626 assert(isa<FieldDecl>(*PI));
1627 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001628 }
1629
1630 // Expand the current designator into the set of replacement
1631 // designators, so we have a full subobject path down to where the
1632 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001633 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001634 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001635}
Mike Stump11289f42009-09-09 15:08:12 +00001636
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001637/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001638/// corresponds to FieldName.
1639static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1640 IdentifierInfo *FieldName) {
Argyrios Kyrtzidis54b10292012-09-10 22:04:26 +00001641 if (!FieldName)
Craig Topperc3ec1492014-05-26 06:22:03 +00001642 return nullptr;
Argyrios Kyrtzidis54b10292012-09-10 22:04:26 +00001643
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001644 assert(AnonField->isAnonymousStructOrUnion());
1645 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman6d1bebb2012-02-09 22:16:56 +00001646 while (IndirectFieldDecl *IF =
1647 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidis54b10292012-09-10 22:04:26 +00001648 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001649 return IF;
1650 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001651 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001652 return nullptr;
Douglas Gregord5846a12009-04-15 06:41:24 +00001653}
1654
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001655static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1656 DesignatedInitExpr *DIE) {
1657 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1658 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1659 for (unsigned I = 0; I < NumIndexExprs; ++I)
1660 IndexExprs[I] = DIE->getSubExpr(I + 1);
1661 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001662 DIE->size(), IndexExprs,
1663 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001664 DIE->usesGNUSyntax(), DIE->getInit());
1665}
1666
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001667namespace {
1668
1669// Callback to only accept typo corrections that are for field members of
1670// the given struct or union.
1671class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1672 public:
1673 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1674 : Record(RD) {}
1675
Craig Toppere14c0f82014-03-12 04:55:44 +00001676 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001677 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1678 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1679 }
1680
1681 private:
1682 RecordDecl *Record;
1683};
1684
1685}
1686
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001687/// @brief Check the well-formedness of a C99 designated initializer.
1688///
1689/// Determines whether the designated initializer @p DIE, which
1690/// resides at the given @p Index within the initializer list @p
1691/// IList, is well-formed for a current object of type @p DeclType
1692/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001693/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001694/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001695///
1696/// @param IList The initializer list in which this designated
1697/// initializer occurs.
1698///
Douglas Gregora5324162009-04-15 04:56:10 +00001699/// @param DIE The designated initializer expression.
1700///
1701/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001702///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00001703/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001704/// into which the designation in @p DIE should refer.
1705///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001706/// @param NextField If non-NULL and the first designator in @p DIE is
1707/// a field, this will be set to the field declaration corresponding
1708/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001709///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001710/// @param NextElementIndex If non-NULL and the first designator in @p
1711/// DIE is an array designator or GNU array-range designator, this
1712/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001713///
1714/// @param Index Index into @p IList where the designated initializer
1715/// @p DIE occurs.
1716///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001717/// @param StructuredList The initializer list expression that
1718/// describes all of the subobject initializers in the order they'll
1719/// actually be initialized.
1720///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001721/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001722bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001723InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001724 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001725 DesignatedInitExpr *DIE,
1726 unsigned DesigIdx,
1727 QualType &CurrentObjectType,
1728 RecordDecl::field_iterator *NextField,
1729 llvm::APSInt *NextElementIndex,
1730 unsigned &Index,
1731 InitListExpr *StructuredList,
1732 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001733 bool FinishSubobjectInit,
1734 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001735 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001736 // Check the actual initialization for the designated object type.
1737 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001738
1739 // Temporarily remove the designator expression from the
1740 // initializer list that the child calls see, so that we don't try
1741 // to re-process the designator.
1742 unsigned OldIndex = Index;
1743 IList->setInit(OldIndex, DIE->getInit());
1744
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001745 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001746 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001747
1748 // Restore the designated initializer expression in the syntactic
1749 // form of the initializer list.
1750 if (IList->getInit(OldIndex) != DIE->getInit())
1751 DIE->setInit(IList->getInit(OldIndex));
1752 IList->setInit(OldIndex, DIE);
1753
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001754 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001755 }
1756
Douglas Gregora5324162009-04-15 04:56:10 +00001757 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001758 bool IsFirstDesignator = (DesigIdx == 0);
1759 if (!VerifyOnly) {
1760 assert((IsFirstDesignator || StructuredList) &&
1761 "Need a non-designated initializer list to start from");
1762
1763 // Determine the structural initializer list that corresponds to the
1764 // current subobject.
Benjamin Kramer6b441d62012-02-23 14:48:40 +00001765 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001766 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1767 StructuredList, StructuredIndex,
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001768 SourceRange(D->getLocStart(),
1769 DIE->getLocEnd()));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001770 assert(StructuredList && "Expected a structured initializer list");
1771 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001772
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001773 if (D->isFieldDesignator()) {
1774 // C99 6.7.8p7:
1775 //
1776 // If a designator has the form
1777 //
1778 // . identifier
1779 //
1780 // then the current object (defined below) shall have
1781 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001782 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001783 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001784 if (!RT) {
1785 SourceLocation Loc = D->getDotLoc();
1786 if (Loc.isInvalid())
1787 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001788 if (!VerifyOnly)
1789 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001790 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001791 ++Index;
1792 return true;
1793 }
1794
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001795 // Note: we perform a linear search of the fields here, despite
1796 // the fact that we have a faster lookup method, because we always
1797 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001798 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001799 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001800 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001801 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001802 Field = RT->getDecl()->field_begin(),
1803 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001804 for (; Field != FieldEnd; ++Field) {
1805 if (Field->isUnnamedBitfield())
1806 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001807
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001808 // If we find a field representing an anonymous field, look in the
1809 // IndirectFieldDecl that follow for the designated initializer.
1810 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1811 if (IndirectFieldDecl *IF =
David Blaikie40ed2972012-06-06 20:45:41 +00001812 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001813 // In verify mode, don't modify the original.
1814 if (VerifyOnly)
1815 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001816 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1817 D = DIE->getDesignator(DesigIdx);
1818 break;
1819 }
1820 }
David Blaikie40ed2972012-06-06 20:45:41 +00001821 if (KnownField && KnownField == *Field)
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001822 break;
1823 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001824 break;
1825
1826 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001827 }
1828
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001829 if (Field == FieldEnd) {
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001830 if (VerifyOnly) {
1831 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001832 return true; // No typo correction when just trying this out.
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001833 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001834
Douglas Gregord5846a12009-04-15 06:41:24 +00001835 // There was no normal field in the struct with the designated
1836 // name. Perform another lookup for this name, which may find
1837 // something that we can't designate (e.g., a member function),
1838 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001839 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001840 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Craig Topperc3ec1492014-05-26 06:22:03 +00001841 FieldDecl *ReplacementField = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00001842 if (Lookup.empty()) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001843 // Name lookup didn't find anything. Determine whether this
1844 // was a typo for another field name.
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001845 FieldInitializerValidatorCCC Validator(RT->getDecl());
Richard Smithf9b15102013-08-17 00:46:16 +00001846 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
1847 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Craig Topperc3ec1492014-05-26 06:22:03 +00001848 Sema::LookupMemberName, /*Scope=*/ nullptr, /*SS=*/ nullptr,
1849 Validator, Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00001850 SemaRef.diagnoseTypo(
1851 Corrected,
1852 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
1853 << FieldName << CurrentObjectType);
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001854 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001855 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001856 } else {
1857 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1858 << FieldName << CurrentObjectType;
1859 ++Index;
1860 return true;
1861 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001862 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001863
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001864 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001865 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001866 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001867 << FieldName;
David Blaikieff7d47a2012-12-19 00:45:41 +00001868 SemaRef.Diag(Lookup.front()->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001869 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001870 ++Index;
1871 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001872 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001873
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001874 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001875 // The replacement field comes from typo correction; find it
1876 // in the list of fields.
1877 FieldIndex = 0;
1878 Field = RT->getDecl()->field_begin();
1879 for (; Field != FieldEnd; ++Field) {
1880 if (Field->isUnnamedBitfield())
1881 continue;
1882
David Blaikie40ed2972012-06-06 20:45:41 +00001883 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001884 Field->getIdentifier() == ReplacementField->getIdentifier())
1885 break;
1886
1887 ++FieldIndex;
1888 }
1889 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001890 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001891
1892 // All of the fields of a union are located at the same place in
1893 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001894 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001895 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00001896 if (!VerifyOnly) {
1897 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
1898 if (CurrentField && CurrentField != *Field) {
1899 assert(StructuredList->getNumInits() == 1
1900 && "A union should never have more than one initializer!");
1901
1902 // we're about to throw away an initializer, emit warning
1903 SemaRef.Diag(D->getFieldLoc(),
1904 diag::warn_initializer_overrides)
1905 << D->getSourceRange();
1906 Expr *ExistingInit = StructuredList->getInit(0);
1907 SemaRef.Diag(ExistingInit->getLocStart(),
1908 diag::note_previous_initializer)
1909 << /*FIXME:has side effects=*/0
1910 << ExistingInit->getSourceRange();
1911
1912 // remove existing initializer
1913 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00001914 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00001915 }
1916
David Blaikie40ed2972012-06-06 20:45:41 +00001917 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00001918 }
Douglas Gregor51695702009-01-29 16:53:55 +00001919 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001920
Douglas Gregora82064c2011-06-29 21:51:31 +00001921 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001922 bool InvalidUse;
1923 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00001924 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001925 else
David Blaikie40ed2972012-06-06 20:45:41 +00001926 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001927 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001928 ++Index;
1929 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001930 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001931
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001932 if (!VerifyOnly) {
1933 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00001934 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001935
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001936 // Make sure that our non-designated initializer list has space
1937 // for a subobject corresponding to this field.
1938 if (FieldIndex >= StructuredList->getNumInits())
1939 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1940 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001941
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001942 // This designator names a flexible array member.
1943 if (Field->getType()->isIncompleteArrayType()) {
1944 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001945 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001946 // We can't designate an object within the flexible array
1947 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001948 if (!VerifyOnly) {
1949 DesignatedInitExpr::Designator *NextD
1950 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001951 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001952 diag::err_designator_into_flexible_array_member)
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001953 << SourceRange(NextD->getLocStart(),
1954 DIE->getLocEnd());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001955 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00001956 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001957 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001958 Invalid = true;
1959 }
1960
Chris Lattner001b29c2010-10-10 17:49:49 +00001961 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1962 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001963 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001964 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001965 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001966 diag::err_flexible_array_init_needs_braces)
1967 << DIE->getInit()->getSourceRange();
1968 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00001969 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001970 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001971 Invalid = true;
1972 }
1973
Eli Friedman3fa64df2011-08-23 22:24:57 +00001974 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00001975 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00001976 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001977 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001978
1979 if (Invalid) {
1980 ++Index;
1981 return true;
1982 }
1983
1984 // Initialize the array.
1985 bool prevHadError = hadError;
1986 unsigned newStructuredIndex = FieldIndex;
1987 unsigned OldIndex = Index;
1988 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001989
1990 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001991 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001992 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001993 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001994
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001995 IList->setInit(OldIndex, DIE);
1996 if (hadError && !prevHadError) {
1997 ++Field;
1998 ++FieldIndex;
1999 if (NextField)
2000 *NextField = Field;
2001 StructuredIndex = FieldIndex;
2002 return true;
2003 }
2004 } else {
2005 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002006 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002007 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002008
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002009 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002010 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002011 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002012 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002013 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002014 true, false))
2015 return true;
2016 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002017
2018 // Find the position of the next field to be initialized in this
2019 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002020 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002021 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002022
2023 // If this the first designator, our caller will continue checking
2024 // the rest of this struct/class/union subobject.
2025 if (IsFirstDesignator) {
2026 if (NextField)
2027 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002028 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002029 return false;
2030 }
2031
Douglas Gregor17bd0942009-01-28 23:36:17 +00002032 if (!FinishSubobjectInit)
2033 return false;
2034
Douglas Gregord5846a12009-04-15 06:41:24 +00002035 // We've already initialized something in the union; we're done.
2036 if (RT->getDecl()->isUnion())
2037 return hadError;
2038
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002039 // Check the remaining fields within this class/struct/union subobject.
2040 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002041
Anders Carlsson6cabf312010-01-23 23:23:01 +00002042 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002043 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002044 return hadError && !prevHadError;
2045 }
2046
2047 // C99 6.7.8p6:
2048 //
2049 // If a designator has the form
2050 //
2051 // [ constant-expression ]
2052 //
2053 // then the current object (defined below) shall have array
2054 // type and the expression shall be an integer constant
2055 // expression. If the array is of unknown size, any
2056 // nonnegative value is valid.
2057 //
2058 // Additionally, cope with the GNU extension that permits
2059 // designators of the form
2060 //
2061 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002062 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002063 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002064 if (!VerifyOnly)
2065 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2066 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002067 ++Index;
2068 return true;
2069 }
2070
Craig Topperc3ec1492014-05-26 06:22:03 +00002071 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002072 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2073 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002074 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002075 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002076 DesignatedEndIndex = DesignatedStartIndex;
2077 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002078 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002079
Mike Stump11289f42009-09-09 15:08:12 +00002080 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002081 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002082 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002083 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002084 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002085
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002086 // Codegen can't handle evaluating array range designators that have side
2087 // effects, because we replicate the AST value for each initialized element.
2088 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2089 // elements with something that has a side effect, so codegen can emit an
2090 // "error unsupported" error instead of miscompiling the app.
2091 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002092 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002093 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002094 }
2095
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002096 if (isa<ConstantArrayType>(AT)) {
2097 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002098 DesignatedStartIndex
2099 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002100 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002101 DesignatedEndIndex
2102 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002103 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2104 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002105 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002106 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002107 diag::err_array_designator_too_large)
2108 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2109 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002110 ++Index;
2111 return true;
2112 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002113 } else {
2114 // Make sure the bit-widths and signedness match.
2115 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002116 DesignatedEndIndex
2117 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002118 else if (DesignatedStartIndex.getBitWidth() <
2119 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002120 DesignatedStartIndex
2121 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002122 DesignatedStartIndex.setIsUnsigned(true);
2123 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002124 }
Mike Stump11289f42009-09-09 15:08:12 +00002125
Eli Friedman1f16b742013-06-11 21:48:11 +00002126 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2127 // We're modifying a string literal init; we have to decompose the string
2128 // so we can modify the individual characters.
2129 ASTContext &Context = SemaRef.Context;
2130 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2131
2132 // Compute the character type
2133 QualType CharTy = AT->getElementType();
2134
2135 // Compute the type of the integer literals.
2136 QualType PromotedCharTy = CharTy;
2137 if (CharTy->isPromotableIntegerType())
2138 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2139 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2140
2141 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2142 // Get the length of the string.
2143 uint64_t StrLen = SL->getLength();
2144 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2145 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2146 StructuredList->resizeInits(Context, StrLen);
2147
2148 // Build a literal for each character in the string, and put them into
2149 // the init list.
2150 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2151 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2152 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002153 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002154 if (CharTy != PromotedCharTy)
2155 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002156 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002157 StructuredList->updateInit(Context, i, Init);
2158 }
2159 } else {
2160 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2161 std::string Str;
2162 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2163
2164 // Get the length of the string.
2165 uint64_t StrLen = Str.size();
2166 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2167 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2168 StructuredList->resizeInits(Context, StrLen);
2169
2170 // Build a literal for each character in the string, and put them into
2171 // the init list.
2172 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2173 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2174 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002175 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002176 if (CharTy != PromotedCharTy)
2177 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002178 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002179 StructuredList->updateInit(Context, i, Init);
2180 }
2181 }
2182 }
2183
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002184 // Make sure that our non-designated initializer list has space
2185 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002186 if (!VerifyOnly &&
2187 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002188 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002189 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002190
Douglas Gregor17bd0942009-01-28 23:36:17 +00002191 // Repeatedly perform subobject initializations in the range
2192 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002193
Douglas Gregor17bd0942009-01-28 23:36:17 +00002194 // Move to the next designator
2195 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2196 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002197
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002198 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002199 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002200
Douglas Gregor17bd0942009-01-28 23:36:17 +00002201 while (DesignatedStartIndex <= DesignatedEndIndex) {
2202 // Recurse to check later designated subobjects.
2203 QualType ElementType = AT->getElementType();
2204 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002205
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002206 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002207 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002208 ElementType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002209 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002210 (DesignatedStartIndex == DesignatedEndIndex),
2211 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002212 return true;
2213
2214 // Move to the next index in the array that we'll be initializing.
2215 ++DesignatedStartIndex;
2216 ElementIndex = DesignatedStartIndex.getZExtValue();
2217 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002218
2219 // If this the first designator, our caller will continue checking
2220 // the rest of this array subobject.
2221 if (IsFirstDesignator) {
2222 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002223 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002224 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002225 return false;
2226 }
Mike Stump11289f42009-09-09 15:08:12 +00002227
Douglas Gregor17bd0942009-01-28 23:36:17 +00002228 if (!FinishSubobjectInit)
2229 return false;
2230
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002231 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002232 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002233 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002234 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002235 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002236 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002237}
2238
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002239// Get the structured initializer list for a subobject of type
2240// @p CurrentObjectType.
2241InitListExpr *
2242InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2243 QualType CurrentObjectType,
2244 InitListExpr *StructuredList,
2245 unsigned StructuredIndex,
2246 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002247 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002248 return nullptr; // No structured list in verification-only mode.
2249 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002250 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002251 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002252 else if (StructuredIndex < StructuredList->getNumInits())
2253 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002254
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002255 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2256 return Result;
2257
2258 if (ExistingInit) {
2259 // We are creating an initializer list that initializes the
2260 // subobjects of the current object, but there was already an
2261 // initialization that completely initialized the current
2262 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002263 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002264 // struct X { int a, b; };
2265 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002266 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002267 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2268 // designated initializer re-initializes the whole
2269 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002270 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002271 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002272 << InitRange;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002273 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002274 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002275 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002276 << ExistingInit->getSourceRange();
2277 }
2278
Mike Stump11289f42009-09-09 15:08:12 +00002279 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002280 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002281 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002282 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002283
Eli Friedman91f5ae52012-02-23 02:25:10 +00002284 QualType ResultType = CurrentObjectType;
2285 if (!ResultType->isArrayType())
2286 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2287 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002288
Douglas Gregor6d00c992009-03-20 23:58:33 +00002289 // Pre-allocate storage for the structured initializer list.
2290 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002291 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002292 bool GotNumInits = false;
2293 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002294 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002295 GotNumInits = true;
2296 } else if (Index < IList->getNumInits()) {
2297 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002298 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002299 GotNumInits = true;
2300 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002301 }
2302
Mike Stump11289f42009-09-09 15:08:12 +00002303 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002304 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2305 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2306 NumElements = CAType->getSize().getZExtValue();
2307 // Simple heuristic so that we don't allocate a very large
2308 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002309 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002310 NumElements = 0;
2311 }
John McCall9dd450b2009-09-21 23:43:11 +00002312 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002313 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002314 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002315 RecordDecl *RDecl = RType->getDecl();
2316 if (RDecl->isUnion())
2317 NumElements = 1;
2318 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002319 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002320 }
2321
Ted Kremenekac034612010-04-13 23:39:13 +00002322 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002323
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002324 // Link this new initializer list into the structured initializer
2325 // lists.
2326 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002327 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002328 else {
2329 Result->setSyntacticForm(IList);
2330 SyntacticToSemantic[IList] = Result;
2331 }
2332
2333 return Result;
2334}
2335
2336/// Update the initializer at index @p StructuredIndex within the
2337/// structured initializer list to the value @p expr.
2338void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2339 unsigned &StructuredIndex,
2340 Expr *expr) {
2341 // No structured initializer list to update
2342 if (!StructuredList)
2343 return;
2344
Ted Kremenekac034612010-04-13 23:39:13 +00002345 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2346 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002347 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002348 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002349 diag::warn_initializer_overrides)
2350 << expr->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002351 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002352 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002353 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002354 << PrevInit->getSourceRange();
2355 }
Mike Stump11289f42009-09-09 15:08:12 +00002356
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002357 ++StructuredIndex;
2358}
2359
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002360/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002361/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002362/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002363/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002364/// failure. Returns the index expression, possibly with an implicit cast
2365/// added, on success. If everything went okay, Value will receive the
2366/// value of the constant expression.
2367static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002368CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002369 SourceLocation Loc = Index->getLocStart();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002370
2371 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002372 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2373 if (Result.isInvalid())
2374 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002375
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002376 if (Value.isSigned() && Value.isNegative())
2377 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002378 << Value.toString(10) << Index->getSourceRange();
2379
Douglas Gregor51650d32009-01-23 21:04:18 +00002380 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002381 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002382}
2383
John McCalldadc5752010-08-24 06:29:42 +00002384ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002385 SourceLocation Loc,
2386 bool GNUSyntax,
2387 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002388 typedef DesignatedInitExpr::Designator ASTDesignator;
2389
2390 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002391 SmallVector<ASTDesignator, 32> Designators;
2392 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002393
2394 // Build designators and check array designator expressions.
2395 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2396 const Designator &D = Desig.getDesignator(Idx);
2397 switch (D.getKind()) {
2398 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002399 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002400 D.getFieldLoc()));
2401 break;
2402
2403 case Designator::ArrayDesignator: {
2404 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2405 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002406 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002407 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002408 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002409 Invalid = true;
2410 else {
2411 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002412 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002413 D.getRBracketLoc()));
2414 InitExpressions.push_back(Index);
2415 }
2416 break;
2417 }
2418
2419 case Designator::ArrayRangeDesignator: {
2420 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2421 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2422 llvm::APSInt StartValue;
2423 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002424 bool StartDependent = StartIndex->isTypeDependent() ||
2425 StartIndex->isValueDependent();
2426 bool EndDependent = EndIndex->isTypeDependent() ||
2427 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002428 if (!StartDependent)
2429 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002430 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002431 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002432 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002433
2434 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002435 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002436 else {
2437 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002438 if (StartDependent || EndDependent) {
2439 // Nothing to compute.
2440 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002441 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002442 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002443 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002444
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002445 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002446 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002447 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002448 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2449 Invalid = true;
2450 } else {
2451 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002452 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002453 D.getEllipsisLoc(),
2454 D.getRBracketLoc()));
2455 InitExpressions.push_back(StartIndex);
2456 InitExpressions.push_back(EndIndex);
2457 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002458 }
2459 break;
2460 }
2461 }
2462 }
2463
2464 if (Invalid || Init.isInvalid())
2465 return ExprError();
2466
2467 // Clear out the expressions within the designation.
2468 Desig.ClearExprs(*this);
2469
2470 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002471 = DesignatedInitExpr::Create(Context,
2472 Designators.data(), Designators.size(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00002473 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002474 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002475
David Blaikiebbafb8a2012-03-11 07:00:24 +00002476 if (!getLangOpts().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002477 Diag(DIE->getLocStart(), diag::ext_designated_init)
2478 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002479
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002480 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002481}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002482
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002483//===----------------------------------------------------------------------===//
2484// Initialization entity
2485//===----------------------------------------------------------------------===//
2486
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002487InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002488 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002489 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002490{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002491 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2492 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002493 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002494 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002495 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002496 Type = VT->getElementType();
2497 } else {
2498 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2499 assert(CT && "Unexpected type");
2500 Kind = EK_ComplexElement;
2501 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002502 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002503}
2504
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002505InitializedEntity
2506InitializedEntity::InitializeBase(ASTContext &Context,
2507 const CXXBaseSpecifier *Base,
2508 bool IsInheritedVirtualBase) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002509 InitializedEntity Result;
2510 Result.Kind = EK_Base;
Craig Topperc3ec1492014-05-26 06:22:03 +00002511 Result.Parent = nullptr;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002512 Result.Base = reinterpret_cast<uintptr_t>(Base);
2513 if (IsInheritedVirtualBase)
2514 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002515
Douglas Gregor1b303932009-12-22 15:35:07 +00002516 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002517 return Result;
2518}
2519
Douglas Gregor85dabae2009-12-16 01:38:02 +00002520DeclarationName InitializedEntity::getName() const {
2521 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002522 case EK_Parameter:
2523 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00002524 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2525 return (D ? D->getDeclName() : DeclarationName());
2526 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002527
2528 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002529 case EK_Member:
2530 return VariableOrMember->getDeclName();
2531
Douglas Gregor19666fb2012-02-15 16:57:26 +00002532 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002533 return DeclarationName(Capture.VarID);
Douglas Gregor19666fb2012-02-15 16:57:26 +00002534
Douglas Gregor85dabae2009-12-16 01:38:02 +00002535 case EK_Result:
2536 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002537 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002538 case EK_Temporary:
2539 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002540 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002541 case EK_ArrayElement:
2542 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002543 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002544 case EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002545 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002546 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002547 return DeclarationName();
2548 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002549
David Blaikie8a40f702012-01-17 06:56:22 +00002550 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002551}
2552
Douglas Gregora4b592a2009-12-19 03:01:41 +00002553DeclaratorDecl *InitializedEntity::getDecl() const {
2554 switch (getKind()) {
2555 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002556 case EK_Member:
2557 return VariableOrMember;
2558
John McCall31168b02011-06-15 23:02:42 +00002559 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002560 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00002561 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2562
Douglas Gregora4b592a2009-12-19 03:01:41 +00002563 case EK_Result:
2564 case EK_Exception:
2565 case EK_New:
2566 case EK_Temporary:
2567 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002568 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002569 case EK_ArrayElement:
2570 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002571 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002572 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002573 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002574 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002575 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00002576 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00002577 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002578
David Blaikie8a40f702012-01-17 06:56:22 +00002579 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002580}
2581
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002582bool InitializedEntity::allowsNRVO() const {
2583 switch (getKind()) {
2584 case EK_Result:
2585 case EK_Exception:
2586 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002587
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002588 case EK_Variable:
2589 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002590 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002591 case EK_Member:
2592 case EK_New:
2593 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002594 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002595 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002596 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002597 case EK_ArrayElement:
2598 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002599 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002600 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002601 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002602 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002603 break;
2604 }
2605
2606 return false;
2607}
2608
Richard Smithe6c01442013-06-05 00:46:14 +00002609unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00002610 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00002611 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2612 for (unsigned I = 0; I != Depth; ++I)
2613 OS << "`-";
2614
2615 switch (getKind()) {
2616 case EK_Variable: OS << "Variable"; break;
2617 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002618 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2619 break;
Richard Smithe6c01442013-06-05 00:46:14 +00002620 case EK_Result: OS << "Result"; break;
2621 case EK_Exception: OS << "Exception"; break;
2622 case EK_Member: OS << "Member"; break;
2623 case EK_New: OS << "New"; break;
2624 case EK_Temporary: OS << "Temporary"; break;
2625 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002626 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00002627 case EK_Base: OS << "Base"; break;
2628 case EK_Delegating: OS << "Delegating"; break;
2629 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2630 case EK_VectorElement: OS << "VectorElement " << Index; break;
2631 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2632 case EK_BlockElement: OS << "Block"; break;
2633 case EK_LambdaCapture:
2634 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002635 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00002636 break;
2637 }
2638
2639 if (Decl *D = getDecl()) {
2640 OS << " ";
2641 cast<NamedDecl>(D)->printQualifiedName(OS);
2642 }
2643
2644 OS << " '" << getType().getAsString() << "'\n";
2645
2646 return Depth + 1;
2647}
2648
2649void InitializedEntity::dump() const {
2650 dumpImpl(llvm::errs());
2651}
2652
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002653//===----------------------------------------------------------------------===//
2654// Initialization sequence
2655//===----------------------------------------------------------------------===//
2656
2657void InitializationSequence::Step::Destroy() {
2658 switch (Kind) {
2659 case SK_ResolveAddressOfOverloadedFunction:
2660 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002661 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002662 case SK_CastDerivedToBaseLValue:
2663 case SK_BindReference:
2664 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002665 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002666 case SK_UserConversion:
2667 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002668 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002669 case SK_QualificationConversionLValue:
Jordan Roseb1312a52013-04-11 00:58:58 +00002670 case SK_LValueToRValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002671 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002672 case SK_ListConstructorCall:
Sebastian Redl29526f02011-11-27 16:50:07 +00002673 case SK_UnwrapInitList:
2674 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002675 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002676 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002677 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002678 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002679 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002680 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00002681 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002682 case SK_PassByIndirectCopyRestore:
2683 case SK_PassByIndirectRestore:
2684 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002685 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00002686 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002687 case SK_OCLZeroEvent:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002688 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002689
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002690 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00002691 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002692 delete ICS;
2693 }
2694}
2695
Douglas Gregor838fcc32010-03-26 20:14:36 +00002696bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002697 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002698}
2699
2700bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002701 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002702 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002703
Douglas Gregor838fcc32010-03-26 20:14:36 +00002704 switch (getFailureKind()) {
2705 case FK_TooManyInitsForReference:
2706 case FK_ArrayNeedsInitList:
2707 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00002708 case FK_ArrayNeedsInitListOrWideStringLiteral:
2709 case FK_NarrowStringIntoWideCharArray:
2710 case FK_WideStringIntoCharArray:
2711 case FK_IncompatWideStringIntoWideChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002712 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2713 case FK_NonConstLValueReferenceBindingToTemporary:
2714 case FK_NonConstLValueReferenceBindingToUnrelated:
2715 case FK_RValueReferenceBindingToLValue:
2716 case FK_ReferenceInitDropsQualifiers:
2717 case FK_ReferenceInitFailed:
2718 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002719 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002720 case FK_TooManyInitsForScalar:
2721 case FK_ReferenceBindingToInitList:
2722 case FK_InitListBadDestinationType:
2723 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002724 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002725 case FK_ArrayTypeMismatch:
2726 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002727 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002728 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002729 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00002730 case FK_ExplicitConstructor:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002731 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002732
Douglas Gregor838fcc32010-03-26 20:14:36 +00002733 case FK_ReferenceInitOverloadFailed:
2734 case FK_UserConversionOverloadFailed:
2735 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002736 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002737 return FailedOverloadResult == OR_Ambiguous;
2738 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002739
David Blaikie8a40f702012-01-17 06:56:22 +00002740 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00002741}
2742
Douglas Gregorb33eed02010-04-16 22:09:46 +00002743bool InitializationSequence::isConstructorInitialization() const {
2744 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2745}
2746
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002747void
2748InitializationSequence
2749::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2750 DeclAccessPair Found,
2751 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002752 Step S;
2753 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2754 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002755 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002756 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002757 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002758 Steps.push_back(S);
2759}
2760
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002761void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002762 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002763 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002764 switch (VK) {
2765 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2766 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2767 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002768 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002769 S.Type = BaseType;
2770 Steps.push_back(S);
2771}
2772
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002773void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002774 bool BindingTemporary) {
2775 Step S;
2776 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2777 S.Type = T;
2778 Steps.push_back(S);
2779}
2780
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002781void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2782 Step S;
2783 S.Kind = SK_ExtraneousCopyToTemporary;
2784 S.Type = T;
2785 Steps.push_back(S);
2786}
2787
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002788void
2789InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2790 DeclAccessPair FoundDecl,
2791 QualType T,
2792 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002793 Step S;
2794 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002795 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002796 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002797 S.Function.Function = Function;
2798 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002799 Steps.push_back(S);
2800}
2801
2802void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002803 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002804 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002805 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002806 switch (VK) {
2807 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002808 S.Kind = SK_QualificationConversionRValue;
2809 break;
John McCall2536c6d2010-08-25 10:28:54 +00002810 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002811 S.Kind = SK_QualificationConversionXValue;
2812 break;
John McCall2536c6d2010-08-25 10:28:54 +00002813 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002814 S.Kind = SK_QualificationConversionLValue;
2815 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002816 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002817 S.Type = Ty;
2818 Steps.push_back(S);
2819}
2820
Jordan Roseb1312a52013-04-11 00:58:58 +00002821void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2822 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2823
2824 Step S;
2825 S.Kind = SK_LValueToRValue;
2826 S.Type = Ty;
2827 Steps.push_back(S);
2828}
2829
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002830void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00002831 const ImplicitConversionSequence &ICS, QualType T,
2832 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002833 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00002834 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
2835 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002836 S.Type = T;
2837 S.ICS = new ImplicitConversionSequence(ICS);
2838 Steps.push_back(S);
2839}
2840
Douglas Gregor51e77d52009-12-10 17:56:55 +00002841void InitializationSequence::AddListInitializationStep(QualType T) {
2842 Step S;
2843 S.Kind = SK_ListInitialization;
2844 S.Type = T;
2845 Steps.push_back(S);
2846}
2847
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002848void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002849InitializationSequence
2850::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2851 AccessSpecifier Access,
2852 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002853 bool HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002854 bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002855 Step S;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002856 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2857 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002858 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002859 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002860 S.Function.Function = Constructor;
2861 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002862 Steps.push_back(S);
2863}
2864
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002865void InitializationSequence::AddZeroInitializationStep(QualType T) {
2866 Step S;
2867 S.Kind = SK_ZeroInitialization;
2868 S.Type = T;
2869 Steps.push_back(S);
2870}
2871
Douglas Gregore1314a62009-12-18 05:02:21 +00002872void InitializationSequence::AddCAssignmentStep(QualType T) {
2873 Step S;
2874 S.Kind = SK_CAssignment;
2875 S.Type = T;
2876 Steps.push_back(S);
2877}
2878
Eli Friedman78275202009-12-19 08:11:05 +00002879void InitializationSequence::AddStringInitStep(QualType T) {
2880 Step S;
2881 S.Kind = SK_StringInit;
2882 S.Type = T;
2883 Steps.push_back(S);
2884}
2885
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002886void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2887 Step S;
2888 S.Kind = SK_ObjCObjectConversion;
2889 S.Type = T;
2890 Steps.push_back(S);
2891}
2892
Douglas Gregore2f943b2011-02-22 18:29:51 +00002893void InitializationSequence::AddArrayInitStep(QualType T) {
2894 Step S;
2895 S.Kind = SK_ArrayInit;
2896 S.Type = T;
2897 Steps.push_back(S);
2898}
2899
Richard Smithebeed412012-02-15 22:38:09 +00002900void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2901 Step S;
2902 S.Kind = SK_ParenthesizedArrayInit;
2903 S.Type = T;
2904 Steps.push_back(S);
2905}
2906
John McCall31168b02011-06-15 23:02:42 +00002907void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2908 bool shouldCopy) {
2909 Step s;
2910 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2911 : SK_PassByIndirectRestore);
2912 s.Type = type;
2913 Steps.push_back(s);
2914}
2915
2916void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2917 Step S;
2918 S.Kind = SK_ProduceObjCObject;
2919 S.Type = T;
2920 Steps.push_back(S);
2921}
2922
Sebastian Redlc1839b12012-01-17 22:49:42 +00002923void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2924 Step S;
2925 S.Kind = SK_StdInitializerList;
2926 S.Type = T;
2927 Steps.push_back(S);
2928}
2929
Guy Benyei61054192013-02-07 10:55:47 +00002930void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
2931 Step S;
2932 S.Kind = SK_OCLSamplerInit;
2933 S.Type = T;
2934 Steps.push_back(S);
2935}
2936
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002937void InitializationSequence::AddOCLZeroEventStep(QualType T) {
2938 Step S;
2939 S.Kind = SK_OCLZeroEvent;
2940 S.Type = T;
2941 Steps.push_back(S);
2942}
2943
Sebastian Redl29526f02011-11-27 16:50:07 +00002944void InitializationSequence::RewrapReferenceInitList(QualType T,
2945 InitListExpr *Syntactic) {
2946 assert(Syntactic->getNumInits() == 1 &&
2947 "Can only rewrap trivial init lists.");
2948 Step S;
2949 S.Kind = SK_UnwrapInitList;
2950 S.Type = Syntactic->getInit(0)->getType();
2951 Steps.insert(Steps.begin(), S);
2952
2953 S.Kind = SK_RewrapInitList;
2954 S.Type = T;
2955 S.WrappingSyntacticList = Syntactic;
2956 Steps.push_back(S);
2957}
2958
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002959void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002960 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002961 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002962 this->Failure = Failure;
2963 this->FailedOverloadResult = Result;
2964}
2965
2966//===----------------------------------------------------------------------===//
2967// Attempt initialization
2968//===----------------------------------------------------------------------===//
2969
John McCall31168b02011-06-15 23:02:42 +00002970static void MaybeProduceObjCObject(Sema &S,
2971 InitializationSequence &Sequence,
2972 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002973 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00002974
2975 /// When initializing a parameter, produce the value if it's marked
2976 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002977 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00002978 if (!Entity.isParameterConsumed())
2979 return;
2980
2981 assert(Entity.getType()->isObjCRetainableType() &&
2982 "consuming an object of unretainable type?");
2983 Sequence.AddProduceObjCObjectStep(Entity.getType());
2984
2985 /// When initializing a return value, if the return type is a
2986 /// retainable type, then returns need to immediately retain the
2987 /// object. If an autorelease is required, it will be done at the
2988 /// last instant.
2989 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2990 if (!Entity.getType()->isObjCRetainableType())
2991 return;
2992
2993 Sequence.AddProduceObjCObjectStep(Entity.getType());
2994 }
2995}
2996
Richard Smithcc1b96d2013-06-12 22:31:48 +00002997static void TryListInitialization(Sema &S,
2998 const InitializedEntity &Entity,
2999 const InitializationKind &Kind,
3000 InitListExpr *InitList,
3001 InitializationSequence &Sequence);
3002
Richard Smithd86812d2012-07-05 08:39:21 +00003003/// \brief When initializing from init list via constructor, handle
3004/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003005///
Richard Smithd86812d2012-07-05 08:39:21 +00003006/// \return true if we have handled initialization of an object of type
3007/// std::initializer_list<T>, false otherwise.
3008static bool TryInitializerListConstruction(Sema &S,
3009 InitListExpr *List,
3010 QualType DestType,
3011 InitializationSequence &Sequence) {
3012 QualType E;
3013 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003014 return false;
3015
Richard Smithcc1b96d2013-06-12 22:31:48 +00003016 if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
3017 Sequence.setIncompleteTypeFailure(E);
3018 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003019 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003020
3021 // Try initializing a temporary array from the init list.
3022 QualType ArrayType = S.Context.getConstantArrayType(
3023 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3024 List->getNumInits()),
3025 clang::ArrayType::Normal, 0);
3026 InitializedEntity HiddenArray =
3027 InitializedEntity::InitializeTemporary(ArrayType);
3028 InitializationKind Kind =
3029 InitializationKind::CreateDirectList(List->getExprLoc());
3030 TryListInitialization(S, HiddenArray, Kind, List, Sequence);
3031 if (Sequence)
3032 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003033 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003034}
3035
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003036static OverloadingResult
3037ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003038 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003039 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003040 ArrayRef<NamedDecl *> Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003041 OverloadCandidateSet::iterator &Best,
3042 bool CopyInitializing, bool AllowExplicit,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003043 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003044 CandidateSet.clear();
3045
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003046 for (ArrayRef<NamedDecl *>::iterator
3047 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003048 NamedDecl *D = *Con;
3049 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3050 bool SuppressUserConversions = false;
3051
3052 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003053 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003054 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3055 if (ConstructorTmpl)
3056 Constructor = cast<CXXConstructorDecl>(
3057 ConstructorTmpl->getTemplatedDecl());
3058 else {
3059 Constructor = cast<CXXConstructorDecl>(D);
3060
Richard Smith6c6ddab2013-09-21 21:23:47 +00003061 // C++11 [over.best.ics]p4:
3062 // However, when considering the argument of a constructor or
3063 // user-defined conversion function that is a candidate:
3064 // -- by 13.3.1.3 when invoked for the copying/moving of a temporary
3065 // in the second step of a class copy-initialization,
3066 // -- by 13.3.1.7 when passing the initializer list as a single
3067 // argument or when the initializer list has exactly one elementand
3068 // a conversion to some class X or reference to (possibly
3069 // cv-qualified) X is considered for the first parameter of a
3070 // constructor of X, or
3071 // -- by 13.3.1.4, 13.3.1.5, or 13.3.1.6 in all cases,
3072 // only standard conversion sequences and ellipsis conversion sequences
3073 // are considered.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003074 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003075 Constructor->isCopyOrMoveConstructor())
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003076 SuppressUserConversions = true;
3077 }
3078
3079 if (!Constructor->isInvalidDecl() &&
3080 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003081 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003082 if (ConstructorTmpl)
3083 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003084 /*ExplicitArgs*/ nullptr, Args,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003085 CandidateSet, SuppressUserConversions);
Douglas Gregor6073dca2012-02-24 23:56:31 +00003086 else {
3087 // C++ [over.match.copy]p1:
3088 // - When initializing a temporary to be bound to the first parameter
3089 // of a constructor that takes a reference to possibly cv-qualified
3090 // T as its first argument, called with a single argument in the
3091 // context of direct-initialization, explicit conversion functions
3092 // are also considered.
3093 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003094 Args.size() == 1 &&
Douglas Gregor6073dca2012-02-24 23:56:31 +00003095 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003096 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003097 SuppressUserConversions,
3098 /*PartialOverloading=*/false,
3099 /*AllowExplicit=*/AllowExplicitConv);
3100 }
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003101 }
3102 }
3103
3104 // Perform overload resolution and return the result.
3105 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3106}
3107
Sebastian Redled2e5322011-12-22 14:44:04 +00003108/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3109/// enumerates the constructors of the initialized entity and performs overload
3110/// resolution to select the best.
Sebastian Redl88e4d492012-02-04 21:27:33 +00003111/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redled2e5322011-12-22 14:44:04 +00003112/// class type.
3113static void TryConstructorInitialization(Sema &S,
3114 const InitializedEntity &Entity,
3115 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003116 MultiExprArg Args, QualType DestType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003117 InitializationSequence &Sequence,
Sebastian Redl88e4d492012-02-04 21:27:33 +00003118 bool InitListSyntax = false) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003119 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Sebastian Redl88e4d492012-02-04 21:27:33 +00003120 "InitListSyntax must come with a single initializer list argument.");
3121
Sebastian Redled2e5322011-12-22 14:44:04 +00003122 // The type we're constructing needs to be complete.
3123 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003124 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003125 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003126 }
3127
3128 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3129 assert(DestRecordType && "Constructor initialization requires record type");
3130 CXXRecordDecl *DestRecordDecl
3131 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3132
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003133 // Build the candidate set directly in the initialization sequence
3134 // structure, so that it will persist if we fail.
3135 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3136
3137 // Determine whether we are allowed to call explicit constructors or
3138 // explicit conversion operators.
Sebastian Redl048a6d72012-04-01 19:54:59 +00003139 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003140 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003141
Sebastian Redled2e5322011-12-22 14:44:04 +00003142 // - Otherwise, if T is a class type, constructors are considered. The
3143 // applicable constructors are enumerated, and the best one is chosen
3144 // through overload resolution.
David Blaikieff7d47a2012-12-19 00:45:41 +00003145 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003146 // The container holding the constructors can under certain conditions
3147 // be changed while iterating (e.g. because of deserialization).
3148 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003149 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redled2e5322011-12-22 14:44:04 +00003150
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003151 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003152 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003153 bool AsInitializerList = false;
3154
3155 // C++11 [over.match.list]p1:
3156 // When objects of non-aggregate type T are list-initialized, overload
3157 // resolution selects the constructor in two phases:
3158 // - Initially, the candidate functions are the initializer-list
3159 // constructors of the class T and the argument list consists of the
3160 // initializer list as a single argument.
3161 if (InitListSyntax) {
Richard Smithd86812d2012-07-05 08:39:21 +00003162 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003163 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003164
3165 // If the initializer list has no elements and T has a default constructor,
3166 // the first phase is omitted.
Richard Smith2be35f52012-12-01 02:35:44 +00003167 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003168 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003169 CandidateSet, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003170 CopyInitialization, AllowExplicit,
3171 /*OnlyListConstructor=*/true,
3172 InitListSyntax);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003173
3174 // Time to unwrap the init list.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003175 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003176 }
3177
3178 // C++11 [over.match.list]p1:
3179 // - If no viable initializer-list constructor is found, overload resolution
3180 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003181 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003182 // elements of the initializer list.
3183 if (Result == OR_No_Viable_Function) {
3184 AsInitializerList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003185 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003186 CandidateSet, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003187 CopyInitialization, AllowExplicit,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003188 /*OnlyListConstructors=*/false,
3189 InitListSyntax);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003190 }
3191 if (Result) {
Sebastian Redl88e4d492012-02-04 21:27:33 +00003192 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003193 InitializationSequence::FK_ListConstructorOverloadFailed :
3194 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003195 Result);
3196 return;
3197 }
3198
Richard Smithd86812d2012-07-05 08:39:21 +00003199 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003200 // If a program calls for the default initialization of an object
3201 // of a const-qualified type T, T shall be a class type with a
3202 // user-provided default constructor.
3203 if (Kind.getKind() == InitializationKind::IK_Default &&
3204 Entity.getType().isConstQualified() &&
Aaron Ballman899b9c62012-07-31 22:40:31 +00003205 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redled2e5322011-12-22 14:44:04 +00003206 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3207 return;
3208 }
3209
Sebastian Redl048a6d72012-04-01 19:54:59 +00003210 // C++11 [over.match.list]p1:
3211 // In copy-list-initialization, if an explicit constructor is chosen, the
3212 // initializer is ill-formed.
3213 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3214 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3215 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3216 return;
3217 }
3218
Sebastian Redled2e5322011-12-22 14:44:04 +00003219 // Add the constructor initialization step. Any cv-qualification conversion is
3220 // subsumed by the initialization.
3221 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redled2e5322011-12-22 14:44:04 +00003222 Sequence.AddConstructorInitializationStep(CtorDecl,
3223 Best->FoundDecl.getAccess(),
3224 DestType, HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003225 InitListSyntax, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003226}
3227
Sebastian Redl29526f02011-11-27 16:50:07 +00003228static bool
3229ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3230 Expr *Initializer,
3231 QualType &SourceType,
3232 QualType &UnqualifiedSourceType,
3233 QualType UnqualifiedTargetType,
3234 InitializationSequence &Sequence) {
3235 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3236 S.Context.OverloadTy) {
3237 DeclAccessPair Found;
3238 bool HadMultipleCandidates = false;
3239 if (FunctionDecl *Fn
3240 = S.ResolveAddressOfOverloadedFunction(Initializer,
3241 UnqualifiedTargetType,
3242 false, Found,
3243 &HadMultipleCandidates)) {
3244 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3245 HadMultipleCandidates);
3246 SourceType = Fn->getType();
3247 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3248 } else if (!UnqualifiedTargetType->isRecordType()) {
3249 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3250 return true;
3251 }
3252 }
3253 return false;
3254}
3255
3256static void TryReferenceInitializationCore(Sema &S,
3257 const InitializedEntity &Entity,
3258 const InitializationKind &Kind,
3259 Expr *Initializer,
3260 QualType cv1T1, QualType T1,
3261 Qualifiers T1Quals,
3262 QualType cv2T2, QualType T2,
3263 Qualifiers T2Quals,
3264 InitializationSequence &Sequence);
3265
Richard Smithd86812d2012-07-05 08:39:21 +00003266static void TryValueInitialization(Sema &S,
3267 const InitializedEntity &Entity,
3268 const InitializationKind &Kind,
3269 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00003270 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00003271
Sebastian Redl29526f02011-11-27 16:50:07 +00003272/// \brief Attempt list initialization of a reference.
3273static void TryReferenceListInitialization(Sema &S,
3274 const InitializedEntity &Entity,
3275 const InitializationKind &Kind,
3276 InitListExpr *InitList,
Richard Smithfaadef72013-06-08 00:02:08 +00003277 InitializationSequence &Sequence) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003278 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003279 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003280 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3281 return;
3282 }
3283
3284 QualType DestType = Entity.getType();
3285 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3286 Qualifiers T1Quals;
3287 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3288
3289 // Reference initialization via an initializer list works thus:
3290 // If the initializer list consists of a single element that is
3291 // reference-related to the referenced type, bind directly to that element
3292 // (possibly creating temporaries).
3293 // Otherwise, initialize a temporary with the initializer list and
3294 // bind to that.
3295 if (InitList->getNumInits() == 1) {
3296 Expr *Initializer = InitList->getInit(0);
3297 QualType cv2T2 = Initializer->getType();
3298 Qualifiers T2Quals;
3299 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3300
3301 // If this fails, creating a temporary wouldn't work either.
3302 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3303 T1, Sequence))
3304 return;
3305
3306 SourceLocation DeclLoc = Initializer->getLocStart();
3307 bool dummy1, dummy2, dummy3;
3308 Sema::ReferenceCompareResult RefRelationship
3309 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3310 dummy2, dummy3);
3311 if (RefRelationship >= Sema::Ref_Related) {
3312 // Try to bind the reference here.
3313 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3314 T1Quals, cv2T2, T2, T2Quals, Sequence);
3315 if (Sequence)
3316 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3317 return;
3318 }
Richard Smith03d93932013-01-15 07:58:29 +00003319
3320 // Update the initializer if we've resolved an overloaded function.
3321 if (Sequence.step_begin() != Sequence.step_end())
3322 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00003323 }
3324
3325 // Not reference-related. Create a temporary and bind to that.
3326 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3327
3328 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3329 if (Sequence) {
3330 if (DestType->isRValueReferenceType() ||
3331 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3332 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3333 else
3334 Sequence.SetFailed(
3335 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3336 }
3337}
3338
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003339/// \brief Attempt list initialization (C++0x [dcl.init.list])
3340static void TryListInitialization(Sema &S,
3341 const InitializedEntity &Entity,
3342 const InitializationKind &Kind,
3343 InitListExpr *InitList,
3344 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003345 QualType DestType = Entity.getType();
3346
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003347 // C++ doesn't allow scalar initialization with more than one argument.
3348 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003349 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003350 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3351 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3352 return;
3353 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003354 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003355 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003356 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003357 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003358 if (DestType->isRecordType()) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003359 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003360 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl4f28b582012-02-19 12:27:43 +00003361 return;
3362 }
3363
Richard Smithd86812d2012-07-05 08:39:21 +00003364 // C++11 [dcl.init.list]p3:
3365 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redl4f28b582012-02-19 12:27:43 +00003366 if (!DestType->isAggregateType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003367 if (S.getLangOpts().CPlusPlus11) {
Richard Smithd86812d2012-07-05 08:39:21 +00003368 // - Otherwise, if the initializer list has no elements and T is a
3369 // class type with a default constructor, the object is
3370 // value-initialized.
3371 if (InitList->getNumInits() == 0) {
3372 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
Richard Smith2be35f52012-12-01 02:35:44 +00003373 if (RD->hasDefaultConstructor()) {
Richard Smithd86812d2012-07-05 08:39:21 +00003374 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3375 return;
3376 }
3377 }
3378
3379 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3380 // an initializer_list object constructed [...]
3381 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3382 return;
3383
3384 // - Otherwise, if T is a class type, constructors are considered.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003385 Expr *InitListAsExpr = InitList;
3386 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smithd86812d2012-07-05 08:39:21 +00003387 Sequence, /*InitListSyntax*/true);
Sebastian Redl4f28b582012-02-19 12:27:43 +00003388 } else
3389 Sequence.SetFailed(
3390 InitializationSequence::FK_InitListBadDestinationType);
3391 return;
3392 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003393 }
Richard Smith089c3162013-09-21 21:55:46 +00003394 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
3395 InitList->getNumInits() == 1 &&
3396 InitList->getInit(0)->getType()->isRecordType()) {
3397 // - Otherwise, if the initializer list has a single element of type E
3398 // [...references are handled above...], the object or reference is
3399 // initialized from that element; if a narrowing conversion is required
3400 // to convert the element to T, the program is ill-formed.
3401 //
3402 // Per core-24034, this is direct-initialization if we were performing
3403 // direct-list-initialization and copy-initialization otherwise.
3404 // We can't use InitListChecker for this, because it always performs
3405 // copy-initialization. This only matters if we might use an 'explicit'
3406 // conversion operator, so we only need to handle the cases where the source
3407 // is of record type.
3408 InitializationKind SubKind =
3409 Kind.getKind() == InitializationKind::IK_DirectList
3410 ? InitializationKind::CreateDirect(Kind.getLocation(),
3411 InitList->getLBraceLoc(),
3412 InitList->getRBraceLoc())
3413 : Kind;
3414 Expr *SubInit[1] = { InitList->getInit(0) };
3415 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3416 /*TopLevelOfInitList*/true);
3417 if (Sequence)
3418 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3419 return;
3420 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003421
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003422 InitListChecker CheckInitList(S, Entity, InitList,
Richard Smithde229232013-06-06 11:41:05 +00003423 DestType, /*VerifyOnly=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003424 if (CheckInitList.HadError()) {
3425 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3426 return;
3427 }
3428
3429 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003430 Sequence.AddListInitializationStep(DestType);
3431}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003432
3433/// \brief Try a reference initialization that involves calling a conversion
3434/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003435static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3436 const InitializedEntity &Entity,
3437 const InitializationKind &Kind,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003438 Expr *Initializer,
3439 bool AllowRValues,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003440 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003441 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003442 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3443 QualType T1 = cv1T1.getUnqualifiedType();
3444 QualType cv2T2 = Initializer->getType();
3445 QualType T2 = cv2T2.getUnqualifiedType();
3446
3447 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003448 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003449 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003450 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003451 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003452 ObjCConversion,
3453 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003454 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003455 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003456 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003457 (void)ObjCLifetimeConversion;
3458
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003459 // Build the candidate set directly in the initialization sequence
3460 // structure, so that it will persist if we fail.
3461 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3462 CandidateSet.clear();
3463
3464 // Determine whether we are allowed to call explicit constructors or
3465 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003466 bool AllowExplicit = Kind.AllowExplicit();
Richard Smith6c6ddab2013-09-21 21:23:47 +00003467 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3468
Craig Topperc3ec1492014-05-26 06:22:03 +00003469 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003470 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3471 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003472 // The type we're converting to is a class type. Enumerate its constructors
3473 // to see if there is a suitable conversion.
3474 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003475
David Blaikieff7d47a2012-12-19 00:45:41 +00003476 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003477 // The container holding the constructors can under certain conditions
3478 // be changed while iterating (e.g. because of deserialization).
3479 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003480 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00003481 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003482 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3483 NamedDecl *D = *CI;
John McCalla0296f72010-03-19 07:35:19 +00003484 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3485
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003486 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003487 CXXConstructorDecl *Constructor = nullptr;
John McCalla0296f72010-03-19 07:35:19 +00003488 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003489 if (ConstructorTmpl)
3490 Constructor = cast<CXXConstructorDecl>(
3491 ConstructorTmpl->getTemplatedDecl());
3492 else
John McCalla0296f72010-03-19 07:35:19 +00003493 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003494
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003495 if (!Constructor->isInvalidDecl() &&
3496 Constructor->isConvertingConstructor(AllowExplicit)) {
3497 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003498 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003499 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003500 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003501 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003502 else
John McCalla0296f72010-03-19 07:35:19 +00003503 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003504 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003505 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003506 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003507 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003508 }
John McCall3696dcb2010-08-17 07:23:57 +00003509 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3510 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003511
Craig Topperc3ec1492014-05-26 06:22:03 +00003512 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003513 if ((T2RecordType = T2->getAs<RecordType>()) &&
3514 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003515 // The type we're converting from is a class type, enumerate its conversion
3516 // functions.
3517 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3518
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003519 std::pair<CXXRecordDecl::conversion_iterator,
3520 CXXRecordDecl::conversion_iterator>
3521 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3522 for (CXXRecordDecl::conversion_iterator
3523 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003524 NamedDecl *D = *I;
3525 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3526 if (isa<UsingShadowDecl>(D))
3527 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003528
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003529 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3530 CXXConversionDecl *Conv;
3531 if (ConvTemplate)
3532 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3533 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003534 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003535
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003536 // If the conversion function doesn't return a reference type,
3537 // it can't be considered for this conversion unless we're allowed to
3538 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003539 // FIXME: Do we need to make sure that we only consider conversion
3540 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003541 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00003542 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003543 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3544 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003545 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003546 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00003547 DestType, CandidateSet,
3548 /*AllowObjCConversionOnExplicit=*/
3549 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003550 else
John McCalla0296f72010-03-19 07:35:19 +00003551 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00003552 Initializer, DestType, CandidateSet,
3553 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003554 }
3555 }
3556 }
John McCall3696dcb2010-08-17 07:23:57 +00003557 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3558 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003559
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003560 SourceLocation DeclLoc = Initializer->getLocStart();
3561
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003562 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003563 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003564 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003565 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003566 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003567
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003568 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00003569 // This is the overload that will be used for this initialization step if we
3570 // use this initialization. Mark it as referenced.
3571 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00003572
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003573 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003574 if (isa<CXXConversionDecl>(Function))
Alp Toker314cc812014-01-25 16:55:45 +00003575 T2 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003576 else
3577 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003578
3579 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003580 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003581 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003582 T2.getNonLValueExprType(S.Context),
3583 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003584
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003585 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003586 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003587 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003588 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003589 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003590 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003591 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003592
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003593 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003594 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003595 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003596 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003597 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003598 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003599 NewDerivedToBase, NewObjCConversion,
3600 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003601 if (NewRefRelationship == Sema::Ref_Incompatible) {
3602 // If the type we've converted to is not reference-related to the
3603 // type we're looking for, then there is another conversion step
3604 // we need to perform to produce a temporary of the right type
3605 // that we'll be binding to.
3606 ImplicitConversionSequence ICS;
3607 ICS.setStandard();
3608 ICS.Standard = Best->FinalConversion;
3609 T2 = ICS.Standard.getToType(2);
3610 Sequence.AddConversionSequenceStep(ICS, T2);
3611 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003612 Sequence.AddDerivedToBaseCastStep(
3613 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003614 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003615 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003616 else if (NewObjCConversion)
3617 Sequence.AddObjCObjectConversionStep(
3618 S.Context.getQualifiedType(T1,
3619 T2.getNonReferenceType().getQualifiers()));
3620
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003621 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003622 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003623
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003624 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3625 return OR_Success;
3626}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003627
Richard Smithc620f552011-10-19 16:55:56 +00003628static void CheckCXX98CompatAccessibleCopy(Sema &S,
3629 const InitializedEntity &Entity,
3630 Expr *CurInitExpr);
3631
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003632/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3633static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003634 const InitializedEntity &Entity,
3635 const InitializationKind &Kind,
3636 Expr *Initializer,
3637 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003638 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003639 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003640 Qualifiers T1Quals;
3641 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003642 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003643 Qualifiers T2Quals;
3644 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003645
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003646 // If the initializer is the address of an overloaded function, try
3647 // to resolve the overloaded function. If all goes well, T2 is the
3648 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003649 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3650 T1, Sequence))
3651 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003652
Sebastian Redl29526f02011-11-27 16:50:07 +00003653 // Delegate everything else to a subfunction.
3654 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3655 T1Quals, cv2T2, T2, T2Quals, Sequence);
3656}
3657
Jordan Roseb1312a52013-04-11 00:58:58 +00003658/// Converts the target of reference initialization so that it has the
3659/// appropriate qualifiers and value kind.
3660///
3661/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3662/// \code
3663/// int x;
3664/// const int &r = x;
3665/// \endcode
3666///
3667/// In this case the reference is binding to a bitfield lvalue, which isn't
3668/// valid. Perform a load to create a lifetime-extended temporary instead.
3669/// \code
3670/// const int &r = someStruct.bitfield;
3671/// \endcode
3672static ExprValueKind
3673convertQualifiersAndValueKindIfNecessary(Sema &S,
3674 InitializationSequence &Sequence,
3675 Expr *Initializer,
3676 QualType cv1T1,
3677 Qualifiers T1Quals,
3678 Qualifiers T2Quals,
3679 bool IsLValueRef) {
John McCalld25db7e2013-05-06 21:39:12 +00003680 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Roseb1312a52013-04-11 00:58:58 +00003681 Initializer->refersToVectorElement();
3682
3683 if (IsNonAddressableType) {
3684 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3685 // lvalue reference to a non-volatile const type, or the reference shall be
3686 // an rvalue reference.
3687 //
3688 // If not, we can't make a temporary and bind to that. Give up and allow the
3689 // error to be diagnosed later.
3690 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3691 assert(Initializer->isGLValue());
3692 return Initializer->getValueKind();
3693 }
3694
3695 // Force a load so we can materialize a temporary.
3696 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3697 return VK_RValue;
3698 }
3699
3700 if (T1Quals != T2Quals) {
3701 Sequence.AddQualificationConversionStep(cv1T1,
3702 Initializer->getValueKind());
3703 }
3704
3705 return Initializer->getValueKind();
3706}
3707
3708
Sebastian Redl29526f02011-11-27 16:50:07 +00003709/// \brief Reference initialization without resolving overloaded functions.
3710static void TryReferenceInitializationCore(Sema &S,
3711 const InitializedEntity &Entity,
3712 const InitializationKind &Kind,
3713 Expr *Initializer,
3714 QualType cv1T1, QualType T1,
3715 Qualifiers T1Quals,
3716 QualType cv2T2, QualType T2,
3717 Qualifiers T2Quals,
3718 InitializationSequence &Sequence) {
3719 QualType DestType = Entity.getType();
3720 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003721 // Compute some basic properties of the types and the initializer.
3722 bool isLValueRef = DestType->isLValueReferenceType();
3723 bool isRValueRef = !isLValueRef;
3724 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003725 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003726 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003727 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003728 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003729 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003730 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003731
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003732 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003733 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003734 // "cv2 T2" as follows:
3735 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003736 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003737 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00003738 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00003739 // there are no function rvalues in C++, rvalue refs to functions are treated
3740 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003741 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003742 bool T1Function = T1->isFunctionType();
3743 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003744 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003745 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003746 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003747 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003748 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003749 // reference-compatible with "cv2 T2," or
3750 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003751 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003752 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003753 // can occur. However, we do pay attention to whether it is a bit-field
3754 // to decide whether we're actually binding to a temporary created from
3755 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003756 if (DerivedToBase)
3757 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003758 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003759 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003760 else if (ObjCConversion)
3761 Sequence.AddObjCObjectConversionStep(
3762 S.Context.getQualifiedType(T1, T2Quals));
3763
Jordan Roseb1312a52013-04-11 00:58:58 +00003764 ExprValueKind ValueKind =
3765 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3766 cv1T1, T1Quals, T2Quals,
3767 isLValueRef);
3768 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003769 return;
3770 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003771
3772 // - has a class type (i.e., T2 is a class type), where T1 is not
3773 // reference-related to T2, and can be implicitly converted to an
3774 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3775 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003776 // applicable conversion functions (13.3.1.6) and choosing the best
3777 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003778 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00003779 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00003780 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3781 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003782 ConvOvlResult = TryRefInitWithConversionFunction(
3783 S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003784 if (ConvOvlResult == OR_Success)
3785 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00003786 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00003787 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003788 InitializationSequence::FK_ReferenceInitOverloadFailed,
3789 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003790 }
3791 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003792
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003793 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003794 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003795 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003796 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003797 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3798 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3799 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003800 Sequence.SetOverloadFailure(
3801 InitializationSequence::FK_ReferenceInitOverloadFailed,
3802 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003803 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003804 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003805 ? (RefRelationship == Sema::Ref_Related
3806 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3807 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3808 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003809
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003810 return;
3811 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003812
Douglas Gregor92e460e2011-01-20 16:44:54 +00003813 // - If the initializer expression
3814 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3815 // "cv1 T1" is reference-compatible with "cv2 T2"
3816 // Note: functions are handled below.
3817 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003818 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003819 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003820 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003821 (InitCategory.isXValue() ||
3822 (InitCategory.isPRValue() && T2->isRecordType()) ||
3823 (InitCategory.isPRValue() && T2->isArrayType()))) {
3824 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3825 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003826 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3827 // compiler the freedom to perform a copy here or bind to the
3828 // object, while C++0x requires that we bind directly to the
3829 // object. Hence, we always bind to the object without making an
3830 // extra copy. However, in C++03 requires that we check for the
3831 // presence of a suitable copy constructor:
3832 //
3833 // The constructor that would be used to make the copy shall
3834 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003835 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003836 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003837 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00003838 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003839 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003840
Douglas Gregor92e460e2011-01-20 16:44:54 +00003841 if (DerivedToBase)
3842 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3843 ValueKind);
3844 else if (ObjCConversion)
3845 Sequence.AddObjCObjectConversionStep(
3846 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003847
Jordan Roseb1312a52013-04-11 00:58:58 +00003848 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3849 Initializer, cv1T1,
3850 T1Quals, T2Quals,
3851 isLValueRef);
3852
3853 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003854 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003855 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003856
3857 // - has a class type (i.e., T2 is a class type), where T1 is not
3858 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003859 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3860 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00003861 //
3862 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00003863 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003864 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003865 ConvOvlResult = TryRefInitWithConversionFunction(
3866 S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003867 if (ConvOvlResult)
3868 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003869 InitializationSequence::FK_ReferenceInitOverloadFailed,
3870 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003871
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003872 return;
3873 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003874
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00003875 if ((RefRelationship == Sema::Ref_Compatible ||
3876 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3877 isRValueRef && InitCategory.isLValue()) {
3878 Sequence.SetFailed(
3879 InitializationSequence::FK_RValueReferenceBindingToLValue);
3880 return;
3881 }
3882
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003883 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3884 return;
3885 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003886
3887 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003888 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00003889 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003890 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003891
John McCallec6f4e92010-06-04 02:29:22 +00003892 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3893
Richard Smith2eabf782013-06-13 00:57:57 +00003894 // FIXME: Why do we use an implicit conversion here rather than trying
3895 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00003896 ImplicitConversionSequence ICS
3897 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00003898 /*SuppressUserConversions=*/false,
3899 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003900 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003901 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3902 /*AllowObjCWritebackConversion=*/false);
3903
3904 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003905 // FIXME: Use the conversion function set stored in ICS to turn
3906 // this into an overloading ambiguity diagnostic. However, we need
3907 // to keep that set as an OverloadCandidateSet rather than as some
3908 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003909 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3910 Sequence.SetOverloadFailure(
3911 InitializationSequence::FK_ReferenceInitOverloadFailed,
3912 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003913 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3914 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003915 else
3916 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003917 return;
John McCall31168b02011-06-15 23:02:42 +00003918 } else {
3919 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003920 }
3921
3922 // [...] If T1 is reference-related to T2, cv1 must be the
3923 // same cv-qualification as, or greater cv-qualification
3924 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003925 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3926 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003927 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003928 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003929 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3930 return;
3931 }
3932
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003933 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003934 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003935 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003936 InitCategory.isLValue()) {
3937 Sequence.SetFailed(
3938 InitializationSequence::FK_RValueReferenceBindingToLValue);
3939 return;
3940 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003941
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003942 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3943 return;
3944}
3945
3946/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003947/// (C++ [dcl.init.string], C99 6.7.8).
3948static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003949 const InitializedEntity &Entity,
3950 const InitializationKind &Kind,
3951 Expr *Initializer,
3952 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003953 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003954}
3955
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003956/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003957static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003958 const InitializedEntity &Entity,
3959 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00003960 InitializationSequence &Sequence,
3961 InitListExpr *InitList) {
3962 assert((!InitList || InitList->getNumInits() == 0) &&
3963 "Shouldn't use value-init for non-empty init lists");
3964
Richard Smith1bfe0682012-02-14 21:14:13 +00003965 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003966 //
3967 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003968 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003969
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003970 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00003971 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003972
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003973 if (const RecordType *RT = T->getAs<RecordType>()) {
3974 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00003975 bool NeedZeroInitialization = true;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003976 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithd86812d2012-07-05 08:39:21 +00003977 // C++98:
3978 // -- if T is a class type (clause 9) with a user-declared constructor
3979 // (12.1), then the default constructor for T is called (and the
3980 // initialization is ill-formed if T has no accessible default
3981 // constructor);
Richard Smith1bfe0682012-02-14 21:14:13 +00003982 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithd86812d2012-07-05 08:39:21 +00003983 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00003984 } else {
3985 // C++11:
3986 // -- if T is a class type (clause 9) with either no default constructor
3987 // (12.1 [class.ctor]) or a default constructor that is user-provided
3988 // or deleted, then the object is default-initialized;
3989 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3990 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithd86812d2012-07-05 08:39:21 +00003991 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00003992 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003993
Richard Smith1bfe0682012-02-14 21:14:13 +00003994 // -- if T is a (possibly cv-qualified) non-union class type without a
3995 // user-provided or deleted default constructor, then the object is
3996 // zero-initialized and, if T has a non-trivial default constructor,
3997 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00003998 // The 'non-union' here was removed by DR1502. The 'non-trivial default
3999 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004000 if (NeedZeroInitialization)
4001 Sequence.AddZeroInitializationStep(Entity.getType());
4002
Richard Smith593f9932012-12-08 02:01:17 +00004003 // C++03:
4004 // -- if T is a non-union class type without a user-declared constructor,
4005 // then every non-static data member and base class component of T is
4006 // value-initialized;
4007 // [...] A program that calls for [...] value-initialization of an
4008 // entity of reference type is ill-formed.
4009 //
4010 // C++11 doesn't need this handling, because value-initialization does not
4011 // occur recursively there, and the implicit default constructor is
4012 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004013 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004014 ClassDecl->hasUninitializedReferenceMember()) {
4015 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4016 return;
4017 }
4018
Richard Smithd86812d2012-07-05 08:39:21 +00004019 // If this is list-value-initialization, pass the empty init list on when
4020 // building the constructor call. This affects the semantics of a few
4021 // things (such as whether an explicit default constructor can be called).
4022 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004023 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004024 bool InitListSyntax = InitList;
4025
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004026 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4027 InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004028 }
4029 }
4030
Douglas Gregor1b303932009-12-22 15:35:07 +00004031 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004032}
4033
Douglas Gregor85dabae2009-12-16 01:38:02 +00004034/// \brief Attempt default initialization (C++ [dcl.init]p6).
4035static void TryDefaultInitialization(Sema &S,
4036 const InitializedEntity &Entity,
4037 const InitializationKind &Kind,
4038 InitializationSequence &Sequence) {
4039 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004040
Douglas Gregor85dabae2009-12-16 01:38:02 +00004041 // C++ [dcl.init]p6:
4042 // To default-initialize an object of type T means:
4043 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004044 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4045
Douglas Gregor85dabae2009-12-16 01:38:02 +00004046 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4047 // constructor for T is called (and the initialization is ill-formed if
4048 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004049 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004050 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004051 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004052 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004053
Douglas Gregor85dabae2009-12-16 01:38:02 +00004054 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004055
Douglas Gregor85dabae2009-12-16 01:38:02 +00004056 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004057 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004058 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004059 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004060 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004061 return;
4062 }
4063
4064 // If the destination type has a lifetime property, zero-initialize it.
4065 if (DestType.getQualifiers().hasObjCLifetime()) {
4066 Sequence.AddZeroInitializationStep(Entity.getType());
4067 return;
4068 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004069}
4070
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004071/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4072/// which enumerates all conversion functions and performs overload resolution
4073/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004074static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004075 const InitializedEntity &Entity,
4076 const InitializationKind &Kind,
4077 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004078 InitializationSequence &Sequence,
4079 bool TopLevelOfInitList) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004080 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004081 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4082 QualType SourceType = Initializer->getType();
4083 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4084 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004085
Douglas Gregor540c3b02009-12-14 17:27:33 +00004086 // Build the candidate set directly in the initialization sequence
4087 // structure, so that it will persist if we fail.
4088 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4089 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004090
Douglas Gregor540c3b02009-12-14 17:27:33 +00004091 // Determine whether we are allowed to call explicit constructors or
4092 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004093 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004094
Douglas Gregor540c3b02009-12-14 17:27:33 +00004095 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4096 // The type we're converting to is a class type. Enumerate its constructors
4097 // to see if there is a suitable conversion.
4098 CXXRecordDecl *DestRecordDecl
4099 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004100
Douglas Gregord9848152010-04-26 14:36:57 +00004101 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004102 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004103 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie12be6392012-10-18 16:57:32 +00004104 // The container holding the constructors can under certain conditions
4105 // be changed while iterating. To be safe we copy the lookup results
4106 // to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004107 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004108 for (SmallVectorImpl<NamedDecl *>::iterator
David Blaikie12be6392012-10-18 16:57:32 +00004109 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregord9848152010-04-26 14:36:57 +00004110 Con != ConEnd; ++Con) {
4111 NamedDecl *D = *Con;
4112 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004113
Douglas Gregord9848152010-04-26 14:36:57 +00004114 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00004115 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregord9848152010-04-26 14:36:57 +00004116 FunctionTemplateDecl *ConstructorTmpl
4117 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004118 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00004119 Constructor = cast<CXXConstructorDecl>(
4120 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00004121 else
Douglas Gregord9848152010-04-26 14:36:57 +00004122 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004123
Douglas Gregord9848152010-04-26 14:36:57 +00004124 if (!Constructor->isInvalidDecl() &&
4125 Constructor->isConvertingConstructor(AllowExplicit)) {
4126 if (ConstructorTmpl)
4127 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004128 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004129 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004130 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004131 else
4132 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004133 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004134 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004135 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004136 }
Douglas Gregord9848152010-04-26 14:36:57 +00004137 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004138 }
Eli Friedman78275202009-12-19 08:11:05 +00004139
4140 SourceLocation DeclLoc = Initializer->getLocStart();
4141
Douglas Gregor540c3b02009-12-14 17:27:33 +00004142 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4143 // The type we're converting from is a class type, enumerate its conversion
4144 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004145
Eli Friedman4afe9a32009-12-20 22:12:03 +00004146 // We can only enumerate the conversion functions for a complete type; if
4147 // the type isn't complete, simply skip this step.
4148 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4149 CXXRecordDecl *SourceRecordDecl
4150 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004151
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004152 std::pair<CXXRecordDecl::conversion_iterator,
4153 CXXRecordDecl::conversion_iterator>
4154 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4155 for (CXXRecordDecl::conversion_iterator
4156 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004157 NamedDecl *D = *I;
4158 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4159 if (isa<UsingShadowDecl>(D))
4160 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004161
Eli Friedman4afe9a32009-12-20 22:12:03 +00004162 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4163 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004164 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004165 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004166 else
John McCallda4458e2010-03-31 01:36:47 +00004167 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004168
Eli Friedman4afe9a32009-12-20 22:12:03 +00004169 if (AllowExplicit || !Conv->isExplicit()) {
4170 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004171 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004172 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004173 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004174 else
John McCalla0296f72010-03-19 07:35:19 +00004175 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004176 Initializer, DestType, CandidateSet,
4177 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004178 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004179 }
4180 }
4181 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004182
4183 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004184 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004185 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00004186 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004187 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004188 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004189 Result);
4190 return;
4191 }
John McCall0d1da222010-01-12 00:44:57 +00004192
Douglas Gregor540c3b02009-12-14 17:27:33 +00004193 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004194 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004195 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004196
Douglas Gregor540c3b02009-12-14 17:27:33 +00004197 if (isa<CXXConstructorDecl>(Function)) {
4198 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004199 // subsumed by the initialization. Per DR5, the created temporary is of the
4200 // cv-unqualified type of the destination.
4201 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4202 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004203 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004204 return;
4205 }
4206
4207 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004208 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004209 if (ConvType->getAs<RecordType>()) {
Richard Smithb24f0672012-02-11 19:22:50 +00004210 // If we're converting to a class type, there may be an copy of
Douglas Gregor5ab11652010-04-17 22:01:05 +00004211 // the resulting temporary object (possible to create an object of
4212 // a base class type). That copy is not a separate conversion, so
4213 // we just make a note of the actual destination type (possibly a
4214 // base class of the type returned by the conversion function) and
4215 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004216 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4217 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004218 return;
4219 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004220
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004221 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4222 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004223
Douglas Gregor5ab11652010-04-17 22:01:05 +00004224 // If the conversion following the call to the conversion function
4225 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004226 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4227 Best->FinalConversion.Third) {
4228 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004229 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004230 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004231 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004232 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004233}
4234
Richard Smithf032001b2013-06-20 02:18:31 +00004235/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4236/// a function with a pointer return type contains a 'return false;' statement.
4237/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4238/// code using that header.
4239///
4240/// Work around this by treating 'return false;' as zero-initializing the result
4241/// if it's used in a pointer-returning function in a system header.
4242static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4243 const InitializedEntity &Entity,
4244 const Expr *Init) {
4245 return S.getLangOpts().CPlusPlus11 &&
4246 Entity.getKind() == InitializedEntity::EK_Result &&
4247 Entity.getType()->isPointerType() &&
4248 isa<CXXBoolLiteralExpr>(Init) &&
4249 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4250 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4251}
4252
John McCall31168b02011-06-15 23:02:42 +00004253/// The non-zero enum values here are indexes into diagnostic alternatives.
4254enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4255
4256/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00004257static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004258 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00004259 // Skip parens.
4260 e = e->IgnoreParens();
4261
4262 // Skip address-of nodes.
4263 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4264 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004265 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4266 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004267
4268 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00004269 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4270 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00004271 case CK_Dependent:
4272 case CK_BitCast:
4273 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00004274 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004275 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004276
4277 case CK_ArrayToPointerDecay:
4278 return IIK_nonscalar;
4279
4280 case CK_NullToPointer:
4281 return IIK_okay;
4282
4283 default:
4284 break;
4285 }
4286
4287 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00004288 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004289 // set isWeakAccess to true, to mean that there will be an implicit
4290 // load which requires a cleanup.
4291 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4292 isWeakAccess = true;
4293
John McCall63f84442011-06-27 23:59:58 +00004294 if (!isAddressOf) return IIK_nonlocal;
4295
John McCall113bee02012-03-10 09:33:50 +00004296 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4297 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00004298
4299 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00004300
4301 // If we have a conditional operator, check both sides.
4302 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004303 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4304 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00004305 return iik;
4306
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004307 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004308
4309 // These are never scalar.
4310 } else if (isa<ArraySubscriptExpr>(e)) {
4311 return IIK_nonscalar;
4312
4313 // Otherwise, it needs to be a null pointer constant.
4314 } else {
4315 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4316 ? IIK_okay : IIK_nonlocal);
4317 }
4318
4319 return IIK_nonlocal;
4320}
4321
4322/// Check whether the given expression is a valid operand for an
4323/// indirect copy/restore.
4324static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4325 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004326 bool isWeakAccess = false;
4327 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4328 // If isWeakAccess to true, there will be an implicit
4329 // load which requires a cleanup.
4330 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4331 S.ExprNeedsCleanups = true;
4332
John McCall31168b02011-06-15 23:02:42 +00004333 if (iik == IIK_okay) return;
4334
4335 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4336 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4337 << src->getSourceRange();
4338}
4339
Douglas Gregore2f943b2011-02-22 18:29:51 +00004340/// \brief Determine whether we have compatible array types for the
4341/// purposes of GNU by-copy array initialization.
4342static bool hasCompatibleArrayTypes(ASTContext &Context,
4343 const ArrayType *Dest,
4344 const ArrayType *Source) {
4345 // If the source and destination array types are equivalent, we're
4346 // done.
4347 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4348 return true;
4349
4350 // Make sure that the element types are the same.
4351 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4352 return false;
4353
4354 // The only mismatch we allow is when the destination is an
4355 // incomplete array type and the source is a constant array type.
4356 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4357}
4358
John McCall31168b02011-06-15 23:02:42 +00004359static bool tryObjCWritebackConversion(Sema &S,
4360 InitializationSequence &Sequence,
4361 const InitializedEntity &Entity,
4362 Expr *Initializer) {
4363 bool ArrayDecay = false;
4364 QualType ArgType = Initializer->getType();
4365 QualType ArgPointee;
4366 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4367 ArrayDecay = true;
4368 ArgPointee = ArgArrayType->getElementType();
4369 ArgType = S.Context.getPointerType(ArgPointee);
4370 }
4371
4372 // Handle write-back conversion.
4373 QualType ConvertedArgType;
4374 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4375 ConvertedArgType))
4376 return false;
4377
4378 // We should copy unless we're passing to an argument explicitly
4379 // marked 'out'.
4380 bool ShouldCopy = true;
4381 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4382 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4383
4384 // Do we need an lvalue conversion?
4385 if (ArrayDecay || Initializer->isGLValue()) {
4386 ImplicitConversionSequence ICS;
4387 ICS.setStandard();
4388 ICS.Standard.setAsIdentityConversion();
4389
4390 QualType ResultType;
4391 if (ArrayDecay) {
4392 ICS.Standard.First = ICK_Array_To_Pointer;
4393 ResultType = S.Context.getPointerType(ArgPointee);
4394 } else {
4395 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4396 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4397 }
4398
4399 Sequence.AddConversionSequenceStep(ICS, ResultType);
4400 }
4401
4402 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4403 return true;
4404}
4405
Guy Benyei61054192013-02-07 10:55:47 +00004406static bool TryOCLSamplerInitialization(Sema &S,
4407 InitializationSequence &Sequence,
4408 QualType DestType,
4409 Expr *Initializer) {
4410 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4411 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4412 return false;
4413
4414 Sequence.AddOCLSamplerInitStep(DestType);
4415 return true;
4416}
4417
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004418//
4419// OpenCL 1.2 spec, s6.12.10
4420//
4421// The event argument can also be used to associate the
4422// async_work_group_copy with a previous async copy allowing
4423// an event to be shared by multiple async copies; otherwise
4424// event should be zero.
4425//
4426static bool TryOCLZeroEventInitialization(Sema &S,
4427 InitializationSequence &Sequence,
4428 QualType DestType,
4429 Expr *Initializer) {
4430 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4431 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4432 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4433 return false;
4434
4435 Sequence.AddOCLZeroEventStep(DestType);
4436 return true;
4437}
4438
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004439InitializationSequence::InitializationSequence(Sema &S,
4440 const InitializedEntity &Entity,
4441 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004442 MultiExprArg Args,
4443 bool TopLevelOfInitList)
Richard Smith100b24a2014-04-17 01:52:14 +00004444 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Richard Smith089c3162013-09-21 21:55:46 +00004445 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
4446}
4447
4448void InitializationSequence::InitializeFrom(Sema &S,
4449 const InitializedEntity &Entity,
4450 const InitializationKind &Kind,
4451 MultiExprArg Args,
4452 bool TopLevelOfInitList) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004453 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004454
John McCall5e77d762013-04-16 07:28:30 +00004455 // Eliminate non-overload placeholder types in the arguments. We
4456 // need to do this before checking whether types are dependent
4457 // because lowering a pseudo-object expression might well give us
4458 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004459 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00004460 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4461 // FIXME: should we be doing this here?
4462 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4463 if (result.isInvalid()) {
4464 SetFailed(FK_PlaceholderType);
4465 return;
4466 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004467 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00004468 }
4469
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004470 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004471 // The semantics of initializers are as follows. The destination type is
4472 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004473 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004474 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004475 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004476 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004477
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004478 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004479 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004480 SequenceKind = DependentSequence;
4481 return;
4482 }
4483
Sebastian Redld201edf2011-06-05 13:59:11 +00004484 // Almost everything is a normal sequence.
4485 setSequenceKind(NormalSequence);
4486
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004487 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00004488 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004489 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004490 Initializer = Args[0];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004491 if (S.getLangOpts().ObjC1) {
4492 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
4493 DestType, Initializer->getType(),
4494 Initializer) ||
4495 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
4496 Args[0] = Initializer;
4497
4498 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004499 if (!isa<InitListExpr>(Initializer))
4500 SourceType = Initializer->getType();
4501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004502
Sebastian Redl0501c632012-02-12 16:37:36 +00004503 // - If the initializer is a (non-parenthesized) braced-init-list, the
4504 // object is list-initialized (8.5.4).
4505 if (Kind.getKind() != InitializationKind::IK_Direct) {
4506 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4507 TryListInitialization(S, Entity, Kind, InitList, *this);
4508 return;
4509 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004510 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004511
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004512 // - If the destination type is a reference type, see 8.5.3.
4513 if (DestType->isReferenceType()) {
4514 // C++0x [dcl.init.ref]p1:
4515 // A variable declared to be a T& or T&&, that is, "reference to type T"
4516 // (8.3.2), shall be initialized by an object, or function, of type T or
4517 // by an object that can be converted into a T.
4518 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004519 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004520 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004521 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004522 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004523 return;
4524 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004525
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004526 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004527 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004528 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004529 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004530 return;
4531 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004532
Douglas Gregor85dabae2009-12-16 01:38:02 +00004533 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004534 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004535 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004536 return;
4537 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004538
John McCall66884dd2011-02-21 07:22:22 +00004539 // - If the destination type is an array of characters, an array of
4540 // char16_t, an array of char32_t, or an array of wchar_t, and the
4541 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004542 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004543 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004544 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004545 if (Initializer && isa<VariableArrayType>(DestAT)) {
4546 SetFailed(FK_VariableLengthArrayHasInitializer);
4547 return;
4548 }
4549
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004550 if (Initializer) {
4551 switch (IsStringInit(Initializer, DestAT, Context)) {
4552 case SIF_None:
4553 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4554 return;
4555 case SIF_NarrowStringIntoWideChar:
4556 SetFailed(FK_NarrowStringIntoWideCharArray);
4557 return;
4558 case SIF_WideStringIntoChar:
4559 SetFailed(FK_WideStringIntoCharArray);
4560 return;
4561 case SIF_IncompatWideStringIntoWideChar:
4562 SetFailed(FK_IncompatWideStringIntoWideChar);
4563 return;
4564 case SIF_Other:
4565 break;
4566 }
John McCall66884dd2011-02-21 07:22:22 +00004567 }
4568
Douglas Gregore2f943b2011-02-22 18:29:51 +00004569 // Note: as an GNU C extension, we allow initialization of an
4570 // array from a compound literal that creates an array of the same
4571 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004572 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00004573 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4574 Initializer->getType()->isArrayType()) {
4575 const ArrayType *SourceAT
4576 = Context.getAsArrayType(Initializer->getType());
4577 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004578 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004579 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004580 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004581 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004582 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004583 }
Richard Smithebeed412012-02-15 22:38:09 +00004584 }
Richard Smithd86812d2012-07-05 08:39:21 +00004585 // Note: as a GNU C++ extension, we allow list-initialization of a
4586 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004587 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00004588 Entity.getKind() == InitializedEntity::EK_Member &&
4589 Initializer && isa<InitListExpr>(Initializer)) {
4590 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4591 *this);
4592 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004593 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004594 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004595 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4596 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004597 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004598 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004599
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004600 return;
4601 }
Eli Friedman78275202009-12-19 08:11:05 +00004602
John McCall31168b02011-06-15 23:02:42 +00004603 // Determine whether we should consider writeback conversions for
4604 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004605 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004606 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00004607
4608 // We're at the end of the line for C: it's either a write-back conversion
4609 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004610 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004611 // If allowed, check whether this is an Objective-C writeback conversion.
4612 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004613 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004614 return;
4615 }
Guy Benyei61054192013-02-07 10:55:47 +00004616
4617 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4618 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004619
4620 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4621 return;
4622
John McCall31168b02011-06-15 23:02:42 +00004623 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004624 AddCAssignmentStep(DestType);
4625 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004626 return;
4627 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004628
David Blaikiebbafb8a2012-03-11 07:00:24 +00004629 assert(S.getLangOpts().CPlusPlus);
John McCall31168b02011-06-15 23:02:42 +00004630
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004631 // - If the destination type is a (possibly cv-qualified) class type:
4632 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004633 // - If the initialization is direct-initialization, or if it is
4634 // copy-initialization where the cv-unqualified version of the
4635 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004636 // class of the destination, constructors are considered. [...]
4637 if (Kind.getKind() == InitializationKind::IK_Direct ||
4638 (Kind.getKind() == InitializationKind::IK_Copy &&
4639 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4640 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004641 TryConstructorInitialization(S, Entity, Kind, Args,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004642 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004643 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004644 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004645 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004646 // used) to a derived class thereof are enumerated as described in
4647 // 13.3.1.4, and the best one is chosen through overload resolution
4648 // (13.3).
4649 else
Richard Smithaaa0ec42013-09-21 21:19:19 +00004650 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4651 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004652 return;
4653 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004654
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004655 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004656 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004657 return;
4658 }
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004659 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004660
4661 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004662 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004663 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smithaaa0ec42013-09-21 21:19:19 +00004664 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4665 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004666 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004667 return;
4668 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004669
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004670 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004671 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004672 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004673 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004674 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00004675
4676 ImplicitConversionSequence ICS
4677 = S.TryImplicitConversion(Initializer, Entity.getType(),
4678 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004679 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004680 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004681 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4682 allowObjCWritebackConversion);
4683
4684 if (ICS.isStandard() &&
4685 ICS.Standard.Second == ICK_Writeback_Conversion) {
4686 // Objective-C ARC writeback conversion.
4687
4688 // We should copy unless we're passing to an argument explicitly
4689 // marked 'out'.
4690 bool ShouldCopy = true;
4691 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4692 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4693
4694 // If there was an lvalue adjustment, add it as a separate conversion.
4695 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4696 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4697 ImplicitConversionSequence LvalueICS;
4698 LvalueICS.setStandard();
4699 LvalueICS.Standard.setAsIdentityConversion();
4700 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4701 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004702 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004703 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004704
4705 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004706 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004707 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00004708 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4709 AddZeroInitializationStep(Entity.getType());
4710 } else if (Initializer->getType() == Context.OverloadTy &&
4711 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4712 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004713 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004714 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004715 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004716 } else {
Richard Smithaaa0ec42013-09-21 21:19:19 +00004717 AddConversionSequenceStep(ICS, Entity.getType(), TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00004718
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004719 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004720 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004721}
4722
4723InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004724 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004725 StepEnd = Steps.end();
4726 Step != StepEnd; ++Step)
4727 Step->Destroy();
4728}
4729
4730//===----------------------------------------------------------------------===//
4731// Perform initialization
4732//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004733static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004734getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004735 switch(Entity.getKind()) {
4736 case InitializedEntity::EK_Variable:
4737 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004738 case InitializedEntity::EK_Exception:
4739 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004740 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004741 return Sema::AA_Initializing;
4742
4743 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004744 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004745 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4746 return Sema::AA_Sending;
4747
Douglas Gregore1314a62009-12-18 05:02:21 +00004748 return Sema::AA_Passing;
4749
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004750 case InitializedEntity::EK_Parameter_CF_Audited:
4751 if (Entity.getDecl() &&
4752 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4753 return Sema::AA_Sending;
4754
4755 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4756
Douglas Gregore1314a62009-12-18 05:02:21 +00004757 case InitializedEntity::EK_Result:
4758 return Sema::AA_Returning;
4759
Douglas Gregore1314a62009-12-18 05:02:21 +00004760 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00004761 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004762 // FIXME: Can we tell apart casting vs. converting?
4763 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004764
Douglas Gregore1314a62009-12-18 05:02:21 +00004765 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004766 case InitializedEntity::EK_ArrayElement:
4767 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004768 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004769 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004770 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004771 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004772 return Sema::AA_Initializing;
4773 }
4774
David Blaikie8a40f702012-01-17 06:56:22 +00004775 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004776}
4777
Richard Smith27874d62013-01-08 00:08:23 +00004778/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00004779/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004780static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004781 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004782 case InitializedEntity::EK_ArrayElement:
4783 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004784 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004785 case InitializedEntity::EK_New:
4786 case InitializedEntity::EK_Variable:
4787 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004788 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004789 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004790 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004791 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004792 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004793 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004794 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004795 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004796
Douglas Gregore1314a62009-12-18 05:02:21 +00004797 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004798 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00004799 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004800 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004801 return true;
4802 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004803
Douglas Gregore1314a62009-12-18 05:02:21 +00004804 llvm_unreachable("missed an InitializedEntity kind?");
4805}
4806
Douglas Gregor95562572010-04-24 23:45:46 +00004807/// \brief Whether the given entity, when initialized with an object
4808/// created for that initialization, requires destruction.
4809static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4810 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00004811 case InitializedEntity::EK_Result:
4812 case InitializedEntity::EK_New:
4813 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004814 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004815 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004816 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004817 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004818 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00004819 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004820
Richard Smith27874d62013-01-08 00:08:23 +00004821 case InitializedEntity::EK_Member:
Douglas Gregor95562572010-04-24 23:45:46 +00004822 case InitializedEntity::EK_Variable:
4823 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004824 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00004825 case InitializedEntity::EK_Temporary:
4826 case InitializedEntity::EK_ArrayElement:
4827 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004828 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004829 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00004830 return true;
4831 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004832
4833 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004834}
4835
Richard Smithc620f552011-10-19 16:55:56 +00004836/// \brief Look for copy and move constructors and constructor templates, for
4837/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4838static void LookupCopyAndMoveConstructors(Sema &S,
4839 OverloadCandidateSet &CandidateSet,
4840 CXXRecordDecl *Class,
4841 Expr *CurInitExpr) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004842 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004843 // The container holding the constructors can under certain conditions
4844 // be changed while iterating (e.g. because of deserialization).
4845 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004846 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004847 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004848 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4849 NamedDecl *D = *CI;
Craig Topperc3ec1492014-05-26 06:22:03 +00004850 CXXConstructorDecl *Constructor = nullptr;
Richard Smithc620f552011-10-19 16:55:56 +00004851
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004852 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smithc620f552011-10-19 16:55:56 +00004853 // Handle copy/moveconstructors, only.
4854 if (!Constructor || Constructor->isInvalidDecl() ||
4855 !Constructor->isCopyOrMoveConstructor() ||
4856 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4857 continue;
4858
4859 DeclAccessPair FoundDecl
4860 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4861 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004862 CurInitExpr, CandidateSet);
Richard Smithc620f552011-10-19 16:55:56 +00004863 continue;
4864 }
4865
4866 // Handle constructor templates.
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004867 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smithc620f552011-10-19 16:55:56 +00004868 if (ConstructorTmpl->isInvalidDecl())
4869 continue;
4870
4871 Constructor = cast<CXXConstructorDecl>(
4872 ConstructorTmpl->getTemplatedDecl());
4873 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4874 continue;
4875
4876 // FIXME: Do we need to limit this to copy-constructor-like
4877 // candidates?
4878 DeclAccessPair FoundDecl
4879 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
Craig Topperc3ec1492014-05-26 06:22:03 +00004880 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004881 CurInitExpr, CandidateSet, true);
Richard Smithc620f552011-10-19 16:55:56 +00004882 }
4883}
4884
4885/// \brief Get the location at which initialization diagnostics should appear.
4886static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4887 Expr *Initializer) {
4888 switch (Entity.getKind()) {
4889 case InitializedEntity::EK_Result:
4890 return Entity.getReturnLoc();
4891
4892 case InitializedEntity::EK_Exception:
4893 return Entity.getThrowLoc();
4894
4895 case InitializedEntity::EK_Variable:
4896 return Entity.getDecl()->getLocation();
4897
Douglas Gregor19666fb2012-02-15 16:57:26 +00004898 case InitializedEntity::EK_LambdaCapture:
4899 return Entity.getCaptureLoc();
4900
Richard Smithc620f552011-10-19 16:55:56 +00004901 case InitializedEntity::EK_ArrayElement:
4902 case InitializedEntity::EK_Member:
4903 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004904 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00004905 case InitializedEntity::EK_Temporary:
4906 case InitializedEntity::EK_New:
4907 case InitializedEntity::EK_Base:
4908 case InitializedEntity::EK_Delegating:
4909 case InitializedEntity::EK_VectorElement:
4910 case InitializedEntity::EK_ComplexElement:
4911 case InitializedEntity::EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004912 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004913 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00004914 return Initializer->getLocStart();
4915 }
4916 llvm_unreachable("missed an InitializedEntity kind?");
4917}
4918
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004919/// \brief Make a (potentially elidable) temporary copy of the object
4920/// provided by the given initializer by calling the appropriate copy
4921/// constructor.
4922///
4923/// \param S The Sema object used for type-checking.
4924///
Abramo Bagnara92141d22011-01-27 19:55:10 +00004925/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004926/// the type of the initializer expression or a superclass thereof.
4927///
James Dennett634962f2012-06-14 21:40:34 +00004928/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004929///
4930/// \param CurInit The initializer expression.
4931///
4932/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4933/// is permitted in C++03 (but not C++0x) when binding a reference to
4934/// an rvalue.
4935///
4936/// \returns An expression that copies the initializer expression into
4937/// a temporary object, or an error expression if a copy could not be
4938/// created.
John McCalldadc5752010-08-24 06:29:42 +00004939static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00004940 QualType T,
4941 const InitializedEntity &Entity,
4942 ExprResult CurInit,
4943 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00004944 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00004945 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00004946 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004947 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004948 Class = cast<CXXRecordDecl>(Record->getDecl());
4949 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004950 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004951
Douglas Gregor5d369002011-01-21 18:05:27 +00004952 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004953 // When certain criteria are met, an implementation is allowed to
4954 // omit the copy/move construction of a class object, even if the
4955 // copy/move constructor and/or destructor for the object have
4956 // side effects. [...]
4957 // - when a temporary class object that has not been bound to a
4958 // reference (12.2) would be copied/moved to a class object
4959 // with the same cv-unqualified type, the copy/move operation
4960 // can be omitted by constructing the temporary object
4961 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004962 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004963 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004964 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004965 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004966 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00004967 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00004968 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00004969
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004970 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004971 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004972 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00004973
Douglas Gregorf282a762011-01-21 19:38:21 +00004974 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00004975 // Only consider constructors and constructor templates. Per
4976 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4977 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00004978 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00004979 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004980
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004981 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4982
Douglas Gregore1314a62009-12-18 05:02:21 +00004983 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004984 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004985 case OR_Success:
4986 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004987
Douglas Gregore1314a62009-12-18 05:02:21 +00004988 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004989 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4990 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4991 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004992 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004993 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004994 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004995 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004996 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004997 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004998
Douglas Gregore1314a62009-12-18 05:02:21 +00004999 case OR_Ambiguous:
5000 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005001 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005002 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005003 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00005004 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005005
Douglas Gregore1314a62009-12-18 05:02:21 +00005006 case OR_Deleted:
5007 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005008 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005009 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00005010 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00005011 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005012 }
5013
Douglas Gregor5ab11652010-04-17 22:01:05 +00005014 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00005015 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005016 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005017
Anders Carlssona01874b2010-04-21 18:47:17 +00005018 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005019 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005020
5021 if (IsExtraneousCopy) {
5022 // If this is a totally extraneous copy for C++03 reference
5023 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005024 // expression. We don't generate an (elided) copy operation here
5025 // because doing so would require us to pass down a flag to avoid
5026 // infinite recursion, where each step adds another extraneous,
5027 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005028
Douglas Gregor30b52772010-04-18 07:57:34 +00005029 // Instantiate the default arguments of any extra parameters in
5030 // the selected copy constructor, as if we were going to create a
5031 // proper call to the copy constructor.
5032 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5033 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5034 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005035 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005036 break;
5037
5038 // Build the default argument expression; we don't actually care
5039 // if this succeeds or not, because this routine will complain
5040 // if there was a problem.
5041 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5042 }
5043
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005044 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005045 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005046
Douglas Gregor5ab11652010-04-17 22:01:05 +00005047 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005048 // constructor call (we might have derived-to-base conversions, or
5049 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005050 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005051 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005052
Douglas Gregord0ace022010-04-25 00:55:24 +00005053 // Actually perform the constructor call.
5054 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005055 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005056 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005057 /*ListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005058 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005059 CXXConstructExpr::CK_Complete,
5060 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005061
Douglas Gregord0ace022010-04-25 00:55:24 +00005062 // If we're supposed to bind temporaries, do so.
5063 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005064 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005065 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005066}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005067
Richard Smithc620f552011-10-19 16:55:56 +00005068/// \brief Check whether elidable copy construction for binding a reference to
5069/// a temporary would have succeeded if we were building in C++98 mode, for
5070/// -Wc++98-compat.
5071static void CheckCXX98CompatAccessibleCopy(Sema &S,
5072 const InitializedEntity &Entity,
5073 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005074 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005075
5076 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5077 if (!Record)
5078 return;
5079
5080 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005081 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00005082 return;
5083
5084 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00005085 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005086 LookupCopyAndMoveConstructors(
5087 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5088
5089 // Perform overload resolution.
5090 OverloadCandidateSet::iterator Best;
5091 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5092
5093 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5094 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5095 << CurInitExpr->getSourceRange();
5096
5097 switch (OR) {
5098 case OR_Success:
5099 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCall5dadb652012-04-07 03:04:20 +00005100 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005101 // FIXME: Check default arguments as far as that's possible.
5102 break;
5103
5104 case OR_No_Viable_Function:
5105 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005106 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005107 break;
5108
5109 case OR_Ambiguous:
5110 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005111 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005112 break;
5113
5114 case OR_Deleted:
5115 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005116 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005117 break;
5118 }
5119}
5120
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005121void InitializationSequence::PrintInitLocationNote(Sema &S,
5122 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005123 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005124 if (Entity.getDecl()->getLocation().isInvalid())
5125 return;
5126
5127 if (Entity.getDecl()->getDeclName())
5128 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5129 << Entity.getDecl()->getDeclName();
5130 else
5131 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5132 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005133 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5134 Entity.getMethodDecl())
5135 S.Diag(Entity.getMethodDecl()->getLocation(),
5136 diag::note_method_return_type_change)
5137 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005138}
5139
Sebastian Redl112aa822011-07-14 19:07:55 +00005140static bool isReferenceBinding(const InitializationSequence::Step &s) {
5141 return s.Kind == InitializationSequence::SK_BindReference ||
5142 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5143}
5144
Jordan Rose6c0505e2013-05-06 16:48:12 +00005145/// Returns true if the parameters describe a constructor initialization of
5146/// an explicit temporary object, e.g. "Point(x, y)".
5147static bool isExplicitTemporary(const InitializedEntity &Entity,
5148 const InitializationKind &Kind,
5149 unsigned NumArgs) {
5150 switch (Entity.getKind()) {
5151 case InitializedEntity::EK_Temporary:
5152 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005153 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005154 break;
5155 default:
5156 return false;
5157 }
5158
5159 switch (Kind.getKind()) {
5160 case InitializationKind::IK_DirectList:
5161 return true;
5162 // FIXME: Hack to work around cast weirdness.
5163 case InitializationKind::IK_Direct:
5164 case InitializationKind::IK_Value:
5165 return NumArgs != 1;
5166 default:
5167 return false;
5168 }
5169}
5170
Sebastian Redled2e5322011-12-22 14:44:04 +00005171static ExprResult
5172PerformConstructorInitialization(Sema &S,
5173 const InitializedEntity &Entity,
5174 const InitializationKind &Kind,
5175 MultiExprArg Args,
5176 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00005177 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005178 bool IsListInitialization,
5179 SourceLocation LBraceLoc,
5180 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005181 unsigned NumArgs = Args.size();
5182 CXXConstructorDecl *Constructor
5183 = cast<CXXConstructorDecl>(Step.Function.Function);
5184 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5185
5186 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005187 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00005188 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5189 ? Kind.getEqualLoc()
5190 : Kind.getLocation();
5191
5192 if (Kind.getKind() == InitializationKind::IK_Default) {
5193 // Force even a trivial, implicit default constructor to be
5194 // semantically checked. We do this explicitly because we don't build
5195 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00005196 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00005197 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00005198 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00005199 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5200 }
5201
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005202 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00005203
Douglas Gregor6073dca2012-02-24 23:56:31 +00005204 // C++ [over.match.copy]p1:
5205 // - When initializing a temporary to be bound to the first parameter
5206 // of a constructor that takes a reference to possibly cv-qualified
5207 // T as its first argument, called with a single argument in the
5208 // context of direct-initialization, explicit conversion functions
5209 // are also considered.
5210 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5211 Args.size() == 1 &&
5212 Constructor->isCopyOrMoveConstructor();
5213
Sebastian Redled2e5322011-12-22 14:44:04 +00005214 // Determine the arguments required to actually perform the constructor
5215 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005216 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005217 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00005218 AllowExplicitConv,
5219 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00005220 return ExprError();
5221
5222
Jordan Rose6c0505e2013-05-06 16:48:12 +00005223 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005224 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedmanfa0df832012-02-02 03:46:19 +00005225 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith22262ab2013-05-04 06:44:46 +00005226 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5227 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005228
5229 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5230 if (!TSInfo)
5231 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005232 SourceRange ParenOrBraceRange =
5233 (Kind.getKind() == InitializationKind::IK_DirectList)
5234 ? SourceRange(LBraceLoc, RBraceLoc)
5235 : Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005236
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005237 CurInit = new (S.Context) CXXTemporaryObjectExpr(
5238 S.Context, Constructor, TSInfo, ConstructorArgs, ParenOrBraceRange,
5239 HadMultipleCandidates, IsListInitialization,
5240 ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00005241 } else {
5242 CXXConstructExpr::ConstructionKind ConstructKind =
5243 CXXConstructExpr::CK_Complete;
5244
5245 if (Entity.getKind() == InitializedEntity::EK_Base) {
5246 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5247 CXXConstructExpr::CK_VirtualBase :
5248 CXXConstructExpr::CK_NonVirtualBase;
5249 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5250 ConstructKind = CXXConstructExpr::CK_Delegating;
5251 }
5252
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005253 // Only get the parenthesis or brace range if it is a list initialization or
5254 // direct construction.
5255 SourceRange ParenOrBraceRange;
5256 if (IsListInitialization)
5257 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
5258 else if (Kind.getKind() == InitializationKind::IK_Direct)
5259 ParenOrBraceRange = Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005260
5261 // If the entity allows NRVO, mark the construction as elidable
5262 // unconditionally.
5263 if (Entity.allowsNRVO())
5264 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5265 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005266 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005267 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005268 IsListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005269 ConstructorInitRequiresZeroInit,
5270 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005271 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005272 else
5273 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5274 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005275 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005276 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005277 IsListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005278 ConstructorInitRequiresZeroInit,
5279 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005280 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005281 }
5282 if (CurInit.isInvalid())
5283 return ExprError();
5284
5285 // Only check access if all of that succeeded.
5286 S.CheckConstructorAccess(Loc, Constructor, Entity,
5287 Step.Function.FoundDecl.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005288 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5289 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005290
5291 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005292 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00005293
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005294 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00005295}
5296
Richard Smitheb3cad52012-06-04 22:27:30 +00005297/// Determine whether the specified InitializedEntity definitely has a lifetime
5298/// longer than the current full-expression. Conservatively returns false if
5299/// it's unclear.
5300static bool
5301InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5302 const InitializedEntity *Top = &Entity;
5303 while (Top->getParent())
5304 Top = Top->getParent();
5305
5306 switch (Top->getKind()) {
5307 case InitializedEntity::EK_Variable:
5308 case InitializedEntity::EK_Result:
5309 case InitializedEntity::EK_Exception:
5310 case InitializedEntity::EK_Member:
5311 case InitializedEntity::EK_New:
5312 case InitializedEntity::EK_Base:
5313 case InitializedEntity::EK_Delegating:
5314 return true;
5315
5316 case InitializedEntity::EK_ArrayElement:
5317 case InitializedEntity::EK_VectorElement:
5318 case InitializedEntity::EK_BlockElement:
5319 case InitializedEntity::EK_ComplexElement:
5320 // Could not determine what the full initialization is. Assume it might not
5321 // outlive the full-expression.
5322 return false;
5323
5324 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005325 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00005326 case InitializedEntity::EK_Temporary:
5327 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005328 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005329 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00005330 // The entity being initialized might not outlive the full-expression.
5331 return false;
5332 }
5333
5334 llvm_unreachable("unknown entity kind");
5335}
5336
Richard Smithe6c01442013-06-05 00:46:14 +00005337/// Determine the declaration which an initialized entity ultimately refers to,
5338/// for the purpose of lifetime-extending a temporary bound to a reference in
5339/// the initialization of \p Entity.
David Majnemerdaff3702014-05-01 17:50:17 +00005340static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
5341 const InitializedEntity *Entity,
Craig Topperc3ec1492014-05-26 06:22:03 +00005342 const InitializedEntity *FallbackDecl = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00005343 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00005344 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005345 case InitializedEntity::EK_Variable:
5346 // The temporary [...] persists for the lifetime of the reference
David Majnemerdaff3702014-05-01 17:50:17 +00005347 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005348
5349 case InitializedEntity::EK_Member:
5350 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005351 if (Entity->getParent())
5352 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5353 Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00005354
5355 // except:
5356 // -- A temporary bound to a reference member in a constructor's
5357 // ctor-initializer persists until the constructor exits.
David Majnemerdaff3702014-05-01 17:50:17 +00005358 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005359
5360 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005361 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00005362 // -- A temporary bound to a reference parameter in a function call
5363 // persists until the completion of the full-expression containing
5364 // the call.
5365 case InitializedEntity::EK_Result:
5366 // -- The lifetime of a temporary bound to the returned value in a
5367 // function return statement is not extended; the temporary is
5368 // destroyed at the end of the full-expression in the return statement.
5369 case InitializedEntity::EK_New:
5370 // -- A temporary bound to a reference in a new-initializer persists
5371 // until the completion of the full-expression containing the
5372 // new-initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005373 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005374
5375 case InitializedEntity::EK_Temporary:
5376 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005377 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00005378 // We don't yet know the storage duration of the surrounding temporary.
5379 // Assume it's got full-expression duration for now, it will patch up our
5380 // storage duration if that's not correct.
David Majnemerdaff3702014-05-01 17:50:17 +00005381 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005382
5383 case InitializedEntity::EK_ArrayElement:
5384 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005385 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5386 FallbackDecl);
Richard Smithe6c01442013-06-05 00:46:14 +00005387
5388 case InitializedEntity::EK_Base:
5389 case InitializedEntity::EK_Delegating:
5390 // We can reach this case for aggregate initialization in a constructor:
5391 // struct A { int &&r; };
5392 // struct B : A { B() : A{0} {} };
5393 // In this case, use the innermost field decl as the context.
5394 return FallbackDecl;
5395
5396 case InitializedEntity::EK_BlockElement:
5397 case InitializedEntity::EK_LambdaCapture:
5398 case InitializedEntity::EK_Exception:
5399 case InitializedEntity::EK_VectorElement:
5400 case InitializedEntity::EK_ComplexElement:
David Majnemerdaff3702014-05-01 17:50:17 +00005401 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005402 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00005403 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00005404}
5405
David Majnemerdaff3702014-05-01 17:50:17 +00005406static void performLifetimeExtension(Expr *Init,
5407 const InitializedEntity *ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005408
5409/// Update a glvalue expression that is used as the initializer of a reference
5410/// to note that its lifetime is extended.
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005411/// \return \c true if any temporary had its lifetime extended.
David Majnemerdaff3702014-05-01 17:50:17 +00005412static bool
5413performReferenceExtension(Expr *Init,
5414 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00005415 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5416 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5417 // This is just redundant braces around an initializer. Step over it.
5418 Init = ILE->getInit(0);
5419 }
5420 }
5421
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005422 // Walk past any constructs which we can lifetime-extend across.
5423 Expr *Old;
5424 do {
5425 Old = Init;
5426
5427 // Step over any subobject adjustments; we may have a materialized
5428 // temporary inside them.
5429 SmallVector<const Expr *, 2> CommaLHSs;
5430 SmallVector<SubobjectAdjustment, 2> Adjustments;
5431 Init = const_cast<Expr *>(
5432 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5433
5434 // Per current approach for DR1376, look through casts to reference type
5435 // when performing lifetime extension.
5436 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5437 if (CE->getSubExpr()->isGLValue())
5438 Init = CE->getSubExpr();
5439
5440 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5441 // It's unclear if binding a reference to that xvalue extends the array
5442 // temporary.
5443 } while (Init != Old);
5444
Richard Smithe6c01442013-06-05 00:46:14 +00005445 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5446 // Update the storage duration of the materialized temporary.
5447 // FIXME: Rebuild the expression instead of mutating it.
David Majnemerdaff3702014-05-01 17:50:17 +00005448 ME->setExtendingDecl(ExtendingEntity->getDecl(),
5449 ExtendingEntity->allocateManglingNumber());
5450 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005451 return true;
Richard Smithe6c01442013-06-05 00:46:14 +00005452 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005453
5454 return false;
Richard Smithe6c01442013-06-05 00:46:14 +00005455}
5456
5457/// Update a prvalue expression that is going to be materialized as a
5458/// lifetime-extended temporary.
David Majnemerdaff3702014-05-01 17:50:17 +00005459static void performLifetimeExtension(Expr *Init,
5460 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00005461 // Dig out the expression which constructs the extended temporary.
5462 SmallVector<const Expr *, 2> CommaLHSs;
5463 SmallVector<SubobjectAdjustment, 2> Adjustments;
5464 Init = const_cast<Expr *>(
5465 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5466
Richard Smith736a9472013-06-12 20:42:33 +00005467 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5468 Init = BTE->getSubExpr();
5469
Richard Smithcc1b96d2013-06-12 22:31:48 +00005470 if (CXXStdInitializerListExpr *ILE =
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005471 dyn_cast<CXXStdInitializerListExpr>(Init)) {
David Majnemerdaff3702014-05-01 17:50:17 +00005472 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005473 return;
5474 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00005475
Richard Smithe6c01442013-06-05 00:46:14 +00005476 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00005477 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005478 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
David Majnemerdaff3702014-05-01 17:50:17 +00005479 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005480 return;
5481 }
5482
Richard Smithcc1b96d2013-06-12 22:31:48 +00005483 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005484 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5485
5486 // If we lifetime-extend a braced initializer which is initializing an
5487 // aggregate, and that aggregate contains reference members which are
5488 // bound to temporaries, those temporaries are also lifetime-extended.
5489 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5490 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005491 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005492 else {
5493 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005494 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00005495 if (Index >= ILE->getNumInits())
5496 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005497 if (I->isUnnamedBitfield())
5498 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00005499 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00005500 if (I->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005501 performReferenceExtension(SubInit, ExtendingEntity);
Richard Smith8d7f11d2013-06-27 22:54:33 +00005502 else if (isa<InitListExpr>(SubInit) ||
5503 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smithe6c01442013-06-05 00:46:14 +00005504 // This may be either aggregate-initialization of a member or
5505 // initialization of a std::initializer_list object. Either way,
5506 // we should recursively lifetime-extend that initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005507 performLifetimeExtension(SubInit, ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005508 ++Index;
5509 }
5510 }
5511 }
5512 }
5513}
5514
Richard Smithcc1b96d2013-06-12 22:31:48 +00005515static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5516 const Expr *Init, bool IsInitializerList,
5517 const ValueDecl *ExtendingDecl) {
5518 // Warn if a field lifetime-extends a temporary.
5519 if (isa<FieldDecl>(ExtendingDecl)) {
5520 if (IsInitializerList) {
5521 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5522 << /*at end of constructor*/true;
5523 return;
5524 }
5525
5526 bool IsSubobjectMember = false;
5527 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5528 Ent = Ent->getParent()) {
5529 if (Ent->getKind() != InitializedEntity::EK_Base) {
5530 IsSubobjectMember = true;
5531 break;
5532 }
5533 }
5534 S.Diag(Init->getExprLoc(),
5535 diag::warn_bind_ref_member_to_temporary)
5536 << ExtendingDecl << Init->getSourceRange()
5537 << IsSubobjectMember << IsInitializerList;
5538 if (IsSubobjectMember)
5539 S.Diag(ExtendingDecl->getLocation(),
5540 diag::note_ref_subobject_of_member_declared_here);
5541 else
5542 S.Diag(ExtendingDecl->getLocation(),
5543 diag::note_ref_or_ptr_member_declared_here)
5544 << /*is pointer*/false;
5545 }
5546}
5547
Richard Smithaaa0ec42013-09-21 21:19:19 +00005548static void DiagnoseNarrowingInInitList(Sema &S,
5549 const ImplicitConversionSequence &ICS,
5550 QualType PreNarrowingType,
5551 QualType EntityType,
5552 const Expr *PostInit);
5553
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005554ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005555InitializationSequence::Perform(Sema &S,
5556 const InitializedEntity &Entity,
5557 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00005558 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005559 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005560 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005561 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00005562 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005564
Sebastian Redld201edf2011-06-05 13:59:11 +00005565 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005566 // If the declaration is a non-dependent, incomplete array type
5567 // that has an initializer, then its type will be completed once
5568 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00005569 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00005570 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00005571 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005572 if (const IncompleteArrayType *ArrayT
5573 = S.Context.getAsIncompleteArrayType(DeclType)) {
5574 // FIXME: We don't currently have the ability to accurately
5575 // compute the length of an initializer list without
5576 // performing full type-checking of the initializer list
5577 // (since we have to determine where braces are implicitly
5578 // introduced and such). So, we fall back to making the array
5579 // type a dependently-sized array type with no specified
5580 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005581 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005582 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00005583
Douglas Gregor51e77d52009-12-10 17:56:55 +00005584 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00005585 if (DeclaratorDecl *DD = Entity.getDecl()) {
5586 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5587 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00005588 if (IncompleteArrayTypeLoc ArrayLoc =
5589 TL.getAs<IncompleteArrayTypeLoc>())
5590 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00005591 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00005592 }
5593
5594 *ResultType
5595 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005596 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005597 ArrayT->getSizeModifier(),
5598 ArrayT->getIndexTypeCVRQualifiers(),
5599 Brackets);
5600 }
5601
5602 }
5603 }
Sebastian Redla9351792012-02-11 23:51:47 +00005604 if (Kind.getKind() == InitializationKind::IK_Direct &&
5605 !Kind.isExplicitCast()) {
5606 // Rebuild the ParenListExpr.
5607 SourceRange ParenRange = Kind.getParenRange();
5608 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005609 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00005610 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00005611 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00005612 Kind.isExplicitCast() ||
5613 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005614 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005615 }
5616
Sebastian Redld201edf2011-06-05 13:59:11 +00005617 // No steps means no initialization.
5618 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005619 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005620
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005621 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005622 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005623 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00005624 // Produce a C++98 compatibility warning if we are initializing a reference
5625 // from an initializer list. For parameters, we produce a better warning
5626 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005627 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00005628 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5629 << Init->getSourceRange();
5630 }
5631
Richard Smitheb3cad52012-06-04 22:27:30 +00005632 // Diagnose cases where we initialize a pointer to an array temporary, and the
5633 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005634 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00005635 Entity.getType()->isPointerType() &&
5636 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005637 Expr *Init = Args[0];
Richard Smitheb3cad52012-06-04 22:27:30 +00005638 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5639 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5640 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5641 << Init->getSourceRange();
5642 }
5643
Douglas Gregor1b303932009-12-22 15:35:07 +00005644 QualType DestType = Entity.getType().getNonReferenceType();
5645 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00005646 // the same as Entity.getDecl()->getType() in cases involving type merging,
5647 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00005648 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00005649 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00005650 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005651
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005652 ExprResult CurInit((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005653
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005654 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00005655 // grab the only argument out the Args and place it into the "current"
5656 // initializer.
5657 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005658 case SK_ResolveAddressOfOverloadedFunction:
5659 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005660 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005661 case SK_CastDerivedToBaseLValue:
5662 case SK_BindReference:
5663 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005664 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00005665 case SK_UserConversion:
5666 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005667 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005668 case SK_QualificationConversionRValue:
Jordan Roseb1312a52013-04-11 00:58:58 +00005669 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005670 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00005671 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00005672 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00005673 case SK_UnwrapInitList:
5674 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00005675 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00005676 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00005677 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00005678 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00005679 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00005680 case SK_PassByIndirectCopyRestore:
5681 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00005682 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005683 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00005684 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005685 case SK_OCLZeroEvent: {
Douglas Gregore1314a62009-12-18 05:02:21 +00005686 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005687 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00005688 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005689 break;
John McCall34376a62010-12-04 03:47:34 +00005690 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005691
Douglas Gregore1314a62009-12-18 05:02:21 +00005692 case SK_ConstructorInitialization:
Richard Smithd86812d2012-07-05 08:39:21 +00005693 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00005694 case SK_ZeroInitialization:
5695 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005696 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005697
5698 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005699 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005700 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005701 for (step_iterator Step = step_begin(), StepEnd = step_end();
5702 Step != StepEnd; ++Step) {
5703 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005704 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005705
John Wiegley01296292011-04-08 18:41:53 +00005706 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005707
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005708 switch (Step->Kind) {
5709 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005710 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005711 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00005712 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00005713 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5714 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005715 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00005716 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00005717 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005718 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005719
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005720 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005721 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005722 case SK_CastDerivedToBaseLValue: {
5723 // We have a derived-to-base cast that produces either an rvalue or an
5724 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005725
John McCallcf142162010-08-07 06:22:56 +00005726 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00005727
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005728 // Casts to inaccessible base classes are allowed with C-style casts.
5729 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5730 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00005731 CurInit.get()->getLocStart(),
5732 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00005733 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00005734 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005735
Douglas Gregor88d292c2010-05-13 16:44:06 +00005736 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5737 QualType T = SourceType;
5738 if (const PointerType *Pointer = T->getAs<PointerType>())
5739 T = Pointer->getPointeeType();
5740 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00005741 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00005742 cast<CXXRecordDecl>(RecordTy->getDecl()));
5743 }
5744
John McCall2536c6d2010-08-25 10:28:54 +00005745 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005746 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005747 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005748 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005749 VK_XValue :
5750 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005751 CurInit =
5752 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
5753 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005754 break;
5755 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005756
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005757 case SK_BindReference:
John McCalld25db7e2013-05-06 21:39:12 +00005758 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5759 if (CurInit.get()->refersToBitField()) {
5760 // We don't necessarily have an unambiguous source bit-field.
5761 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005762 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00005763 << Entity.getType().isVolatileQualified()
John McCalld25db7e2013-05-06 21:39:12 +00005764 << (BitField ? BitField->getDeclName() : DeclarationName())
Craig Topperc3ec1492014-05-26 06:22:03 +00005765 << (BitField != nullptr)
John Wiegley01296292011-04-08 18:41:53 +00005766 << CurInit.get()->getSourceRange();
John McCalld25db7e2013-05-06 21:39:12 +00005767 if (BitField)
5768 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5769
John McCallfaf5fb42010-08-26 23:41:50 +00005770 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005771 }
Anders Carlssona91be642010-01-29 02:47:33 +00005772
John Wiegley01296292011-04-08 18:41:53 +00005773 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00005774 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005775 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5776 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00005777 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005778 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005779 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005780 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005781
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005782 // Reference binding does not have any corresponding ASTs.
5783
5784 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005785 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005786 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005787
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005788 // Even though we didn't materialize a temporary, the binding may still
5789 // extend the lifetime of a temporary. This happens if we bind a reference
5790 // to the result of a cast to reference type.
David Majnemerdaff3702014-05-01 17:50:17 +00005791 if (const InitializedEntity *ExtendingEntity =
5792 getEntityForTemporaryLifetimeExtension(&Entity))
5793 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
5794 warnOnLifetimeExtension(S, Entity, CurInit.get(),
5795 /*IsInitializerList=*/false,
5796 ExtendingEntity->getDecl());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005797
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005798 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005799
Richard Smithe6c01442013-06-05 00:46:14 +00005800 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00005801 // Make sure the "temporary" is actually an rvalue.
5802 assert(CurInit.get()->isRValue() && "not a temporary");
5803
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005804 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005805 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005806 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005807
Douglas Gregorfe314812011-06-21 17:03:29 +00005808 // Materialize the temporary into memory.
Richard Smith736a9472013-06-12 20:42:33 +00005809 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Richard Smithe6c01442013-06-05 00:46:14 +00005810 Entity.getType().getNonReferenceType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00005811 Entity.getType()->isLValueReferenceType());
5812
5813 // Maybe lifetime-extend the temporary's subobjects to match the
5814 // entity's lifetime.
5815 if (const InitializedEntity *ExtendingEntity =
5816 getEntityForTemporaryLifetimeExtension(&Entity))
5817 if (performReferenceExtension(MTE, ExtendingEntity))
5818 warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false,
5819 ExtendingEntity->getDecl());
Douglas Gregor58df5092011-06-22 16:12:01 +00005820
5821 // If we're binding to an Objective-C object that has lifetime, we
Richard Smith736a9472013-06-12 20:42:33 +00005822 // need cleanups. Likewise if we're extending this temporary to automatic
5823 // storage duration -- we need to register its cleanup during the
5824 // full-expression's cleanups.
5825 if ((S.getLangOpts().ObjCAutoRefCount &&
5826 MTE->getType()->isObjCLifetimeType()) ||
5827 (MTE->getStorageDuration() == SD_Automatic &&
5828 MTE->getType().isDestructedType()))
Douglas Gregor58df5092011-06-22 16:12:01 +00005829 S.ExprNeedsCleanups = true;
Richard Smith736a9472013-06-12 20:42:33 +00005830
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005831 CurInit = MTE;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005832 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005833 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005834
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005835 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005836 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005837 /*IsExtraneousCopy=*/true);
5838 break;
5839
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005840 case SK_UserConversion: {
5841 // We have a user-defined conversion that invokes either a constructor
5842 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00005843 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00005844 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00005845 FunctionDecl *Fn = Step->Function.Function;
5846 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005847 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00005848 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00005849 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005850 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005851 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00005852 SourceLocation Loc = CurInit.get()->getLocStart();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005853 CurInit.get(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00005854
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005855 // Determine the arguments required to actually perform the constructor
5856 // call.
John Wiegley01296292011-04-08 18:41:53 +00005857 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005858 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00005859 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005860 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005861 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005862
Richard Smithb24f0672012-02-11 19:22:50 +00005863 // Build an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005864 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005865 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005866 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005867 /*ListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005868 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005869 CXXConstructExpr::CK_Complete,
5870 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005871 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005872 return ExprError();
John McCall760af172010-02-01 03:16:54 +00005873
Anders Carlssona01874b2010-04-21 18:47:17 +00005874 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00005875 FoundFn.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005876 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5877 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005878
John McCalle3027922010-08-25 11:45:40 +00005879 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00005880 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5881 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5882 S.IsDerivedFrom(SourceType, Class))
5883 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005884
Douglas Gregor95562572010-04-24 23:45:46 +00005885 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005886 } else {
5887 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00005888 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00005889 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00005890 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00005891 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5892 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005893
5894 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005895 // derived-to-base conversion? I believe the answer is "no", because
5896 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00005897 ExprResult CurInitExprRes =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005898 S.PerformObjectArgumentInitialization(CurInit.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005899 /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00005900 FoundFn, Conversion);
5901 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005902 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005903 CurInit = CurInitExprRes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005904
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005905 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005906 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5907 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005908 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00005909 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005910
John McCalle3027922010-08-25 11:45:40 +00005911 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005912
Alp Toker314cc812014-01-25 16:55:45 +00005913 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005914 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005915
Sebastian Redl112aa822011-07-14 19:07:55 +00005916 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005917 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5918
5919 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00005920 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00005921 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005922 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00005923 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00005924 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00005925 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00005926 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00005927 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
5928 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00005929 }
5930 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005931
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005932 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
5933 CastKind, CurInit.get(), nullptr,
5934 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005935 if (MaybeBindToTemp)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005936 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005937 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005938 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005939 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005940 break;
5941 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005942
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005943 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005944 case SK_QualificationConversionXValue:
5945 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005946 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00005947 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005948 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005949 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005950 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005951 VK_XValue :
5952 VK_RValue);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005953 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005954 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005955 }
5956
Jordan Roseb1312a52013-04-11 00:58:58 +00005957 case SK_LValueToRValue: {
5958 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005959 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
5960 CK_LValueToRValue, CurInit.get(),
5961 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00005962 break;
5963 }
5964
Richard Smithaaa0ec42013-09-21 21:19:19 +00005965 case SK_ConversionSequence:
5966 case SK_ConversionSequenceNoNarrowing: {
5967 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00005968 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5969 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00005970 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00005971 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00005972 ExprResult CurInitExprRes =
5973 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00005974 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00005975 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005976 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005977 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00005978
5979 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
5980 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
5981 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
5982 CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005983 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00005984 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005985
Douglas Gregor51e77d52009-12-10 17:56:55 +00005986 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00005987 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00005988 // If we're not initializing the top-level entity, we need to create an
5989 // InitializeTemporary entity for our target type.
5990 QualType Ty = Step->Type;
5991 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00005992 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00005993 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5994 InitListChecker PerformInitList(S, InitEntity,
Richard Smithde229232013-06-06 11:41:05 +00005995 InitList, Ty, /*VerifyOnly=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005996 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00005997 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005998
Richard Smithcc1b96d2013-06-12 22:31:48 +00005999 // Hack: We must update *ResultType if available in order to set the
6000 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
6001 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
6002 if (ResultType &&
6003 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00006004 if ((*ResultType)->isRValueReferenceType())
6005 Ty = S.Context.getRValueReferenceType(Ty);
6006 else if ((*ResultType)->isLValueReferenceType())
6007 Ty = S.Context.getLValueReferenceType(Ty,
6008 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
6009 *ResultType = Ty;
6010 }
6011
6012 InitListExpr *StructuredInitList =
6013 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006014 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00006015 CurInit = shouldBindAsTemporary(InitEntity)
6016 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006017 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006018 break;
6019 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006020
Sebastian Redled2e5322011-12-22 14:44:04 +00006021 case SK_ListConstructorCall: {
Sebastian Redl5a41f682012-02-12 16:37:24 +00006022 // When an initializer list is passed for a parameter of type "reference
6023 // to object", we don't get an EK_Temporary entity, but instead an
6024 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00006025 // FIXME: This is a hack. What we really should do is create a user
6026 // conversion step for this case, but this makes it considerably more
6027 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00006028 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6029 Entity.getType().getNonReferenceType());
6030 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00006031 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006032 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00006033 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6034 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006035 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00006036 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6037 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006038 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006039 ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006040 /*IsListInitialization*/ true,
6041 InitList->getLBraceLoc(),
6042 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00006043 break;
6044 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006045
Sebastian Redl29526f02011-11-27 16:50:07 +00006046 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006047 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00006048 break;
6049
6050 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006051 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00006052 InitListExpr *Syntactic = Step->WrappingSyntacticList;
6053 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00006054 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00006055 ILE->setSyntacticForm(Syntactic);
6056 ILE->setType(E->getType());
6057 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006058 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00006059 break;
6060 }
6061
Sebastian Redl99f66162012-02-19 12:27:56 +00006062 case SK_ConstructorInitialization: {
6063 // When an initializer list is passed for a parameter of type "reference
6064 // to object", we don't get an EK_Temporary entity, but instead an
6065 // EK_Parameter entity with reference type.
6066 // FIXME: This is a hack. What we really should do is create a user
6067 // conversion step for this case, but this makes it considerably more
6068 // complicated. For now, this will do.
6069 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6070 Entity.getType().getNonReferenceType());
6071 bool UseTemporary = Entity.getType()->isReferenceType();
6072 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
6073 : Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006074 Kind, Args, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006075 ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006076 /*IsListInitialization*/ false,
6077 /*LBraceLoc*/ SourceLocation(),
6078 /*RBraceLoc*/ SourceLocation());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006079 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00006080 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006081
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006082 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006083 step_iterator NextStep = Step;
6084 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006085 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00006086 (NextStep->Kind == SK_ConstructorInitialization ||
6087 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006088 // The need for zero-initialization is recorded directly into
6089 // the call to the object's constructor within the next step.
6090 ConstructorInitRequiresZeroInit = true;
6091 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006092 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006093 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00006094 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6095 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006096 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00006097 Kind.getRange().getBegin());
6098
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006099 CurInit = new (S.Context) CXXScalarValueInitExpr(
6100 TSInfo->getType().getNonLValueExprType(S.Context), TSInfo,
6101 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006102 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006103 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006104 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006105 break;
6106 }
Douglas Gregore1314a62009-12-18 05:02:21 +00006107
6108 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00006109 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006110 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00006111 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00006112 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6113 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00006114 if (Result.isInvalid())
6115 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006116 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00006117
6118 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006119 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00006120 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006121 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00006122 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00006123 == Sema::Compatible)
6124 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00006125 if (CurInitExprRes.isInvalid())
6126 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006127 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00006128
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006129 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00006130 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6131 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00006132 CurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00006133 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006134 &Complained)) {
6135 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00006136 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006137 } else if (Complained)
6138 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00006139 break;
6140 }
Eli Friedman78275202009-12-19 08:11:05 +00006141
6142 case SK_StringInit: {
6143 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00006144 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00006145 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00006146 break;
6147 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006148
6149 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006150 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00006151 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00006152 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006153 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006154
6155 case SK_ArrayInit:
6156 // Okay: we checked everything before creating this step. Note that
6157 // this is a GNU extension.
6158 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00006159 << Step->Type << CurInit.get()->getType()
6160 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00006161
6162 // If the destination type is an incomplete array type, update the
6163 // type accordingly.
6164 if (ResultType) {
6165 if (const IncompleteArrayType *IncompleteDest
6166 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6167 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00006168 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00006169 *ResultType = S.Context.getConstantArrayType(
6170 IncompleteDest->getElementType(),
6171 ConstantSource->getSize(),
6172 ArrayType::Normal, 0);
6173 }
6174 }
6175 }
John McCall31168b02011-06-15 23:02:42 +00006176 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006177
Richard Smithebeed412012-02-15 22:38:09 +00006178 case SK_ParenthesizedArrayInit:
6179 // Okay: we checked everything before creating this step. Note that
6180 // this is a GNU extension.
6181 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6182 << CurInit.get()->getSourceRange();
6183 break;
6184
John McCall31168b02011-06-15 23:02:42 +00006185 case SK_PassByIndirectCopyRestore:
6186 case SK_PassByIndirectRestore:
6187 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006188 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
6189 CurInit.get(), Step->Type,
6190 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00006191 break;
6192
6193 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006194 CurInit =
6195 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
6196 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00006197 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006198
6199 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006200 S.Diag(CurInit.get()->getExprLoc(),
6201 diag::warn_cxx98_compat_initializer_list_init)
6202 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00006203
Richard Smithcc1b96d2013-06-12 22:31:48 +00006204 // Materialize the temporary into memory.
6205 MaterializeTemporaryExpr *MTE = new (S.Context)
6206 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00006207 /*BoundToLvalueReference=*/false);
6208
6209 // Maybe lifetime-extend the array temporary's subobjects to match the
6210 // entity's lifetime.
6211 if (const InitializedEntity *ExtendingEntity =
6212 getEntityForTemporaryLifetimeExtension(&Entity))
6213 if (performReferenceExtension(MTE, ExtendingEntity))
6214 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6215 /*IsInitializerList=*/true,
6216 ExtendingEntity->getDecl());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006217
6218 // Wrap it in a construction of a std::initializer_list<T>.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006219 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006220
6221 // Bind the result, in case the library has given initializer_list a
6222 // non-trivial destructor.
6223 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006224 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00006225 break;
6226 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006227
Guy Benyei61054192013-02-07 10:55:47 +00006228 case SK_OCLSamplerInit: {
6229 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006230 "Sampler initialization on non-sampler type.");
Guy Benyei61054192013-02-07 10:55:47 +00006231
6232 QualType SourceType = CurInit.get()->getType();
Guy Benyei61054192013-02-07 10:55:47 +00006233
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006234 if (Entity.isParameterKind()) {
Guy Benyei61054192013-02-07 10:55:47 +00006235 if (!SourceType->isSamplerT())
6236 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6237 << SourceType;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006238 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
Guy Benyei61054192013-02-07 10:55:47 +00006239 llvm_unreachable("Invalid EntityKind!");
6240 }
6241
6242 break;
6243 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006244 case SK_OCLZeroEvent: {
6245 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006246 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006247
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006248 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006249 CK_ZeroToOCLEvent,
6250 CurInit.get()->getValueKind());
6251 break;
6252 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006253 }
6254 }
John McCall1f425642010-11-11 03:21:53 +00006255
6256 // Diagnose non-fatal problems with the completed initialization.
6257 if (Entity.getKind() == InitializedEntity::EK_Member &&
6258 cast<FieldDecl>(Entity.getDecl())->isBitField())
6259 S.CheckBitFieldInitialization(Kind.getLocation(),
6260 cast<FieldDecl>(Entity.getDecl()),
6261 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006262
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006263 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006264}
6265
Richard Smith593f9932012-12-08 02:01:17 +00006266/// Somewhere within T there is an uninitialized reference subobject.
6267/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00006268static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6269 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00006270 if (T->isReferenceType()) {
6271 S.Diag(Loc, diag::err_reference_without_init)
6272 << T.getNonReferenceType();
6273 return true;
6274 }
6275
6276 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6277 if (!RD || !RD->hasUninitializedReferenceMember())
6278 return false;
6279
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006280 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00006281 if (FI->isUnnamedBitfield())
6282 continue;
6283
6284 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6285 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6286 return true;
6287 }
6288 }
6289
Aaron Ballman574705e2014-03-13 15:41:46 +00006290 for (const auto &BI : RD->bases()) {
6291 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00006292 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6293 return true;
6294 }
6295 }
6296
6297 return false;
6298}
6299
6300
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006301//===----------------------------------------------------------------------===//
6302// Diagnose initialization failures
6303//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00006304
6305/// Emit notes associated with an initialization that failed due to a
6306/// "simple" conversion failure.
6307static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6308 Expr *op) {
6309 QualType destType = entity.getType();
6310 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6311 op->getType()->isObjCObjectPointerType()) {
6312
6313 // Emit a possible note about the conversion failing because the
6314 // operand is a message send with a related result type.
6315 S.EmitRelatedResultTypeNote(op);
6316
6317 // Emit a possible note about a return failing because we're
6318 // expecting a related result type.
6319 if (entity.getKind() == InitializedEntity::EK_Result)
6320 S.EmitRelatedResultTypeNoteForReturn(destType);
6321 }
6322}
6323
Richard Smith0449aaf2013-11-21 23:30:57 +00006324static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6325 InitListExpr *InitList) {
6326 QualType DestType = Entity.getType();
6327
6328 QualType E;
6329 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6330 QualType ArrayType = S.Context.getConstantArrayType(
6331 E.withConst(),
6332 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6333 InitList->getNumInits()),
6334 clang::ArrayType::Normal, 0);
6335 InitializedEntity HiddenArray =
6336 InitializedEntity::InitializeTemporary(ArrayType);
6337 return diagnoseListInit(S, HiddenArray, InitList);
6338 }
6339
6340 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
6341 /*VerifyOnly=*/false);
6342 assert(DiagnoseInitList.HadError() &&
6343 "Inconsistent init list check result.");
6344}
6345
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006346bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006347 const InitializedEntity &Entity,
6348 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006349 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006350 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006351 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006352
Douglas Gregor1b303932009-12-22 15:35:07 +00006353 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006354 switch (Failure) {
6355 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006356 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006357 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00006358 // Dig out the reference subobject which is uninitialized and diagnose it.
6359 // If this is value-initialization, this could be nested some way within
6360 // the target type.
6361 assert(Kind.getKind() == InitializationKind::IK_Value ||
6362 DestType->isReferenceType());
6363 bool Diagnosed =
6364 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6365 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6366 (void)Diagnosed;
6367 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006368 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006369 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006370 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006371
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006372 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006373 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006374 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006375 case FK_ArrayNeedsInitListOrStringLiteral:
6376 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6377 break;
6378 case FK_ArrayNeedsInitListOrWideStringLiteral:
6379 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6380 break;
6381 case FK_NarrowStringIntoWideCharArray:
6382 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6383 break;
6384 case FK_WideStringIntoCharArray:
6385 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6386 break;
6387 case FK_IncompatWideStringIntoWideChar:
6388 S.Diag(Kind.getLocation(),
6389 diag::err_array_init_incompat_wide_string_into_wchar);
6390 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006391 case FK_ArrayTypeMismatch:
6392 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00006393 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00006394 (Failure == FK_ArrayTypeMismatch
6395 ? diag::err_array_init_different_type
6396 : diag::err_array_init_non_constant_array))
6397 << DestType.getNonReferenceType()
6398 << Args[0]->getType()
6399 << Args[0]->getSourceRange();
6400 break;
6401
John McCalla59dc2f2012-01-05 00:13:19 +00006402 case FK_VariableLengthArrayHasInitializer:
6403 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6404 << Args[0]->getSourceRange();
6405 break;
6406
John McCall16df1e52010-03-30 21:47:33 +00006407 case FK_AddressOfOverloadFailed: {
6408 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006409 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006410 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00006411 true,
6412 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006413 break;
John McCall16df1e52010-03-30 21:47:33 +00006414 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006415
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006416 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00006417 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006418 switch (FailedOverloadResult) {
6419 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00006420 if (Failure == FK_UserConversionOverloadFailed)
6421 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6422 << Args[0]->getType() << DestType
6423 << Args[0]->getSourceRange();
6424 else
6425 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6426 << DestType << Args[0]->getType()
6427 << Args[0]->getSourceRange();
6428
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006429 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006430 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006431
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006432 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00006433 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00006434 DestType.getNonReferenceType(),
6435 diag::err_typecheck_nonviable_condition_incomplete,
6436 Args[0]->getType(), Args[0]->getSourceRange()))
6437 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6438 << Args[0]->getType() << Args[0]->getSourceRange()
6439 << DestType.getNonReferenceType();
6440
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006441 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006442 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006443
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006444 case OR_Deleted: {
6445 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6446 << Args[0]->getType() << DestType.getNonReferenceType()
6447 << Args[0]->getSourceRange();
6448 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006449 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00006450 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6451 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006452 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00006453 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006454 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006455 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006456 }
6457 break;
6458 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006459
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006460 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006461 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006462 }
6463 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006464
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006465 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00006466 if (isa<InitListExpr>(Args[0])) {
6467 S.Diag(Kind.getLocation(),
6468 diag::err_lvalue_reference_bind_to_initlist)
6469 << DestType.getNonReferenceType().isVolatileQualified()
6470 << DestType.getNonReferenceType()
6471 << Args[0]->getSourceRange();
6472 break;
6473 }
6474 // Intentional fallthrough
6475
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006476 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006477 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006478 Failure == FK_NonConstLValueReferenceBindingToTemporary
6479 ? diag::err_lvalue_reference_bind_to_temporary
6480 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00006481 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006482 << DestType.getNonReferenceType()
6483 << Args[0]->getType()
6484 << Args[0]->getSourceRange();
6485 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006486
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006487 case FK_RValueReferenceBindingToLValue:
6488 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00006489 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006490 << Args[0]->getSourceRange();
6491 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006492
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006493 case FK_ReferenceInitDropsQualifiers:
6494 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6495 << DestType.getNonReferenceType()
6496 << Args[0]->getType()
6497 << Args[0]->getSourceRange();
6498 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006499
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006500 case FK_ReferenceInitFailed:
6501 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6502 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00006503 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006504 << Args[0]->getType()
6505 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00006506 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006507 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006508
Douglas Gregorb491ed32011-02-19 21:32:49 +00006509 case FK_ConversionFailed: {
6510 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00006511 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00006512 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006513 << DestType
John McCall086a4642010-11-24 05:12:34 +00006514 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00006515 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006516 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00006517 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6518 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00006519 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00006520 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00006521 }
John Wiegley01296292011-04-08 18:41:53 +00006522
6523 case FK_ConversionFromPropertyFailed:
6524 // No-op. This error has already been reported.
6525 break;
6526
Douglas Gregor51e77d52009-12-10 17:56:55 +00006527 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00006528 SourceRange R;
6529
6530 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00006531 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00006532 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006533 else
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006534 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00006535
Alp Tokerb6cc5922014-05-03 03:45:55 +00006536 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00006537 if (Kind.isCStyleOrFunctionalCast())
6538 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6539 << R;
6540 else
6541 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6542 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006543 break;
6544 }
6545
6546 case FK_ReferenceBindingToInitList:
6547 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6548 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6549 break;
6550
6551 case FK_InitListBadDestinationType:
6552 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6553 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6554 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006555
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006556 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006557 case FK_ConstructorOverloadFailed: {
6558 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006559 if (Args.size())
6560 ArgsRange = SourceRange(Args.front()->getLocStart(),
6561 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006562
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006563 if (Failure == FK_ListConstructorOverloadFailed) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006564 assert(Args.size() == 1 && "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006565 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006566 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006567 }
6568
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006569 // FIXME: Using "DestType" for the entity we're printing is probably
6570 // bad.
6571 switch (FailedOverloadResult) {
6572 case OR_Ambiguous:
6573 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6574 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006575 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006576 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006577
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006578 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006579 if (Kind.getKind() == InitializationKind::IK_Default &&
6580 (Entity.getKind() == InitializedEntity::EK_Base ||
6581 Entity.getKind() == InitializedEntity::EK_Member) &&
6582 isa<CXXConstructorDecl>(S.CurContext)) {
6583 // This is implicit default initialization of a member or
6584 // base within a constructor. If no viable function was
6585 // found, notify the user that she needs to explicitly
6586 // initialize this base/member.
6587 CXXConstructorDecl *Constructor
6588 = cast<CXXConstructorDecl>(S.CurContext);
6589 if (Entity.getKind() == InitializedEntity::EK_Base) {
6590 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006591 << (Constructor->getInheritedConstructor() ? 2 :
6592 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006593 << S.Context.getTypeDeclType(Constructor->getParent())
6594 << /*base=*/0
6595 << Entity.getType();
6596
6597 RecordDecl *BaseDecl
6598 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6599 ->getDecl();
6600 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6601 << S.Context.getTagDeclType(BaseDecl);
6602 } else {
6603 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006604 << (Constructor->getInheritedConstructor() ? 2 :
6605 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006606 << S.Context.getTypeDeclType(Constructor->getParent())
6607 << /*member=*/1
6608 << Entity.getName();
Alp Toker2afa8782014-05-28 12:20:14 +00006609 S.Diag(Entity.getDecl()->getLocation(),
6610 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006611
6612 if (const RecordType *Record
6613 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006614 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006615 diag::note_previous_decl)
6616 << S.Context.getTagDeclType(Record->getDecl());
6617 }
6618 break;
6619 }
6620
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006621 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6622 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006623 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006624 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006625
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006626 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006627 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006628 OverloadingResult Ovl
6629 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00006630 if (Ovl != OR_Deleted) {
6631 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6632 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006633 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00006634 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006635 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00006636
6637 // If this is a defaulted or implicitly-declared function, then
6638 // it was implicitly deleted. Make it clear that the deletion was
6639 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00006640 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006641 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00006642 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006643 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00006644 else
6645 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6646 << true << DestType << ArgsRange;
6647
6648 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006649 break;
6650 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006651
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006652 case OR_Success:
6653 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006654 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006655 }
David Blaikie60deeee2012-01-17 08:24:58 +00006656 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006657
Douglas Gregor85dabae2009-12-16 01:38:02 +00006658 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006659 if (Entity.getKind() == InitializedEntity::EK_Member &&
6660 isa<CXXConstructorDecl>(S.CurContext)) {
6661 // This is implicit default-initialization of a const member in
6662 // a constructor. Complain that it needs to be explicitly
6663 // initialized.
6664 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6665 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006666 << (Constructor->getInheritedConstructor() ? 2 :
6667 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006668 << S.Context.getTypeDeclType(Constructor->getParent())
6669 << /*const=*/1
6670 << Entity.getName();
6671 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6672 << Entity.getName();
6673 } else {
6674 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6675 << DestType << (bool)DestType->getAs<RecordType>();
6676 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00006677 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006678
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006679 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00006680 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006681 diag::err_init_incomplete_type);
6682 break;
6683
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006684 case FK_ListInitializationFailed: {
6685 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00006686 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6687 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006688 break;
6689 }
John McCall4124c492011-10-17 18:40:02 +00006690
6691 case FK_PlaceholderType: {
6692 // FIXME: Already diagnosed!
6693 break;
6694 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00006695
Sebastian Redl048a6d72012-04-01 19:54:59 +00006696 case FK_ExplicitConstructor: {
6697 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6698 << Args[0]->getSourceRange();
6699 OverloadCandidateSet::iterator Best;
6700 OverloadingResult Ovl
6701 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00006702 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00006703 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6704 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6705 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6706 break;
6707 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006708 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006709
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006710 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006711 return true;
6712}
Douglas Gregore1314a62009-12-18 05:02:21 +00006713
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006714void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006715 switch (SequenceKind) {
6716 case FailedSequence: {
6717 OS << "Failed sequence: ";
6718 switch (Failure) {
6719 case FK_TooManyInitsForReference:
6720 OS << "too many initializers for reference";
6721 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006722
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006723 case FK_ArrayNeedsInitList:
6724 OS << "array requires initializer list";
6725 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006726
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006727 case FK_ArrayNeedsInitListOrStringLiteral:
6728 OS << "array requires initializer list or string literal";
6729 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006730
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006731 case FK_ArrayNeedsInitListOrWideStringLiteral:
6732 OS << "array requires initializer list or wide string literal";
6733 break;
6734
6735 case FK_NarrowStringIntoWideCharArray:
6736 OS << "narrow string into wide char array";
6737 break;
6738
6739 case FK_WideStringIntoCharArray:
6740 OS << "wide string into char array";
6741 break;
6742
6743 case FK_IncompatWideStringIntoWideChar:
6744 OS << "incompatible wide string into wide char array";
6745 break;
6746
Douglas Gregore2f943b2011-02-22 18:29:51 +00006747 case FK_ArrayTypeMismatch:
6748 OS << "array type mismatch";
6749 break;
6750
6751 case FK_NonConstantArrayInit:
6752 OS << "non-constant array initializer";
6753 break;
6754
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006755 case FK_AddressOfOverloadFailed:
6756 OS << "address of overloaded function failed";
6757 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006758
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006759 case FK_ReferenceInitOverloadFailed:
6760 OS << "overload resolution for reference initialization failed";
6761 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006762
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006763 case FK_NonConstLValueReferenceBindingToTemporary:
6764 OS << "non-const lvalue reference bound to temporary";
6765 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006766
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006767 case FK_NonConstLValueReferenceBindingToUnrelated:
6768 OS << "non-const lvalue reference bound to unrelated type";
6769 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006770
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006771 case FK_RValueReferenceBindingToLValue:
6772 OS << "rvalue reference bound to an lvalue";
6773 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006774
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006775 case FK_ReferenceInitDropsQualifiers:
6776 OS << "reference initialization drops qualifiers";
6777 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006778
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006779 case FK_ReferenceInitFailed:
6780 OS << "reference initialization failed";
6781 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006782
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006783 case FK_ConversionFailed:
6784 OS << "conversion failed";
6785 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006786
John Wiegley01296292011-04-08 18:41:53 +00006787 case FK_ConversionFromPropertyFailed:
6788 OS << "conversion from property failed";
6789 break;
6790
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006791 case FK_TooManyInitsForScalar:
6792 OS << "too many initializers for scalar";
6793 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006794
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006795 case FK_ReferenceBindingToInitList:
6796 OS << "referencing binding to initializer list";
6797 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006798
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006799 case FK_InitListBadDestinationType:
6800 OS << "initializer list for non-aggregate, non-scalar type";
6801 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006802
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006803 case FK_UserConversionOverloadFailed:
6804 OS << "overloading failed for user-defined conversion";
6805 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006806
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006807 case FK_ConstructorOverloadFailed:
6808 OS << "constructor overloading failed";
6809 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006810
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006811 case FK_DefaultInitOfConst:
6812 OS << "default initialization of a const variable";
6813 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006814
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00006815 case FK_Incomplete:
6816 OS << "initialization of incomplete type";
6817 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006818
6819 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006820 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00006821 break;
6822
John McCalla59dc2f2012-01-05 00:13:19 +00006823 case FK_VariableLengthArrayHasInitializer:
6824 OS << "variable length array has an initializer";
6825 break;
6826
John McCall4124c492011-10-17 18:40:02 +00006827 case FK_PlaceholderType:
6828 OS << "initializer expression isn't contextually valid";
6829 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00006830
6831 case FK_ListConstructorOverloadFailed:
6832 OS << "list constructor overloading failed";
6833 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006834
Sebastian Redl048a6d72012-04-01 19:54:59 +00006835 case FK_ExplicitConstructor:
6836 OS << "list copy initialization chose explicit constructor";
6837 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006838 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006839 OS << '\n';
6840 return;
6841 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006842
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006843 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00006844 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006845 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006846
Sebastian Redld201edf2011-06-05 13:59:11 +00006847 case NormalSequence:
6848 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006849 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006850 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006851
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006852 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6853 if (S != step_begin()) {
6854 OS << " -> ";
6855 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006856
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006857 switch (S->Kind) {
6858 case SK_ResolveAddressOfOverloadedFunction:
6859 OS << "resolve address of overloaded function";
6860 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006861
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006862 case SK_CastDerivedToBaseRValue:
6863 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6864 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006865
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006866 case SK_CastDerivedToBaseXValue:
6867 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6868 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006869
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006870 case SK_CastDerivedToBaseLValue:
6871 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6872 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006873
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006874 case SK_BindReference:
6875 OS << "bind reference to lvalue";
6876 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006877
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006878 case SK_BindReferenceToTemporary:
6879 OS << "bind reference to a temporary";
6880 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006881
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006882 case SK_ExtraneousCopyToTemporary:
6883 OS << "extraneous C++03 copy to temporary";
6884 break;
6885
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006886 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00006887 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006888 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006889
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006890 case SK_QualificationConversionRValue:
6891 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00006892 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006893
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006894 case SK_QualificationConversionXValue:
6895 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00006896 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006897
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006898 case SK_QualificationConversionLValue:
6899 OS << "qualification conversion (lvalue)";
6900 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006901
Jordan Roseb1312a52013-04-11 00:58:58 +00006902 case SK_LValueToRValue:
6903 OS << "load (lvalue to rvalue)";
6904 break;
6905
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006906 case SK_ConversionSequence:
6907 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00006908 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006909 OS << ")";
6910 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006911
Richard Smithaaa0ec42013-09-21 21:19:19 +00006912 case SK_ConversionSequenceNoNarrowing:
6913 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00006914 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00006915 OS << ")";
6916 break;
6917
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006918 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006919 OS << "list aggregate initialization";
6920 break;
6921
6922 case SK_ListConstructorCall:
6923 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006924 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006925
Sebastian Redl29526f02011-11-27 16:50:07 +00006926 case SK_UnwrapInitList:
6927 OS << "unwrap reference initializer list";
6928 break;
6929
6930 case SK_RewrapInitList:
6931 OS << "rewrap reference initializer list";
6932 break;
6933
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006934 case SK_ConstructorInitialization:
6935 OS << "constructor initialization";
6936 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006937
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006938 case SK_ZeroInitialization:
6939 OS << "zero initialization";
6940 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006941
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006942 case SK_CAssignment:
6943 OS << "C assignment";
6944 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006945
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006946 case SK_StringInit:
6947 OS << "string initialization";
6948 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006949
6950 case SK_ObjCObjectConversion:
6951 OS << "Objective-C object conversion";
6952 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006953
6954 case SK_ArrayInit:
6955 OS << "array initialization";
6956 break;
John McCall31168b02011-06-15 23:02:42 +00006957
Richard Smithebeed412012-02-15 22:38:09 +00006958 case SK_ParenthesizedArrayInit:
6959 OS << "parenthesized array initialization";
6960 break;
6961
John McCall31168b02011-06-15 23:02:42 +00006962 case SK_PassByIndirectCopyRestore:
6963 OS << "pass by indirect copy and restore";
6964 break;
6965
6966 case SK_PassByIndirectRestore:
6967 OS << "pass by indirect restore";
6968 break;
6969
6970 case SK_ProduceObjCObject:
6971 OS << "Objective-C object retension";
6972 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006973
6974 case SK_StdInitializerList:
6975 OS << "std::initializer_list from initializer list";
6976 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006977
Guy Benyei61054192013-02-07 10:55:47 +00006978 case SK_OCLSamplerInit:
6979 OS << "OpenCL sampler_t from integer constant";
6980 break;
6981
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006982 case SK_OCLZeroEvent:
6983 OS << "OpenCL event_t from zero";
6984 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006985 }
Richard Smith6b216962013-02-05 05:52:24 +00006986
6987 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006988 }
Richard Smith6b216962013-02-05 05:52:24 +00006989
6990 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006991}
6992
6993void InitializationSequence::dump() const {
6994 dump(llvm::errs());
6995}
6996
Richard Smithaaa0ec42013-09-21 21:19:19 +00006997static void DiagnoseNarrowingInInitList(Sema &S,
6998 const ImplicitConversionSequence &ICS,
6999 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007000 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007001 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007002 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00007003 switch (ICS.getKind()) {
7004 case ImplicitConversionSequence::StandardConversion:
7005 SCS = &ICS.Standard;
7006 break;
7007 case ImplicitConversionSequence::UserDefinedConversion:
7008 SCS = &ICS.UserDefined.After;
7009 break;
7010 case ImplicitConversionSequence::AmbiguousConversion:
7011 case ImplicitConversionSequence::EllipsisConversion:
7012 case ImplicitConversionSequence::BadConversion:
7013 return;
7014 }
7015
Richard Smith66e05fe2012-01-18 05:21:49 +00007016 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
7017 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00007018 QualType ConstantType;
7019 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
7020 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00007021 case NK_Not_Narrowing:
7022 // No narrowing occurred.
7023 return;
7024
7025 case NK_Type_Narrowing:
7026 // This was a floating-to-integer conversion, which is always considered a
7027 // narrowing conversion even if the value is a constant and can be
7028 // represented exactly as an integer.
7029 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007030 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7031 ? diag::warn_init_list_type_narrowing
7032 : diag::ext_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007033 << PostInit->getSourceRange()
7034 << PreNarrowingType.getLocalUnqualifiedType()
7035 << EntityType.getLocalUnqualifiedType();
7036 break;
7037
7038 case NK_Constant_Narrowing:
7039 // A constant value was narrowed.
7040 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007041 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7042 ? diag::warn_init_list_constant_narrowing
7043 : diag::ext_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007044 << PostInit->getSourceRange()
Richard Smith5614ca72012-03-23 23:55:39 +00007045 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007046 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007047 break;
7048
7049 case NK_Variable_Narrowing:
7050 // A variable's value may have been narrowed.
7051 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007052 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7053 ? diag::warn_init_list_variable_narrowing
7054 : diag::ext_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007055 << PostInit->getSourceRange()
7056 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007057 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007058 break;
7059 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007060
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007061 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007062 llvm::raw_svector_ostream OS(StaticCast);
7063 OS << "static_cast<";
7064 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7065 // It's important to use the typedef's name if there is one so that the
7066 // fixit doesn't break code using types like int64_t.
7067 //
7068 // FIXME: This will break if the typedef requires qualification. But
7069 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007070 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007071 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00007072 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007073 else {
7074 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
7075 // with a broken cast.
7076 return;
7077 }
7078 OS << ">(";
Alp Tokerb0869032014-05-17 01:13:18 +00007079 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007080 << PostInit->getSourceRange()
7081 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
7082 << FixItHint::CreateInsertion(
7083 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007084}
7085
Douglas Gregore1314a62009-12-18 05:02:21 +00007086//===----------------------------------------------------------------------===//
7087// Initialization helper functions
7088//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00007089bool
7090Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7091 ExprResult Init) {
7092 if (Init.isInvalid())
7093 return false;
7094
7095 Expr *InitE = Init.get();
7096 assert(InitE && "No initialization expression");
7097
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00007098 InitializationKind Kind
7099 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007100 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00007101 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00007102}
7103
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007104ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00007105Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7106 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007107 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00007108 bool TopLevelOfInitList,
7109 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00007110 if (Init.isInvalid())
7111 return ExprError();
7112
John McCall1f425642010-11-11 03:21:53 +00007113 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00007114 assert(InitE && "No initialization expression?");
7115
7116 if (EqualLoc.isInvalid())
7117 EqualLoc = InitE->getLocStart();
7118
7119 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00007120 EqualLoc,
7121 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00007122 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007123 Init.get();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007124
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007125 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00007126
Richard Smith66e05fe2012-01-18 05:21:49 +00007127 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00007128}