blob: 406f524e04175466e6e5885df4afdd74e72d7a8a [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Sebastian Redl26bcc942011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattner0cb78032009-02-24 22:27:37 +000011//
Steve Narofff8ecff22008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
John McCall8b0666c2010-08-20 18:27:03 +000014#include "clang/Sema/Designator.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall83024632010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000018#include "clang/Lex/Preprocessor.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000019#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000023#include "clang/AST/TypeLoc.h"
Sebastian Redlc1839b12012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000028#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000029using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000030
Chris Lattner0cb78032009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
John McCall66884dd2011-02-21 07:22:22 +000035static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
36 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000037 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38 return 0;
39
Chris Lattnera9196812009-02-26 23:26:43 +000040 // See if this is a string literal or @encode.
41 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000042
Chris Lattnera9196812009-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 Lattner012b3392009-02-26 23:42:47 +000049 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000050
51 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregorfb65e592011-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 Friedman42a84652009-05-31 10:54:53 +000058 return ElemTy->isCharType() ? Init : 0;
Douglas Gregorfb65e592011-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 Lattnera9196812009-02-26 23:26:43 +000071
Douglas Gregorfb65e592011-07-27 05:40:30 +000072 return 0;
73 }
Mike Stump11289f42009-09-09 15:08:12 +000074
Douglas Gregorfb65e592011-07-27 05:40:30 +000075 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +000076}
77
John McCall66884dd2011-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 McCall5decec92011-02-21 07:57:55 +000085static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
86 Sema &S) {
Chris Lattnerd8b741c82009-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 Stump11289f42009-09-09 15:08:12 +000091
Chris Lattner0cb78032009-02-24 22:27:37 +000092 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000093 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000094 // being initialized to a string literal.
95 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000096 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000097 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000098 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
99 ConstVal,
100 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000101 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000102 }
Mike Stump11289f42009-09-09 15:08:12 +0000103
Eli Friedman893abe42009-05-29 18:22:49 +0000104 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000105
Eli Friedman554eba92011-04-11 00:23:45 +0000106 // We have an array of character type with known size. However,
Eli Friedman893abe42009-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.
Eli Friedman554eba92011-04-11 00:23:45 +0000109 if (S.getLangOptions().CPlusPlus) {
Anders Carlssond162fb82011-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 Friedman554eba92011-04-11 00:23:45 +0000119 // [dcl.init.string]p2
120 if (StrLength > CAT->getSize().getZExtValue())
121 S.Diag(Str->getSourceRange().getBegin(),
122 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())
127 S.Diag(Str->getSourceRange().getBegin(),
128 diag::warn_initializer_string_for_char_array_too_long)
129 << Str->getSourceRange();
130 }
Mike Stump11289f42009-09-09 15:08:12 +0000131
Eli Friedman893abe42009-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 Lattner0cb78032009-02-24 22:27:37 +0000137}
138
Chris Lattner0cb78032009-02-24 22:27:37 +0000139//===----------------------------------------------------------------------===//
140// Semantic checking for initializer lists.
141//===----------------------------------------------------------------------===//
142
Douglas Gregorcde232f2009-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 Bagnara92141d22011-01-27 19:55:10 +0000157/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-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 Lattner9ececce2009-02-24 22:48:58 +0000170namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000171class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000172 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000173 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000174 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000175 bool AllowBraceElision;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000176 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
177 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000178
Anders Carlsson6cabf312010-01-23 23:23:01 +0000179 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000180 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000181 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000182 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000183 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000184 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000185 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000186 unsigned &StructuredIndex,
187 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000188 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000189 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000190 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000191 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000192 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000193 unsigned &StructuredIndex,
194 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000195 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000196 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000197 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000198 InitListExpr *StructuredList,
199 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-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 Carlsson6cabf312010-01-23 23:23:01 +0000205 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000206 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000207 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000208 InitListExpr *StructuredList,
209 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000210 void CheckReferenceType(const InitializedEntity &Entity,
211 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000212 unsigned &Index,
213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000215 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000216 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000217 InitListExpr *StructuredList,
218 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000219 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000220 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000221 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000222 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000223 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000224 unsigned &StructuredIndex,
225 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000226 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000227 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000228 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000229 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000230 InitListExpr *StructuredList,
231 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000232 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000233 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000234 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000235 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000236 RecordDecl::field_iterator *NextField,
237 llvm::APSInt *NextElementIndex,
238 unsigned &Index,
239 InitListExpr *StructuredList,
240 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000241 bool FinishSubobjectInit,
242 bool TopLevelObject);
Douglas Gregor85df8d82009-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 Gregorcde232f2009-01-29 01:05:33 +0000248 void UpdateStructuredListElement(InitListExpr *StructuredList,
249 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000250 Expr *expr);
251 int numArrayElements(QualType DeclType);
252 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000253
Douglas Gregor2bb07652009-12-22 00:05:34 +0000254 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
255 const InitializedEntity &ParentEntity,
256 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000257 void FillInValueInitializations(const InitializedEntity &Entity,
258 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000259 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
260 Expr *InitExpr, FieldDecl *Field,
261 bool TopLevelObject);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000262 void CheckValueInitializable(const InitializedEntity &Entity);
263
Douglas Gregor85df8d82009-01-29 00:45:39 +0000264public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000265 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000266 InitListExpr *IL, QualType &T, bool VerifyOnly,
267 bool AllowBraceElision);
Douglas Gregor85df8d82009-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 Lattner9ececce2009-02-24 22:48:58 +0000274} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000275
Sebastian Redl2b47b7a2011-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 Gregor2bb07652009-12-22 00:05:34 +0000288void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
289 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000290 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000291 bool &RequiresSecondPass) {
292 SourceLocation Loc = ILE->getSourceRange().getBegin();
293 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000294 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-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 Takumif9cbcc42011-01-27 07:10:08 +0000313
Douglas Gregor2bb07652009-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 Takumif9cbcc42011-01-27 07:10:08 +0000322
John McCalldadc5752010-08-24 06:29:42 +0000323 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000324 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000325 if (MemberInit.isInvalid()) {
326 hadError = true;
327 return;
328 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000329
Douglas Gregor2bb07652009-12-22 00:05:34 +0000330 if (hadError) {
331 // Do nothing
332 } else if (Init < NumInits) {
333 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redld201edf2011-06-05 13:59:11 +0000334 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregor2bb07652009-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 Kremenekac034612010-04-13 23:39:13 +0000339 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000340 RequiresSecondPass = true;
341 }
342 } else if (InitListExpr *InnerILE
343 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000344 FillInValueInitializations(MemberEntity, InnerILE,
345 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000346}
347
Douglas Gregor347f7ea2009-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 Takumif9cbcc42011-01-27 07:10:08 +0000351void
Douglas Gregor723796a2009-12-16 06:35:08 +0000352InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
353 InitListExpr *ILE,
354 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000355 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000356 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000357 SourceLocation Loc = ILE->getSourceRange().getBegin();
358 if (ILE->getSyntacticForm())
359 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000360
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000361 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-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 Gregor347f7ea2009-01-28 21:54:33 +0000374
Douglas Gregor2bb07652009-12-22 00:05:34 +0000375 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000376 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000377
378 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
379 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000380 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000381
Douglas Gregor2bb07652009-12-22 00:05:34 +0000382 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000383
Douglas Gregor2bb07652009-12-22 00:05:34 +0000384 // Only look at the first initialization of a union.
385 if (RType->getDecl()->isUnion())
386 break;
387 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000388 }
389
390 return;
Mike Stump11289f42009-09-09 15:08:12 +0000391 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000392
393 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000394
Douglas Gregor723796a2009-12-16 06:35:08 +0000395 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000396 unsigned NumInits = ILE->getNumInits();
397 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000398 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000399 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000400 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
401 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000402 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000403 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000404 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000405 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000406 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000407 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000408 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000409 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000410 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000411
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000412
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000413 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000414 if (hadError)
415 return;
416
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000417 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
418 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000419 ElementEntity.setElementIndex(Init);
420
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000421 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
422 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregor723796a2009-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 Gregora5c9e1a2009-02-02 17:43:21 +0000428 hadError = true;
429 return;
430 }
431
John McCalldadc5752010-08-24 06:29:42 +0000432 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000433 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000434 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000435 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000436 return;
437 }
438
439 if (hadError) {
440 // Do nothing
441 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-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 Kyrtzidisb2ed28e2011-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 Redld201edf2011-06-05 13:59:11 +0000456 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidisb2ed28e2011-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 Gregor723796a2009-12-16 06:35:08 +0000464 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000465 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000466 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregor723796a2009-12-16 06:35:08 +0000467 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000468 }
469}
470
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000471
Douglas Gregor723796a2009-12-16 06:35:08 +0000472InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000473 InitListExpr *IL, QualType &T,
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000474 bool VerifyOnly, bool AllowBraceElision)
Richard Smith0f8ede12011-12-20 04:00:21 +0000475 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000476 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000477
Eli Friedman23a9e312008-05-19 19:16:24 +0000478 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000479 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000480 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000481 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000482 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000483 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000484 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000485
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000486 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000487 bool RequiresSecondPass = false;
488 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000489 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000490 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000491 RequiresSecondPass);
492 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000493}
494
495int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000496 // FIXME: use a proper constant
497 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000498 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000499 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-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 Kremenekc23c7e62009-07-29 21:53:49 +0000506 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000507 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000508 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000509 Field = structDecl->field_begin(),
510 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000511 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +0000512 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000513 ++InitializableMembers;
514 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000515 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000516 return std::min(InitializableMembers, 1);
517 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000518}
519
Anders Carlsson6cabf312010-01-23 23:23:01 +0000520void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000521 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000522 QualType T, unsigned &Index,
523 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000524 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000525 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000526
Steve Narofff8ecff22008-05-01 22:18:59 +0000527 if (T->isArrayType())
528 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000529 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000530 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000531 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000532 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000533 else
David Blaikie83d382b2011-09-23 05:06:16 +0000534 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000535
Eli Friedmane0f832b2008-05-25 13:49:22 +0000536 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000537 if (!VerifyOnly)
538 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
539 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000540 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000541 hadError = true;
542 return;
543 }
544
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000545 // Build a structured initializer list corresponding to this subobject.
546 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000547 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
548 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000549 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
550 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000551 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000552
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000553 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000554 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000555 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000556 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000557 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000558 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000559
560 if (VerifyOnly) {
561 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
562 hadError = true;
563 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000564 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000565
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000566 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-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 Takumif9cbcc42011-01-27 07:10:08 +0000574
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000575 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000576 if (T->isArrayType() || T->isRecordType()) {
577 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000578 AllowBraceElision ? diag::warn_missing_braces :
579 diag::err_missing_braces)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000580 << StructuredSubobjectInitList->getSourceRange()
581 << FixItHint::CreateInsertion(
582 StructuredSubobjectInitList->getLocStart(), "{")
583 << FixItHint::CreateInsertion(
584 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000585 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000586 "}");
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000587 if (!AllowBraceElision)
588 hadError = true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000589 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000590 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000591}
592
Anders Carlsson6cabf312010-01-23 23:23:01 +0000593void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000594 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000595 unsigned &Index,
596 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000597 unsigned &StructuredIndex,
598 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000599 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000600 if (!VerifyOnly) {
601 SyntacticToSemantic[IList] = StructuredList;
602 StructuredList->setSyntacticForm(IList);
603 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000604 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000605 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000606 if (!VerifyOnly) {
607 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
608 IList->setType(ExprTy);
609 StructuredList->setType(ExprTy);
610 }
Eli Friedman85f54972008-05-25 13:22:35 +0000611 if (hadError)
612 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000613
Eli Friedman85f54972008-05-25 13:22:35 +0000614 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000615 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000616 if (VerifyOnly) {
617 if (SemaRef.getLangOptions().CPlusPlus ||
618 (SemaRef.getLangOptions().OpenCL &&
619 IList->getType()->isVectorType())) {
620 hadError = true;
621 }
622 return;
623 }
624
Eli Friedmanbd327452009-05-29 20:20:05 +0000625 if (StructuredIndex == 1 &&
626 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000627 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000628 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000629 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000630 hadError = true;
631 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000632 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000633 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000634 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000635 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000636 // Don't complain for incomplete types, since we'll get an error
637 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000638 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000639 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000640 CurrentObjectType->isArrayType()? 0 :
641 CurrentObjectType->isVectorType()? 1 :
642 CurrentObjectType->isScalarType()? 2 :
643 CurrentObjectType->isUnionType()? 3 :
644 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000645
646 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000647 if (SemaRef.getLangOptions().CPlusPlus) {
648 DK = diag::err_excess_initializers;
649 hadError = true;
650 }
Nate Begeman425038c2009-07-07 21:53:06 +0000651 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
652 DK = diag::err_excess_initializers;
653 hadError = true;
654 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000655
Chris Lattnerb0912a52009-02-24 22:50:46 +0000656 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000657 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000658 }
659 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000660
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000661 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
662 !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000663 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000664 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000665 << FixItHint::CreateRemoval(IList->getLocStart())
666 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000667}
668
Anders Carlsson6cabf312010-01-23 23:23:01 +0000669void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000670 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000671 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000672 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000673 unsigned &Index,
674 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000675 unsigned &StructuredIndex,
676 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000677 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
678 // Explicitly braced initializer for complex type can be real+imaginary
679 // parts.
680 CheckComplexType(Entity, IList, DeclType, Index,
681 StructuredList, StructuredIndex);
682 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000683 CheckScalarType(Entity, IList, DeclType, Index,
684 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000685 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000686 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000687 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000688 } else if (DeclType->isAggregateType()) {
689 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000690 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000691 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000692 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000693 StructuredList, StructuredIndex,
694 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000695 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000696 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000697 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000698 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000700 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000701 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000702 } else
David Blaikie83d382b2011-09-23 05:06:16 +0000703 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000704 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
705 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000706 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000707 if (!VerifyOnly)
708 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
709 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000710 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000711 } else if (DeclType->isRecordType()) {
712 // C++ [dcl.init]p14:
713 // [...] If the class is an aggregate (8.5.1), and the initializer
714 // is a brace-enclosed list, see 8.5.1.
715 //
716 // Note: 8.5.1 is handled below; here, we diagnose the case where
717 // we have an initializer list and a destination type that is not
718 // an aggregate.
719 // FIXME: In C++0x, this is yet another form of initialization.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000720 if (!VerifyOnly)
721 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
722 << DeclType << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000723 hadError = true;
724 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000725 CheckReferenceType(Entity, IList, DeclType, Index,
726 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000727 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000728 if (!VerifyOnly)
729 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
730 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000731 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000732 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000733 if (!VerifyOnly)
734 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
735 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000736 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000737 }
738}
739
Anders Carlsson6cabf312010-01-23 23:23:01 +0000740void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000741 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000742 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000743 unsigned &Index,
744 InitListExpr *StructuredList,
745 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000746 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000747 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
748 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000749 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000750 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000751 = getStructuredSubobjectInit(IList, Index, ElemType,
752 StructuredList, StructuredIndex,
753 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000754 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000755 newStructuredList, newStructuredIndex);
756 ++StructuredIndex;
757 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000758 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000759 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000760 return CheckScalarType(Entity, IList, ElemType, Index,
761 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000762 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000763 return CheckReferenceType(Entity, IList, ElemType, Index,
764 StructuredList, StructuredIndex);
765 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000766
John McCall5decec92011-02-21 07:57:55 +0000767 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
768 // arrayType can be incomplete if we're initializing a flexible
769 // array member. There's nothing we can do with the completed
770 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000771
John McCall5decec92011-02-21 07:57:55 +0000772 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedmand8d7a372011-09-26 19:09:09 +0000773 if (!VerifyOnly) {
774 CheckStringInit(Str, ElemType, arrayType, SemaRef);
775 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
776 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000777 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000778 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000779 }
John McCall5decec92011-02-21 07:57:55 +0000780
781 // Fall through for subaggregate initialization.
782
783 } else if (SemaRef.getLangOptions().CPlusPlus) {
784 // C++ [dcl.init.aggr]p12:
785 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000786 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000787 // an initializer-list. If the initializer can initialize a
788 // member, the member is initialized. [...]
789
790 // FIXME: Better EqualLoc?
791 InitializationKind Kind =
792 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
793 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
794
795 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000796 if (!VerifyOnly) {
Richard Smith0f8ede12011-12-20 04:00:21 +0000797 ExprResult Result =
798 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
799 if (Result.isInvalid())
800 hadError = true;
John McCall5decec92011-02-21 07:57:55 +0000801
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000802 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smith0f8ede12011-12-20 04:00:21 +0000803 Result.takeAs<Expr>());
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000804 }
John McCall5decec92011-02-21 07:57:55 +0000805 ++Index;
806 return;
807 }
808
809 // Fall through for subaggregate initialization
810 } else {
811 // C99 6.7.8p13:
812 //
813 // The initializer for a structure or union object that has
814 // automatic storage duration shall be either an initializer
815 // list as described below, or a single expression that has
816 // compatible structure or union type. In the latter case, the
817 // initial value of the object, including unnamed members, is
818 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000819 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000820 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000821 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
822 !VerifyOnly)
John McCall5decec92011-02-21 07:57:55 +0000823 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000824 if (ExprRes.isInvalid())
825 hadError = true;
826 else {
827 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
828 if (ExprRes.isInvalid())
829 hadError = true;
830 }
831 UpdateStructuredListElement(StructuredList, StructuredIndex,
832 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000833 ++Index;
834 return;
835 }
John Wiegley01296292011-04-08 18:41:53 +0000836 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000837 // Fall through for subaggregate initialization
838 }
839
840 // C++ [dcl.init.aggr]p12:
841 //
842 // [...] Otherwise, if the member is itself a non-empty
843 // subaggregate, brace elision is assumed and the initializer is
844 // considered for the initialization of the first member of
845 // the subaggregate.
Tanya Lattner83559382011-07-15 23:07:01 +0000846 if (!SemaRef.getLangOptions().OpenCL &&
847 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +0000848 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
849 StructuredIndex);
850 ++StructuredIndex;
851 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000852 if (!VerifyOnly) {
853 // We cannot initialize this element, so let
854 // PerformCopyInitialization produce the appropriate diagnostic.
855 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
856 SemaRef.Owned(expr),
857 /*TopLevelOfInitList=*/true);
858 }
John McCall5decec92011-02-21 07:57:55 +0000859 hadError = true;
860 ++Index;
861 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000862 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000863}
864
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000865void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
866 InitListExpr *IList, QualType DeclType,
867 unsigned &Index,
868 InitListExpr *StructuredList,
869 unsigned &StructuredIndex) {
870 assert(Index == 0 && "Index in explicit init list must be zero");
871
872 // As an extension, clang supports complex initializers, which initialize
873 // a complex number component-wise. When an explicit initializer list for
874 // a complex number contains two two initializers, this extension kicks in:
875 // it exepcts the initializer list to contain two elements convertible to
876 // the element type of the complex type. The first element initializes
877 // the real part, and the second element intitializes the imaginary part.
878
879 if (IList->getNumInits() != 2)
880 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
881 StructuredIndex);
882
883 // This is an extension in C. (The builtin _Complex type does not exist
884 // in the C++ standard.)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000885 if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000886 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
887 << IList->getSourceRange();
888
889 // Initialize the complex number.
890 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
891 InitializedEntity ElementEntity =
892 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
893
894 for (unsigned i = 0; i < 2; ++i) {
895 ElementEntity.setElementIndex(Index);
896 CheckSubElementType(ElementEntity, IList, elementType, Index,
897 StructuredList, StructuredIndex);
898 }
899}
900
901
Anders Carlsson6cabf312010-01-23 23:23:01 +0000902void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000903 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000904 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000905 InitListExpr *StructuredList,
906 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000907 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +0000908 if (!VerifyOnly)
909 SemaRef.Diag(IList->getLocStart(),
910 SemaRef.getLangOptions().CPlusPlus0x ?
911 diag::warn_cxx98_compat_empty_scalar_initializer :
912 diag::err_empty_scalar_initializer)
913 << IList->getSourceRange();
914 hadError = !SemaRef.getLangOptions().CPlusPlus0x;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000915 ++Index;
916 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000917 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000918 }
John McCall643169b2010-11-11 00:46:36 +0000919
920 Expr *expr = IList->getInit(Index);
921 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000922 if (!VerifyOnly)
923 SemaRef.Diag(SubIList->getLocStart(),
924 diag::warn_many_braces_around_scalar_init)
925 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000926
927 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
928 StructuredIndex);
929 return;
930 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000931 if (!VerifyOnly)
932 SemaRef.Diag(expr->getSourceRange().getBegin(),
933 diag::err_designator_for_scalar_init)
934 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000935 hadError = true;
936 ++Index;
937 ++StructuredIndex;
938 return;
939 }
940
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000941 if (VerifyOnly) {
942 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
943 hadError = true;
944 ++Index;
945 return;
946 }
947
John McCall643169b2010-11-11 00:46:36 +0000948 ExprResult Result =
949 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000950 SemaRef.Owned(expr),
951 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +0000952
953 Expr *ResultExpr = 0;
954
955 if (Result.isInvalid())
956 hadError = true; // types weren't compatible.
957 else {
958 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000959
John McCall643169b2010-11-11 00:46:36 +0000960 if (ResultExpr != expr) {
961 // The type was promoted, update initializer list.
962 IList->setInit(Index, ResultExpr);
963 }
964 }
965 if (hadError)
966 ++StructuredIndex;
967 else
968 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
969 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000970}
971
Anders Carlsson6cabf312010-01-23 23:23:01 +0000972void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
973 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000974 unsigned &Index,
975 InitListExpr *StructuredList,
976 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000977 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +0000978 // FIXME: It would be wonderful if we could point at the actual member. In
979 // general, it would be useful to pass location information down the stack,
980 // so that we know the location (or decl) of the "current object" being
981 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000982 if (!VerifyOnly)
983 SemaRef.Diag(IList->getLocStart(),
984 diag::err_init_reference_member_uninitialized)
985 << DeclType
986 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000987 hadError = true;
988 ++Index;
989 ++StructuredIndex;
990 return;
991 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000992
993 Expr *expr = IList->getInit(Index);
Sebastian Redl29526f02011-11-27 16:50:07 +0000994 if (isa<InitListExpr>(expr) && !SemaRef.getLangOptions().CPlusPlus0x) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000995 if (!VerifyOnly)
996 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
997 << DeclType << IList->getSourceRange();
998 hadError = true;
999 ++Index;
1000 ++StructuredIndex;
1001 return;
1002 }
1003
1004 if (VerifyOnly) {
1005 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1006 hadError = true;
1007 ++Index;
1008 return;
1009 }
1010
1011 ExprResult Result =
1012 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1013 SemaRef.Owned(expr),
1014 /*TopLevelOfInitList=*/true);
1015
1016 if (Result.isInvalid())
1017 hadError = true;
1018
1019 expr = Result.takeAs<Expr>();
1020 IList->setInit(Index, expr);
1021
1022 if (hadError)
1023 ++StructuredIndex;
1024 else
1025 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1026 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001027}
1028
Anders Carlsson6cabf312010-01-23 23:23:01 +00001029void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001030 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001031 unsigned &Index,
1032 InitListExpr *StructuredList,
1033 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001034 const VectorType *VT = DeclType->getAs<VectorType>();
1035 unsigned maxElements = VT->getNumElements();
1036 unsigned numEltsInit = 0;
1037 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001038
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001039 if (Index >= IList->getNumInits()) {
1040 // Make sure the element type can be value-initialized.
1041 if (VerifyOnly)
1042 CheckValueInitializable(
1043 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1044 return;
1045 }
1046
John McCall6a16b2f2010-10-30 00:11:39 +00001047 if (!SemaRef.getLangOptions().OpenCL) {
1048 // If the initializing element is a vector, try to copy-initialize
1049 // instead of breaking it apart (which is doomed to failure anyway).
1050 Expr *Init = IList->getInit(Index);
1051 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001052 if (VerifyOnly) {
1053 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1054 hadError = true;
1055 ++Index;
1056 return;
1057 }
1058
John McCall6a16b2f2010-10-30 00:11:39 +00001059 ExprResult Result =
1060 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001061 SemaRef.Owned(Init),
1062 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001063
1064 Expr *ResultExpr = 0;
1065 if (Result.isInvalid())
1066 hadError = true; // types weren't compatible.
1067 else {
1068 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001069
John McCall6a16b2f2010-10-30 00:11:39 +00001070 if (ResultExpr != Init) {
1071 // The type was promoted, update initializer list.
1072 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001073 }
1074 }
John McCall6a16b2f2010-10-30 00:11:39 +00001075 if (hadError)
1076 ++StructuredIndex;
1077 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001078 UpdateStructuredListElement(StructuredList, StructuredIndex,
1079 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001080 ++Index;
1081 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001082 }
Mike Stump11289f42009-09-09 15:08:12 +00001083
John McCall6a16b2f2010-10-30 00:11:39 +00001084 InitializedEntity ElementEntity =
1085 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001086
John McCall6a16b2f2010-10-30 00:11:39 +00001087 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1088 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001089 if (Index >= IList->getNumInits()) {
1090 if (VerifyOnly)
1091 CheckValueInitializable(ElementEntity);
John McCall6a16b2f2010-10-30 00:11:39 +00001092 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001094
John McCall6a16b2f2010-10-30 00:11:39 +00001095 ElementEntity.setElementIndex(Index);
1096 CheckSubElementType(ElementEntity, IList, elementType, Index,
1097 StructuredList, StructuredIndex);
1098 }
1099 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001100 }
John McCall6a16b2f2010-10-30 00:11:39 +00001101
1102 InitializedEntity ElementEntity =
1103 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001104
John McCall6a16b2f2010-10-30 00:11:39 +00001105 // OpenCL initializers allows vectors to be constructed from vectors.
1106 for (unsigned i = 0; i < maxElements; ++i) {
1107 // Don't attempt to go past the end of the init list
1108 if (Index >= IList->getNumInits())
1109 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001110
John McCall6a16b2f2010-10-30 00:11:39 +00001111 ElementEntity.setElementIndex(Index);
1112
1113 QualType IType = IList->getInit(Index)->getType();
1114 if (!IType->isVectorType()) {
1115 CheckSubElementType(ElementEntity, IList, elementType, Index,
1116 StructuredList, StructuredIndex);
1117 ++numEltsInit;
1118 } else {
1119 QualType VecType;
1120 const VectorType *IVT = IType->getAs<VectorType>();
1121 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001122
John McCall6a16b2f2010-10-30 00:11:39 +00001123 if (IType->isExtVectorType())
1124 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1125 else
1126 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001127 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001128 CheckSubElementType(ElementEntity, IList, VecType, Index,
1129 StructuredList, StructuredIndex);
1130 numEltsInit += numIElts;
1131 }
1132 }
1133
1134 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001135 if (numEltsInit != maxElements) {
1136 if (!VerifyOnly)
1137 SemaRef.Diag(IList->getSourceRange().getBegin(),
1138 diag::err_vector_incorrect_num_initializers)
1139 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1140 hadError = true;
1141 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001142}
1143
Anders Carlsson6cabf312010-01-23 23:23:01 +00001144void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001145 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001146 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001147 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001148 unsigned &Index,
1149 InitListExpr *StructuredList,
1150 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001151 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1152
Steve Narofff8ecff22008-05-01 22:18:59 +00001153 // Check for the special-case of initializing an array with a string.
1154 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +00001155 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +00001156 SemaRef.Context)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001157 // We place the string literal directly into the resulting
1158 // initializer list. This is the only place where the structure
1159 // of the structured initializer list doesn't match exactly,
1160 // because doing so would involve allocating one character
1161 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001162 if (!VerifyOnly) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001163 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001164 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1165 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1166 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001167 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001168 return;
1169 }
1170 }
John McCall66884dd2011-02-21 07:22:22 +00001171 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001172 // Check for VLAs; in standard C it would be possible to check this
1173 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1174 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001175 if (!VerifyOnly)
1176 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1177 diag::err_variable_object_no_init)
1178 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001179 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001180 ++Index;
1181 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001182 return;
1183 }
1184
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001185 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001186 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1187 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001188 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001189 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001190 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001191 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001192 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001193 maxElementsKnown = true;
1194 }
1195
John McCall66884dd2011-02-21 07:22:22 +00001196 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001197 while (Index < IList->getNumInits()) {
1198 Expr *Init = IList->getInit(Index);
1199 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001200 // If we're not the subobject that matches up with the '{' for
1201 // the designator, we shouldn't be handling the
1202 // designator. Return immediately.
1203 if (!SubobjectIsDesignatorContext)
1204 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001205
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001206 // Handle this designated initializer. elementIndex will be
1207 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001208 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001209 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001210 StructuredList, StructuredIndex, true,
1211 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001212 hadError = true;
1213 continue;
1214 }
1215
Douglas Gregor033d1252009-01-23 16:54:12 +00001216 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001217 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001218 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001219 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001220 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001221
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001222 // If the array is of incomplete type, keep track of the number of
1223 // elements in the initializer.
1224 if (!maxElementsKnown && elementIndex > maxElements)
1225 maxElements = elementIndex;
1226
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001227 continue;
1228 }
1229
1230 // If we know the maximum number of elements, and we've already
1231 // hit it, stop consuming elements in the initializer list.
1232 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001233 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001234
Anders Carlsson6cabf312010-01-23 23:23:01 +00001235 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001236 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001237 Entity);
1238 // Check this element.
1239 CheckSubElementType(ElementEntity, IList, elementType, Index,
1240 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001241 ++elementIndex;
1242
1243 // If the array is of incomplete type, keep track of the number of
1244 // elements in the initializer.
1245 if (!maxElementsKnown && elementIndex > maxElements)
1246 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001247 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001248 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001249 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001250 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001251 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001252 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001253 // Sizing an array implicitly to zero is not allowed by ISO C,
1254 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001255 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001256 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001257 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001258
Mike Stump11289f42009-09-09 15:08:12 +00001259 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001260 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001261 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001262 if (!hadError && VerifyOnly) {
1263 // Check if there are any members of the array that get value-initialized.
1264 // If so, check if doing that is possible.
1265 // FIXME: This needs to detect holes left by designated initializers too.
1266 if (maxElementsKnown && elementIndex < maxElements)
1267 CheckValueInitializable(InitializedEntity::InitializeElement(
1268 SemaRef.Context, 0, Entity));
1269 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001270}
1271
Eli Friedman3fa64df2011-08-23 22:24:57 +00001272bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1273 Expr *InitExpr,
1274 FieldDecl *Field,
1275 bool TopLevelObject) {
1276 // Handle GNU flexible array initializers.
1277 unsigned FlexArrayDiag;
1278 if (isa<InitListExpr>(InitExpr) &&
1279 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1280 // Empty flexible array init always allowed as an extension
1281 FlexArrayDiag = diag::ext_flexible_array_init;
1282 } else if (SemaRef.getLangOptions().CPlusPlus) {
1283 // Disallow flexible array init in C++; it is not required for gcc
1284 // compatibility, and it needs work to IRGen correctly in general.
1285 FlexArrayDiag = diag::err_flexible_array_init;
1286 } else if (!TopLevelObject) {
1287 // Disallow flexible array init on non-top-level object
1288 FlexArrayDiag = diag::err_flexible_array_init;
1289 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1290 // Disallow flexible array init on anything which is not a variable.
1291 FlexArrayDiag = diag::err_flexible_array_init;
1292 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1293 // Disallow flexible array init on local variables.
1294 FlexArrayDiag = diag::err_flexible_array_init;
1295 } else {
1296 // Allow other cases.
1297 FlexArrayDiag = diag::ext_flexible_array_init;
1298 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001299
1300 if (!VerifyOnly) {
1301 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1302 FlexArrayDiag)
1303 << InitExpr->getSourceRange().getBegin();
1304 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1305 << Field;
1306 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001307
1308 return FlexArrayDiag != diag::ext_flexible_array_init;
1309}
1310
Anders Carlsson6cabf312010-01-23 23:23:01 +00001311void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001312 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001313 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001314 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001315 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001316 unsigned &Index,
1317 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001318 unsigned &StructuredIndex,
1319 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001320 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001321
Eli Friedman23a9e312008-05-19 19:16:24 +00001322 // If the record is invalid, some of it's members are invalid. To avoid
1323 // confusion, we forgo checking the intializer for the entire record.
1324 if (structDecl->isInvalidDecl()) {
1325 hadError = true;
1326 return;
Mike Stump11289f42009-09-09 15:08:12 +00001327 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001328
1329 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001330 // Value-initialize the first named member of the union.
1331 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1332 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1333 Field != FieldEnd; ++Field) {
1334 if (Field->getDeclName()) {
1335 if (VerifyOnly)
1336 CheckValueInitializable(
1337 InitializedEntity::InitializeMember(*Field, &Entity));
1338 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001339 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001340 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001341 }
1342 }
1343 return;
1344 }
1345
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001346 // If structDecl is a forward declaration, this loop won't do
1347 // anything except look at designated initializers; That's okay,
1348 // because an error should get printed out elsewhere. It might be
1349 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001350 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001351 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001352 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001353 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001354 while (Index < IList->getNumInits()) {
1355 Expr *Init = IList->getInit(Index);
1356
1357 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001358 // If we're not the subobject that matches up with the '{' for
1359 // the designator, we shouldn't be handling the
1360 // designator. Return immediately.
1361 if (!SubobjectIsDesignatorContext)
1362 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001363
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001364 // Handle this designated initializer. Field will be updated to
1365 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001366 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001367 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001368 StructuredList, StructuredIndex,
1369 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001370 hadError = true;
1371
Douglas Gregora9add4e2009-02-12 19:00:39 +00001372 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001373
1374 // Disable check for missing fields when designators are used.
1375 // This matches gcc behaviour.
1376 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001377 continue;
1378 }
1379
1380 if (Field == FieldEnd) {
1381 // We've run out of fields. We're done.
1382 break;
1383 }
1384
Douglas Gregora9add4e2009-02-12 19:00:39 +00001385 // We've already initialized a member of a union. We're done.
1386 if (InitializedSomething && DeclType->isUnionType())
1387 break;
1388
Douglas Gregor91f84212008-12-11 16:49:14 +00001389 // If we've hit the flexible array member at the end, we're done.
1390 if (Field->getType()->isIncompleteArrayType())
1391 break;
1392
Douglas Gregor51695702009-01-29 16:53:55 +00001393 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001394 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001395 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001396 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001397 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001398
Douglas Gregora82064c2011-06-29 21:51:31 +00001399 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001400 bool InvalidUse;
1401 if (VerifyOnly)
1402 InvalidUse = !SemaRef.CanUseDecl(*Field);
1403 else
1404 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1405 IList->getInit(Index)->getLocStart());
1406 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001407 ++Index;
1408 ++Field;
1409 hadError = true;
1410 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001411 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001412
Anders Carlsson6cabf312010-01-23 23:23:01 +00001413 InitializedEntity MemberEntity =
1414 InitializedEntity::InitializeMember(*Field, &Entity);
1415 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1416 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001417 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001418
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001419 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001420 // Initialize the first field within the union.
1421 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001422 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001423
1424 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001425 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001426
John McCalle40b58e2010-03-11 19:32:38 +00001427 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001428 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1429 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1430 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001431 // It is possible we have one or more unnamed bitfields remaining.
1432 // Find first (if any) named field and emit warning.
1433 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1434 it != end; ++it) {
1435 if (!it->isUnnamedBitfield()) {
1436 SemaRef.Diag(IList->getSourceRange().getEnd(),
1437 diag::warn_missing_field_initializers) << it->getName();
1438 break;
1439 }
1440 }
1441 }
1442
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001443 // Check that any remaining fields can be value-initialized.
1444 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1445 !Field->getType()->isIncompleteArrayType()) {
1446 // FIXME: Should check for holes left by designated initializers too.
1447 for (; Field != FieldEnd && !hadError; ++Field) {
1448 if (!Field->isUnnamedBitfield())
1449 CheckValueInitializable(
1450 InitializedEntity::InitializeMember(*Field, &Entity));
1451 }
1452 }
1453
Mike Stump11289f42009-09-09 15:08:12 +00001454 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001455 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001456 return;
1457
Eli Friedman3fa64df2011-08-23 22:24:57 +00001458 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1459 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001460 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001461 ++Index;
1462 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001463 }
1464
Anders Carlsson6cabf312010-01-23 23:23:01 +00001465 InitializedEntity MemberEntity =
1466 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001467
Anders Carlsson6cabf312010-01-23 23:23:01 +00001468 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001469 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001470 StructuredList, StructuredIndex);
1471 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001472 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001473 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001474}
Steve Narofff8ecff22008-05-01 22:18:59 +00001475
Douglas Gregord5846a12009-04-15 06:41:24 +00001476/// \brief Expand a field designator that refers to a member of an
1477/// anonymous struct or union into a series of field designators that
1478/// refers to the field within the appropriate subobject.
1479///
Douglas Gregord5846a12009-04-15 06:41:24 +00001480static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001481 DesignatedInitExpr *DIE,
1482 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001483 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001484 typedef DesignatedInitExpr::Designator Designator;
1485
Douglas Gregord5846a12009-04-15 06:41:24 +00001486 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001487 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001488 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1489 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1490 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001491 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001492 DIE->getDesignator(DesigIdx)->getDotLoc(),
1493 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1494 else
1495 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1496 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001497 assert(isa<FieldDecl>(*PI));
1498 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001499 }
1500
1501 // Expand the current designator into the set of replacement
1502 // designators, so we have a full subobject path down to where the
1503 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001504 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001505 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001506}
Mike Stump11289f42009-09-09 15:08:12 +00001507
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001508/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001509/// corresponds to FieldName.
1510static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1511 IdentifierInfo *FieldName) {
1512 assert(AnonField->isAnonymousStructOrUnion());
1513 Decl *NextDecl = AnonField->getNextDeclInContext();
1514 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1515 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1516 return IF;
1517 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001518 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001519 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001520}
1521
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001522static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1523 DesignatedInitExpr *DIE) {
1524 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1525 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1526 for (unsigned I = 0; I < NumIndexExprs; ++I)
1527 IndexExprs[I] = DIE->getSubExpr(I + 1);
1528 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1529 DIE->size(), IndexExprs.data(),
1530 NumIndexExprs, DIE->getEqualOrColonLoc(),
1531 DIE->usesGNUSyntax(), DIE->getInit());
1532}
1533
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001534namespace {
1535
1536// Callback to only accept typo corrections that are for field members of
1537// the given struct or union.
1538class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1539 public:
1540 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1541 : Record(RD) {}
1542
1543 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1544 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1545 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1546 }
1547
1548 private:
1549 RecordDecl *Record;
1550};
1551
1552}
1553
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001554/// @brief Check the well-formedness of a C99 designated initializer.
1555///
1556/// Determines whether the designated initializer @p DIE, which
1557/// resides at the given @p Index within the initializer list @p
1558/// IList, is well-formed for a current object of type @p DeclType
1559/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001560/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001561/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001562///
1563/// @param IList The initializer list in which this designated
1564/// initializer occurs.
1565///
Douglas Gregora5324162009-04-15 04:56:10 +00001566/// @param DIE The designated initializer expression.
1567///
1568/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001569///
1570/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1571/// into which the designation in @p DIE should refer.
1572///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001573/// @param NextField If non-NULL and the first designator in @p DIE is
1574/// a field, this will be set to the field declaration corresponding
1575/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001576///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001577/// @param NextElementIndex If non-NULL and the first designator in @p
1578/// DIE is an array designator or GNU array-range designator, this
1579/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001580///
1581/// @param Index Index into @p IList where the designated initializer
1582/// @p DIE occurs.
1583///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001584/// @param StructuredList The initializer list expression that
1585/// describes all of the subobject initializers in the order they'll
1586/// actually be initialized.
1587///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001588/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001589bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001590InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001591 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001592 DesignatedInitExpr *DIE,
1593 unsigned DesigIdx,
1594 QualType &CurrentObjectType,
1595 RecordDecl::field_iterator *NextField,
1596 llvm::APSInt *NextElementIndex,
1597 unsigned &Index,
1598 InitListExpr *StructuredList,
1599 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001600 bool FinishSubobjectInit,
1601 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001602 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001603 // Check the actual initialization for the designated object type.
1604 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001605
1606 // Temporarily remove the designator expression from the
1607 // initializer list that the child calls see, so that we don't try
1608 // to re-process the designator.
1609 unsigned OldIndex = Index;
1610 IList->setInit(OldIndex, DIE->getInit());
1611
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001612 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001613 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001614
1615 // Restore the designated initializer expression in the syntactic
1616 // form of the initializer list.
1617 if (IList->getInit(OldIndex) != DIE->getInit())
1618 DIE->setInit(IList->getInit(OldIndex));
1619 IList->setInit(OldIndex, DIE);
1620
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001621 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001622 }
1623
Douglas Gregora5324162009-04-15 04:56:10 +00001624 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001625 bool IsFirstDesignator = (DesigIdx == 0);
1626 if (!VerifyOnly) {
1627 assert((IsFirstDesignator || StructuredList) &&
1628 "Need a non-designated initializer list to start from");
1629
1630 // Determine the structural initializer list that corresponds to the
1631 // current subobject.
1632 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1633 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1634 StructuredList, StructuredIndex,
1635 SourceRange(D->getStartLocation(),
1636 DIE->getSourceRange().getEnd()));
1637 assert(StructuredList && "Expected a structured initializer list");
1638 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001639
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001640 if (D->isFieldDesignator()) {
1641 // C99 6.7.8p7:
1642 //
1643 // If a designator has the form
1644 //
1645 // . identifier
1646 //
1647 // then the current object (defined below) shall have
1648 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001649 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001650 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001651 if (!RT) {
1652 SourceLocation Loc = D->getDotLoc();
1653 if (Loc.isInvalid())
1654 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001655 if (!VerifyOnly)
1656 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1657 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001658 ++Index;
1659 return true;
1660 }
1661
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001662 // Note: we perform a linear search of the fields here, despite
1663 // the fact that we have a faster lookup method, because we always
1664 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001665 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001666 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001667 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001668 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001669 Field = RT->getDecl()->field_begin(),
1670 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001671 for (; Field != FieldEnd; ++Field) {
1672 if (Field->isUnnamedBitfield())
1673 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001674
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001675 // If we find a field representing an anonymous field, look in the
1676 // IndirectFieldDecl that follow for the designated initializer.
1677 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1678 if (IndirectFieldDecl *IF =
1679 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001680 // In verify mode, don't modify the original.
1681 if (VerifyOnly)
1682 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001683 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1684 D = DIE->getDesignator(DesigIdx);
1685 break;
1686 }
1687 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001688 if (KnownField && KnownField == *Field)
1689 break;
1690 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001691 break;
1692
1693 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001694 }
1695
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001696 if (Field == FieldEnd) {
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001697 if (VerifyOnly) {
1698 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001699 return true; // No typo correction when just trying this out.
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001700 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001701
Douglas Gregord5846a12009-04-15 06:41:24 +00001702 // There was no normal field in the struct with the designated
1703 // name. Perform another lookup for this name, which may find
1704 // something that we can't designate (e.g., a member function),
1705 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001706 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001707 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001708 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001709 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001710 // Name lookup didn't find anything. Determine whether this
1711 // was a typo for another field name.
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001712 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001713 TypoCorrection Corrected = SemaRef.CorrectTypo(
1714 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001715 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001716 RT->getDecl());
1717 if (Corrected) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001718 std::string CorrectedStr(
1719 Corrected.getAsString(SemaRef.getLangOptions()));
1720 std::string CorrectedQuotedStr(
1721 Corrected.getQuoted(SemaRef.getLangOptions()));
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001722 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001723 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001724 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001725 << FieldName << CurrentObjectType << CorrectedQuotedStr
1726 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001727 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001728 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001729 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001730 } else {
1731 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1732 << FieldName << CurrentObjectType;
1733 ++Index;
1734 return true;
1735 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001736 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001737
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001738 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001739 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001740 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001741 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001742 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001743 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001744 ++Index;
1745 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001746 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001747
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001748 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001749 // The replacement field comes from typo correction; find it
1750 // in the list of fields.
1751 FieldIndex = 0;
1752 Field = RT->getDecl()->field_begin();
1753 for (; Field != FieldEnd; ++Field) {
1754 if (Field->isUnnamedBitfield())
1755 continue;
1756
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001757 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001758 Field->getIdentifier() == ReplacementField->getIdentifier())
1759 break;
1760
1761 ++FieldIndex;
1762 }
1763 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001764 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001765
1766 // All of the fields of a union are located at the same place in
1767 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001768 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001769 FieldIndex = 0;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001770 if (!VerifyOnly)
1771 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001772 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001773
Douglas Gregora82064c2011-06-29 21:51:31 +00001774 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001775 bool InvalidUse;
1776 if (VerifyOnly)
1777 InvalidUse = !SemaRef.CanUseDecl(*Field);
1778 else
1779 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1780 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001781 ++Index;
1782 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001783 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001784
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001785 if (!VerifyOnly) {
1786 // Update the designator with the field declaration.
1787 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001788
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001789 // Make sure that our non-designated initializer list has space
1790 // for a subobject corresponding to this field.
1791 if (FieldIndex >= StructuredList->getNumInits())
1792 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1793 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001794
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001795 // This designator names a flexible array member.
1796 if (Field->getType()->isIncompleteArrayType()) {
1797 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001798 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001799 // We can't designate an object within the flexible array
1800 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001801 if (!VerifyOnly) {
1802 DesignatedInitExpr::Designator *NextD
1803 = DIE->getDesignator(DesigIdx + 1);
1804 SemaRef.Diag(NextD->getStartLocation(),
1805 diag::err_designator_into_flexible_array_member)
1806 << SourceRange(NextD->getStartLocation(),
1807 DIE->getSourceRange().getEnd());
1808 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1809 << *Field;
1810 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001811 Invalid = true;
1812 }
1813
Chris Lattner001b29c2010-10-10 17:49:49 +00001814 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1815 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001816 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001817 if (!VerifyOnly) {
1818 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1819 diag::err_flexible_array_init_needs_braces)
1820 << DIE->getInit()->getSourceRange();
1821 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1822 << *Field;
1823 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001824 Invalid = true;
1825 }
1826
Eli Friedman3fa64df2011-08-23 22:24:57 +00001827 // Check GNU flexible array initializer.
1828 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1829 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001830 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001831
1832 if (Invalid) {
1833 ++Index;
1834 return true;
1835 }
1836
1837 // Initialize the array.
1838 bool prevHadError = hadError;
1839 unsigned newStructuredIndex = FieldIndex;
1840 unsigned OldIndex = Index;
1841 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001842
1843 InitializedEntity MemberEntity =
1844 InitializedEntity::InitializeMember(*Field, &Entity);
1845 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001846 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001847
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001848 IList->setInit(OldIndex, DIE);
1849 if (hadError && !prevHadError) {
1850 ++Field;
1851 ++FieldIndex;
1852 if (NextField)
1853 *NextField = Field;
1854 StructuredIndex = FieldIndex;
1855 return true;
1856 }
1857 } else {
1858 // Recurse to check later designated subobjects.
1859 QualType FieldType = (*Field)->getType();
1860 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001861
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001862 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001863 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001864 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1865 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001866 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001867 true, false))
1868 return true;
1869 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001870
1871 // Find the position of the next field to be initialized in this
1872 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001873 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001874 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001875
1876 // If this the first designator, our caller will continue checking
1877 // the rest of this struct/class/union subobject.
1878 if (IsFirstDesignator) {
1879 if (NextField)
1880 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001881 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001882 return false;
1883 }
1884
Douglas Gregor17bd0942009-01-28 23:36:17 +00001885 if (!FinishSubobjectInit)
1886 return false;
1887
Douglas Gregord5846a12009-04-15 06:41:24 +00001888 // We've already initialized something in the union; we're done.
1889 if (RT->getDecl()->isUnion())
1890 return hadError;
1891
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001892 // Check the remaining fields within this class/struct/union subobject.
1893 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001894
Anders Carlsson6cabf312010-01-23 23:23:01 +00001895 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001896 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001897 return hadError && !prevHadError;
1898 }
1899
1900 // C99 6.7.8p6:
1901 //
1902 // If a designator has the form
1903 //
1904 // [ constant-expression ]
1905 //
1906 // then the current object (defined below) shall have array
1907 // type and the expression shall be an integer constant
1908 // expression. If the array is of unknown size, any
1909 // nonnegative value is valid.
1910 //
1911 // Additionally, cope with the GNU extension that permits
1912 // designators of the form
1913 //
1914 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001915 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001916 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001917 if (!VerifyOnly)
1918 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1919 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001920 ++Index;
1921 return true;
1922 }
1923
1924 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001925 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1926 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001927 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00001928 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001929 DesignatedEndIndex = DesignatedStartIndex;
1930 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001931 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001932
Mike Stump11289f42009-09-09 15:08:12 +00001933 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001934 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001935 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001936 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001937 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001938
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001939 // Codegen can't handle evaluating array range designators that have side
1940 // effects, because we replicate the AST value for each initialized element.
1941 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1942 // elements with something that has a side effect, so codegen can emit an
1943 // "error unsupported" error instead of miscompiling the app.
1944 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001945 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001946 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001947 }
1948
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001949 if (isa<ConstantArrayType>(AT)) {
1950 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001951 DesignatedStartIndex
1952 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001953 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001954 DesignatedEndIndex
1955 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001956 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1957 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00001958 if (!VerifyOnly)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001959 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1960 diag::err_array_designator_too_large)
1961 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1962 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001963 ++Index;
1964 return true;
1965 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001966 } else {
1967 // Make sure the bit-widths and signedness match.
1968 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001969 DesignatedEndIndex
1970 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001971 else if (DesignatedStartIndex.getBitWidth() <
1972 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001973 DesignatedStartIndex
1974 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001975 DesignatedStartIndex.setIsUnsigned(true);
1976 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001977 }
Mike Stump11289f42009-09-09 15:08:12 +00001978
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001979 // Make sure that our non-designated initializer list has space
1980 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001981 if (!VerifyOnly &&
1982 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001983 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001984 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001985
Douglas Gregor17bd0942009-01-28 23:36:17 +00001986 // Repeatedly perform subobject initializations in the range
1987 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001988
Douglas Gregor17bd0942009-01-28 23:36:17 +00001989 // Move to the next designator
1990 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1991 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001992
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001993 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001994 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001995
Douglas Gregor17bd0942009-01-28 23:36:17 +00001996 while (DesignatedStartIndex <= DesignatedEndIndex) {
1997 // Recurse to check later designated subobjects.
1998 QualType ElementType = AT->getElementType();
1999 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002000
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002001 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002002 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2003 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002004 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002005 (DesignatedStartIndex == DesignatedEndIndex),
2006 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002007 return true;
2008
2009 // Move to the next index in the array that we'll be initializing.
2010 ++DesignatedStartIndex;
2011 ElementIndex = DesignatedStartIndex.getZExtValue();
2012 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002013
2014 // If this the first designator, our caller will continue checking
2015 // the rest of this array subobject.
2016 if (IsFirstDesignator) {
2017 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002018 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002019 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002020 return false;
2021 }
Mike Stump11289f42009-09-09 15:08:12 +00002022
Douglas Gregor17bd0942009-01-28 23:36:17 +00002023 if (!FinishSubobjectInit)
2024 return false;
2025
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002026 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002027 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002028 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002029 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002030 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002031 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002032}
2033
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002034// Get the structured initializer list for a subobject of type
2035// @p CurrentObjectType.
2036InitListExpr *
2037InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2038 QualType CurrentObjectType,
2039 InitListExpr *StructuredList,
2040 unsigned StructuredIndex,
2041 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002042 if (VerifyOnly)
2043 return 0; // No structured list in verification-only mode.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002044 Expr *ExistingInit = 0;
2045 if (!StructuredList)
2046 ExistingInit = SyntacticToSemantic[IList];
2047 else if (StructuredIndex < StructuredList->getNumInits())
2048 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002049
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002050 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2051 return Result;
2052
2053 if (ExistingInit) {
2054 // We are creating an initializer list that initializes the
2055 // subobjects of the current object, but there was already an
2056 // initialization that completely initialized the current
2057 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002058 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002059 // struct X { int a, b; };
2060 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002061 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002062 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2063 // designated initializer re-initializes the whole
2064 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002065 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002066 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002067 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00002068 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002069 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002070 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002071 << ExistingInit->getSourceRange();
2072 }
2073
Mike Stump11289f42009-09-09 15:08:12 +00002074 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002075 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2076 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00002077 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002078
Douglas Gregora8a089b2010-07-13 18:40:04 +00002079 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002080
Douglas Gregor6d00c992009-03-20 23:58:33 +00002081 // Pre-allocate storage for the structured initializer list.
2082 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002083 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002084 bool GotNumInits = false;
2085 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002086 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002087 GotNumInits = true;
2088 } else if (Index < IList->getNumInits()) {
2089 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002090 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002091 GotNumInits = true;
2092 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002093 }
2094
Mike Stump11289f42009-09-09 15:08:12 +00002095 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002096 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2097 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2098 NumElements = CAType->getSize().getZExtValue();
2099 // Simple heuristic so that we don't allocate a very large
2100 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002101 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002102 NumElements = 0;
2103 }
John McCall9dd450b2009-09-21 23:43:11 +00002104 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002105 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002106 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002107 RecordDecl *RDecl = RType->getDecl();
2108 if (RDecl->isUnion())
2109 NumElements = 1;
2110 else
Mike Stump11289f42009-09-09 15:08:12 +00002111 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002112 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002113 }
2114
Ted Kremenekac034612010-04-13 23:39:13 +00002115 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002116
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002117 // Link this new initializer list into the structured initializer
2118 // lists.
2119 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002120 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002121 else {
2122 Result->setSyntacticForm(IList);
2123 SyntacticToSemantic[IList] = Result;
2124 }
2125
2126 return Result;
2127}
2128
2129/// Update the initializer at index @p StructuredIndex within the
2130/// structured initializer list to the value @p expr.
2131void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2132 unsigned &StructuredIndex,
2133 Expr *expr) {
2134 // No structured initializer list to update
2135 if (!StructuredList)
2136 return;
2137
Ted Kremenekac034612010-04-13 23:39:13 +00002138 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2139 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002140 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00002141 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002142 diag::warn_initializer_overrides)
2143 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002144 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002145 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002146 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002147 << PrevInit->getSourceRange();
2148 }
Mike Stump11289f42009-09-09 15:08:12 +00002149
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002150 ++StructuredIndex;
2151}
2152
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002153/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002154/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002155/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002156/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002157/// failure. Returns the index expression, possibly with an implicit cast
2158/// added, on success. If everything went okay, Value will receive the
2159/// value of the constant expression.
2160static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002161CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002162 SourceLocation Loc = Index->getSourceRange().getBegin();
2163
2164 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002165 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2166 if (Result.isInvalid())
2167 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002168
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002169 if (Value.isSigned() && Value.isNegative())
2170 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002171 << Value.toString(10) << Index->getSourceRange();
2172
Douglas Gregor51650d32009-01-23 21:04:18 +00002173 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002174 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002175}
2176
John McCalldadc5752010-08-24 06:29:42 +00002177ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002178 SourceLocation Loc,
2179 bool GNUSyntax,
2180 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002181 typedef DesignatedInitExpr::Designator ASTDesignator;
2182
2183 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002184 SmallVector<ASTDesignator, 32> Designators;
2185 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002186
2187 // Build designators and check array designator expressions.
2188 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2189 const Designator &D = Desig.getDesignator(Idx);
2190 switch (D.getKind()) {
2191 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002192 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002193 D.getFieldLoc()));
2194 break;
2195
2196 case Designator::ArrayDesignator: {
2197 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2198 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002199 if (!Index->isTypeDependent() && !Index->isValueDependent())
2200 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2201 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002202 Invalid = true;
2203 else {
2204 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002205 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002206 D.getRBracketLoc()));
2207 InitExpressions.push_back(Index);
2208 }
2209 break;
2210 }
2211
2212 case Designator::ArrayRangeDesignator: {
2213 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2214 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2215 llvm::APSInt StartValue;
2216 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002217 bool StartDependent = StartIndex->isTypeDependent() ||
2218 StartIndex->isValueDependent();
2219 bool EndDependent = EndIndex->isTypeDependent() ||
2220 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002221 if (!StartDependent)
2222 StartIndex =
2223 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2224 if (!EndDependent)
2225 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2226
2227 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002228 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002229 else {
2230 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002231 if (StartDependent || EndDependent) {
2232 // Nothing to compute.
2233 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002234 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002235 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002236 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002237
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002238 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002239 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002240 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002241 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2242 Invalid = true;
2243 } else {
2244 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002245 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002246 D.getEllipsisLoc(),
2247 D.getRBracketLoc()));
2248 InitExpressions.push_back(StartIndex);
2249 InitExpressions.push_back(EndIndex);
2250 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002251 }
2252 break;
2253 }
2254 }
2255 }
2256
2257 if (Invalid || Init.isInvalid())
2258 return ExprError();
2259
2260 // Clear out the expressions within the designation.
2261 Desig.ClearExprs(*this);
2262
2263 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002264 = DesignatedInitExpr::Create(Context,
2265 Designators.data(), Designators.size(),
2266 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00002267 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002268
Richard Smithe4345902011-12-29 21:57:33 +00002269 if (!getLangOptions().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002270 Diag(DIE->getLocStart(), diag::ext_designated_init)
2271 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002272
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002273 return Owned(DIE);
2274}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002275
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002276//===----------------------------------------------------------------------===//
2277// Initialization entity
2278//===----------------------------------------------------------------------===//
2279
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002280InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002281 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002282 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002283{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002284 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2285 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002286 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002287 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002288 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002289 Type = VT->getElementType();
2290 } else {
2291 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2292 assert(CT && "Unexpected type");
2293 Kind = EK_ComplexElement;
2294 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002295 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002296}
2297
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002298InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002299 CXXBaseSpecifier *Base,
2300 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002301{
2302 InitializedEntity Result;
2303 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002304 Result.Base = reinterpret_cast<uintptr_t>(Base);
2305 if (IsInheritedVirtualBase)
2306 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002307
Douglas Gregor1b303932009-12-22 15:35:07 +00002308 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002309 return Result;
2310}
2311
Douglas Gregor85dabae2009-12-16 01:38:02 +00002312DeclarationName InitializedEntity::getName() const {
2313 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002314 case EK_Parameter: {
2315 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2316 return (D ? D->getDeclName() : DeclarationName());
2317 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002318
2319 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002320 case EK_Member:
2321 return VariableOrMember->getDeclName();
2322
2323 case EK_Result:
2324 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002325 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002326 case EK_Temporary:
2327 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002328 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002329 case EK_ArrayElement:
2330 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002331 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002332 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002333 return DeclarationName();
2334 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002335
David Blaikie8a40f702012-01-17 06:56:22 +00002336 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002337}
2338
Douglas Gregora4b592a2009-12-19 03:01:41 +00002339DeclaratorDecl *InitializedEntity::getDecl() const {
2340 switch (getKind()) {
2341 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002342 case EK_Member:
2343 return VariableOrMember;
2344
John McCall31168b02011-06-15 23:02:42 +00002345 case EK_Parameter:
2346 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2347
Douglas Gregora4b592a2009-12-19 03:01:41 +00002348 case EK_Result:
2349 case EK_Exception:
2350 case EK_New:
2351 case EK_Temporary:
2352 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002353 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002354 case EK_ArrayElement:
2355 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002356 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002357 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002358 return 0;
2359 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002360
David Blaikie8a40f702012-01-17 06:56:22 +00002361 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002362}
2363
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002364bool InitializedEntity::allowsNRVO() const {
2365 switch (getKind()) {
2366 case EK_Result:
2367 case EK_Exception:
2368 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002369
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002370 case EK_Variable:
2371 case EK_Parameter:
2372 case EK_Member:
2373 case EK_New:
2374 case EK_Temporary:
2375 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002376 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002377 case EK_ArrayElement:
2378 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002379 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002380 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002381 break;
2382 }
2383
2384 return false;
2385}
2386
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002387//===----------------------------------------------------------------------===//
2388// Initialization sequence
2389//===----------------------------------------------------------------------===//
2390
2391void InitializationSequence::Step::Destroy() {
2392 switch (Kind) {
2393 case SK_ResolveAddressOfOverloadedFunction:
2394 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002395 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002396 case SK_CastDerivedToBaseLValue:
2397 case SK_BindReference:
2398 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002399 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002400 case SK_UserConversion:
2401 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002402 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002403 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002404 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002405 case SK_ListConstructorCall:
Sebastian Redl29526f02011-11-27 16:50:07 +00002406 case SK_UnwrapInitList:
2407 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002408 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002409 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002410 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002411 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002412 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002413 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002414 case SK_PassByIndirectCopyRestore:
2415 case SK_PassByIndirectRestore:
2416 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002417 case SK_StdInitializerList:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002418 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002419
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002420 case SK_ConversionSequence:
2421 delete ICS;
2422 }
2423}
2424
Douglas Gregor838fcc32010-03-26 20:14:36 +00002425bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002426 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002427}
2428
2429bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002430 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002431 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002432
Douglas Gregor838fcc32010-03-26 20:14:36 +00002433 switch (getFailureKind()) {
2434 case FK_TooManyInitsForReference:
2435 case FK_ArrayNeedsInitList:
2436 case FK_ArrayNeedsInitListOrStringLiteral:
2437 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2438 case FK_NonConstLValueReferenceBindingToTemporary:
2439 case FK_NonConstLValueReferenceBindingToUnrelated:
2440 case FK_RValueReferenceBindingToLValue:
2441 case FK_ReferenceInitDropsQualifiers:
2442 case FK_ReferenceInitFailed:
2443 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002444 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002445 case FK_TooManyInitsForScalar:
2446 case FK_ReferenceBindingToInitList:
2447 case FK_InitListBadDestinationType:
2448 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002449 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002450 case FK_ArrayTypeMismatch:
2451 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002452 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002453 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002454 case FK_PlaceholderType:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002455 case FK_InitListElementCopyFailure:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002456 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002457
Douglas Gregor838fcc32010-03-26 20:14:36 +00002458 case FK_ReferenceInitOverloadFailed:
2459 case FK_UserConversionOverloadFailed:
2460 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002461 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002462 return FailedOverloadResult == OR_Ambiguous;
2463 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002464
David Blaikie8a40f702012-01-17 06:56:22 +00002465 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00002466}
2467
Douglas Gregorb33eed02010-04-16 22:09:46 +00002468bool InitializationSequence::isConstructorInitialization() const {
2469 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2470}
2471
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002472void
2473InitializationSequence
2474::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2475 DeclAccessPair Found,
2476 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002477 Step S;
2478 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2479 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002480 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002481 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002482 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002483 Steps.push_back(S);
2484}
2485
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002486void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002487 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002488 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002489 switch (VK) {
2490 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2491 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2492 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002493 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002494 S.Type = BaseType;
2495 Steps.push_back(S);
2496}
2497
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002498void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002499 bool BindingTemporary) {
2500 Step S;
2501 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2502 S.Type = T;
2503 Steps.push_back(S);
2504}
2505
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002506void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2507 Step S;
2508 S.Kind = SK_ExtraneousCopyToTemporary;
2509 S.Type = T;
2510 Steps.push_back(S);
2511}
2512
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002513void
2514InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2515 DeclAccessPair FoundDecl,
2516 QualType T,
2517 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002518 Step S;
2519 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002520 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002521 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002522 S.Function.Function = Function;
2523 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002524 Steps.push_back(S);
2525}
2526
2527void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002528 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002529 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002530 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002531 switch (VK) {
2532 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002533 S.Kind = SK_QualificationConversionRValue;
2534 break;
John McCall2536c6d2010-08-25 10:28:54 +00002535 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002536 S.Kind = SK_QualificationConversionXValue;
2537 break;
John McCall2536c6d2010-08-25 10:28:54 +00002538 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002539 S.Kind = SK_QualificationConversionLValue;
2540 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002541 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002542 S.Type = Ty;
2543 Steps.push_back(S);
2544}
2545
2546void InitializationSequence::AddConversionSequenceStep(
2547 const ImplicitConversionSequence &ICS,
2548 QualType T) {
2549 Step S;
2550 S.Kind = SK_ConversionSequence;
2551 S.Type = T;
2552 S.ICS = new ImplicitConversionSequence(ICS);
2553 Steps.push_back(S);
2554}
2555
Douglas Gregor51e77d52009-12-10 17:56:55 +00002556void InitializationSequence::AddListInitializationStep(QualType T) {
2557 Step S;
2558 S.Kind = SK_ListInitialization;
2559 S.Type = T;
2560 Steps.push_back(S);
2561}
2562
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002563void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002564InitializationSequence
2565::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2566 AccessSpecifier Access,
2567 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002568 bool HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002569 bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002570 Step S;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002571 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2572 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002573 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002574 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002575 S.Function.Function = Constructor;
2576 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002577 Steps.push_back(S);
2578}
2579
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002580void InitializationSequence::AddZeroInitializationStep(QualType T) {
2581 Step S;
2582 S.Kind = SK_ZeroInitialization;
2583 S.Type = T;
2584 Steps.push_back(S);
2585}
2586
Douglas Gregore1314a62009-12-18 05:02:21 +00002587void InitializationSequence::AddCAssignmentStep(QualType T) {
2588 Step S;
2589 S.Kind = SK_CAssignment;
2590 S.Type = T;
2591 Steps.push_back(S);
2592}
2593
Eli Friedman78275202009-12-19 08:11:05 +00002594void InitializationSequence::AddStringInitStep(QualType T) {
2595 Step S;
2596 S.Kind = SK_StringInit;
2597 S.Type = T;
2598 Steps.push_back(S);
2599}
2600
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002601void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2602 Step S;
2603 S.Kind = SK_ObjCObjectConversion;
2604 S.Type = T;
2605 Steps.push_back(S);
2606}
2607
Douglas Gregore2f943b2011-02-22 18:29:51 +00002608void InitializationSequence::AddArrayInitStep(QualType T) {
2609 Step S;
2610 S.Kind = SK_ArrayInit;
2611 S.Type = T;
2612 Steps.push_back(S);
2613}
2614
John McCall31168b02011-06-15 23:02:42 +00002615void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2616 bool shouldCopy) {
2617 Step s;
2618 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2619 : SK_PassByIndirectRestore);
2620 s.Type = type;
2621 Steps.push_back(s);
2622}
2623
2624void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2625 Step S;
2626 S.Kind = SK_ProduceObjCObject;
2627 S.Type = T;
2628 Steps.push_back(S);
2629}
2630
Sebastian Redlc1839b12012-01-17 22:49:42 +00002631void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2632 Step S;
2633 S.Kind = SK_StdInitializerList;
2634 S.Type = T;
2635 Steps.push_back(S);
2636}
2637
Sebastian Redl29526f02011-11-27 16:50:07 +00002638void InitializationSequence::RewrapReferenceInitList(QualType T,
2639 InitListExpr *Syntactic) {
2640 assert(Syntactic->getNumInits() == 1 &&
2641 "Can only rewrap trivial init lists.");
2642 Step S;
2643 S.Kind = SK_UnwrapInitList;
2644 S.Type = Syntactic->getInit(0)->getType();
2645 Steps.insert(Steps.begin(), S);
2646
2647 S.Kind = SK_RewrapInitList;
2648 S.Type = T;
2649 S.WrappingSyntacticList = Syntactic;
2650 Steps.push_back(S);
2651}
2652
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002653void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002654 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002655 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002656 this->Failure = Failure;
2657 this->FailedOverloadResult = Result;
2658}
2659
2660//===----------------------------------------------------------------------===//
2661// Attempt initialization
2662//===----------------------------------------------------------------------===//
2663
John McCall31168b02011-06-15 23:02:42 +00002664static void MaybeProduceObjCObject(Sema &S,
2665 InitializationSequence &Sequence,
2666 const InitializedEntity &Entity) {
2667 if (!S.getLangOptions().ObjCAutoRefCount) return;
2668
2669 /// When initializing a parameter, produce the value if it's marked
2670 /// __attribute__((ns_consumed)).
2671 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2672 if (!Entity.isParameterConsumed())
2673 return;
2674
2675 assert(Entity.getType()->isObjCRetainableType() &&
2676 "consuming an object of unretainable type?");
2677 Sequence.AddProduceObjCObjectStep(Entity.getType());
2678
2679 /// When initializing a return value, if the return type is a
2680 /// retainable type, then returns need to immediately retain the
2681 /// object. If an autorelease is required, it will be done at the
2682 /// last instant.
2683 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2684 if (!Entity.getType()->isObjCRetainableType())
2685 return;
2686
2687 Sequence.AddProduceObjCObjectStep(Entity.getType());
2688 }
2689}
2690
Sebastian Redled2e5322011-12-22 14:44:04 +00002691/// \brief When initializing from init list via constructor, deal with the
2692/// empty init list and std::initializer_list special cases.
2693///
2694/// \return True if this was a special case, false otherwise.
2695static bool TryListConstructionSpecialCases(Sema &S,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002696 InitListExpr *List,
Sebastian Redled2e5322011-12-22 14:44:04 +00002697 CXXRecordDecl *DestRecordDecl,
2698 QualType DestType,
2699 InitializationSequence &Sequence) {
Sebastian Redlc1839b12012-01-17 22:49:42 +00002700 // C++11 [dcl.init.list]p3:
Sebastian Redled2e5322011-12-22 14:44:04 +00002701 // List-initialization of an object of type T is defined as follows:
2702 // - If the initializer list has no elements and T is a class type with
2703 // a default constructor, the object is value-initialized.
Sebastian Redl88e4d492012-02-04 21:27:33 +00002704 if (List->getNumInits() == 0) {
Sebastian Redled2e5322011-12-22 14:44:04 +00002705 if (CXXConstructorDecl *DefaultConstructor =
2706 S.LookupDefaultConstructor(DestRecordDecl)) {
2707 if (DefaultConstructor->isDeleted() ||
2708 S.isFunctionConsideredUnavailable(DefaultConstructor)) {
2709 // Fake an overload resolution failure.
2710 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2711 DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
2712 DefaultConstructor->getAccess());
2713 if (FunctionTemplateDecl *ConstructorTmpl =
2714 dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
2715 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2716 /*ExplicitArgs*/ 0,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002717 0, 0, CandidateSet,
Sebastian Redled2e5322011-12-22 14:44:04 +00002718 /*SuppressUserConversions*/ false);
2719 else
2720 S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002721 0, 0, CandidateSet,
Sebastian Redled2e5322011-12-22 14:44:04 +00002722 /*SuppressUserConversions*/ false);
2723 Sequence.SetOverloadFailure(
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002724 InitializationSequence::FK_ListConstructorOverloadFailed,
2725 OR_Deleted);
Sebastian Redled2e5322011-12-22 14:44:04 +00002726 } else
2727 Sequence.AddConstructorInitializationStep(DefaultConstructor,
2728 DefaultConstructor->getAccess(),
2729 DestType,
2730 /*MultipleCandidates=*/false,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002731 /*FromInitList=*/true,
2732 /*AsInitList=*/false);
Sebastian Redled2e5322011-12-22 14:44:04 +00002733 return true;
2734 }
2735 }
2736
2737 // - Otherwise, if T is a specialization of std::initializer_list, [...]
Sebastian Redlc1839b12012-01-17 22:49:42 +00002738 QualType E;
2739 if (S.isStdInitializerList(DestType, &E)) {
2740 // Check that each individual element can be copy-constructed. But since we
2741 // have no place to store further information, we'll recalculate everything
2742 // later.
2743 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2744 S.Context.getConstantArrayType(E,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002745 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2746 List->getNumInits()),
Sebastian Redlc1839b12012-01-17 22:49:42 +00002747 ArrayType::Normal, 0));
2748 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2749 0, HiddenArray);
Sebastian Redl88e4d492012-02-04 21:27:33 +00002750 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
Sebastian Redlc1839b12012-01-17 22:49:42 +00002751 Element.setElementIndex(i);
Sebastian Redl88e4d492012-02-04 21:27:33 +00002752 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
Sebastian Redlc1839b12012-01-17 22:49:42 +00002753 Sequence.SetFailed(
2754 InitializationSequence::FK_InitListElementCopyFailure);
2755 return true;
2756 }
2757 }
2758 Sequence.AddStdInitializerListConstructionStep(DestType);
2759 return true;
2760 }
Sebastian Redled2e5322011-12-22 14:44:04 +00002761
2762 // Not a special case.
2763 return false;
2764}
2765
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002766static OverloadingResult
2767ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
2768 Expr **Args, unsigned NumArgs,
2769 OverloadCandidateSet &CandidateSet,
2770 DeclContext::lookup_iterator Con,
2771 DeclContext::lookup_iterator ConEnd,
2772 OverloadCandidateSet::iterator &Best,
2773 bool CopyInitializing, bool AllowExplicit,
2774 bool OnlyListConstructors) {
2775 CandidateSet.clear();
2776
2777 for (; Con != ConEnd; ++Con) {
2778 NamedDecl *D = *Con;
2779 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2780 bool SuppressUserConversions = false;
2781
2782 // Find the constructor (which may be a template).
2783 CXXConstructorDecl *Constructor = 0;
2784 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2785 if (ConstructorTmpl)
2786 Constructor = cast<CXXConstructorDecl>(
2787 ConstructorTmpl->getTemplatedDecl());
2788 else {
2789 Constructor = cast<CXXConstructorDecl>(D);
2790
2791 // If we're performing copy initialization using a copy constructor, we
2792 // suppress user-defined conversions on the arguments.
2793 // FIXME: Move constructors?
2794 if (CopyInitializing && Constructor->isCopyConstructor())
2795 SuppressUserConversions = true;
2796 }
2797
2798 if (!Constructor->isInvalidDecl() &&
2799 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002800 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002801 if (ConstructorTmpl)
2802 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2803 /*ExplicitArgs*/ 0,
2804 Args, NumArgs, CandidateSet,
2805 SuppressUserConversions);
2806 else
2807 S.AddOverloadCandidate(Constructor, FoundDecl,
2808 Args, NumArgs, CandidateSet,
2809 SuppressUserConversions);
2810 }
2811 }
2812
2813 // Perform overload resolution and return the result.
2814 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2815}
2816
Sebastian Redled2e5322011-12-22 14:44:04 +00002817/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2818/// enumerates the constructors of the initialized entity and performs overload
2819/// resolution to select the best.
Sebastian Redl88e4d492012-02-04 21:27:33 +00002820/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redled2e5322011-12-22 14:44:04 +00002821/// class type.
2822static void TryConstructorInitialization(Sema &S,
2823 const InitializedEntity &Entity,
2824 const InitializationKind &Kind,
2825 Expr **Args, unsigned NumArgs,
2826 QualType DestType,
2827 InitializationSequence &Sequence,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002828 bool InitListSyntax = false) {
2829 assert((!InitListSyntax || (NumArgs == 1 && isa<InitListExpr>(Args[0]))) &&
2830 "InitListSyntax must come with a single initializer list argument.");
2831
Sebastian Redled2e5322011-12-22 14:44:04 +00002832 // Check constructor arguments for self reference.
2833 if (DeclaratorDecl *DD = Entity.getDecl())
2834 // Parameters arguments are occassionially constructed with itself,
2835 // for instance, in recursive functions. Skip them.
2836 if (!isa<ParmVarDecl>(DD))
2837 for (unsigned i = 0; i < NumArgs; ++i)
2838 S.CheckSelfReference(DD, Args[i]);
2839
Sebastian Redled2e5322011-12-22 14:44:04 +00002840 // The type we're constructing needs to be complete.
2841 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2842 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002843 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00002844 }
2845
2846 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2847 assert(DestRecordType && "Constructor initialization requires record type");
2848 CXXRecordDecl *DestRecordDecl
2849 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2850
Sebastian Redl88e4d492012-02-04 21:27:33 +00002851 if (InitListSyntax &&
2852 TryListConstructionSpecialCases(S, cast<InitListExpr>(Args[0]),
2853 DestRecordDecl, DestType, Sequence))
Sebastian Redled2e5322011-12-22 14:44:04 +00002854 return;
2855
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002856 // Build the candidate set directly in the initialization sequence
2857 // structure, so that it will persist if we fail.
2858 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2859
2860 // Determine whether we are allowed to call explicit constructors or
2861 // explicit conversion operators.
2862 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2863 Kind.getKind() == InitializationKind::IK_Value ||
2864 Kind.getKind() == InitializationKind::IK_Default);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002865 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00002866
Sebastian Redled2e5322011-12-22 14:44:04 +00002867 // - Otherwise, if T is a class type, constructors are considered. The
2868 // applicable constructors are enumerated, and the best one is chosen
2869 // through overload resolution.
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002870 DeclContext::lookup_iterator ConStart, ConEnd;
2871 llvm::tie(ConStart, ConEnd) = S.LookupConstructors(DestRecordDecl);
Sebastian Redled2e5322011-12-22 14:44:04 +00002872
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002873 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00002874 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002875 bool AsInitializerList = false;
2876
2877 // C++11 [over.match.list]p1:
2878 // When objects of non-aggregate type T are list-initialized, overload
2879 // resolution selects the constructor in two phases:
2880 // - Initially, the candidate functions are the initializer-list
2881 // constructors of the class T and the argument list consists of the
2882 // initializer list as a single argument.
2883 if (InitListSyntax) {
2884 AsInitializerList = true;
2885 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2886 CandidateSet, ConStart, ConEnd, Best,
2887 CopyInitialization, AllowExplicit,
2888 /*OnlyListConstructor=*/true);
2889
2890 // Time to unwrap the init list.
2891 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
2892 Args = ILE->getInits();
2893 NumArgs = ILE->getNumInits();
2894 }
2895
2896 // C++11 [over.match.list]p1:
2897 // - If no viable initializer-list constructor is found, overload resolution
2898 // is performed again, where the candidate functions are all the
2899 // constructors of the class T nad the argument list consists of the
2900 // elements of the initializer list.
2901 if (Result == OR_No_Viable_Function) {
2902 AsInitializerList = false;
2903 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2904 CandidateSet, ConStart, ConEnd, Best,
2905 CopyInitialization, AllowExplicit,
2906 /*OnlyListConstructors=*/false);
2907 }
2908 if (Result) {
Sebastian Redl88e4d492012-02-04 21:27:33 +00002909 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002910 InitializationSequence::FK_ListConstructorOverloadFailed :
2911 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00002912 Result);
2913 return;
2914 }
2915
2916 // C++0x [dcl.init]p6:
2917 // If a program calls for the default initialization of an object
2918 // of a const-qualified type T, T shall be a class type with a
2919 // user-provided default constructor.
2920 if (Kind.getKind() == InitializationKind::IK_Default &&
2921 Entity.getType().isConstQualified() &&
2922 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2923 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2924 return;
2925 }
2926
2927 // Add the constructor initialization step. Any cv-qualification conversion is
2928 // subsumed by the initialization.
2929 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2930 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2931 Sequence.AddConstructorInitializationStep(CtorDecl,
2932 Best->FoundDecl.getAccess(),
2933 DestType, HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002934 InitListSyntax, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00002935}
2936
Sebastian Redl29526f02011-11-27 16:50:07 +00002937static bool
2938ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2939 Expr *Initializer,
2940 QualType &SourceType,
2941 QualType &UnqualifiedSourceType,
2942 QualType UnqualifiedTargetType,
2943 InitializationSequence &Sequence) {
2944 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
2945 S.Context.OverloadTy) {
2946 DeclAccessPair Found;
2947 bool HadMultipleCandidates = false;
2948 if (FunctionDecl *Fn
2949 = S.ResolveAddressOfOverloadedFunction(Initializer,
2950 UnqualifiedTargetType,
2951 false, Found,
2952 &HadMultipleCandidates)) {
2953 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
2954 HadMultipleCandidates);
2955 SourceType = Fn->getType();
2956 UnqualifiedSourceType = SourceType.getUnqualifiedType();
2957 } else if (!UnqualifiedTargetType->isRecordType()) {
2958 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2959 return true;
2960 }
2961 }
2962 return false;
2963}
2964
2965static void TryReferenceInitializationCore(Sema &S,
2966 const InitializedEntity &Entity,
2967 const InitializationKind &Kind,
2968 Expr *Initializer,
2969 QualType cv1T1, QualType T1,
2970 Qualifiers T1Quals,
2971 QualType cv2T2, QualType T2,
2972 Qualifiers T2Quals,
2973 InitializationSequence &Sequence);
2974
2975static void TryListInitialization(Sema &S,
2976 const InitializedEntity &Entity,
2977 const InitializationKind &Kind,
2978 InitListExpr *InitList,
2979 InitializationSequence &Sequence);
2980
2981/// \brief Attempt list initialization of a reference.
2982static void TryReferenceListInitialization(Sema &S,
2983 const InitializedEntity &Entity,
2984 const InitializationKind &Kind,
2985 InitListExpr *InitList,
2986 InitializationSequence &Sequence)
2987{
2988 // First, catch C++03 where this isn't possible.
2989 if (!S.getLangOptions().CPlusPlus0x) {
2990 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2991 return;
2992 }
2993
2994 QualType DestType = Entity.getType();
2995 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2996 Qualifiers T1Quals;
2997 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
2998
2999 // Reference initialization via an initializer list works thus:
3000 // If the initializer list consists of a single element that is
3001 // reference-related to the referenced type, bind directly to that element
3002 // (possibly creating temporaries).
3003 // Otherwise, initialize a temporary with the initializer list and
3004 // bind to that.
3005 if (InitList->getNumInits() == 1) {
3006 Expr *Initializer = InitList->getInit(0);
3007 QualType cv2T2 = Initializer->getType();
3008 Qualifiers T2Quals;
3009 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3010
3011 // If this fails, creating a temporary wouldn't work either.
3012 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3013 T1, Sequence))
3014 return;
3015
3016 SourceLocation DeclLoc = Initializer->getLocStart();
3017 bool dummy1, dummy2, dummy3;
3018 Sema::ReferenceCompareResult RefRelationship
3019 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3020 dummy2, dummy3);
3021 if (RefRelationship >= Sema::Ref_Related) {
3022 // Try to bind the reference here.
3023 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3024 T1Quals, cv2T2, T2, T2Quals, Sequence);
3025 if (Sequence)
3026 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3027 return;
3028 }
3029 }
3030
3031 // Not reference-related. Create a temporary and bind to that.
3032 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3033
3034 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3035 if (Sequence) {
3036 if (DestType->isRValueReferenceType() ||
3037 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3038 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3039 else
3040 Sequence.SetFailed(
3041 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3042 }
3043}
3044
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003045/// \brief Attempt list initialization (C++0x [dcl.init.list])
3046static void TryListInitialization(Sema &S,
3047 const InitializedEntity &Entity,
3048 const InitializationKind &Kind,
3049 InitListExpr *InitList,
3050 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003051 QualType DestType = Entity.getType();
3052
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003053 // C++ doesn't allow scalar initialization with more than one argument.
3054 // But C99 complex numbers are scalars and it makes sense there.
3055 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
3056 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3057 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3058 return;
3059 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003060 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003061 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003062 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003063 }
3064 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Sebastian Redl88e4d492012-02-04 21:27:33 +00003065 if (S.getLangOptions().CPlusPlus0x) {
3066 Expr *Arg = InitList;
3067 TryConstructorInitialization(S, Entity, Kind, &Arg, 1, DestType,
3068 Sequence, /*InitListSyntax=*/true);
3069 } else
Sebastian Redled2e5322011-12-22 14:44:04 +00003070 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003071 return;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003072 }
3073
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003074 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00003075 DestType, /*VerifyOnly=*/true,
3076 Kind.getKind() != InitializationKind::IK_Direct ||
3077 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003078 if (CheckInitList.HadError()) {
3079 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3080 return;
3081 }
3082
3083 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003084 Sequence.AddListInitializationStep(DestType);
3085}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003086
3087/// \brief Try a reference initialization that involves calling a conversion
3088/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003089static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3090 const InitializedEntity &Entity,
3091 const InitializationKind &Kind,
3092 Expr *Initializer,
3093 bool AllowRValues,
3094 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003095 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003096 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3097 QualType T1 = cv1T1.getUnqualifiedType();
3098 QualType cv2T2 = Initializer->getType();
3099 QualType T2 = cv2T2.getUnqualifiedType();
3100
3101 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003102 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003103 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003104 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003105 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003106 ObjCConversion,
3107 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003108 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003109 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003110 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003111 (void)ObjCLifetimeConversion;
3112
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003113 // Build the candidate set directly in the initialization sequence
3114 // structure, so that it will persist if we fail.
3115 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3116 CandidateSet.clear();
3117
3118 // Determine whether we are allowed to call explicit constructors or
3119 // explicit conversion operators.
3120 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003121
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003122 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003123 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3124 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003125 // The type we're converting to is a class type. Enumerate its constructors
3126 // to see if there is a suitable conversion.
3127 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003128
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003129 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003130 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003131 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003132 NamedDecl *D = *Con;
3133 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3134
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003135 // Find the constructor (which may be a template).
3136 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003137 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003138 if (ConstructorTmpl)
3139 Constructor = cast<CXXConstructorDecl>(
3140 ConstructorTmpl->getTemplatedDecl());
3141 else
John McCalla0296f72010-03-19 07:35:19 +00003142 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003143
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003144 if (!Constructor->isInvalidDecl() &&
3145 Constructor->isConvertingConstructor(AllowExplicit)) {
3146 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003147 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003148 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003149 &Initializer, 1, CandidateSet,
3150 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003151 else
John McCalla0296f72010-03-19 07:35:19 +00003152 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003153 &Initializer, 1, CandidateSet,
3154 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003155 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003156 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003157 }
John McCall3696dcb2010-08-17 07:23:57 +00003158 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3159 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003160
Douglas Gregor496e8b342010-05-07 19:42:26 +00003161 const RecordType *T2RecordType = 0;
3162 if ((T2RecordType = T2->getAs<RecordType>()) &&
3163 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003164 // The type we're converting from is a class type, enumerate its conversion
3165 // functions.
3166 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3167
John McCallad371252010-01-20 00:46:10 +00003168 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003169 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003170 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3171 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003172 NamedDecl *D = *I;
3173 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3174 if (isa<UsingShadowDecl>(D))
3175 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003176
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003177 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3178 CXXConversionDecl *Conv;
3179 if (ConvTemplate)
3180 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3181 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003182 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003183
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003184 // If the conversion function doesn't return a reference type,
3185 // it can't be considered for this conversion unless we're allowed to
3186 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003187 // FIXME: Do we need to make sure that we only consider conversion
3188 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003189 // break recursion.
3190 if ((AllowExplicit || !Conv->isExplicit()) &&
3191 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3192 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003193 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003194 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00003195 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003196 else
John McCalla0296f72010-03-19 07:35:19 +00003197 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00003198 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003199 }
3200 }
3201 }
John McCall3696dcb2010-08-17 07:23:57 +00003202 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3203 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003204
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003205 SourceLocation DeclLoc = Initializer->getLocStart();
3206
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003207 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003208 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003209 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003210 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003211 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003212
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003213 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003214
Chandler Carruth30141632011-02-25 19:41:05 +00003215 // This is the overload that will actually be used for the initialization, so
3216 // mark it as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00003217 S.MarkFunctionReferenced(DeclLoc, Function);
Chandler Carruth30141632011-02-25 19:41:05 +00003218
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003219 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003220 if (isa<CXXConversionDecl>(Function))
3221 T2 = Function->getResultType();
3222 else
3223 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003224
3225 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003226 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003227 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003228 T2.getNonLValueExprType(S.Context),
3229 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003230
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003231 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003232 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003233 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003234 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003235 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003236 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003237 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003238
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003239 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003240 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003241 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003242 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003243 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003244 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003245 NewDerivedToBase, NewObjCConversion,
3246 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003247 if (NewRefRelationship == Sema::Ref_Incompatible) {
3248 // If the type we've converted to is not reference-related to the
3249 // type we're looking for, then there is another conversion step
3250 // we need to perform to produce a temporary of the right type
3251 // that we'll be binding to.
3252 ImplicitConversionSequence ICS;
3253 ICS.setStandard();
3254 ICS.Standard = Best->FinalConversion;
3255 T2 = ICS.Standard.getToType(2);
3256 Sequence.AddConversionSequenceStep(ICS, T2);
3257 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003258 Sequence.AddDerivedToBaseCastStep(
3259 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003260 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003261 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003262 else if (NewObjCConversion)
3263 Sequence.AddObjCObjectConversionStep(
3264 S.Context.getQualifiedType(T1,
3265 T2.getNonReferenceType().getQualifiers()));
3266
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003267 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003268 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003269
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003270 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3271 return OR_Success;
3272}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003273
Richard Smithc620f552011-10-19 16:55:56 +00003274static void CheckCXX98CompatAccessibleCopy(Sema &S,
3275 const InitializedEntity &Entity,
3276 Expr *CurInitExpr);
3277
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003278/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3279static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003280 const InitializedEntity &Entity,
3281 const InitializationKind &Kind,
3282 Expr *Initializer,
3283 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003284 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003285 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003286 Qualifiers T1Quals;
3287 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003288 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003289 Qualifiers T2Quals;
3290 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003291
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003292 // If the initializer is the address of an overloaded function, try
3293 // to resolve the overloaded function. If all goes well, T2 is the
3294 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003295 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3296 T1, Sequence))
3297 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003298
Sebastian Redl29526f02011-11-27 16:50:07 +00003299 // Delegate everything else to a subfunction.
3300 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3301 T1Quals, cv2T2, T2, T2Quals, Sequence);
3302}
3303
3304/// \brief Reference initialization without resolving overloaded functions.
3305static void TryReferenceInitializationCore(Sema &S,
3306 const InitializedEntity &Entity,
3307 const InitializationKind &Kind,
3308 Expr *Initializer,
3309 QualType cv1T1, QualType T1,
3310 Qualifiers T1Quals,
3311 QualType cv2T2, QualType T2,
3312 Qualifiers T2Quals,
3313 InitializationSequence &Sequence) {
3314 QualType DestType = Entity.getType();
3315 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003316 // Compute some basic properties of the types and the initializer.
3317 bool isLValueRef = DestType->isLValueReferenceType();
3318 bool isRValueRef = !isLValueRef;
3319 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003320 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003321 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003322 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003323 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003324 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003325 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003326
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003327 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003328 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003329 // "cv2 T2" as follows:
3330 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003331 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003332 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00003333 // Note the analogous bullet points for rvlaue refs to functions. Because
3334 // there are no function rvalues in C++, rvalue refs to functions are treated
3335 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003336 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003337 bool T1Function = T1->isFunctionType();
3338 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003339 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003340 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003341 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003342 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003343 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003344 // reference-compatible with "cv2 T2," or
3345 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003346 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003347 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003348 // can occur. However, we do pay attention to whether it is a bit-field
3349 // to decide whether we're actually binding to a temporary created from
3350 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003351 if (DerivedToBase)
3352 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003353 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003354 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003355 else if (ObjCConversion)
3356 Sequence.AddObjCObjectConversionStep(
3357 S.Context.getQualifiedType(T1, T2Quals));
3358
Chandler Carruth04bdce62010-01-12 20:32:25 +00003359 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00003360 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003361 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003362 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003363 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003364 return;
3365 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003366
3367 // - has a class type (i.e., T2 is a class type), where T1 is not
3368 // reference-related to T2, and can be implicitly converted to an
3369 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3370 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003371 // applicable conversion functions (13.3.1.6) and choosing the best
3372 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003373 // If we have an rvalue ref to function type here, the rhs must be
3374 // an rvalue.
3375 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3376 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003377 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003378 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00003379 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003380 Sequence);
3381 if (ConvOvlResult == OR_Success)
3382 return;
John McCall0d1da222010-01-12 00:44:57 +00003383 if (ConvOvlResult != OR_No_Viable_Function) {
3384 Sequence.SetOverloadFailure(
3385 InitializationSequence::FK_ReferenceInitOverloadFailed,
3386 ConvOvlResult);
3387 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003388 }
3389 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003390
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003391 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003392 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003393 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003394 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003395 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3396 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3397 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003398 Sequence.SetOverloadFailure(
3399 InitializationSequence::FK_ReferenceInitOverloadFailed,
3400 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003401 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003402 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003403 ? (RefRelationship == Sema::Ref_Related
3404 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3405 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3406 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003407
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003408 return;
3409 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003410
Douglas Gregor92e460e2011-01-20 16:44:54 +00003411 // - If the initializer expression
3412 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3413 // "cv1 T1" is reference-compatible with "cv2 T2"
3414 // Note: functions are handled below.
3415 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003416 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003417 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003418 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003419 (InitCategory.isXValue() ||
3420 (InitCategory.isPRValue() && T2->isRecordType()) ||
3421 (InitCategory.isPRValue() && T2->isArrayType()))) {
3422 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3423 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003424 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3425 // compiler the freedom to perform a copy here or bind to the
3426 // object, while C++0x requires that we bind directly to the
3427 // object. Hence, we always bind to the object without making an
3428 // extra copy. However, in C++03 requires that we check for the
3429 // presence of a suitable copy constructor:
3430 //
3431 // The constructor that would be used to make the copy shall
3432 // be callable whether or not the copy is actually done.
Francois Pichet0706d202011-09-17 17:15:52 +00003433 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003434 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smithc620f552011-10-19 16:55:56 +00003435 else if (S.getLangOptions().CPlusPlus0x)
3436 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003437 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003438
Douglas Gregor92e460e2011-01-20 16:44:54 +00003439 if (DerivedToBase)
3440 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3441 ValueKind);
3442 else if (ObjCConversion)
3443 Sequence.AddObjCObjectConversionStep(
3444 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003445
Douglas Gregor92e460e2011-01-20 16:44:54 +00003446 if (T1Quals != T2Quals)
3447 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003448 Sequence.AddReferenceBindingStep(cv1T1,
Peter Collingbournefcc764d2011-11-13 00:51:30 +00003449 /*bindingTemporary=*/InitCategory.isPRValue());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003450 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003451 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003452
3453 // - has a class type (i.e., T2 is a class type), where T1 is not
3454 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003455 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3456 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00003457 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003458 if (RefRelationship == Sema::Ref_Incompatible) {
3459 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3460 Kind, Initializer,
3461 /*AllowRValues=*/true,
3462 Sequence);
3463 if (ConvOvlResult)
3464 Sequence.SetOverloadFailure(
3465 InitializationSequence::FK_ReferenceInitOverloadFailed,
3466 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003467
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003468 return;
3469 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003470
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003471 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3472 return;
3473 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003474
3475 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003476 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003477 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003478 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003479
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003480 // Determine whether we are allowed to call explicit constructors or
3481 // explicit conversion operators.
3482 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00003483
3484 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3485
John McCall31168b02011-06-15 23:02:42 +00003486 ImplicitConversionSequence ICS
3487 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00003488 /*SuppressUserConversions*/ false,
3489 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00003490 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003491 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3492 /*AllowObjCWritebackConversion=*/false);
3493
3494 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003495 // FIXME: Use the conversion function set stored in ICS to turn
3496 // this into an overloading ambiguity diagnostic. However, we need
3497 // to keep that set as an OverloadCandidateSet rather than as some
3498 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003499 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3500 Sequence.SetOverloadFailure(
3501 InitializationSequence::FK_ReferenceInitOverloadFailed,
3502 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003503 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3504 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003505 else
3506 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003507 return;
John McCall31168b02011-06-15 23:02:42 +00003508 } else {
3509 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003510 }
3511
3512 // [...] If T1 is reference-related to T2, cv1 must be the
3513 // same cv-qualification as, or greater cv-qualification
3514 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003515 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3516 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003517 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003518 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003519 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3520 return;
3521 }
3522
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003523 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003524 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003525 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003526 InitCategory.isLValue()) {
3527 Sequence.SetFailed(
3528 InitializationSequence::FK_RValueReferenceBindingToLValue);
3529 return;
3530 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003531
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003532 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3533 return;
3534}
3535
3536/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003537/// (C++ [dcl.init.string], C99 6.7.8).
3538static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003539 const InitializedEntity &Entity,
3540 const InitializationKind &Kind,
3541 Expr *Initializer,
3542 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003543 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003544}
3545
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003546/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003547static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003548 const InitializedEntity &Entity,
3549 const InitializationKind &Kind,
3550 InitializationSequence &Sequence) {
3551 // C++ [dcl.init]p5:
3552 //
3553 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003554 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003555
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003556 // -- if T is an array type, then each element is value-initialized;
3557 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3558 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003559
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003560 if (const RecordType *RT = T->getAs<RecordType>()) {
3561 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3562 // -- if T is a class type (clause 9) with a user-declared
3563 // constructor (12.1), then the default constructor for T is
3564 // called (and the initialization is ill-formed if T has no
3565 // accessible default constructor);
3566 //
3567 // FIXME: we really want to refer to a single subobject of the array,
3568 // but Entity doesn't have a way to capture that (yet).
3569 if (ClassDecl->hasUserDeclaredConstructor())
3570 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003571
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003572 // -- if T is a (possibly cv-qualified) non-union class type
3573 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003574 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003575 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003576 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003577 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003578 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003579 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003580 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003581 }
3582 }
3583
Douglas Gregor1b303932009-12-22 15:35:07 +00003584 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003585}
3586
Douglas Gregor85dabae2009-12-16 01:38:02 +00003587/// \brief Attempt default initialization (C++ [dcl.init]p6).
3588static void TryDefaultInitialization(Sema &S,
3589 const InitializedEntity &Entity,
3590 const InitializationKind &Kind,
3591 InitializationSequence &Sequence) {
3592 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003593
Douglas Gregor85dabae2009-12-16 01:38:02 +00003594 // C++ [dcl.init]p6:
3595 // To default-initialize an object of type T means:
3596 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003597 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3598
Douglas Gregor85dabae2009-12-16 01:38:02 +00003599 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3600 // constructor for T is called (and the initialization is ill-formed if
3601 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003602 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003603 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3604 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003605 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003606
Douglas Gregor85dabae2009-12-16 01:38:02 +00003607 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003608
Douglas Gregor85dabae2009-12-16 01:38:02 +00003609 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003610 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003611 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003612 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003613 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003614 return;
3615 }
3616
3617 // If the destination type has a lifetime property, zero-initialize it.
3618 if (DestType.getQualifiers().hasObjCLifetime()) {
3619 Sequence.AddZeroInitializationStep(Entity.getType());
3620 return;
3621 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003622}
3623
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003624/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3625/// which enumerates all conversion functions and performs overload resolution
3626/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003627static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003628 const InitializedEntity &Entity,
3629 const InitializationKind &Kind,
3630 Expr *Initializer,
3631 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003632 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003633 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3634 QualType SourceType = Initializer->getType();
3635 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3636 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003637
Douglas Gregor540c3b02009-12-14 17:27:33 +00003638 // Build the candidate set directly in the initialization sequence
3639 // structure, so that it will persist if we fail.
3640 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3641 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003642
Douglas Gregor540c3b02009-12-14 17:27:33 +00003643 // Determine whether we are allowed to call explicit constructors or
3644 // explicit conversion operators.
3645 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003646
Douglas Gregor540c3b02009-12-14 17:27:33 +00003647 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3648 // The type we're converting to is a class type. Enumerate its constructors
3649 // to see if there is a suitable conversion.
3650 CXXRecordDecl *DestRecordDecl
3651 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003652
Douglas Gregord9848152010-04-26 14:36:57 +00003653 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003654 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003655 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003656 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003657 Con != ConEnd; ++Con) {
3658 NamedDecl *D = *Con;
3659 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003660
Douglas Gregord9848152010-04-26 14:36:57 +00003661 // Find the constructor (which may be a template).
3662 CXXConstructorDecl *Constructor = 0;
3663 FunctionTemplateDecl *ConstructorTmpl
3664 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003665 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003666 Constructor = cast<CXXConstructorDecl>(
3667 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003668 else
Douglas Gregord9848152010-04-26 14:36:57 +00003669 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003670
Douglas Gregord9848152010-04-26 14:36:57 +00003671 if (!Constructor->isInvalidDecl() &&
3672 Constructor->isConvertingConstructor(AllowExplicit)) {
3673 if (ConstructorTmpl)
3674 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3675 /*ExplicitArgs*/ 0,
3676 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003677 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003678 else
3679 S.AddOverloadCandidate(Constructor, FoundDecl,
3680 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003681 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003682 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003683 }
Douglas Gregord9848152010-04-26 14:36:57 +00003684 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003685 }
Eli Friedman78275202009-12-19 08:11:05 +00003686
3687 SourceLocation DeclLoc = Initializer->getLocStart();
3688
Douglas Gregor540c3b02009-12-14 17:27:33 +00003689 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3690 // The type we're converting from is a class type, enumerate its conversion
3691 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003692
Eli Friedman4afe9a32009-12-20 22:12:03 +00003693 // We can only enumerate the conversion functions for a complete type; if
3694 // the type isn't complete, simply skip this step.
3695 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3696 CXXRecordDecl *SourceRecordDecl
3697 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003698
John McCallad371252010-01-20 00:46:10 +00003699 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003700 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003701 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003702 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003703 I != E; ++I) {
3704 NamedDecl *D = *I;
3705 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3706 if (isa<UsingShadowDecl>(D))
3707 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003708
Eli Friedman4afe9a32009-12-20 22:12:03 +00003709 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3710 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003711 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003712 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003713 else
John McCallda4458e2010-03-31 01:36:47 +00003714 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003715
Eli Friedman4afe9a32009-12-20 22:12:03 +00003716 if (AllowExplicit || !Conv->isExplicit()) {
3717 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003718 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003719 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003720 CandidateSet);
3721 else
John McCalla0296f72010-03-19 07:35:19 +00003722 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003723 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003724 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003725 }
3726 }
3727 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003728
3729 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003730 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003731 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003732 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003733 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003734 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003735 Result);
3736 return;
3737 }
John McCall0d1da222010-01-12 00:44:57 +00003738
Douglas Gregor540c3b02009-12-14 17:27:33 +00003739 FunctionDecl *Function = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00003740 S.MarkFunctionReferenced(DeclLoc, Function);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003741 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003742
Douglas Gregor540c3b02009-12-14 17:27:33 +00003743 if (isa<CXXConstructorDecl>(Function)) {
3744 // Add the user-defined conversion step. Any cv-qualification conversion is
3745 // subsumed by the initialization.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003746 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3747 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003748 return;
3749 }
3750
3751 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003752 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003753 if (ConvType->getAs<RecordType>()) {
3754 // If we're converting to a class type, there may be an copy if
3755 // the resulting temporary object (possible to create an object of
3756 // a base class type). That copy is not a separate conversion, so
3757 // we just make a note of the actual destination type (possibly a
3758 // base class of the type returned by the conversion function) and
3759 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003760 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3761 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003762 return;
3763 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003764
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003765 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3766 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003767
Douglas Gregor5ab11652010-04-17 22:01:05 +00003768 // If the conversion following the call to the conversion function
3769 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003770 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3771 Best->FinalConversion.Third) {
3772 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003773 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003774 ICS.Standard = Best->FinalConversion;
3775 Sequence.AddConversionSequenceStep(ICS, DestType);
3776 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003777}
3778
John McCall31168b02011-06-15 23:02:42 +00003779/// The non-zero enum values here are indexes into diagnostic alternatives.
3780enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3781
3782/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003783static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3784 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003785 // Skip parens.
3786 e = e->IgnoreParens();
3787
3788 // Skip address-of nodes.
3789 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3790 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003791 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003792
3793 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003794 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3795 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003796 case CK_Dependent:
3797 case CK_BitCast:
3798 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003799 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003800 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003801
3802 case CK_ArrayToPointerDecay:
3803 return IIK_nonscalar;
3804
3805 case CK_NullToPointer:
3806 return IIK_okay;
3807
3808 default:
3809 break;
3810 }
3811
3812 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003813 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3814 if (!isAddressOf) return IIK_nonlocal;
3815
3816 VarDecl *var;
3817 if (isa<DeclRefExpr>(e)) {
3818 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3819 if (!var) return IIK_nonlocal;
3820 } else {
3821 var = cast<BlockDeclRefExpr>(e)->getDecl();
3822 }
3823
3824 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003825
3826 // If we have a conditional operator, check both sides.
3827 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003828 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003829 return iik;
3830
John McCall63f84442011-06-27 23:59:58 +00003831 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003832
3833 // These are never scalar.
3834 } else if (isa<ArraySubscriptExpr>(e)) {
3835 return IIK_nonscalar;
3836
3837 // Otherwise, it needs to be a null pointer constant.
3838 } else {
3839 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3840 ? IIK_okay : IIK_nonlocal);
3841 }
3842
3843 return IIK_nonlocal;
3844}
3845
3846/// Check whether the given expression is a valid operand for an
3847/// indirect copy/restore.
3848static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3849 assert(src->isRValue());
3850
John McCall63f84442011-06-27 23:59:58 +00003851 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003852 if (iik == IIK_okay) return;
3853
3854 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3855 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3856 << src->getSourceRange();
3857}
3858
Douglas Gregore2f943b2011-02-22 18:29:51 +00003859/// \brief Determine whether we have compatible array types for the
3860/// purposes of GNU by-copy array initialization.
3861static bool hasCompatibleArrayTypes(ASTContext &Context,
3862 const ArrayType *Dest,
3863 const ArrayType *Source) {
3864 // If the source and destination array types are equivalent, we're
3865 // done.
3866 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3867 return true;
3868
3869 // Make sure that the element types are the same.
3870 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3871 return false;
3872
3873 // The only mismatch we allow is when the destination is an
3874 // incomplete array type and the source is a constant array type.
3875 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3876}
3877
John McCall31168b02011-06-15 23:02:42 +00003878static bool tryObjCWritebackConversion(Sema &S,
3879 InitializationSequence &Sequence,
3880 const InitializedEntity &Entity,
3881 Expr *Initializer) {
3882 bool ArrayDecay = false;
3883 QualType ArgType = Initializer->getType();
3884 QualType ArgPointee;
3885 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3886 ArrayDecay = true;
3887 ArgPointee = ArgArrayType->getElementType();
3888 ArgType = S.Context.getPointerType(ArgPointee);
3889 }
3890
3891 // Handle write-back conversion.
3892 QualType ConvertedArgType;
3893 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3894 ConvertedArgType))
3895 return false;
3896
3897 // We should copy unless we're passing to an argument explicitly
3898 // marked 'out'.
3899 bool ShouldCopy = true;
3900 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3901 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3902
3903 // Do we need an lvalue conversion?
3904 if (ArrayDecay || Initializer->isGLValue()) {
3905 ImplicitConversionSequence ICS;
3906 ICS.setStandard();
3907 ICS.Standard.setAsIdentityConversion();
3908
3909 QualType ResultType;
3910 if (ArrayDecay) {
3911 ICS.Standard.First = ICK_Array_To_Pointer;
3912 ResultType = S.Context.getPointerType(ArgPointee);
3913 } else {
3914 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3915 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3916 }
3917
3918 Sequence.AddConversionSequenceStep(ICS, ResultType);
3919 }
3920
3921 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3922 return true;
3923}
3924
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003925InitializationSequence::InitializationSequence(Sema &S,
3926 const InitializedEntity &Entity,
3927 const InitializationKind &Kind,
3928 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003929 unsigned NumArgs)
3930 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003931 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003932
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003933 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003934 // The semantics of initializers are as follows. The destination type is
3935 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003936 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003937 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003938 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003939 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003940
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003941 if (DestType->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003942 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3943 SequenceKind = DependentSequence;
3944 return;
3945 }
3946
Sebastian Redld201edf2011-06-05 13:59:11 +00003947 // Almost everything is a normal sequence.
3948 setSequenceKind(NormalSequence);
3949
John McCalled75c092010-12-07 22:54:16 +00003950 for (unsigned I = 0; I != NumArgs; ++I)
John McCalld5c98ae2011-11-15 01:35:18 +00003951 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +00003952 // FIXME: should we be doing this here?
John McCalld5c98ae2011-11-15 01:35:18 +00003953 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
3954 if (result.isInvalid()) {
3955 SetFailed(FK_PlaceholderType);
3956 return;
John McCall4124c492011-10-17 18:40:02 +00003957 }
John McCalld5c98ae2011-11-15 01:35:18 +00003958 Args[I] = result.take();
John Wiegley01296292011-04-08 18:41:53 +00003959 }
John McCalled75c092010-12-07 22:54:16 +00003960
John McCall4124c492011-10-17 18:40:02 +00003961
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003962 QualType SourceType;
3963 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003964 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003965 Initializer = Args[0];
3966 if (!isa<InitListExpr>(Initializer))
3967 SourceType = Initializer->getType();
3968 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003969
3970 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003971 // list-initialized (8.5.4).
3972 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003973 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003974 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003975 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003976
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003977 // - If the destination type is a reference type, see 8.5.3.
3978 if (DestType->isReferenceType()) {
3979 // C++0x [dcl.init.ref]p1:
3980 // A variable declared to be a T& or T&&, that is, "reference to type T"
3981 // (8.3.2), shall be initialized by an object, or function, of type T or
3982 // by an object that can be converted into a T.
3983 // (Therefore, multiple arguments are not permitted.)
3984 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003985 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003986 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003987 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003988 return;
3989 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003990
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003991 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003992 if (Kind.getKind() == InitializationKind::IK_Value ||
3993 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003994 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003995 return;
3996 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003997
Douglas Gregor85dabae2009-12-16 01:38:02 +00003998 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003999 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004000 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004001 return;
4002 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004003
John McCall66884dd2011-02-21 07:22:22 +00004004 // - If the destination type is an array of characters, an array of
4005 // char16_t, an array of char32_t, or an array of wchar_t, and the
4006 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004007 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004008 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004009 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004010 if (Initializer && isa<VariableArrayType>(DestAT)) {
4011 SetFailed(FK_VariableLengthArrayHasInitializer);
4012 return;
4013 }
4014
Douglas Gregore2f943b2011-02-22 18:29:51 +00004015 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004016 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00004017 return;
4018 }
4019
Douglas Gregore2f943b2011-02-22 18:29:51 +00004020 // Note: as an GNU C extension, we allow initialization of an
4021 // array from a compound literal that creates an array of the same
4022 // type, so long as the initializer has no side effects.
4023 if (!S.getLangOptions().CPlusPlus && Initializer &&
4024 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4025 Initializer->getType()->isArrayType()) {
4026 const ArrayType *SourceAT
4027 = Context.getAsArrayType(Initializer->getType());
4028 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004029 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004030 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004031 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004032 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004033 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004034 }
4035 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004036 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004037 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004038 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004039
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004040 return;
4041 }
Eli Friedman78275202009-12-19 08:11:05 +00004042
John McCall31168b02011-06-15 23:02:42 +00004043 // Determine whether we should consider writeback conversions for
4044 // Objective-C ARC.
4045 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
4046 Entity.getKind() == InitializedEntity::EK_Parameter;
4047
4048 // We're at the end of the line for C: it's either a write-back conversion
4049 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00004050 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004051 // If allowed, check whether this is an Objective-C writeback conversion.
4052 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004053 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004054 return;
4055 }
4056
4057 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004058 AddCAssignmentStep(DestType);
4059 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004060 return;
4061 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004062
John McCall31168b02011-06-15 23:02:42 +00004063 assert(S.getLangOptions().CPlusPlus);
4064
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004065 // - If the destination type is a (possibly cv-qualified) class type:
4066 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004067 // - If the initialization is direct-initialization, or if it is
4068 // copy-initialization where the cv-unqualified version of the
4069 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004070 // class of the destination, constructors are considered. [...]
4071 if (Kind.getKind() == InitializationKind::IK_Direct ||
4072 (Kind.getKind() == InitializationKind::IK_Copy &&
4073 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4074 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004075 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004076 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004077 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004078 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004079 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004080 // used) to a derived class thereof are enumerated as described in
4081 // 13.3.1.4, and the best one is chosen through overload resolution
4082 // (13.3).
4083 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004084 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004085 return;
4086 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004087
Douglas Gregor85dabae2009-12-16 01:38:02 +00004088 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004089 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004090 return;
4091 }
4092 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004093
4094 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004095 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004096 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004097 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4098 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004099 return;
4100 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004101
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004102 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004103 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004104 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004105 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004106 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00004107
4108 ImplicitConversionSequence ICS
4109 = S.TryImplicitConversion(Initializer, Entity.getType(),
4110 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004111 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004112 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004113 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4114 allowObjCWritebackConversion);
4115
4116 if (ICS.isStandard() &&
4117 ICS.Standard.Second == ICK_Writeback_Conversion) {
4118 // Objective-C ARC writeback conversion.
4119
4120 // We should copy unless we're passing to an argument explicitly
4121 // marked 'out'.
4122 bool ShouldCopy = true;
4123 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4124 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4125
4126 // If there was an lvalue adjustment, add it as a separate conversion.
4127 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4128 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4129 ImplicitConversionSequence LvalueICS;
4130 LvalueICS.setStandard();
4131 LvalueICS.Standard.setAsIdentityConversion();
4132 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4133 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004134 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004135 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004136
4137 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004138 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004139 DeclAccessPair dap;
4140 if (Initializer->getType() == Context.OverloadTy &&
4141 !S.ResolveAddressOfOverloadedFunction(Initializer
4142 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004143 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004144 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004145 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004146 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004147 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00004148
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004149 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004150 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004151}
4152
4153InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004154 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004155 StepEnd = Steps.end();
4156 Step != StepEnd; ++Step)
4157 Step->Destroy();
4158}
4159
4160//===----------------------------------------------------------------------===//
4161// Perform initialization
4162//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004163static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00004164getAssignmentAction(const InitializedEntity &Entity) {
4165 switch(Entity.getKind()) {
4166 case InitializedEntity::EK_Variable:
4167 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004168 case InitializedEntity::EK_Exception:
4169 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004170 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004171 return Sema::AA_Initializing;
4172
4173 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004174 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004175 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4176 return Sema::AA_Sending;
4177
Douglas Gregore1314a62009-12-18 05:02:21 +00004178 return Sema::AA_Passing;
4179
4180 case InitializedEntity::EK_Result:
4181 return Sema::AA_Returning;
4182
Douglas Gregore1314a62009-12-18 05:02:21 +00004183 case InitializedEntity::EK_Temporary:
4184 // FIXME: Can we tell apart casting vs. converting?
4185 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004186
Douglas Gregore1314a62009-12-18 05:02:21 +00004187 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004188 case InitializedEntity::EK_ArrayElement:
4189 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004190 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004191 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004192 return Sema::AA_Initializing;
4193 }
4194
David Blaikie8a40f702012-01-17 06:56:22 +00004195 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004196}
4197
Douglas Gregor95562572010-04-24 23:45:46 +00004198/// \brief Whether we should binding a created object as a temporary when
4199/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004200static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004201 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004202 case InitializedEntity::EK_ArrayElement:
4203 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004204 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004205 case InitializedEntity::EK_New:
4206 case InitializedEntity::EK_Variable:
4207 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004208 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004209 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004210 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004211 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004212 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004213 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004214
Douglas Gregore1314a62009-12-18 05:02:21 +00004215 case InitializedEntity::EK_Parameter:
4216 case InitializedEntity::EK_Temporary:
4217 return true;
4218 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004219
Douglas Gregore1314a62009-12-18 05:02:21 +00004220 llvm_unreachable("missed an InitializedEntity kind?");
4221}
4222
Douglas Gregor95562572010-04-24 23:45:46 +00004223/// \brief Whether the given entity, when initialized with an object
4224/// created for that initialization, requires destruction.
4225static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4226 switch (Entity.getKind()) {
4227 case InitializedEntity::EK_Member:
4228 case InitializedEntity::EK_Result:
4229 case InitializedEntity::EK_New:
4230 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004231 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004232 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004233 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004234 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00004235 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004236
Douglas Gregor95562572010-04-24 23:45:46 +00004237 case InitializedEntity::EK_Variable:
4238 case InitializedEntity::EK_Parameter:
4239 case InitializedEntity::EK_Temporary:
4240 case InitializedEntity::EK_ArrayElement:
4241 case InitializedEntity::EK_Exception:
4242 return true;
4243 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004244
4245 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004246}
4247
Richard Smithc620f552011-10-19 16:55:56 +00004248/// \brief Look for copy and move constructors and constructor templates, for
4249/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4250static void LookupCopyAndMoveConstructors(Sema &S,
4251 OverloadCandidateSet &CandidateSet,
4252 CXXRecordDecl *Class,
4253 Expr *CurInitExpr) {
4254 DeclContext::lookup_iterator Con, ConEnd;
4255 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4256 Con != ConEnd; ++Con) {
4257 CXXConstructorDecl *Constructor = 0;
4258
4259 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4260 // Handle copy/moveconstructors, only.
4261 if (!Constructor || Constructor->isInvalidDecl() ||
4262 !Constructor->isCopyOrMoveConstructor() ||
4263 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4264 continue;
4265
4266 DeclAccessPair FoundDecl
4267 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4268 S.AddOverloadCandidate(Constructor, FoundDecl,
4269 &CurInitExpr, 1, CandidateSet);
4270 continue;
4271 }
4272
4273 // Handle constructor templates.
4274 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4275 if (ConstructorTmpl->isInvalidDecl())
4276 continue;
4277
4278 Constructor = cast<CXXConstructorDecl>(
4279 ConstructorTmpl->getTemplatedDecl());
4280 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4281 continue;
4282
4283 // FIXME: Do we need to limit this to copy-constructor-like
4284 // candidates?
4285 DeclAccessPair FoundDecl
4286 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4287 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4288 &CurInitExpr, 1, CandidateSet, true);
4289 }
4290}
4291
4292/// \brief Get the location at which initialization diagnostics should appear.
4293static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4294 Expr *Initializer) {
4295 switch (Entity.getKind()) {
4296 case InitializedEntity::EK_Result:
4297 return Entity.getReturnLoc();
4298
4299 case InitializedEntity::EK_Exception:
4300 return Entity.getThrowLoc();
4301
4302 case InitializedEntity::EK_Variable:
4303 return Entity.getDecl()->getLocation();
4304
4305 case InitializedEntity::EK_ArrayElement:
4306 case InitializedEntity::EK_Member:
4307 case InitializedEntity::EK_Parameter:
4308 case InitializedEntity::EK_Temporary:
4309 case InitializedEntity::EK_New:
4310 case InitializedEntity::EK_Base:
4311 case InitializedEntity::EK_Delegating:
4312 case InitializedEntity::EK_VectorElement:
4313 case InitializedEntity::EK_ComplexElement:
4314 case InitializedEntity::EK_BlockElement:
4315 return Initializer->getLocStart();
4316 }
4317 llvm_unreachable("missed an InitializedEntity kind?");
4318}
4319
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004320/// \brief Make a (potentially elidable) temporary copy of the object
4321/// provided by the given initializer by calling the appropriate copy
4322/// constructor.
4323///
4324/// \param S The Sema object used for type-checking.
4325///
Abramo Bagnara92141d22011-01-27 19:55:10 +00004326/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004327/// the type of the initializer expression or a superclass thereof.
4328///
4329/// \param Enter The entity being initialized.
4330///
4331/// \param CurInit The initializer expression.
4332///
4333/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4334/// is permitted in C++03 (but not C++0x) when binding a reference to
4335/// an rvalue.
4336///
4337/// \returns An expression that copies the initializer expression into
4338/// a temporary object, or an error expression if a copy could not be
4339/// created.
John McCalldadc5752010-08-24 06:29:42 +00004340static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00004341 QualType T,
4342 const InitializedEntity &Entity,
4343 ExprResult CurInit,
4344 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00004345 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00004346 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004347 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004348 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004349 Class = cast<CXXRecordDecl>(Record->getDecl());
4350 if (!Class)
4351 return move(CurInit);
4352
Douglas Gregor5d369002011-01-21 18:05:27 +00004353 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004354 // When certain criteria are met, an implementation is allowed to
4355 // omit the copy/move construction of a class object, even if the
4356 // copy/move constructor and/or destructor for the object have
4357 // side effects. [...]
4358 // - when a temporary class object that has not been bound to a
4359 // reference (12.2) would be copied/moved to a class object
4360 // with the same cv-unqualified type, the copy/move operation
4361 // can be omitted by constructing the temporary object
4362 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004363 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004364 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004365 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004366 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004367 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00004368 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00004369 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00004370
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004371 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00004372 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4373 return move(CurInit);
4374
Douglas Gregorf282a762011-01-21 19:38:21 +00004375 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00004376 // Only consider constructors and constructor templates. Per
4377 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4378 // is direct-initialization.
John McCallbc077cf2010-02-08 23:07:23 +00004379 OverloadCandidateSet CandidateSet(Loc);
Richard Smithc620f552011-10-19 16:55:56 +00004380 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004381
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004382 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4383
Douglas Gregore1314a62009-12-18 05:02:21 +00004384 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004385 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004386 case OR_Success:
4387 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004388
Douglas Gregore1314a62009-12-18 05:02:21 +00004389 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004390 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4391 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4392 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004393 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004394 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004395 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004396 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004397 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004398 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004399
Douglas Gregore1314a62009-12-18 05:02:21 +00004400 case OR_Ambiguous:
4401 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004402 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004403 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004404 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00004405 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004406
Douglas Gregore1314a62009-12-18 05:02:21 +00004407 case OR_Deleted:
4408 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004409 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004410 << CurInitExpr->getSourceRange();
4411 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004412 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00004413 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004414 }
4415
Douglas Gregor5ab11652010-04-17 22:01:05 +00004416 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00004417 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004418 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004419
Anders Carlssona01874b2010-04-21 18:47:17 +00004420 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004421 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004422
4423 if (IsExtraneousCopy) {
4424 // If this is a totally extraneous copy for C++03 reference
4425 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004426 // expression. We don't generate an (elided) copy operation here
4427 // because doing so would require us to pass down a flag to avoid
4428 // infinite recursion, where each step adds another extraneous,
4429 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004430
Douglas Gregor30b52772010-04-18 07:57:34 +00004431 // Instantiate the default arguments of any extra parameters in
4432 // the selected copy constructor, as if we were going to create a
4433 // proper call to the copy constructor.
4434 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4435 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4436 if (S.RequireCompleteType(Loc, Parm->getType(),
4437 S.PDiag(diag::err_call_incomplete_argument)))
4438 break;
4439
4440 // Build the default argument expression; we don't actually care
4441 // if this succeeds or not, because this routine will complain
4442 // if there was a problem.
4443 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4444 }
4445
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004446 return S.Owned(CurInitExpr);
4447 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004448
Eli Friedmanfa0df832012-02-02 03:46:19 +00004449 S.MarkFunctionReferenced(Loc, Constructor);
Chandler Carruth30141632011-02-25 19:41:05 +00004450
Douglas Gregor5ab11652010-04-17 22:01:05 +00004451 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004452 // constructor call (we might have derived-to-base conversions, or
4453 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004454 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004455 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004456 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004457
Douglas Gregord0ace022010-04-25 00:55:24 +00004458 // Actually perform the constructor call.
4459 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004460 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004461 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004462 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004463 CXXConstructExpr::CK_Complete,
4464 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004465
Douglas Gregord0ace022010-04-25 00:55:24 +00004466 // If we're supposed to bind temporaries, do so.
4467 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4468 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4469 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004470}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004471
Richard Smithc620f552011-10-19 16:55:56 +00004472/// \brief Check whether elidable copy construction for binding a reference to
4473/// a temporary would have succeeded if we were building in C++98 mode, for
4474/// -Wc++98-compat.
4475static void CheckCXX98CompatAccessibleCopy(Sema &S,
4476 const InitializedEntity &Entity,
4477 Expr *CurInitExpr) {
4478 assert(S.getLangOptions().CPlusPlus0x);
4479
4480 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4481 if (!Record)
4482 return;
4483
4484 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4485 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4486 == DiagnosticsEngine::Ignored)
4487 return;
4488
4489 // Find constructors which would have been considered.
4490 OverloadCandidateSet CandidateSet(Loc);
4491 LookupCopyAndMoveConstructors(
4492 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4493
4494 // Perform overload resolution.
4495 OverloadCandidateSet::iterator Best;
4496 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4497
4498 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4499 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4500 << CurInitExpr->getSourceRange();
4501
4502 switch (OR) {
4503 case OR_Success:
4504 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4505 Best->FoundDecl.getAccess(), Diag);
4506 // FIXME: Check default arguments as far as that's possible.
4507 break;
4508
4509 case OR_No_Viable_Function:
4510 S.Diag(Loc, Diag);
4511 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4512 break;
4513
4514 case OR_Ambiguous:
4515 S.Diag(Loc, Diag);
4516 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4517 break;
4518
4519 case OR_Deleted:
4520 S.Diag(Loc, Diag);
4521 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4522 << 1 << Best->Function->isDeleted();
4523 break;
4524 }
4525}
4526
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004527void InitializationSequence::PrintInitLocationNote(Sema &S,
4528 const InitializedEntity &Entity) {
4529 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4530 if (Entity.getDecl()->getLocation().isInvalid())
4531 return;
4532
4533 if (Entity.getDecl()->getDeclName())
4534 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4535 << Entity.getDecl()->getDeclName();
4536 else
4537 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4538 }
4539}
4540
Sebastian Redl112aa822011-07-14 19:07:55 +00004541static bool isReferenceBinding(const InitializationSequence::Step &s) {
4542 return s.Kind == InitializationSequence::SK_BindReference ||
4543 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4544}
4545
Sebastian Redled2e5322011-12-22 14:44:04 +00004546static ExprResult
4547PerformConstructorInitialization(Sema &S,
4548 const InitializedEntity &Entity,
4549 const InitializationKind &Kind,
4550 MultiExprArg Args,
4551 const InitializationSequence::Step& Step,
4552 bool &ConstructorInitRequiresZeroInit) {
4553 unsigned NumArgs = Args.size();
4554 CXXConstructorDecl *Constructor
4555 = cast<CXXConstructorDecl>(Step.Function.Function);
4556 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4557
4558 // Build a call to the selected constructor.
4559 ASTOwningVector<Expr*> ConstructorArgs(S);
4560 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4561 ? Kind.getEqualLoc()
4562 : Kind.getLocation();
4563
4564 if (Kind.getKind() == InitializationKind::IK_Default) {
4565 // Force even a trivial, implicit default constructor to be
4566 // semantically checked. We do this explicitly because we don't build
4567 // the definition for completely trivial constructors.
4568 CXXRecordDecl *ClassDecl = Constructor->getParent();
4569 assert(ClassDecl && "No parent class for constructor.");
4570 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4571 ClassDecl->hasTrivialDefaultConstructor() &&
4572 !Constructor->isUsed(false))
4573 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4574 }
4575
4576 ExprResult CurInit = S.Owned((Expr *)0);
4577
4578 // Determine the arguments required to actually perform the constructor
4579 // call.
4580 if (S.CompleteConstructorCall(Constructor, move(Args),
4581 Loc, ConstructorArgs))
4582 return ExprError();
4583
4584
4585 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4586 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4587 (Kind.getKind() == InitializationKind::IK_Direct ||
4588 Kind.getKind() == InitializationKind::IK_Value)) {
4589 // An explicitly-constructed temporary, e.g., X(1, 2).
4590 unsigned NumExprs = ConstructorArgs.size();
4591 Expr **Exprs = (Expr **)ConstructorArgs.take();
Eli Friedmanfa0df832012-02-02 03:46:19 +00004592 S.MarkFunctionReferenced(Loc, Constructor);
Sebastian Redled2e5322011-12-22 14:44:04 +00004593 S.DiagnoseUseOfDecl(Constructor, Loc);
4594
4595 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4596 if (!TSInfo)
4597 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4598
4599 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4600 Constructor,
4601 TSInfo,
4602 Exprs,
4603 NumExprs,
4604 Kind.getParenRange(),
4605 HadMultipleCandidates,
4606 ConstructorInitRequiresZeroInit));
4607 } else {
4608 CXXConstructExpr::ConstructionKind ConstructKind =
4609 CXXConstructExpr::CK_Complete;
4610
4611 if (Entity.getKind() == InitializedEntity::EK_Base) {
4612 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4613 CXXConstructExpr::CK_VirtualBase :
4614 CXXConstructExpr::CK_NonVirtualBase;
4615 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4616 ConstructKind = CXXConstructExpr::CK_Delegating;
4617 }
4618
4619 // Only get the parenthesis range if it is a direct construction.
4620 SourceRange parenRange =
4621 Kind.getKind() == InitializationKind::IK_Direct ?
4622 Kind.getParenRange() : SourceRange();
4623
4624 // If the entity allows NRVO, mark the construction as elidable
4625 // unconditionally.
4626 if (Entity.allowsNRVO())
4627 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4628 Constructor, /*Elidable=*/true,
4629 move_arg(ConstructorArgs),
4630 HadMultipleCandidates,
4631 ConstructorInitRequiresZeroInit,
4632 ConstructKind,
4633 parenRange);
4634 else
4635 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4636 Constructor,
4637 move_arg(ConstructorArgs),
4638 HadMultipleCandidates,
4639 ConstructorInitRequiresZeroInit,
4640 ConstructKind,
4641 parenRange);
4642 }
4643 if (CurInit.isInvalid())
4644 return ExprError();
4645
4646 // Only check access if all of that succeeded.
4647 S.CheckConstructorAccess(Loc, Constructor, Entity,
4648 Step.Function.FoundDecl.getAccess());
4649 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4650
4651 if (shouldBindAsTemporary(Entity))
4652 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4653
4654 return move(CurInit);
4655}
4656
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004657ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004658InitializationSequence::Perform(Sema &S,
4659 const InitializedEntity &Entity,
4660 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004661 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004662 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004663 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004664 unsigned NumArgs = Args.size();
4665 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004666 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004667 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004668
Sebastian Redld201edf2011-06-05 13:59:11 +00004669 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004670 // If the declaration is a non-dependent, incomplete array type
4671 // that has an initializer, then its type will be completed once
4672 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004673 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004674 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004675 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004676 if (const IncompleteArrayType *ArrayT
4677 = S.Context.getAsIncompleteArrayType(DeclType)) {
4678 // FIXME: We don't currently have the ability to accurately
4679 // compute the length of an initializer list without
4680 // performing full type-checking of the initializer list
4681 // (since we have to determine where braces are implicitly
4682 // introduced and such). So, we fall back to making the array
4683 // type a dependently-sized array type with no specified
4684 // bound.
4685 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4686 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004687
Douglas Gregor51e77d52009-12-10 17:56:55 +00004688 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004689 if (DeclaratorDecl *DD = Entity.getDecl()) {
4690 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4691 TypeLoc TL = TInfo->getTypeLoc();
4692 if (IncompleteArrayTypeLoc *ArrayLoc
4693 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4694 Brackets = ArrayLoc->getBracketsRange();
4695 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004696 }
4697
4698 *ResultType
4699 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4700 /*NumElts=*/0,
4701 ArrayT->getSizeModifier(),
4702 ArrayT->getIndexTypeCVRQualifiers(),
4703 Brackets);
4704 }
4705
4706 }
4707 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004708 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4709 Kind.isExplicitCast());
4710 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004711 }
4712
Sebastian Redld201edf2011-06-05 13:59:11 +00004713 // No steps means no initialization.
4714 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004715 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004716
Douglas Gregor1b303932009-12-22 15:35:07 +00004717 QualType DestType = Entity.getType().getNonReferenceType();
4718 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004719 // the same as Entity.getDecl()->getType() in cases involving type merging,
4720 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004721 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004722 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004723 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004724
John McCalldadc5752010-08-24 06:29:42 +00004725 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004726
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004727 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004728 // grab the only argument out the Args and place it into the "current"
4729 // initializer.
4730 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004731 case SK_ResolveAddressOfOverloadedFunction:
4732 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004733 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004734 case SK_CastDerivedToBaseLValue:
4735 case SK_BindReference:
4736 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004737 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004738 case SK_UserConversion:
4739 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004740 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004741 case SK_QualificationConversionRValue:
4742 case SK_ConversionSequence:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004743 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00004744 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00004745 case SK_UnwrapInitList:
4746 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00004747 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004748 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004749 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004750 case SK_ArrayInit:
4751 case SK_PassByIndirectCopyRestore:
4752 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00004753 case SK_ProduceObjCObject:
4754 case SK_StdInitializerList: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004755 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004756 CurInit = Args.get()[0];
4757 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004758 break;
John McCall34376a62010-12-04 03:47:34 +00004759 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004760
Douglas Gregore1314a62009-12-18 05:02:21 +00004761 case SK_ConstructorInitialization:
4762 case SK_ZeroInitialization:
4763 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004764 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004765
4766 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004767 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004768 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004769 for (step_iterator Step = step_begin(), StepEnd = step_end();
4770 Step != StepEnd; ++Step) {
4771 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004772 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004773
John Wiegley01296292011-04-08 18:41:53 +00004774 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004775
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004776 switch (Step->Kind) {
4777 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004778 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004779 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004780 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004781 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004782 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004783 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004784 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004785 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004786
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004787 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004788 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004789 case SK_CastDerivedToBaseLValue: {
4790 // We have a derived-to-base cast that produces either an rvalue or an
4791 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004792
John McCallcf142162010-08-07 06:22:56 +00004793 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004794
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004795 // Casts to inaccessible base classes are allowed with C-style casts.
4796 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4797 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004798 CurInit.get()->getLocStart(),
4799 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004800 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004801 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004802
Douglas Gregor88d292c2010-05-13 16:44:06 +00004803 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4804 QualType T = SourceType;
4805 if (const PointerType *Pointer = T->getAs<PointerType>())
4806 T = Pointer->getPointeeType();
4807 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004808 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004809 cast<CXXRecordDecl>(RecordTy->getDecl()));
4810 }
4811
John McCall2536c6d2010-08-25 10:28:54 +00004812 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004813 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004814 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004815 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004816 VK_XValue :
4817 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004818 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4819 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004820 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004821 CurInit.get(),
4822 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004823 break;
4824 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004825
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004826 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004827 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004828 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4829 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004830 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004831 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004832 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004833 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004834 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004835 }
Anders Carlssona91be642010-01-29 02:47:33 +00004836
John Wiegley01296292011-04-08 18:41:53 +00004837 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004838 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004839 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4840 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004841 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004842 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004843 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004844 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004845
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004846 // Reference binding does not have any corresponding ASTs.
4847
4848 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004849 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004850 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004851
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004852 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004853
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004854 case SK_BindReferenceToTemporary:
4855 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004856 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004857 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004858
Douglas Gregorfe314812011-06-21 17:03:29 +00004859 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004860 CurInit = new (S.Context) MaterializeTemporaryExpr(
4861 Entity.getType().getNonReferenceType(),
4862 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004863 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004864
4865 // If we're binding to an Objective-C object that has lifetime, we
4866 // need cleanups.
4867 if (S.getLangOptions().ObjCAutoRefCount &&
4868 CurInit.get()->getType()->isObjCLifetimeType())
4869 S.ExprNeedsCleanups = true;
4870
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004871 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004872
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004873 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004874 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004875 /*IsExtraneousCopy=*/true);
4876 break;
4877
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004878 case SK_UserConversion: {
4879 // We have a user-defined conversion that invokes either a constructor
4880 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004881 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004882 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004883 FunctionDecl *Fn = Step->Function.Function;
4884 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004885 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00004886 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00004887 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004888 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004889 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004890 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004891 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004892
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004893 // Determine the arguments required to actually perform the constructor
4894 // call.
John Wiegley01296292011-04-08 18:41:53 +00004895 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004896 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004897 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004898 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004899 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004900
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004901 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004902 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004903 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004904 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004905 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004906 CXXConstructExpr::CK_Complete,
4907 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004908 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004909 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004910
Anders Carlssona01874b2010-04-21 18:47:17 +00004911 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004912 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004913 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004914
John McCalle3027922010-08-25 11:45:40 +00004915 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004916 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4917 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4918 S.IsDerivedFrom(SourceType, Class))
4919 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004920
Douglas Gregor95562572010-04-24 23:45:46 +00004921 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004922 } else {
4923 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004924 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley01296292011-04-08 18:41:53 +00004925 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004926 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004927 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004928
4929 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004930 // derived-to-base conversion? I believe the answer is "no", because
4931 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00004932 ExprResult CurInitExprRes =
4933 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4934 FoundFn, Conversion);
4935 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004936 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004937 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004938
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004939 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004940 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
4941 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004942 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00004943 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004944
John McCalle3027922010-08-25 11:45:40 +00004945 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004946
Douglas Gregor95562572010-04-24 23:45:46 +00004947 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004948 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004949
Sebastian Redl112aa822011-07-14 19:07:55 +00004950 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004951 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
4952
4953 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00004954 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00004955 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004956 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00004957 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00004958 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00004959 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00004960 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
John Wiegley01296292011-04-08 18:41:53 +00004961 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00004962 }
4963 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004964
John McCallcf142162010-08-07 06:22:56 +00004965 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00004966 CurInit.get()->getType(),
4967 CastKind, CurInit.get(), 0,
Eli Friedmanf272d402011-09-27 01:11:35 +00004968 CurInit.get()->getValueKind()));
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004969 if (MaybeBindToTemp)
4970 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004971 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004972 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4973 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004974 break;
4975 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004976
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004977 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004978 case SK_QualificationConversionXValue:
4979 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004980 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00004981 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004982 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004983 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004984 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004985 VK_XValue :
4986 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00004987 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004988 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004989 }
4990
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004991 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00004992 Sema::CheckedConversionKind CCK
4993 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4994 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00004995 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00004996 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00004997 ExprResult CurInitExprRes =
4998 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00004999 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00005000 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005001 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005002 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005003 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00005004 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005005
Douglas Gregor51e77d52009-12-10 17:56:55 +00005006 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00005007 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl29526f02011-11-27 16:50:07 +00005008 // Hack: We must pass *ResultType if available in order to set the type
5009 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5010 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5011 // temporary, not a reference, so we should pass Ty.
5012 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5013 // Since this step is never used for a reference directly, we explicitly
5014 // unwrap references here and rewrap them afterwards.
5015 // We also need to create a InitializeTemporary entity for this.
5016 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
5017 bool IsTemporary = ResultType && (*ResultType)->isReferenceType();
5018 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5019 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
5020 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005021 Kind.getKind() != InitializationKind::IK_Direct ||
5022 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005023 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00005024 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005025
Sebastian Redl29526f02011-11-27 16:50:07 +00005026 if (ResultType) {
5027 if ((*ResultType)->isRValueReferenceType())
5028 Ty = S.Context.getRValueReferenceType(Ty);
5029 else if ((*ResultType)->isLValueReferenceType())
5030 Ty = S.Context.getLValueReferenceType(Ty,
5031 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5032 *ResultType = Ty;
5033 }
5034
5035 InitListExpr *StructuredInitList =
5036 PerformInitList.getFullyStructuredList();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005037 CurInit.release();
Sebastian Redl29526f02011-11-27 16:50:07 +00005038 CurInit = S.Owned(StructuredInitList);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005039 break;
5040 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005041
Sebastian Redled2e5322011-12-22 14:44:04 +00005042 case SK_ListConstructorCall: {
5043 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5044 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
5045 CurInit = PerformConstructorInitialization(S, Entity, Kind,
5046 move(Arg), *Step,
5047 ConstructorInitRequiresZeroInit);
5048 break;
5049 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005050
Sebastian Redl29526f02011-11-27 16:50:07 +00005051 case SK_UnwrapInitList:
5052 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5053 break;
5054
5055 case SK_RewrapInitList: {
5056 Expr *E = CurInit.take();
5057 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5058 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5059 Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
5060 ILE->setSyntacticForm(Syntactic);
5061 ILE->setType(E->getType());
5062 ILE->setValueKind(E->getValueKind());
5063 CurInit = S.Owned(ILE);
5064 break;
5065 }
5066
Sebastian Redled2e5322011-12-22 14:44:04 +00005067 case SK_ConstructorInitialization:
5068 CurInit = PerformConstructorInitialization(S, Entity, Kind, move(Args),
5069 *Step,
5070 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005071 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005072
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005073 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005074 step_iterator NextStep = Step;
5075 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005076 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005077 NextStep->Kind == SK_ConstructorInitialization) {
5078 // The need for zero-initialization is recorded directly into
5079 // the call to the object's constructor within the next step.
5080 ConstructorInitRequiresZeroInit = true;
5081 } else if (Kind.getKind() == InitializationKind::IK_Value &&
5082 S.getLangOptions().CPlusPlus &&
5083 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00005084 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5085 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005086 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00005087 Kind.getRange().getBegin());
5088
5089 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5090 TSInfo->getType().getNonLValueExprType(S.Context),
5091 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005092 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005093 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005094 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005095 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005096 break;
5097 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005098
5099 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00005100 QualType SourceType = CurInit.get()->getType();
5101 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00005102 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00005103 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5104 if (Result.isInvalid())
5105 return ExprError();
5106 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00005107
5108 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005109 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00005110 if (ConvTy != Sema::Compatible &&
5111 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00005112 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00005113 == Sema::Compatible)
5114 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00005115 if (CurInitExprRes.isInvalid())
5116 return ExprError();
5117 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00005118
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005119 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00005120 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5121 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00005122 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005123 getAssignmentAction(Entity),
5124 &Complained)) {
5125 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005126 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005127 } else if (Complained)
5128 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00005129 break;
5130 }
Eli Friedman78275202009-12-19 08:11:05 +00005131
5132 case SK_StringInit: {
5133 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00005134 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00005135 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00005136 break;
5137 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005138
5139 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00005140 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00005141 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005142 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005143 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005144
5145 case SK_ArrayInit:
5146 // Okay: we checked everything before creating this step. Note that
5147 // this is a GNU extension.
5148 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00005149 << Step->Type << CurInit.get()->getType()
5150 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00005151
5152 // If the destination type is an incomplete array type, update the
5153 // type accordingly.
5154 if (ResultType) {
5155 if (const IncompleteArrayType *IncompleteDest
5156 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5157 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00005158 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00005159 *ResultType = S.Context.getConstantArrayType(
5160 IncompleteDest->getElementType(),
5161 ConstantSource->getSize(),
5162 ArrayType::Normal, 0);
5163 }
5164 }
5165 }
John McCall31168b02011-06-15 23:02:42 +00005166 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005167
John McCall31168b02011-06-15 23:02:42 +00005168 case SK_PassByIndirectCopyRestore:
5169 case SK_PassByIndirectRestore:
5170 checkIndirectCopyRestoreSource(S, CurInit.get());
5171 CurInit = S.Owned(new (S.Context)
5172 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5173 Step->Kind == SK_PassByIndirectCopyRestore));
5174 break;
5175
5176 case SK_ProduceObjCObject:
5177 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00005178 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00005179 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00005180 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005181
5182 case SK_StdInitializerList: {
5183 QualType Dest = Step->Type;
5184 QualType E;
5185 bool Success = S.isStdInitializerList(Dest, &E);
5186 (void)Success;
5187 assert(Success && "Destination type changed?");
5188 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
5189 unsigned NumInits = ILE->getNumInits();
5190 SmallVector<Expr*, 16> Converted(NumInits);
5191 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5192 S.Context.getConstantArrayType(E,
5193 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5194 NumInits),
5195 ArrayType::Normal, 0));
5196 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5197 0, HiddenArray);
5198 for (unsigned i = 0; i < NumInits; ++i) {
5199 Element.setElementIndex(i);
5200 ExprResult Init = S.Owned(ILE->getInit(i));
5201 ExprResult Res = S.PerformCopyInitialization(Element,
5202 Init.get()->getExprLoc(),
5203 Init);
5204 assert(!Res.isInvalid() && "Result changed since try phase.");
5205 Converted[i] = Res.take();
5206 }
5207 InitListExpr *Semantic = new (S.Context)
5208 InitListExpr(S.Context, ILE->getLBraceLoc(),
5209 Converted.data(), NumInits, ILE->getRBraceLoc());
5210 Semantic->setSyntacticForm(ILE);
5211 Semantic->setType(Dest);
5212 CurInit = S.Owned(Semantic);
5213 break;
5214 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005215 }
5216 }
John McCall1f425642010-11-11 03:21:53 +00005217
5218 // Diagnose non-fatal problems with the completed initialization.
5219 if (Entity.getKind() == InitializedEntity::EK_Member &&
5220 cast<FieldDecl>(Entity.getDecl())->isBitField())
5221 S.CheckBitFieldInitialization(Kind.getLocation(),
5222 cast<FieldDecl>(Entity.getDecl()),
5223 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005224
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005225 return move(CurInit);
5226}
5227
5228//===----------------------------------------------------------------------===//
5229// Diagnose initialization failures
5230//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005231bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005232 const InitializedEntity &Entity,
5233 const InitializationKind &Kind,
5234 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005235 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005236 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005237
Douglas Gregor1b303932009-12-22 15:35:07 +00005238 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005239 switch (Failure) {
5240 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005241 // FIXME: Customize for the initialized entity?
5242 if (NumArgs == 0)
5243 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5244 << DestType.getNonReferenceType();
5245 else // FIXME: diagnostic below could be better!
5246 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5247 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005248 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005249
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005250 case FK_ArrayNeedsInitList:
5251 case FK_ArrayNeedsInitListOrStringLiteral:
5252 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5253 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5254 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005255
Douglas Gregore2f943b2011-02-22 18:29:51 +00005256 case FK_ArrayTypeMismatch:
5257 case FK_NonConstantArrayInit:
5258 S.Diag(Kind.getLocation(),
5259 (Failure == FK_ArrayTypeMismatch
5260 ? diag::err_array_init_different_type
5261 : diag::err_array_init_non_constant_array))
5262 << DestType.getNonReferenceType()
5263 << Args[0]->getType()
5264 << Args[0]->getSourceRange();
5265 break;
5266
John McCalla59dc2f2012-01-05 00:13:19 +00005267 case FK_VariableLengthArrayHasInitializer:
5268 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5269 << Args[0]->getSourceRange();
5270 break;
5271
John McCall16df1e52010-03-30 21:47:33 +00005272 case FK_AddressOfOverloadFailed: {
5273 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005274 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005275 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00005276 true,
5277 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005278 break;
John McCall16df1e52010-03-30 21:47:33 +00005279 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005280
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005281 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00005282 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005283 switch (FailedOverloadResult) {
5284 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00005285 if (Failure == FK_UserConversionOverloadFailed)
5286 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5287 << Args[0]->getType() << DestType
5288 << Args[0]->getSourceRange();
5289 else
5290 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5291 << DestType << Args[0]->getType()
5292 << Args[0]->getSourceRange();
5293
John McCall5c32be02010-08-24 20:38:10 +00005294 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005295 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005296
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005297 case OR_No_Viable_Function:
5298 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5299 << Args[0]->getType() << DestType.getNonReferenceType()
5300 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00005301 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005302 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005303
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005304 case OR_Deleted: {
5305 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5306 << Args[0]->getType() << DestType.getNonReferenceType()
5307 << Args[0]->getSourceRange();
5308 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005309 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00005310 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5311 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005312 if (Ovl == OR_Deleted) {
5313 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005314 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005315 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005316 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005317 }
5318 break;
5319 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005320
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005321 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005322 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005323 }
5324 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005325
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005326 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00005327 if (isa<InitListExpr>(Args[0])) {
5328 S.Diag(Kind.getLocation(),
5329 diag::err_lvalue_reference_bind_to_initlist)
5330 << DestType.getNonReferenceType().isVolatileQualified()
5331 << DestType.getNonReferenceType()
5332 << Args[0]->getSourceRange();
5333 break;
5334 }
5335 // Intentional fallthrough
5336
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005337 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005338 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005339 Failure == FK_NonConstLValueReferenceBindingToTemporary
5340 ? diag::err_lvalue_reference_bind_to_temporary
5341 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00005342 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005343 << DestType.getNonReferenceType()
5344 << Args[0]->getType()
5345 << Args[0]->getSourceRange();
5346 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005347
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005348 case FK_RValueReferenceBindingToLValue:
5349 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00005350 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005351 << Args[0]->getSourceRange();
5352 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005353
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005354 case FK_ReferenceInitDropsQualifiers:
5355 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5356 << DestType.getNonReferenceType()
5357 << Args[0]->getType()
5358 << Args[0]->getSourceRange();
5359 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005360
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005361 case FK_ReferenceInitFailed:
5362 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5363 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00005364 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005365 << Args[0]->getType()
5366 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00005367 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5368 Args[0]->getType()->isObjCObjectPointerType())
5369 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005370 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005371
Douglas Gregorb491ed32011-02-19 21:32:49 +00005372 case FK_ConversionFailed: {
5373 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00005374 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00005375 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005376 << DestType
John McCall086a4642010-11-24 05:12:34 +00005377 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00005378 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005379 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00005380 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5381 S.Diag(Kind.getLocation(), PDiag);
Douglas Gregor33823722011-06-11 01:09:30 +00005382 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5383 Args[0]->getType()->isObjCObjectPointerType())
5384 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005385 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00005386 }
John Wiegley01296292011-04-08 18:41:53 +00005387
5388 case FK_ConversionFromPropertyFailed:
5389 // No-op. This error has already been reported.
5390 break;
5391
Douglas Gregor51e77d52009-12-10 17:56:55 +00005392 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00005393 SourceRange R;
5394
5395 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00005396 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00005397 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005398 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00005399 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00005400
Douglas Gregor8ec51732010-09-08 21:40:08 +00005401 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5402 if (Kind.isCStyleOrFunctionalCast())
5403 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5404 << R;
5405 else
5406 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5407 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00005408 break;
5409 }
5410
5411 case FK_ReferenceBindingToInitList:
5412 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5413 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5414 break;
5415
5416 case FK_InitListBadDestinationType:
5417 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5418 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5419 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005420
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005421 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005422 case FK_ConstructorOverloadFailed: {
5423 SourceRange ArgsRange;
5424 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005425 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005426 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005427
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005428 if (Failure == FK_ListConstructorOverloadFailed) {
5429 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5430 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5431 Args = InitList->getInits();
5432 NumArgs = InitList->getNumInits();
5433 }
5434
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005435 // FIXME: Using "DestType" for the entity we're printing is probably
5436 // bad.
5437 switch (FailedOverloadResult) {
5438 case OR_Ambiguous:
5439 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5440 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005441 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5442 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005443 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005444
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005445 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005446 if (Kind.getKind() == InitializationKind::IK_Default &&
5447 (Entity.getKind() == InitializedEntity::EK_Base ||
5448 Entity.getKind() == InitializedEntity::EK_Member) &&
5449 isa<CXXConstructorDecl>(S.CurContext)) {
5450 // This is implicit default initialization of a member or
5451 // base within a constructor. If no viable function was
5452 // found, notify the user that she needs to explicitly
5453 // initialize this base/member.
5454 CXXConstructorDecl *Constructor
5455 = cast<CXXConstructorDecl>(S.CurContext);
5456 if (Entity.getKind() == InitializedEntity::EK_Base) {
5457 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5458 << Constructor->isImplicit()
5459 << S.Context.getTypeDeclType(Constructor->getParent())
5460 << /*base=*/0
5461 << Entity.getType();
5462
5463 RecordDecl *BaseDecl
5464 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5465 ->getDecl();
5466 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5467 << S.Context.getTagDeclType(BaseDecl);
5468 } else {
5469 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5470 << Constructor->isImplicit()
5471 << S.Context.getTypeDeclType(Constructor->getParent())
5472 << /*member=*/1
5473 << Entity.getName();
5474 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5475
5476 if (const RecordType *Record
5477 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005478 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005479 diag::note_previous_decl)
5480 << S.Context.getTagDeclType(Record->getDecl());
5481 }
5482 break;
5483 }
5484
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005485 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5486 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005487 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005488 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005489
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005490 case OR_Deleted: {
5491 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5492 << true << DestType << ArgsRange;
5493 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005494 OverloadingResult Ovl
5495 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005496 if (Ovl == OR_Deleted) {
5497 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005498 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005499 } else {
5500 llvm_unreachable("Inconsistent overload resolution?");
5501 }
5502 break;
5503 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005504
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005505 case OR_Success:
5506 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005507 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005508 }
David Blaikie60deeee2012-01-17 08:24:58 +00005509 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005510
Douglas Gregor85dabae2009-12-16 01:38:02 +00005511 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005512 if (Entity.getKind() == InitializedEntity::EK_Member &&
5513 isa<CXXConstructorDecl>(S.CurContext)) {
5514 // This is implicit default-initialization of a const member in
5515 // a constructor. Complain that it needs to be explicitly
5516 // initialized.
5517 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5518 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5519 << Constructor->isImplicit()
5520 << S.Context.getTypeDeclType(Constructor->getParent())
5521 << /*const=*/1
5522 << Entity.getName();
5523 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5524 << Entity.getName();
5525 } else {
5526 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5527 << DestType << (bool)DestType->getAs<RecordType>();
5528 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00005529 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005530
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005531 case FK_Incomplete:
5532 S.RequireCompleteType(Kind.getLocation(), DestType,
5533 diag::err_init_incomplete_type);
5534 break;
5535
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005536 case FK_ListInitializationFailed: {
5537 // Run the init list checker again to emit diagnostics.
5538 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5539 QualType DestType = Entity.getType();
5540 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005541 DestType, /*VerifyOnly=*/false,
5542 Kind.getKind() != InitializationKind::IK_Direct ||
5543 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005544 assert(DiagnoseInitList.HadError() &&
5545 "Inconsistent init list check result.");
5546 break;
5547 }
John McCall4124c492011-10-17 18:40:02 +00005548
5549 case FK_PlaceholderType: {
5550 // FIXME: Already diagnosed!
5551 break;
5552 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00005553
5554 case FK_InitListElementCopyFailure: {
5555 // Try to perform all copies again.
5556 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5557 unsigned NumInits = InitList->getNumInits();
5558 QualType DestType = Entity.getType();
5559 QualType E;
5560 bool Success = S.isStdInitializerList(DestType, &E);
5561 (void)Success;
5562 assert(Success && "Where did the std::initializer_list go?");
5563 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5564 S.Context.getConstantArrayType(E,
5565 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5566 NumInits),
5567 ArrayType::Normal, 0));
5568 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
5569 0, HiddenArray);
5570 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
5571 // where the init list type is wrong, e.g.
5572 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
5573 // FIXME: Emit a note if we hit the limit?
5574 int ErrorCount = 0;
5575 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
5576 Element.setElementIndex(i);
5577 ExprResult Init = S.Owned(InitList->getInit(i));
5578 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
5579 .isInvalid())
5580 ++ErrorCount;
5581 }
5582 break;
5583 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005584 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005585
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005586 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005587 return true;
5588}
Douglas Gregore1314a62009-12-18 05:02:21 +00005589
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005590void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005591 switch (SequenceKind) {
5592 case FailedSequence: {
5593 OS << "Failed sequence: ";
5594 switch (Failure) {
5595 case FK_TooManyInitsForReference:
5596 OS << "too many initializers for reference";
5597 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005598
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005599 case FK_ArrayNeedsInitList:
5600 OS << "array requires initializer list";
5601 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005602
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005603 case FK_ArrayNeedsInitListOrStringLiteral:
5604 OS << "array requires initializer list or string literal";
5605 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005606
Douglas Gregore2f943b2011-02-22 18:29:51 +00005607 case FK_ArrayTypeMismatch:
5608 OS << "array type mismatch";
5609 break;
5610
5611 case FK_NonConstantArrayInit:
5612 OS << "non-constant array initializer";
5613 break;
5614
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005615 case FK_AddressOfOverloadFailed:
5616 OS << "address of overloaded function failed";
5617 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005618
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005619 case FK_ReferenceInitOverloadFailed:
5620 OS << "overload resolution for reference initialization failed";
5621 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005622
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005623 case FK_NonConstLValueReferenceBindingToTemporary:
5624 OS << "non-const lvalue reference bound to temporary";
5625 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005626
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005627 case FK_NonConstLValueReferenceBindingToUnrelated:
5628 OS << "non-const lvalue reference bound to unrelated type";
5629 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005630
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005631 case FK_RValueReferenceBindingToLValue:
5632 OS << "rvalue reference bound to an lvalue";
5633 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005634
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005635 case FK_ReferenceInitDropsQualifiers:
5636 OS << "reference initialization drops qualifiers";
5637 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005638
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005639 case FK_ReferenceInitFailed:
5640 OS << "reference initialization failed";
5641 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005642
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005643 case FK_ConversionFailed:
5644 OS << "conversion failed";
5645 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005646
John Wiegley01296292011-04-08 18:41:53 +00005647 case FK_ConversionFromPropertyFailed:
5648 OS << "conversion from property failed";
5649 break;
5650
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005651 case FK_TooManyInitsForScalar:
5652 OS << "too many initializers for scalar";
5653 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005654
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005655 case FK_ReferenceBindingToInitList:
5656 OS << "referencing binding to initializer list";
5657 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005658
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005659 case FK_InitListBadDestinationType:
5660 OS << "initializer list for non-aggregate, non-scalar type";
5661 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005662
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005663 case FK_UserConversionOverloadFailed:
5664 OS << "overloading failed for user-defined conversion";
5665 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005666
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005667 case FK_ConstructorOverloadFailed:
5668 OS << "constructor overloading failed";
5669 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005670
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005671 case FK_DefaultInitOfConst:
5672 OS << "default initialization of a const variable";
5673 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005674
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005675 case FK_Incomplete:
5676 OS << "initialization of incomplete type";
5677 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005678
5679 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005680 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00005681 break;
5682
John McCalla59dc2f2012-01-05 00:13:19 +00005683 case FK_VariableLengthArrayHasInitializer:
5684 OS << "variable length array has an initializer";
5685 break;
5686
John McCall4124c492011-10-17 18:40:02 +00005687 case FK_PlaceholderType:
5688 OS << "initializer expression isn't contextually valid";
5689 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00005690
5691 case FK_ListConstructorOverloadFailed:
5692 OS << "list constructor overloading failed";
5693 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005694
5695 case FK_InitListElementCopyFailure:
5696 OS << "copy construction of initializer list element failed";
5697 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005698 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005699 OS << '\n';
5700 return;
5701 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005702
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005703 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005704 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005705 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005706
Sebastian Redld201edf2011-06-05 13:59:11 +00005707 case NormalSequence:
5708 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005709 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005710 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005711
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005712 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5713 if (S != step_begin()) {
5714 OS << " -> ";
5715 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005716
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005717 switch (S->Kind) {
5718 case SK_ResolveAddressOfOverloadedFunction:
5719 OS << "resolve address of overloaded function";
5720 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005721
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005722 case SK_CastDerivedToBaseRValue:
5723 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5724 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005725
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005726 case SK_CastDerivedToBaseXValue:
5727 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5728 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005729
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005730 case SK_CastDerivedToBaseLValue:
5731 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5732 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005733
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005734 case SK_BindReference:
5735 OS << "bind reference to lvalue";
5736 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005737
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005738 case SK_BindReferenceToTemporary:
5739 OS << "bind reference to a temporary";
5740 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005741
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005742 case SK_ExtraneousCopyToTemporary:
5743 OS << "extraneous C++03 copy to temporary";
5744 break;
5745
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005746 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005747 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005748 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005749
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005750 case SK_QualificationConversionRValue:
5751 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005752 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005753
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005754 case SK_QualificationConversionXValue:
5755 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005756 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005757
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005758 case SK_QualificationConversionLValue:
5759 OS << "qualification conversion (lvalue)";
5760 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005761
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005762 case SK_ConversionSequence:
5763 OS << "implicit conversion sequence (";
5764 S->ICS->DebugPrint(); // FIXME: use OS
5765 OS << ")";
5766 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005767
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005768 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005769 OS << "list aggregate initialization";
5770 break;
5771
5772 case SK_ListConstructorCall:
5773 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005774 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005775
Sebastian Redl29526f02011-11-27 16:50:07 +00005776 case SK_UnwrapInitList:
5777 OS << "unwrap reference initializer list";
5778 break;
5779
5780 case SK_RewrapInitList:
5781 OS << "rewrap reference initializer list";
5782 break;
5783
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005784 case SK_ConstructorInitialization:
5785 OS << "constructor initialization";
5786 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005787
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005788 case SK_ZeroInitialization:
5789 OS << "zero initialization";
5790 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005791
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005792 case SK_CAssignment:
5793 OS << "C assignment";
5794 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005795
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005796 case SK_StringInit:
5797 OS << "string initialization";
5798 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005799
5800 case SK_ObjCObjectConversion:
5801 OS << "Objective-C object conversion";
5802 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005803
5804 case SK_ArrayInit:
5805 OS << "array initialization";
5806 break;
John McCall31168b02011-06-15 23:02:42 +00005807
5808 case SK_PassByIndirectCopyRestore:
5809 OS << "pass by indirect copy and restore";
5810 break;
5811
5812 case SK_PassByIndirectRestore:
5813 OS << "pass by indirect restore";
5814 break;
5815
5816 case SK_ProduceObjCObject:
5817 OS << "Objective-C object retension";
5818 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005819
5820 case SK_StdInitializerList:
5821 OS << "std::initializer_list from initializer list";
5822 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005823 }
5824 }
5825}
5826
5827void InitializationSequence::dump() const {
5828 dump(llvm::errs());
5829}
5830
Richard Smith66e05fe2012-01-18 05:21:49 +00005831static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
5832 QualType EntityType,
5833 const Expr *PreInit,
5834 const Expr *PostInit) {
5835 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
5836 return;
5837
5838 // A narrowing conversion can only appear as the final implicit conversion in
5839 // an initialization sequence.
5840 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
5841 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
5842 return;
5843
5844 const ImplicitConversionSequence &ICS = *LastStep.ICS;
5845 const StandardConversionSequence *SCS = 0;
5846 switch (ICS.getKind()) {
5847 case ImplicitConversionSequence::StandardConversion:
5848 SCS = &ICS.Standard;
5849 break;
5850 case ImplicitConversionSequence::UserDefinedConversion:
5851 SCS = &ICS.UserDefined.After;
5852 break;
5853 case ImplicitConversionSequence::AmbiguousConversion:
5854 case ImplicitConversionSequence::EllipsisConversion:
5855 case ImplicitConversionSequence::BadConversion:
5856 return;
5857 }
5858
5859 // Determine the type prior to the narrowing conversion. If a conversion
5860 // operator was used, this may be different from both the type of the entity
5861 // and of the pre-initialization expression.
5862 QualType PreNarrowingType = PreInit->getType();
5863 if (Seq.step_begin() + 1 != Seq.step_end())
5864 PreNarrowingType = Seq.step_end()[-2].Type;
5865
5866 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
5867 APValue ConstantValue;
Richard Smithf8379a02012-01-18 23:55:52 +00005868 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00005869 case NK_Not_Narrowing:
5870 // No narrowing occurred.
5871 return;
5872
5873 case NK_Type_Narrowing:
5874 // This was a floating-to-integer conversion, which is always considered a
5875 // narrowing conversion even if the value is a constant and can be
5876 // represented exactly as an integer.
5877 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00005878 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5879 diag::warn_init_list_type_narrowing
5880 : S.isSFINAEContext()?
5881 diag::err_init_list_type_narrowing_sfinae
5882 : diag::err_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00005883 << PostInit->getSourceRange()
5884 << PreNarrowingType.getLocalUnqualifiedType()
5885 << EntityType.getLocalUnqualifiedType();
5886 break;
5887
5888 case NK_Constant_Narrowing:
5889 // A constant value was narrowed.
5890 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00005891 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5892 diag::warn_init_list_constant_narrowing
5893 : S.isSFINAEContext()?
5894 diag::err_init_list_constant_narrowing_sfinae
5895 : diag::err_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00005896 << PostInit->getSourceRange()
Richard Smithf6f003a2011-12-16 19:06:07 +00005897 << ConstantValue.getAsString(S.getASTContext(), EntityType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005898 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00005899 break;
5900
5901 case NK_Variable_Narrowing:
5902 // A variable's value may have been narrowed.
5903 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00005904 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5905 diag::warn_init_list_variable_narrowing
5906 : S.isSFINAEContext()?
5907 diag::err_init_list_variable_narrowing_sfinae
5908 : diag::err_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00005909 << PostInit->getSourceRange()
5910 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005911 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00005912 break;
5913 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005914
5915 llvm::SmallString<128> StaticCast;
5916 llvm::raw_svector_ostream OS(StaticCast);
5917 OS << "static_cast<";
5918 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5919 // It's important to use the typedef's name if there is one so that the
5920 // fixit doesn't break code using types like int64_t.
5921 //
5922 // FIXME: This will break if the typedef requires qualification. But
5923 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005924 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005925 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5926 OS << BT->getName(S.getLangOptions());
5927 else {
5928 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5929 // with a broken cast.
5930 return;
5931 }
5932 OS << ">(";
Richard Smith66e05fe2012-01-18 05:21:49 +00005933 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
5934 << PostInit->getSourceRange()
5935 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005936 << FixItHint::CreateInsertion(
Richard Smith66e05fe2012-01-18 05:21:49 +00005937 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005938}
5939
Douglas Gregore1314a62009-12-18 05:02:21 +00005940//===----------------------------------------------------------------------===//
5941// Initialization helper functions
5942//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00005943bool
5944Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5945 ExprResult Init) {
5946 if (Init.isInvalid())
5947 return false;
5948
5949 Expr *InitE = Init.get();
5950 assert(InitE && "No initialization expression");
5951
5952 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5953 SourceLocation());
5954 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005955 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00005956}
5957
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005958ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00005959Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5960 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005961 ExprResult Init,
5962 bool TopLevelOfInitList) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005963 if (Init.isInvalid())
5964 return ExprError();
5965
John McCall1f425642010-11-11 03:21:53 +00005966 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00005967 assert(InitE && "No initialization expression?");
5968
5969 if (EqualLoc.isInvalid())
5970 EqualLoc = InitE->getLocStart();
5971
5972 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5973 EqualLoc);
5974 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5975 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005976
Richard Smith66e05fe2012-01-18 05:21:49 +00005977 ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
5978
5979 if (!Result.isInvalid() && TopLevelOfInitList)
5980 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
5981 InitE, Result.get());
5982
5983 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00005984}