1 //===--- 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 // 10 // This file implements semantic analysis for initializers. The main entry 11 // point is Sema::CheckInitList(), but all of the work is performed 12 // within the InitListChecker class. 13 // 14 // This file also implements Sema::CheckInitializerTypes. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "Sema.h" 19 #include "clang/Parse/Designator.h" 20 #include "clang/AST/ASTContext.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/ExprObjC.h" 23 #include <map> 24 using namespace clang; 25 26 //===----------------------------------------------------------------------===// 27 // Sema Initialization Checking 28 //===----------------------------------------------------------------------===// 29 30 static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) { 31 const ArrayType *AT = Context.getAsArrayType(DeclType); 32 if (!AT) return 0; 33 34 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT)) 35 return 0; 36 37 // See if this is a string literal or @encode. 38 Init = Init->IgnoreParens(); 39 40 // Handle @encode, which is a narrow string. 41 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType()) 42 return Init; 43 44 // Otherwise we can only handle string literals. 45 StringLiteral *SL = dyn_cast<StringLiteral>(Init); 46 if (SL == 0) return 0; 47 48 QualType ElemTy = Context.getCanonicalType(AT->getElementType()); 49 // char array can be initialized with a narrow string. 50 // Only allow char x[] = "foo"; not char x[] = L"foo"; 51 if (!SL->isWide()) 52 return ElemTy->isCharType() ? Init : 0; 53 54 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with 55 // correction from DR343): "An array with element type compatible with a 56 // qualified or unqualified version of wchar_t may be initialized by a wide 57 // string literal, optionally enclosed in braces." 58 if (Context.typesAreCompatible(Context.getWCharType(), 59 ElemTy.getUnqualifiedType())) 60 return Init; 61 62 return 0; 63 } 64 65 static bool CheckSingleInitializer(Expr *&Init, QualType DeclType, 66 bool DirectInit, Sema &S) { 67 // Get the type before calling CheckSingleAssignmentConstraints(), since 68 // it can promote the expression. 69 QualType InitType = Init->getType(); 70 71 if (S.getLangOptions().CPlusPlus) { 72 // FIXME: I dislike this error message. A lot. 73 if (S.PerformImplicitConversion(Init, DeclType, "initializing", DirectInit)) 74 return S.Diag(Init->getSourceRange().getBegin(), 75 diag::err_typecheck_convert_incompatible) 76 << DeclType << Init->getType() << "initializing" 77 << Init->getSourceRange(); 78 return false; 79 } 80 81 Sema::AssignConvertType ConvTy = 82 S.CheckSingleAssignmentConstraints(DeclType, Init); 83 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType, 84 InitType, Init, "initializing"); 85 } 86 87 static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) { 88 // Get the length of the string as parsed. 89 uint64_t StrLength = 90 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue(); 91 92 93 const ArrayType *AT = S.Context.getAsArrayType(DeclT); 94 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 95 // C99 6.7.8p14. We have an array of character type with unknown size 96 // being initialized to a string literal. 97 llvm::APSInt ConstVal(32); 98 ConstVal = StrLength; 99 // Return a new array type (C99 6.7.8p22). 100 DeclT = S.Context.getConstantArrayWithoutExprType(IAT->getElementType(), 101 ConstVal, 102 ArrayType::Normal, 0); 103 return; 104 } 105 106 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); 107 108 // C99 6.7.8p14. We have an array of character type with known size. However, 109 // the size may be smaller or larger than the string we are initializing. 110 // FIXME: Avoid truncation for 64-bit length strings. 111 if (StrLength-1 > CAT->getSize().getZExtValue()) 112 S.Diag(Str->getSourceRange().getBegin(), 113 diag::warn_initializer_string_for_char_array_too_long) 114 << Str->getSourceRange(); 115 116 // Set the type to the actual size that we are initializing. If we have 117 // something like: 118 // char x[1] = "foo"; 119 // then this will set the string literal's type to char[1]. 120 Str->setType(DeclT); 121 } 122 123 bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType, 124 SourceLocation InitLoc, 125 DeclarationName InitEntity, bool DirectInit) { 126 if (DeclType->isDependentType() || 127 Init->isTypeDependent() || Init->isValueDependent()) 128 return false; 129 130 // C++ [dcl.init.ref]p1: 131 // A variable declared to be a T& or T&&, that is "reference to type T" 132 // (8.3.2), shall be initialized by an object, or function, of 133 // type T or by an object that can be converted into a T. 134 if (DeclType->isReferenceType()) 135 return CheckReferenceInit(Init, DeclType, 136 /*SuppressUserConversions=*/false, 137 /*AllowExplicit=*/DirectInit, 138 /*ForceRValue=*/false); 139 140 // C99 6.7.8p3: The type of the entity to be initialized shall be an array 141 // of unknown size ("[]") or an object type that is not a variable array type. 142 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType)) 143 return Diag(InitLoc, diag::err_variable_object_no_init) 144 << VAT->getSizeExpr()->getSourceRange(); 145 146 InitListExpr *InitList = dyn_cast<InitListExpr>(Init); 147 if (!InitList) { 148 // FIXME: Handle wide strings 149 if (Expr *Str = IsStringInit(Init, DeclType, Context)) { 150 CheckStringInit(Str, DeclType, *this); 151 return false; 152 } 153 154 // C++ [dcl.init]p14: 155 // -- If the destination type is a (possibly cv-qualified) class 156 // type: 157 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) { 158 QualType DeclTypeC = Context.getCanonicalType(DeclType); 159 QualType InitTypeC = Context.getCanonicalType(Init->getType()); 160 161 // -- If the initialization is direct-initialization, or if it is 162 // copy-initialization where the cv-unqualified version of the 163 // source type is the same class as, or a derived class of, the 164 // class of the destination, constructors are considered. 165 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) || 166 IsDerivedFrom(InitTypeC, DeclTypeC)) { 167 const CXXRecordDecl *RD = 168 cast<CXXRecordDecl>(DeclType->getAs<RecordType>()->getDecl()); 169 170 // No need to make a CXXConstructExpr if both the ctor and dtor are 171 // trivial. 172 if (RD->hasTrivialConstructor() && RD->hasTrivialDestructor()) 173 return false; 174 175 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 176 177 CXXConstructorDecl *Constructor 178 = PerformInitializationByConstructor(DeclType, 179 MultiExprArg(*this, 180 (void **)&Init, 1), 181 InitLoc, Init->getSourceRange(), 182 InitEntity, 183 DirectInit? IK_Direct : IK_Copy, 184 ConstructorArgs); 185 if (!Constructor) 186 return true; 187 188 OwningExprResult InitResult = 189 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 190 DeclType, Constructor, 191 move_arg(ConstructorArgs)); 192 if (InitResult.isInvalid()) 193 return true; 194 195 Init = InitResult.takeAs<Expr>(); 196 return false; 197 } 198 199 // -- Otherwise (i.e., for the remaining copy-initialization 200 // cases), user-defined conversion sequences that can 201 // convert from the source type to the destination type or 202 // (when a conversion function is used) to a derived class 203 // thereof are enumerated as described in 13.3.1.4, and the 204 // best one is chosen through overload resolution 205 // (13.3). If the conversion cannot be done or is 206 // ambiguous, the initialization is ill-formed. The 207 // function selected is called with the initializer 208 // expression as its argument; if the function is a 209 // constructor, the call initializes a temporary of the 210 // destination type. 211 // FIXME: We're pretending to do copy elision here; return to this when we 212 // have ASTs for such things. 213 if (!PerformImplicitConversion(Init, DeclType, "initializing")) 214 return false; 215 216 if (InitEntity) 217 return Diag(InitLoc, diag::err_cannot_initialize_decl) 218 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid) 219 << Init->getType() << Init->getSourceRange(); 220 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname) 221 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid) 222 << Init->getType() << Init->getSourceRange(); 223 } 224 225 // C99 6.7.8p16. 226 if (DeclType->isArrayType()) 227 return Diag(Init->getLocStart(), diag::err_array_init_list_required) 228 << Init->getSourceRange(); 229 230 return CheckSingleInitializer(Init, DeclType, DirectInit, *this); 231 } 232 233 bool hadError = CheckInitList(InitList, DeclType); 234 Init = InitList; 235 return hadError; 236 } 237 238 //===----------------------------------------------------------------------===// 239 // Semantic checking for initializer lists. 240 //===----------------------------------------------------------------------===// 241 242 /// @brief Semantic checking for initializer lists. 243 /// 244 /// The InitListChecker class contains a set of routines that each 245 /// handle the initialization of a certain kind of entity, e.g., 246 /// arrays, vectors, struct/union types, scalars, etc. The 247 /// InitListChecker itself performs a recursive walk of the subobject 248 /// structure of the type to be initialized, while stepping through 249 /// the initializer list one element at a time. The IList and Index 250 /// parameters to each of the Check* routines contain the active 251 /// (syntactic) initializer list and the index into that initializer 252 /// list that represents the current initializer. Each routine is 253 /// responsible for moving that Index forward as it consumes elements. 254 /// 255 /// Each Check* routine also has a StructuredList/StructuredIndex 256 /// arguments, which contains the current the "structured" (semantic) 257 /// initializer list and the index into that initializer list where we 258 /// are copying initializers as we map them over to the semantic 259 /// list. Once we have completed our recursive walk of the subobject 260 /// structure, we will have constructed a full semantic initializer 261 /// list. 262 /// 263 /// C99 designators cause changes in the initializer list traversal, 264 /// because they make the initialization "jump" into a specific 265 /// subobject and then continue the initialization from that 266 /// point. CheckDesignatedInitializer() recursively steps into the 267 /// designated subobject and manages backing out the recursion to 268 /// initialize the subobjects after the one designated. 269 namespace { 270 class InitListChecker { 271 Sema &SemaRef; 272 bool hadError; 273 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic; 274 InitListExpr *FullyStructuredList; 275 276 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T, 277 unsigned &Index, InitListExpr *StructuredList, 278 unsigned &StructuredIndex, 279 bool TopLevelObject = false); 280 void CheckExplicitInitList(InitListExpr *IList, QualType &T, 281 unsigned &Index, InitListExpr *StructuredList, 282 unsigned &StructuredIndex, 283 bool TopLevelObject = false); 284 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType, 285 bool SubobjectIsDesignatorContext, 286 unsigned &Index, 287 InitListExpr *StructuredList, 288 unsigned &StructuredIndex, 289 bool TopLevelObject = false); 290 void CheckSubElementType(InitListExpr *IList, QualType ElemType, 291 unsigned &Index, 292 InitListExpr *StructuredList, 293 unsigned &StructuredIndex); 294 void CheckScalarType(InitListExpr *IList, QualType DeclType, 295 unsigned &Index, 296 InitListExpr *StructuredList, 297 unsigned &StructuredIndex); 298 void CheckReferenceType(InitListExpr *IList, QualType DeclType, 299 unsigned &Index, 300 InitListExpr *StructuredList, 301 unsigned &StructuredIndex); 302 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index, 303 InitListExpr *StructuredList, 304 unsigned &StructuredIndex); 305 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType, 306 RecordDecl::field_iterator Field, 307 bool SubobjectIsDesignatorContext, unsigned &Index, 308 InitListExpr *StructuredList, 309 unsigned &StructuredIndex, 310 bool TopLevelObject = false); 311 void CheckArrayType(InitListExpr *IList, QualType &DeclType, 312 llvm::APSInt elementIndex, 313 bool SubobjectIsDesignatorContext, unsigned &Index, 314 InitListExpr *StructuredList, 315 unsigned &StructuredIndex); 316 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE, 317 unsigned DesigIdx, 318 QualType &CurrentObjectType, 319 RecordDecl::field_iterator *NextField, 320 llvm::APSInt *NextElementIndex, 321 unsigned &Index, 322 InitListExpr *StructuredList, 323 unsigned &StructuredIndex, 324 bool FinishSubobjectInit, 325 bool TopLevelObject); 326 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 327 QualType CurrentObjectType, 328 InitListExpr *StructuredList, 329 unsigned StructuredIndex, 330 SourceRange InitRange); 331 void UpdateStructuredListElement(InitListExpr *StructuredList, 332 unsigned &StructuredIndex, 333 Expr *expr); 334 int numArrayElements(QualType DeclType); 335 int numStructUnionElements(QualType DeclType); 336 337 void FillInValueInitializations(InitListExpr *ILE); 338 public: 339 InitListChecker(Sema &S, InitListExpr *IL, QualType &T); 340 bool HadError() { return hadError; } 341 342 // @brief Retrieves the fully-structured initializer list used for 343 // semantic analysis and code generation. 344 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; } 345 }; 346 } // end anonymous namespace 347 348 /// Recursively replaces NULL values within the given initializer list 349 /// with expressions that perform value-initialization of the 350 /// appropriate type. 351 void InitListChecker::FillInValueInitializations(InitListExpr *ILE) { 352 assert((ILE->getType() != SemaRef.Context.VoidTy) && 353 "Should not have void type"); 354 SourceLocation Loc = ILE->getSourceRange().getBegin(); 355 if (ILE->getSyntacticForm()) 356 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin(); 357 358 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { 359 unsigned Init = 0, NumInits = ILE->getNumInits(); 360 for (RecordDecl::field_iterator 361 Field = RType->getDecl()->field_begin(), 362 FieldEnd = RType->getDecl()->field_end(); 363 Field != FieldEnd; ++Field) { 364 if (Field->isUnnamedBitfield()) 365 continue; 366 367 if (Init >= NumInits || !ILE->getInit(Init)) { 368 if (Field->getType()->isReferenceType()) { 369 // C++ [dcl.init.aggr]p9: 370 // If an incomplete or empty initializer-list leaves a 371 // member of reference type uninitialized, the program is 372 // ill-formed. 373 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized) 374 << Field->getType() 375 << ILE->getSyntacticForm()->getSourceRange(); 376 SemaRef.Diag(Field->getLocation(), 377 diag::note_uninit_reference_member); 378 hadError = true; 379 return; 380 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) { 381 hadError = true; 382 return; 383 } 384 385 // FIXME: If value-initialization involves calling a constructor, should 386 // we make that call explicit in the representation (even when it means 387 // extending the initializer list)? 388 if (Init < NumInits && !hadError) 389 ILE->setInit(Init, 390 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType())); 391 } else if (InitListExpr *InnerILE 392 = dyn_cast<InitListExpr>(ILE->getInit(Init))) 393 FillInValueInitializations(InnerILE); 394 ++Init; 395 396 // Only look at the first initialization of a union. 397 if (RType->getDecl()->isUnion()) 398 break; 399 } 400 401 return; 402 } 403 404 QualType ElementType; 405 406 unsigned NumInits = ILE->getNumInits(); 407 unsigned NumElements = NumInits; 408 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) { 409 ElementType = AType->getElementType(); 410 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) 411 NumElements = CAType->getSize().getZExtValue(); 412 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) { 413 ElementType = VType->getElementType(); 414 NumElements = VType->getNumElements(); 415 } else 416 ElementType = ILE->getType(); 417 418 for (unsigned Init = 0; Init != NumElements; ++Init) { 419 if (Init >= NumInits || !ILE->getInit(Init)) { 420 if (SemaRef.CheckValueInitialization(ElementType, Loc)) { 421 hadError = true; 422 return; 423 } 424 425 // FIXME: If value-initialization involves calling a constructor, should 426 // we make that call explicit in the representation (even when it means 427 // extending the initializer list)? 428 if (Init < NumInits && !hadError) 429 ILE->setInit(Init, 430 new (SemaRef.Context) ImplicitValueInitExpr(ElementType)); 431 } else if (InitListExpr *InnerILE 432 = dyn_cast<InitListExpr>(ILE->getInit(Init))) 433 FillInValueInitializations(InnerILE); 434 } 435 } 436 437 438 InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T) 439 : SemaRef(S) { 440 hadError = false; 441 442 unsigned newIndex = 0; 443 unsigned newStructuredIndex = 0; 444 FullyStructuredList 445 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange()); 446 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex, 447 /*TopLevelObject=*/true); 448 449 if (!hadError) 450 FillInValueInitializations(FullyStructuredList); 451 } 452 453 int InitListChecker::numArrayElements(QualType DeclType) { 454 // FIXME: use a proper constant 455 int maxElements = 0x7FFFFFFF; 456 if (const ConstantArrayType *CAT = 457 SemaRef.Context.getAsConstantArrayType(DeclType)) { 458 maxElements = static_cast<int>(CAT->getSize().getZExtValue()); 459 } 460 return maxElements; 461 } 462 463 int InitListChecker::numStructUnionElements(QualType DeclType) { 464 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl(); 465 int InitializableMembers = 0; 466 for (RecordDecl::field_iterator 467 Field = structDecl->field_begin(), 468 FieldEnd = structDecl->field_end(); 469 Field != FieldEnd; ++Field) { 470 if ((*Field)->getIdentifier() || !(*Field)->isBitField()) 471 ++InitializableMembers; 472 } 473 if (structDecl->isUnion()) 474 return std::min(InitializableMembers, 1); 475 return InitializableMembers - structDecl->hasFlexibleArrayMember(); 476 } 477 478 void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList, 479 QualType T, unsigned &Index, 480 InitListExpr *StructuredList, 481 unsigned &StructuredIndex, 482 bool TopLevelObject) { 483 int maxElements = 0; 484 485 if (T->isArrayType()) 486 maxElements = numArrayElements(T); 487 else if (T->isStructureType() || T->isUnionType()) 488 maxElements = numStructUnionElements(T); 489 else if (T->isVectorType()) 490 maxElements = T->getAsVectorType()->getNumElements(); 491 else 492 assert(0 && "CheckImplicitInitList(): Illegal type"); 493 494 if (maxElements == 0) { 495 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(), 496 diag::err_implicit_empty_initializer); 497 ++Index; 498 hadError = true; 499 return; 500 } 501 502 // Build a structured initializer list corresponding to this subobject. 503 InitListExpr *StructuredSubobjectInitList 504 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList, 505 StructuredIndex, 506 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(), 507 ParentIList->getSourceRange().getEnd())); 508 unsigned StructuredSubobjectInitIndex = 0; 509 510 // Check the element types and build the structural subobject. 511 unsigned StartIndex = Index; 512 CheckListElementTypes(ParentIList, T, false, Index, 513 StructuredSubobjectInitList, 514 StructuredSubobjectInitIndex, 515 TopLevelObject); 516 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); 517 StructuredSubobjectInitList->setType(T); 518 519 // Update the structured sub-object initializer so that it's ending 520 // range corresponds with the end of the last initializer it used. 521 if (EndIndex < ParentIList->getNumInits()) { 522 SourceLocation EndLoc 523 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd(); 524 StructuredSubobjectInitList->setRBraceLoc(EndLoc); 525 } 526 } 527 528 void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T, 529 unsigned &Index, 530 InitListExpr *StructuredList, 531 unsigned &StructuredIndex, 532 bool TopLevelObject) { 533 assert(IList->isExplicit() && "Illegal Implicit InitListExpr"); 534 SyntacticToSemantic[IList] = StructuredList; 535 StructuredList->setSyntacticForm(IList); 536 CheckListElementTypes(IList, T, true, Index, StructuredList, 537 StructuredIndex, TopLevelObject); 538 IList->setType(T); 539 StructuredList->setType(T); 540 if (hadError) 541 return; 542 543 if (Index < IList->getNumInits()) { 544 // We have leftover initializers 545 if (StructuredIndex == 1 && 546 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) { 547 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer; 548 if (SemaRef.getLangOptions().CPlusPlus) { 549 DK = diag::err_excess_initializers_in_char_array_initializer; 550 hadError = true; 551 } 552 // Special-case 553 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) 554 << IList->getInit(Index)->getSourceRange(); 555 } else if (!T->isIncompleteType()) { 556 // Don't complain for incomplete types, since we'll get an error 557 // elsewhere 558 QualType CurrentObjectType = StructuredList->getType(); 559 int initKind = 560 CurrentObjectType->isArrayType()? 0 : 561 CurrentObjectType->isVectorType()? 1 : 562 CurrentObjectType->isScalarType()? 2 : 563 CurrentObjectType->isUnionType()? 3 : 564 4; 565 566 unsigned DK = diag::warn_excess_initializers; 567 if (SemaRef.getLangOptions().CPlusPlus) { 568 DK = diag::err_excess_initializers; 569 hadError = true; 570 } 571 if (SemaRef.getLangOptions().OpenCL && initKind == 1) { 572 DK = diag::err_excess_initializers; 573 hadError = true; 574 } 575 576 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) 577 << initKind << IList->getInit(Index)->getSourceRange(); 578 } 579 } 580 581 if (T->isScalarType() && !TopLevelObject) 582 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init) 583 << IList->getSourceRange() 584 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocStart())) 585 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocEnd())); 586 } 587 588 void InitListChecker::CheckListElementTypes(InitListExpr *IList, 589 QualType &DeclType, 590 bool SubobjectIsDesignatorContext, 591 unsigned &Index, 592 InitListExpr *StructuredList, 593 unsigned &StructuredIndex, 594 bool TopLevelObject) { 595 if (DeclType->isScalarType()) { 596 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex); 597 } else if (DeclType->isVectorType()) { 598 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex); 599 } else if (DeclType->isAggregateType()) { 600 if (DeclType->isRecordType()) { 601 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 602 CheckStructUnionTypes(IList, DeclType, RD->field_begin(), 603 SubobjectIsDesignatorContext, Index, 604 StructuredList, StructuredIndex, 605 TopLevelObject); 606 } else if (DeclType->isArrayType()) { 607 llvm::APSInt Zero( 608 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()), 609 false); 610 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index, 611 StructuredList, StructuredIndex); 612 } else 613 assert(0 && "Aggregate that isn't a structure or array?!"); 614 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { 615 // This type is invalid, issue a diagnostic. 616 ++Index; 617 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type) 618 << DeclType; 619 hadError = true; 620 } else if (DeclType->isRecordType()) { 621 // C++ [dcl.init]p14: 622 // [...] If the class is an aggregate (8.5.1), and the initializer 623 // is a brace-enclosed list, see 8.5.1. 624 // 625 // Note: 8.5.1 is handled below; here, we diagnose the case where 626 // we have an initializer list and a destination type that is not 627 // an aggregate. 628 // FIXME: In C++0x, this is yet another form of initialization. 629 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list) 630 << DeclType << IList->getSourceRange(); 631 hadError = true; 632 } else if (DeclType->isReferenceType()) { 633 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex); 634 } else { 635 // In C, all types are either scalars or aggregates, but 636 // additional handling is needed here for C++ (and possibly others?). 637 assert(0 && "Unsupported initializer type"); 638 } 639 } 640 641 void InitListChecker::CheckSubElementType(InitListExpr *IList, 642 QualType ElemType, 643 unsigned &Index, 644 InitListExpr *StructuredList, 645 unsigned &StructuredIndex) { 646 Expr *expr = IList->getInit(Index); 647 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { 648 unsigned newIndex = 0; 649 unsigned newStructuredIndex = 0; 650 InitListExpr *newStructuredList 651 = getStructuredSubobjectInit(IList, Index, ElemType, 652 StructuredList, StructuredIndex, 653 SubInitList->getSourceRange()); 654 CheckExplicitInitList(SubInitList, ElemType, newIndex, 655 newStructuredList, newStructuredIndex); 656 ++StructuredIndex; 657 ++Index; 658 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) { 659 CheckStringInit(Str, ElemType, SemaRef); 660 UpdateStructuredListElement(StructuredList, StructuredIndex, Str); 661 ++Index; 662 } else if (ElemType->isScalarType()) { 663 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex); 664 } else if (ElemType->isReferenceType()) { 665 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex); 666 } else { 667 if (SemaRef.getLangOptions().CPlusPlus) { 668 // C++ [dcl.init.aggr]p12: 669 // All implicit type conversions (clause 4) are considered when 670 // initializing the aggregate member with an ini- tializer from 671 // an initializer-list. If the initializer can initialize a 672 // member, the member is initialized. [...] 673 ImplicitConversionSequence ICS 674 = SemaRef.TryCopyInitialization(expr, ElemType, 675 /*SuppressUserConversions=*/false, 676 /*ForceRValue=*/false, 677 /*InOverloadResolution=*/false); 678 679 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) { 680 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS, 681 "initializing")) 682 hadError = true; 683 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 684 ++Index; 685 return; 686 } 687 688 // Fall through for subaggregate initialization 689 } else { 690 // C99 6.7.8p13: 691 // 692 // The initializer for a structure or union object that has 693 // automatic storage duration shall be either an initializer 694 // list as described below, or a single expression that has 695 // compatible structure or union type. In the latter case, the 696 // initial value of the object, including unnamed members, is 697 // that of the expression. 698 if ((ElemType->isRecordType() || ElemType->isVectorType()) && 699 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) { 700 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 701 ++Index; 702 return; 703 } 704 705 // Fall through for subaggregate initialization 706 } 707 708 // C++ [dcl.init.aggr]p12: 709 // 710 // [...] Otherwise, if the member is itself a non-empty 711 // subaggregate, brace elision is assumed and the initializer is 712 // considered for the initialization of the first member of 713 // the subaggregate. 714 if (ElemType->isAggregateType() || ElemType->isVectorType()) { 715 CheckImplicitInitList(IList, ElemType, Index, StructuredList, 716 StructuredIndex); 717 ++StructuredIndex; 718 } else { 719 // We cannot initialize this element, so let 720 // PerformCopyInitialization produce the appropriate diagnostic. 721 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing"); 722 hadError = true; 723 ++Index; 724 ++StructuredIndex; 725 } 726 } 727 } 728 729 void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType, 730 unsigned &Index, 731 InitListExpr *StructuredList, 732 unsigned &StructuredIndex) { 733 if (Index < IList->getNumInits()) { 734 Expr *expr = IList->getInit(Index); 735 if (isa<InitListExpr>(expr)) { 736 SemaRef.Diag(IList->getLocStart(), 737 diag::err_many_braces_around_scalar_init) 738 << IList->getSourceRange(); 739 hadError = true; 740 ++Index; 741 ++StructuredIndex; 742 return; 743 } else if (isa<DesignatedInitExpr>(expr)) { 744 SemaRef.Diag(expr->getSourceRange().getBegin(), 745 diag::err_designator_for_scalar_init) 746 << DeclType << expr->getSourceRange(); 747 hadError = true; 748 ++Index; 749 ++StructuredIndex; 750 return; 751 } 752 753 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer. 754 if (CheckSingleInitializer(expr, DeclType, false, SemaRef)) 755 hadError = true; // types weren't compatible. 756 else if (savExpr != expr) { 757 // The type was promoted, update initializer list. 758 IList->setInit(Index, expr); 759 } 760 if (hadError) 761 ++StructuredIndex; 762 else 763 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 764 ++Index; 765 } else { 766 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer) 767 << IList->getSourceRange(); 768 hadError = true; 769 ++Index; 770 ++StructuredIndex; 771 return; 772 } 773 } 774 775 void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType, 776 unsigned &Index, 777 InitListExpr *StructuredList, 778 unsigned &StructuredIndex) { 779 if (Index < IList->getNumInits()) { 780 Expr *expr = IList->getInit(Index); 781 if (isa<InitListExpr>(expr)) { 782 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list) 783 << DeclType << IList->getSourceRange(); 784 hadError = true; 785 ++Index; 786 ++StructuredIndex; 787 return; 788 } 789 790 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer. 791 if (SemaRef.CheckReferenceInit(expr, DeclType, 792 /*SuppressUserConversions=*/false, 793 /*AllowExplicit=*/false, 794 /*ForceRValue=*/false)) 795 hadError = true; 796 else if (savExpr != expr) { 797 // The type was promoted, update initializer list. 798 IList->setInit(Index, expr); 799 } 800 if (hadError) 801 ++StructuredIndex; 802 else 803 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 804 ++Index; 805 } else { 806 // FIXME: It would be wonderful if we could point at the actual member. In 807 // general, it would be useful to pass location information down the stack, 808 // so that we know the location (or decl) of the "current object" being 809 // initialized. 810 SemaRef.Diag(IList->getLocStart(), 811 diag::err_init_reference_member_uninitialized) 812 << DeclType 813 << IList->getSourceRange(); 814 hadError = true; 815 ++Index; 816 ++StructuredIndex; 817 return; 818 } 819 } 820 821 void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType, 822 unsigned &Index, 823 InitListExpr *StructuredList, 824 unsigned &StructuredIndex) { 825 if (Index < IList->getNumInits()) { 826 const VectorType *VT = DeclType->getAsVectorType(); 827 unsigned maxElements = VT->getNumElements(); 828 unsigned numEltsInit = 0; 829 QualType elementType = VT->getElementType(); 830 831 if (!SemaRef.getLangOptions().OpenCL) { 832 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) { 833 // Don't attempt to go past the end of the init list 834 if (Index >= IList->getNumInits()) 835 break; 836 CheckSubElementType(IList, elementType, Index, 837 StructuredList, StructuredIndex); 838 } 839 } else { 840 // OpenCL initializers allows vectors to be constructed from vectors. 841 for (unsigned i = 0; i < maxElements; ++i) { 842 // Don't attempt to go past the end of the init list 843 if (Index >= IList->getNumInits()) 844 break; 845 QualType IType = IList->getInit(Index)->getType(); 846 if (!IType->isVectorType()) { 847 CheckSubElementType(IList, elementType, Index, 848 StructuredList, StructuredIndex); 849 ++numEltsInit; 850 } else { 851 const VectorType *IVT = IType->getAsVectorType(); 852 unsigned numIElts = IVT->getNumElements(); 853 QualType VecType = SemaRef.Context.getExtVectorType(elementType, 854 numIElts); 855 CheckSubElementType(IList, VecType, Index, 856 StructuredList, StructuredIndex); 857 numEltsInit += numIElts; 858 } 859 } 860 } 861 862 // OpenCL & AltiVec require all elements to be initialized. 863 if (numEltsInit != maxElements) 864 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec) 865 SemaRef.Diag(IList->getSourceRange().getBegin(), 866 diag::err_vector_incorrect_num_initializers) 867 << (numEltsInit < maxElements) << maxElements << numEltsInit; 868 } 869 } 870 871 void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType, 872 llvm::APSInt elementIndex, 873 bool SubobjectIsDesignatorContext, 874 unsigned &Index, 875 InitListExpr *StructuredList, 876 unsigned &StructuredIndex) { 877 // Check for the special-case of initializing an array with a string. 878 if (Index < IList->getNumInits()) { 879 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType, 880 SemaRef.Context)) { 881 CheckStringInit(Str, DeclType, SemaRef); 882 // We place the string literal directly into the resulting 883 // initializer list. This is the only place where the structure 884 // of the structured initializer list doesn't match exactly, 885 // because doing so would involve allocating one character 886 // constant for each string. 887 UpdateStructuredListElement(StructuredList, StructuredIndex, Str); 888 StructuredList->resizeInits(SemaRef.Context, StructuredIndex); 889 ++Index; 890 return; 891 } 892 } 893 if (const VariableArrayType *VAT = 894 SemaRef.Context.getAsVariableArrayType(DeclType)) { 895 // Check for VLAs; in standard C it would be possible to check this 896 // earlier, but I don't know where clang accepts VLAs (gcc accepts 897 // them in all sorts of strange places). 898 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(), 899 diag::err_variable_object_no_init) 900 << VAT->getSizeExpr()->getSourceRange(); 901 hadError = true; 902 ++Index; 903 ++StructuredIndex; 904 return; 905 } 906 907 // We might know the maximum number of elements in advance. 908 llvm::APSInt maxElements(elementIndex.getBitWidth(), 909 elementIndex.isUnsigned()); 910 bool maxElementsKnown = false; 911 if (const ConstantArrayType *CAT = 912 SemaRef.Context.getAsConstantArrayType(DeclType)) { 913 maxElements = CAT->getSize(); 914 elementIndex.extOrTrunc(maxElements.getBitWidth()); 915 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 916 maxElementsKnown = true; 917 } 918 919 QualType elementType = SemaRef.Context.getAsArrayType(DeclType) 920 ->getElementType(); 921 while (Index < IList->getNumInits()) { 922 Expr *Init = IList->getInit(Index); 923 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 924 // If we're not the subobject that matches up with the '{' for 925 // the designator, we shouldn't be handling the 926 // designator. Return immediately. 927 if (!SubobjectIsDesignatorContext) 928 return; 929 930 // Handle this designated initializer. elementIndex will be 931 // updated to be the next array element we'll initialize. 932 if (CheckDesignatedInitializer(IList, DIE, 0, 933 DeclType, 0, &elementIndex, Index, 934 StructuredList, StructuredIndex, true, 935 false)) { 936 hadError = true; 937 continue; 938 } 939 940 if (elementIndex.getBitWidth() > maxElements.getBitWidth()) 941 maxElements.extend(elementIndex.getBitWidth()); 942 else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) 943 elementIndex.extend(maxElements.getBitWidth()); 944 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 945 946 // If the array is of incomplete type, keep track of the number of 947 // elements in the initializer. 948 if (!maxElementsKnown && elementIndex > maxElements) 949 maxElements = elementIndex; 950 951 continue; 952 } 953 954 // If we know the maximum number of elements, and we've already 955 // hit it, stop consuming elements in the initializer list. 956 if (maxElementsKnown && elementIndex == maxElements) 957 break; 958 959 // Check this element. 960 CheckSubElementType(IList, elementType, Index, 961 StructuredList, StructuredIndex); 962 ++elementIndex; 963 964 // If the array is of incomplete type, keep track of the number of 965 // elements in the initializer. 966 if (!maxElementsKnown && elementIndex > maxElements) 967 maxElements = elementIndex; 968 } 969 if (!hadError && DeclType->isIncompleteArrayType()) { 970 // If this is an incomplete array type, the actual type needs to 971 // be calculated here. 972 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); 973 if (maxElements == Zero) { 974 // Sizing an array implicitly to zero is not allowed by ISO C, 975 // but is supported by GNU. 976 SemaRef.Diag(IList->getLocStart(), 977 diag::ext_typecheck_zero_array_size); 978 } 979 980 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements, 981 ArrayType::Normal, 0); 982 } 983 } 984 985 void InitListChecker::CheckStructUnionTypes(InitListExpr *IList, 986 QualType DeclType, 987 RecordDecl::field_iterator Field, 988 bool SubobjectIsDesignatorContext, 989 unsigned &Index, 990 InitListExpr *StructuredList, 991 unsigned &StructuredIndex, 992 bool TopLevelObject) { 993 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl(); 994 995 // If the record is invalid, some of it's members are invalid. To avoid 996 // confusion, we forgo checking the intializer for the entire record. 997 if (structDecl->isInvalidDecl()) { 998 hadError = true; 999 return; 1000 } 1001 1002 if (DeclType->isUnionType() && IList->getNumInits() == 0) { 1003 // Value-initialize the first named member of the union. 1004 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 1005 for (RecordDecl::field_iterator FieldEnd = RD->field_end(); 1006 Field != FieldEnd; ++Field) { 1007 if (Field->getDeclName()) { 1008 StructuredList->setInitializedFieldInUnion(*Field); 1009 break; 1010 } 1011 } 1012 return; 1013 } 1014 1015 // If structDecl is a forward declaration, this loop won't do 1016 // anything except look at designated initializers; That's okay, 1017 // because an error should get printed out elsewhere. It might be 1018 // worthwhile to skip over the rest of the initializer, though. 1019 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 1020 RecordDecl::field_iterator FieldEnd = RD->field_end(); 1021 bool InitializedSomething = false; 1022 while (Index < IList->getNumInits()) { 1023 Expr *Init = IList->getInit(Index); 1024 1025 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 1026 // If we're not the subobject that matches up with the '{' for 1027 // the designator, we shouldn't be handling the 1028 // designator. Return immediately. 1029 if (!SubobjectIsDesignatorContext) 1030 return; 1031 1032 // Handle this designated initializer. Field will be updated to 1033 // the next field that we'll be initializing. 1034 if (CheckDesignatedInitializer(IList, DIE, 0, 1035 DeclType, &Field, 0, Index, 1036 StructuredList, StructuredIndex, 1037 true, TopLevelObject)) 1038 hadError = true; 1039 1040 InitializedSomething = true; 1041 continue; 1042 } 1043 1044 if (Field == FieldEnd) { 1045 // We've run out of fields. We're done. 1046 break; 1047 } 1048 1049 // We've already initialized a member of a union. We're done. 1050 if (InitializedSomething && DeclType->isUnionType()) 1051 break; 1052 1053 // If we've hit the flexible array member at the end, we're done. 1054 if (Field->getType()->isIncompleteArrayType()) 1055 break; 1056 1057 if (Field->isUnnamedBitfield()) { 1058 // Don't initialize unnamed bitfields, e.g. "int : 20;" 1059 ++Field; 1060 continue; 1061 } 1062 1063 CheckSubElementType(IList, Field->getType(), Index, 1064 StructuredList, StructuredIndex); 1065 InitializedSomething = true; 1066 1067 if (DeclType->isUnionType()) { 1068 // Initialize the first field within the union. 1069 StructuredList->setInitializedFieldInUnion(*Field); 1070 } 1071 1072 ++Field; 1073 } 1074 1075 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || 1076 Index >= IList->getNumInits()) 1077 return; 1078 1079 // Handle GNU flexible array initializers. 1080 if (!TopLevelObject && 1081 (!isa<InitListExpr>(IList->getInit(Index)) || 1082 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) { 1083 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(), 1084 diag::err_flexible_array_init_nonempty) 1085 << IList->getInit(Index)->getSourceRange().getBegin(); 1086 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1087 << *Field; 1088 hadError = true; 1089 ++Index; 1090 return; 1091 } else { 1092 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(), 1093 diag::ext_flexible_array_init) 1094 << IList->getInit(Index)->getSourceRange().getBegin(); 1095 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1096 << *Field; 1097 } 1098 1099 if (isa<InitListExpr>(IList->getInit(Index))) 1100 CheckSubElementType(IList, Field->getType(), Index, StructuredList, 1101 StructuredIndex); 1102 else 1103 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList, 1104 StructuredIndex); 1105 } 1106 1107 /// \brief Expand a field designator that refers to a member of an 1108 /// anonymous struct or union into a series of field designators that 1109 /// refers to the field within the appropriate subobject. 1110 /// 1111 /// Field/FieldIndex will be updated to point to the (new) 1112 /// currently-designated field. 1113 static void ExpandAnonymousFieldDesignator(Sema &SemaRef, 1114 DesignatedInitExpr *DIE, 1115 unsigned DesigIdx, 1116 FieldDecl *Field, 1117 RecordDecl::field_iterator &FieldIter, 1118 unsigned &FieldIndex) { 1119 typedef DesignatedInitExpr::Designator Designator; 1120 1121 // Build the path from the current object to the member of the 1122 // anonymous struct/union (backwards). 1123 llvm::SmallVector<FieldDecl *, 4> Path; 1124 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path); 1125 1126 // Build the replacement designators. 1127 llvm::SmallVector<Designator, 4> Replacements; 1128 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator 1129 FI = Path.rbegin(), FIEnd = Path.rend(); 1130 FI != FIEnd; ++FI) { 1131 if (FI + 1 == FIEnd) 1132 Replacements.push_back(Designator((IdentifierInfo *)0, 1133 DIE->getDesignator(DesigIdx)->getDotLoc(), 1134 DIE->getDesignator(DesigIdx)->getFieldLoc())); 1135 else 1136 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(), 1137 SourceLocation())); 1138 Replacements.back().setField(*FI); 1139 } 1140 1141 // Expand the current designator into the set of replacement 1142 // designators, so we have a full subobject path down to where the 1143 // member of the anonymous struct/union is actually stored. 1144 DIE->ExpandDesignator(DesigIdx, &Replacements[0], 1145 &Replacements[0] + Replacements.size()); 1146 1147 // Update FieldIter/FieldIndex; 1148 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext()); 1149 FieldIter = Record->field_begin(); 1150 FieldIndex = 0; 1151 for (RecordDecl::field_iterator FEnd = Record->field_end(); 1152 FieldIter != FEnd; ++FieldIter) { 1153 if (FieldIter->isUnnamedBitfield()) 1154 continue; 1155 1156 if (*FieldIter == Path.back()) 1157 return; 1158 1159 ++FieldIndex; 1160 } 1161 1162 assert(false && "Unable to find anonymous struct/union field"); 1163 } 1164 1165 /// @brief Check the well-formedness of a C99 designated initializer. 1166 /// 1167 /// Determines whether the designated initializer @p DIE, which 1168 /// resides at the given @p Index within the initializer list @p 1169 /// IList, is well-formed for a current object of type @p DeclType 1170 /// (C99 6.7.8). The actual subobject that this designator refers to 1171 /// within the current subobject is returned in either 1172 /// @p NextField or @p NextElementIndex (whichever is appropriate). 1173 /// 1174 /// @param IList The initializer list in which this designated 1175 /// initializer occurs. 1176 /// 1177 /// @param DIE The designated initializer expression. 1178 /// 1179 /// @param DesigIdx The index of the current designator. 1180 /// 1181 /// @param DeclType The type of the "current object" (C99 6.7.8p17), 1182 /// into which the designation in @p DIE should refer. 1183 /// 1184 /// @param NextField If non-NULL and the first designator in @p DIE is 1185 /// a field, this will be set to the field declaration corresponding 1186 /// to the field named by the designator. 1187 /// 1188 /// @param NextElementIndex If non-NULL and the first designator in @p 1189 /// DIE is an array designator or GNU array-range designator, this 1190 /// will be set to the last index initialized by this designator. 1191 /// 1192 /// @param Index Index into @p IList where the designated initializer 1193 /// @p DIE occurs. 1194 /// 1195 /// @param StructuredList The initializer list expression that 1196 /// describes all of the subobject initializers in the order they'll 1197 /// actually be initialized. 1198 /// 1199 /// @returns true if there was an error, false otherwise. 1200 bool 1201 InitListChecker::CheckDesignatedInitializer(InitListExpr *IList, 1202 DesignatedInitExpr *DIE, 1203 unsigned DesigIdx, 1204 QualType &CurrentObjectType, 1205 RecordDecl::field_iterator *NextField, 1206 llvm::APSInt *NextElementIndex, 1207 unsigned &Index, 1208 InitListExpr *StructuredList, 1209 unsigned &StructuredIndex, 1210 bool FinishSubobjectInit, 1211 bool TopLevelObject) { 1212 if (DesigIdx == DIE->size()) { 1213 // Check the actual initialization for the designated object type. 1214 bool prevHadError = hadError; 1215 1216 // Temporarily remove the designator expression from the 1217 // initializer list that the child calls see, so that we don't try 1218 // to re-process the designator. 1219 unsigned OldIndex = Index; 1220 IList->setInit(OldIndex, DIE->getInit()); 1221 1222 CheckSubElementType(IList, CurrentObjectType, Index, 1223 StructuredList, StructuredIndex); 1224 1225 // Restore the designated initializer expression in the syntactic 1226 // form of the initializer list. 1227 if (IList->getInit(OldIndex) != DIE->getInit()) 1228 DIE->setInit(IList->getInit(OldIndex)); 1229 IList->setInit(OldIndex, DIE); 1230 1231 return hadError && !prevHadError; 1232 } 1233 1234 bool IsFirstDesignator = (DesigIdx == 0); 1235 assert((IsFirstDesignator || StructuredList) && 1236 "Need a non-designated initializer list to start from"); 1237 1238 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx); 1239 // Determine the structural initializer list that corresponds to the 1240 // current subobject. 1241 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList] 1242 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, 1243 StructuredList, StructuredIndex, 1244 SourceRange(D->getStartLocation(), 1245 DIE->getSourceRange().getEnd())); 1246 assert(StructuredList && "Expected a structured initializer list"); 1247 1248 if (D->isFieldDesignator()) { 1249 // C99 6.7.8p7: 1250 // 1251 // If a designator has the form 1252 // 1253 // . identifier 1254 // 1255 // then the current object (defined below) shall have 1256 // structure or union type and the identifier shall be the 1257 // name of a member of that type. 1258 const RecordType *RT = CurrentObjectType->getAs<RecordType>(); 1259 if (!RT) { 1260 SourceLocation Loc = D->getDotLoc(); 1261 if (Loc.isInvalid()) 1262 Loc = D->getFieldLoc(); 1263 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr) 1264 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType; 1265 ++Index; 1266 return true; 1267 } 1268 1269 // Note: we perform a linear search of the fields here, despite 1270 // the fact that we have a faster lookup method, because we always 1271 // need to compute the field's index. 1272 FieldDecl *KnownField = D->getField(); 1273 IdentifierInfo *FieldName = D->getFieldName(); 1274 unsigned FieldIndex = 0; 1275 RecordDecl::field_iterator 1276 Field = RT->getDecl()->field_begin(), 1277 FieldEnd = RT->getDecl()->field_end(); 1278 for (; Field != FieldEnd; ++Field) { 1279 if (Field->isUnnamedBitfield()) 1280 continue; 1281 1282 if (KnownField == *Field || Field->getIdentifier() == FieldName) 1283 break; 1284 1285 ++FieldIndex; 1286 } 1287 1288 if (Field == FieldEnd) { 1289 // There was no normal field in the struct with the designated 1290 // name. Perform another lookup for this name, which may find 1291 // something that we can't designate (e.g., a member function), 1292 // may find nothing, or may find a member of an anonymous 1293 // struct/union. 1294 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName); 1295 if (Lookup.first == Lookup.second) { 1296 // Name lookup didn't find anything. 1297 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown) 1298 << FieldName << CurrentObjectType; 1299 ++Index; 1300 return true; 1301 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) && 1302 cast<RecordDecl>((*Lookup.first)->getDeclContext()) 1303 ->isAnonymousStructOrUnion()) { 1304 // Handle an field designator that refers to a member of an 1305 // anonymous struct or union. 1306 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, 1307 cast<FieldDecl>(*Lookup.first), 1308 Field, FieldIndex); 1309 D = DIE->getDesignator(DesigIdx); 1310 } else { 1311 // Name lookup found something, but it wasn't a field. 1312 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield) 1313 << FieldName; 1314 SemaRef.Diag((*Lookup.first)->getLocation(), 1315 diag::note_field_designator_found); 1316 ++Index; 1317 return true; 1318 } 1319 } else if (!KnownField && 1320 cast<RecordDecl>((*Field)->getDeclContext()) 1321 ->isAnonymousStructOrUnion()) { 1322 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field, 1323 Field, FieldIndex); 1324 D = DIE->getDesignator(DesigIdx); 1325 } 1326 1327 // All of the fields of a union are located at the same place in 1328 // the initializer list. 1329 if (RT->getDecl()->isUnion()) { 1330 FieldIndex = 0; 1331 StructuredList->setInitializedFieldInUnion(*Field); 1332 } 1333 1334 // Update the designator with the field declaration. 1335 D->setField(*Field); 1336 1337 // Make sure that our non-designated initializer list has space 1338 // for a subobject corresponding to this field. 1339 if (FieldIndex >= StructuredList->getNumInits()) 1340 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1); 1341 1342 // This designator names a flexible array member. 1343 if (Field->getType()->isIncompleteArrayType()) { 1344 bool Invalid = false; 1345 if ((DesigIdx + 1) != DIE->size()) { 1346 // We can't designate an object within the flexible array 1347 // member (because GCC doesn't allow it). 1348 DesignatedInitExpr::Designator *NextD 1349 = DIE->getDesignator(DesigIdx + 1); 1350 SemaRef.Diag(NextD->getStartLocation(), 1351 diag::err_designator_into_flexible_array_member) 1352 << SourceRange(NextD->getStartLocation(), 1353 DIE->getSourceRange().getEnd()); 1354 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1355 << *Field; 1356 Invalid = true; 1357 } 1358 1359 if (!hadError && !isa<InitListExpr>(DIE->getInit())) { 1360 // The initializer is not an initializer list. 1361 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(), 1362 diag::err_flexible_array_init_needs_braces) 1363 << DIE->getInit()->getSourceRange(); 1364 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1365 << *Field; 1366 Invalid = true; 1367 } 1368 1369 // Handle GNU flexible array initializers. 1370 if (!Invalid && !TopLevelObject && 1371 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) { 1372 SemaRef.Diag(DIE->getSourceRange().getBegin(), 1373 diag::err_flexible_array_init_nonempty) 1374 << DIE->getSourceRange().getBegin(); 1375 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1376 << *Field; 1377 Invalid = true; 1378 } 1379 1380 if (Invalid) { 1381 ++Index; 1382 return true; 1383 } 1384 1385 // Initialize the array. 1386 bool prevHadError = hadError; 1387 unsigned newStructuredIndex = FieldIndex; 1388 unsigned OldIndex = Index; 1389 IList->setInit(Index, DIE->getInit()); 1390 CheckSubElementType(IList, Field->getType(), Index, 1391 StructuredList, newStructuredIndex); 1392 IList->setInit(OldIndex, DIE); 1393 if (hadError && !prevHadError) { 1394 ++Field; 1395 ++FieldIndex; 1396 if (NextField) 1397 *NextField = Field; 1398 StructuredIndex = FieldIndex; 1399 return true; 1400 } 1401 } else { 1402 // Recurse to check later designated subobjects. 1403 QualType FieldType = (*Field)->getType(); 1404 unsigned newStructuredIndex = FieldIndex; 1405 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0, 1406 Index, StructuredList, newStructuredIndex, 1407 true, false)) 1408 return true; 1409 } 1410 1411 // Find the position of the next field to be initialized in this 1412 // subobject. 1413 ++Field; 1414 ++FieldIndex; 1415 1416 // If this the first designator, our caller will continue checking 1417 // the rest of this struct/class/union subobject. 1418 if (IsFirstDesignator) { 1419 if (NextField) 1420 *NextField = Field; 1421 StructuredIndex = FieldIndex; 1422 return false; 1423 } 1424 1425 if (!FinishSubobjectInit) 1426 return false; 1427 1428 // We've already initialized something in the union; we're done. 1429 if (RT->getDecl()->isUnion()) 1430 return hadError; 1431 1432 // Check the remaining fields within this class/struct/union subobject. 1433 bool prevHadError = hadError; 1434 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index, 1435 StructuredList, FieldIndex); 1436 return hadError && !prevHadError; 1437 } 1438 1439 // C99 6.7.8p6: 1440 // 1441 // If a designator has the form 1442 // 1443 // [ constant-expression ] 1444 // 1445 // then the current object (defined below) shall have array 1446 // type and the expression shall be an integer constant 1447 // expression. If the array is of unknown size, any 1448 // nonnegative value is valid. 1449 // 1450 // Additionally, cope with the GNU extension that permits 1451 // designators of the form 1452 // 1453 // [ constant-expression ... constant-expression ] 1454 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType); 1455 if (!AT) { 1456 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array) 1457 << CurrentObjectType; 1458 ++Index; 1459 return true; 1460 } 1461 1462 Expr *IndexExpr = 0; 1463 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; 1464 if (D->isArrayDesignator()) { 1465 IndexExpr = DIE->getArrayIndex(*D); 1466 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context); 1467 DesignatedEndIndex = DesignatedStartIndex; 1468 } else { 1469 assert(D->isArrayRangeDesignator() && "Need array-range designator"); 1470 1471 1472 DesignatedStartIndex = 1473 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context); 1474 DesignatedEndIndex = 1475 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context); 1476 IndexExpr = DIE->getArrayRangeEnd(*D); 1477 1478 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue()) 1479 FullyStructuredList->sawArrayRangeDesignator(); 1480 } 1481 1482 if (isa<ConstantArrayType>(AT)) { 1483 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false); 1484 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth()); 1485 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); 1486 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth()); 1487 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); 1488 if (DesignatedEndIndex >= MaxElements) { 1489 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(), 1490 diag::err_array_designator_too_large) 1491 << DesignatedEndIndex.toString(10) << MaxElements.toString(10) 1492 << IndexExpr->getSourceRange(); 1493 ++Index; 1494 return true; 1495 } 1496 } else { 1497 // Make sure the bit-widths and signedness match. 1498 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth()) 1499 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth()); 1500 else if (DesignatedStartIndex.getBitWidth() < 1501 DesignatedEndIndex.getBitWidth()) 1502 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth()); 1503 DesignatedStartIndex.setIsUnsigned(true); 1504 DesignatedEndIndex.setIsUnsigned(true); 1505 } 1506 1507 // Make sure that our non-designated initializer list has space 1508 // for a subobject corresponding to this array element. 1509 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) 1510 StructuredList->resizeInits(SemaRef.Context, 1511 DesignatedEndIndex.getZExtValue() + 1); 1512 1513 // Repeatedly perform subobject initializations in the range 1514 // [DesignatedStartIndex, DesignatedEndIndex]. 1515 1516 // Move to the next designator 1517 unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); 1518 unsigned OldIndex = Index; 1519 while (DesignatedStartIndex <= DesignatedEndIndex) { 1520 // Recurse to check later designated subobjects. 1521 QualType ElementType = AT->getElementType(); 1522 Index = OldIndex; 1523 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0, 1524 Index, StructuredList, ElementIndex, 1525 (DesignatedStartIndex == DesignatedEndIndex), 1526 false)) 1527 return true; 1528 1529 // Move to the next index in the array that we'll be initializing. 1530 ++DesignatedStartIndex; 1531 ElementIndex = DesignatedStartIndex.getZExtValue(); 1532 } 1533 1534 // If this the first designator, our caller will continue checking 1535 // the rest of this array subobject. 1536 if (IsFirstDesignator) { 1537 if (NextElementIndex) 1538 *NextElementIndex = DesignatedStartIndex; 1539 StructuredIndex = ElementIndex; 1540 return false; 1541 } 1542 1543 if (!FinishSubobjectInit) 1544 return false; 1545 1546 // Check the remaining elements within this array subobject. 1547 bool prevHadError = hadError; 1548 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index, 1549 StructuredList, ElementIndex); 1550 return hadError && !prevHadError; 1551 } 1552 1553 // Get the structured initializer list for a subobject of type 1554 // @p CurrentObjectType. 1555 InitListExpr * 1556 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 1557 QualType CurrentObjectType, 1558 InitListExpr *StructuredList, 1559 unsigned StructuredIndex, 1560 SourceRange InitRange) { 1561 Expr *ExistingInit = 0; 1562 if (!StructuredList) 1563 ExistingInit = SyntacticToSemantic[IList]; 1564 else if (StructuredIndex < StructuredList->getNumInits()) 1565 ExistingInit = StructuredList->getInit(StructuredIndex); 1566 1567 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit)) 1568 return Result; 1569 1570 if (ExistingInit) { 1571 // We are creating an initializer list that initializes the 1572 // subobjects of the current object, but there was already an 1573 // initialization that completely initialized the current 1574 // subobject, e.g., by a compound literal: 1575 // 1576 // struct X { int a, b; }; 1577 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; 1578 // 1579 // Here, xs[0].a == 0 and xs[0].b == 3, since the second, 1580 // designated initializer re-initializes the whole 1581 // subobject [0], overwriting previous initializers. 1582 SemaRef.Diag(InitRange.getBegin(), 1583 diag::warn_subobject_initializer_overrides) 1584 << InitRange; 1585 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(), 1586 diag::note_previous_initializer) 1587 << /*FIXME:has side effects=*/0 1588 << ExistingInit->getSourceRange(); 1589 } 1590 1591 InitListExpr *Result 1592 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0, 1593 InitRange.getEnd()); 1594 1595 Result->setType(CurrentObjectType); 1596 1597 // Pre-allocate storage for the structured initializer list. 1598 unsigned NumElements = 0; 1599 unsigned NumInits = 0; 1600 if (!StructuredList) 1601 NumInits = IList->getNumInits(); 1602 else if (Index < IList->getNumInits()) { 1603 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) 1604 NumInits = SubList->getNumInits(); 1605 } 1606 1607 if (const ArrayType *AType 1608 = SemaRef.Context.getAsArrayType(CurrentObjectType)) { 1609 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) { 1610 NumElements = CAType->getSize().getZExtValue(); 1611 // Simple heuristic so that we don't allocate a very large 1612 // initializer with many empty entries at the end. 1613 if (NumInits && NumElements > NumInits) 1614 NumElements = 0; 1615 } 1616 } else if (const VectorType *VType = CurrentObjectType->getAsVectorType()) 1617 NumElements = VType->getNumElements(); 1618 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) { 1619 RecordDecl *RDecl = RType->getDecl(); 1620 if (RDecl->isUnion()) 1621 NumElements = 1; 1622 else 1623 NumElements = std::distance(RDecl->field_begin(), 1624 RDecl->field_end()); 1625 } 1626 1627 if (NumElements < NumInits) 1628 NumElements = IList->getNumInits(); 1629 1630 Result->reserveInits(NumElements); 1631 1632 // Link this new initializer list into the structured initializer 1633 // lists. 1634 if (StructuredList) 1635 StructuredList->updateInit(StructuredIndex, Result); 1636 else { 1637 Result->setSyntacticForm(IList); 1638 SyntacticToSemantic[IList] = Result; 1639 } 1640 1641 return Result; 1642 } 1643 1644 /// Update the initializer at index @p StructuredIndex within the 1645 /// structured initializer list to the value @p expr. 1646 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, 1647 unsigned &StructuredIndex, 1648 Expr *expr) { 1649 // No structured initializer list to update 1650 if (!StructuredList) 1651 return; 1652 1653 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) { 1654 // This initializer overwrites a previous initializer. Warn. 1655 SemaRef.Diag(expr->getSourceRange().getBegin(), 1656 diag::warn_initializer_overrides) 1657 << expr->getSourceRange(); 1658 SemaRef.Diag(PrevInit->getSourceRange().getBegin(), 1659 diag::note_previous_initializer) 1660 << /*FIXME:has side effects=*/0 1661 << PrevInit->getSourceRange(); 1662 } 1663 1664 ++StructuredIndex; 1665 } 1666 1667 /// Check that the given Index expression is a valid array designator 1668 /// value. This is essentailly just a wrapper around 1669 /// VerifyIntegerConstantExpression that also checks for negative values 1670 /// and produces a reasonable diagnostic if there is a 1671 /// failure. Returns true if there was an error, false otherwise. If 1672 /// everything went okay, Value will receive the value of the constant 1673 /// expression. 1674 static bool 1675 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { 1676 SourceLocation Loc = Index->getSourceRange().getBegin(); 1677 1678 // Make sure this is an integer constant expression. 1679 if (S.VerifyIntegerConstantExpression(Index, &Value)) 1680 return true; 1681 1682 if (Value.isSigned() && Value.isNegative()) 1683 return S.Diag(Loc, diag::err_array_designator_negative) 1684 << Value.toString(10) << Index->getSourceRange(); 1685 1686 Value.setIsUnsigned(true); 1687 return false; 1688 } 1689 1690 Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, 1691 SourceLocation Loc, 1692 bool GNUSyntax, 1693 OwningExprResult Init) { 1694 typedef DesignatedInitExpr::Designator ASTDesignator; 1695 1696 bool Invalid = false; 1697 llvm::SmallVector<ASTDesignator, 32> Designators; 1698 llvm::SmallVector<Expr *, 32> InitExpressions; 1699 1700 // Build designators and check array designator expressions. 1701 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { 1702 const Designator &D = Desig.getDesignator(Idx); 1703 switch (D.getKind()) { 1704 case Designator::FieldDesignator: 1705 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(), 1706 D.getFieldLoc())); 1707 break; 1708 1709 case Designator::ArrayDesignator: { 1710 Expr *Index = static_cast<Expr *>(D.getArrayIndex()); 1711 llvm::APSInt IndexValue; 1712 if (!Index->isTypeDependent() && 1713 !Index->isValueDependent() && 1714 CheckArrayDesignatorExpr(*this, Index, IndexValue)) 1715 Invalid = true; 1716 else { 1717 Designators.push_back(ASTDesignator(InitExpressions.size(), 1718 D.getLBracketLoc(), 1719 D.getRBracketLoc())); 1720 InitExpressions.push_back(Index); 1721 } 1722 break; 1723 } 1724 1725 case Designator::ArrayRangeDesignator: { 1726 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); 1727 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); 1728 llvm::APSInt StartValue; 1729 llvm::APSInt EndValue; 1730 bool StartDependent = StartIndex->isTypeDependent() || 1731 StartIndex->isValueDependent(); 1732 bool EndDependent = EndIndex->isTypeDependent() || 1733 EndIndex->isValueDependent(); 1734 if ((!StartDependent && 1735 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) || 1736 (!EndDependent && 1737 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))) 1738 Invalid = true; 1739 else { 1740 // Make sure we're comparing values with the same bit width. 1741 if (StartDependent || EndDependent) { 1742 // Nothing to compute. 1743 } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) 1744 EndValue.extend(StartValue.getBitWidth()); 1745 else if (StartValue.getBitWidth() < EndValue.getBitWidth()) 1746 StartValue.extend(EndValue.getBitWidth()); 1747 1748 if (!StartDependent && !EndDependent && EndValue < StartValue) { 1749 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) 1750 << StartValue.toString(10) << EndValue.toString(10) 1751 << StartIndex->getSourceRange() << EndIndex->getSourceRange(); 1752 Invalid = true; 1753 } else { 1754 Designators.push_back(ASTDesignator(InitExpressions.size(), 1755 D.getLBracketLoc(), 1756 D.getEllipsisLoc(), 1757 D.getRBracketLoc())); 1758 InitExpressions.push_back(StartIndex); 1759 InitExpressions.push_back(EndIndex); 1760 } 1761 } 1762 break; 1763 } 1764 } 1765 } 1766 1767 if (Invalid || Init.isInvalid()) 1768 return ExprError(); 1769 1770 // Clear out the expressions within the designation. 1771 Desig.ClearExprs(*this); 1772 1773 DesignatedInitExpr *DIE 1774 = DesignatedInitExpr::Create(Context, 1775 Designators.data(), Designators.size(), 1776 InitExpressions.data(), InitExpressions.size(), 1777 Loc, GNUSyntax, Init.takeAs<Expr>()); 1778 return Owned(DIE); 1779 } 1780 1781 bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) { 1782 InitListChecker CheckInitList(*this, InitList, DeclType); 1783 if (!CheckInitList.HadError()) 1784 InitList = CheckInitList.getFullyStructuredList(); 1785 1786 return CheckInitList.HadError(); 1787 } 1788 1789 /// \brief Diagnose any semantic errors with value-initialization of 1790 /// the given type. 1791 /// 1792 /// Value-initialization effectively zero-initializes any types 1793 /// without user-declared constructors, and calls the default 1794 /// constructor for a for any type that has a user-declared 1795 /// constructor (C++ [dcl.init]p5). Value-initialization can fail when 1796 /// a type with a user-declared constructor does not have an 1797 /// accessible, non-deleted default constructor. In C, everything can 1798 /// be value-initialized, which corresponds to C's notion of 1799 /// initializing objects with static storage duration when no 1800 /// initializer is provided for that object. 1801 /// 1802 /// \returns true if there was an error, false otherwise. 1803 bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) { 1804 // C++ [dcl.init]p5: 1805 // 1806 // To value-initialize an object of type T means: 1807 1808 // -- if T is an array type, then each element is value-initialized; 1809 if (const ArrayType *AT = Context.getAsArrayType(Type)) 1810 return CheckValueInitialization(AT->getElementType(), Loc); 1811 1812 if (const RecordType *RT = Type->getAs<RecordType>()) { 1813 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 1814 // -- if T is a class type (clause 9) with a user-declared 1815 // constructor (12.1), then the default constructor for T is 1816 // called (and the initialization is ill-formed if T has no 1817 // accessible default constructor); 1818 if (ClassDecl->hasUserDeclaredConstructor()) { 1819 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 1820 1821 CXXConstructorDecl *Constructor 1822 = PerformInitializationByConstructor(Type, 1823 MultiExprArg(*this, 0, 0), 1824 Loc, SourceRange(Loc), 1825 DeclarationName(), 1826 IK_Direct, 1827 ConstructorArgs); 1828 if (!Constructor) 1829 return true; 1830 1831 OwningExprResult Init 1832 = BuildCXXConstructExpr(Loc, Type, Constructor, 1833 move_arg(ConstructorArgs)); 1834 if (Init.isInvalid()) 1835 return true; 1836 1837 // FIXME: Actually perform the value-initialization! 1838 return false; 1839 } 1840 } 1841 } 1842 1843 if (Type->isReferenceType()) { 1844 // C++ [dcl.init]p5: 1845 // [...] A program that calls for default-initialization or 1846 // value-initialization of an entity of reference type is 1847 // ill-formed. [...] 1848 // FIXME: Once we have code that goes through this path, add an actual 1849 // diagnostic :) 1850 } 1851 1852 return false; 1853 } 1854