blob: f748db943a121fb1c6928e3898c59b4cf66b02c5 [file] [log] [blame]
Steve Naroff0cca7492008-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 Redl5d3d41d2011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattnerdd8e0062009-02-24 22:27:37 +000011//
Steve Naroff0cca7492008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
John McCall19510852010-08-20 18:27:03 +000014#include "clang/Sema/Designator.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000018#include "clang/Lex/Preprocessor.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000019#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000023#include "clang/AST/TypeLoc.h"
Sebastian Redl2b916b82012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskin19159132011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000028#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000029using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000030
Chris Lattnerdd8e0062009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
John McCallce6c9b72011-02-21 07:22:22 +000035static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
36 ASTContext &Context) {
Eli Friedman8718a6a2009-05-29 18:22:49 +000037 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38 return 0;
39
Chris Lattner8879e3b2009-02-26 23:26:43 +000040 // See if this is a string literal or @encode.
41 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000042
Chris Lattner8879e3b2009-02-26 23:26:43 +000043 // Handle @encode, which is a narrow string.
44 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
45 return Init;
46
47 // Otherwise we can only handle string literals.
48 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000049 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000050
51 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregor5cee1192011-07-27 05:40:30 +000052
53 switch (SL->getKind()) {
54 case StringLiteral::Ascii:
55 case StringLiteral::UTF8:
56 // char array can be initialized with a narrow string.
57 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedmanbb6415c2009-05-31 10:54:53 +000058 return ElemTy->isCharType() ? Init : 0;
Douglas Gregor5cee1192011-07-27 05:40:30 +000059 case StringLiteral::UTF16:
60 return ElemTy->isChar16Type() ? Init : 0;
61 case StringLiteral::UTF32:
62 return ElemTy->isChar32Type() ? Init : 0;
63 case StringLiteral::Wide:
64 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
65 // correction from DR343): "An array with element type compatible with a
66 // qualified or unqualified version of wchar_t may be initialized by a wide
67 // string literal, optionally enclosed in braces."
68 if (Context.typesAreCompatible(Context.getWCharType(),
69 ElemTy.getUnqualifiedType()))
70 return Init;
Chris Lattner8879e3b2009-02-26 23:26:43 +000071
Douglas Gregor5cee1192011-07-27 05:40:30 +000072 return 0;
73 }
Mike Stump1eb44332009-09-09 15:08:12 +000074
Douglas Gregor5cee1192011-07-27 05:40:30 +000075 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattnerdd8e0062009-02-24 22:27:37 +000076}
77
John McCallce6c9b72011-02-21 07:22:22 +000078static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
79 const ArrayType *arrayType = Context.getAsArrayType(declType);
80 if (!arrayType) return 0;
81
82 return IsStringInit(init, arrayType, Context);
83}
84
John McCallfef8b342011-02-21 07:57:55 +000085static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
86 Sema &S) {
Chris Lattner79e079d2009-02-24 23:10:27 +000087 // Get the length of the string as parsed.
88 uint64_t StrLength =
89 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
90
Mike Stump1eb44332009-09-09 15:08:12 +000091
Chris Lattnerdd8e0062009-02-24 22:27:37 +000092 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000093 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000094 // being initialized to a string literal.
95 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000096 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000097 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000098 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
99 ConstVal,
100 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000101 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000102 }
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Eli Friedman8718a6a2009-05-29 18:22:49 +0000104 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000106 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-05-29 18:22:49 +0000107 // the size may be smaller or larger than the string we are initializing.
108 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikie4e4d0842012-03-11 07:00:24 +0000109 if (S.getLangOpts().CPlusPlus) {
Anders Carlssonb8fc45f2011-04-14 00:41:11 +0000110 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
111 // For Pascal strings it's OK to strip off the terminating null character,
112 // so the example below is valid:
113 //
114 // unsigned char a[2] = "\pa";
115 if (SL->isPascal())
116 StrLength--;
117 }
118
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000119 // [dcl.init.string]p2
120 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000121 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000122 diag::err_initializer_string_for_char_array_too_long)
123 << Str->getSourceRange();
124 } else {
125 // C99 6.7.8p14.
126 if (StrLength-1 > CAT->getSize().getZExtValue())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000127 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000128 diag::warn_initializer_string_for_char_array_too_long)
129 << Str->getSourceRange();
130 }
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Eli Friedman8718a6a2009-05-29 18:22:49 +0000132 // Set the type to the actual size that we are initializing. If we have
133 // something like:
134 // char x[1] = "foo";
135 // then this will set the string literal's type to char[1].
136 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000137}
138
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000139//===----------------------------------------------------------------------===//
140// Semantic checking for initializer lists.
141//===----------------------------------------------------------------------===//
142
Douglas Gregor9e80f722009-01-29 01:05:33 +0000143/// @brief Semantic checking for initializer lists.
144///
145/// The InitListChecker class contains a set of routines that each
146/// handle the initialization of a certain kind of entity, e.g.,
147/// arrays, vectors, struct/union types, scalars, etc. The
148/// InitListChecker itself performs a recursive walk of the subobject
149/// structure of the type to be initialized, while stepping through
150/// the initializer list one element at a time. The IList and Index
151/// parameters to each of the Check* routines contain the active
152/// (syntactic) initializer list and the index into that initializer
153/// list that represents the current initializer. Each routine is
154/// responsible for moving that Index forward as it consumes elements.
155///
156/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000157/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000158/// initializer list and the index into that initializer list where we
159/// are copying initializers as we map them over to the semantic
160/// list. Once we have completed our recursive walk of the subobject
161/// structure, we will have constructed a full semantic initializer
162/// list.
163///
164/// C99 designators cause changes in the initializer list traversal,
165/// because they make the initialization "jump" into a specific
166/// subobject and then continue the initialization from that
167/// point. CheckDesignatedInitializer() recursively steps into the
168/// designated subobject and manages backing out the recursion to
169/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000170namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000171class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000172 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000173 bool hadError;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000174 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redlc2235182011-10-16 18:19:28 +0000175 bool AllowBraceElision;
Benjamin Kramera7894162012-02-23 14:48:40 +0000176 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000177 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000178
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000179 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000180 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000181 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000182 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000183 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000184 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000185 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000186 unsigned &StructuredIndex,
187 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000188 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000189 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000190 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000191 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000192 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000193 unsigned &StructuredIndex,
194 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000195 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000196 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000197 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000198 InitListExpr *StructuredList,
199 unsigned &StructuredIndex);
Eli Friedman0c706c22011-09-19 23:17:44 +0000200 void CheckComplexType(const InitializedEntity &Entity,
201 InitListExpr *IList, QualType DeclType,
202 unsigned &Index,
203 InitListExpr *StructuredList,
204 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000205 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000206 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000207 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000208 InitListExpr *StructuredList,
209 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000210 void CheckReferenceType(const InitializedEntity &Entity,
211 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000212 unsigned &Index,
213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000215 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000216 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000217 InitListExpr *StructuredList,
218 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000219 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000220 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000221 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000222 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000223 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000224 unsigned &StructuredIndex,
225 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000226 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000227 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000228 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000229 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000230 InitListExpr *StructuredList,
231 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000232 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000233 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000234 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000235 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000236 RecordDecl::field_iterator *NextField,
237 llvm::APSInt *NextElementIndex,
238 unsigned &Index,
239 InitListExpr *StructuredList,
240 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000241 bool FinishSubobjectInit,
242 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000243 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
244 QualType CurrentObjectType,
245 InitListExpr *StructuredList,
246 unsigned StructuredIndex,
247 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000248 void UpdateStructuredListElement(InitListExpr *StructuredList,
249 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000250 Expr *expr);
251 int numArrayElements(QualType DeclType);
252 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000253
Douglas Gregord6d37de2009-12-22 00:05:34 +0000254 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
255 const InitializedEntity &ParentEntity,
256 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000257 void FillInValueInitializations(const InitializedEntity &Entity,
258 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000259 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
260 Expr *InitExpr, FieldDecl *Field,
261 bool TopLevelObject);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000262 void CheckValueInitializable(const InitializedEntity &Entity);
263
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000264public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000265 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlc2235182011-10-16 18:19:28 +0000266 InitListExpr *IL, QualType &T, bool VerifyOnly,
267 bool AllowBraceElision);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000268 bool HadError() { return hadError; }
269
270 // @brief Retrieves the fully-structured initializer list used for
271 // semantic analysis and code generation.
272 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
273};
Chris Lattner8b419b92009-02-24 22:48:58 +0000274} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000275
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000276void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
277 assert(VerifyOnly &&
278 "CheckValueInitializable is only inteded for verification mode.");
279
280 SourceLocation Loc;
281 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
282 true);
283 InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
284 if (InitSeq.Failed())
285 hadError = true;
286}
287
Douglas Gregord6d37de2009-12-22 00:05:34 +0000288void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
289 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000290 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000291 bool &RequiresSecondPass) {
Daniel Dunbar96a00142012-03-09 18:35:03 +0000292 SourceLocation Loc = ILE->getLocStart();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000293 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000294 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000295 = InitializedEntity::InitializeMember(Field, &ParentEntity);
296 if (Init >= NumInits || !ILE->getInit(Init)) {
297 // FIXME: We probably don't need to handle references
298 // specially here, since value-initialization of references is
299 // handled in InitializationSequence.
300 if (Field->getType()->isReferenceType()) {
301 // C++ [dcl.init.aggr]p9:
302 // If an incomplete or empty initializer-list leaves a
303 // member of reference type uninitialized, the program is
304 // ill-formed.
305 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
306 << Field->getType()
307 << ILE->getSyntacticForm()->getSourceRange();
308 SemaRef.Diag(Field->getLocation(),
309 diag::note_uninit_reference_member);
310 hadError = true;
311 return;
312 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000313
Douglas Gregord6d37de2009-12-22 00:05:34 +0000314 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
315 true);
316 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
317 if (!InitSeq) {
318 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
319 hadError = true;
320 return;
321 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000322
John McCall60d7b3a2010-08-24 06:29:42 +0000323 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000324 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000325 if (MemberInit.isInvalid()) {
326 hadError = true;
327 return;
328 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000329
Douglas Gregord6d37de2009-12-22 00:05:34 +0000330 if (hadError) {
331 // Do nothing
332 } else if (Init < NumInits) {
333 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000334 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000335 // Value-initialization requires a constructor call, so
336 // extend the initializer list to include the constructor
337 // call and make a note that we'll need to take another pass
338 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000339 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000340 RequiresSecondPass = true;
341 }
342 } else if (InitListExpr *InnerILE
343 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000344 FillInValueInitializations(MemberEntity, InnerILE,
345 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000346}
347
Douglas Gregor4c678342009-01-28 21:54:33 +0000348/// Recursively replaces NULL values within the given initializer list
349/// with expressions that perform value-initialization of the
350/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000351void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000352InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
353 InitListExpr *ILE,
354 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000355 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000356 "Should not have void type");
Daniel Dunbar96a00142012-03-09 18:35:03 +0000357 SourceLocation Loc = ILE->getLocStart();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000358 if (ILE->getSyntacticForm())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000359 Loc = ILE->getSyntacticForm()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Ted Kremenek6217b802009-07-29 21:53:49 +0000361 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000362 if (RType->getDecl()->isUnion() &&
363 ILE->getInitializedFieldInUnion())
364 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
365 Entity, ILE, RequiresSecondPass);
366 else {
367 unsigned Init = 0;
368 for (RecordDecl::field_iterator
369 Field = RType->getDecl()->field_begin(),
370 FieldEnd = RType->getDecl()->field_end();
371 Field != FieldEnd; ++Field) {
372 if (Field->isUnnamedBitfield())
373 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000374
Douglas Gregord6d37de2009-12-22 00:05:34 +0000375 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000376 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000377
378 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
379 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000380 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000381
Douglas Gregord6d37de2009-12-22 00:05:34 +0000382 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000383
Douglas Gregord6d37de2009-12-22 00:05:34 +0000384 // Only look at the first initialization of a union.
385 if (RType->getDecl()->isUnion())
386 break;
387 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000388 }
389
390 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000391 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000392
393 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000395 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000396 unsigned NumInits = ILE->getNumInits();
397 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000398 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000399 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000400 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
401 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000402 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000403 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000404 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000405 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000406 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000407 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000408 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000409 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000410 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000411
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000412
Douglas Gregor87fd7032009-02-02 17:43:21 +0000413 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000414 if (hadError)
415 return;
416
Anders Carlssond3d824d2010-01-23 04:34:47 +0000417 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
418 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000419 ElementEntity.setElementIndex(Init);
420
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000421 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
422 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000423 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
424 true);
425 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
426 if (!InitSeq) {
427 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000428 hadError = true;
429 return;
430 }
431
John McCall60d7b3a2010-08-24 06:29:42 +0000432 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000433 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000434 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000435 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000436 return;
437 }
438
439 if (hadError) {
440 // Do nothing
441 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000442 // For arrays, just set the expression used for value-initialization
443 // of the "holes" in the array.
444 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
445 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
446 else
447 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000448 } else {
449 // For arrays, just set the expression used for value-initialization
450 // of the rest of elements and exit.
451 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
452 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
453 return;
454 }
455
Sebastian Redl7491c492011-06-05 13:59:11 +0000456 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000457 // Value-initialization requires a constructor call, so
458 // extend the initializer list to include the constructor
459 // call and make a note that we'll need to take another pass
460 // through the initializer list.
461 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
462 RequiresSecondPass = true;
463 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000464 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000465 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000466 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000467 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000468 }
469}
470
Chris Lattner68355a52009-01-29 05:10:57 +0000471
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000472InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000473 InitListExpr *IL, QualType &T,
Sebastian Redlc2235182011-10-16 18:19:28 +0000474 bool VerifyOnly, bool AllowBraceElision)
Richard Smithb6f8d282011-12-20 04:00:21 +0000475 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000476 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000477
Eli Friedmanb85f7072008-05-19 19:16:24 +0000478 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000479 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000480 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000481 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000482 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000483 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000484 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000485
Sebastian Redl14b0c192011-09-24 17:48:00 +0000486 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000487 bool RequiresSecondPass = false;
488 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000489 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000490 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000491 RequiresSecondPass);
492 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000493}
494
495int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000496 // FIXME: use a proper constant
497 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000498 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000499 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000500 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
501 }
502 return maxElements;
503}
504
505int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000506 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000507 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000508 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000509 Field = structDecl->field_begin(),
510 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000511 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +0000512 if (!Field->isUnnamedBitfield())
Douglas Gregor4c678342009-01-28 21:54:33 +0000513 ++InitializableMembers;
514 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000515 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000516 return std::min(InitializableMembers, 1);
517 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000518}
519
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000520void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000521 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000522 QualType T, unsigned &Index,
523 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000524 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000525 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Steve Naroff0cca7492008-05-01 22:18:59 +0000527 if (T->isArrayType())
528 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000529 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000530 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000531 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000532 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000533 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000534 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000535
Eli Friedman402256f2008-05-25 13:49:22 +0000536 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000537 if (!VerifyOnly)
538 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
539 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000540 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000541 hadError = true;
542 return;
543 }
544
Douglas Gregor4c678342009-01-28 21:54:33 +0000545 // Build a structured initializer list corresponding to this subobject.
546 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000547 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
548 StructuredIndex,
Daniel Dunbar96a00142012-03-09 18:35:03 +0000549 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregored8a93d2009-03-01 17:12:46 +0000550 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000551 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000552
Douglas Gregor4c678342009-01-28 21:54:33 +0000553 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000554 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000555 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000556 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000557 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000558 StructuredSubobjectInitIndex);
Sebastian Redlc2235182011-10-16 18:19:28 +0000559
560 if (VerifyOnly) {
561 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
562 hadError = true;
563 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000564 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000565
Sebastian Redlc2235182011-10-16 18:19:28 +0000566 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000567 // Update the structured sub-object initializer so that it's ending
568 // range corresponds with the end of the last initializer it used.
569 if (EndIndex < ParentIList->getNumInits()) {
570 SourceLocation EndLoc
571 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
572 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
573 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000574
Sebastian Redlc2235182011-10-16 18:19:28 +0000575 // Complain about missing braces.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000576 if (T->isArrayType() || T->isRecordType()) {
577 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redlc2235182011-10-16 18:19:28 +0000578 AllowBraceElision ? diag::warn_missing_braces :
579 diag::err_missing_braces)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000580 << StructuredSubobjectInitList->getSourceRange()
581 << FixItHint::CreateInsertion(
582 StructuredSubobjectInitList->getLocStart(), "{")
583 << FixItHint::CreateInsertion(
584 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000585 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000586 "}");
Sebastian Redlc2235182011-10-16 18:19:28 +0000587 if (!AllowBraceElision)
588 hadError = true;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000589 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000590 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000591}
592
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000593void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000594 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000595 unsigned &Index,
596 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000597 unsigned &StructuredIndex,
598 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000599 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000600 if (!VerifyOnly) {
601 SyntacticToSemantic[IList] = StructuredList;
602 StructuredList->setSyntacticForm(IList);
603 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000604 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000605 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000606 if (!VerifyOnly) {
Eli Friedman5c89c392012-02-23 02:25:10 +0000607 QualType ExprTy = T;
608 if (!ExprTy->isArrayType())
609 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000610 IList->setType(ExprTy);
611 StructuredList->setType(ExprTy);
612 }
Eli Friedman638e1442008-05-25 13:22:35 +0000613 if (hadError)
614 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000615
Eli Friedman638e1442008-05-25 13:22:35 +0000616 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000617 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000618 if (VerifyOnly) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000619 if (SemaRef.getLangOpts().CPlusPlus ||
620 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000621 IList->getType()->isVectorType())) {
622 hadError = true;
623 }
624 return;
625 }
626
Eli Friedmane5408582009-05-29 20:20:05 +0000627 if (StructuredIndex == 1 &&
628 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000629 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
David Blaikie4e4d0842012-03-11 07:00:24 +0000630 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000631 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000632 hadError = true;
633 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000634 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000635 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000636 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000637 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000638 // Don't complain for incomplete types, since we'll get an error
639 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000640 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000641 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000642 CurrentObjectType->isArrayType()? 0 :
643 CurrentObjectType->isVectorType()? 1 :
644 CurrentObjectType->isScalarType()? 2 :
645 CurrentObjectType->isUnionType()? 3 :
646 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000647
648 unsigned DK = diag::warn_excess_initializers;
David Blaikie4e4d0842012-03-11 07:00:24 +0000649 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmane5408582009-05-29 20:20:05 +0000650 DK = diag::err_excess_initializers;
651 hadError = true;
652 }
David Blaikie4e4d0842012-03-11 07:00:24 +0000653 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman08634522009-07-07 21:53:06 +0000654 DK = diag::err_excess_initializers;
655 hadError = true;
656 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000657
Chris Lattner08202542009-02-24 22:50:46 +0000658 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000659 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000660 }
661 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000662
Sebastian Redl14b0c192011-09-24 17:48:00 +0000663 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
664 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000665 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000666 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000667 << FixItHint::CreateRemoval(IList->getLocStart())
668 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000669}
670
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000671void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000672 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000673 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000674 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000675 unsigned &Index,
676 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000677 unsigned &StructuredIndex,
678 bool TopLevelObject) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000679 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
680 // Explicitly braced initializer for complex type can be real+imaginary
681 // parts.
682 CheckComplexType(Entity, IList, DeclType, Index,
683 StructuredList, StructuredIndex);
684 } else if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000685 CheckScalarType(Entity, IList, DeclType, Index,
686 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000687 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000688 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000689 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000690 } else if (DeclType->isAggregateType()) {
691 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000692 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000693 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000694 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000695 StructuredList, StructuredIndex,
696 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000697 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000698 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000699 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000700 false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000701 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson784f6992010-01-23 20:13:41 +0000702 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000703 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000704 } else
David Blaikieb219cfc2011-09-23 05:06:16 +0000705 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000706 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
707 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000708 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000709 if (!VerifyOnly)
710 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
711 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000712 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000713 } else if (DeclType->isRecordType()) {
714 // C++ [dcl.init]p14:
715 // [...] If the class is an aggregate (8.5.1), and the initializer
716 // is a brace-enclosed list, see 8.5.1.
717 //
718 // Note: 8.5.1 is handled below; here, we diagnose the case where
719 // we have an initializer list and a destination type that is not
720 // an aggregate.
721 // FIXME: In C++0x, this is yet another form of initialization.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000722 if (!VerifyOnly)
723 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
724 << DeclType << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +0000725 hadError = true;
726 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000727 CheckReferenceType(Entity, IList, DeclType, Index,
728 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000729 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000730 if (!VerifyOnly)
731 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
732 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000733 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000734 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000735 if (!VerifyOnly)
736 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
737 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000738 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000739 }
740}
741
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000742void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000743 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000744 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000745 unsigned &Index,
746 InitListExpr *StructuredList,
747 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000748 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000749 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
750 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000751 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000752 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000753 = getStructuredSubobjectInit(IList, Index, ElemType,
754 StructuredList, StructuredIndex,
755 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000756 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000757 newStructuredList, newStructuredIndex);
758 ++StructuredIndex;
759 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000760 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000761 } else if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000762 return CheckScalarType(Entity, IList, ElemType, Index,
763 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000764 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000765 return CheckReferenceType(Entity, IList, ElemType, Index,
766 StructuredList, StructuredIndex);
767 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000768
John McCallfef8b342011-02-21 07:57:55 +0000769 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
770 // arrayType can be incomplete if we're initializing a flexible
771 // array member. There's nothing we can do with the completed
772 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000773
John McCallfef8b342011-02-21 07:57:55 +0000774 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000775 if (!VerifyOnly) {
776 CheckStringInit(Str, ElemType, arrayType, SemaRef);
777 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
778 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000779 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000780 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000781 }
John McCallfef8b342011-02-21 07:57:55 +0000782
783 // Fall through for subaggregate initialization.
784
David Blaikie4e4d0842012-03-11 07:00:24 +0000785 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCallfef8b342011-02-21 07:57:55 +0000786 // C++ [dcl.init.aggr]p12:
787 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000788 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000789 // an initializer-list. If the initializer can initialize a
790 // member, the member is initialized. [...]
791
792 // FIXME: Better EqualLoc?
793 InitializationKind Kind =
794 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
795 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
796
797 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000798 if (!VerifyOnly) {
Richard Smithb6f8d282011-12-20 04:00:21 +0000799 ExprResult Result =
800 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
801 if (Result.isInvalid())
802 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000803
Sebastian Redl14b0c192011-09-24 17:48:00 +0000804 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smithb6f8d282011-12-20 04:00:21 +0000805 Result.takeAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000806 }
John McCallfef8b342011-02-21 07:57:55 +0000807 ++Index;
808 return;
809 }
810
811 // Fall through for subaggregate initialization
812 } else {
813 // C99 6.7.8p13:
814 //
815 // The initializer for a structure or union object that has
816 // automatic storage duration shall be either an initializer
817 // list as described below, or a single expression that has
818 // compatible structure or union type. In the latter case, the
819 // initial value of the object, including unnamed members, is
820 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000821 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000822 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000823 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
824 !VerifyOnly)
John McCallfef8b342011-02-21 07:57:55 +0000825 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000826 if (ExprRes.isInvalid())
827 hadError = true;
828 else {
829 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
830 if (ExprRes.isInvalid())
831 hadError = true;
832 }
833 UpdateStructuredListElement(StructuredList, StructuredIndex,
834 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000835 ++Index;
836 return;
837 }
John Wiegley429bb272011-04-08 18:41:53 +0000838 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000839 // Fall through for subaggregate initialization
840 }
841
842 // C++ [dcl.init.aggr]p12:
843 //
844 // [...] Otherwise, if the member is itself a non-empty
845 // subaggregate, brace elision is assumed and the initializer is
846 // considered for the initialization of the first member of
847 // the subaggregate.
David Blaikie4e4d0842012-03-11 07:00:24 +0000848 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000849 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000850 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
851 StructuredIndex);
852 ++StructuredIndex;
853 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000854 if (!VerifyOnly) {
855 // We cannot initialize this element, so let
856 // PerformCopyInitialization produce the appropriate diagnostic.
857 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
858 SemaRef.Owned(expr),
859 /*TopLevelOfInitList=*/true);
860 }
John McCallfef8b342011-02-21 07:57:55 +0000861 hadError = true;
862 ++Index;
863 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000864 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000865}
866
Eli Friedman0c706c22011-09-19 23:17:44 +0000867void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
868 InitListExpr *IList, QualType DeclType,
869 unsigned &Index,
870 InitListExpr *StructuredList,
871 unsigned &StructuredIndex) {
872 assert(Index == 0 && "Index in explicit init list must be zero");
873
874 // As an extension, clang supports complex initializers, which initialize
875 // a complex number component-wise. When an explicit initializer list for
876 // a complex number contains two two initializers, this extension kicks in:
877 // it exepcts the initializer list to contain two elements convertible to
878 // the element type of the complex type. The first element initializes
879 // the real part, and the second element intitializes the imaginary part.
880
881 if (IList->getNumInits() != 2)
882 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
883 StructuredIndex);
884
885 // This is an extension in C. (The builtin _Complex type does not exist
886 // in the C++ standard.)
David Blaikie4e4d0842012-03-11 07:00:24 +0000887 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +0000888 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
889 << IList->getSourceRange();
890
891 // Initialize the complex number.
892 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
893 InitializedEntity ElementEntity =
894 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
895
896 for (unsigned i = 0; i < 2; ++i) {
897 ElementEntity.setElementIndex(Index);
898 CheckSubElementType(ElementEntity, IList, elementType, Index,
899 StructuredList, StructuredIndex);
900 }
901}
902
903
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000904void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000905 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000906 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000907 InitListExpr *StructuredList,
908 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000909 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-10-18 21:39:00 +0000910 if (!VerifyOnly)
911 SemaRef.Diag(IList->getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +0000912 SemaRef.getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +0000913 diag::warn_cxx98_compat_empty_scalar_initializer :
914 diag::err_empty_scalar_initializer)
915 << IList->getSourceRange();
David Blaikie4e4d0842012-03-11 07:00:24 +0000916 hadError = !SemaRef.getLangOpts().CPlusPlus0x;
Douglas Gregor4c678342009-01-28 21:54:33 +0000917 ++Index;
918 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000919 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000920 }
John McCallb934c2d2010-11-11 00:46:36 +0000921
922 Expr *expr = IList->getInit(Index);
923 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000924 if (!VerifyOnly)
925 SemaRef.Diag(SubIList->getLocStart(),
926 diag::warn_many_braces_around_scalar_init)
927 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000928
929 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
930 StructuredIndex);
931 return;
932 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000933 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +0000934 SemaRef.Diag(expr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000935 diag::err_designator_for_scalar_init)
936 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000937 hadError = true;
938 ++Index;
939 ++StructuredIndex;
940 return;
941 }
942
Sebastian Redl14b0c192011-09-24 17:48:00 +0000943 if (VerifyOnly) {
944 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
945 hadError = true;
946 ++Index;
947 return;
948 }
949
John McCallb934c2d2010-11-11 00:46:36 +0000950 ExprResult Result =
951 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000952 SemaRef.Owned(expr),
953 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +0000954
955 Expr *ResultExpr = 0;
956
957 if (Result.isInvalid())
958 hadError = true; // types weren't compatible.
959 else {
960 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000961
John McCallb934c2d2010-11-11 00:46:36 +0000962 if (ResultExpr != expr) {
963 // The type was promoted, update initializer list.
964 IList->setInit(Index, ResultExpr);
965 }
966 }
967 if (hadError)
968 ++StructuredIndex;
969 else
970 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
971 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000972}
973
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000974void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
975 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000976 unsigned &Index,
977 InitListExpr *StructuredList,
978 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000979 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000980 // FIXME: It would be wonderful if we could point at the actual member. In
981 // general, it would be useful to pass location information down the stack,
982 // so that we know the location (or decl) of the "current object" being
983 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000984 if (!VerifyOnly)
985 SemaRef.Diag(IList->getLocStart(),
986 diag::err_init_reference_member_uninitialized)
987 << DeclType
988 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +0000989 hadError = true;
990 ++Index;
991 ++StructuredIndex;
992 return;
993 }
Sebastian Redl14b0c192011-09-24 17:48:00 +0000994
995 Expr *expr = IList->getInit(Index);
David Blaikie4e4d0842012-03-11 07:00:24 +0000996 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus0x) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000997 if (!VerifyOnly)
998 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
999 << DeclType << IList->getSourceRange();
1000 hadError = true;
1001 ++Index;
1002 ++StructuredIndex;
1003 return;
1004 }
1005
1006 if (VerifyOnly) {
1007 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1008 hadError = true;
1009 ++Index;
1010 return;
1011 }
1012
1013 ExprResult Result =
1014 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1015 SemaRef.Owned(expr),
1016 /*TopLevelOfInitList=*/true);
1017
1018 if (Result.isInvalid())
1019 hadError = true;
1020
1021 expr = Result.takeAs<Expr>();
1022 IList->setInit(Index, expr);
1023
1024 if (hadError)
1025 ++StructuredIndex;
1026 else
1027 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1028 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001029}
1030
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001031void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001032 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001033 unsigned &Index,
1034 InitListExpr *StructuredList,
1035 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001036 const VectorType *VT = DeclType->getAs<VectorType>();
1037 unsigned maxElements = VT->getNumElements();
1038 unsigned numEltsInit = 0;
1039 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001040
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001041 if (Index >= IList->getNumInits()) {
1042 // Make sure the element type can be value-initialized.
1043 if (VerifyOnly)
1044 CheckValueInitializable(
1045 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1046 return;
1047 }
1048
David Blaikie4e4d0842012-03-11 07:00:24 +00001049 if (!SemaRef.getLangOpts().OpenCL) {
John McCall20e047a2010-10-30 00:11:39 +00001050 // If the initializing element is a vector, try to copy-initialize
1051 // instead of breaking it apart (which is doomed to failure anyway).
1052 Expr *Init = IList->getInit(Index);
1053 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001054 if (VerifyOnly) {
1055 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1056 hadError = true;
1057 ++Index;
1058 return;
1059 }
1060
John McCall20e047a2010-10-30 00:11:39 +00001061 ExprResult Result =
1062 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001063 SemaRef.Owned(Init),
1064 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001065
1066 Expr *ResultExpr = 0;
1067 if (Result.isInvalid())
1068 hadError = true; // types weren't compatible.
1069 else {
1070 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001071
John McCall20e047a2010-10-30 00:11:39 +00001072 if (ResultExpr != Init) {
1073 // The type was promoted, update initializer list.
1074 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001075 }
1076 }
John McCall20e047a2010-10-30 00:11:39 +00001077 if (hadError)
1078 ++StructuredIndex;
1079 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001080 UpdateStructuredListElement(StructuredList, StructuredIndex,
1081 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001082 ++Index;
1083 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001084 }
Mike Stump1eb44332009-09-09 15:08:12 +00001085
John McCall20e047a2010-10-30 00:11:39 +00001086 InitializedEntity ElementEntity =
1087 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001088
John McCall20e047a2010-10-30 00:11:39 +00001089 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1090 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001091 if (Index >= IList->getNumInits()) {
1092 if (VerifyOnly)
1093 CheckValueInitializable(ElementEntity);
John McCall20e047a2010-10-30 00:11:39 +00001094 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001095 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001096
John McCall20e047a2010-10-30 00:11:39 +00001097 ElementEntity.setElementIndex(Index);
1098 CheckSubElementType(ElementEntity, IList, elementType, Index,
1099 StructuredList, StructuredIndex);
1100 }
1101 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001102 }
John McCall20e047a2010-10-30 00:11:39 +00001103
1104 InitializedEntity ElementEntity =
1105 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001106
John McCall20e047a2010-10-30 00:11:39 +00001107 // OpenCL initializers allows vectors to be constructed from vectors.
1108 for (unsigned i = 0; i < maxElements; ++i) {
1109 // Don't attempt to go past the end of the init list
1110 if (Index >= IList->getNumInits())
1111 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001112
John McCall20e047a2010-10-30 00:11:39 +00001113 ElementEntity.setElementIndex(Index);
1114
1115 QualType IType = IList->getInit(Index)->getType();
1116 if (!IType->isVectorType()) {
1117 CheckSubElementType(ElementEntity, IList, elementType, Index,
1118 StructuredList, StructuredIndex);
1119 ++numEltsInit;
1120 } else {
1121 QualType VecType;
1122 const VectorType *IVT = IType->getAs<VectorType>();
1123 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001124
John McCall20e047a2010-10-30 00:11:39 +00001125 if (IType->isExtVectorType())
1126 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1127 else
1128 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001129 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001130 CheckSubElementType(ElementEntity, IList, VecType, Index,
1131 StructuredList, StructuredIndex);
1132 numEltsInit += numIElts;
1133 }
1134 }
1135
1136 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001137 if (numEltsInit != maxElements) {
1138 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001139 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001140 diag::err_vector_incorrect_num_initializers)
1141 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1142 hadError = true;
1143 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001144}
1145
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001146void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001147 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001148 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001149 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001150 unsigned &Index,
1151 InitListExpr *StructuredList,
1152 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001153 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1154
Steve Naroff0cca7492008-05-01 22:18:59 +00001155 // Check for the special-case of initializing an array with a string.
1156 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +00001157 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001158 SemaRef.Context)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001159 // We place the string literal directly into the resulting
1160 // initializer list. This is the only place where the structure
1161 // of the structured initializer list doesn't match exactly,
1162 // because doing so would involve allocating one character
1163 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001164 if (!VerifyOnly) {
Eli Friedman8a5d9292011-09-26 19:09:09 +00001165 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001166 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1167 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1168 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001169 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001170 return;
1171 }
1172 }
John McCallce6c9b72011-02-21 07:22:22 +00001173 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001174 // Check for VLAs; in standard C it would be possible to check this
1175 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1176 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001177 if (!VerifyOnly)
1178 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1179 diag::err_variable_object_no_init)
1180 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001181 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001182 ++Index;
1183 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001184 return;
1185 }
1186
Douglas Gregor05c13a32009-01-22 00:58:24 +00001187 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001188 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1189 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001190 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001191 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001192 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001193 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001194 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001195 maxElementsKnown = true;
1196 }
1197
John McCallce6c9b72011-02-21 07:22:22 +00001198 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001199 while (Index < IList->getNumInits()) {
1200 Expr *Init = IList->getInit(Index);
1201 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001202 // If we're not the subobject that matches up with the '{' for
1203 // the designator, we shouldn't be handling the
1204 // designator. Return immediately.
1205 if (!SubobjectIsDesignatorContext)
1206 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001207
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001208 // Handle this designated initializer. elementIndex will be
1209 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001210 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001211 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001212 StructuredList, StructuredIndex, true,
1213 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001214 hadError = true;
1215 continue;
1216 }
1217
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001218 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001219 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001220 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001221 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001222 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001223
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001224 // If the array is of incomplete type, keep track of the number of
1225 // elements in the initializer.
1226 if (!maxElementsKnown && elementIndex > maxElements)
1227 maxElements = elementIndex;
1228
Douglas Gregor05c13a32009-01-22 00:58:24 +00001229 continue;
1230 }
1231
1232 // If we know the maximum number of elements, and we've already
1233 // hit it, stop consuming elements in the initializer list.
1234 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001235 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001236
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001237 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001238 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001239 Entity);
1240 // Check this element.
1241 CheckSubElementType(ElementEntity, IList, elementType, Index,
1242 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001243 ++elementIndex;
1244
1245 // If the array is of incomplete type, keep track of the number of
1246 // elements in the initializer.
1247 if (!maxElementsKnown && elementIndex > maxElements)
1248 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001249 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001250 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001251 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001252 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001253 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001254 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001255 // Sizing an array implicitly to zero is not allowed by ISO C,
1256 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001257 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001258 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001259 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001260
Mike Stump1eb44332009-09-09 15:08:12 +00001261 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001262 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001263 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001264 if (!hadError && VerifyOnly) {
1265 // Check if there are any members of the array that get value-initialized.
1266 // If so, check if doing that is possible.
1267 // FIXME: This needs to detect holes left by designated initializers too.
1268 if (maxElementsKnown && elementIndex < maxElements)
1269 CheckValueInitializable(InitializedEntity::InitializeElement(
1270 SemaRef.Context, 0, Entity));
1271 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001272}
1273
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001274bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1275 Expr *InitExpr,
1276 FieldDecl *Field,
1277 bool TopLevelObject) {
1278 // Handle GNU flexible array initializers.
1279 unsigned FlexArrayDiag;
1280 if (isa<InitListExpr>(InitExpr) &&
1281 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1282 // Empty flexible array init always allowed as an extension
1283 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikie4e4d0842012-03-11 07:00:24 +00001284 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001285 // Disallow flexible array init in C++; it is not required for gcc
1286 // compatibility, and it needs work to IRGen correctly in general.
1287 FlexArrayDiag = diag::err_flexible_array_init;
1288 } else if (!TopLevelObject) {
1289 // Disallow flexible array init on non-top-level object
1290 FlexArrayDiag = diag::err_flexible_array_init;
1291 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1292 // Disallow flexible array init on anything which is not a variable.
1293 FlexArrayDiag = diag::err_flexible_array_init;
1294 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1295 // Disallow flexible array init on local variables.
1296 FlexArrayDiag = diag::err_flexible_array_init;
1297 } else {
1298 // Allow other cases.
1299 FlexArrayDiag = diag::ext_flexible_array_init;
1300 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001301
1302 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001303 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001304 FlexArrayDiag)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001305 << InitExpr->getLocStart();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001306 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1307 << Field;
1308 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001309
1310 return FlexArrayDiag != diag::ext_flexible_array_init;
1311}
1312
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001313void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001314 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001315 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001316 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001317 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001318 unsigned &Index,
1319 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001320 unsigned &StructuredIndex,
1321 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001322 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001323
Eli Friedmanb85f7072008-05-19 19:16:24 +00001324 // If the record is invalid, some of it's members are invalid. To avoid
1325 // confusion, we forgo checking the intializer for the entire record.
1326 if (structDecl->isInvalidDecl()) {
1327 hadError = true;
1328 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001329 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001330
1331 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001332 // Value-initialize the first named member of the union.
1333 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1334 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1335 Field != FieldEnd; ++Field) {
1336 if (Field->getDeclName()) {
1337 if (VerifyOnly)
1338 CheckValueInitializable(
1339 InitializedEntity::InitializeMember(*Field, &Entity));
1340 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001341 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001342 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001343 }
1344 }
1345 return;
1346 }
1347
Douglas Gregor05c13a32009-01-22 00:58:24 +00001348 // If structDecl is a forward declaration, this loop won't do
1349 // anything except look at designated initializers; That's okay,
1350 // because an error should get printed out elsewhere. It might be
1351 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001352 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001353 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001354 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001355 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001356 while (Index < IList->getNumInits()) {
1357 Expr *Init = IList->getInit(Index);
1358
1359 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001360 // If we're not the subobject that matches up with the '{' for
1361 // the designator, we shouldn't be handling the
1362 // designator. Return immediately.
1363 if (!SubobjectIsDesignatorContext)
1364 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001365
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001366 // Handle this designated initializer. Field will be updated to
1367 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001368 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001369 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001370 StructuredList, StructuredIndex,
1371 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001372 hadError = true;
1373
Douglas Gregordfb5e592009-02-12 19:00:39 +00001374 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001375
1376 // Disable check for missing fields when designators are used.
1377 // This matches gcc behaviour.
1378 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001379 continue;
1380 }
1381
1382 if (Field == FieldEnd) {
1383 // We've run out of fields. We're done.
1384 break;
1385 }
1386
Douglas Gregordfb5e592009-02-12 19:00:39 +00001387 // We've already initialized a member of a union. We're done.
1388 if (InitializedSomething && DeclType->isUnionType())
1389 break;
1390
Douglas Gregor44b43212008-12-11 16:49:14 +00001391 // If we've hit the flexible array member at the end, we're done.
1392 if (Field->getType()->isIncompleteArrayType())
1393 break;
1394
Douglas Gregor0bb76892009-01-29 16:53:55 +00001395 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001396 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001397 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001398 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001399 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001400
Douglas Gregor54001c12011-06-29 21:51:31 +00001401 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001402 bool InvalidUse;
1403 if (VerifyOnly)
1404 InvalidUse = !SemaRef.CanUseDecl(*Field);
1405 else
1406 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1407 IList->getInit(Index)->getLocStart());
1408 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001409 ++Index;
1410 ++Field;
1411 hadError = true;
1412 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001413 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001414
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001415 InitializedEntity MemberEntity =
1416 InitializedEntity::InitializeMember(*Field, &Entity);
1417 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1418 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001419 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001420
Sebastian Redl14b0c192011-09-24 17:48:00 +00001421 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001422 // Initialize the first field within the union.
1423 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001424 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001425
1426 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001427 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001428
John McCall80639de2010-03-11 19:32:38 +00001429 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001430 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1431 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1432 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001433 // It is possible we have one or more unnamed bitfields remaining.
1434 // Find first (if any) named field and emit warning.
1435 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1436 it != end; ++it) {
1437 if (!it->isUnnamedBitfield()) {
1438 SemaRef.Diag(IList->getSourceRange().getEnd(),
1439 diag::warn_missing_field_initializers) << it->getName();
1440 break;
1441 }
1442 }
1443 }
1444
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001445 // Check that any remaining fields can be value-initialized.
1446 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1447 !Field->getType()->isIncompleteArrayType()) {
1448 // FIXME: Should check for holes left by designated initializers too.
1449 for (; Field != FieldEnd && !hadError; ++Field) {
1450 if (!Field->isUnnamedBitfield())
1451 CheckValueInitializable(
1452 InitializedEntity::InitializeMember(*Field, &Entity));
1453 }
1454 }
1455
Mike Stump1eb44332009-09-09 15:08:12 +00001456 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001457 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001458 return;
1459
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001460 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1461 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001462 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001463 ++Index;
1464 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001465 }
1466
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001467 InitializedEntity MemberEntity =
1468 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001469
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001470 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001471 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001472 StructuredList, StructuredIndex);
1473 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001474 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001475 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001476}
Steve Naroff0cca7492008-05-01 22:18:59 +00001477
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001478/// \brief Expand a field designator that refers to a member of an
1479/// anonymous struct or union into a series of field designators that
1480/// refers to the field within the appropriate subobject.
1481///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001482static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001483 DesignatedInitExpr *DIE,
1484 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001485 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001486 typedef DesignatedInitExpr::Designator Designator;
1487
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001488 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001489 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001490 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1491 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1492 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001493 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001494 DIE->getDesignator(DesigIdx)->getDotLoc(),
1495 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1496 else
1497 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1498 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001499 assert(isa<FieldDecl>(*PI));
1500 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001501 }
1502
1503 // Expand the current designator into the set of replacement
1504 // designators, so we have a full subobject path down to where the
1505 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001506 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001507 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001508}
Mike Stump1eb44332009-09-09 15:08:12 +00001509
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001510/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001511/// corresponds to FieldName.
1512static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1513 IdentifierInfo *FieldName) {
1514 assert(AnonField->isAnonymousStructOrUnion());
1515 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman3e78b192012-02-09 22:16:56 +00001516 while (IndirectFieldDecl *IF =
1517 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Francois Picheta0e27f02010-12-22 03:46:10 +00001518 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1519 return IF;
1520 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001521 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001522 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001523}
1524
Sebastian Redl14b0c192011-09-24 17:48:00 +00001525static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1526 DesignatedInitExpr *DIE) {
1527 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1528 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1529 for (unsigned I = 0; I < NumIndexExprs; ++I)
1530 IndexExprs[I] = DIE->getSubExpr(I + 1);
1531 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1532 DIE->size(), IndexExprs.data(),
1533 NumIndexExprs, DIE->getEqualOrColonLoc(),
1534 DIE->usesGNUSyntax(), DIE->getInit());
1535}
1536
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001537namespace {
1538
1539// Callback to only accept typo corrections that are for field members of
1540// the given struct or union.
1541class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1542 public:
1543 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1544 : Record(RD) {}
1545
1546 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1547 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1548 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1549 }
1550
1551 private:
1552 RecordDecl *Record;
1553};
1554
1555}
1556
Douglas Gregor05c13a32009-01-22 00:58:24 +00001557/// @brief Check the well-formedness of a C99 designated initializer.
1558///
1559/// Determines whether the designated initializer @p DIE, which
1560/// resides at the given @p Index within the initializer list @p
1561/// IList, is well-formed for a current object of type @p DeclType
1562/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001563/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001564/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001565///
1566/// @param IList The initializer list in which this designated
1567/// initializer occurs.
1568///
Douglas Gregor71199712009-04-15 04:56:10 +00001569/// @param DIE The designated initializer expression.
1570///
1571/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001572///
1573/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1574/// into which the designation in @p DIE should refer.
1575///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001576/// @param NextField If non-NULL and the first designator in @p DIE is
1577/// a field, this will be set to the field declaration corresponding
1578/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001579///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001580/// @param NextElementIndex If non-NULL and the first designator in @p
1581/// DIE is an array designator or GNU array-range designator, this
1582/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001583///
1584/// @param Index Index into @p IList where the designated initializer
1585/// @p DIE occurs.
1586///
Douglas Gregor4c678342009-01-28 21:54:33 +00001587/// @param StructuredList The initializer list expression that
1588/// describes all of the subobject initializers in the order they'll
1589/// actually be initialized.
1590///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001591/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001592bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001593InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001594 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001595 DesignatedInitExpr *DIE,
1596 unsigned DesigIdx,
1597 QualType &CurrentObjectType,
1598 RecordDecl::field_iterator *NextField,
1599 llvm::APSInt *NextElementIndex,
1600 unsigned &Index,
1601 InitListExpr *StructuredList,
1602 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001603 bool FinishSubobjectInit,
1604 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001605 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001606 // Check the actual initialization for the designated object type.
1607 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001608
1609 // Temporarily remove the designator expression from the
1610 // initializer list that the child calls see, so that we don't try
1611 // to re-process the designator.
1612 unsigned OldIndex = Index;
1613 IList->setInit(OldIndex, DIE->getInit());
1614
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001615 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001616 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001617
1618 // Restore the designated initializer expression in the syntactic
1619 // form of the initializer list.
1620 if (IList->getInit(OldIndex) != DIE->getInit())
1621 DIE->setInit(IList->getInit(OldIndex));
1622 IList->setInit(OldIndex, DIE);
1623
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001624 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001625 }
1626
Douglas Gregor71199712009-04-15 04:56:10 +00001627 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001628 bool IsFirstDesignator = (DesigIdx == 0);
1629 if (!VerifyOnly) {
1630 assert((IsFirstDesignator || StructuredList) &&
1631 "Need a non-designated initializer list to start from");
1632
1633 // Determine the structural initializer list that corresponds to the
1634 // current subobject.
Benjamin Kramera7894162012-02-23 14:48:40 +00001635 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001636 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1637 StructuredList, StructuredIndex,
1638 SourceRange(D->getStartLocation(),
1639 DIE->getSourceRange().getEnd()));
1640 assert(StructuredList && "Expected a structured initializer list");
1641 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001642
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001643 if (D->isFieldDesignator()) {
1644 // C99 6.7.8p7:
1645 //
1646 // If a designator has the form
1647 //
1648 // . identifier
1649 //
1650 // then the current object (defined below) shall have
1651 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001652 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001653 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001654 if (!RT) {
1655 SourceLocation Loc = D->getDotLoc();
1656 if (Loc.isInvalid())
1657 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001658 if (!VerifyOnly)
1659 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikie4e4d0842012-03-11 07:00:24 +00001660 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001661 ++Index;
1662 return true;
1663 }
1664
Douglas Gregor4c678342009-01-28 21:54:33 +00001665 // Note: we perform a linear search of the fields here, despite
1666 // the fact that we have a faster lookup method, because we always
1667 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001668 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001669 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001670 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001671 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001672 Field = RT->getDecl()->field_begin(),
1673 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001674 for (; Field != FieldEnd; ++Field) {
1675 if (Field->isUnnamedBitfield())
1676 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001677
Francois Picheta0e27f02010-12-22 03:46:10 +00001678 // If we find a field representing an anonymous field, look in the
1679 // IndirectFieldDecl that follow for the designated initializer.
1680 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1681 if (IndirectFieldDecl *IF =
1682 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001683 // In verify mode, don't modify the original.
1684 if (VerifyOnly)
1685 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001686 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1687 D = DIE->getDesignator(DesigIdx);
1688 break;
1689 }
1690 }
Douglas Gregor022d13d2010-10-08 20:44:28 +00001691 if (KnownField && KnownField == *Field)
1692 break;
1693 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001694 break;
1695
1696 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001697 }
1698
Douglas Gregor4c678342009-01-28 21:54:33 +00001699 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001700 if (VerifyOnly) {
1701 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001702 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001703 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001704
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001705 // There was no normal field in the struct with the designated
1706 // name. Perform another lookup for this name, which may find
1707 // something that we can't designate (e.g., a member function),
1708 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001709 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001710 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001711 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001712 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001713 // Name lookup didn't find anything. Determine whether this
1714 // was a typo for another field name.
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001715 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001716 TypoCorrection Corrected = SemaRef.CorrectTypo(
1717 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001718 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001719 RT->getDecl());
1720 if (Corrected) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001721 std::string CorrectedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001722 Corrected.getAsString(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001723 std::string CorrectedQuotedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001724 Corrected.getQuoted(SemaRef.getLangOpts()));
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001725 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001726 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001727 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001728 << FieldName << CurrentObjectType << CorrectedQuotedStr
1729 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001730 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001731 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramera41ee492011-09-25 02:41:26 +00001732 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001733 } else {
1734 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1735 << FieldName << CurrentObjectType;
1736 ++Index;
1737 return true;
1738 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001739 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001740
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001741 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001742 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001743 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001744 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001745 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001746 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001747 ++Index;
1748 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001749 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001750
Francois Picheta0e27f02010-12-22 03:46:10 +00001751 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001752 // The replacement field comes from typo correction; find it
1753 // in the list of fields.
1754 FieldIndex = 0;
1755 Field = RT->getDecl()->field_begin();
1756 for (; Field != FieldEnd; ++Field) {
1757 if (Field->isUnnamedBitfield())
1758 continue;
1759
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001760 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001761 Field->getIdentifier() == ReplacementField->getIdentifier())
1762 break;
1763
1764 ++FieldIndex;
1765 }
1766 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001767 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001768
1769 // All of the fields of a union are located at the same place in
1770 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001771 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001772 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001773 if (!VerifyOnly)
1774 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001775 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001776
Douglas Gregor54001c12011-06-29 21:51:31 +00001777 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001778 bool InvalidUse;
1779 if (VerifyOnly)
1780 InvalidUse = !SemaRef.CanUseDecl(*Field);
1781 else
1782 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1783 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001784 ++Index;
1785 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001786 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001787
Sebastian Redl14b0c192011-09-24 17:48:00 +00001788 if (!VerifyOnly) {
1789 // Update the designator with the field declaration.
1790 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Sebastian Redl14b0c192011-09-24 17:48:00 +00001792 // Make sure that our non-designated initializer list has space
1793 // for a subobject corresponding to this field.
1794 if (FieldIndex >= StructuredList->getNumInits())
1795 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1796 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001797
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001798 // This designator names a flexible array member.
1799 if (Field->getType()->isIncompleteArrayType()) {
1800 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001801 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001802 // We can't designate an object within the flexible array
1803 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001804 if (!VerifyOnly) {
1805 DesignatedInitExpr::Designator *NextD
1806 = DIE->getDesignator(DesigIdx + 1);
1807 SemaRef.Diag(NextD->getStartLocation(),
1808 diag::err_designator_into_flexible_array_member)
1809 << SourceRange(NextD->getStartLocation(),
1810 DIE->getSourceRange().getEnd());
1811 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1812 << *Field;
1813 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001814 Invalid = true;
1815 }
1816
Chris Lattner9046c222010-10-10 17:49:49 +00001817 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1818 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001819 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001820 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001821 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001822 diag::err_flexible_array_init_needs_braces)
1823 << DIE->getInit()->getSourceRange();
1824 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1825 << *Field;
1826 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001827 Invalid = true;
1828 }
1829
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001830 // Check GNU flexible array initializer.
1831 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1832 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001833 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001834
1835 if (Invalid) {
1836 ++Index;
1837 return true;
1838 }
1839
1840 // Initialize the array.
1841 bool prevHadError = hadError;
1842 unsigned newStructuredIndex = FieldIndex;
1843 unsigned OldIndex = Index;
1844 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001845
1846 InitializedEntity MemberEntity =
1847 InitializedEntity::InitializeMember(*Field, &Entity);
1848 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001849 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001850
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001851 IList->setInit(OldIndex, DIE);
1852 if (hadError && !prevHadError) {
1853 ++Field;
1854 ++FieldIndex;
1855 if (NextField)
1856 *NextField = Field;
1857 StructuredIndex = FieldIndex;
1858 return true;
1859 }
1860 } else {
1861 // Recurse to check later designated subobjects.
1862 QualType FieldType = (*Field)->getType();
1863 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001864
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001865 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001866 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001867 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1868 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001869 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001870 true, false))
1871 return true;
1872 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001873
1874 // Find the position of the next field to be initialized in this
1875 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001876 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001877 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001878
1879 // If this the first designator, our caller will continue checking
1880 // the rest of this struct/class/union subobject.
1881 if (IsFirstDesignator) {
1882 if (NextField)
1883 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001884 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001885 return false;
1886 }
1887
Douglas Gregor34e79462009-01-28 23:36:17 +00001888 if (!FinishSubobjectInit)
1889 return false;
1890
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001891 // We've already initialized something in the union; we're done.
1892 if (RT->getDecl()->isUnion())
1893 return hadError;
1894
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001895 // Check the remaining fields within this class/struct/union subobject.
1896 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001897
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001898 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001899 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001900 return hadError && !prevHadError;
1901 }
1902
1903 // C99 6.7.8p6:
1904 //
1905 // If a designator has the form
1906 //
1907 // [ constant-expression ]
1908 //
1909 // then the current object (defined below) shall have array
1910 // type and the expression shall be an integer constant
1911 // expression. If the array is of unknown size, any
1912 // nonnegative value is valid.
1913 //
1914 // Additionally, cope with the GNU extension that permits
1915 // designators of the form
1916 //
1917 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001918 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001919 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001920 if (!VerifyOnly)
1921 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1922 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001923 ++Index;
1924 return true;
1925 }
1926
1927 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001928 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1929 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001930 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001931 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001932 DesignatedEndIndex = DesignatedStartIndex;
1933 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001934 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001935
Mike Stump1eb44332009-09-09 15:08:12 +00001936 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001937 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001938 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001939 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001940 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001941
Chris Lattnere0fd8322011-02-19 22:28:58 +00001942 // Codegen can't handle evaluating array range designators that have side
1943 // effects, because we replicate the AST value for each initialized element.
1944 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1945 // elements with something that has a side effect, so codegen can emit an
1946 // "error unsupported" error instead of miscompiling the app.
1947 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00001948 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00001949 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001950 }
1951
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001952 if (isa<ConstantArrayType>(AT)) {
1953 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001954 DesignatedStartIndex
1955 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001956 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001957 DesignatedEndIndex
1958 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001959 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1960 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00001961 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001962 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001963 diag::err_array_designator_too_large)
1964 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1965 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001966 ++Index;
1967 return true;
1968 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001969 } else {
1970 // Make sure the bit-widths and signedness match.
1971 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001972 DesignatedEndIndex
1973 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001974 else if (DesignatedStartIndex.getBitWidth() <
1975 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001976 DesignatedStartIndex
1977 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001978 DesignatedStartIndex.setIsUnsigned(true);
1979 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001980 }
Mike Stump1eb44332009-09-09 15:08:12 +00001981
Douglas Gregor4c678342009-01-28 21:54:33 +00001982 // Make sure that our non-designated initializer list has space
1983 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001984 if (!VerifyOnly &&
1985 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001986 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001987 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001988
Douglas Gregor34e79462009-01-28 23:36:17 +00001989 // Repeatedly perform subobject initializations in the range
1990 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001991
Douglas Gregor34e79462009-01-28 23:36:17 +00001992 // Move to the next designator
1993 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1994 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001995
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001996 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001997 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001998
Douglas Gregor34e79462009-01-28 23:36:17 +00001999 while (DesignatedStartIndex <= DesignatedEndIndex) {
2000 // Recurse to check later designated subobjects.
2001 QualType ElementType = AT->getElementType();
2002 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002003
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002004 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002005 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2006 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002007 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002008 (DesignatedStartIndex == DesignatedEndIndex),
2009 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00002010 return true;
2011
2012 // Move to the next index in the array that we'll be initializing.
2013 ++DesignatedStartIndex;
2014 ElementIndex = DesignatedStartIndex.getZExtValue();
2015 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002016
2017 // If this the first designator, our caller will continue checking
2018 // the rest of this array subobject.
2019 if (IsFirstDesignator) {
2020 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00002021 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002022 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002023 return false;
2024 }
Mike Stump1eb44332009-09-09 15:08:12 +00002025
Douglas Gregor34e79462009-01-28 23:36:17 +00002026 if (!FinishSubobjectInit)
2027 return false;
2028
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002029 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002030 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002031 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002032 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002033 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002034 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002035}
2036
Douglas Gregor4c678342009-01-28 21:54:33 +00002037// Get the structured initializer list for a subobject of type
2038// @p CurrentObjectType.
2039InitListExpr *
2040InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2041 QualType CurrentObjectType,
2042 InitListExpr *StructuredList,
2043 unsigned StructuredIndex,
2044 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002045 if (VerifyOnly)
2046 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00002047 Expr *ExistingInit = 0;
2048 if (!StructuredList)
Benjamin Kramera7894162012-02-23 14:48:40 +00002049 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor4c678342009-01-28 21:54:33 +00002050 else if (StructuredIndex < StructuredList->getNumInits())
2051 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002052
Douglas Gregor4c678342009-01-28 21:54:33 +00002053 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2054 return Result;
2055
2056 if (ExistingInit) {
2057 // We are creating an initializer list that initializes the
2058 // subobjects of the current object, but there was already an
2059 // initialization that completely initialized the current
2060 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002061 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002062 // struct X { int a, b; };
2063 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002064 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002065 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2066 // designated initializer re-initializes the whole
2067 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002068 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002069 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002070 << InitRange;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002071 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002072 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002073 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002074 << ExistingInit->getSourceRange();
2075 }
2076
Mike Stump1eb44332009-09-09 15:08:12 +00002077 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002078 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2079 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00002080 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002081
Eli Friedman5c89c392012-02-23 02:25:10 +00002082 QualType ResultType = CurrentObjectType;
2083 if (!ResultType->isArrayType())
2084 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2085 Result->setType(ResultType);
Douglas Gregor4c678342009-01-28 21:54:33 +00002086
Douglas Gregorfa219202009-03-20 23:58:33 +00002087 // Pre-allocate storage for the structured initializer list.
2088 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002089 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002090 bool GotNumInits = false;
2091 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002092 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002093 GotNumInits = true;
2094 } else if (Index < IList->getNumInits()) {
2095 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002096 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002097 GotNumInits = true;
2098 }
Douglas Gregor08457732009-03-21 18:13:52 +00002099 }
2100
Mike Stump1eb44332009-09-09 15:08:12 +00002101 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002102 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2103 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2104 NumElements = CAType->getSize().getZExtValue();
2105 // Simple heuristic so that we don't allocate a very large
2106 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002107 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002108 NumElements = 0;
2109 }
John McCall183700f2009-09-21 23:43:11 +00002110 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002111 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002112 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002113 RecordDecl *RDecl = RType->getDecl();
2114 if (RDecl->isUnion())
2115 NumElements = 1;
2116 else
Mike Stump1eb44332009-09-09 15:08:12 +00002117 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002118 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002119 }
2120
Ted Kremenek709210f2010-04-13 23:39:13 +00002121 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002122
Douglas Gregor4c678342009-01-28 21:54:33 +00002123 // Link this new initializer list into the structured initializer
2124 // lists.
2125 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002126 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002127 else {
2128 Result->setSyntacticForm(IList);
2129 SyntacticToSemantic[IList] = Result;
2130 }
2131
2132 return Result;
2133}
2134
2135/// Update the initializer at index @p StructuredIndex within the
2136/// structured initializer list to the value @p expr.
2137void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2138 unsigned &StructuredIndex,
2139 Expr *expr) {
2140 // No structured initializer list to update
2141 if (!StructuredList)
2142 return;
2143
Ted Kremenek709210f2010-04-13 23:39:13 +00002144 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2145 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002146 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar96a00142012-03-09 18:35:03 +00002147 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002148 diag::warn_initializer_overrides)
2149 << expr->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +00002150 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002151 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002152 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002153 << PrevInit->getSourceRange();
2154 }
Mike Stump1eb44332009-09-09 15:08:12 +00002155
Douglas Gregor4c678342009-01-28 21:54:33 +00002156 ++StructuredIndex;
2157}
2158
Douglas Gregor05c13a32009-01-22 00:58:24 +00002159/// Check that the given Index expression is a valid array designator
Richard Smith282e7e62012-02-04 09:53:13 +00002160/// value. This is essentially just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002161/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002162/// and produces a reasonable diagnostic if there is a
Richard Smith282e7e62012-02-04 09:53:13 +00002163/// failure. Returns the index expression, possibly with an implicit cast
2164/// added, on success. If everything went okay, Value will receive the
2165/// value of the constant expression.
2166static ExprResult
Chris Lattner3bf68932009-04-25 21:59:05 +00002167CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002168 SourceLocation Loc = Index->getLocStart();
Douglas Gregor05c13a32009-01-22 00:58:24 +00002169
2170 // Make sure this is an integer constant expression.
Richard Smith282e7e62012-02-04 09:53:13 +00002171 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2172 if (Result.isInvalid())
2173 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002174
Chris Lattner3bf68932009-04-25 21:59:05 +00002175 if (Value.isSigned() && Value.isNegative())
2176 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002177 << Value.toString(10) << Index->getSourceRange();
2178
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002179 Value.setIsUnsigned(true);
Richard Smith282e7e62012-02-04 09:53:13 +00002180 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002181}
2182
John McCall60d7b3a2010-08-24 06:29:42 +00002183ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002184 SourceLocation Loc,
2185 bool GNUSyntax,
2186 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002187 typedef DesignatedInitExpr::Designator ASTDesignator;
2188
2189 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002190 SmallVector<ASTDesignator, 32> Designators;
2191 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002192
2193 // Build designators and check array designator expressions.
2194 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2195 const Designator &D = Desig.getDesignator(Idx);
2196 switch (D.getKind()) {
2197 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002198 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002199 D.getFieldLoc()));
2200 break;
2201
2202 case Designator::ArrayDesignator: {
2203 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2204 llvm::APSInt IndexValue;
Richard Smith282e7e62012-02-04 09:53:13 +00002205 if (!Index->isTypeDependent() && !Index->isValueDependent())
2206 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2207 if (!Index)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002208 Invalid = true;
2209 else {
2210 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002211 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002212 D.getRBracketLoc()));
2213 InitExpressions.push_back(Index);
2214 }
2215 break;
2216 }
2217
2218 case Designator::ArrayRangeDesignator: {
2219 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2220 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2221 llvm::APSInt StartValue;
2222 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002223 bool StartDependent = StartIndex->isTypeDependent() ||
2224 StartIndex->isValueDependent();
2225 bool EndDependent = EndIndex->isTypeDependent() ||
2226 EndIndex->isValueDependent();
Richard Smith282e7e62012-02-04 09:53:13 +00002227 if (!StartDependent)
2228 StartIndex =
2229 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2230 if (!EndDependent)
2231 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2232
2233 if (!StartIndex || !EndIndex)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002234 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002235 else {
2236 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002237 if (StartDependent || EndDependent) {
2238 // Nothing to compute.
2239 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002240 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002241 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002242 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002243
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002244 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002245 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002246 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002247 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2248 Invalid = true;
2249 } else {
2250 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002251 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002252 D.getEllipsisLoc(),
2253 D.getRBracketLoc()));
2254 InitExpressions.push_back(StartIndex);
2255 InitExpressions.push_back(EndIndex);
2256 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002257 }
2258 break;
2259 }
2260 }
2261 }
2262
2263 if (Invalid || Init.isInvalid())
2264 return ExprError();
2265
2266 // Clear out the expressions within the designation.
2267 Desig.ClearExprs(*this);
2268
2269 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002270 = DesignatedInitExpr::Create(Context,
2271 Designators.data(), Designators.size(),
2272 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00002273 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002274
David Blaikie4e4d0842012-03-11 07:00:24 +00002275 if (!getLangOpts().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002276 Diag(DIE->getLocStart(), diag::ext_designated_init)
2277 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002278
Douglas Gregor05c13a32009-01-22 00:58:24 +00002279 return Owned(DIE);
2280}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002281
Douglas Gregor20093b42009-12-09 23:02:17 +00002282//===----------------------------------------------------------------------===//
2283// Initialization entity
2284//===----------------------------------------------------------------------===//
2285
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002286InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002287 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002288 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002289{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002290 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2291 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002292 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002293 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002294 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002295 Type = VT->getElementType();
2296 } else {
2297 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2298 assert(CT && "Unexpected type");
2299 Kind = EK_ComplexElement;
2300 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002301 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002302}
2303
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002304InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002305 CXXBaseSpecifier *Base,
2306 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002307{
2308 InitializedEntity Result;
2309 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002310 Result.Base = reinterpret_cast<uintptr_t>(Base);
2311 if (IsInheritedVirtualBase)
2312 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002313
Douglas Gregord6542d82009-12-22 15:35:07 +00002314 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002315 return Result;
2316}
2317
Douglas Gregor99a2e602009-12-16 01:38:02 +00002318DeclarationName InitializedEntity::getName() const {
2319 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002320 case EK_Parameter: {
2321 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2322 return (D ? D->getDeclName() : DeclarationName());
2323 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002324
2325 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002326 case EK_Member:
2327 return VariableOrMember->getDeclName();
2328
Douglas Gregor47736542012-02-15 16:57:26 +00002329 case EK_LambdaCapture:
2330 return Capture.Var->getDeclName();
2331
Douglas Gregor99a2e602009-12-16 01:38:02 +00002332 case EK_Result:
2333 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002334 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002335 case EK_Temporary:
2336 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002337 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002338 case EK_ArrayElement:
2339 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002340 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002341 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002342 return DeclarationName();
2343 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002344
David Blaikie7530c032012-01-17 06:56:22 +00002345 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor99a2e602009-12-16 01:38:02 +00002346}
2347
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002348DeclaratorDecl *InitializedEntity::getDecl() const {
2349 switch (getKind()) {
2350 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002351 case EK_Member:
2352 return VariableOrMember;
2353
John McCallf85e1932011-06-15 23:02:42 +00002354 case EK_Parameter:
2355 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2356
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002357 case EK_Result:
2358 case EK_Exception:
2359 case EK_New:
2360 case EK_Temporary:
2361 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002362 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002363 case EK_ArrayElement:
2364 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002365 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002366 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002367 case EK_LambdaCapture:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002368 return 0;
2369 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002370
David Blaikie7530c032012-01-17 06:56:22 +00002371 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002372}
2373
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002374bool InitializedEntity::allowsNRVO() const {
2375 switch (getKind()) {
2376 case EK_Result:
2377 case EK_Exception:
2378 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002379
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002380 case EK_Variable:
2381 case EK_Parameter:
2382 case EK_Member:
2383 case EK_New:
2384 case EK_Temporary:
2385 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002386 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002387 case EK_ArrayElement:
2388 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002389 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002390 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002391 case EK_LambdaCapture:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002392 break;
2393 }
2394
2395 return false;
2396}
2397
Douglas Gregor20093b42009-12-09 23:02:17 +00002398//===----------------------------------------------------------------------===//
2399// Initialization sequence
2400//===----------------------------------------------------------------------===//
2401
2402void InitializationSequence::Step::Destroy() {
2403 switch (Kind) {
2404 case SK_ResolveAddressOfOverloadedFunction:
2405 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002406 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002407 case SK_CastDerivedToBaseLValue:
2408 case SK_BindReference:
2409 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002410 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002411 case SK_UserConversion:
2412 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002413 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002414 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002415 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002416 case SK_ListConstructorCall:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002417 case SK_UnwrapInitList:
2418 case SK_RewrapInitList:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002419 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002420 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002421 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002422 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002423 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002424 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00002425 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002426 case SK_PassByIndirectCopyRestore:
2427 case SK_PassByIndirectRestore:
2428 case SK_ProduceObjCObject:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002429 case SK_StdInitializerList:
Douglas Gregor20093b42009-12-09 23:02:17 +00002430 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002431
Douglas Gregor20093b42009-12-09 23:02:17 +00002432 case SK_ConversionSequence:
2433 delete ICS;
2434 }
2435}
2436
Douglas Gregorb70cf442010-03-26 20:14:36 +00002437bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002438 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002439}
2440
2441bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002442 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002443 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002444
Douglas Gregorb70cf442010-03-26 20:14:36 +00002445 switch (getFailureKind()) {
2446 case FK_TooManyInitsForReference:
2447 case FK_ArrayNeedsInitList:
2448 case FK_ArrayNeedsInitListOrStringLiteral:
2449 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2450 case FK_NonConstLValueReferenceBindingToTemporary:
2451 case FK_NonConstLValueReferenceBindingToUnrelated:
2452 case FK_RValueReferenceBindingToLValue:
2453 case FK_ReferenceInitDropsQualifiers:
2454 case FK_ReferenceInitFailed:
2455 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002456 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002457 case FK_TooManyInitsForScalar:
2458 case FK_ReferenceBindingToInitList:
2459 case FK_InitListBadDestinationType:
2460 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002461 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002462 case FK_ArrayTypeMismatch:
2463 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002464 case FK_ListInitializationFailed:
John McCall73076432012-01-05 00:13:19 +00002465 case FK_VariableLengthArrayHasInitializer:
John McCall5acb0c92011-10-17 18:40:02 +00002466 case FK_PlaceholderType:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002467 case FK_InitListElementCopyFailure:
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002468 case FK_ExplicitConstructor:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002469 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002470
Douglas Gregorb70cf442010-03-26 20:14:36 +00002471 case FK_ReferenceInitOverloadFailed:
2472 case FK_UserConversionOverloadFailed:
2473 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002474 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002475 return FailedOverloadResult == OR_Ambiguous;
2476 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002477
David Blaikie7530c032012-01-17 06:56:22 +00002478 llvm_unreachable("Invalid EntityKind!");
Douglas Gregorb70cf442010-03-26 20:14:36 +00002479}
2480
Douglas Gregord6e44a32010-04-16 22:09:46 +00002481bool InitializationSequence::isConstructorInitialization() const {
2482 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2483}
2484
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002485void
2486InitializationSequence
2487::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2488 DeclAccessPair Found,
2489 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002490 Step S;
2491 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2492 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002493 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002494 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002495 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002496 Steps.push_back(S);
2497}
2498
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002499void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002500 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002501 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002502 switch (VK) {
2503 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2504 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2505 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002506 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002507 S.Type = BaseType;
2508 Steps.push_back(S);
2509}
2510
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002511void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002512 bool BindingTemporary) {
2513 Step S;
2514 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2515 S.Type = T;
2516 Steps.push_back(S);
2517}
2518
Douglas Gregor523d46a2010-04-18 07:40:54 +00002519void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2520 Step S;
2521 S.Kind = SK_ExtraneousCopyToTemporary;
2522 S.Type = T;
2523 Steps.push_back(S);
2524}
2525
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002526void
2527InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2528 DeclAccessPair FoundDecl,
2529 QualType T,
2530 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002531 Step S;
2532 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002533 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002534 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002535 S.Function.Function = Function;
2536 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002537 Steps.push_back(S);
2538}
2539
2540void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002541 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002542 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002543 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002544 switch (VK) {
2545 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002546 S.Kind = SK_QualificationConversionRValue;
2547 break;
John McCall5baba9d2010-08-25 10:28:54 +00002548 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002549 S.Kind = SK_QualificationConversionXValue;
2550 break;
John McCall5baba9d2010-08-25 10:28:54 +00002551 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002552 S.Kind = SK_QualificationConversionLValue;
2553 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002554 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002555 S.Type = Ty;
2556 Steps.push_back(S);
2557}
2558
2559void InitializationSequence::AddConversionSequenceStep(
2560 const ImplicitConversionSequence &ICS,
2561 QualType T) {
2562 Step S;
2563 S.Kind = SK_ConversionSequence;
2564 S.Type = T;
2565 S.ICS = new ImplicitConversionSequence(ICS);
2566 Steps.push_back(S);
2567}
2568
Douglas Gregord87b61f2009-12-10 17:56:55 +00002569void InitializationSequence::AddListInitializationStep(QualType T) {
2570 Step S;
2571 S.Kind = SK_ListInitialization;
2572 S.Type = T;
2573 Steps.push_back(S);
2574}
2575
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002576void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002577InitializationSequence
2578::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2579 AccessSpecifier Access,
2580 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002581 bool HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002582 bool FromInitList, bool AsInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002583 Step S;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002584 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2585 : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002586 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002587 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002588 S.Function.Function = Constructor;
2589 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002590 Steps.push_back(S);
2591}
2592
Douglas Gregor71d17402009-12-15 00:01:57 +00002593void InitializationSequence::AddZeroInitializationStep(QualType T) {
2594 Step S;
2595 S.Kind = SK_ZeroInitialization;
2596 S.Type = T;
2597 Steps.push_back(S);
2598}
2599
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002600void InitializationSequence::AddCAssignmentStep(QualType T) {
2601 Step S;
2602 S.Kind = SK_CAssignment;
2603 S.Type = T;
2604 Steps.push_back(S);
2605}
2606
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002607void InitializationSequence::AddStringInitStep(QualType T) {
2608 Step S;
2609 S.Kind = SK_StringInit;
2610 S.Type = T;
2611 Steps.push_back(S);
2612}
2613
Douglas Gregor569c3162010-08-07 11:51:51 +00002614void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2615 Step S;
2616 S.Kind = SK_ObjCObjectConversion;
2617 S.Type = T;
2618 Steps.push_back(S);
2619}
2620
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002621void InitializationSequence::AddArrayInitStep(QualType T) {
2622 Step S;
2623 S.Kind = SK_ArrayInit;
2624 S.Type = T;
2625 Steps.push_back(S);
2626}
2627
Richard Smith0f163e92012-02-15 22:38:09 +00002628void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2629 Step S;
2630 S.Kind = SK_ParenthesizedArrayInit;
2631 S.Type = T;
2632 Steps.push_back(S);
2633}
2634
John McCallf85e1932011-06-15 23:02:42 +00002635void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2636 bool shouldCopy) {
2637 Step s;
2638 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2639 : SK_PassByIndirectRestore);
2640 s.Type = type;
2641 Steps.push_back(s);
2642}
2643
2644void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2645 Step S;
2646 S.Kind = SK_ProduceObjCObject;
2647 S.Type = T;
2648 Steps.push_back(S);
2649}
2650
Sebastian Redl2b916b82012-01-17 22:49:42 +00002651void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2652 Step S;
2653 S.Kind = SK_StdInitializerList;
2654 S.Type = T;
2655 Steps.push_back(S);
2656}
2657
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002658void InitializationSequence::RewrapReferenceInitList(QualType T,
2659 InitListExpr *Syntactic) {
2660 assert(Syntactic->getNumInits() == 1 &&
2661 "Can only rewrap trivial init lists.");
2662 Step S;
2663 S.Kind = SK_UnwrapInitList;
2664 S.Type = Syntactic->getInit(0)->getType();
2665 Steps.insert(Steps.begin(), S);
2666
2667 S.Kind = SK_RewrapInitList;
2668 S.Type = T;
2669 S.WrappingSyntacticList = Syntactic;
2670 Steps.push_back(S);
2671}
2672
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002673void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002674 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002675 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002676 this->Failure = Failure;
2677 this->FailedOverloadResult = Result;
2678}
2679
2680//===----------------------------------------------------------------------===//
2681// Attempt initialization
2682//===----------------------------------------------------------------------===//
2683
John McCallf85e1932011-06-15 23:02:42 +00002684static void MaybeProduceObjCObject(Sema &S,
2685 InitializationSequence &Sequence,
2686 const InitializedEntity &Entity) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002687 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallf85e1932011-06-15 23:02:42 +00002688
2689 /// When initializing a parameter, produce the value if it's marked
2690 /// __attribute__((ns_consumed)).
2691 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2692 if (!Entity.isParameterConsumed())
2693 return;
2694
2695 assert(Entity.getType()->isObjCRetainableType() &&
2696 "consuming an object of unretainable type?");
2697 Sequence.AddProduceObjCObjectStep(Entity.getType());
2698
2699 /// When initializing a return value, if the return type is a
2700 /// retainable type, then returns need to immediately retain the
2701 /// object. If an autorelease is required, it will be done at the
2702 /// last instant.
2703 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2704 if (!Entity.getType()->isObjCRetainableType())
2705 return;
2706
2707 Sequence.AddProduceObjCObjectStep(Entity.getType());
2708 }
2709}
2710
Sebastian Redl10f04a62011-12-22 14:44:04 +00002711/// \brief When initializing from init list via constructor, deal with the
2712/// empty init list and std::initializer_list special cases.
2713///
2714/// \return True if this was a special case, false otherwise.
2715static bool TryListConstructionSpecialCases(Sema &S,
Sebastian Redl08ae3692012-02-04 21:27:33 +00002716 InitListExpr *List,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002717 CXXRecordDecl *DestRecordDecl,
2718 QualType DestType,
2719 InitializationSequence &Sequence) {
Sebastian Redl2b916b82012-01-17 22:49:42 +00002720 // C++11 [dcl.init.list]p3:
Richard Smith1d0c9a82012-02-14 21:14:13 +00002721 // List-initialization of an object or reference of type T is defined as
2722 // follows:
2723 // - If T is an aggregate, aggregate initialization is performed.
2724 if (DestType->isAggregateType())
2725 return false;
2726
2727 // - Otherwise, if the initializer list has no elements and T is a class
2728 // type with a default constructor, the object is value-initialized.
Sebastian Redl08ae3692012-02-04 21:27:33 +00002729 if (List->getNumInits() == 0) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00002730 if (CXXConstructorDecl *DefaultConstructor =
2731 S.LookupDefaultConstructor(DestRecordDecl)) {
2732 if (DefaultConstructor->isDeleted() ||
2733 S.isFunctionConsideredUnavailable(DefaultConstructor)) {
2734 // Fake an overload resolution failure.
2735 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2736 DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
2737 DefaultConstructor->getAccess());
2738 if (FunctionTemplateDecl *ConstructorTmpl =
2739 dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
2740 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2741 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002742 ArrayRef<Expr*>(), CandidateSet,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002743 /*SuppressUserConversions*/ false);
2744 else
2745 S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002746 ArrayRef<Expr*>(), CandidateSet,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002747 /*SuppressUserConversions*/ false);
2748 Sequence.SetOverloadFailure(
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002749 InitializationSequence::FK_ListConstructorOverloadFailed,
2750 OR_Deleted);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002751 } else
2752 Sequence.AddConstructorInitializationStep(DefaultConstructor,
2753 DefaultConstructor->getAccess(),
2754 DestType,
2755 /*MultipleCandidates=*/false,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002756 /*FromInitList=*/true,
2757 /*AsInitList=*/false);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002758 return true;
2759 }
2760 }
2761
2762 // - Otherwise, if T is a specialization of std::initializer_list, [...]
Sebastian Redl2b916b82012-01-17 22:49:42 +00002763 QualType E;
2764 if (S.isStdInitializerList(DestType, &E)) {
2765 // Check that each individual element can be copy-constructed. But since we
2766 // have no place to store further information, we'll recalculate everything
2767 // later.
2768 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2769 S.Context.getConstantArrayType(E,
Sebastian Redl08ae3692012-02-04 21:27:33 +00002770 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2771 List->getNumInits()),
Sebastian Redl2b916b82012-01-17 22:49:42 +00002772 ArrayType::Normal, 0));
2773 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2774 0, HiddenArray);
Sebastian Redl08ae3692012-02-04 21:27:33 +00002775 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
Sebastian Redl2b916b82012-01-17 22:49:42 +00002776 Element.setElementIndex(i);
Sebastian Redl08ae3692012-02-04 21:27:33 +00002777 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
Sebastian Redl2b916b82012-01-17 22:49:42 +00002778 Sequence.SetFailed(
2779 InitializationSequence::FK_InitListElementCopyFailure);
2780 return true;
2781 }
2782 }
2783 Sequence.AddStdInitializerListConstructionStep(DestType);
2784 return true;
2785 }
Sebastian Redl10f04a62011-12-22 14:44:04 +00002786
2787 // Not a special case.
2788 return false;
2789}
2790
Sebastian Redl96715b22012-02-04 21:27:39 +00002791static OverloadingResult
2792ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
2793 Expr **Args, unsigned NumArgs,
2794 OverloadCandidateSet &CandidateSet,
2795 DeclContext::lookup_iterator Con,
2796 DeclContext::lookup_iterator ConEnd,
2797 OverloadCandidateSet::iterator &Best,
2798 bool CopyInitializing, bool AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002799 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002800 CandidateSet.clear();
2801
2802 for (; Con != ConEnd; ++Con) {
2803 NamedDecl *D = *Con;
2804 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2805 bool SuppressUserConversions = false;
2806
2807 // Find the constructor (which may be a template).
2808 CXXConstructorDecl *Constructor = 0;
2809 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2810 if (ConstructorTmpl)
2811 Constructor = cast<CXXConstructorDecl>(
2812 ConstructorTmpl->getTemplatedDecl());
2813 else {
2814 Constructor = cast<CXXConstructorDecl>(D);
2815
2816 // If we're performing copy initialization using a copy constructor, we
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002817 // suppress user-defined conversions on the arguments. We do the same for
2818 // move constructors.
2819 if ((CopyInitializing || (InitListSyntax && NumArgs == 1)) &&
2820 Constructor->isCopyOrMoveConstructor())
Sebastian Redl96715b22012-02-04 21:27:39 +00002821 SuppressUserConversions = true;
2822 }
2823
2824 if (!Constructor->isInvalidDecl() &&
2825 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002826 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002827 if (ConstructorTmpl)
2828 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2829 /*ExplicitArgs*/ 0,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002830 llvm::makeArrayRef(Args, NumArgs),
2831 CandidateSet, SuppressUserConversions);
Douglas Gregored878af2012-02-24 23:56:31 +00002832 else {
2833 // C++ [over.match.copy]p1:
2834 // - When initializing a temporary to be bound to the first parameter
2835 // of a constructor that takes a reference to possibly cv-qualified
2836 // T as its first argument, called with a single argument in the
2837 // context of direct-initialization, explicit conversion functions
2838 // are also considered.
2839 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
2840 NumArgs == 1 &&
2841 Constructor->isCopyOrMoveConstructor();
Sebastian Redl96715b22012-02-04 21:27:39 +00002842 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002843 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregored878af2012-02-24 23:56:31 +00002844 SuppressUserConversions,
2845 /*PartialOverloading=*/false,
2846 /*AllowExplicit=*/AllowExplicitConv);
2847 }
Sebastian Redl96715b22012-02-04 21:27:39 +00002848 }
2849 }
2850
2851 // Perform overload resolution and return the result.
2852 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2853}
2854
Sebastian Redl10f04a62011-12-22 14:44:04 +00002855/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2856/// enumerates the constructors of the initialized entity and performs overload
2857/// resolution to select the best.
Sebastian Redl08ae3692012-02-04 21:27:33 +00002858/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redl10f04a62011-12-22 14:44:04 +00002859/// class type.
2860static void TryConstructorInitialization(Sema &S,
2861 const InitializedEntity &Entity,
2862 const InitializationKind &Kind,
2863 Expr **Args, unsigned NumArgs,
2864 QualType DestType,
2865 InitializationSequence &Sequence,
Sebastian Redl08ae3692012-02-04 21:27:33 +00002866 bool InitListSyntax = false) {
2867 assert((!InitListSyntax || (NumArgs == 1 && isa<InitListExpr>(Args[0]))) &&
2868 "InitListSyntax must come with a single initializer list argument.");
2869
Sebastian Redl10f04a62011-12-22 14:44:04 +00002870 // Check constructor arguments for self reference.
2871 if (DeclaratorDecl *DD = Entity.getDecl())
2872 // Parameters arguments are occassionially constructed with itself,
2873 // for instance, in recursive functions. Skip them.
2874 if (!isa<ParmVarDecl>(DD))
2875 for (unsigned i = 0; i < NumArgs; ++i)
2876 S.CheckSelfReference(DD, Args[i]);
2877
Sebastian Redl10f04a62011-12-22 14:44:04 +00002878 // The type we're constructing needs to be complete.
2879 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2880 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Sebastian Redl96715b22012-02-04 21:27:39 +00002881 return;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002882 }
2883
2884 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2885 assert(DestRecordType && "Constructor initialization requires record type");
2886 CXXRecordDecl *DestRecordDecl
2887 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2888
Sebastian Redl08ae3692012-02-04 21:27:33 +00002889 if (InitListSyntax &&
2890 TryListConstructionSpecialCases(S, cast<InitListExpr>(Args[0]),
2891 DestRecordDecl, DestType, Sequence))
Sebastian Redl10f04a62011-12-22 14:44:04 +00002892 return;
2893
Sebastian Redl96715b22012-02-04 21:27:39 +00002894 // Build the candidate set directly in the initialization sequence
2895 // structure, so that it will persist if we fail.
2896 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2897
2898 // Determine whether we are allowed to call explicit constructors or
2899 // explicit conversion operators.
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002900 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002901 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl08ae3692012-02-04 21:27:33 +00002902
Sebastian Redl10f04a62011-12-22 14:44:04 +00002903 // - Otherwise, if T is a class type, constructors are considered. The
2904 // applicable constructors are enumerated, and the best one is chosen
2905 // through overload resolution.
Sebastian Redl96715b22012-02-04 21:27:39 +00002906 DeclContext::lookup_iterator ConStart, ConEnd;
2907 llvm::tie(ConStart, ConEnd) = S.LookupConstructors(DestRecordDecl);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002908
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002909 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002910 OverloadCandidateSet::iterator Best;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002911 bool AsInitializerList = false;
2912
2913 // C++11 [over.match.list]p1:
2914 // When objects of non-aggregate type T are list-initialized, overload
2915 // resolution selects the constructor in two phases:
2916 // - Initially, the candidate functions are the initializer-list
2917 // constructors of the class T and the argument list consists of the
2918 // initializer list as a single argument.
2919 if (InitListSyntax) {
2920 AsInitializerList = true;
2921 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2922 CandidateSet, ConStart, ConEnd, Best,
2923 CopyInitialization, AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002924 /*OnlyListConstructor=*/true,
2925 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002926
2927 // Time to unwrap the init list.
2928 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
2929 Args = ILE->getInits();
2930 NumArgs = ILE->getNumInits();
2931 }
2932
2933 // C++11 [over.match.list]p1:
2934 // - If no viable initializer-list constructor is found, overload resolution
2935 // is performed again, where the candidate functions are all the
2936 // constructors of the class T nad the argument list consists of the
2937 // elements of the initializer list.
2938 if (Result == OR_No_Viable_Function) {
2939 AsInitializerList = false;
2940 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2941 CandidateSet, ConStart, ConEnd, Best,
2942 CopyInitialization, AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002943 /*OnlyListConstructors=*/false,
2944 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002945 }
2946 if (Result) {
Sebastian Redl08ae3692012-02-04 21:27:33 +00002947 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002948 InitializationSequence::FK_ListConstructorOverloadFailed :
2949 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002950 Result);
2951 return;
2952 }
2953
2954 // C++0x [dcl.init]p6:
2955 // If a program calls for the default initialization of an object
2956 // of a const-qualified type T, T shall be a class type with a
2957 // user-provided default constructor.
2958 if (Kind.getKind() == InitializationKind::IK_Default &&
2959 Entity.getType().isConstQualified() &&
2960 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2961 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2962 return;
2963 }
2964
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002965 // C++11 [over.match.list]p1:
2966 // In copy-list-initialization, if an explicit constructor is chosen, the
2967 // initializer is ill-formed.
2968 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2969 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
2970 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
2971 return;
2972 }
2973
Sebastian Redl10f04a62011-12-22 14:44:04 +00002974 // Add the constructor initialization step. Any cv-qualification conversion is
2975 // subsumed by the initialization.
2976 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002977 Sequence.AddConstructorInitializationStep(CtorDecl,
2978 Best->FoundDecl.getAccess(),
2979 DestType, HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002980 InitListSyntax, AsInitializerList);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002981}
2982
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002983static bool
2984ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2985 Expr *Initializer,
2986 QualType &SourceType,
2987 QualType &UnqualifiedSourceType,
2988 QualType UnqualifiedTargetType,
2989 InitializationSequence &Sequence) {
2990 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
2991 S.Context.OverloadTy) {
2992 DeclAccessPair Found;
2993 bool HadMultipleCandidates = false;
2994 if (FunctionDecl *Fn
2995 = S.ResolveAddressOfOverloadedFunction(Initializer,
2996 UnqualifiedTargetType,
2997 false, Found,
2998 &HadMultipleCandidates)) {
2999 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3000 HadMultipleCandidates);
3001 SourceType = Fn->getType();
3002 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3003 } else if (!UnqualifiedTargetType->isRecordType()) {
3004 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3005 return true;
3006 }
3007 }
3008 return false;
3009}
3010
3011static void TryReferenceInitializationCore(Sema &S,
3012 const InitializedEntity &Entity,
3013 const InitializationKind &Kind,
3014 Expr *Initializer,
3015 QualType cv1T1, QualType T1,
3016 Qualifiers T1Quals,
3017 QualType cv2T2, QualType T2,
3018 Qualifiers T2Quals,
3019 InitializationSequence &Sequence);
3020
3021static void TryListInitialization(Sema &S,
3022 const InitializedEntity &Entity,
3023 const InitializationKind &Kind,
3024 InitListExpr *InitList,
3025 InitializationSequence &Sequence);
3026
3027/// \brief Attempt list initialization of a reference.
3028static void TryReferenceListInitialization(Sema &S,
3029 const InitializedEntity &Entity,
3030 const InitializationKind &Kind,
3031 InitListExpr *InitList,
3032 InitializationSequence &Sequence)
3033{
3034 // First, catch C++03 where this isn't possible.
David Blaikie4e4d0842012-03-11 07:00:24 +00003035 if (!S.getLangOpts().CPlusPlus0x) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003036 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3037 return;
3038 }
3039
3040 QualType DestType = Entity.getType();
3041 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3042 Qualifiers T1Quals;
3043 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3044
3045 // Reference initialization via an initializer list works thus:
3046 // If the initializer list consists of a single element that is
3047 // reference-related to the referenced type, bind directly to that element
3048 // (possibly creating temporaries).
3049 // Otherwise, initialize a temporary with the initializer list and
3050 // bind to that.
3051 if (InitList->getNumInits() == 1) {
3052 Expr *Initializer = InitList->getInit(0);
3053 QualType cv2T2 = Initializer->getType();
3054 Qualifiers T2Quals;
3055 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3056
3057 // If this fails, creating a temporary wouldn't work either.
3058 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3059 T1, Sequence))
3060 return;
3061
3062 SourceLocation DeclLoc = Initializer->getLocStart();
3063 bool dummy1, dummy2, dummy3;
3064 Sema::ReferenceCompareResult RefRelationship
3065 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3066 dummy2, dummy3);
3067 if (RefRelationship >= Sema::Ref_Related) {
3068 // Try to bind the reference here.
3069 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3070 T1Quals, cv2T2, T2, T2Quals, Sequence);
3071 if (Sequence)
3072 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3073 return;
3074 }
3075 }
3076
3077 // Not reference-related. Create a temporary and bind to that.
3078 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3079
3080 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3081 if (Sequence) {
3082 if (DestType->isRValueReferenceType() ||
3083 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3084 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3085 else
3086 Sequence.SetFailed(
3087 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3088 }
3089}
3090
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003091/// \brief Attempt list initialization (C++0x [dcl.init.list])
3092static void TryListInitialization(Sema &S,
3093 const InitializedEntity &Entity,
3094 const InitializationKind &Kind,
3095 InitListExpr *InitList,
3096 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003097 QualType DestType = Entity.getType();
3098
Sebastian Redl14b0c192011-09-24 17:48:00 +00003099 // C++ doesn't allow scalar initialization with more than one argument.
3100 // But C99 complex numbers are scalars and it makes sense there.
David Blaikie4e4d0842012-03-11 07:00:24 +00003101 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redl14b0c192011-09-24 17:48:00 +00003102 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3103 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3104 return;
3105 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003106 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003107 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003108 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003109 }
Sebastian Redld2231c92012-02-19 12:27:43 +00003110 if (DestType->isRecordType()) {
3111 if (S.RequireCompleteType(InitList->getLocStart(), DestType, S.PDiag())) {
3112 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
3113 return;
3114 }
3115
3116 if (!DestType->isAggregateType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003117 if (S.getLangOpts().CPlusPlus0x) {
Sebastian Redld2231c92012-02-19 12:27:43 +00003118 Expr *Arg = InitList;
3119 // A direct-initializer is not list-syntax, i.e. there's no special
3120 // treatment of "A a({1, 2});".
3121 TryConstructorInitialization(S, Entity, Kind, &Arg, 1, DestType,
3122 Sequence,
3123 Kind.getKind() != InitializationKind::IK_Direct);
3124 } else
3125 Sequence.SetFailed(
3126 InitializationSequence::FK_InitListBadDestinationType);
3127 return;
3128 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003129 }
3130
Sebastian Redl14b0c192011-09-24 17:48:00 +00003131 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00003132 DestType, /*VerifyOnly=*/true,
Sebastian Redl168319c2012-02-12 16:37:24 +00003133 Kind.getKind() != InitializationKind::IK_DirectList ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003134 !S.getLangOpts().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003135 if (CheckInitList.HadError()) {
3136 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3137 return;
3138 }
3139
3140 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003141 Sequence.AddListInitializationStep(DestType);
3142}
Douglas Gregor20093b42009-12-09 23:02:17 +00003143
3144/// \brief Try a reference initialization that involves calling a conversion
3145/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003146static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3147 const InitializedEntity &Entity,
3148 const InitializationKind &Kind,
Douglas Gregored878af2012-02-24 23:56:31 +00003149 Expr *Initializer,
3150 bool AllowRValues,
Douglas Gregor20093b42009-12-09 23:02:17 +00003151 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003152 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003153 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3154 QualType T1 = cv1T1.getUnqualifiedType();
3155 QualType cv2T2 = Initializer->getType();
3156 QualType T2 = cv2T2.getUnqualifiedType();
3157
3158 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003159 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003160 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003161 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003162 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003163 ObjCConversion,
3164 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003165 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003166 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003167 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003168 (void)ObjCLifetimeConversion;
3169
Douglas Gregor20093b42009-12-09 23:02:17 +00003170 // Build the candidate set directly in the initialization sequence
3171 // structure, so that it will persist if we fail.
3172 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3173 CandidateSet.clear();
3174
3175 // Determine whether we are allowed to call explicit constructors or
3176 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003177 bool AllowExplicit = Kind.AllowExplicit();
Douglas Gregored878af2012-02-24 23:56:31 +00003178 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
3179
Douglas Gregor20093b42009-12-09 23:02:17 +00003180 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003181 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3182 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003183 // The type we're converting to is a class type. Enumerate its constructors
3184 // to see if there is a suitable conversion.
3185 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003186
Douglas Gregor20093b42009-12-09 23:02:17 +00003187 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003188 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00003189 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003190 NamedDecl *D = *Con;
3191 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3192
Douglas Gregor20093b42009-12-09 23:02:17 +00003193 // Find the constructor (which may be a template).
3194 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003195 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003196 if (ConstructorTmpl)
3197 Constructor = cast<CXXConstructorDecl>(
3198 ConstructorTmpl->getTemplatedDecl());
3199 else
John McCall9aa472c2010-03-19 07:35:19 +00003200 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003201
Douglas Gregor20093b42009-12-09 23:02:17 +00003202 if (!Constructor->isInvalidDecl() &&
3203 Constructor->isConvertingConstructor(AllowExplicit)) {
3204 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003205 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003206 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003207 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003208 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003209 else
John McCall9aa472c2010-03-19 07:35:19 +00003210 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003211 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003212 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003213 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003214 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003215 }
John McCall572fc622010-08-17 07:23:57 +00003216 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3217 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003218
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003219 const RecordType *T2RecordType = 0;
3220 if ((T2RecordType = T2->getAs<RecordType>()) &&
3221 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003222 // The type we're converting from is a class type, enumerate its conversion
3223 // functions.
3224 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3225
John McCalleec51cf2010-01-20 00:46:10 +00003226 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00003227 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003228 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3229 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003230 NamedDecl *D = *I;
3231 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3232 if (isa<UsingShadowDecl>(D))
3233 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003234
Douglas Gregor20093b42009-12-09 23:02:17 +00003235 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3236 CXXConversionDecl *Conv;
3237 if (ConvTemplate)
3238 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3239 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003240 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003241
Douglas Gregor20093b42009-12-09 23:02:17 +00003242 // If the conversion function doesn't return a reference type,
3243 // it can't be considered for this conversion unless we're allowed to
3244 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003245 // FIXME: Do we need to make sure that we only consider conversion
3246 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003247 // break recursion.
Douglas Gregored878af2012-02-24 23:56:31 +00003248 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003249 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3250 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003251 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003252 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00003253 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003254 else
John McCall9aa472c2010-03-19 07:35:19 +00003255 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00003256 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003257 }
3258 }
3259 }
John McCall572fc622010-08-17 07:23:57 +00003260 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3261 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003262
Douglas Gregor20093b42009-12-09 23:02:17 +00003263 SourceLocation DeclLoc = Initializer->getLocStart();
3264
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003265 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003266 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003267 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003268 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003269 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003270
Douglas Gregor20093b42009-12-09 23:02:17 +00003271 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00003272
Chandler Carruth25ca4212011-02-25 19:41:05 +00003273 // This is the overload that will actually be used for the initialization, so
3274 // mark it as used.
Eli Friedman5f2987c2012-02-02 03:46:19 +00003275 S.MarkFunctionReferenced(DeclLoc, Function);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003276
Eli Friedman03981012009-12-11 02:42:07 +00003277 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003278 if (isa<CXXConversionDecl>(Function))
3279 T2 = Function->getResultType();
3280 else
3281 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003282
3283 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003284 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003285 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003286 T2.getNonLValueExprType(S.Context),
3287 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003288
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003289 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003290 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003291 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003292 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003293 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003294 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003295 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003296
Douglas Gregor20093b42009-12-09 23:02:17 +00003297 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003298 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003299 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003300 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003301 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003302 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003303 NewDerivedToBase, NewObjCConversion,
3304 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003305 if (NewRefRelationship == Sema::Ref_Incompatible) {
3306 // If the type we've converted to is not reference-related to the
3307 // type we're looking for, then there is another conversion step
3308 // we need to perform to produce a temporary of the right type
3309 // that we'll be binding to.
3310 ImplicitConversionSequence ICS;
3311 ICS.setStandard();
3312 ICS.Standard = Best->FinalConversion;
3313 T2 = ICS.Standard.getToType(2);
3314 Sequence.AddConversionSequenceStep(ICS, T2);
3315 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003316 Sequence.AddDerivedToBaseCastStep(
3317 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003318 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003319 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003320 else if (NewObjCConversion)
3321 Sequence.AddObjCObjectConversionStep(
3322 S.Context.getQualifiedType(T1,
3323 T2.getNonReferenceType().getQualifiers()));
3324
Douglas Gregor20093b42009-12-09 23:02:17 +00003325 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003326 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003327
Douglas Gregor20093b42009-12-09 23:02:17 +00003328 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3329 return OR_Success;
3330}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003331
Richard Smith83da2e72011-10-19 16:55:56 +00003332static void CheckCXX98CompatAccessibleCopy(Sema &S,
3333 const InitializedEntity &Entity,
3334 Expr *CurInitExpr);
3335
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003336/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3337static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003338 const InitializedEntity &Entity,
3339 const InitializationKind &Kind,
3340 Expr *Initializer,
3341 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003342 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003343 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003344 Qualifiers T1Quals;
3345 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003346 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003347 Qualifiers T2Quals;
3348 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003349
Douglas Gregor20093b42009-12-09 23:02:17 +00003350 // If the initializer is the address of an overloaded function, try
3351 // to resolve the overloaded function. If all goes well, T2 is the
3352 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003353 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3354 T1, Sequence))
3355 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003356
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003357 // Delegate everything else to a subfunction.
3358 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3359 T1Quals, cv2T2, T2, T2Quals, Sequence);
3360}
3361
3362/// \brief Reference initialization without resolving overloaded functions.
3363static void TryReferenceInitializationCore(Sema &S,
3364 const InitializedEntity &Entity,
3365 const InitializationKind &Kind,
3366 Expr *Initializer,
3367 QualType cv1T1, QualType T1,
3368 Qualifiers T1Quals,
3369 QualType cv2T2, QualType T2,
3370 Qualifiers T2Quals,
3371 InitializationSequence &Sequence) {
3372 QualType DestType = Entity.getType();
3373 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003374 // Compute some basic properties of the types and the initializer.
3375 bool isLValueRef = DestType->isLValueReferenceType();
3376 bool isRValueRef = !isLValueRef;
3377 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003378 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003379 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003380 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003381 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003382 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003383 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003384
Douglas Gregor20093b42009-12-09 23:02:17 +00003385 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003386 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003387 // "cv2 T2" as follows:
3388 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003389 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003390 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003391 // Note the analogous bullet points for rvlaue refs to functions. Because
3392 // there are no function rvalues in C++, rvalue refs to functions are treated
3393 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003394 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003395 bool T1Function = T1->isFunctionType();
3396 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003397 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003398 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003399 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003400 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003401 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003402 // reference-compatible with "cv2 T2," or
3403 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003404 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003405 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003406 // can occur. However, we do pay attention to whether it is a bit-field
3407 // to decide whether we're actually binding to a temporary created from
3408 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003409 if (DerivedToBase)
3410 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003411 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003412 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003413 else if (ObjCConversion)
3414 Sequence.AddObjCObjectConversionStep(
3415 S.Context.getQualifiedType(T1, T2Quals));
3416
Chandler Carruth5535c382010-01-12 20:32:25 +00003417 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00003418 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003419 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00003420 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003421 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00003422 return;
3423 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003424
3425 // - has a class type (i.e., T2 is a class type), where T1 is not
3426 // reference-related to T2, and can be implicitly converted to an
3427 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3428 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003429 // applicable conversion functions (13.3.1.6) and choosing the best
3430 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003431 // If we have an rvalue ref to function type here, the rhs must be
3432 // an rvalue.
3433 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3434 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003435 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003436 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003437 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003438 Sequence);
3439 if (ConvOvlResult == OR_Success)
3440 return;
John McCall1d318332010-01-12 00:44:57 +00003441 if (ConvOvlResult != OR_No_Viable_Function) {
3442 Sequence.SetOverloadFailure(
3443 InitializationSequence::FK_ReferenceInitOverloadFailed,
3444 ConvOvlResult);
3445 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003446 }
3447 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003448
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003449 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003450 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003451 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003452 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003453 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3454 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3455 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003456 Sequence.SetOverloadFailure(
3457 InitializationSequence::FK_ReferenceInitOverloadFailed,
3458 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003459 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003460 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003461 ? (RefRelationship == Sema::Ref_Related
3462 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3463 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3464 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003465
Douglas Gregor20093b42009-12-09 23:02:17 +00003466 return;
3467 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003468
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003469 // - If the initializer expression
3470 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3471 // "cv1 T1" is reference-compatible with "cv2 T2"
3472 // Note: functions are handled below.
3473 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003474 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003475 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003476 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003477 (InitCategory.isXValue() ||
3478 (InitCategory.isPRValue() && T2->isRecordType()) ||
3479 (InitCategory.isPRValue() && T2->isArrayType()))) {
3480 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3481 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003482 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3483 // compiler the freedom to perform a copy here or bind to the
3484 // object, while C++0x requires that we bind directly to the
3485 // object. Hence, we always bind to the object without making an
3486 // extra copy. However, in C++03 requires that we check for the
3487 // presence of a suitable copy constructor:
3488 //
3489 // The constructor that would be used to make the copy shall
3490 // be callable whether or not the copy is actually done.
David Blaikie4e4d0842012-03-11 07:00:24 +00003491 if (!S.getLangOpts().CPlusPlus0x && !S.getLangOpts().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003492 Sequence.AddExtraneousCopyToTemporary(cv2T2);
David Blaikie4e4d0842012-03-11 07:00:24 +00003493 else if (S.getLangOpts().CPlusPlus0x)
Richard Smith83da2e72011-10-19 16:55:56 +00003494 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003495 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003496
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003497 if (DerivedToBase)
3498 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3499 ValueKind);
3500 else if (ObjCConversion)
3501 Sequence.AddObjCObjectConversionStep(
3502 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003503
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003504 if (T1Quals != T2Quals)
3505 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003506 Sequence.AddReferenceBindingStep(cv1T1,
Peter Collingbourne65bfd682011-11-13 00:51:30 +00003507 /*bindingTemporary=*/InitCategory.isPRValue());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003508 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003509 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003510
3511 // - has a class type (i.e., T2 is a class type), where T1 is not
3512 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003513 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3514 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003515 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003516 if (RefRelationship == Sema::Ref_Incompatible) {
3517 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3518 Kind, Initializer,
3519 /*AllowRValues=*/true,
3520 Sequence);
3521 if (ConvOvlResult)
3522 Sequence.SetOverloadFailure(
3523 InitializationSequence::FK_ReferenceInitOverloadFailed,
3524 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003525
Douglas Gregor20093b42009-12-09 23:02:17 +00003526 return;
3527 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003528
Douglas Gregor20093b42009-12-09 23:02:17 +00003529 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3530 return;
3531 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003532
3533 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003534 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003535 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003536 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003537
Douglas Gregor20093b42009-12-09 23:02:17 +00003538 // Determine whether we are allowed to call explicit constructors or
3539 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003540 bool AllowExplicit = Kind.AllowExplicit();
John McCall369371c2010-06-04 02:29:22 +00003541
3542 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3543
John McCallf85e1932011-06-15 23:02:42 +00003544 ImplicitConversionSequence ICS
3545 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003546 /*SuppressUserConversions*/ false,
3547 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003548 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003549 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3550 /*AllowObjCWritebackConversion=*/false);
3551
3552 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003553 // FIXME: Use the conversion function set stored in ICS to turn
3554 // this into an overloading ambiguity diagnostic. However, we need
3555 // to keep that set as an OverloadCandidateSet rather than as some
3556 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003557 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3558 Sequence.SetOverloadFailure(
3559 InitializationSequence::FK_ReferenceInitOverloadFailed,
3560 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003561 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3562 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003563 else
3564 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003565 return;
John McCallf85e1932011-06-15 23:02:42 +00003566 } else {
3567 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003568 }
3569
3570 // [...] If T1 is reference-related to T2, cv1 must be the
3571 // same cv-qualification as, or greater cv-qualification
3572 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003573 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3574 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003575 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003576 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003577 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3578 return;
3579 }
3580
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003581 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003582 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003583 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003584 InitCategory.isLValue()) {
3585 Sequence.SetFailed(
3586 InitializationSequence::FK_RValueReferenceBindingToLValue);
3587 return;
3588 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003589
Douglas Gregor20093b42009-12-09 23:02:17 +00003590 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3591 return;
3592}
3593
3594/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003595/// (C++ [dcl.init.string], C99 6.7.8).
3596static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003597 const InitializedEntity &Entity,
3598 const InitializationKind &Kind,
3599 Expr *Initializer,
3600 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003601 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003602}
3603
Douglas Gregor71d17402009-12-15 00:01:57 +00003604/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003605static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003606 const InitializedEntity &Entity,
3607 const InitializationKind &Kind,
3608 InitializationSequence &Sequence) {
Richard Smith1d0c9a82012-02-14 21:14:13 +00003609 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor71d17402009-12-15 00:01:57 +00003610 //
3611 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003612 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003613
Douglas Gregor71d17402009-12-15 00:01:57 +00003614 // -- if T is an array type, then each element is value-initialized;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003615 T = S.Context.getBaseElementType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003616
Douglas Gregor71d17402009-12-15 00:01:57 +00003617 if (const RecordType *RT = T->getAs<RecordType>()) {
3618 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smith1d0c9a82012-02-14 21:14:13 +00003619 // C++98:
Douglas Gregor71d17402009-12-15 00:01:57 +00003620 // -- if T is a class type (clause 9) with a user-declared
3621 // constructor (12.1), then the default constructor for T is
3622 // called (and the initialization is ill-formed if T has no
3623 // accessible default constructor);
David Blaikie4e4d0842012-03-11 07:00:24 +00003624 if (!S.getLangOpts().CPlusPlus0x) {
Richard Smith1d0c9a82012-02-14 21:14:13 +00003625 if (ClassDecl->hasUserDeclaredConstructor())
3626 // FIXME: we really want to refer to a single subobject of the array,
3627 // but Entity doesn't have a way to capture that (yet).
3628 return TryConstructorInitialization(S, Entity, Kind, 0, 0,
3629 T, Sequence);
3630 } else {
3631 // C++11:
3632 // -- if T is a class type (clause 9) with either no default constructor
3633 // (12.1 [class.ctor]) or a default constructor that is user-provided
3634 // or deleted, then the object is default-initialized;
3635 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3636 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
3637 return TryConstructorInitialization(S, Entity, Kind, 0, 0,
3638 T, Sequence);
3639 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003640
Richard Smith1d0c9a82012-02-14 21:14:13 +00003641 // -- if T is a (possibly cv-qualified) non-union class type without a
3642 // user-provided or deleted default constructor, then the object is
3643 // zero-initialized and, if T has a non-trivial default constructor,
3644 // default-initialized;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003645 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00003646 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003647 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003648 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor16006c92009-12-16 18:50:27 +00003649 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003650 }
3651 }
3652
Douglas Gregord6542d82009-12-22 15:35:07 +00003653 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003654}
3655
Douglas Gregor99a2e602009-12-16 01:38:02 +00003656/// \brief Attempt default initialization (C++ [dcl.init]p6).
3657static void TryDefaultInitialization(Sema &S,
3658 const InitializedEntity &Entity,
3659 const InitializationKind &Kind,
3660 InitializationSequence &Sequence) {
3661 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003662
Douglas Gregor99a2e602009-12-16 01:38:02 +00003663 // C++ [dcl.init]p6:
3664 // To default-initialize an object of type T means:
3665 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003666 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3667
Douglas Gregor99a2e602009-12-16 01:38:02 +00003668 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3669 // constructor for T is called (and the initialization is ill-formed if
3670 // T has no accessible default constructor);
David Blaikie4e4d0842012-03-11 07:00:24 +00003671 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003672 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3673 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003674 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003675
Douglas Gregor99a2e602009-12-16 01:38:02 +00003676 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003677
Douglas Gregor99a2e602009-12-16 01:38:02 +00003678 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003679 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003680 // default constructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00003681 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003682 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003683 return;
3684 }
3685
3686 // If the destination type has a lifetime property, zero-initialize it.
3687 if (DestType.getQualifiers().hasObjCLifetime()) {
3688 Sequence.AddZeroInitializationStep(Entity.getType());
3689 return;
3690 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003691}
3692
Douglas Gregor20093b42009-12-09 23:02:17 +00003693/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3694/// which enumerates all conversion functions and performs overload resolution
3695/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003696static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003697 const InitializedEntity &Entity,
3698 const InitializationKind &Kind,
3699 Expr *Initializer,
3700 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003701 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003702 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3703 QualType SourceType = Initializer->getType();
3704 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3705 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003706
Douglas Gregor4a520a22009-12-14 17:27:33 +00003707 // Build the candidate set directly in the initialization sequence
3708 // structure, so that it will persist if we fail.
3709 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3710 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003711
Douglas Gregor4a520a22009-12-14 17:27:33 +00003712 // Determine whether we are allowed to call explicit constructors or
3713 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003714 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003715
Douglas Gregor4a520a22009-12-14 17:27:33 +00003716 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3717 // The type we're converting to is a class type. Enumerate its constructors
3718 // to see if there is a suitable conversion.
3719 CXXRecordDecl *DestRecordDecl
3720 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003721
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003722 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003723 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003724 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003725 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003726 Con != ConEnd; ++Con) {
3727 NamedDecl *D = *Con;
3728 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003729
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003730 // Find the constructor (which may be a template).
3731 CXXConstructorDecl *Constructor = 0;
3732 FunctionTemplateDecl *ConstructorTmpl
3733 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003734 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003735 Constructor = cast<CXXConstructorDecl>(
3736 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003737 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003738 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003739
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003740 if (!Constructor->isInvalidDecl() &&
3741 Constructor->isConvertingConstructor(AllowExplicit)) {
3742 if (ConstructorTmpl)
3743 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3744 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003745 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003746 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003747 else
3748 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003749 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003750 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003751 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003752 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003753 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003754 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003755
3756 SourceLocation DeclLoc = Initializer->getLocStart();
3757
Douglas Gregor4a520a22009-12-14 17:27:33 +00003758 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3759 // The type we're converting from is a class type, enumerate its conversion
3760 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003761
Eli Friedman33c2da92009-12-20 22:12:03 +00003762 // We can only enumerate the conversion functions for a complete type; if
3763 // the type isn't complete, simply skip this step.
3764 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3765 CXXRecordDecl *SourceRecordDecl
3766 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003767
John McCalleec51cf2010-01-20 00:46:10 +00003768 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003769 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003770 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003771 E = Conversions->end();
Eli Friedman33c2da92009-12-20 22:12:03 +00003772 I != E; ++I) {
3773 NamedDecl *D = *I;
3774 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3775 if (isa<UsingShadowDecl>(D))
3776 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003777
Eli Friedman33c2da92009-12-20 22:12:03 +00003778 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3779 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003780 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003781 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003782 else
John McCall32daa422010-03-31 01:36:47 +00003783 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003784
Eli Friedman33c2da92009-12-20 22:12:03 +00003785 if (AllowExplicit || !Conv->isExplicit()) {
3786 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003787 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003788 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003789 CandidateSet);
3790 else
John McCall9aa472c2010-03-19 07:35:19 +00003791 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003792 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003793 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003794 }
3795 }
3796 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003797
3798 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003799 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003800 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003801 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003802 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003803 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003804 Result);
3805 return;
3806 }
John McCall1d318332010-01-12 00:44:57 +00003807
Douglas Gregor4a520a22009-12-14 17:27:33 +00003808 FunctionDecl *Function = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00003809 S.MarkFunctionReferenced(DeclLoc, Function);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003810 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003811
Douglas Gregor4a520a22009-12-14 17:27:33 +00003812 if (isa<CXXConstructorDecl>(Function)) {
3813 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithf2e4dfc2012-02-11 19:22:50 +00003814 // subsumed by the initialization. Per DR5, the created temporary is of the
3815 // cv-unqualified type of the destination.
3816 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3817 DestType.getUnqualifiedType(),
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003818 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003819 return;
3820 }
3821
3822 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003823 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003824 if (ConvType->getAs<RecordType>()) {
Richard Smithf2e4dfc2012-02-11 19:22:50 +00003825 // If we're converting to a class type, there may be an copy of
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003826 // the resulting temporary object (possible to create an object of
3827 // a base class type). That copy is not a separate conversion, so
3828 // we just make a note of the actual destination type (possibly a
3829 // base class of the type returned by the conversion function) and
3830 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003831 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3832 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003833 return;
3834 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003835
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003836 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3837 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003838
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003839 // If the conversion following the call to the conversion function
3840 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003841 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3842 Best->FinalConversion.Third) {
3843 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003844 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003845 ICS.Standard = Best->FinalConversion;
3846 Sequence.AddConversionSequenceStep(ICS, DestType);
3847 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003848}
3849
John McCallf85e1932011-06-15 23:02:42 +00003850/// The non-zero enum values here are indexes into diagnostic alternatives.
3851enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3852
3853/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003854static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3855 bool isAddressOf) {
John McCallf85e1932011-06-15 23:02:42 +00003856 // Skip parens.
3857 e = e->IgnoreParens();
3858
3859 // Skip address-of nodes.
3860 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3861 if (op->getOpcode() == UO_AddrOf)
John McCallc03fa492011-06-27 23:59:58 +00003862 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCallf85e1932011-06-15 23:02:42 +00003863
3864 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00003865 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3866 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00003867 case CK_Dependent:
3868 case CK_BitCast:
3869 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00003870 case CK_NoOp:
John McCallc03fa492011-06-27 23:59:58 +00003871 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003872
3873 case CK_ArrayToPointerDecay:
3874 return IIK_nonscalar;
3875
3876 case CK_NullToPointer:
3877 return IIK_okay;
3878
3879 default:
3880 break;
3881 }
3882
3883 // If we have a declaration reference, it had better be a local variable.
John McCallf4b88a42012-03-10 09:33:50 +00003884 } else if (isa<DeclRefExpr>(e)) {
John McCallc03fa492011-06-27 23:59:58 +00003885 if (!isAddressOf) return IIK_nonlocal;
3886
John McCallf4b88a42012-03-10 09:33:50 +00003887 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3888 if (!var) return IIK_nonlocal;
John McCallc03fa492011-06-27 23:59:58 +00003889
3890 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00003891
3892 // If we have a conditional operator, check both sides.
3893 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCallc03fa492011-06-27 23:59:58 +00003894 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCallf85e1932011-06-15 23:02:42 +00003895 return iik;
3896
John McCallc03fa492011-06-27 23:59:58 +00003897 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003898
3899 // These are never scalar.
3900 } else if (isa<ArraySubscriptExpr>(e)) {
3901 return IIK_nonscalar;
3902
3903 // Otherwise, it needs to be a null pointer constant.
3904 } else {
3905 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3906 ? IIK_okay : IIK_nonlocal);
3907 }
3908
3909 return IIK_nonlocal;
3910}
3911
3912/// Check whether the given expression is a valid operand for an
3913/// indirect copy/restore.
3914static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3915 assert(src->isRValue());
3916
John McCallc03fa492011-06-27 23:59:58 +00003917 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCallf85e1932011-06-15 23:02:42 +00003918 if (iik == IIK_okay) return;
3919
3920 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3921 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3922 << src->getSourceRange();
3923}
3924
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003925/// \brief Determine whether we have compatible array types for the
3926/// purposes of GNU by-copy array initialization.
3927static bool hasCompatibleArrayTypes(ASTContext &Context,
3928 const ArrayType *Dest,
3929 const ArrayType *Source) {
3930 // If the source and destination array types are equivalent, we're
3931 // done.
3932 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3933 return true;
3934
3935 // Make sure that the element types are the same.
3936 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3937 return false;
3938
3939 // The only mismatch we allow is when the destination is an
3940 // incomplete array type and the source is a constant array type.
3941 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3942}
3943
John McCallf85e1932011-06-15 23:02:42 +00003944static bool tryObjCWritebackConversion(Sema &S,
3945 InitializationSequence &Sequence,
3946 const InitializedEntity &Entity,
3947 Expr *Initializer) {
3948 bool ArrayDecay = false;
3949 QualType ArgType = Initializer->getType();
3950 QualType ArgPointee;
3951 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3952 ArrayDecay = true;
3953 ArgPointee = ArgArrayType->getElementType();
3954 ArgType = S.Context.getPointerType(ArgPointee);
3955 }
3956
3957 // Handle write-back conversion.
3958 QualType ConvertedArgType;
3959 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3960 ConvertedArgType))
3961 return false;
3962
3963 // We should copy unless we're passing to an argument explicitly
3964 // marked 'out'.
3965 bool ShouldCopy = true;
3966 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3967 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3968
3969 // Do we need an lvalue conversion?
3970 if (ArrayDecay || Initializer->isGLValue()) {
3971 ImplicitConversionSequence ICS;
3972 ICS.setStandard();
3973 ICS.Standard.setAsIdentityConversion();
3974
3975 QualType ResultType;
3976 if (ArrayDecay) {
3977 ICS.Standard.First = ICK_Array_To_Pointer;
3978 ResultType = S.Context.getPointerType(ArgPointee);
3979 } else {
3980 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3981 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3982 }
3983
3984 Sequence.AddConversionSequenceStep(ICS, ResultType);
3985 }
3986
3987 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3988 return true;
3989}
3990
Douglas Gregor20093b42009-12-09 23:02:17 +00003991InitializationSequence::InitializationSequence(Sema &S,
3992 const InitializedEntity &Entity,
3993 const InitializationKind &Kind,
3994 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003995 unsigned NumArgs)
3996 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003997 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003998
Douglas Gregor20093b42009-12-09 23:02:17 +00003999 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004000 // The semantics of initializers are as follows. The destination type is
4001 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00004002 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004003 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00004004 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004005 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004006
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004007 if (DestType->isDependentType() ||
Ahmed Charles13a140c2012-02-25 11:00:22 +00004008 Expr::hasAnyTypeDependentArguments(llvm::makeArrayRef(Args, NumArgs))) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004009 SequenceKind = DependentSequence;
4010 return;
4011 }
4012
Sebastian Redl7491c492011-06-05 13:59:11 +00004013 // Almost everything is a normal sequence.
4014 setSequenceKind(NormalSequence);
4015
John McCall241d5582010-12-07 22:54:16 +00004016 for (unsigned I = 0; I != NumArgs; ++I)
John McCall32509f12011-11-15 01:35:18 +00004017 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall5acb0c92011-10-17 18:40:02 +00004018 // FIXME: should we be doing this here?
John McCall32509f12011-11-15 01:35:18 +00004019 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4020 if (result.isInvalid()) {
4021 SetFailed(FK_PlaceholderType);
4022 return;
John McCall5acb0c92011-10-17 18:40:02 +00004023 }
John McCall32509f12011-11-15 01:35:18 +00004024 Args[I] = result.take();
John Wiegley429bb272011-04-08 18:41:53 +00004025 }
John McCall241d5582010-12-07 22:54:16 +00004026
John McCall5acb0c92011-10-17 18:40:02 +00004027
Douglas Gregor20093b42009-12-09 23:02:17 +00004028 QualType SourceType;
4029 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00004030 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004031 Initializer = Args[0];
4032 if (!isa<InitListExpr>(Initializer))
4033 SourceType = Initializer->getType();
4034 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004035
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004036 // - If the initializer is a (non-parenthesized) braced-init-list, the
4037 // object is list-initialized (8.5.4).
4038 if (Kind.getKind() != InitializationKind::IK_Direct) {
4039 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4040 TryListInitialization(S, Entity, Kind, InitList, *this);
4041 return;
4042 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004043 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004044
Douglas Gregor20093b42009-12-09 23:02:17 +00004045 // - If the destination type is a reference type, see 8.5.3.
4046 if (DestType->isReferenceType()) {
4047 // C++0x [dcl.init.ref]p1:
4048 // A variable declared to be a T& or T&&, that is, "reference to type T"
4049 // (8.3.2), shall be initialized by an object, or function, of type T or
4050 // by an object that can be converted into a T.
4051 // (Therefore, multiple arguments are not permitted.)
4052 if (NumArgs != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004053 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00004054 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004055 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004056 return;
4057 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004058
Douglas Gregor20093b42009-12-09 23:02:17 +00004059 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004060 if (Kind.getKind() == InitializationKind::IK_Value ||
4061 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004062 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004063 return;
4064 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004065
Douglas Gregor99a2e602009-12-16 01:38:02 +00004066 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00004067 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004068 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004069 return;
4070 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004071
John McCallce6c9b72011-02-21 07:22:22 +00004072 // - If the destination type is an array of characters, an array of
4073 // char16_t, an array of char32_t, or an array of wchar_t, and the
4074 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004075 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00004076 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004077 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCall73076432012-01-05 00:13:19 +00004078 if (Initializer && isa<VariableArrayType>(DestAT)) {
4079 SetFailed(FK_VariableLengthArrayHasInitializer);
4080 return;
4081 }
4082
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004083 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004084 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00004085 return;
4086 }
4087
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004088 // Note: as an GNU C extension, we allow initialization of an
4089 // array from a compound literal that creates an array of the same
4090 // type, so long as the initializer has no side effects.
David Blaikie4e4d0842012-03-11 07:00:24 +00004091 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004092 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4093 Initializer->getType()->isArrayType()) {
4094 const ArrayType *SourceAT
4095 = Context.getAsArrayType(Initializer->getType());
4096 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004097 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004098 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004099 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004100 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004101 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004102 }
Richard Smith0f163e92012-02-15 22:38:09 +00004103 }
4104 // Note: as a GNU C++ extension, we allow initialization of a
4105 // class member from a parenthesized initializer list.
David Blaikie4e4d0842012-03-11 07:00:24 +00004106 else if (S.getLangOpts().CPlusPlus &&
Richard Smith0f163e92012-02-15 22:38:09 +00004107 Entity.getKind() == InitializedEntity::EK_Member &&
4108 Initializer && isa<InitListExpr>(Initializer)) {
4109 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4110 *this);
4111 AddParenthesizedArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004112 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004113 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00004114 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004115 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004116
Douglas Gregor20093b42009-12-09 23:02:17 +00004117 return;
4118 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004119
John McCallf85e1932011-06-15 23:02:42 +00004120 // Determine whether we should consider writeback conversions for
4121 // Objective-C ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00004122 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00004123 Entity.getKind() == InitializedEntity::EK_Parameter;
4124
4125 // We're at the end of the line for C: it's either a write-back conversion
4126 // or it's a C assignment. There's no need to check anything else.
David Blaikie4e4d0842012-03-11 07:00:24 +00004127 if (!S.getLangOpts().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00004128 // If allowed, check whether this is an Objective-C writeback conversion.
4129 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004130 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00004131 return;
4132 }
4133
4134 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004135 AddCAssignmentStep(DestType);
4136 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004137 return;
4138 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004139
David Blaikie4e4d0842012-03-11 07:00:24 +00004140 assert(S.getLangOpts().CPlusPlus);
John McCallf85e1932011-06-15 23:02:42 +00004141
Douglas Gregor20093b42009-12-09 23:02:17 +00004142 // - If the destination type is a (possibly cv-qualified) class type:
4143 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004144 // - If the initialization is direct-initialization, or if it is
4145 // copy-initialization where the cv-unqualified version of the
4146 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004147 // class of the destination, constructors are considered. [...]
4148 if (Kind.getKind() == InitializationKind::IK_Direct ||
4149 (Kind.getKind() == InitializationKind::IK_Copy &&
4150 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4151 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004152 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004153 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004154 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004155 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004156 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004157 // used) to a derived class thereof are enumerated as described in
4158 // 13.3.1.4, and the best one is chosen through overload resolution
4159 // (13.3).
4160 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004161 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004162 return;
4163 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004164
Douglas Gregor99a2e602009-12-16 01:38:02 +00004165 if (NumArgs > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004166 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004167 return;
4168 }
4169 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004170
4171 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004172 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004173 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004174 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4175 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004176 return;
4177 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004178
Douglas Gregor20093b42009-12-09 23:02:17 +00004179 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004180 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004181 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004182 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004183 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00004184
4185 ImplicitConversionSequence ICS
4186 = S.TryImplicitConversion(Initializer, Entity.getType(),
4187 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004188 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004189 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004190 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4191 allowObjCWritebackConversion);
4192
4193 if (ICS.isStandard() &&
4194 ICS.Standard.Second == ICK_Writeback_Conversion) {
4195 // Objective-C ARC writeback conversion.
4196
4197 // We should copy unless we're passing to an argument explicitly
4198 // marked 'out'.
4199 bool ShouldCopy = true;
4200 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4201 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4202
4203 // If there was an lvalue adjustment, add it as a separate conversion.
4204 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4205 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4206 ImplicitConversionSequence LvalueICS;
4207 LvalueICS.setStandard();
4208 LvalueICS.Standard.setAsIdentityConversion();
4209 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4210 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004211 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004212 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004213
4214 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004215 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004216 DeclAccessPair dap;
4217 if (Initializer->getType() == Context.OverloadTy &&
4218 !S.ResolveAddressOfOverloadedFunction(Initializer
4219 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004220 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004221 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004222 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004223 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004224 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00004225
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004226 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004227 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004228}
4229
4230InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004231 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004232 StepEnd = Steps.end();
4233 Step != StepEnd; ++Step)
4234 Step->Destroy();
4235}
4236
4237//===----------------------------------------------------------------------===//
4238// Perform initialization
4239//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004240static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004241getAssignmentAction(const InitializedEntity &Entity) {
4242 switch(Entity.getKind()) {
4243 case InitializedEntity::EK_Variable:
4244 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004245 case InitializedEntity::EK_Exception:
4246 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004247 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004248 return Sema::AA_Initializing;
4249
4250 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004251 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004252 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4253 return Sema::AA_Sending;
4254
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004255 return Sema::AA_Passing;
4256
4257 case InitializedEntity::EK_Result:
4258 return Sema::AA_Returning;
4259
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004260 case InitializedEntity::EK_Temporary:
4261 // FIXME: Can we tell apart casting vs. converting?
4262 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004263
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004264 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004265 case InitializedEntity::EK_ArrayElement:
4266 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004267 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004268 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004269 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004270 return Sema::AA_Initializing;
4271 }
4272
David Blaikie7530c032012-01-17 06:56:22 +00004273 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004274}
4275
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004276/// \brief Whether we should binding a created object as a temporary when
4277/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004278static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004279 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004280 case InitializedEntity::EK_ArrayElement:
4281 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004282 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004283 case InitializedEntity::EK_New:
4284 case InitializedEntity::EK_Variable:
4285 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004286 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004287 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004288 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004289 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004290 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004291 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004292 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004293
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004294 case InitializedEntity::EK_Parameter:
4295 case InitializedEntity::EK_Temporary:
4296 return true;
4297 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004298
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004299 llvm_unreachable("missed an InitializedEntity kind?");
4300}
4301
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004302/// \brief Whether the given entity, when initialized with an object
4303/// created for that initialization, requires destruction.
4304static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4305 switch (Entity.getKind()) {
4306 case InitializedEntity::EK_Member:
4307 case InitializedEntity::EK_Result:
4308 case InitializedEntity::EK_New:
4309 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004310 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004311 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004312 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004313 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004314 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004315 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004316
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004317 case InitializedEntity::EK_Variable:
4318 case InitializedEntity::EK_Parameter:
4319 case InitializedEntity::EK_Temporary:
4320 case InitializedEntity::EK_ArrayElement:
4321 case InitializedEntity::EK_Exception:
4322 return true;
4323 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004324
4325 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004326}
4327
Richard Smith83da2e72011-10-19 16:55:56 +00004328/// \brief Look for copy and move constructors and constructor templates, for
4329/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4330static void LookupCopyAndMoveConstructors(Sema &S,
4331 OverloadCandidateSet &CandidateSet,
4332 CXXRecordDecl *Class,
4333 Expr *CurInitExpr) {
4334 DeclContext::lookup_iterator Con, ConEnd;
4335 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4336 Con != ConEnd; ++Con) {
4337 CXXConstructorDecl *Constructor = 0;
4338
4339 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4340 // Handle copy/moveconstructors, only.
4341 if (!Constructor || Constructor->isInvalidDecl() ||
4342 !Constructor->isCopyOrMoveConstructor() ||
4343 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4344 continue;
4345
4346 DeclAccessPair FoundDecl
4347 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4348 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004349 CurInitExpr, CandidateSet);
Richard Smith83da2e72011-10-19 16:55:56 +00004350 continue;
4351 }
4352
4353 // Handle constructor templates.
4354 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4355 if (ConstructorTmpl->isInvalidDecl())
4356 continue;
4357
4358 Constructor = cast<CXXConstructorDecl>(
4359 ConstructorTmpl->getTemplatedDecl());
4360 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4361 continue;
4362
4363 // FIXME: Do we need to limit this to copy-constructor-like
4364 // candidates?
4365 DeclAccessPair FoundDecl
4366 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4367 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004368 CurInitExpr, CandidateSet, true);
Richard Smith83da2e72011-10-19 16:55:56 +00004369 }
4370}
4371
4372/// \brief Get the location at which initialization diagnostics should appear.
4373static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4374 Expr *Initializer) {
4375 switch (Entity.getKind()) {
4376 case InitializedEntity::EK_Result:
4377 return Entity.getReturnLoc();
4378
4379 case InitializedEntity::EK_Exception:
4380 return Entity.getThrowLoc();
4381
4382 case InitializedEntity::EK_Variable:
4383 return Entity.getDecl()->getLocation();
4384
Douglas Gregor47736542012-02-15 16:57:26 +00004385 case InitializedEntity::EK_LambdaCapture:
4386 return Entity.getCaptureLoc();
4387
Richard Smith83da2e72011-10-19 16:55:56 +00004388 case InitializedEntity::EK_ArrayElement:
4389 case InitializedEntity::EK_Member:
4390 case InitializedEntity::EK_Parameter:
4391 case InitializedEntity::EK_Temporary:
4392 case InitializedEntity::EK_New:
4393 case InitializedEntity::EK_Base:
4394 case InitializedEntity::EK_Delegating:
4395 case InitializedEntity::EK_VectorElement:
4396 case InitializedEntity::EK_ComplexElement:
4397 case InitializedEntity::EK_BlockElement:
4398 return Initializer->getLocStart();
4399 }
4400 llvm_unreachable("missed an InitializedEntity kind?");
4401}
4402
Douglas Gregor523d46a2010-04-18 07:40:54 +00004403/// \brief Make a (potentially elidable) temporary copy of the object
4404/// provided by the given initializer by calling the appropriate copy
4405/// constructor.
4406///
4407/// \param S The Sema object used for type-checking.
4408///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004409/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004410/// the type of the initializer expression or a superclass thereof.
4411///
4412/// \param Enter The entity being initialized.
4413///
4414/// \param CurInit The initializer expression.
4415///
4416/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4417/// is permitted in C++03 (but not C++0x) when binding a reference to
4418/// an rvalue.
4419///
4420/// \returns An expression that copies the initializer expression into
4421/// a temporary object, or an error expression if a copy could not be
4422/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004423static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004424 QualType T,
4425 const InitializedEntity &Entity,
4426 ExprResult CurInit,
4427 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004428 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004429 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004430 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004431 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004432 Class = cast<CXXRecordDecl>(Record->getDecl());
4433 if (!Class)
4434 return move(CurInit);
4435
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004436 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004437 // When certain criteria are met, an implementation is allowed to
4438 // omit the copy/move construction of a class object, even if the
4439 // copy/move constructor and/or destructor for the object have
4440 // side effects. [...]
4441 // - when a temporary class object that has not been bound to a
4442 // reference (12.2) would be copied/moved to a class object
4443 // with the same cv-unqualified type, the copy/move operation
4444 // can be omitted by constructing the temporary object
4445 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004446 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004447 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004448 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004449 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004450 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004451 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00004452 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004453
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004454 // Make sure that the type we are copying is complete.
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004455 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4456 return move(CurInit);
4457
Douglas Gregorcc15f012011-01-21 19:38:21 +00004458 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00004459 // Only consider constructors and constructor templates. Per
4460 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4461 // is direct-initialization.
John McCall5769d612010-02-08 23:07:23 +00004462 OverloadCandidateSet CandidateSet(Loc);
Richard Smith83da2e72011-10-19 16:55:56 +00004463 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004464
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004465 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4466
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004467 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004468 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004469 case OR_Success:
4470 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004471
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004472 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004473 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4474 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4475 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004476 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004477 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004478 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004479 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004480 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004481 return move(CurInit);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004482
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004483 case OR_Ambiguous:
4484 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004485 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004486 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004487 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallf312b1e2010-08-26 23:41:50 +00004488 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004489
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004490 case OR_Deleted:
4491 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004492 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004493 << CurInitExpr->getSourceRange();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004494 S.NoteDeletedFunction(Best->Function);
John McCallf312b1e2010-08-26 23:41:50 +00004495 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004496 }
4497
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004498 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00004499 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004500 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004501
Anders Carlsson9a68a672010-04-21 18:47:17 +00004502 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004503 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004504
4505 if (IsExtraneousCopy) {
4506 // If this is a totally extraneous copy for C++03 reference
4507 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004508 // expression. We don't generate an (elided) copy operation here
4509 // because doing so would require us to pass down a flag to avoid
4510 // infinite recursion, where each step adds another extraneous,
4511 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004512
Douglas Gregor2559a702010-04-18 07:57:34 +00004513 // Instantiate the default arguments of any extra parameters in
4514 // the selected copy constructor, as if we were going to create a
4515 // proper call to the copy constructor.
4516 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4517 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4518 if (S.RequireCompleteType(Loc, Parm->getType(),
4519 S.PDiag(diag::err_call_incomplete_argument)))
4520 break;
4521
4522 // Build the default argument expression; we don't actually care
4523 // if this succeeds or not, because this routine will complain
4524 // if there was a problem.
4525 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4526 }
4527
Douglas Gregor523d46a2010-04-18 07:40:54 +00004528 return S.Owned(CurInitExpr);
4529 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004530
Eli Friedman5f2987c2012-02-02 03:46:19 +00004531 S.MarkFunctionReferenced(Loc, Constructor);
Chandler Carruth25ca4212011-02-25 19:41:05 +00004532
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004533 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004534 // constructor call (we might have derived-to-base conversions, or
4535 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00004536 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004537 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004538 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004539
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004540 // Actually perform the constructor call.
4541 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00004542 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004543 HadMultipleCandidates,
John McCall7a1fad32010-08-24 07:32:53 +00004544 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004545 CXXConstructExpr::CK_Complete,
4546 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004547
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004548 // If we're supposed to bind temporaries, do so.
4549 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4550 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4551 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004552}
Douglas Gregor20093b42009-12-09 23:02:17 +00004553
Richard Smith83da2e72011-10-19 16:55:56 +00004554/// \brief Check whether elidable copy construction for binding a reference to
4555/// a temporary would have succeeded if we were building in C++98 mode, for
4556/// -Wc++98-compat.
4557static void CheckCXX98CompatAccessibleCopy(Sema &S,
4558 const InitializedEntity &Entity,
4559 Expr *CurInitExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00004560 assert(S.getLangOpts().CPlusPlus0x);
Richard Smith83da2e72011-10-19 16:55:56 +00004561
4562 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4563 if (!Record)
4564 return;
4565
4566 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4567 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4568 == DiagnosticsEngine::Ignored)
4569 return;
4570
4571 // Find constructors which would have been considered.
4572 OverloadCandidateSet CandidateSet(Loc);
4573 LookupCopyAndMoveConstructors(
4574 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4575
4576 // Perform overload resolution.
4577 OverloadCandidateSet::iterator Best;
4578 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4579
4580 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4581 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4582 << CurInitExpr->getSourceRange();
4583
4584 switch (OR) {
4585 case OR_Success:
4586 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4587 Best->FoundDecl.getAccess(), Diag);
4588 // FIXME: Check default arguments as far as that's possible.
4589 break;
4590
4591 case OR_No_Viable_Function:
4592 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004593 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004594 break;
4595
4596 case OR_Ambiguous:
4597 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004598 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004599 break;
4600
4601 case OR_Deleted:
4602 S.Diag(Loc, Diag);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004603 S.NoteDeletedFunction(Best->Function);
Richard Smith83da2e72011-10-19 16:55:56 +00004604 break;
4605 }
4606}
4607
Douglas Gregora41a8c52010-04-22 00:20:18 +00004608void InitializationSequence::PrintInitLocationNote(Sema &S,
4609 const InitializedEntity &Entity) {
4610 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4611 if (Entity.getDecl()->getLocation().isInvalid())
4612 return;
4613
4614 if (Entity.getDecl()->getDeclName())
4615 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4616 << Entity.getDecl()->getDeclName();
4617 else
4618 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4619 }
4620}
4621
Sebastian Redl3b802322011-07-14 19:07:55 +00004622static bool isReferenceBinding(const InitializationSequence::Step &s) {
4623 return s.Kind == InitializationSequence::SK_BindReference ||
4624 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4625}
4626
Sebastian Redl10f04a62011-12-22 14:44:04 +00004627static ExprResult
4628PerformConstructorInitialization(Sema &S,
4629 const InitializedEntity &Entity,
4630 const InitializationKind &Kind,
4631 MultiExprArg Args,
4632 const InitializationSequence::Step& Step,
4633 bool &ConstructorInitRequiresZeroInit) {
4634 unsigned NumArgs = Args.size();
4635 CXXConstructorDecl *Constructor
4636 = cast<CXXConstructorDecl>(Step.Function.Function);
4637 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4638
4639 // Build a call to the selected constructor.
4640 ASTOwningVector<Expr*> ConstructorArgs(S);
4641 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4642 ? Kind.getEqualLoc()
4643 : Kind.getLocation();
4644
4645 if (Kind.getKind() == InitializationKind::IK_Default) {
4646 // Force even a trivial, implicit default constructor to be
4647 // semantically checked. We do this explicitly because we don't build
4648 // the definition for completely trivial constructors.
Matt Beaumont-Gay28e47022012-02-24 08:37:56 +00004649 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redl10f04a62011-12-22 14:44:04 +00004650 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregor5d86f612012-02-24 07:48:37 +00004651 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004652 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4653 }
4654
4655 ExprResult CurInit = S.Owned((Expr *)0);
4656
Douglas Gregored878af2012-02-24 23:56:31 +00004657 // C++ [over.match.copy]p1:
4658 // - When initializing a temporary to be bound to the first parameter
4659 // of a constructor that takes a reference to possibly cv-qualified
4660 // T as its first argument, called with a single argument in the
4661 // context of direct-initialization, explicit conversion functions
4662 // are also considered.
4663 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
4664 Args.size() == 1 &&
4665 Constructor->isCopyOrMoveConstructor();
4666
Sebastian Redl10f04a62011-12-22 14:44:04 +00004667 // Determine the arguments required to actually perform the constructor
4668 // call.
4669 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregored878af2012-02-24 23:56:31 +00004670 Loc, ConstructorArgs,
4671 AllowExplicitConv))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004672 return ExprError();
4673
4674
4675 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Sebastian Redl188158d2012-03-08 21:05:45 +00004676 (Kind.getKind() == InitializationKind::IK_DirectList ||
4677 (NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4678 (Kind.getKind() == InitializationKind::IK_Direct ||
4679 Kind.getKind() == InitializationKind::IK_Value)))) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00004680 // An explicitly-constructed temporary, e.g., X(1, 2).
4681 unsigned NumExprs = ConstructorArgs.size();
4682 Expr **Exprs = (Expr **)ConstructorArgs.take();
Eli Friedman5f2987c2012-02-02 03:46:19 +00004683 S.MarkFunctionReferenced(Loc, Constructor);
Sebastian Redl10f04a62011-12-22 14:44:04 +00004684 S.DiagnoseUseOfDecl(Constructor, Loc);
4685
4686 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4687 if (!TSInfo)
4688 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Sebastian Redl188158d2012-03-08 21:05:45 +00004689 SourceRange ParenRange;
4690 if (Kind.getKind() != InitializationKind::IK_DirectList)
4691 ParenRange = Kind.getParenRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00004692
4693 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4694 Constructor,
4695 TSInfo,
4696 Exprs,
4697 NumExprs,
Sebastian Redl188158d2012-03-08 21:05:45 +00004698 ParenRange,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004699 HadMultipleCandidates,
4700 ConstructorInitRequiresZeroInit));
4701 } else {
4702 CXXConstructExpr::ConstructionKind ConstructKind =
4703 CXXConstructExpr::CK_Complete;
4704
4705 if (Entity.getKind() == InitializedEntity::EK_Base) {
4706 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4707 CXXConstructExpr::CK_VirtualBase :
4708 CXXConstructExpr::CK_NonVirtualBase;
4709 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4710 ConstructKind = CXXConstructExpr::CK_Delegating;
4711 }
4712
4713 // Only get the parenthesis range if it is a direct construction.
4714 SourceRange parenRange =
4715 Kind.getKind() == InitializationKind::IK_Direct ?
4716 Kind.getParenRange() : SourceRange();
4717
4718 // If the entity allows NRVO, mark the construction as elidable
4719 // unconditionally.
4720 if (Entity.allowsNRVO())
4721 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4722 Constructor, /*Elidable=*/true,
4723 move_arg(ConstructorArgs),
4724 HadMultipleCandidates,
4725 ConstructorInitRequiresZeroInit,
4726 ConstructKind,
4727 parenRange);
4728 else
4729 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4730 Constructor,
4731 move_arg(ConstructorArgs),
4732 HadMultipleCandidates,
4733 ConstructorInitRequiresZeroInit,
4734 ConstructKind,
4735 parenRange);
4736 }
4737 if (CurInit.isInvalid())
4738 return ExprError();
4739
4740 // Only check access if all of that succeeded.
4741 S.CheckConstructorAccess(Loc, Constructor, Entity,
4742 Step.Function.FoundDecl.getAccess());
4743 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4744
4745 if (shouldBindAsTemporary(Entity))
4746 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4747
4748 return move(CurInit);
4749}
4750
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004751ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00004752InitializationSequence::Perform(Sema &S,
4753 const InitializedEntity &Entity,
4754 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00004755 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00004756 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004757 if (Failed()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004758 unsigned NumArgs = Args.size();
4759 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00004760 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004761 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004762
Sebastian Redl7491c492011-06-05 13:59:11 +00004763 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004764 // If the declaration is a non-dependent, incomplete array type
4765 // that has an initializer, then its type will be completed once
4766 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00004767 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00004768 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004769 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004770 if (const IncompleteArrayType *ArrayT
4771 = S.Context.getAsIncompleteArrayType(DeclType)) {
4772 // FIXME: We don't currently have the ability to accurately
4773 // compute the length of an initializer list without
4774 // performing full type-checking of the initializer list
4775 // (since we have to determine where braces are implicitly
4776 // introduced and such). So, we fall back to making the array
4777 // type a dependently-sized array type with no specified
4778 // bound.
4779 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4780 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00004781
Douglas Gregord87b61f2009-12-10 17:56:55 +00004782 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00004783 if (DeclaratorDecl *DD = Entity.getDecl()) {
4784 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4785 TypeLoc TL = TInfo->getTypeLoc();
4786 if (IncompleteArrayTypeLoc *ArrayLoc
4787 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4788 Brackets = ArrayLoc->getBracketsRange();
4789 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00004790 }
4791
4792 *ResultType
4793 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4794 /*NumElts=*/0,
4795 ArrayT->getSizeModifier(),
4796 ArrayT->getIndexTypeCVRQualifiers(),
4797 Brackets);
4798 }
4799
4800 }
4801 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004802 if (Kind.getKind() == InitializationKind::IK_Direct &&
4803 !Kind.isExplicitCast()) {
4804 // Rebuild the ParenListExpr.
4805 SourceRange ParenRange = Kind.getParenRange();
4806 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
4807 move(Args));
4808 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004809 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4810 Kind.isExplicitCast());
4811 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004812 }
4813
Sebastian Redl7491c492011-06-05 13:59:11 +00004814 // No steps means no initialization.
4815 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00004816 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004817
Douglas Gregord6542d82009-12-22 15:35:07 +00004818 QualType DestType = Entity.getType().getNonReferenceType();
4819 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00004820 // the same as Entity.getDecl()->getType() in cases involving type merging,
4821 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00004822 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00004823 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00004824 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004825
John McCall60d7b3a2010-08-24 06:29:42 +00004826 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004827
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004828 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00004829 // grab the only argument out the Args and place it into the "current"
4830 // initializer.
4831 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004832 case SK_ResolveAddressOfOverloadedFunction:
4833 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004834 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004835 case SK_CastDerivedToBaseLValue:
4836 case SK_BindReference:
4837 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00004838 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004839 case SK_UserConversion:
4840 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004841 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004842 case SK_QualificationConversionRValue:
4843 case SK_ConversionSequence:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00004844 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004845 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00004846 case SK_UnwrapInitList:
4847 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004848 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004849 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004850 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00004851 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00004852 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00004853 case SK_PassByIndirectCopyRestore:
4854 case SK_PassByIndirectRestore:
Sebastian Redl2b916b82012-01-17 22:49:42 +00004855 case SK_ProduceObjCObject:
4856 case SK_StdInitializerList: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004857 assert(Args.size() == 1);
John Wiegley429bb272011-04-08 18:41:53 +00004858 CurInit = Args.get()[0];
4859 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004860 break;
John McCallf6a16482010-12-04 03:47:34 +00004861 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004862
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004863 case SK_ConstructorInitialization:
4864 case SK_ZeroInitialization:
4865 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004866 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004867
4868 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00004869 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00004870 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00004871 for (step_iterator Step = step_begin(), StepEnd = step_end();
4872 Step != StepEnd; ++Step) {
4873 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004874 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004875
John Wiegley429bb272011-04-08 18:41:53 +00004876 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004877
Douglas Gregor20093b42009-12-09 23:02:17 +00004878 switch (Step->Kind) {
4879 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004880 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00004881 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00004882 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00004883 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00004884 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00004885 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00004886 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00004887 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004888
Douglas Gregor20093b42009-12-09 23:02:17 +00004889 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004890 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00004891 case SK_CastDerivedToBaseLValue: {
4892 // We have a derived-to-base cast that produces either an rvalue or an
4893 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004894
John McCallf871d0c2010-08-07 06:22:56 +00004895 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004896
Douglas Gregor20093b42009-12-09 23:02:17 +00004897 // Casts to inaccessible base classes are allowed with C-style casts.
4898 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4899 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00004900 CurInit.get()->getLocStart(),
4901 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004902 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00004903 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004904
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004905 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4906 QualType T = SourceType;
4907 if (const PointerType *Pointer = T->getAs<PointerType>())
4908 T = Pointer->getPointeeType();
4909 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00004910 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004911 cast<CXXRecordDecl>(RecordTy->getDecl()));
4912 }
4913
John McCall5baba9d2010-08-25 10:28:54 +00004914 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004915 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004916 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004917 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004918 VK_XValue :
4919 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00004920 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4921 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004922 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00004923 CurInit.get(),
4924 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00004925 break;
4926 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004927
Douglas Gregor20093b42009-12-09 23:02:17 +00004928 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00004929 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004930 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4931 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00004932 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004933 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00004934 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00004935 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00004936 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004937 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00004938
John Wiegley429bb272011-04-08 18:41:53 +00004939 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00004940 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00004941 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4942 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00004943 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004944 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004945 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00004946 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004947
Douglas Gregor20093b42009-12-09 23:02:17 +00004948 // Reference binding does not have any corresponding ASTs.
4949
4950 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004951 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004952 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00004953
Douglas Gregor20093b42009-12-09 23:02:17 +00004954 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00004955
Douglas Gregor20093b42009-12-09 23:02:17 +00004956 case SK_BindReferenceToTemporary:
4957 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004958 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004959 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004960
Douglas Gregor03e80032011-06-21 17:03:29 +00004961 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00004962 CurInit = new (S.Context) MaterializeTemporaryExpr(
4963 Entity.getType().getNonReferenceType(),
4964 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00004965 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00004966
4967 // If we're binding to an Objective-C object that has lifetime, we
4968 // need cleanups.
David Blaikie4e4d0842012-03-11 07:00:24 +00004969 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregord7b23162011-06-22 16:12:01 +00004970 CurInit.get()->getType()->isObjCLifetimeType())
4971 S.ExprNeedsCleanups = true;
4972
Douglas Gregor20093b42009-12-09 23:02:17 +00004973 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004974
Douglas Gregor523d46a2010-04-18 07:40:54 +00004975 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004976 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregor523d46a2010-04-18 07:40:54 +00004977 /*IsExtraneousCopy=*/true);
4978 break;
4979
Douglas Gregor20093b42009-12-09 23:02:17 +00004980 case SK_UserConversion: {
4981 // We have a user-defined conversion that invokes either a constructor
4982 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00004983 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004984 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00004985 FunctionDecl *Fn = Step->Function.Function;
4986 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004987 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004988 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00004989 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004990 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004991 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley429bb272011-04-08 18:41:53 +00004992 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00004993 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00004994
Douglas Gregor20093b42009-12-09 23:02:17 +00004995 // Determine the arguments required to actually perform the constructor
4996 // call.
John Wiegley429bb272011-04-08 18:41:53 +00004997 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00004998 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00004999 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00005000 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00005001 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005002
Richard Smithf2e4dfc2012-02-11 19:22:50 +00005003 // Build an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005004 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00005005 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005006 HadMultipleCandidates,
John McCall7a1fad32010-08-24 07:32:53 +00005007 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005008 CXXConstructExpr::CK_Complete,
5009 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00005010 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005011 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00005012
Anders Carlsson9a68a672010-04-21 18:47:17 +00005013 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00005014 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00005015 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005016
John McCall2de56d12010-08-25 11:45:40 +00005017 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005018 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5019 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5020 S.IsDerivedFrom(SourceType, Class))
5021 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005022
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005023 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00005024 } else {
5025 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00005026 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00005027 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00005028 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00005029 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005030
5031 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00005032 // derived-to-base conversion? I believe the answer is "no", because
5033 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00005034 ExprResult CurInitExprRes =
5035 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5036 FoundFn, Conversion);
5037 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005038 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00005039 CurInit = move(CurInitExprRes);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005040
Douglas Gregor20093b42009-12-09 23:02:17 +00005041 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005042 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5043 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00005044 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00005045 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005046
John McCall2de56d12010-08-25 11:45:40 +00005047 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005048
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005049 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005050 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005051
Sebastian Redl3b802322011-07-14 19:07:55 +00005052 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00005053 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5054
5055 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00005056 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005057 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005058 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00005059 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00005060 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005061 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedman5f2987c2012-02-02 03:46:19 +00005062 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
John Wiegley429bb272011-04-08 18:41:53 +00005063 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005064 }
5065 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005066
John McCallf871d0c2010-08-07 06:22:56 +00005067 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00005068 CurInit.get()->getType(),
5069 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00005070 CurInit.get()->getValueKind()));
Abramo Bagnara960809e2011-11-16 22:46:05 +00005071 if (MaybeBindToTemp)
5072 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00005073 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00005074 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
5075 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00005076 break;
5077 }
Sebastian Redl906082e2010-07-20 04:20:21 +00005078
Douglas Gregor20093b42009-12-09 23:02:17 +00005079 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005080 case SK_QualificationConversionXValue:
5081 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00005082 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00005083 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005084 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005085 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005086 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005087 VK_XValue :
5088 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005089 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00005090 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005091 }
5092
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005093 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00005094 Sema::CheckedConversionKind CCK
5095 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5096 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00005097 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00005098 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00005099 ExprResult CurInitExprRes =
5100 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00005101 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00005102 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005103 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00005104 CurInit = move(CurInitExprRes);
Douglas Gregor20093b42009-12-09 23:02:17 +00005105 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005106 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005107
Douglas Gregord87b61f2009-12-10 17:56:55 +00005108 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00005109 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005110 // Hack: We must pass *ResultType if available in order to set the type
5111 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5112 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5113 // temporary, not a reference, so we should pass Ty.
5114 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5115 // Since this step is never used for a reference directly, we explicitly
5116 // unwrap references here and rewrap them afterwards.
5117 // We also need to create a InitializeTemporary entity for this.
5118 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
Sebastian Redlcbf82092012-03-07 16:10:45 +00005119 bool IsTemporary = Entity.getType()->isReferenceType();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005120 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5121 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
5122 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00005123 Kind.getKind() != InitializationKind::IK_DirectList ||
David Blaikie4e4d0842012-03-11 07:00:24 +00005124 !S.getLangOpts().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005125 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00005126 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005127
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005128 if (ResultType) {
5129 if ((*ResultType)->isRValueReferenceType())
5130 Ty = S.Context.getRValueReferenceType(Ty);
5131 else if ((*ResultType)->isLValueReferenceType())
5132 Ty = S.Context.getLValueReferenceType(Ty,
5133 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5134 *ResultType = Ty;
5135 }
5136
5137 InitListExpr *StructuredInitList =
5138 PerformInitList.getFullyStructuredList();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005139 CurInit.release();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005140 CurInit = S.Owned(StructuredInitList);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005141 break;
5142 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005143
Sebastian Redl10f04a62011-12-22 14:44:04 +00005144 case SK_ListConstructorCall: {
Sebastian Redl168319c2012-02-12 16:37:24 +00005145 // When an initializer list is passed for a parameter of type "reference
5146 // to object", we don't get an EK_Temporary entity, but instead an
5147 // EK_Parameter entity with reference type.
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005148 // FIXME: This is a hack. What we really should do is create a user
5149 // conversion step for this case, but this makes it considerably more
5150 // complicated. For now, this will do.
Sebastian Redl168319c2012-02-12 16:37:24 +00005151 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5152 Entity.getType().getNonReferenceType());
5153 bool UseTemporary = Entity.getType()->isReferenceType();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005154 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5155 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl168319c2012-02-12 16:37:24 +00005156 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5157 Entity,
5158 Kind, move(Arg), *Step,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005159 ConstructorInitRequiresZeroInit);
5160 break;
5161 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005162
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005163 case SK_UnwrapInitList:
5164 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5165 break;
5166
5167 case SK_RewrapInitList: {
5168 Expr *E = CurInit.take();
5169 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5170 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5171 Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
5172 ILE->setSyntacticForm(Syntactic);
5173 ILE->setType(E->getType());
5174 ILE->setValueKind(E->getValueKind());
5175 CurInit = S.Owned(ILE);
5176 break;
5177 }
5178
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005179 case SK_ConstructorInitialization: {
5180 // When an initializer list is passed for a parameter of type "reference
5181 // to object", we don't get an EK_Temporary entity, but instead an
5182 // EK_Parameter entity with reference type.
5183 // FIXME: This is a hack. What we really should do is create a user
5184 // conversion step for this case, but this makes it considerably more
5185 // complicated. For now, this will do.
5186 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5187 Entity.getType().getNonReferenceType());
5188 bool UseTemporary = Entity.getType()->isReferenceType();
5189 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5190 : Entity,
5191 Kind, move(Args), *Step,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005192 ConstructorInitRequiresZeroInit);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005193 break;
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005194 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005195
Douglas Gregor71d17402009-12-15 00:01:57 +00005196 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00005197 step_iterator NextStep = Step;
5198 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005199 if (NextStep != StepEnd &&
Douglas Gregor16006c92009-12-16 18:50:27 +00005200 NextStep->Kind == SK_ConstructorInitialization) {
5201 // The need for zero-initialization is recorded directly into
5202 // the call to the object's constructor within the next step.
5203 ConstructorInitRequiresZeroInit = true;
5204 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005205 S.getLangOpts().CPlusPlus &&
Douglas Gregor16006c92009-12-16 18:50:27 +00005206 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00005207 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5208 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005209 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00005210 Kind.getRange().getBegin());
5211
5212 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5213 TSInfo->getType().getNonLValueExprType(S.Context),
5214 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00005215 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00005216 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00005217 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00005218 }
Douglas Gregor71d17402009-12-15 00:01:57 +00005219 break;
5220 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005221
5222 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00005223 QualType SourceType = CurInit.get()->getType();
5224 ExprResult Result = move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005225 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00005226 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5227 if (Result.isInvalid())
5228 return ExprError();
5229 CurInit = move(Result);
Douglas Gregoraa037312009-12-22 07:24:36 +00005230
5231 // If this is a call, allow conversion to a transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005232 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregoraa037312009-12-22 07:24:36 +00005233 if (ConvTy != Sema::Compatible &&
5234 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00005235 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00005236 == Sema::Compatible)
5237 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00005238 if (CurInitExprRes.isInvalid())
5239 return ExprError();
5240 CurInit = move(CurInitExprRes);
Douglas Gregoraa037312009-12-22 07:24:36 +00005241
Douglas Gregora41a8c52010-04-22 00:20:18 +00005242 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005243 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5244 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00005245 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00005246 getAssignmentAction(Entity),
5247 &Complained)) {
5248 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005249 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005250 } else if (Complained)
5251 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005252 break;
5253 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005254
5255 case SK_StringInit: {
5256 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00005257 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00005258 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005259 break;
5260 }
Douglas Gregor569c3162010-08-07 11:51:51 +00005261
5262 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00005263 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005264 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00005265 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00005266 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005267
5268 case SK_ArrayInit:
5269 // Okay: we checked everything before creating this step. Note that
5270 // this is a GNU extension.
5271 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00005272 << Step->Type << CurInit.get()->getType()
5273 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005274
5275 // If the destination type is an incomplete array type, update the
5276 // type accordingly.
5277 if (ResultType) {
5278 if (const IncompleteArrayType *IncompleteDest
5279 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5280 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00005281 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005282 *ResultType = S.Context.getConstantArrayType(
5283 IncompleteDest->getElementType(),
5284 ConstantSource->getSize(),
5285 ArrayType::Normal, 0);
5286 }
5287 }
5288 }
John McCallf85e1932011-06-15 23:02:42 +00005289 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005290
Richard Smith0f163e92012-02-15 22:38:09 +00005291 case SK_ParenthesizedArrayInit:
5292 // Okay: we checked everything before creating this step. Note that
5293 // this is a GNU extension.
5294 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
5295 << CurInit.get()->getSourceRange();
5296 break;
5297
John McCallf85e1932011-06-15 23:02:42 +00005298 case SK_PassByIndirectCopyRestore:
5299 case SK_PassByIndirectRestore:
5300 checkIndirectCopyRestoreSource(S, CurInit.get());
5301 CurInit = S.Owned(new (S.Context)
5302 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5303 Step->Kind == SK_PassByIndirectCopyRestore));
5304 break;
5305
5306 case SK_ProduceObjCObject:
5307 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00005308 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00005309 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005310 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005311
5312 case SK_StdInitializerList: {
5313 QualType Dest = Step->Type;
5314 QualType E;
5315 bool Success = S.isStdInitializerList(Dest, &E);
5316 (void)Success;
5317 assert(Success && "Destination type changed?");
Sebastian Redl28357452012-03-05 19:35:43 +00005318
5319 // If the element type has a destructor, check it.
5320 if (CXXRecordDecl *RD = E->getAsCXXRecordDecl()) {
5321 if (!RD->hasIrrelevantDestructor()) {
5322 if (CXXDestructorDecl *Destructor = S.LookupDestructor(RD)) {
5323 S.MarkFunctionReferenced(Kind.getLocation(), Destructor);
5324 S.CheckDestructorAccess(Kind.getLocation(), Destructor,
5325 S.PDiag(diag::err_access_dtor_temp) << E);
5326 S.DiagnoseUseOfDecl(Destructor, Kind.getLocation());
5327 }
5328 }
5329 }
5330
Sebastian Redl2b916b82012-01-17 22:49:42 +00005331 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
5332 unsigned NumInits = ILE->getNumInits();
5333 SmallVector<Expr*, 16> Converted(NumInits);
5334 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5335 S.Context.getConstantArrayType(E,
5336 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5337 NumInits),
5338 ArrayType::Normal, 0));
5339 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5340 0, HiddenArray);
5341 for (unsigned i = 0; i < NumInits; ++i) {
5342 Element.setElementIndex(i);
5343 ExprResult Init = S.Owned(ILE->getInit(i));
5344 ExprResult Res = S.PerformCopyInitialization(Element,
5345 Init.get()->getExprLoc(),
5346 Init);
5347 assert(!Res.isInvalid() && "Result changed since try phase.");
5348 Converted[i] = Res.take();
5349 }
5350 InitListExpr *Semantic = new (S.Context)
5351 InitListExpr(S.Context, ILE->getLBraceLoc(),
5352 Converted.data(), NumInits, ILE->getRBraceLoc());
5353 Semantic->setSyntacticForm(ILE);
5354 Semantic->setType(Dest);
Sebastian Redl32cf1f22012-02-17 08:42:25 +00005355 Semantic->setInitializesStdInitializerList();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005356 CurInit = S.Owned(Semantic);
5357 break;
5358 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005359 }
5360 }
John McCall15d7d122010-11-11 03:21:53 +00005361
5362 // Diagnose non-fatal problems with the completed initialization.
5363 if (Entity.getKind() == InitializedEntity::EK_Member &&
5364 cast<FieldDecl>(Entity.getDecl())->isBitField())
5365 S.CheckBitFieldInitialization(Kind.getLocation(),
5366 cast<FieldDecl>(Entity.getDecl()),
5367 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005368
Douglas Gregor20093b42009-12-09 23:02:17 +00005369 return move(CurInit);
5370}
5371
5372//===----------------------------------------------------------------------===//
5373// Diagnose initialization failures
5374//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005375bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00005376 const InitializedEntity &Entity,
5377 const InitializationKind &Kind,
5378 Expr **Args, unsigned NumArgs) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005379 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00005380 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005381
Douglas Gregord6542d82009-12-22 15:35:07 +00005382 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005383 switch (Failure) {
5384 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005385 // FIXME: Customize for the initialized entity?
5386 if (NumArgs == 0)
5387 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5388 << DestType.getNonReferenceType();
5389 else // FIXME: diagnostic below could be better!
5390 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5391 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00005392 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005393
Douglas Gregor20093b42009-12-09 23:02:17 +00005394 case FK_ArrayNeedsInitList:
5395 case FK_ArrayNeedsInitListOrStringLiteral:
5396 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5397 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5398 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005399
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005400 case FK_ArrayTypeMismatch:
5401 case FK_NonConstantArrayInit:
5402 S.Diag(Kind.getLocation(),
5403 (Failure == FK_ArrayTypeMismatch
5404 ? diag::err_array_init_different_type
5405 : diag::err_array_init_non_constant_array))
5406 << DestType.getNonReferenceType()
5407 << Args[0]->getType()
5408 << Args[0]->getSourceRange();
5409 break;
5410
John McCall73076432012-01-05 00:13:19 +00005411 case FK_VariableLengthArrayHasInitializer:
5412 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5413 << Args[0]->getSourceRange();
5414 break;
5415
John McCall6bb80172010-03-30 21:47:33 +00005416 case FK_AddressOfOverloadFailed: {
5417 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005418 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00005419 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00005420 true,
5421 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00005422 break;
John McCall6bb80172010-03-30 21:47:33 +00005423 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005424
Douglas Gregor20093b42009-12-09 23:02:17 +00005425 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00005426 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00005427 switch (FailedOverloadResult) {
5428 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005429 if (Failure == FK_UserConversionOverloadFailed)
5430 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5431 << Args[0]->getType() << DestType
5432 << Args[0]->getSourceRange();
5433 else
5434 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5435 << DestType << Args[0]->getType()
5436 << Args[0]->getSourceRange();
5437
Ahmed Charles13a140c2012-02-25 11:00:22 +00005438 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5439 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor20093b42009-12-09 23:02:17 +00005440 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005441
Douglas Gregor20093b42009-12-09 23:02:17 +00005442 case OR_No_Viable_Function:
5443 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5444 << Args[0]->getType() << DestType.getNonReferenceType()
5445 << Args[0]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005446 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
5447 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor20093b42009-12-09 23:02:17 +00005448 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005449
Douglas Gregor20093b42009-12-09 23:02:17 +00005450 case OR_Deleted: {
5451 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5452 << Args[0]->getType() << DestType.getNonReferenceType()
5453 << Args[0]->getSourceRange();
5454 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005455 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005456 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5457 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00005458 if (Ovl == OR_Deleted) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005459 S.NoteDeletedFunction(Best->Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005460 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005461 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00005462 }
5463 break;
5464 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005465
Douglas Gregor20093b42009-12-09 23:02:17 +00005466 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005467 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00005468 }
5469 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005470
Douglas Gregor20093b42009-12-09 23:02:17 +00005471 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005472 if (isa<InitListExpr>(Args[0])) {
5473 S.Diag(Kind.getLocation(),
5474 diag::err_lvalue_reference_bind_to_initlist)
5475 << DestType.getNonReferenceType().isVolatileQualified()
5476 << DestType.getNonReferenceType()
5477 << Args[0]->getSourceRange();
5478 break;
5479 }
5480 // Intentional fallthrough
5481
Douglas Gregor20093b42009-12-09 23:02:17 +00005482 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005483 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00005484 Failure == FK_NonConstLValueReferenceBindingToTemporary
5485 ? diag::err_lvalue_reference_bind_to_temporary
5486 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00005487 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005488 << DestType.getNonReferenceType()
5489 << Args[0]->getType()
5490 << Args[0]->getSourceRange();
5491 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005492
Douglas Gregor20093b42009-12-09 23:02:17 +00005493 case FK_RValueReferenceBindingToLValue:
5494 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00005495 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00005496 << Args[0]->getSourceRange();
5497 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005498
Douglas Gregor20093b42009-12-09 23:02:17 +00005499 case FK_ReferenceInitDropsQualifiers:
5500 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5501 << DestType.getNonReferenceType()
5502 << Args[0]->getType()
5503 << Args[0]->getSourceRange();
5504 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005505
Douglas Gregor20093b42009-12-09 23:02:17 +00005506 case FK_ReferenceInitFailed:
5507 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5508 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00005509 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00005510 << Args[0]->getType()
5511 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00005512 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5513 Args[0]->getType()->isObjCObjectPointerType())
5514 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005515 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005516
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005517 case FK_ConversionFailed: {
5518 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005519 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005520 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00005521 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00005522 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005523 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00005524 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005525 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5526 S.Diag(Kind.getLocation(), PDiag);
Douglas Gregor926df6c2011-06-11 01:09:30 +00005527 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5528 Args[0]->getType()->isObjCObjectPointerType())
5529 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005530 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005531 }
John Wiegley429bb272011-04-08 18:41:53 +00005532
5533 case FK_ConversionFromPropertyFailed:
5534 // No-op. This error has already been reported.
5535 break;
5536
Douglas Gregord87b61f2009-12-10 17:56:55 +00005537 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00005538 SourceRange R;
5539
5540 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00005541 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00005542 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005543 else
Douglas Gregor19311e72010-09-08 21:40:08 +00005544 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00005545
Douglas Gregor19311e72010-09-08 21:40:08 +00005546 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5547 if (Kind.isCStyleOrFunctionalCast())
5548 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5549 << R;
5550 else
5551 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5552 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00005553 break;
5554 }
5555
5556 case FK_ReferenceBindingToInitList:
5557 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5558 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5559 break;
5560
5561 case FK_InitListBadDestinationType:
5562 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5563 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5564 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005565
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005566 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00005567 case FK_ConstructorOverloadFailed: {
5568 SourceRange ArgsRange;
5569 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005570 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00005571 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005572
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005573 if (Failure == FK_ListConstructorOverloadFailed) {
5574 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5575 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5576 Args = InitList->getInits();
5577 NumArgs = InitList->getNumInits();
5578 }
5579
Douglas Gregor51c56d62009-12-14 20:49:26 +00005580 // FIXME: Using "DestType" for the entity we're printing is probably
5581 // bad.
5582 switch (FailedOverloadResult) {
5583 case OR_Ambiguous:
5584 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5585 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005586 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005587 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor51c56d62009-12-14 20:49:26 +00005588 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005589
Douglas Gregor51c56d62009-12-14 20:49:26 +00005590 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005591 if (Kind.getKind() == InitializationKind::IK_Default &&
5592 (Entity.getKind() == InitializedEntity::EK_Base ||
5593 Entity.getKind() == InitializedEntity::EK_Member) &&
5594 isa<CXXConstructorDecl>(S.CurContext)) {
5595 // This is implicit default initialization of a member or
5596 // base within a constructor. If no viable function was
5597 // found, notify the user that she needs to explicitly
5598 // initialize this base/member.
5599 CXXConstructorDecl *Constructor
5600 = cast<CXXConstructorDecl>(S.CurContext);
5601 if (Entity.getKind() == InitializedEntity::EK_Base) {
5602 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5603 << Constructor->isImplicit()
5604 << S.Context.getTypeDeclType(Constructor->getParent())
5605 << /*base=*/0
5606 << Entity.getType();
5607
5608 RecordDecl *BaseDecl
5609 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5610 ->getDecl();
5611 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5612 << S.Context.getTagDeclType(BaseDecl);
5613 } else {
5614 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5615 << Constructor->isImplicit()
5616 << S.Context.getTypeDeclType(Constructor->getParent())
5617 << /*member=*/1
5618 << Entity.getName();
5619 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5620
5621 if (const RecordType *Record
5622 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005623 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005624 diag::note_previous_decl)
5625 << S.Context.getTagDeclType(Record->getDecl());
5626 }
5627 break;
5628 }
5629
Douglas Gregor51c56d62009-12-14 20:49:26 +00005630 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5631 << DestType << ArgsRange;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005632 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
5633 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor51c56d62009-12-14 20:49:26 +00005634 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005635
Douglas Gregor51c56d62009-12-14 20:49:26 +00005636 case OR_Deleted: {
Douglas Gregor51c56d62009-12-14 20:49:26 +00005637 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005638 OverloadingResult Ovl
5639 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregore4e68d42012-02-15 19:33:52 +00005640 if (Ovl != OR_Deleted) {
5641 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5642 << true << DestType << ArgsRange;
Douglas Gregor51c56d62009-12-14 20:49:26 +00005643 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregore4e68d42012-02-15 19:33:52 +00005644 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00005645 }
Douglas Gregore4e68d42012-02-15 19:33:52 +00005646
5647 // If this is a defaulted or implicitly-declared function, then
5648 // it was implicitly deleted. Make it clear that the deletion was
5649 // implicit.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005650 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00005651 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith6c4c36c2012-03-30 20:53:28 +00005652 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00005653 << DestType << ArgsRange;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005654 else
5655 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5656 << true << DestType << ArgsRange;
5657
5658 S.NoteDeletedFunction(Best->Function);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005659 break;
5660 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005661
Douglas Gregor51c56d62009-12-14 20:49:26 +00005662 case OR_Success:
5663 llvm_unreachable("Conversion did not fail!");
Douglas Gregor51c56d62009-12-14 20:49:26 +00005664 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005665 }
David Blaikie9fdefb32012-01-17 08:24:58 +00005666 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005667
Douglas Gregor99a2e602009-12-16 01:38:02 +00005668 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005669 if (Entity.getKind() == InitializedEntity::EK_Member &&
5670 isa<CXXConstructorDecl>(S.CurContext)) {
5671 // This is implicit default-initialization of a const member in
5672 // a constructor. Complain that it needs to be explicitly
5673 // initialized.
5674 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5675 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5676 << Constructor->isImplicit()
5677 << S.Context.getTypeDeclType(Constructor->getParent())
5678 << /*const=*/1
5679 << Entity.getName();
5680 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5681 << Entity.getName();
5682 } else {
5683 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5684 << DestType << (bool)DestType->getAs<RecordType>();
5685 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00005686 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005687
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005688 case FK_Incomplete:
5689 S.RequireCompleteType(Kind.getLocation(), DestType,
5690 diag::err_init_incomplete_type);
5691 break;
5692
Sebastian Redl14b0c192011-09-24 17:48:00 +00005693 case FK_ListInitializationFailed: {
5694 // Run the init list checker again to emit diagnostics.
5695 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5696 QualType DestType = Entity.getType();
5697 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00005698 DestType, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00005699 Kind.getKind() != InitializationKind::IK_DirectList ||
David Blaikie4e4d0842012-03-11 07:00:24 +00005700 !S.getLangOpts().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005701 assert(DiagnoseInitList.HadError() &&
5702 "Inconsistent init list check result.");
5703 break;
5704 }
John McCall5acb0c92011-10-17 18:40:02 +00005705
5706 case FK_PlaceholderType: {
5707 // FIXME: Already diagnosed!
5708 break;
5709 }
Sebastian Redl2b916b82012-01-17 22:49:42 +00005710
5711 case FK_InitListElementCopyFailure: {
5712 // Try to perform all copies again.
5713 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5714 unsigned NumInits = InitList->getNumInits();
5715 QualType DestType = Entity.getType();
5716 QualType E;
5717 bool Success = S.isStdInitializerList(DestType, &E);
5718 (void)Success;
5719 assert(Success && "Where did the std::initializer_list go?");
5720 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5721 S.Context.getConstantArrayType(E,
5722 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5723 NumInits),
5724 ArrayType::Normal, 0));
5725 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
5726 0, HiddenArray);
5727 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
5728 // where the init list type is wrong, e.g.
5729 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
5730 // FIXME: Emit a note if we hit the limit?
5731 int ErrorCount = 0;
5732 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
5733 Element.setElementIndex(i);
5734 ExprResult Init = S.Owned(InitList->getInit(i));
5735 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
5736 .isInvalid())
5737 ++ErrorCount;
5738 }
5739 break;
5740 }
Sebastian Redl70e24fc2012-04-01 19:54:59 +00005741
5742 case FK_ExplicitConstructor: {
5743 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
5744 << Args[0]->getSourceRange();
5745 OverloadCandidateSet::iterator Best;
5746 OverloadingResult Ovl
5747 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
5748 assert(Ovl == OR_Success && "Inconsistent overload resolution");
5749 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
5750 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
5751 break;
5752 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005753 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005754
Douglas Gregora41a8c52010-04-22 00:20:18 +00005755 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00005756 return true;
5757}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005758
Chris Lattner5f9e2722011-07-23 10:55:15 +00005759void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005760 switch (SequenceKind) {
5761 case FailedSequence: {
5762 OS << "Failed sequence: ";
5763 switch (Failure) {
5764 case FK_TooManyInitsForReference:
5765 OS << "too many initializers for reference";
5766 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005767
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005768 case FK_ArrayNeedsInitList:
5769 OS << "array requires initializer list";
5770 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005771
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005772 case FK_ArrayNeedsInitListOrStringLiteral:
5773 OS << "array requires initializer list or string literal";
5774 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005775
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005776 case FK_ArrayTypeMismatch:
5777 OS << "array type mismatch";
5778 break;
5779
5780 case FK_NonConstantArrayInit:
5781 OS << "non-constant array initializer";
5782 break;
5783
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005784 case FK_AddressOfOverloadFailed:
5785 OS << "address of overloaded function failed";
5786 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005787
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005788 case FK_ReferenceInitOverloadFailed:
5789 OS << "overload resolution for reference initialization failed";
5790 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005791
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005792 case FK_NonConstLValueReferenceBindingToTemporary:
5793 OS << "non-const lvalue reference bound to temporary";
5794 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005795
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005796 case FK_NonConstLValueReferenceBindingToUnrelated:
5797 OS << "non-const lvalue reference bound to unrelated type";
5798 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005799
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005800 case FK_RValueReferenceBindingToLValue:
5801 OS << "rvalue reference bound to an lvalue";
5802 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005803
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005804 case FK_ReferenceInitDropsQualifiers:
5805 OS << "reference initialization drops qualifiers";
5806 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005807
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005808 case FK_ReferenceInitFailed:
5809 OS << "reference initialization failed";
5810 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005811
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005812 case FK_ConversionFailed:
5813 OS << "conversion failed";
5814 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005815
John Wiegley429bb272011-04-08 18:41:53 +00005816 case FK_ConversionFromPropertyFailed:
5817 OS << "conversion from property failed";
5818 break;
5819
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005820 case FK_TooManyInitsForScalar:
5821 OS << "too many initializers for scalar";
5822 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005823
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005824 case FK_ReferenceBindingToInitList:
5825 OS << "referencing binding to initializer list";
5826 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005827
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005828 case FK_InitListBadDestinationType:
5829 OS << "initializer list for non-aggregate, non-scalar type";
5830 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005831
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005832 case FK_UserConversionOverloadFailed:
5833 OS << "overloading failed for user-defined conversion";
5834 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005835
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005836 case FK_ConstructorOverloadFailed:
5837 OS << "constructor overloading failed";
5838 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005839
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005840 case FK_DefaultInitOfConst:
5841 OS << "default initialization of a const variable";
5842 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005843
Douglas Gregor72a43bb2010-05-20 22:12:02 +00005844 case FK_Incomplete:
5845 OS << "initialization of incomplete type";
5846 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005847
5848 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00005849 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00005850 break;
5851
John McCall73076432012-01-05 00:13:19 +00005852 case FK_VariableLengthArrayHasInitializer:
5853 OS << "variable length array has an initializer";
5854 break;
5855
John McCall5acb0c92011-10-17 18:40:02 +00005856 case FK_PlaceholderType:
5857 OS << "initializer expression isn't contextually valid";
5858 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00005859
5860 case FK_ListConstructorOverloadFailed:
5861 OS << "list constructor overloading failed";
5862 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005863
5864 case FK_InitListElementCopyFailure:
5865 OS << "copy construction of initializer list element failed";
5866 break;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00005867
5868 case FK_ExplicitConstructor:
5869 OS << "list copy initialization chose explicit constructor";
5870 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005871 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005872 OS << '\n';
5873 return;
5874 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005875
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005876 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00005877 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005878 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005879
Sebastian Redl7491c492011-06-05 13:59:11 +00005880 case NormalSequence:
5881 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005882 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005883 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005884
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005885 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5886 if (S != step_begin()) {
5887 OS << " -> ";
5888 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005889
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005890 switch (S->Kind) {
5891 case SK_ResolveAddressOfOverloadedFunction:
5892 OS << "resolve address of overloaded function";
5893 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005894
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005895 case SK_CastDerivedToBaseRValue:
5896 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5897 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005898
Sebastian Redl906082e2010-07-20 04:20:21 +00005899 case SK_CastDerivedToBaseXValue:
5900 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5901 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005902
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005903 case SK_CastDerivedToBaseLValue:
5904 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5905 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005906
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005907 case SK_BindReference:
5908 OS << "bind reference to lvalue";
5909 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005910
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005911 case SK_BindReferenceToTemporary:
5912 OS << "bind reference to a temporary";
5913 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005914
Douglas Gregor523d46a2010-04-18 07:40:54 +00005915 case SK_ExtraneousCopyToTemporary:
5916 OS << "extraneous C++03 copy to temporary";
5917 break;
5918
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005919 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00005920 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005921 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005922
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005923 case SK_QualificationConversionRValue:
5924 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005925 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005926
Sebastian Redl906082e2010-07-20 04:20:21 +00005927 case SK_QualificationConversionXValue:
5928 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005929 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005930
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005931 case SK_QualificationConversionLValue:
5932 OS << "qualification conversion (lvalue)";
5933 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005934
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005935 case SK_ConversionSequence:
5936 OS << "implicit conversion sequence (";
5937 S->ICS->DebugPrint(); // FIXME: use OS
5938 OS << ")";
5939 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005940
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005941 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005942 OS << "list aggregate initialization";
5943 break;
5944
5945 case SK_ListConstructorCall:
5946 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005947 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005948
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005949 case SK_UnwrapInitList:
5950 OS << "unwrap reference initializer list";
5951 break;
5952
5953 case SK_RewrapInitList:
5954 OS << "rewrap reference initializer list";
5955 break;
5956
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005957 case SK_ConstructorInitialization:
5958 OS << "constructor initialization";
5959 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005960
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005961 case SK_ZeroInitialization:
5962 OS << "zero initialization";
5963 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005964
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005965 case SK_CAssignment:
5966 OS << "C assignment";
5967 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005968
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005969 case SK_StringInit:
5970 OS << "string initialization";
5971 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00005972
5973 case SK_ObjCObjectConversion:
5974 OS << "Objective-C object conversion";
5975 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005976
5977 case SK_ArrayInit:
5978 OS << "array initialization";
5979 break;
John McCallf85e1932011-06-15 23:02:42 +00005980
Richard Smith0f163e92012-02-15 22:38:09 +00005981 case SK_ParenthesizedArrayInit:
5982 OS << "parenthesized array initialization";
5983 break;
5984
John McCallf85e1932011-06-15 23:02:42 +00005985 case SK_PassByIndirectCopyRestore:
5986 OS << "pass by indirect copy and restore";
5987 break;
5988
5989 case SK_PassByIndirectRestore:
5990 OS << "pass by indirect restore";
5991 break;
5992
5993 case SK_ProduceObjCObject:
5994 OS << "Objective-C object retension";
5995 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005996
5997 case SK_StdInitializerList:
5998 OS << "std::initializer_list from initializer list";
5999 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006000 }
6001 }
6002}
6003
6004void InitializationSequence::dump() const {
6005 dump(llvm::errs());
6006}
6007
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006008static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
6009 QualType EntityType,
6010 const Expr *PreInit,
6011 const Expr *PostInit) {
6012 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
6013 return;
6014
6015 // A narrowing conversion can only appear as the final implicit conversion in
6016 // an initialization sequence.
6017 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
6018 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
6019 return;
6020
6021 const ImplicitConversionSequence &ICS = *LastStep.ICS;
6022 const StandardConversionSequence *SCS = 0;
6023 switch (ICS.getKind()) {
6024 case ImplicitConversionSequence::StandardConversion:
6025 SCS = &ICS.Standard;
6026 break;
6027 case ImplicitConversionSequence::UserDefinedConversion:
6028 SCS = &ICS.UserDefined.After;
6029 break;
6030 case ImplicitConversionSequence::AmbiguousConversion:
6031 case ImplicitConversionSequence::EllipsisConversion:
6032 case ImplicitConversionSequence::BadConversion:
6033 return;
6034 }
6035
6036 // Determine the type prior to the narrowing conversion. If a conversion
6037 // operator was used, this may be different from both the type of the entity
6038 // and of the pre-initialization expression.
6039 QualType PreNarrowingType = PreInit->getType();
6040 if (Seq.step_begin() + 1 != Seq.step_end())
6041 PreNarrowingType = Seq.step_end()[-2].Type;
6042
6043 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6044 APValue ConstantValue;
Richard Smithf6028062012-03-23 23:55:39 +00006045 QualType ConstantType;
6046 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6047 ConstantType)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006048 case NK_Not_Narrowing:
6049 // No narrowing occurred.
6050 return;
6051
6052 case NK_Type_Narrowing:
6053 // This was a floating-to-integer conversion, which is always considered a
6054 // narrowing conversion even if the value is a constant and can be
6055 // represented exactly as an integer.
6056 S.Diag(PostInit->getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00006057 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006058 diag::warn_init_list_type_narrowing
6059 : S.isSFINAEContext()?
6060 diag::err_init_list_type_narrowing_sfinae
6061 : diag::err_init_list_type_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006062 << PostInit->getSourceRange()
6063 << PreNarrowingType.getLocalUnqualifiedType()
6064 << EntityType.getLocalUnqualifiedType();
6065 break;
6066
6067 case NK_Constant_Narrowing:
6068 // A constant value was narrowed.
6069 S.Diag(PostInit->getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00006070 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006071 diag::warn_init_list_constant_narrowing
6072 : S.isSFINAEContext()?
6073 diag::err_init_list_constant_narrowing_sfinae
6074 : diag::err_init_list_constant_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006075 << PostInit->getSourceRange()
Richard Smithf6028062012-03-23 23:55:39 +00006076 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006077 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006078 break;
6079
6080 case NK_Variable_Narrowing:
6081 // A variable's value may have been narrowed.
6082 S.Diag(PostInit->getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00006083 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006084 diag::warn_init_list_variable_narrowing
6085 : S.isSFINAEContext()?
6086 diag::err_init_list_variable_narrowing_sfinae
6087 : diag::err_init_list_variable_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006088 << PostInit->getSourceRange()
6089 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006090 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006091 break;
6092 }
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006093
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006094 SmallString<128> StaticCast;
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006095 llvm::raw_svector_ostream OS(StaticCast);
6096 OS << "static_cast<";
6097 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6098 // It's important to use the typedef's name if there is one so that the
6099 // fixit doesn't break code using types like int64_t.
6100 //
6101 // FIXME: This will break if the typedef requires qualification. But
6102 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006103 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006104 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikie4e4d0842012-03-11 07:00:24 +00006105 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006106 else {
6107 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
6108 // with a broken cast.
6109 return;
6110 }
6111 OS << ">(";
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006112 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6113 << PostInit->getSourceRange()
6114 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006115 << FixItHint::CreateInsertion(
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006116 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006117}
6118
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006119//===----------------------------------------------------------------------===//
6120// Initialization helper functions
6121//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00006122bool
6123Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6124 ExprResult Init) {
6125 if (Init.isInvalid())
6126 return false;
6127
6128 Expr *InitE = Init.get();
6129 assert(InitE && "No initialization expression");
6130
6131 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
6132 SourceLocation());
6133 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00006134 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00006135}
6136
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006137ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006138Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6139 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006140 ExprResult Init,
Douglas Gregored878af2012-02-24 23:56:31 +00006141 bool TopLevelOfInitList,
6142 bool AllowExplicit) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006143 if (Init.isInvalid())
6144 return ExprError();
6145
John McCall15d7d122010-11-11 03:21:53 +00006146 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006147 assert(InitE && "No initialization expression?");
6148
6149 if (EqualLoc.isInvalid())
6150 EqualLoc = InitE->getLocStart();
6151
6152 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregored878af2012-02-24 23:56:31 +00006153 EqualLoc,
6154 AllowExplicit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006155 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
6156 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006157
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006158 ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
6159
6160 if (!Result.isInvalid() && TopLevelOfInitList)
6161 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6162 InitE, Result.get());
6163
6164 return Result;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006165}