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