1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===// 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 type-related semantic analysis. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "clang/Sema/Template.h" 16 #include "clang/Basic/OpenCL.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/TypeLoc.h" 23 #include "clang/AST/TypeLocVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/Basic/PartialDiagnostic.h" 26 #include "clang/Basic/TargetInfo.h" 27 #include "clang/Lex/Preprocessor.h" 28 #include "clang/Sema/DeclSpec.h" 29 #include "clang/Sema/DelayedDiagnostic.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/Support/ErrorHandling.h" 32 using namespace clang; 33 34 /// isOmittedBlockReturnType - Return true if this declarator is missing a 35 /// return type because this is a omitted return type on a block literal. 36 static bool isOmittedBlockReturnType(const Declarator &D) { 37 if (D.getContext() != Declarator::BlockLiteralContext || 38 D.getDeclSpec().hasTypeSpecifier()) 39 return false; 40 41 if (D.getNumTypeObjects() == 0) 42 return true; // ^{ ... } 43 44 if (D.getNumTypeObjects() == 1 && 45 D.getTypeObject(0).Kind == DeclaratorChunk::Function) 46 return true; // ^(int X, float Y) { ... } 47 48 return false; 49 } 50 51 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which 52 /// doesn't apply to the given type. 53 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr, 54 QualType type) { 55 bool useExpansionLoc = false; 56 57 unsigned diagID = 0; 58 switch (attr.getKind()) { 59 case AttributeList::AT_objc_gc: 60 diagID = diag::warn_pointer_attribute_wrong_type; 61 useExpansionLoc = true; 62 break; 63 64 case AttributeList::AT_objc_ownership: 65 diagID = diag::warn_objc_object_attribute_wrong_type; 66 useExpansionLoc = true; 67 break; 68 69 default: 70 // Assume everything else was a function attribute. 71 diagID = diag::warn_function_attribute_wrong_type; 72 break; 73 } 74 75 SourceLocation loc = attr.getLoc(); 76 StringRef name = attr.getName()->getName(); 77 78 // The GC attributes are usually written with macros; special-case them. 79 if (useExpansionLoc && loc.isMacroID() && attr.getParameterName()) { 80 if (attr.getParameterName()->isStr("strong")) { 81 if (S.findMacroSpelling(loc, "__strong")) name = "__strong"; 82 } else if (attr.getParameterName()->isStr("weak")) { 83 if (S.findMacroSpelling(loc, "__weak")) name = "__weak"; 84 } 85 } 86 87 S.Diag(loc, diagID) << name << type; 88 } 89 90 // objc_gc applies to Objective-C pointers or, otherwise, to the 91 // smallest available pointer type (i.e. 'void*' in 'void**'). 92 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \ 93 case AttributeList::AT_objc_gc: \ 94 case AttributeList::AT_objc_ownership 95 96 // Function type attributes. 97 #define FUNCTION_TYPE_ATTRS_CASELIST \ 98 case AttributeList::AT_noreturn: \ 99 case AttributeList::AT_cdecl: \ 100 case AttributeList::AT_fastcall: \ 101 case AttributeList::AT_stdcall: \ 102 case AttributeList::AT_thiscall: \ 103 case AttributeList::AT_pascal: \ 104 case AttributeList::AT_regparm: \ 105 case AttributeList::AT_pcs \ 106 107 namespace { 108 /// An object which stores processing state for the entire 109 /// GetTypeForDeclarator process. 110 class TypeProcessingState { 111 Sema &sema; 112 113 /// The declarator being processed. 114 Declarator &declarator; 115 116 /// The index of the declarator chunk we're currently processing. 117 /// May be the total number of valid chunks, indicating the 118 /// DeclSpec. 119 unsigned chunkIndex; 120 121 /// Whether there are non-trivial modifications to the decl spec. 122 bool trivial; 123 124 /// Whether we saved the attributes in the decl spec. 125 bool hasSavedAttrs; 126 127 /// The original set of attributes on the DeclSpec. 128 SmallVector<AttributeList*, 2> savedAttrs; 129 130 /// A list of attributes to diagnose the uselessness of when the 131 /// processing is complete. 132 SmallVector<AttributeList*, 2> ignoredTypeAttrs; 133 134 public: 135 TypeProcessingState(Sema &sema, Declarator &declarator) 136 : sema(sema), declarator(declarator), 137 chunkIndex(declarator.getNumTypeObjects()), 138 trivial(true), hasSavedAttrs(false) {} 139 140 Sema &getSema() const { 141 return sema; 142 } 143 144 Declarator &getDeclarator() const { 145 return declarator; 146 } 147 148 unsigned getCurrentChunkIndex() const { 149 return chunkIndex; 150 } 151 152 void setCurrentChunkIndex(unsigned idx) { 153 assert(idx <= declarator.getNumTypeObjects()); 154 chunkIndex = idx; 155 } 156 157 AttributeList *&getCurrentAttrListRef() const { 158 assert(chunkIndex <= declarator.getNumTypeObjects()); 159 if (chunkIndex == declarator.getNumTypeObjects()) 160 return getMutableDeclSpec().getAttributes().getListRef(); 161 return declarator.getTypeObject(chunkIndex).getAttrListRef(); 162 } 163 164 /// Save the current set of attributes on the DeclSpec. 165 void saveDeclSpecAttrs() { 166 // Don't try to save them multiple times. 167 if (hasSavedAttrs) return; 168 169 DeclSpec &spec = getMutableDeclSpec(); 170 for (AttributeList *attr = spec.getAttributes().getList(); attr; 171 attr = attr->getNext()) 172 savedAttrs.push_back(attr); 173 trivial &= savedAttrs.empty(); 174 hasSavedAttrs = true; 175 } 176 177 /// Record that we had nowhere to put the given type attribute. 178 /// We will diagnose such attributes later. 179 void addIgnoredTypeAttr(AttributeList &attr) { 180 ignoredTypeAttrs.push_back(&attr); 181 } 182 183 /// Diagnose all the ignored type attributes, given that the 184 /// declarator worked out to the given type. 185 void diagnoseIgnoredTypeAttrs(QualType type) const { 186 for (SmallVectorImpl<AttributeList*>::const_iterator 187 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end(); 188 i != e; ++i) 189 diagnoseBadTypeAttribute(getSema(), **i, type); 190 } 191 192 ~TypeProcessingState() { 193 if (trivial) return; 194 195 restoreDeclSpecAttrs(); 196 } 197 198 private: 199 DeclSpec &getMutableDeclSpec() const { 200 return const_cast<DeclSpec&>(declarator.getDeclSpec()); 201 } 202 203 void restoreDeclSpecAttrs() { 204 assert(hasSavedAttrs); 205 206 if (savedAttrs.empty()) { 207 getMutableDeclSpec().getAttributes().set(0); 208 return; 209 } 210 211 getMutableDeclSpec().getAttributes().set(savedAttrs[0]); 212 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i) 213 savedAttrs[i]->setNext(savedAttrs[i+1]); 214 savedAttrs.back()->setNext(0); 215 } 216 }; 217 218 /// Basically std::pair except that we really want to avoid an 219 /// implicit operator= for safety concerns. It's also a minor 220 /// link-time optimization for this to be a private type. 221 struct AttrAndList { 222 /// The attribute. 223 AttributeList &first; 224 225 /// The head of the list the attribute is currently in. 226 AttributeList *&second; 227 228 AttrAndList(AttributeList &attr, AttributeList *&head) 229 : first(attr), second(head) {} 230 }; 231 } 232 233 namespace llvm { 234 template <> struct isPodLike<AttrAndList> { 235 static const bool value = true; 236 }; 237 } 238 239 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) { 240 attr.setNext(head); 241 head = &attr; 242 } 243 244 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) { 245 if (head == &attr) { 246 head = attr.getNext(); 247 return; 248 } 249 250 AttributeList *cur = head; 251 while (true) { 252 assert(cur && cur->getNext() && "ran out of attrs?"); 253 if (cur->getNext() == &attr) { 254 cur->setNext(attr.getNext()); 255 return; 256 } 257 cur = cur->getNext(); 258 } 259 } 260 261 static void moveAttrFromListToList(AttributeList &attr, 262 AttributeList *&fromList, 263 AttributeList *&toList) { 264 spliceAttrOutOfList(attr, fromList); 265 spliceAttrIntoList(attr, toList); 266 } 267 268 static void processTypeAttrs(TypeProcessingState &state, 269 QualType &type, bool isDeclSpec, 270 AttributeList *attrs); 271 272 static bool handleFunctionTypeAttr(TypeProcessingState &state, 273 AttributeList &attr, 274 QualType &type); 275 276 static bool handleObjCGCTypeAttr(TypeProcessingState &state, 277 AttributeList &attr, QualType &type); 278 279 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 280 AttributeList &attr, QualType &type); 281 282 static bool handleObjCPointerTypeAttr(TypeProcessingState &state, 283 AttributeList &attr, QualType &type) { 284 if (attr.getKind() == AttributeList::AT_objc_gc) 285 return handleObjCGCTypeAttr(state, attr, type); 286 assert(attr.getKind() == AttributeList::AT_objc_ownership); 287 return handleObjCOwnershipTypeAttr(state, attr, type); 288 } 289 290 /// Given that an objc_gc attribute was written somewhere on a 291 /// declaration *other* than on the declarator itself (for which, use 292 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it 293 /// didn't apply in whatever position it was written in, try to move 294 /// it to a more appropriate position. 295 static void distributeObjCPointerTypeAttr(TypeProcessingState &state, 296 AttributeList &attr, 297 QualType type) { 298 Declarator &declarator = state.getDeclarator(); 299 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 300 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 301 switch (chunk.Kind) { 302 case DeclaratorChunk::Pointer: 303 case DeclaratorChunk::BlockPointer: 304 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 305 chunk.getAttrListRef()); 306 return; 307 308 case DeclaratorChunk::Paren: 309 case DeclaratorChunk::Array: 310 continue; 311 312 // Don't walk through these. 313 case DeclaratorChunk::Reference: 314 case DeclaratorChunk::Function: 315 case DeclaratorChunk::MemberPointer: 316 goto error; 317 } 318 } 319 error: 320 321 diagnoseBadTypeAttribute(state.getSema(), attr, type); 322 } 323 324 /// Distribute an objc_gc type attribute that was written on the 325 /// declarator. 326 static void 327 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state, 328 AttributeList &attr, 329 QualType &declSpecType) { 330 Declarator &declarator = state.getDeclarator(); 331 332 // objc_gc goes on the innermost pointer to something that's not a 333 // pointer. 334 unsigned innermost = -1U; 335 bool considerDeclSpec = true; 336 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 337 DeclaratorChunk &chunk = declarator.getTypeObject(i); 338 switch (chunk.Kind) { 339 case DeclaratorChunk::Pointer: 340 case DeclaratorChunk::BlockPointer: 341 innermost = i; 342 continue; 343 344 case DeclaratorChunk::Reference: 345 case DeclaratorChunk::MemberPointer: 346 case DeclaratorChunk::Paren: 347 case DeclaratorChunk::Array: 348 continue; 349 350 case DeclaratorChunk::Function: 351 considerDeclSpec = false; 352 goto done; 353 } 354 } 355 done: 356 357 // That might actually be the decl spec if we weren't blocked by 358 // anything in the declarator. 359 if (considerDeclSpec) { 360 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) { 361 // Splice the attribute into the decl spec. Prevents the 362 // attribute from being applied multiple times and gives 363 // the source-location-filler something to work with. 364 state.saveDeclSpecAttrs(); 365 moveAttrFromListToList(attr, declarator.getAttrListRef(), 366 declarator.getMutableDeclSpec().getAttributes().getListRef()); 367 return; 368 } 369 } 370 371 // Otherwise, if we found an appropriate chunk, splice the attribute 372 // into it. 373 if (innermost != -1U) { 374 moveAttrFromListToList(attr, declarator.getAttrListRef(), 375 declarator.getTypeObject(innermost).getAttrListRef()); 376 return; 377 } 378 379 // Otherwise, diagnose when we're done building the type. 380 spliceAttrOutOfList(attr, declarator.getAttrListRef()); 381 state.addIgnoredTypeAttr(attr); 382 } 383 384 /// A function type attribute was written somewhere in a declaration 385 /// *other* than on the declarator itself or in the decl spec. Given 386 /// that it didn't apply in whatever position it was written in, try 387 /// to move it to a more appropriate position. 388 static void distributeFunctionTypeAttr(TypeProcessingState &state, 389 AttributeList &attr, 390 QualType type) { 391 Declarator &declarator = state.getDeclarator(); 392 393 // Try to push the attribute from the return type of a function to 394 // the function itself. 395 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 396 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 397 switch (chunk.Kind) { 398 case DeclaratorChunk::Function: 399 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 400 chunk.getAttrListRef()); 401 return; 402 403 case DeclaratorChunk::Paren: 404 case DeclaratorChunk::Pointer: 405 case DeclaratorChunk::BlockPointer: 406 case DeclaratorChunk::Array: 407 case DeclaratorChunk::Reference: 408 case DeclaratorChunk::MemberPointer: 409 continue; 410 } 411 } 412 413 diagnoseBadTypeAttribute(state.getSema(), attr, type); 414 } 415 416 /// Try to distribute a function type attribute to the innermost 417 /// function chunk or type. Returns true if the attribute was 418 /// distributed, false if no location was found. 419 static bool 420 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state, 421 AttributeList &attr, 422 AttributeList *&attrList, 423 QualType &declSpecType) { 424 Declarator &declarator = state.getDeclarator(); 425 426 // Put it on the innermost function chunk, if there is one. 427 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 428 DeclaratorChunk &chunk = declarator.getTypeObject(i); 429 if (chunk.Kind != DeclaratorChunk::Function) continue; 430 431 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef()); 432 return true; 433 } 434 435 if (handleFunctionTypeAttr(state, attr, declSpecType)) { 436 spliceAttrOutOfList(attr, attrList); 437 return true; 438 } 439 440 return false; 441 } 442 443 /// A function type attribute was written in the decl spec. Try to 444 /// apply it somewhere. 445 static void 446 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, 447 AttributeList &attr, 448 QualType &declSpecType) { 449 state.saveDeclSpecAttrs(); 450 451 // Try to distribute to the innermost. 452 if (distributeFunctionTypeAttrToInnermost(state, attr, 453 state.getCurrentAttrListRef(), 454 declSpecType)) 455 return; 456 457 // If that failed, diagnose the bad attribute when the declarator is 458 // fully built. 459 state.addIgnoredTypeAttr(attr); 460 } 461 462 /// A function type attribute was written on the declarator. Try to 463 /// apply it somewhere. 464 static void 465 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, 466 AttributeList &attr, 467 QualType &declSpecType) { 468 Declarator &declarator = state.getDeclarator(); 469 470 // Try to distribute to the innermost. 471 if (distributeFunctionTypeAttrToInnermost(state, attr, 472 declarator.getAttrListRef(), 473 declSpecType)) 474 return; 475 476 // If that failed, diagnose the bad attribute when the declarator is 477 // fully built. 478 spliceAttrOutOfList(attr, declarator.getAttrListRef()); 479 state.addIgnoredTypeAttr(attr); 480 } 481 482 /// \brief Given that there are attributes written on the declarator 483 /// itself, try to distribute any type attributes to the appropriate 484 /// declarator chunk. 485 /// 486 /// These are attributes like the following: 487 /// int f ATTR; 488 /// int (f ATTR)(); 489 /// but not necessarily this: 490 /// int f() ATTR; 491 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, 492 QualType &declSpecType) { 493 // Collect all the type attributes from the declarator itself. 494 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!"); 495 AttributeList *attr = state.getDeclarator().getAttributes(); 496 AttributeList *next; 497 do { 498 next = attr->getNext(); 499 500 switch (attr->getKind()) { 501 OBJC_POINTER_TYPE_ATTRS_CASELIST: 502 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType); 503 break; 504 505 case AttributeList::AT_ns_returns_retained: 506 if (!state.getSema().getLangOptions().ObjCAutoRefCount) 507 break; 508 // fallthrough 509 510 FUNCTION_TYPE_ATTRS_CASELIST: 511 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType); 512 break; 513 514 default: 515 break; 516 } 517 } while ((attr = next)); 518 } 519 520 /// Add a synthetic '()' to a block-literal declarator if it is 521 /// required, given the return type. 522 static void maybeSynthesizeBlockSignature(TypeProcessingState &state, 523 QualType declSpecType) { 524 Declarator &declarator = state.getDeclarator(); 525 526 // First, check whether the declarator would produce a function, 527 // i.e. whether the innermost semantic chunk is a function. 528 if (declarator.isFunctionDeclarator()) { 529 // If so, make that declarator a prototyped declarator. 530 declarator.getFunctionTypeInfo().hasPrototype = true; 531 return; 532 } 533 534 // If there are any type objects, the type as written won't name a 535 // function, regardless of the decl spec type. This is because a 536 // block signature declarator is always an abstract-declarator, and 537 // abstract-declarators can't just be parentheses chunks. Therefore 538 // we need to build a function chunk unless there are no type 539 // objects and the decl spec type is a function. 540 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType()) 541 return; 542 543 // Note that there *are* cases with invalid declarators where 544 // declarators consist solely of parentheses. In general, these 545 // occur only in failed efforts to make function declarators, so 546 // faking up the function chunk is still the right thing to do. 547 548 // Otherwise, we need to fake up a function declarator. 549 SourceLocation loc = declarator.getSourceRange().getBegin(); 550 551 // ...and *prepend* it to the declarator. 552 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction( 553 /*proto*/ true, 554 /*variadic*/ false, SourceLocation(), 555 /*args*/ 0, 0, 556 /*type quals*/ 0, 557 /*ref-qualifier*/true, SourceLocation(), 558 /*mutable qualifier*/SourceLocation(), 559 /*EH*/ EST_None, SourceLocation(), 0, 0, 0, 0, 560 /*parens*/ loc, loc, 561 declarator)); 562 563 // For consistency, make sure the state still has us as processing 564 // the decl spec. 565 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1); 566 state.setCurrentChunkIndex(declarator.getNumTypeObjects()); 567 } 568 569 /// \brief Convert the specified declspec to the appropriate type 570 /// object. 571 /// \param D the declarator containing the declaration specifier. 572 /// \returns The type described by the declaration specifiers. This function 573 /// never returns null. 574 static QualType ConvertDeclSpecToType(TypeProcessingState &state) { 575 // FIXME: Should move the logic from DeclSpec::Finish to here for validity 576 // checking. 577 578 Sema &S = state.getSema(); 579 Declarator &declarator = state.getDeclarator(); 580 const DeclSpec &DS = declarator.getDeclSpec(); 581 SourceLocation DeclLoc = declarator.getIdentifierLoc(); 582 if (DeclLoc.isInvalid()) 583 DeclLoc = DS.getSourceRange().getBegin(); 584 585 ASTContext &Context = S.Context; 586 587 QualType Result; 588 switch (DS.getTypeSpecType()) { 589 case DeclSpec::TST_void: 590 Result = Context.VoidTy; 591 break; 592 case DeclSpec::TST_char: 593 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 594 Result = Context.CharTy; 595 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) 596 Result = Context.SignedCharTy; 597 else { 598 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 599 "Unknown TSS value"); 600 Result = Context.UnsignedCharTy; 601 } 602 break; 603 case DeclSpec::TST_wchar: 604 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 605 Result = Context.WCharTy; 606 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { 607 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 608 << DS.getSpecifierName(DS.getTypeSpecType()); 609 Result = Context.getSignedWCharType(); 610 } else { 611 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 612 "Unknown TSS value"); 613 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 614 << DS.getSpecifierName(DS.getTypeSpecType()); 615 Result = Context.getUnsignedWCharType(); 616 } 617 break; 618 case DeclSpec::TST_char16: 619 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 620 "Unknown TSS value"); 621 Result = Context.Char16Ty; 622 break; 623 case DeclSpec::TST_char32: 624 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 625 "Unknown TSS value"); 626 Result = Context.Char32Ty; 627 break; 628 case DeclSpec::TST_unspecified: 629 // "<proto1,proto2>" is an objc qualified ID with a missing id. 630 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { 631 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 632 (ObjCProtocolDecl**)PQ, 633 DS.getNumProtocolQualifiers()); 634 Result = Context.getObjCObjectPointerType(Result); 635 break; 636 } 637 638 // If this is a missing declspec in a block literal return context, then it 639 // is inferred from the return statements inside the block. 640 if (isOmittedBlockReturnType(declarator)) { 641 Result = Context.DependentTy; 642 break; 643 } 644 645 // Unspecified typespec defaults to int in C90. However, the C90 grammar 646 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, 647 // type-qualifier, or storage-class-specifier. If not, emit an extwarn. 648 // Note that the one exception to this is function definitions, which are 649 // allowed to be completely missing a declspec. This is handled in the 650 // parser already though by it pretending to have seen an 'int' in this 651 // case. 652 if (S.getLangOptions().ImplicitInt) { 653 // In C89 mode, we only warn if there is a completely missing declspec 654 // when one is not allowed. 655 if (DS.isEmpty()) { 656 S.Diag(DeclLoc, diag::ext_missing_declspec) 657 << DS.getSourceRange() 658 << FixItHint::CreateInsertion(DS.getSourceRange().getBegin(), "int"); 659 } 660 } else if (!DS.hasTypeSpecifier()) { 661 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: 662 // "At least one type specifier shall be given in the declaration 663 // specifiers in each declaration, and in the specifier-qualifier list in 664 // each struct declaration and type name." 665 // FIXME: Does Microsoft really have the implicit int extension in C++? 666 if (S.getLangOptions().CPlusPlus && 667 !S.getLangOptions().MicrosoftExt) { 668 S.Diag(DeclLoc, diag::err_missing_type_specifier) 669 << DS.getSourceRange(); 670 671 // When this occurs in C++ code, often something is very broken with the 672 // value being declared, poison it as invalid so we don't get chains of 673 // errors. 674 declarator.setInvalidType(true); 675 } else { 676 S.Diag(DeclLoc, diag::ext_missing_type_specifier) 677 << DS.getSourceRange(); 678 } 679 } 680 681 // FALL THROUGH. 682 case DeclSpec::TST_int: { 683 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { 684 switch (DS.getTypeSpecWidth()) { 685 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; 686 case DeclSpec::TSW_short: Result = Context.ShortTy; break; 687 case DeclSpec::TSW_long: Result = Context.LongTy; break; 688 case DeclSpec::TSW_longlong: 689 Result = Context.LongLongTy; 690 691 // long long is a C99 feature. 692 if (!S.getLangOptions().C99 && 693 !S.getLangOptions().CPlusPlus0x) 694 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong); 695 break; 696 } 697 } else { 698 switch (DS.getTypeSpecWidth()) { 699 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; 700 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; 701 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; 702 case DeclSpec::TSW_longlong: 703 Result = Context.UnsignedLongLongTy; 704 705 // long long is a C99 feature. 706 if (!S.getLangOptions().C99 && 707 !S.getLangOptions().CPlusPlus0x) 708 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong); 709 break; 710 } 711 } 712 break; 713 } 714 case DeclSpec::TST_half: Result = Context.HalfTy; break; 715 case DeclSpec::TST_float: Result = Context.FloatTy; break; 716 case DeclSpec::TST_double: 717 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) 718 Result = Context.LongDoubleTy; 719 else 720 Result = Context.DoubleTy; 721 722 if (S.getLangOptions().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) { 723 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64); 724 declarator.setInvalidType(true); 725 } 726 break; 727 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool 728 case DeclSpec::TST_decimal32: // _Decimal32 729 case DeclSpec::TST_decimal64: // _Decimal64 730 case DeclSpec::TST_decimal128: // _Decimal128 731 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); 732 Result = Context.IntTy; 733 declarator.setInvalidType(true); 734 break; 735 case DeclSpec::TST_class: 736 case DeclSpec::TST_enum: 737 case DeclSpec::TST_union: 738 case DeclSpec::TST_struct: { 739 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl()); 740 if (!D) { 741 // This can happen in C++ with ambiguous lookups. 742 Result = Context.IntTy; 743 declarator.setInvalidType(true); 744 break; 745 } 746 747 // If the type is deprecated or unavailable, diagnose it. 748 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc()); 749 750 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 751 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!"); 752 753 // TypeQuals handled by caller. 754 Result = Context.getTypeDeclType(D); 755 756 // In both C and C++, make an ElaboratedType. 757 ElaboratedTypeKeyword Keyword 758 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType()); 759 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result); 760 761 if (D->isInvalidDecl()) 762 declarator.setInvalidType(true); 763 break; 764 } 765 case DeclSpec::TST_typename: { 766 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 767 DS.getTypeSpecSign() == 0 && 768 "Can't handle qualifiers on typedef names yet!"); 769 Result = S.GetTypeFromParser(DS.getRepAsType()); 770 if (Result.isNull()) 771 declarator.setInvalidType(true); 772 else if (DeclSpec::ProtocolQualifierListTy PQ 773 = DS.getProtocolQualifiers()) { 774 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) { 775 // Silently drop any existing protocol qualifiers. 776 // TODO: determine whether that's the right thing to do. 777 if (ObjT->getNumProtocols()) 778 Result = ObjT->getBaseType(); 779 780 if (DS.getNumProtocolQualifiers()) 781 Result = Context.getObjCObjectType(Result, 782 (ObjCProtocolDecl**) PQ, 783 DS.getNumProtocolQualifiers()); 784 } else if (Result->isObjCIdType()) { 785 // id<protocol-list> 786 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 787 (ObjCProtocolDecl**) PQ, 788 DS.getNumProtocolQualifiers()); 789 Result = Context.getObjCObjectPointerType(Result); 790 } else if (Result->isObjCClassType()) { 791 // Class<protocol-list> 792 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 793 (ObjCProtocolDecl**) PQ, 794 DS.getNumProtocolQualifiers()); 795 Result = Context.getObjCObjectPointerType(Result); 796 } else { 797 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers) 798 << DS.getSourceRange(); 799 declarator.setInvalidType(true); 800 } 801 } 802 803 // TypeQuals handled by caller. 804 break; 805 } 806 case DeclSpec::TST_typeofType: 807 // FIXME: Preserve type source info. 808 Result = S.GetTypeFromParser(DS.getRepAsType()); 809 assert(!Result.isNull() && "Didn't get a type for typeof?"); 810 if (!Result->isDependentType()) 811 if (const TagType *TT = Result->getAs<TagType>()) 812 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc()); 813 // TypeQuals handled by caller. 814 Result = Context.getTypeOfType(Result); 815 break; 816 case DeclSpec::TST_typeofExpr: { 817 Expr *E = DS.getRepAsExpr(); 818 assert(E && "Didn't get an expression for typeof?"); 819 // TypeQuals handled by caller. 820 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc()); 821 if (Result.isNull()) { 822 Result = Context.IntTy; 823 declarator.setInvalidType(true); 824 } 825 break; 826 } 827 case DeclSpec::TST_decltype: { 828 Expr *E = DS.getRepAsExpr(); 829 assert(E && "Didn't get an expression for decltype?"); 830 // TypeQuals handled by caller. 831 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc()); 832 if (Result.isNull()) { 833 Result = Context.IntTy; 834 declarator.setInvalidType(true); 835 } 836 break; 837 } 838 case DeclSpec::TST_underlyingType: 839 Result = S.GetTypeFromParser(DS.getRepAsType()); 840 assert(!Result.isNull() && "Didn't get a type for __underlying_type?"); 841 Result = S.BuildUnaryTransformType(Result, 842 UnaryTransformType::EnumUnderlyingType, 843 DS.getTypeSpecTypeLoc()); 844 if (Result.isNull()) { 845 Result = Context.IntTy; 846 declarator.setInvalidType(true); 847 } 848 break; 849 850 case DeclSpec::TST_auto: { 851 // TypeQuals handled by caller. 852 Result = Context.getAutoType(QualType()); 853 break; 854 } 855 856 case DeclSpec::TST_unknown_anytype: 857 Result = Context.UnknownAnyTy; 858 break; 859 860 case DeclSpec::TST_atomic: 861 Result = S.GetTypeFromParser(DS.getRepAsType()); 862 assert(!Result.isNull() && "Didn't get a type for _Atomic?"); 863 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc()); 864 if (Result.isNull()) { 865 Result = Context.IntTy; 866 declarator.setInvalidType(true); 867 } 868 break; 869 870 case DeclSpec::TST_error: 871 Result = Context.IntTy; 872 declarator.setInvalidType(true); 873 break; 874 } 875 876 // Handle complex types. 877 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { 878 if (S.getLangOptions().Freestanding) 879 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); 880 Result = Context.getComplexType(Result); 881 } else if (DS.isTypeAltiVecVector()) { 882 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result)); 883 assert(typeSize > 0 && "type size for vector must be greater than 0 bits"); 884 VectorType::VectorKind VecKind = VectorType::AltiVecVector; 885 if (DS.isTypeAltiVecPixel()) 886 VecKind = VectorType::AltiVecPixel; 887 else if (DS.isTypeAltiVecBool()) 888 VecKind = VectorType::AltiVecBool; 889 Result = Context.getVectorType(Result, 128/typeSize, VecKind); 890 } 891 892 // FIXME: Imaginary. 893 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary) 894 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported); 895 896 // Before we process any type attributes, synthesize a block literal 897 // function declarator if necessary. 898 if (declarator.getContext() == Declarator::BlockLiteralContext) 899 maybeSynthesizeBlockSignature(state, Result); 900 901 // Apply any type attributes from the decl spec. This may cause the 902 // list of type attributes to be temporarily saved while the type 903 // attributes are pushed around. 904 if (AttributeList *attrs = DS.getAttributes().getList()) 905 processTypeAttrs(state, Result, true, attrs); 906 907 // Apply const/volatile/restrict qualifiers to T. 908 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 909 910 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 911 // or incomplete types shall not be restrict-qualified." C++ also allows 912 // restrict-qualified references. 913 if (TypeQuals & DeclSpec::TQ_restrict) { 914 if (Result->isAnyPointerType() || Result->isReferenceType()) { 915 QualType EltTy; 916 if (Result->isObjCObjectPointerType()) 917 EltTy = Result; 918 else 919 EltTy = Result->isPointerType() ? 920 Result->getAs<PointerType>()->getPointeeType() : 921 Result->getAs<ReferenceType>()->getPointeeType(); 922 923 // If we have a pointer or reference, the pointee must have an object 924 // incomplete type. 925 if (!EltTy->isIncompleteOrObjectType()) { 926 S.Diag(DS.getRestrictSpecLoc(), 927 diag::err_typecheck_invalid_restrict_invalid_pointee) 928 << EltTy << DS.getSourceRange(); 929 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier. 930 } 931 } else { 932 S.Diag(DS.getRestrictSpecLoc(), 933 diag::err_typecheck_invalid_restrict_not_pointer) 934 << Result << DS.getSourceRange(); 935 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier. 936 } 937 } 938 939 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification 940 // of a function type includes any type qualifiers, the behavior is 941 // undefined." 942 if (Result->isFunctionType() && TypeQuals) { 943 // Get some location to point at, either the C or V location. 944 SourceLocation Loc; 945 if (TypeQuals & DeclSpec::TQ_const) 946 Loc = DS.getConstSpecLoc(); 947 else if (TypeQuals & DeclSpec::TQ_volatile) 948 Loc = DS.getVolatileSpecLoc(); 949 else { 950 assert((TypeQuals & DeclSpec::TQ_restrict) && 951 "Has CVR quals but not C, V, or R?"); 952 Loc = DS.getRestrictSpecLoc(); 953 } 954 S.Diag(Loc, diag::warn_typecheck_function_qualifiers) 955 << Result << DS.getSourceRange(); 956 } 957 958 // C++ [dcl.ref]p1: 959 // Cv-qualified references are ill-formed except when the 960 // cv-qualifiers are introduced through the use of a typedef 961 // (7.1.3) or of a template type argument (14.3), in which 962 // case the cv-qualifiers are ignored. 963 // FIXME: Shouldn't we be checking SCS_typedef here? 964 if (DS.getTypeSpecType() == DeclSpec::TST_typename && 965 TypeQuals && Result->isReferenceType()) { 966 TypeQuals &= ~DeclSpec::TQ_const; 967 TypeQuals &= ~DeclSpec::TQ_volatile; 968 } 969 970 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals); 971 Result = Context.getQualifiedType(Result, Quals); 972 } 973 974 return Result; 975 } 976 977 static std::string getPrintableNameForEntity(DeclarationName Entity) { 978 if (Entity) 979 return Entity.getAsString(); 980 981 return "type name"; 982 } 983 984 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, 985 Qualifiers Qs) { 986 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 987 // object or incomplete types shall not be restrict-qualified." 988 if (Qs.hasRestrict()) { 989 unsigned DiagID = 0; 990 QualType ProblemTy; 991 992 const Type *Ty = T->getCanonicalTypeInternal().getTypePtr(); 993 if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) { 994 if (!RTy->getPointeeType()->isIncompleteOrObjectType()) { 995 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 996 ProblemTy = T->getAs<ReferenceType>()->getPointeeType(); 997 } 998 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) { 999 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) { 1000 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 1001 ProblemTy = T->getAs<PointerType>()->getPointeeType(); 1002 } 1003 } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) { 1004 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) { 1005 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 1006 ProblemTy = T->getAs<PointerType>()->getPointeeType(); 1007 } 1008 } else if (!Ty->isDependentType()) { 1009 // FIXME: this deserves a proper diagnostic 1010 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 1011 ProblemTy = T; 1012 } 1013 1014 if (DiagID) { 1015 Diag(Loc, DiagID) << ProblemTy; 1016 Qs.removeRestrict(); 1017 } 1018 } 1019 1020 return Context.getQualifiedType(T, Qs); 1021 } 1022 1023 /// \brief Build a paren type including \p T. 1024 QualType Sema::BuildParenType(QualType T) { 1025 return Context.getParenType(T); 1026 } 1027 1028 /// Given that we're building a pointer or reference to the given 1029 static QualType inferARCLifetimeForPointee(Sema &S, QualType type, 1030 SourceLocation loc, 1031 bool isReference) { 1032 // Bail out if retention is unrequired or already specified. 1033 if (!type->isObjCLifetimeType() || 1034 type.getObjCLifetime() != Qualifiers::OCL_None) 1035 return type; 1036 1037 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None; 1038 1039 // If the object type is const-qualified, we can safely use 1040 // __unsafe_unretained. This is safe (because there are no read 1041 // barriers), and it'll be safe to coerce anything but __weak* to 1042 // the resulting type. 1043 if (type.isConstQualified()) { 1044 implicitLifetime = Qualifiers::OCL_ExplicitNone; 1045 1046 // Otherwise, check whether the static type does not require 1047 // retaining. This currently only triggers for Class (possibly 1048 // protocol-qualifed, and arrays thereof). 1049 } else if (type->isObjCARCImplicitlyUnretainedType()) { 1050 implicitLifetime = Qualifiers::OCL_ExplicitNone; 1051 1052 // If we are in an unevaluated context, like sizeof, assume ExplicitNone and 1053 // don't give error. 1054 } else if (S.ExprEvalContexts.back().Context == Sema::Unevaluated) { 1055 implicitLifetime = Qualifiers::OCL_ExplicitNone; 1056 1057 // If that failed, give an error and recover using __autoreleasing. 1058 } else { 1059 // These types can show up in private ivars in system headers, so 1060 // we need this to not be an error in those cases. Instead we 1061 // want to delay. 1062 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 1063 S.DelayedDiagnostics.add( 1064 sema::DelayedDiagnostic::makeForbiddenType(loc, 1065 diag::err_arc_indirect_no_ownership, type, isReference)); 1066 } else { 1067 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference; 1068 } 1069 implicitLifetime = Qualifiers::OCL_Autoreleasing; 1070 } 1071 assert(implicitLifetime && "didn't infer any lifetime!"); 1072 1073 Qualifiers qs; 1074 qs.addObjCLifetime(implicitLifetime); 1075 return S.Context.getQualifiedType(type, qs); 1076 } 1077 1078 /// \brief Build a pointer type. 1079 /// 1080 /// \param T The type to which we'll be building a pointer. 1081 /// 1082 /// \param Loc The location of the entity whose type involves this 1083 /// pointer type or, if there is no such entity, the location of the 1084 /// type that will have pointer type. 1085 /// 1086 /// \param Entity The name of the entity that involves the pointer 1087 /// type, if known. 1088 /// 1089 /// \returns A suitable pointer type, if there are no 1090 /// errors. Otherwise, returns a NULL type. 1091 QualType Sema::BuildPointerType(QualType T, 1092 SourceLocation Loc, DeclarationName Entity) { 1093 if (T->isReferenceType()) { 1094 // C++ 8.3.2p4: There shall be no ... pointers to references ... 1095 Diag(Loc, diag::err_illegal_decl_pointer_to_reference) 1096 << getPrintableNameForEntity(Entity) << T; 1097 return QualType(); 1098 } 1099 1100 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType"); 1101 1102 // In ARC, it is forbidden to build pointers to unqualified pointers. 1103 if (getLangOptions().ObjCAutoRefCount) 1104 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false); 1105 1106 // Build the pointer type. 1107 return Context.getPointerType(T); 1108 } 1109 1110 /// \brief Build a reference type. 1111 /// 1112 /// \param T The type to which we'll be building a reference. 1113 /// 1114 /// \param Loc The location of the entity whose type involves this 1115 /// reference type or, if there is no such entity, the location of the 1116 /// type that will have reference type. 1117 /// 1118 /// \param Entity The name of the entity that involves the reference 1119 /// type, if known. 1120 /// 1121 /// \returns A suitable reference type, if there are no 1122 /// errors. Otherwise, returns a NULL type. 1123 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, 1124 SourceLocation Loc, 1125 DeclarationName Entity) { 1126 assert(Context.getCanonicalType(T) != Context.OverloadTy && 1127 "Unresolved overloaded function type"); 1128 1129 // C++0x [dcl.ref]p6: 1130 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a 1131 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a 1132 // type T, an attempt to create the type "lvalue reference to cv TR" creates 1133 // the type "lvalue reference to T", while an attempt to create the type 1134 // "rvalue reference to cv TR" creates the type TR. 1135 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); 1136 1137 // C++ [dcl.ref]p4: There shall be no references to references. 1138 // 1139 // According to C++ DR 106, references to references are only 1140 // diagnosed when they are written directly (e.g., "int & &"), 1141 // but not when they happen via a typedef: 1142 // 1143 // typedef int& intref; 1144 // typedef intref& intref2; 1145 // 1146 // Parser::ParseDeclaratorInternal diagnoses the case where 1147 // references are written directly; here, we handle the 1148 // collapsing of references-to-references as described in C++0x. 1149 // DR 106 and 540 introduce reference-collapsing into C++98/03. 1150 1151 // C++ [dcl.ref]p1: 1152 // A declarator that specifies the type "reference to cv void" 1153 // is ill-formed. 1154 if (T->isVoidType()) { 1155 Diag(Loc, diag::err_reference_to_void); 1156 return QualType(); 1157 } 1158 1159 // In ARC, it is forbidden to build references to unqualified pointers. 1160 if (getLangOptions().ObjCAutoRefCount) 1161 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true); 1162 1163 // Handle restrict on references. 1164 if (LValueRef) 1165 return Context.getLValueReferenceType(T, SpelledAsLValue); 1166 return Context.getRValueReferenceType(T); 1167 } 1168 1169 /// Check whether the specified array size makes the array type a VLA. If so, 1170 /// return true, if not, return the size of the array in SizeVal. 1171 static bool isArraySizeVLA(Expr *ArraySize, llvm::APSInt &SizeVal, Sema &S) { 1172 // If the size is an ICE, it certainly isn't a VLA. 1173 if (ArraySize->isIntegerConstantExpr(SizeVal, S.Context)) 1174 return false; 1175 1176 // If we're in a GNU mode (like gnu99, but not c99) accept any evaluatable 1177 // value as an extension. 1178 Expr::EvalResult Result; 1179 if (S.LangOpts.GNUMode && ArraySize->Evaluate(Result, S.Context)) { 1180 if (!Result.hasSideEffects() && Result.Val.isInt()) { 1181 SizeVal = Result.Val.getInt(); 1182 S.Diag(ArraySize->getLocStart(), diag::ext_vla_folded_to_constant); 1183 return false; 1184 } 1185 } 1186 1187 return true; 1188 } 1189 1190 1191 /// \brief Build an array type. 1192 /// 1193 /// \param T The type of each element in the array. 1194 /// 1195 /// \param ASM C99 array size modifier (e.g., '*', 'static'). 1196 /// 1197 /// \param ArraySize Expression describing the size of the array. 1198 /// 1199 /// \param Loc The location of the entity whose type involves this 1200 /// array type or, if there is no such entity, the location of the 1201 /// type that will have array type. 1202 /// 1203 /// \param Entity The name of the entity that involves the array 1204 /// type, if known. 1205 /// 1206 /// \returns A suitable array type, if there are no errors. Otherwise, 1207 /// returns a NULL type. 1208 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 1209 Expr *ArraySize, unsigned Quals, 1210 SourceRange Brackets, DeclarationName Entity) { 1211 1212 SourceLocation Loc = Brackets.getBegin(); 1213 if (getLangOptions().CPlusPlus) { 1214 // C++ [dcl.array]p1: 1215 // T is called the array element type; this type shall not be a reference 1216 // type, the (possibly cv-qualified) type void, a function type or an 1217 // abstract class type. 1218 // 1219 // Note: function types are handled in the common path with C. 1220 if (T->isReferenceType()) { 1221 Diag(Loc, diag::err_illegal_decl_array_of_references) 1222 << getPrintableNameForEntity(Entity) << T; 1223 return QualType(); 1224 } 1225 1226 if (T->isVoidType()) { 1227 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T; 1228 return QualType(); 1229 } 1230 1231 if (RequireNonAbstractType(Brackets.getBegin(), T, 1232 diag::err_array_of_abstract_type)) 1233 return QualType(); 1234 1235 } else { 1236 // C99 6.7.5.2p1: If the element type is an incomplete or function type, 1237 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) 1238 if (RequireCompleteType(Loc, T, 1239 diag::err_illegal_decl_array_incomplete_type)) 1240 return QualType(); 1241 } 1242 1243 if (T->isFunctionType()) { 1244 Diag(Loc, diag::err_illegal_decl_array_of_functions) 1245 << getPrintableNameForEntity(Entity) << T; 1246 return QualType(); 1247 } 1248 1249 if (T->getContainedAutoType()) { 1250 Diag(Loc, diag::err_illegal_decl_array_of_auto) 1251 << getPrintableNameForEntity(Entity) << T; 1252 return QualType(); 1253 } 1254 1255 if (const RecordType *EltTy = T->getAs<RecordType>()) { 1256 // If the element type is a struct or union that contains a variadic 1257 // array, accept it as a GNU extension: C99 6.7.2.1p2. 1258 if (EltTy->getDecl()->hasFlexibleArrayMember()) 1259 Diag(Loc, diag::ext_flexible_array_in_array) << T; 1260 } else if (T->isObjCObjectType()) { 1261 Diag(Loc, diag::err_objc_array_of_interfaces) << T; 1262 return QualType(); 1263 } 1264 1265 // Do lvalue-to-rvalue conversions on the array size expression. 1266 if (ArraySize && !ArraySize->isRValue()) { 1267 ExprResult Result = DefaultLvalueConversion(ArraySize); 1268 if (Result.isInvalid()) 1269 return QualType(); 1270 1271 ArraySize = Result.take(); 1272 } 1273 1274 // C99 6.7.5.2p1: The size expression shall have integer type. 1275 // TODO: in theory, if we were insane, we could allow contextual 1276 // conversions to integer type here. 1277 if (ArraySize && !ArraySize->isTypeDependent() && 1278 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { 1279 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 1280 << ArraySize->getType() << ArraySize->getSourceRange(); 1281 return QualType(); 1282 } 1283 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType())); 1284 if (!ArraySize) { 1285 if (ASM == ArrayType::Star) 1286 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets); 1287 else 1288 T = Context.getIncompleteArrayType(T, ASM, Quals); 1289 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) { 1290 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); 1291 } else if (!T->isDependentType() && !T->isIncompleteType() && 1292 !T->isConstantSizeType()) { 1293 // C99: an array with an element type that has a non-constant-size is a VLA. 1294 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); 1295 } else if (isArraySizeVLA(ArraySize, ConstVal, *this)) { 1296 // C99: an array with a non-ICE size is a VLA. We accept any expression 1297 // that we can fold to a non-zero positive value as an extension. 1298 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); 1299 } else { 1300 // C99 6.7.5.2p1: If the expression is a constant expression, it shall 1301 // have a value greater than zero. 1302 if (ConstVal.isSigned() && ConstVal.isNegative()) { 1303 if (Entity) 1304 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size) 1305 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange(); 1306 else 1307 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size) 1308 << ArraySize->getSourceRange(); 1309 return QualType(); 1310 } 1311 if (ConstVal == 0) { 1312 // GCC accepts zero sized static arrays. We allow them when 1313 // we're not in a SFINAE context. 1314 Diag(ArraySize->getLocStart(), 1315 isSFINAEContext()? diag::err_typecheck_zero_array_size 1316 : diag::ext_typecheck_zero_array_size) 1317 << ArraySize->getSourceRange(); 1318 1319 if (ASM == ArrayType::Static) { 1320 Diag(ArraySize->getLocStart(), 1321 diag::warn_typecheck_zero_static_array_size) 1322 << ArraySize->getSourceRange(); 1323 ASM = ArrayType::Normal; 1324 } 1325 } else if (!T->isDependentType() && !T->isVariablyModifiedType() && 1326 !T->isIncompleteType()) { 1327 // Is the array too large? 1328 unsigned ActiveSizeBits 1329 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal); 1330 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) 1331 Diag(ArraySize->getLocStart(), diag::err_array_too_large) 1332 << ConstVal.toString(10) 1333 << ArraySize->getSourceRange(); 1334 } 1335 1336 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals); 1337 } 1338 // If this is not C99, extwarn about VLA's and C99 array size modifiers. 1339 if (!getLangOptions().C99) { 1340 if (T->isVariableArrayType()) { 1341 // Prohibit the use of non-POD types in VLAs. 1342 QualType BaseT = Context.getBaseElementType(T); 1343 if (!T->isDependentType() && 1344 !BaseT.isPODType(Context) && 1345 !BaseT->isObjCLifetimeType()) { 1346 Diag(Loc, diag::err_vla_non_pod) 1347 << BaseT; 1348 return QualType(); 1349 } 1350 // Prohibit the use of VLAs during template argument deduction. 1351 else if (isSFINAEContext()) { 1352 Diag(Loc, diag::err_vla_in_sfinae); 1353 return QualType(); 1354 } 1355 // Just extwarn about VLAs. 1356 else 1357 Diag(Loc, diag::ext_vla); 1358 } else if (ASM != ArrayType::Normal || Quals != 0) 1359 Diag(Loc, 1360 getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx 1361 : diag::ext_c99_array_usage); 1362 } 1363 1364 return T; 1365 } 1366 1367 /// \brief Build an ext-vector type. 1368 /// 1369 /// Run the required checks for the extended vector type. 1370 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, 1371 SourceLocation AttrLoc) { 1372 // unlike gcc's vector_size attribute, we do not allow vectors to be defined 1373 // in conjunction with complex types (pointers, arrays, functions, etc.). 1374 if (!T->isDependentType() && 1375 !T->isIntegerType() && !T->isRealFloatingType()) { 1376 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; 1377 return QualType(); 1378 } 1379 1380 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { 1381 llvm::APSInt vecSize(32); 1382 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) { 1383 Diag(AttrLoc, diag::err_attribute_argument_not_int) 1384 << "ext_vector_type" << ArraySize->getSourceRange(); 1385 return QualType(); 1386 } 1387 1388 // unlike gcc's vector_size attribute, the size is specified as the 1389 // number of elements, not the number of bytes. 1390 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); 1391 1392 if (vectorSize == 0) { 1393 Diag(AttrLoc, diag::err_attribute_zero_size) 1394 << ArraySize->getSourceRange(); 1395 return QualType(); 1396 } 1397 1398 return Context.getExtVectorType(T, vectorSize); 1399 } 1400 1401 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc); 1402 } 1403 1404 /// \brief Build a function type. 1405 /// 1406 /// This routine checks the function type according to C++ rules and 1407 /// under the assumption that the result type and parameter types have 1408 /// just been instantiated from a template. It therefore duplicates 1409 /// some of the behavior of GetTypeForDeclarator, but in a much 1410 /// simpler form that is only suitable for this narrow use case. 1411 /// 1412 /// \param T The return type of the function. 1413 /// 1414 /// \param ParamTypes The parameter types of the function. This array 1415 /// will be modified to account for adjustments to the types of the 1416 /// function parameters. 1417 /// 1418 /// \param NumParamTypes The number of parameter types in ParamTypes. 1419 /// 1420 /// \param Variadic Whether this is a variadic function type. 1421 /// 1422 /// \param Quals The cvr-qualifiers to be applied to the function type. 1423 /// 1424 /// \param Loc The location of the entity whose type involves this 1425 /// function type or, if there is no such entity, the location of the 1426 /// type that will have function type. 1427 /// 1428 /// \param Entity The name of the entity that involves the function 1429 /// type, if known. 1430 /// 1431 /// \returns A suitable function type, if there are no 1432 /// errors. Otherwise, returns a NULL type. 1433 QualType Sema::BuildFunctionType(QualType T, 1434 QualType *ParamTypes, 1435 unsigned NumParamTypes, 1436 bool Variadic, unsigned Quals, 1437 RefQualifierKind RefQualifier, 1438 SourceLocation Loc, DeclarationName Entity, 1439 FunctionType::ExtInfo Info) { 1440 if (T->isArrayType() || T->isFunctionType()) { 1441 Diag(Loc, diag::err_func_returning_array_function) 1442 << T->isFunctionType() << T; 1443 return QualType(); 1444 } 1445 1446 // Functions cannot return half FP. 1447 if (T->isHalfType()) { 1448 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 << 1449 FixItHint::CreateInsertion(Loc, "*"); 1450 return QualType(); 1451 } 1452 1453 bool Invalid = false; 1454 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) { 1455 // FIXME: Loc is too inprecise here, should use proper locations for args. 1456 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]); 1457 if (ParamType->isVoidType()) { 1458 Diag(Loc, diag::err_param_with_void_type); 1459 Invalid = true; 1460 } else if (ParamType->isHalfType()) { 1461 // Disallow half FP arguments. 1462 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 << 1463 FixItHint::CreateInsertion(Loc, "*"); 1464 Invalid = true; 1465 } 1466 1467 ParamTypes[Idx] = ParamType; 1468 } 1469 1470 if (Invalid) 1471 return QualType(); 1472 1473 FunctionProtoType::ExtProtoInfo EPI; 1474 EPI.Variadic = Variadic; 1475 EPI.TypeQuals = Quals; 1476 EPI.RefQualifier = RefQualifier; 1477 EPI.ExtInfo = Info; 1478 1479 return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI); 1480 } 1481 1482 /// \brief Build a member pointer type \c T Class::*. 1483 /// 1484 /// \param T the type to which the member pointer refers. 1485 /// \param Class the class type into which the member pointer points. 1486 /// \param CVR Qualifiers applied to the member pointer type 1487 /// \param Loc the location where this type begins 1488 /// \param Entity the name of the entity that will have this member pointer type 1489 /// 1490 /// \returns a member pointer type, if successful, or a NULL type if there was 1491 /// an error. 1492 QualType Sema::BuildMemberPointerType(QualType T, QualType Class, 1493 SourceLocation Loc, 1494 DeclarationName Entity) { 1495 // Verify that we're not building a pointer to pointer to function with 1496 // exception specification. 1497 if (CheckDistantExceptionSpec(T)) { 1498 Diag(Loc, diag::err_distant_exception_spec); 1499 1500 // FIXME: If we're doing this as part of template instantiation, 1501 // we should return immediately. 1502 1503 // Build the type anyway, but use the canonical type so that the 1504 // exception specifiers are stripped off. 1505 T = Context.getCanonicalType(T); 1506 } 1507 1508 // C++ 8.3.3p3: A pointer to member shall not point to ... a member 1509 // with reference type, or "cv void." 1510 if (T->isReferenceType()) { 1511 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) 1512 << (Entity? Entity.getAsString() : "type name") << T; 1513 return QualType(); 1514 } 1515 1516 if (T->isVoidType()) { 1517 Diag(Loc, diag::err_illegal_decl_mempointer_to_void) 1518 << (Entity? Entity.getAsString() : "type name"); 1519 return QualType(); 1520 } 1521 1522 if (!Class->isDependentType() && !Class->isRecordType()) { 1523 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; 1524 return QualType(); 1525 } 1526 1527 // In the Microsoft ABI, the class is allowed to be an incomplete 1528 // type. In such cases, the compiler makes a worst-case assumption. 1529 // We make no such assumption right now, so emit an error if the 1530 // class isn't a complete type. 1531 if (Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft && 1532 RequireCompleteType(Loc, Class, diag::err_incomplete_type)) 1533 return QualType(); 1534 1535 return Context.getMemberPointerType(T, Class.getTypePtr()); 1536 } 1537 1538 /// \brief Build a block pointer type. 1539 /// 1540 /// \param T The type to which we'll be building a block pointer. 1541 /// 1542 /// \param CVR The cvr-qualifiers to be applied to the block pointer type. 1543 /// 1544 /// \param Loc The location of the entity whose type involves this 1545 /// block pointer type or, if there is no such entity, the location of the 1546 /// type that will have block pointer type. 1547 /// 1548 /// \param Entity The name of the entity that involves the block pointer 1549 /// type, if known. 1550 /// 1551 /// \returns A suitable block pointer type, if there are no 1552 /// errors. Otherwise, returns a NULL type. 1553 QualType Sema::BuildBlockPointerType(QualType T, 1554 SourceLocation Loc, 1555 DeclarationName Entity) { 1556 if (!T->isFunctionType()) { 1557 Diag(Loc, diag::err_nonfunction_block_type); 1558 return QualType(); 1559 } 1560 1561 return Context.getBlockPointerType(T); 1562 } 1563 1564 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { 1565 QualType QT = Ty.get(); 1566 if (QT.isNull()) { 1567 if (TInfo) *TInfo = 0; 1568 return QualType(); 1569 } 1570 1571 TypeSourceInfo *DI = 0; 1572 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { 1573 QT = LIT->getType(); 1574 DI = LIT->getTypeSourceInfo(); 1575 } 1576 1577 if (TInfo) *TInfo = DI; 1578 return QT; 1579 } 1580 1581 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 1582 Qualifiers::ObjCLifetime ownership, 1583 unsigned chunkIndex); 1584 1585 /// Given that this is the declaration of a parameter under ARC, 1586 /// attempt to infer attributes and such for pointer-to-whatever 1587 /// types. 1588 static void inferARCWriteback(TypeProcessingState &state, 1589 QualType &declSpecType) { 1590 Sema &S = state.getSema(); 1591 Declarator &declarator = state.getDeclarator(); 1592 1593 // TODO: should we care about decl qualifiers? 1594 1595 // Check whether the declarator has the expected form. We walk 1596 // from the inside out in order to make the block logic work. 1597 unsigned outermostPointerIndex = 0; 1598 bool isBlockPointer = false; 1599 unsigned numPointers = 0; 1600 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 1601 unsigned chunkIndex = i; 1602 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex); 1603 switch (chunk.Kind) { 1604 case DeclaratorChunk::Paren: 1605 // Ignore parens. 1606 break; 1607 1608 case DeclaratorChunk::Reference: 1609 case DeclaratorChunk::Pointer: 1610 // Count the number of pointers. Treat references 1611 // interchangeably as pointers; if they're mis-ordered, normal 1612 // type building will discover that. 1613 outermostPointerIndex = chunkIndex; 1614 numPointers++; 1615 break; 1616 1617 case DeclaratorChunk::BlockPointer: 1618 // If we have a pointer to block pointer, that's an acceptable 1619 // indirect reference; anything else is not an application of 1620 // the rules. 1621 if (numPointers != 1) return; 1622 numPointers++; 1623 outermostPointerIndex = chunkIndex; 1624 isBlockPointer = true; 1625 1626 // We don't care about pointer structure in return values here. 1627 goto done; 1628 1629 case DeclaratorChunk::Array: // suppress if written (id[])? 1630 case DeclaratorChunk::Function: 1631 case DeclaratorChunk::MemberPointer: 1632 return; 1633 } 1634 } 1635 done: 1636 1637 // If we have *one* pointer, then we want to throw the qualifier on 1638 // the declaration-specifiers, which means that it needs to be a 1639 // retainable object type. 1640 if (numPointers == 1) { 1641 // If it's not a retainable object type, the rule doesn't apply. 1642 if (!declSpecType->isObjCRetainableType()) return; 1643 1644 // If it already has lifetime, don't do anything. 1645 if (declSpecType.getObjCLifetime()) return; 1646 1647 // Otherwise, modify the type in-place. 1648 Qualifiers qs; 1649 1650 if (declSpecType->isObjCARCImplicitlyUnretainedType()) 1651 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone); 1652 else 1653 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing); 1654 declSpecType = S.Context.getQualifiedType(declSpecType, qs); 1655 1656 // If we have *two* pointers, then we want to throw the qualifier on 1657 // the outermost pointer. 1658 } else if (numPointers == 2) { 1659 // If we don't have a block pointer, we need to check whether the 1660 // declaration-specifiers gave us something that will turn into a 1661 // retainable object pointer after we slap the first pointer on it. 1662 if (!isBlockPointer && !declSpecType->isObjCObjectType()) 1663 return; 1664 1665 // Look for an explicit lifetime attribute there. 1666 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex); 1667 if (chunk.Kind != DeclaratorChunk::Pointer && 1668 chunk.Kind != DeclaratorChunk::BlockPointer) 1669 return; 1670 for (const AttributeList *attr = chunk.getAttrs(); attr; 1671 attr = attr->getNext()) 1672 if (attr->getKind() == AttributeList::AT_objc_ownership) 1673 return; 1674 1675 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing, 1676 outermostPointerIndex); 1677 1678 // Any other number of pointers/references does not trigger the rule. 1679 } else return; 1680 1681 // TODO: mark whether we did this inference? 1682 } 1683 1684 static void DiagnoseIgnoredQualifiers(unsigned Quals, 1685 SourceLocation ConstQualLoc, 1686 SourceLocation VolatileQualLoc, 1687 SourceLocation RestrictQualLoc, 1688 Sema& S) { 1689 std::string QualStr; 1690 unsigned NumQuals = 0; 1691 SourceLocation Loc; 1692 1693 FixItHint ConstFixIt; 1694 FixItHint VolatileFixIt; 1695 FixItHint RestrictFixIt; 1696 1697 const SourceManager &SM = S.getSourceManager(); 1698 1699 // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to 1700 // find a range and grow it to encompass all the qualifiers, regardless of 1701 // the order in which they textually appear. 1702 if (Quals & Qualifiers::Const) { 1703 ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc); 1704 QualStr = "const"; 1705 ++NumQuals; 1706 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc)) 1707 Loc = ConstQualLoc; 1708 } 1709 if (Quals & Qualifiers::Volatile) { 1710 VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc); 1711 QualStr += (NumQuals == 0 ? "volatile" : " volatile"); 1712 ++NumQuals; 1713 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc)) 1714 Loc = VolatileQualLoc; 1715 } 1716 if (Quals & Qualifiers::Restrict) { 1717 RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc); 1718 QualStr += (NumQuals == 0 ? "restrict" : " restrict"); 1719 ++NumQuals; 1720 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc)) 1721 Loc = RestrictQualLoc; 1722 } 1723 1724 assert(NumQuals > 0 && "No known qualifiers?"); 1725 1726 S.Diag(Loc, diag::warn_qual_return_type) 1727 << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt; 1728 } 1729 1730 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, 1731 TypeSourceInfo *&ReturnTypeInfo) { 1732 Sema &SemaRef = state.getSema(); 1733 Declarator &D = state.getDeclarator(); 1734 QualType T; 1735 ReturnTypeInfo = 0; 1736 1737 // The TagDecl owned by the DeclSpec. 1738 TagDecl *OwnedTagDecl = 0; 1739 1740 switch (D.getName().getKind()) { 1741 case UnqualifiedId::IK_ImplicitSelfParam: 1742 case UnqualifiedId::IK_OperatorFunctionId: 1743 case UnqualifiedId::IK_Identifier: 1744 case UnqualifiedId::IK_LiteralOperatorId: 1745 case UnqualifiedId::IK_TemplateId: 1746 T = ConvertDeclSpecToType(state); 1747 1748 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { 1749 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 1750 // Owned declaration is embedded in declarator. 1751 OwnedTagDecl->setEmbeddedInDeclarator(true); 1752 } 1753 break; 1754 1755 case UnqualifiedId::IK_ConstructorName: 1756 case UnqualifiedId::IK_ConstructorTemplateId: 1757 case UnqualifiedId::IK_DestructorName: 1758 // Constructors and destructors don't have return types. Use 1759 // "void" instead. 1760 T = SemaRef.Context.VoidTy; 1761 break; 1762 1763 case UnqualifiedId::IK_ConversionFunctionId: 1764 // The result type of a conversion function is the type that it 1765 // converts to. 1766 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId, 1767 &ReturnTypeInfo); 1768 break; 1769 } 1770 1771 if (D.getAttributes()) 1772 distributeTypeAttrsFromDeclarator(state, T); 1773 1774 // C++0x [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. 1775 // In C++0x, a function declarator using 'auto' must have a trailing return 1776 // type (this is checked later) and we can skip this. In other languages 1777 // using auto, we need to check regardless. 1778 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 1779 (!SemaRef.getLangOptions().CPlusPlus0x || !D.isFunctionDeclarator())) { 1780 int Error = -1; 1781 1782 switch (D.getContext()) { 1783 case Declarator::KNRTypeListContext: 1784 llvm_unreachable("K&R type lists aren't allowed in C++"); 1785 break; 1786 case Declarator::ObjCParameterContext: 1787 case Declarator::ObjCResultContext: 1788 case Declarator::PrototypeContext: 1789 Error = 0; // Function prototype 1790 break; 1791 case Declarator::MemberContext: 1792 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) 1793 break; 1794 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) { 1795 case TTK_Enum: llvm_unreachable("unhandled tag kind"); 1796 case TTK_Struct: Error = 1; /* Struct member */ break; 1797 case TTK_Union: Error = 2; /* Union member */ break; 1798 case TTK_Class: Error = 3; /* Class member */ break; 1799 } 1800 break; 1801 case Declarator::CXXCatchContext: 1802 case Declarator::ObjCCatchContext: 1803 Error = 4; // Exception declaration 1804 break; 1805 case Declarator::TemplateParamContext: 1806 Error = 5; // Template parameter 1807 break; 1808 case Declarator::BlockLiteralContext: 1809 Error = 6; // Block literal 1810 break; 1811 case Declarator::TemplateTypeArgContext: 1812 Error = 7; // Template type argument 1813 break; 1814 case Declarator::AliasDeclContext: 1815 case Declarator::AliasTemplateContext: 1816 Error = 9; // Type alias 1817 break; 1818 case Declarator::TypeNameContext: 1819 Error = 11; // Generic 1820 break; 1821 case Declarator::FileContext: 1822 case Declarator::BlockContext: 1823 case Declarator::ForContext: 1824 case Declarator::ConditionContext: 1825 case Declarator::CXXNewContext: 1826 break; 1827 } 1828 1829 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 1830 Error = 8; 1831 1832 // In Objective-C it is an error to use 'auto' on a function declarator. 1833 if (D.isFunctionDeclarator()) 1834 Error = 10; 1835 1836 // C++0x [dcl.spec.auto]p2: 'auto' is always fine if the declarator 1837 // contains a trailing return type. That is only legal at the outermost 1838 // level. Check all declarator chunks (outermost first) anyway, to give 1839 // better diagnostics. 1840 if (SemaRef.getLangOptions().CPlusPlus0x && Error != -1) { 1841 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 1842 unsigned chunkIndex = e - i - 1; 1843 state.setCurrentChunkIndex(chunkIndex); 1844 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 1845 if (DeclType.Kind == DeclaratorChunk::Function) { 1846 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 1847 if (FTI.TrailingReturnType) { 1848 Error = -1; 1849 break; 1850 } 1851 } 1852 } 1853 } 1854 1855 if (Error != -1) { 1856 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 1857 diag::err_auto_not_allowed) 1858 << Error; 1859 T = SemaRef.Context.IntTy; 1860 D.setInvalidType(true); 1861 } else 1862 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 1863 diag::warn_cxx98_compat_auto_type_specifier); 1864 } 1865 1866 if (SemaRef.getLangOptions().CPlusPlus && 1867 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { 1868 // Check the contexts where C++ forbids the declaration of a new class 1869 // or enumeration in a type-specifier-seq. 1870 switch (D.getContext()) { 1871 case Declarator::FileContext: 1872 case Declarator::MemberContext: 1873 case Declarator::BlockContext: 1874 case Declarator::ForContext: 1875 case Declarator::BlockLiteralContext: 1876 // C++0x [dcl.type]p3: 1877 // A type-specifier-seq shall not define a class or enumeration unless 1878 // it appears in the type-id of an alias-declaration (7.1.3) that is not 1879 // the declaration of a template-declaration. 1880 case Declarator::AliasDeclContext: 1881 break; 1882 case Declarator::AliasTemplateContext: 1883 SemaRef.Diag(OwnedTagDecl->getLocation(), 1884 diag::err_type_defined_in_alias_template) 1885 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 1886 break; 1887 case Declarator::TypeNameContext: 1888 case Declarator::TemplateParamContext: 1889 case Declarator::CXXNewContext: 1890 case Declarator::CXXCatchContext: 1891 case Declarator::ObjCCatchContext: 1892 case Declarator::TemplateTypeArgContext: 1893 SemaRef.Diag(OwnedTagDecl->getLocation(), 1894 diag::err_type_defined_in_type_specifier) 1895 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 1896 break; 1897 case Declarator::PrototypeContext: 1898 case Declarator::ObjCParameterContext: 1899 case Declarator::ObjCResultContext: 1900 case Declarator::KNRTypeListContext: 1901 // C++ [dcl.fct]p6: 1902 // Types shall not be defined in return or parameter types. 1903 SemaRef.Diag(OwnedTagDecl->getLocation(), 1904 diag::err_type_defined_in_param_type) 1905 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 1906 break; 1907 case Declarator::ConditionContext: 1908 // C++ 6.4p2: 1909 // The type-specifier-seq shall not contain typedef and shall not declare 1910 // a new class or enumeration. 1911 SemaRef.Diag(OwnedTagDecl->getLocation(), 1912 diag::err_type_defined_in_condition); 1913 break; 1914 } 1915 } 1916 1917 return T; 1918 } 1919 1920 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, 1921 QualType declSpecType, 1922 TypeSourceInfo *TInfo) { 1923 1924 QualType T = declSpecType; 1925 Declarator &D = state.getDeclarator(); 1926 Sema &S = state.getSema(); 1927 ASTContext &Context = S.Context; 1928 const LangOptions &LangOpts = S.getLangOptions(); 1929 1930 bool ImplicitlyNoexcept = false; 1931 if (D.getName().getKind() == UnqualifiedId::IK_OperatorFunctionId && 1932 LangOpts.CPlusPlus0x) { 1933 OverloadedOperatorKind OO = D.getName().OperatorFunctionId.Operator; 1934 /// In C++0x, deallocation functions (normal and array operator delete) 1935 /// are implicitly noexcept. 1936 if (OO == OO_Delete || OO == OO_Array_Delete) 1937 ImplicitlyNoexcept = true; 1938 } 1939 1940 // The name we're declaring, if any. 1941 DeclarationName Name; 1942 if (D.getIdentifier()) 1943 Name = D.getIdentifier(); 1944 1945 // Does this declaration declare a typedef-name? 1946 bool IsTypedefName = 1947 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || 1948 D.getContext() == Declarator::AliasDeclContext || 1949 D.getContext() == Declarator::AliasTemplateContext; 1950 1951 // Walk the DeclTypeInfo, building the recursive type as we go. 1952 // DeclTypeInfos are ordered from the identifier out, which is 1953 // opposite of what we want :). 1954 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 1955 unsigned chunkIndex = e - i - 1; 1956 state.setCurrentChunkIndex(chunkIndex); 1957 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 1958 switch (DeclType.Kind) { 1959 default: llvm_unreachable("Unknown decltype!"); 1960 case DeclaratorChunk::Paren: 1961 T = S.BuildParenType(T); 1962 break; 1963 case DeclaratorChunk::BlockPointer: 1964 // If blocks are disabled, emit an error. 1965 if (!LangOpts.Blocks) 1966 S.Diag(DeclType.Loc, diag::err_blocks_disable); 1967 1968 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); 1969 if (DeclType.Cls.TypeQuals) 1970 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); 1971 break; 1972 case DeclaratorChunk::Pointer: 1973 // Verify that we're not building a pointer to pointer to function with 1974 // exception specification. 1975 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 1976 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 1977 D.setInvalidType(true); 1978 // Build the type anyway. 1979 } 1980 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) { 1981 T = Context.getObjCObjectPointerType(T); 1982 if (DeclType.Ptr.TypeQuals) 1983 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 1984 break; 1985 } 1986 T = S.BuildPointerType(T, DeclType.Loc, Name); 1987 if (DeclType.Ptr.TypeQuals) 1988 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 1989 1990 break; 1991 case DeclaratorChunk::Reference: { 1992 // Verify that we're not building a reference to pointer to function with 1993 // exception specification. 1994 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 1995 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 1996 D.setInvalidType(true); 1997 // Build the type anyway. 1998 } 1999 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); 2000 2001 Qualifiers Quals; 2002 if (DeclType.Ref.HasRestrict) 2003 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); 2004 break; 2005 } 2006 case DeclaratorChunk::Array: { 2007 // Verify that we're not building an array of pointers to function with 2008 // exception specification. 2009 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 2010 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 2011 D.setInvalidType(true); 2012 // Build the type anyway. 2013 } 2014 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 2015 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 2016 ArrayType::ArraySizeModifier ASM; 2017 if (ATI.isStar) 2018 ASM = ArrayType::Star; 2019 else if (ATI.hasStatic) 2020 ASM = ArrayType::Static; 2021 else 2022 ASM = ArrayType::Normal; 2023 if (ASM == ArrayType::Star && !D.isPrototypeContext()) { 2024 // FIXME: This check isn't quite right: it allows star in prototypes 2025 // for function definitions, and disallows some edge cases detailed 2026 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 2027 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 2028 ASM = ArrayType::Normal; 2029 D.setInvalidType(true); 2030 } 2031 T = S.BuildArrayType(T, ASM, ArraySize, 2032 Qualifiers::fromCVRMask(ATI.TypeQuals), 2033 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 2034 break; 2035 } 2036 case DeclaratorChunk::Function: { 2037 // If the function declarator has a prototype (i.e. it is not () and 2038 // does not have a K&R-style identifier list), then the arguments are part 2039 // of the type, otherwise the argument list is (). 2040 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 2041 2042 // Check for auto functions and trailing return type and adjust the 2043 // return type accordingly. 2044 if (!D.isInvalidType()) { 2045 // trailing-return-type is only required if we're declaring a function, 2046 // and not, for instance, a pointer to a function. 2047 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 2048 !FTI.TrailingReturnType && chunkIndex == 0) { 2049 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2050 diag::err_auto_missing_trailing_return); 2051 T = Context.IntTy; 2052 D.setInvalidType(true); 2053 } else if (FTI.TrailingReturnType) { 2054 // T must be exactly 'auto' at this point. See CWG issue 681. 2055 if (isa<ParenType>(T)) { 2056 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2057 diag::err_trailing_return_in_parens) 2058 << T << D.getDeclSpec().getSourceRange(); 2059 D.setInvalidType(true); 2060 } else if (T.hasQualifiers() || !isa<AutoType>(T)) { 2061 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2062 diag::err_trailing_return_without_auto) 2063 << T << D.getDeclSpec().getSourceRange(); 2064 D.setInvalidType(true); 2065 } 2066 2067 T = S.GetTypeFromParser( 2068 ParsedType::getFromOpaquePtr(FTI.TrailingReturnType), 2069 &TInfo); 2070 } 2071 } 2072 2073 // C99 6.7.5.3p1: The return type may not be a function or array type. 2074 // For conversion functions, we'll diagnose this particular error later. 2075 if ((T->isArrayType() || T->isFunctionType()) && 2076 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) { 2077 unsigned diagID = diag::err_func_returning_array_function; 2078 // Last processing chunk in block context means this function chunk 2079 // represents the block. 2080 if (chunkIndex == 0 && 2081 D.getContext() == Declarator::BlockLiteralContext) 2082 diagID = diag::err_block_returning_array_function; 2083 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; 2084 T = Context.IntTy; 2085 D.setInvalidType(true); 2086 } 2087 2088 // Do not allow returning half FP value. 2089 // FIXME: This really should be in BuildFunctionType. 2090 if (T->isHalfType()) { 2091 S.Diag(D.getIdentifierLoc(), 2092 diag::err_parameters_retval_cannot_have_fp16_type) << 1 2093 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*"); 2094 D.setInvalidType(true); 2095 } 2096 2097 // cv-qualifiers on return types are pointless except when the type is a 2098 // class type in C++. 2099 if (isa<PointerType>(T) && T.getLocalCVRQualifiers() && 2100 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) && 2101 (!LangOpts.CPlusPlus || !T->isDependentType())) { 2102 assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?"); 2103 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); 2104 assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer); 2105 2106 DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr; 2107 2108 DiagnoseIgnoredQualifiers(PTI.TypeQuals, 2109 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc), 2110 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc), 2111 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc), 2112 S); 2113 2114 } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() && 2115 (!LangOpts.CPlusPlus || 2116 (!T->isDependentType() && !T->isRecordType()))) { 2117 2118 DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(), 2119 D.getDeclSpec().getConstSpecLoc(), 2120 D.getDeclSpec().getVolatileSpecLoc(), 2121 D.getDeclSpec().getRestrictSpecLoc(), 2122 S); 2123 } 2124 2125 if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) { 2126 // C++ [dcl.fct]p6: 2127 // Types shall not be defined in return or parameter types. 2128 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 2129 if (Tag->isCompleteDefinition()) 2130 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 2131 << Context.getTypeDeclType(Tag); 2132 } 2133 2134 // Exception specs are not allowed in typedefs. Complain, but add it 2135 // anyway. 2136 if (IsTypedefName && FTI.getExceptionSpecType()) 2137 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef) 2138 << (D.getContext() == Declarator::AliasDeclContext || 2139 D.getContext() == Declarator::AliasTemplateContext); 2140 2141 if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) { 2142 // Simple void foo(), where the incoming T is the result type. 2143 T = Context.getFunctionNoProtoType(T); 2144 } else { 2145 // We allow a zero-parameter variadic function in C if the 2146 // function is marked with the "overloadable" attribute. Scan 2147 // for this attribute now. 2148 if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) { 2149 bool Overloadable = false; 2150 for (const AttributeList *Attrs = D.getAttributes(); 2151 Attrs; Attrs = Attrs->getNext()) { 2152 if (Attrs->getKind() == AttributeList::AT_overloadable) { 2153 Overloadable = true; 2154 break; 2155 } 2156 } 2157 2158 if (!Overloadable) 2159 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg); 2160 } 2161 2162 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) { 2163 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function 2164 // definition. 2165 S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration); 2166 D.setInvalidType(true); 2167 break; 2168 } 2169 2170 FunctionProtoType::ExtProtoInfo EPI; 2171 EPI.Variadic = FTI.isVariadic; 2172 EPI.TypeQuals = FTI.TypeQuals; 2173 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None 2174 : FTI.RefQualifierIsLValueRef? RQ_LValue 2175 : RQ_RValue; 2176 2177 // Otherwise, we have a function with an argument list that is 2178 // potentially variadic. 2179 SmallVector<QualType, 16> ArgTys; 2180 ArgTys.reserve(FTI.NumArgs); 2181 2182 SmallVector<bool, 16> ConsumedArguments; 2183 ConsumedArguments.reserve(FTI.NumArgs); 2184 bool HasAnyConsumedArguments = false; 2185 2186 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 2187 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 2188 QualType ArgTy = Param->getType(); 2189 assert(!ArgTy.isNull() && "Couldn't parse type?"); 2190 2191 // Adjust the parameter type. 2192 assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) && 2193 "Unadjusted type?"); 2194 2195 // Look for 'void'. void is allowed only as a single argument to a 2196 // function with no other parameters (C99 6.7.5.3p10). We record 2197 // int(void) as a FunctionProtoType with an empty argument list. 2198 if (ArgTy->isVoidType()) { 2199 // If this is something like 'float(int, void)', reject it. 'void' 2200 // is an incomplete type (C99 6.2.5p19) and function decls cannot 2201 // have arguments of incomplete type. 2202 if (FTI.NumArgs != 1 || FTI.isVariadic) { 2203 S.Diag(DeclType.Loc, diag::err_void_only_param); 2204 ArgTy = Context.IntTy; 2205 Param->setType(ArgTy); 2206 } else if (FTI.ArgInfo[i].Ident) { 2207 // Reject, but continue to parse 'int(void abc)'. 2208 S.Diag(FTI.ArgInfo[i].IdentLoc, 2209 diag::err_param_with_void_type); 2210 ArgTy = Context.IntTy; 2211 Param->setType(ArgTy); 2212 } else { 2213 // Reject, but continue to parse 'float(const void)'. 2214 if (ArgTy.hasQualifiers()) 2215 S.Diag(DeclType.Loc, diag::err_void_param_qualified); 2216 2217 // Do not add 'void' to the ArgTys list. 2218 break; 2219 } 2220 } else if (ArgTy->isHalfType()) { 2221 // Disallow half FP arguments. 2222 // FIXME: This really should be in BuildFunctionType. 2223 S.Diag(Param->getLocation(), 2224 diag::err_parameters_retval_cannot_have_fp16_type) << 0 2225 << FixItHint::CreateInsertion(Param->getLocation(), "*"); 2226 D.setInvalidType(); 2227 } else if (!FTI.hasPrototype) { 2228 if (ArgTy->isPromotableIntegerType()) { 2229 ArgTy = Context.getPromotedIntegerType(ArgTy); 2230 Param->setKNRPromoted(true); 2231 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) { 2232 if (BTy->getKind() == BuiltinType::Float) { 2233 ArgTy = Context.DoubleTy; 2234 Param->setKNRPromoted(true); 2235 } 2236 } 2237 } 2238 2239 if (LangOpts.ObjCAutoRefCount) { 2240 bool Consumed = Param->hasAttr<NSConsumedAttr>(); 2241 ConsumedArguments.push_back(Consumed); 2242 HasAnyConsumedArguments |= Consumed; 2243 } 2244 2245 ArgTys.push_back(ArgTy); 2246 } 2247 2248 if (HasAnyConsumedArguments) 2249 EPI.ConsumedArguments = ConsumedArguments.data(); 2250 2251 SmallVector<QualType, 4> Exceptions; 2252 EPI.ExceptionSpecType = FTI.getExceptionSpecType(); 2253 if (FTI.getExceptionSpecType() == EST_Dynamic) { 2254 Exceptions.reserve(FTI.NumExceptions); 2255 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) { 2256 // FIXME: Preserve type source info. 2257 QualType ET = S.GetTypeFromParser(FTI.Exceptions[ei].Ty); 2258 // Check that the type is valid for an exception spec, and 2259 // drop it if not. 2260 if (!S.CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range)) 2261 Exceptions.push_back(ET); 2262 } 2263 EPI.NumExceptions = Exceptions.size(); 2264 EPI.Exceptions = Exceptions.data(); 2265 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) { 2266 // If an error occurred, there's no expression here. 2267 if (Expr *NoexceptExpr = FTI.NoexceptExpr) { 2268 assert((NoexceptExpr->isTypeDependent() || 2269 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 2270 Context.BoolTy) && 2271 "Parser should have made sure that the expression is boolean"); 2272 SourceLocation ErrLoc; 2273 llvm::APSInt Dummy; 2274 if (!NoexceptExpr->isValueDependent() && 2275 !NoexceptExpr->isIntegerConstantExpr(Dummy, Context, &ErrLoc, 2276 /*evaluated*/false)) 2277 S.Diag(ErrLoc, diag::err_noexcept_needs_constant_expression) 2278 << NoexceptExpr->getSourceRange(); 2279 else 2280 EPI.NoexceptExpr = NoexceptExpr; 2281 } 2282 } else if (FTI.getExceptionSpecType() == EST_None && 2283 ImplicitlyNoexcept && chunkIndex == 0) { 2284 // Only the outermost chunk is marked noexcept, of course. 2285 EPI.ExceptionSpecType = EST_BasicNoexcept; 2286 } 2287 2288 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI); 2289 } 2290 2291 break; 2292 } 2293 case DeclaratorChunk::MemberPointer: 2294 // The scope spec must refer to a class, or be dependent. 2295 CXXScopeSpec &SS = DeclType.Mem.Scope(); 2296 QualType ClsType; 2297 if (SS.isInvalid()) { 2298 // Avoid emitting extra errors if we already errored on the scope. 2299 D.setInvalidType(true); 2300 } else if (S.isDependentScopeSpecifier(SS) || 2301 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) { 2302 NestedNameSpecifier *NNS 2303 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 2304 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 2305 switch (NNS->getKind()) { 2306 case NestedNameSpecifier::Identifier: 2307 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, 2308 NNS->getAsIdentifier()); 2309 break; 2310 2311 case NestedNameSpecifier::Namespace: 2312 case NestedNameSpecifier::NamespaceAlias: 2313 case NestedNameSpecifier::Global: 2314 llvm_unreachable("Nested-name-specifier must name a type"); 2315 break; 2316 2317 case NestedNameSpecifier::TypeSpec: 2318 case NestedNameSpecifier::TypeSpecWithTemplate: 2319 ClsType = QualType(NNS->getAsType(), 0); 2320 // Note: if the NNS has a prefix and ClsType is a nondependent 2321 // TemplateSpecializationType, then the NNS prefix is NOT included 2322 // in ClsType; hence we wrap ClsType into an ElaboratedType. 2323 // NOTE: in particular, no wrap occurs if ClsType already is an 2324 // Elaborated, DependentName, or DependentTemplateSpecialization. 2325 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) 2326 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); 2327 break; 2328 } 2329 } else { 2330 S.Diag(DeclType.Mem.Scope().getBeginLoc(), 2331 diag::err_illegal_decl_mempointer_in_nonclass) 2332 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 2333 << DeclType.Mem.Scope().getRange(); 2334 D.setInvalidType(true); 2335 } 2336 2337 if (!ClsType.isNull()) 2338 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier()); 2339 if (T.isNull()) { 2340 T = Context.IntTy; 2341 D.setInvalidType(true); 2342 } else if (DeclType.Mem.TypeQuals) { 2343 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); 2344 } 2345 break; 2346 } 2347 2348 if (T.isNull()) { 2349 D.setInvalidType(true); 2350 T = Context.IntTy; 2351 } 2352 2353 // See if there are any attributes on this declarator chunk. 2354 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs())) 2355 processTypeAttrs(state, T, false, attrs); 2356 } 2357 2358 if (LangOpts.CPlusPlus && T->isFunctionType()) { 2359 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 2360 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 2361 2362 // C++ 8.3.5p4: 2363 // A cv-qualifier-seq shall only be part of the function type 2364 // for a nonstatic member function, the function type to which a pointer 2365 // to member refers, or the top-level function type of a function typedef 2366 // declaration. 2367 // 2368 // Core issue 547 also allows cv-qualifiers on function types that are 2369 // top-level template type arguments. 2370 bool FreeFunction; 2371 if (!D.getCXXScopeSpec().isSet()) { 2372 FreeFunction = (D.getContext() != Declarator::MemberContext || 2373 D.getDeclSpec().isFriendSpecified()); 2374 } else { 2375 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); 2376 FreeFunction = (DC && !DC->isRecord()); 2377 } 2378 2379 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member 2380 // function that is not a constructor declares that function to be const. 2381 if (D.getDeclSpec().isConstexprSpecified() && !FreeFunction && 2382 D.getName().getKind() != UnqualifiedId::IK_ConstructorName && 2383 D.getName().getKind() != UnqualifiedId::IK_ConstructorTemplateId && 2384 !(FnTy->getTypeQuals() & DeclSpec::TQ_const)) { 2385 // Rebuild function type adding a 'const' qualifier. 2386 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 2387 EPI.TypeQuals |= DeclSpec::TQ_const; 2388 T = Context.getFunctionType(FnTy->getResultType(), 2389 FnTy->arg_type_begin(), 2390 FnTy->getNumArgs(), EPI); 2391 } 2392 2393 // C++0x [dcl.fct]p6: 2394 // A ref-qualifier shall only be part of the function type for a 2395 // non-static member function, the function type to which a pointer to 2396 // member refers, or the top-level function type of a function typedef 2397 // declaration. 2398 if ((FnTy->getTypeQuals() != 0 || FnTy->getRefQualifier()) && 2399 !(D.getContext() == Declarator::TemplateTypeArgContext && 2400 !D.isFunctionDeclarator()) && !IsTypedefName && 2401 (FreeFunction || 2402 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) { 2403 if (D.getContext() == Declarator::TemplateTypeArgContext) { 2404 // Accept qualified function types as template type arguments as a GNU 2405 // extension. This is also the subject of C++ core issue 547. 2406 std::string Quals; 2407 if (FnTy->getTypeQuals() != 0) 2408 Quals = Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString(); 2409 2410 switch (FnTy->getRefQualifier()) { 2411 case RQ_None: 2412 break; 2413 2414 case RQ_LValue: 2415 if (!Quals.empty()) 2416 Quals += ' '; 2417 Quals += '&'; 2418 break; 2419 2420 case RQ_RValue: 2421 if (!Quals.empty()) 2422 Quals += ' '; 2423 Quals += "&&"; 2424 break; 2425 } 2426 2427 S.Diag(D.getIdentifierLoc(), 2428 diag::ext_qualified_function_type_template_arg) 2429 << Quals; 2430 } else { 2431 if (FnTy->getTypeQuals() != 0) { 2432 if (D.isFunctionDeclarator()) 2433 S.Diag(D.getIdentifierLoc(), 2434 diag::err_invalid_qualified_function_type); 2435 else 2436 S.Diag(D.getIdentifierLoc(), 2437 diag::err_invalid_qualified_typedef_function_type_use) 2438 << FreeFunction; 2439 } 2440 2441 if (FnTy->getRefQualifier()) { 2442 if (D.isFunctionDeclarator()) { 2443 SourceLocation Loc = D.getIdentifierLoc(); 2444 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) { 2445 const DeclaratorChunk &Chunk = D.getTypeObject(N-I-1); 2446 if (Chunk.Kind == DeclaratorChunk::Function && 2447 Chunk.Fun.hasRefQualifier()) { 2448 Loc = Chunk.Fun.getRefQualifierLoc(); 2449 break; 2450 } 2451 } 2452 2453 S.Diag(Loc, diag::err_invalid_ref_qualifier_function_type) 2454 << (FnTy->getRefQualifier() == RQ_LValue) 2455 << FixItHint::CreateRemoval(Loc); 2456 } else { 2457 S.Diag(D.getIdentifierLoc(), 2458 diag::err_invalid_ref_qualifier_typedef_function_type_use) 2459 << FreeFunction 2460 << (FnTy->getRefQualifier() == RQ_LValue); 2461 } 2462 } 2463 2464 // Strip the cv-qualifiers and ref-qualifiers from the type. 2465 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 2466 EPI.TypeQuals = 0; 2467 EPI.RefQualifier = RQ_None; 2468 2469 T = Context.getFunctionType(FnTy->getResultType(), 2470 FnTy->arg_type_begin(), 2471 FnTy->getNumArgs(), EPI); 2472 } 2473 } 2474 } 2475 2476 // Apply any undistributed attributes from the declarator. 2477 if (!T.isNull()) 2478 if (AttributeList *attrs = D.getAttributes()) 2479 processTypeAttrs(state, T, false, attrs); 2480 2481 // Diagnose any ignored type attributes. 2482 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T); 2483 2484 // C++0x [dcl.constexpr]p9: 2485 // A constexpr specifier used in an object declaration declares the object 2486 // as const. 2487 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) { 2488 T.addConst(); 2489 } 2490 2491 // If there was an ellipsis in the declarator, the declaration declares a 2492 // parameter pack whose type may be a pack expansion type. 2493 if (D.hasEllipsis() && !T.isNull()) { 2494 // C++0x [dcl.fct]p13: 2495 // A declarator-id or abstract-declarator containing an ellipsis shall 2496 // only be used in a parameter-declaration. Such a parameter-declaration 2497 // is a parameter pack (14.5.3). [...] 2498 switch (D.getContext()) { 2499 case Declarator::PrototypeContext: 2500 // C++0x [dcl.fct]p13: 2501 // [...] When it is part of a parameter-declaration-clause, the 2502 // parameter pack is a function parameter pack (14.5.3). The type T 2503 // of the declarator-id of the function parameter pack shall contain 2504 // a template parameter pack; each template parameter pack in T is 2505 // expanded by the function parameter pack. 2506 // 2507 // We represent function parameter packs as function parameters whose 2508 // type is a pack expansion. 2509 if (!T->containsUnexpandedParameterPack()) { 2510 S.Diag(D.getEllipsisLoc(), 2511 diag::err_function_parameter_pack_without_parameter_packs) 2512 << T << D.getSourceRange(); 2513 D.setEllipsisLoc(SourceLocation()); 2514 } else { 2515 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>()); 2516 } 2517 break; 2518 2519 case Declarator::TemplateParamContext: 2520 // C++0x [temp.param]p15: 2521 // If a template-parameter is a [...] is a parameter-declaration that 2522 // declares a parameter pack (8.3.5), then the template-parameter is a 2523 // template parameter pack (14.5.3). 2524 // 2525 // Note: core issue 778 clarifies that, if there are any unexpanded 2526 // parameter packs in the type of the non-type template parameter, then 2527 // it expands those parameter packs. 2528 if (T->containsUnexpandedParameterPack()) 2529 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>()); 2530 else 2531 S.Diag(D.getEllipsisLoc(), 2532 LangOpts.CPlusPlus0x 2533 ? diag::warn_cxx98_compat_variadic_templates 2534 : diag::ext_variadic_templates); 2535 break; 2536 2537 case Declarator::FileContext: 2538 case Declarator::KNRTypeListContext: 2539 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here? 2540 case Declarator::ObjCResultContext: // FIXME: special diagnostic here? 2541 case Declarator::TypeNameContext: 2542 case Declarator::CXXNewContext: 2543 case Declarator::AliasDeclContext: 2544 case Declarator::AliasTemplateContext: 2545 case Declarator::MemberContext: 2546 case Declarator::BlockContext: 2547 case Declarator::ForContext: 2548 case Declarator::ConditionContext: 2549 case Declarator::CXXCatchContext: 2550 case Declarator::ObjCCatchContext: 2551 case Declarator::BlockLiteralContext: 2552 case Declarator::TemplateTypeArgContext: 2553 // FIXME: We may want to allow parameter packs in block-literal contexts 2554 // in the future. 2555 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter); 2556 D.setEllipsisLoc(SourceLocation()); 2557 break; 2558 } 2559 } 2560 2561 if (T.isNull()) 2562 return Context.getNullTypeSourceInfo(); 2563 else if (D.isInvalidType()) 2564 return Context.getTrivialTypeSourceInfo(T); 2565 2566 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo); 2567 } 2568 2569 /// GetTypeForDeclarator - Convert the type for the specified 2570 /// declarator to Type instances. 2571 /// 2572 /// The result of this call will never be null, but the associated 2573 /// type may be a null type if there's an unrecoverable error. 2574 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { 2575 // Determine the type of the declarator. Not all forms of declarator 2576 // have a type. 2577 2578 TypeProcessingState state(*this, D); 2579 2580 TypeSourceInfo *ReturnTypeInfo = 0; 2581 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 2582 if (T.isNull()) 2583 return Context.getNullTypeSourceInfo(); 2584 2585 if (D.isPrototypeContext() && getLangOptions().ObjCAutoRefCount) 2586 inferARCWriteback(state, T); 2587 2588 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); 2589 } 2590 2591 static void transferARCOwnershipToDeclSpec(Sema &S, 2592 QualType &declSpecTy, 2593 Qualifiers::ObjCLifetime ownership) { 2594 if (declSpecTy->isObjCRetainableType() && 2595 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { 2596 Qualifiers qs; 2597 qs.addObjCLifetime(ownership); 2598 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); 2599 } 2600 } 2601 2602 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 2603 Qualifiers::ObjCLifetime ownership, 2604 unsigned chunkIndex) { 2605 Sema &S = state.getSema(); 2606 Declarator &D = state.getDeclarator(); 2607 2608 // Look for an explicit lifetime attribute. 2609 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); 2610 for (const AttributeList *attr = chunk.getAttrs(); attr; 2611 attr = attr->getNext()) 2612 if (attr->getKind() == AttributeList::AT_objc_ownership) 2613 return; 2614 2615 const char *attrStr = 0; 2616 switch (ownership) { 2617 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); break; 2618 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; 2619 case Qualifiers::OCL_Strong: attrStr = "strong"; break; 2620 case Qualifiers::OCL_Weak: attrStr = "weak"; break; 2621 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; 2622 } 2623 2624 // If there wasn't one, add one (with an invalid source location 2625 // so that we don't make an AttributedType for it). 2626 AttributeList *attr = D.getAttributePool() 2627 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(), 2628 /*scope*/ 0, SourceLocation(), 2629 &S.Context.Idents.get(attrStr), SourceLocation(), 2630 /*args*/ 0, 0, 2631 /*declspec*/ false, /*C++0x*/ false); 2632 spliceAttrIntoList(*attr, chunk.getAttrListRef()); 2633 2634 // TODO: mark whether we did this inference? 2635 } 2636 2637 static void transferARCOwnership(TypeProcessingState &state, 2638 QualType &declSpecTy, 2639 Qualifiers::ObjCLifetime ownership) { 2640 Sema &S = state.getSema(); 2641 Declarator &D = state.getDeclarator(); 2642 2643 int inner = -1; 2644 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 2645 DeclaratorChunk &chunk = D.getTypeObject(i); 2646 switch (chunk.Kind) { 2647 case DeclaratorChunk::Paren: 2648 // Ignore parens. 2649 break; 2650 2651 case DeclaratorChunk::Array: 2652 case DeclaratorChunk::Reference: 2653 case DeclaratorChunk::Pointer: 2654 inner = i; 2655 break; 2656 2657 case DeclaratorChunk::BlockPointer: 2658 return transferARCOwnershipToDeclaratorChunk(state, ownership, i); 2659 2660 case DeclaratorChunk::Function: 2661 case DeclaratorChunk::MemberPointer: 2662 return; 2663 } 2664 } 2665 2666 if (inner == -1) 2667 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 2668 2669 DeclaratorChunk &chunk = D.getTypeObject(inner); 2670 if (chunk.Kind == DeclaratorChunk::Pointer) { 2671 if (declSpecTy->isObjCRetainableType()) 2672 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 2673 if (declSpecTy->isObjCObjectType()) 2674 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); 2675 } else { 2676 assert(chunk.Kind == DeclaratorChunk::Array || 2677 chunk.Kind == DeclaratorChunk::Reference); 2678 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 2679 } 2680 } 2681 2682 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { 2683 TypeProcessingState state(*this, D); 2684 2685 TypeSourceInfo *ReturnTypeInfo = 0; 2686 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 2687 if (declSpecTy.isNull()) 2688 return Context.getNullTypeSourceInfo(); 2689 2690 if (getLangOptions().ObjCAutoRefCount) { 2691 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); 2692 if (ownership != Qualifiers::OCL_None) 2693 transferARCOwnership(state, declSpecTy, ownership); 2694 } 2695 2696 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); 2697 } 2698 2699 /// Map an AttributedType::Kind to an AttributeList::Kind. 2700 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) { 2701 switch (kind) { 2702 case AttributedType::attr_address_space: 2703 return AttributeList::AT_address_space; 2704 case AttributedType::attr_regparm: 2705 return AttributeList::AT_regparm; 2706 case AttributedType::attr_vector_size: 2707 return AttributeList::AT_vector_size; 2708 case AttributedType::attr_neon_vector_type: 2709 return AttributeList::AT_neon_vector_type; 2710 case AttributedType::attr_neon_polyvector_type: 2711 return AttributeList::AT_neon_polyvector_type; 2712 case AttributedType::attr_objc_gc: 2713 return AttributeList::AT_objc_gc; 2714 case AttributedType::attr_objc_ownership: 2715 return AttributeList::AT_objc_ownership; 2716 case AttributedType::attr_noreturn: 2717 return AttributeList::AT_noreturn; 2718 case AttributedType::attr_cdecl: 2719 return AttributeList::AT_cdecl; 2720 case AttributedType::attr_fastcall: 2721 return AttributeList::AT_fastcall; 2722 case AttributedType::attr_stdcall: 2723 return AttributeList::AT_stdcall; 2724 case AttributedType::attr_thiscall: 2725 return AttributeList::AT_thiscall; 2726 case AttributedType::attr_pascal: 2727 return AttributeList::AT_pascal; 2728 case AttributedType::attr_pcs: 2729 return AttributeList::AT_pcs; 2730 } 2731 llvm_unreachable("unexpected attribute kind!"); 2732 return AttributeList::Kind(); 2733 } 2734 2735 static void fillAttributedTypeLoc(AttributedTypeLoc TL, 2736 const AttributeList *attrs) { 2737 AttributedType::Kind kind = TL.getAttrKind(); 2738 2739 assert(attrs && "no type attributes in the expected location!"); 2740 AttributeList::Kind parsedKind = getAttrListKind(kind); 2741 while (attrs->getKind() != parsedKind) { 2742 attrs = attrs->getNext(); 2743 assert(attrs && "no matching attribute in expected location!"); 2744 } 2745 2746 TL.setAttrNameLoc(attrs->getLoc()); 2747 if (TL.hasAttrExprOperand()) 2748 TL.setAttrExprOperand(attrs->getArg(0)); 2749 else if (TL.hasAttrEnumOperand()) 2750 TL.setAttrEnumOperandLoc(attrs->getParameterLoc()); 2751 2752 // FIXME: preserve this information to here. 2753 if (TL.hasAttrOperand()) 2754 TL.setAttrOperandParensRange(SourceRange()); 2755 } 2756 2757 namespace { 2758 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 2759 ASTContext &Context; 2760 const DeclSpec &DS; 2761 2762 public: 2763 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS) 2764 : Context(Context), DS(DS) {} 2765 2766 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 2767 fillAttributedTypeLoc(TL, DS.getAttributes().getList()); 2768 Visit(TL.getModifiedLoc()); 2769 } 2770 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 2771 Visit(TL.getUnqualifiedLoc()); 2772 } 2773 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 2774 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 2775 } 2776 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 2777 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 2778 } 2779 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 2780 // Handle the base type, which might not have been written explicitly. 2781 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) { 2782 TL.setHasBaseTypeAsWritten(false); 2783 TL.getBaseLoc().initialize(Context, SourceLocation()); 2784 } else { 2785 TL.setHasBaseTypeAsWritten(true); 2786 Visit(TL.getBaseLoc()); 2787 } 2788 2789 // Protocol qualifiers. 2790 if (DS.getProtocolQualifiers()) { 2791 assert(TL.getNumProtocols() > 0); 2792 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers()); 2793 TL.setLAngleLoc(DS.getProtocolLAngleLoc()); 2794 TL.setRAngleLoc(DS.getSourceRange().getEnd()); 2795 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i) 2796 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]); 2797 } else { 2798 assert(TL.getNumProtocols() == 0); 2799 TL.setLAngleLoc(SourceLocation()); 2800 TL.setRAngleLoc(SourceLocation()); 2801 } 2802 } 2803 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 2804 TL.setStarLoc(SourceLocation()); 2805 Visit(TL.getPointeeLoc()); 2806 } 2807 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 2808 TypeSourceInfo *TInfo = 0; 2809 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 2810 2811 // If we got no declarator info from previous Sema routines, 2812 // just fill with the typespec loc. 2813 if (!TInfo) { 2814 TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); 2815 return; 2816 } 2817 2818 TypeLoc OldTL = TInfo->getTypeLoc(); 2819 if (TInfo->getType()->getAs<ElaboratedType>()) { 2820 ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL); 2821 TemplateSpecializationTypeLoc NamedTL = 2822 cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc()); 2823 TL.copy(NamedTL); 2824 } 2825 else 2826 TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL)); 2827 } 2828 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 2829 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 2830 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 2831 TL.setParensRange(DS.getTypeofParensRange()); 2832 } 2833 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 2834 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 2835 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 2836 TL.setParensRange(DS.getTypeofParensRange()); 2837 assert(DS.getRepAsType()); 2838 TypeSourceInfo *TInfo = 0; 2839 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 2840 TL.setUnderlyingTInfo(TInfo); 2841 } 2842 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 2843 // FIXME: This holds only because we only have one unary transform. 2844 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType); 2845 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 2846 TL.setParensRange(DS.getTypeofParensRange()); 2847 assert(DS.getRepAsType()); 2848 TypeSourceInfo *TInfo = 0; 2849 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 2850 TL.setUnderlyingTInfo(TInfo); 2851 } 2852 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 2853 // By default, use the source location of the type specifier. 2854 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 2855 if (TL.needsExtraLocalData()) { 2856 // Set info for the written builtin specifiers. 2857 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 2858 // Try to have a meaningful source location. 2859 if (TL.getWrittenSignSpec() != TSS_unspecified) 2860 // Sign spec loc overrides the others (e.g., 'unsigned long'). 2861 TL.setBuiltinLoc(DS.getTypeSpecSignLoc()); 2862 else if (TL.getWrittenWidthSpec() != TSW_unspecified) 2863 // Width spec loc overrides type spec loc (e.g., 'short int'). 2864 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc()); 2865 } 2866 } 2867 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 2868 ElaboratedTypeKeyword Keyword 2869 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 2870 if (DS.getTypeSpecType() == TST_typename) { 2871 TypeSourceInfo *TInfo = 0; 2872 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 2873 if (TInfo) { 2874 TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc())); 2875 return; 2876 } 2877 } 2878 TL.setKeywordLoc(Keyword != ETK_None 2879 ? DS.getTypeSpecTypeLoc() 2880 : SourceLocation()); 2881 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 2882 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 2883 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 2884 } 2885 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 2886 ElaboratedTypeKeyword Keyword 2887 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 2888 if (DS.getTypeSpecType() == TST_typename) { 2889 TypeSourceInfo *TInfo = 0; 2890 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 2891 if (TInfo) { 2892 TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc())); 2893 return; 2894 } 2895 } 2896 TL.setKeywordLoc(Keyword != ETK_None 2897 ? DS.getTypeSpecTypeLoc() 2898 : SourceLocation()); 2899 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 2900 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 2901 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 2902 } 2903 void VisitDependentTemplateSpecializationTypeLoc( 2904 DependentTemplateSpecializationTypeLoc TL) { 2905 ElaboratedTypeKeyword Keyword 2906 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 2907 if (Keyword == ETK_Typename) { 2908 TypeSourceInfo *TInfo = 0; 2909 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 2910 if (TInfo) { 2911 TL.copy(cast<DependentTemplateSpecializationTypeLoc>( 2912 TInfo->getTypeLoc())); 2913 return; 2914 } 2915 } 2916 TL.initializeLocal(Context, SourceLocation()); 2917 TL.setKeywordLoc(Keyword != ETK_None 2918 ? DS.getTypeSpecTypeLoc() 2919 : SourceLocation()); 2920 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 2921 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 2922 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 2923 } 2924 void VisitTagTypeLoc(TagTypeLoc TL) { 2925 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 2926 } 2927 void VisitAtomicTypeLoc(AtomicTypeLoc TL) { 2928 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 2929 TL.setParensRange(DS.getTypeofParensRange()); 2930 2931 TypeSourceInfo *TInfo = 0; 2932 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 2933 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 2934 } 2935 2936 void VisitTypeLoc(TypeLoc TL) { 2937 // FIXME: add other typespec types and change this to an assert. 2938 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 2939 } 2940 }; 2941 2942 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 2943 ASTContext &Context; 2944 const DeclaratorChunk &Chunk; 2945 2946 public: 2947 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk) 2948 : Context(Context), Chunk(Chunk) {} 2949 2950 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 2951 llvm_unreachable("qualified type locs not expected here!"); 2952 } 2953 2954 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 2955 fillAttributedTypeLoc(TL, Chunk.getAttrs()); 2956 } 2957 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 2958 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 2959 TL.setCaretLoc(Chunk.Loc); 2960 } 2961 void VisitPointerTypeLoc(PointerTypeLoc TL) { 2962 assert(Chunk.Kind == DeclaratorChunk::Pointer); 2963 TL.setStarLoc(Chunk.Loc); 2964 } 2965 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 2966 assert(Chunk.Kind == DeclaratorChunk::Pointer); 2967 TL.setStarLoc(Chunk.Loc); 2968 } 2969 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 2970 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 2971 const CXXScopeSpec& SS = Chunk.Mem.Scope(); 2972 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); 2973 2974 const Type* ClsTy = TL.getClass(); 2975 QualType ClsQT = QualType(ClsTy, 0); 2976 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); 2977 // Now copy source location info into the type loc component. 2978 TypeLoc ClsTL = ClsTInfo->getTypeLoc(); 2979 switch (NNSLoc.getNestedNameSpecifier()->getKind()) { 2980 case NestedNameSpecifier::Identifier: 2981 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); 2982 { 2983 DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL); 2984 DNTLoc.setKeywordLoc(SourceLocation()); 2985 DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); 2986 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); 2987 } 2988 break; 2989 2990 case NestedNameSpecifier::TypeSpec: 2991 case NestedNameSpecifier::TypeSpecWithTemplate: 2992 if (isa<ElaboratedType>(ClsTy)) { 2993 ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL); 2994 ETLoc.setKeywordLoc(SourceLocation()); 2995 ETLoc.setQualifierLoc(NNSLoc.getPrefix()); 2996 TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); 2997 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); 2998 } else { 2999 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); 3000 } 3001 break; 3002 3003 case NestedNameSpecifier::Namespace: 3004 case NestedNameSpecifier::NamespaceAlias: 3005 case NestedNameSpecifier::Global: 3006 llvm_unreachable("Nested-name-specifier must name a type"); 3007 break; 3008 } 3009 3010 // Finally fill in MemberPointerLocInfo fields. 3011 TL.setStarLoc(Chunk.Loc); 3012 TL.setClassTInfo(ClsTInfo); 3013 } 3014 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 3015 assert(Chunk.Kind == DeclaratorChunk::Reference); 3016 // 'Amp' is misleading: this might have been originally 3017 /// spelled with AmpAmp. 3018 TL.setAmpLoc(Chunk.Loc); 3019 } 3020 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 3021 assert(Chunk.Kind == DeclaratorChunk::Reference); 3022 assert(!Chunk.Ref.LValueRef); 3023 TL.setAmpAmpLoc(Chunk.Loc); 3024 } 3025 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 3026 assert(Chunk.Kind == DeclaratorChunk::Array); 3027 TL.setLBracketLoc(Chunk.Loc); 3028 TL.setRBracketLoc(Chunk.EndLoc); 3029 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 3030 } 3031 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 3032 assert(Chunk.Kind == DeclaratorChunk::Function); 3033 TL.setLocalRangeBegin(Chunk.Loc); 3034 TL.setLocalRangeEnd(Chunk.EndLoc); 3035 TL.setTrailingReturn(!!Chunk.Fun.TrailingReturnType); 3036 3037 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 3038 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) { 3039 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 3040 TL.setArg(tpi++, Param); 3041 } 3042 // FIXME: exception specs 3043 } 3044 void VisitParenTypeLoc(ParenTypeLoc TL) { 3045 assert(Chunk.Kind == DeclaratorChunk::Paren); 3046 TL.setLParenLoc(Chunk.Loc); 3047 TL.setRParenLoc(Chunk.EndLoc); 3048 } 3049 3050 void VisitTypeLoc(TypeLoc TL) { 3051 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 3052 } 3053 }; 3054 } 3055 3056 /// \brief Create and instantiate a TypeSourceInfo with type source information. 3057 /// 3058 /// \param T QualType referring to the type as written in source code. 3059 /// 3060 /// \param ReturnTypeInfo For declarators whose return type does not show 3061 /// up in the normal place in the declaration specifiers (such as a C++ 3062 /// conversion function), this pointer will refer to a type source information 3063 /// for that return type. 3064 TypeSourceInfo * 3065 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 3066 TypeSourceInfo *ReturnTypeInfo) { 3067 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T); 3068 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 3069 3070 // Handle parameter packs whose type is a pack expansion. 3071 if (isa<PackExpansionType>(T)) { 3072 cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc()); 3073 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 3074 } 3075 3076 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 3077 while (isa<AttributedTypeLoc>(CurrTL)) { 3078 AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL); 3079 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs()); 3080 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 3081 } 3082 3083 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL); 3084 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 3085 } 3086 3087 // If we have different source information for the return type, use 3088 // that. This really only applies to C++ conversion functions. 3089 if (ReturnTypeInfo) { 3090 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 3091 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 3092 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 3093 } else { 3094 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL); 3095 } 3096 3097 return TInfo; 3098 } 3099 3100 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo. 3101 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { 3102 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 3103 // and Sema during declaration parsing. Try deallocating/caching them when 3104 // it's appropriate, instead of allocating them and keeping them around. 3105 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 3106 TypeAlignment); 3107 new (LocT) LocInfoType(T, TInfo); 3108 assert(LocT->getTypeClass() != T->getTypeClass() && 3109 "LocInfoType's TypeClass conflicts with an existing Type class"); 3110 return ParsedType::make(QualType(LocT, 0)); 3111 } 3112 3113 void LocInfoType::getAsStringInternal(std::string &Str, 3114 const PrintingPolicy &Policy) const { 3115 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" 3116 " was used directly instead of getting the QualType through" 3117 " GetTypeFromParser"); 3118 } 3119 3120 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 3121 // C99 6.7.6: Type names have no identifier. This is already validated by 3122 // the parser. 3123 assert(D.getIdentifier() == 0 && "Type name should have no identifier!"); 3124 3125 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 3126 QualType T = TInfo->getType(); 3127 if (D.isInvalidType()) 3128 return true; 3129 3130 // Make sure there are no unused decl attributes on the declarator. 3131 // We don't want to do this for ObjC parameters because we're going 3132 // to apply them to the actual parameter declaration. 3133 if (D.getContext() != Declarator::ObjCParameterContext) 3134 checkUnusedDeclAttributes(D); 3135 3136 if (getLangOptions().CPlusPlus) { 3137 // Check that there are no default arguments (C++ only). 3138 CheckExtraCXXDefaultArguments(D); 3139 } 3140 3141 return CreateParsedType(T, TInfo); 3142 } 3143 3144 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { 3145 QualType T = Context.getObjCInstanceType(); 3146 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 3147 return CreateParsedType(T, TInfo); 3148 } 3149 3150 3151 //===----------------------------------------------------------------------===// 3152 // Type Attribute Processing 3153 //===----------------------------------------------------------------------===// 3154 3155 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 3156 /// specified type. The attribute contains 1 argument, the id of the address 3157 /// space for the type. 3158 static void HandleAddressSpaceTypeAttribute(QualType &Type, 3159 const AttributeList &Attr, Sema &S){ 3160 3161 // If this type is already address space qualified, reject it. 3162 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by 3163 // qualifiers for two or more different address spaces." 3164 if (Type.getAddressSpace()) { 3165 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 3166 Attr.setInvalid(); 3167 return; 3168 } 3169 3170 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be 3171 // qualified by an address-space qualifier." 3172 if (Type->isFunctionType()) { 3173 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); 3174 Attr.setInvalid(); 3175 return; 3176 } 3177 3178 // Check the attribute arguments. 3179 if (Attr.getNumArgs() != 1) { 3180 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 3181 Attr.setInvalid(); 3182 return; 3183 } 3184 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0)); 3185 llvm::APSInt addrSpace(32); 3186 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() || 3187 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 3188 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int) 3189 << ASArgExpr->getSourceRange(); 3190 Attr.setInvalid(); 3191 return; 3192 } 3193 3194 // Bounds checking. 3195 if (addrSpace.isSigned()) { 3196 if (addrSpace.isNegative()) { 3197 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative) 3198 << ASArgExpr->getSourceRange(); 3199 Attr.setInvalid(); 3200 return; 3201 } 3202 addrSpace.setIsSigned(false); 3203 } 3204 llvm::APSInt max(addrSpace.getBitWidth()); 3205 max = Qualifiers::MaxAddressSpace; 3206 if (addrSpace > max) { 3207 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high) 3208 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange(); 3209 Attr.setInvalid(); 3210 return; 3211 } 3212 3213 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 3214 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 3215 } 3216 3217 /// handleObjCOwnershipTypeAttr - Process an objc_ownership 3218 /// attribute on the specified type. 3219 /// 3220 /// Returns 'true' if the attribute was handled. 3221 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 3222 AttributeList &attr, 3223 QualType &type) { 3224 if (!type->isObjCRetainableType() && !type->isDependentType()) 3225 return false; 3226 3227 Sema &S = state.getSema(); 3228 SourceLocation AttrLoc = attr.getLoc(); 3229 if (AttrLoc.isMacroID()) 3230 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first; 3231 3232 if (type.getQualifiers().getObjCLifetime()) { 3233 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) 3234 << type; 3235 return true; 3236 } 3237 3238 if (!attr.getParameterName()) { 3239 S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string) 3240 << "objc_ownership" << 1; 3241 attr.setInvalid(); 3242 return true; 3243 } 3244 3245 Qualifiers::ObjCLifetime lifetime; 3246 if (attr.getParameterName()->isStr("none")) 3247 lifetime = Qualifiers::OCL_ExplicitNone; 3248 else if (attr.getParameterName()->isStr("strong")) 3249 lifetime = Qualifiers::OCL_Strong; 3250 else if (attr.getParameterName()->isStr("weak")) 3251 lifetime = Qualifiers::OCL_Weak; 3252 else if (attr.getParameterName()->isStr("autoreleasing")) 3253 lifetime = Qualifiers::OCL_Autoreleasing; 3254 else { 3255 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) 3256 << "objc_ownership" << attr.getParameterName(); 3257 attr.setInvalid(); 3258 return true; 3259 } 3260 3261 // Consume lifetime attributes without further comment outside of 3262 // ARC mode. 3263 if (!S.getLangOptions().ObjCAutoRefCount) 3264 return true; 3265 3266 Qualifiers qs; 3267 qs.setObjCLifetime(lifetime); 3268 QualType origType = type; 3269 type = S.Context.getQualifiedType(type, qs); 3270 3271 // If we have a valid source location for the attribute, use an 3272 // AttributedType instead. 3273 if (AttrLoc.isValid()) 3274 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership, 3275 origType, type); 3276 3277 // Forbid __weak if the runtime doesn't support it. 3278 if (lifetime == Qualifiers::OCL_Weak && 3279 !S.getLangOptions().ObjCRuntimeHasWeak) { 3280 3281 // Actually, delay this until we know what we're parsing. 3282 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 3283 S.DelayedDiagnostics.add( 3284 sema::DelayedDiagnostic::makeForbiddenType( 3285 S.getSourceManager().getExpansionLoc(AttrLoc), 3286 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0)); 3287 } else { 3288 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime); 3289 } 3290 3291 attr.setInvalid(); 3292 return true; 3293 } 3294 3295 // Forbid __weak for class objects marked as 3296 // objc_arc_weak_reference_unavailable 3297 if (lifetime == Qualifiers::OCL_Weak) { 3298 QualType T = type; 3299 while (const PointerType *ptr = T->getAs<PointerType>()) 3300 T = ptr->getPointeeType(); 3301 if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) { 3302 ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl(); 3303 if (Class->isArcWeakrefUnavailable()) { 3304 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); 3305 S.Diag(ObjT->getInterfaceDecl()->getLocation(), 3306 diag::note_class_declared); 3307 } 3308 } 3309 } 3310 3311 return true; 3312 } 3313 3314 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type 3315 /// attribute on the specified type. Returns true to indicate that 3316 /// the attribute was handled, false to indicate that the type does 3317 /// not permit the attribute. 3318 static bool handleObjCGCTypeAttr(TypeProcessingState &state, 3319 AttributeList &attr, 3320 QualType &type) { 3321 Sema &S = state.getSema(); 3322 3323 // Delay if this isn't some kind of pointer. 3324 if (!type->isPointerType() && 3325 !type->isObjCObjectPointerType() && 3326 !type->isBlockPointerType()) 3327 return false; 3328 3329 if (type.getObjCGCAttr() != Qualifiers::GCNone) { 3330 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); 3331 attr.setInvalid(); 3332 return true; 3333 } 3334 3335 // Check the attribute arguments. 3336 if (!attr.getParameterName()) { 3337 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string) 3338 << "objc_gc" << 1; 3339 attr.setInvalid(); 3340 return true; 3341 } 3342 Qualifiers::GC GCAttr; 3343 if (attr.getNumArgs() != 0) { 3344 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 3345 attr.setInvalid(); 3346 return true; 3347 } 3348 if (attr.getParameterName()->isStr("weak")) 3349 GCAttr = Qualifiers::Weak; 3350 else if (attr.getParameterName()->isStr("strong")) 3351 GCAttr = Qualifiers::Strong; 3352 else { 3353 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) 3354 << "objc_gc" << attr.getParameterName(); 3355 attr.setInvalid(); 3356 return true; 3357 } 3358 3359 QualType origType = type; 3360 type = S.Context.getObjCGCQualType(origType, GCAttr); 3361 3362 // Make an attributed type to preserve the source information. 3363 if (attr.getLoc().isValid()) 3364 type = S.Context.getAttributedType(AttributedType::attr_objc_gc, 3365 origType, type); 3366 3367 return true; 3368 } 3369 3370 namespace { 3371 /// A helper class to unwrap a type down to a function for the 3372 /// purposes of applying attributes there. 3373 /// 3374 /// Use: 3375 /// FunctionTypeUnwrapper unwrapped(SemaRef, T); 3376 /// if (unwrapped.isFunctionType()) { 3377 /// const FunctionType *fn = unwrapped.get(); 3378 /// // change fn somehow 3379 /// T = unwrapped.wrap(fn); 3380 /// } 3381 struct FunctionTypeUnwrapper { 3382 enum WrapKind { 3383 Desugar, 3384 Parens, 3385 Pointer, 3386 BlockPointer, 3387 Reference, 3388 MemberPointer 3389 }; 3390 3391 QualType Original; 3392 const FunctionType *Fn; 3393 SmallVector<unsigned char /*WrapKind*/, 8> Stack; 3394 3395 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { 3396 while (true) { 3397 const Type *Ty = T.getTypePtr(); 3398 if (isa<FunctionType>(Ty)) { 3399 Fn = cast<FunctionType>(Ty); 3400 return; 3401 } else if (isa<ParenType>(Ty)) { 3402 T = cast<ParenType>(Ty)->getInnerType(); 3403 Stack.push_back(Parens); 3404 } else if (isa<PointerType>(Ty)) { 3405 T = cast<PointerType>(Ty)->getPointeeType(); 3406 Stack.push_back(Pointer); 3407 } else if (isa<BlockPointerType>(Ty)) { 3408 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3409 Stack.push_back(BlockPointer); 3410 } else if (isa<MemberPointerType>(Ty)) { 3411 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3412 Stack.push_back(MemberPointer); 3413 } else if (isa<ReferenceType>(Ty)) { 3414 T = cast<ReferenceType>(Ty)->getPointeeType(); 3415 Stack.push_back(Reference); 3416 } else { 3417 const Type *DTy = Ty->getUnqualifiedDesugaredType(); 3418 if (Ty == DTy) { 3419 Fn = 0; 3420 return; 3421 } 3422 3423 T = QualType(DTy, 0); 3424 Stack.push_back(Desugar); 3425 } 3426 } 3427 } 3428 3429 bool isFunctionType() const { return (Fn != 0); } 3430 const FunctionType *get() const { return Fn; } 3431 3432 QualType wrap(Sema &S, const FunctionType *New) { 3433 // If T wasn't modified from the unwrapped type, do nothing. 3434 if (New == get()) return Original; 3435 3436 Fn = New; 3437 return wrap(S.Context, Original, 0); 3438 } 3439 3440 private: 3441 QualType wrap(ASTContext &C, QualType Old, unsigned I) { 3442 if (I == Stack.size()) 3443 return C.getQualifiedType(Fn, Old.getQualifiers()); 3444 3445 // Build up the inner type, applying the qualifiers from the old 3446 // type to the new type. 3447 SplitQualType SplitOld = Old.split(); 3448 3449 // As a special case, tail-recurse if there are no qualifiers. 3450 if (SplitOld.second.empty()) 3451 return wrap(C, SplitOld.first, I); 3452 return C.getQualifiedType(wrap(C, SplitOld.first, I), SplitOld.second); 3453 } 3454 3455 QualType wrap(ASTContext &C, const Type *Old, unsigned I) { 3456 if (I == Stack.size()) return QualType(Fn, 0); 3457 3458 switch (static_cast<WrapKind>(Stack[I++])) { 3459 case Desugar: 3460 // This is the point at which we potentially lose source 3461 // information. 3462 return wrap(C, Old->getUnqualifiedDesugaredType(), I); 3463 3464 case Parens: { 3465 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); 3466 return C.getParenType(New); 3467 } 3468 3469 case Pointer: { 3470 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); 3471 return C.getPointerType(New); 3472 } 3473 3474 case BlockPointer: { 3475 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); 3476 return C.getBlockPointerType(New); 3477 } 3478 3479 case MemberPointer: { 3480 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); 3481 QualType New = wrap(C, OldMPT->getPointeeType(), I); 3482 return C.getMemberPointerType(New, OldMPT->getClass()); 3483 } 3484 3485 case Reference: { 3486 const ReferenceType *OldRef = cast<ReferenceType>(Old); 3487 QualType New = wrap(C, OldRef->getPointeeType(), I); 3488 if (isa<LValueReferenceType>(OldRef)) 3489 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); 3490 else 3491 return C.getRValueReferenceType(New); 3492 } 3493 } 3494 3495 llvm_unreachable("unknown wrapping kind"); 3496 return QualType(); 3497 } 3498 }; 3499 } 3500 3501 /// Process an individual function attribute. Returns true to 3502 /// indicate that the attribute was handled, false if it wasn't. 3503 static bool handleFunctionTypeAttr(TypeProcessingState &state, 3504 AttributeList &attr, 3505 QualType &type) { 3506 Sema &S = state.getSema(); 3507 3508 FunctionTypeUnwrapper unwrapped(S, type); 3509 3510 if (attr.getKind() == AttributeList::AT_noreturn) { 3511 if (S.CheckNoReturnAttr(attr)) 3512 return true; 3513 3514 // Delay if this is not a function type. 3515 if (!unwrapped.isFunctionType()) 3516 return false; 3517 3518 // Otherwise we can process right away. 3519 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); 3520 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 3521 return true; 3522 } 3523 3524 // ns_returns_retained is not always a type attribute, but if we got 3525 // here, we're treating it as one right now. 3526 if (attr.getKind() == AttributeList::AT_ns_returns_retained) { 3527 assert(S.getLangOptions().ObjCAutoRefCount && 3528 "ns_returns_retained treated as type attribute in non-ARC"); 3529 if (attr.getNumArgs()) return true; 3530 3531 // Delay if this is not a function type. 3532 if (!unwrapped.isFunctionType()) 3533 return false; 3534 3535 FunctionType::ExtInfo EI 3536 = unwrapped.get()->getExtInfo().withProducesResult(true); 3537 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 3538 return true; 3539 } 3540 3541 if (attr.getKind() == AttributeList::AT_regparm) { 3542 unsigned value; 3543 if (S.CheckRegparmAttr(attr, value)) 3544 return true; 3545 3546 // Delay if this is not a function type. 3547 if (!unwrapped.isFunctionType()) 3548 return false; 3549 3550 // Diagnose regparm with fastcall. 3551 const FunctionType *fn = unwrapped.get(); 3552 CallingConv CC = fn->getCallConv(); 3553 if (CC == CC_X86FastCall) { 3554 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 3555 << FunctionType::getNameForCallConv(CC) 3556 << "regparm"; 3557 attr.setInvalid(); 3558 return true; 3559 } 3560 3561 FunctionType::ExtInfo EI = 3562 unwrapped.get()->getExtInfo().withRegParm(value); 3563 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 3564 return true; 3565 } 3566 3567 // Otherwise, a calling convention. 3568 CallingConv CC; 3569 if (S.CheckCallingConvAttr(attr, CC)) 3570 return true; 3571 3572 // Delay if the type didn't work out to a function. 3573 if (!unwrapped.isFunctionType()) return false; 3574 3575 const FunctionType *fn = unwrapped.get(); 3576 CallingConv CCOld = fn->getCallConv(); 3577 if (S.Context.getCanonicalCallConv(CC) == 3578 S.Context.getCanonicalCallConv(CCOld)) { 3579 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC); 3580 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 3581 return true; 3582 } 3583 3584 if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) { 3585 // Should we diagnose reapplications of the same convention? 3586 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 3587 << FunctionType::getNameForCallConv(CC) 3588 << FunctionType::getNameForCallConv(CCOld); 3589 attr.setInvalid(); 3590 return true; 3591 } 3592 3593 // Diagnose the use of X86 fastcall on varargs or unprototyped functions. 3594 if (CC == CC_X86FastCall) { 3595 if (isa<FunctionNoProtoType>(fn)) { 3596 S.Diag(attr.getLoc(), diag::err_cconv_knr) 3597 << FunctionType::getNameForCallConv(CC); 3598 attr.setInvalid(); 3599 return true; 3600 } 3601 3602 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn); 3603 if (FnP->isVariadic()) { 3604 S.Diag(attr.getLoc(), diag::err_cconv_varargs) 3605 << FunctionType::getNameForCallConv(CC); 3606 attr.setInvalid(); 3607 return true; 3608 } 3609 3610 // Also diagnose fastcall with regparm. 3611 if (fn->getHasRegParm()) { 3612 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 3613 << "regparm" 3614 << FunctionType::getNameForCallConv(CC); 3615 attr.setInvalid(); 3616 return true; 3617 } 3618 } 3619 3620 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC); 3621 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 3622 return true; 3623 } 3624 3625 /// Handle OpenCL image access qualifiers: read_only, write_only, read_write 3626 static void HandleOpenCLImageAccessAttribute(QualType& CurType, 3627 const AttributeList &Attr, 3628 Sema &S) { 3629 // Check the attribute arguments. 3630 if (Attr.getNumArgs() != 1) { 3631 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 3632 Attr.setInvalid(); 3633 return; 3634 } 3635 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0)); 3636 llvm::APSInt arg(32); 3637 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 3638 !sizeExpr->isIntegerConstantExpr(arg, S.Context)) { 3639 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 3640 << "opencl_image_access" << sizeExpr->getSourceRange(); 3641 Attr.setInvalid(); 3642 return; 3643 } 3644 unsigned iarg = static_cast<unsigned>(arg.getZExtValue()); 3645 switch (iarg) { 3646 case CLIA_read_only: 3647 case CLIA_write_only: 3648 case CLIA_read_write: 3649 // Implemented in a separate patch 3650 break; 3651 default: 3652 // Implemented in a separate patch 3653 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 3654 << sizeExpr->getSourceRange(); 3655 Attr.setInvalid(); 3656 break; 3657 } 3658 } 3659 3660 /// HandleVectorSizeAttribute - this attribute is only applicable to integral 3661 /// and float scalars, although arrays, pointers, and function return values are 3662 /// allowed in conjunction with this construct. Aggregates with this attribute 3663 /// are invalid, even if they are of the same size as a corresponding scalar. 3664 /// The raw attribute should contain precisely 1 argument, the vector size for 3665 /// the variable, measured in bytes. If curType and rawAttr are well formed, 3666 /// this routine will return a new vector type. 3667 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, 3668 Sema &S) { 3669 // Check the attribute arguments. 3670 if (Attr.getNumArgs() != 1) { 3671 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 3672 Attr.setInvalid(); 3673 return; 3674 } 3675 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0)); 3676 llvm::APSInt vecSize(32); 3677 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 3678 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) { 3679 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 3680 << "vector_size" << sizeExpr->getSourceRange(); 3681 Attr.setInvalid(); 3682 return; 3683 } 3684 // the base type must be integer or float, and can't already be a vector. 3685 if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) { 3686 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 3687 Attr.setInvalid(); 3688 return; 3689 } 3690 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 3691 // vecSize is specified in bytes - convert to bits. 3692 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); 3693 3694 // the vector size needs to be an integral multiple of the type size. 3695 if (vectorSize % typeSize) { 3696 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 3697 << sizeExpr->getSourceRange(); 3698 Attr.setInvalid(); 3699 return; 3700 } 3701 if (vectorSize == 0) { 3702 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size) 3703 << sizeExpr->getSourceRange(); 3704 Attr.setInvalid(); 3705 return; 3706 } 3707 3708 // Success! Instantiate the vector type, the number of elements is > 0, and 3709 // not required to be a power of 2, unlike GCC. 3710 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, 3711 VectorType::GenericVector); 3712 } 3713 3714 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on 3715 /// a type. 3716 static void HandleExtVectorTypeAttr(QualType &CurType, 3717 const AttributeList &Attr, 3718 Sema &S) { 3719 Expr *sizeExpr; 3720 3721 // Special case where the argument is a template id. 3722 if (Attr.getParameterName()) { 3723 CXXScopeSpec SS; 3724 UnqualifiedId id; 3725 id.setIdentifier(Attr.getParameterName(), Attr.getLoc()); 3726 3727 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, id, false, 3728 false); 3729 if (Size.isInvalid()) 3730 return; 3731 3732 sizeExpr = Size.get(); 3733 } else { 3734 // check the attribute arguments. 3735 if (Attr.getNumArgs() != 1) { 3736 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 3737 return; 3738 } 3739 sizeExpr = Attr.getArg(0); 3740 } 3741 3742 // Create the vector type. 3743 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc()); 3744 if (!T.isNull()) 3745 CurType = T; 3746 } 3747 3748 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and 3749 /// "neon_polyvector_type" attributes are used to create vector types that 3750 /// are mangled according to ARM's ABI. Otherwise, these types are identical 3751 /// to those created with the "vector_size" attribute. Unlike "vector_size" 3752 /// the argument to these Neon attributes is the number of vector elements, 3753 /// not the vector size in bytes. The vector width and element type must 3754 /// match one of the standard Neon vector types. 3755 static void HandleNeonVectorTypeAttr(QualType& CurType, 3756 const AttributeList &Attr, Sema &S, 3757 VectorType::VectorKind VecKind, 3758 const char *AttrName) { 3759 // Check the attribute arguments. 3760 if (Attr.getNumArgs() != 1) { 3761 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 3762 Attr.setInvalid(); 3763 return; 3764 } 3765 // The number of elements must be an ICE. 3766 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0)); 3767 llvm::APSInt numEltsInt(32); 3768 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() || 3769 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) { 3770 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 3771 << AttrName << numEltsExpr->getSourceRange(); 3772 Attr.setInvalid(); 3773 return; 3774 } 3775 // Only certain element types are supported for Neon vectors. 3776 const BuiltinType* BTy = CurType->getAs<BuiltinType>(); 3777 if (!BTy || 3778 (VecKind == VectorType::NeonPolyVector && 3779 BTy->getKind() != BuiltinType::SChar && 3780 BTy->getKind() != BuiltinType::Short) || 3781 (BTy->getKind() != BuiltinType::SChar && 3782 BTy->getKind() != BuiltinType::UChar && 3783 BTy->getKind() != BuiltinType::Short && 3784 BTy->getKind() != BuiltinType::UShort && 3785 BTy->getKind() != BuiltinType::Int && 3786 BTy->getKind() != BuiltinType::UInt && 3787 BTy->getKind() != BuiltinType::LongLong && 3788 BTy->getKind() != BuiltinType::ULongLong && 3789 BTy->getKind() != BuiltinType::Float)) { 3790 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType; 3791 Attr.setInvalid(); 3792 return; 3793 } 3794 // The total size of the vector must be 64 or 128 bits. 3795 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 3796 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); 3797 unsigned vecSize = typeSize * numElts; 3798 if (vecSize != 64 && vecSize != 128) { 3799 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; 3800 Attr.setInvalid(); 3801 return; 3802 } 3803 3804 CurType = S.Context.getVectorType(CurType, numElts, VecKind); 3805 } 3806 3807 static void processTypeAttrs(TypeProcessingState &state, QualType &type, 3808 bool isDeclSpec, AttributeList *attrs) { 3809 // Scan through and apply attributes to this type where it makes sense. Some 3810 // attributes (such as __address_space__, __vector_size__, etc) apply to the 3811 // type, but others can be present in the type specifiers even though they 3812 // apply to the decl. Here we apply type attributes and ignore the rest. 3813 3814 AttributeList *next; 3815 do { 3816 AttributeList &attr = *attrs; 3817 next = attr.getNext(); 3818 3819 // Skip attributes that were marked to be invalid. 3820 if (attr.isInvalid()) 3821 continue; 3822 3823 // If this is an attribute we can handle, do so now, 3824 // otherwise, add it to the FnAttrs list for rechaining. 3825 switch (attr.getKind()) { 3826 default: break; 3827 3828 case AttributeList::AT_may_alias: 3829 // FIXME: This attribute needs to actually be handled, but if we ignore 3830 // it it breaks large amounts of Linux software. 3831 attr.setUsedAsTypeAttr(); 3832 break; 3833 case AttributeList::AT_address_space: 3834 HandleAddressSpaceTypeAttribute(type, attr, state.getSema()); 3835 attr.setUsedAsTypeAttr(); 3836 break; 3837 OBJC_POINTER_TYPE_ATTRS_CASELIST: 3838 if (!handleObjCPointerTypeAttr(state, attr, type)) 3839 distributeObjCPointerTypeAttr(state, attr, type); 3840 attr.setUsedAsTypeAttr(); 3841 break; 3842 case AttributeList::AT_vector_size: 3843 HandleVectorSizeAttr(type, attr, state.getSema()); 3844 attr.setUsedAsTypeAttr(); 3845 break; 3846 case AttributeList::AT_ext_vector_type: 3847 if (state.getDeclarator().getDeclSpec().getStorageClassSpec() 3848 != DeclSpec::SCS_typedef) 3849 HandleExtVectorTypeAttr(type, attr, state.getSema()); 3850 attr.setUsedAsTypeAttr(); 3851 break; 3852 case AttributeList::AT_neon_vector_type: 3853 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 3854 VectorType::NeonVector, "neon_vector_type"); 3855 attr.setUsedAsTypeAttr(); 3856 break; 3857 case AttributeList::AT_neon_polyvector_type: 3858 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 3859 VectorType::NeonPolyVector, 3860 "neon_polyvector_type"); 3861 attr.setUsedAsTypeAttr(); 3862 break; 3863 case AttributeList::AT_opencl_image_access: 3864 HandleOpenCLImageAccessAttribute(type, attr, state.getSema()); 3865 attr.setUsedAsTypeAttr(); 3866 break; 3867 3868 case AttributeList::AT_ns_returns_retained: 3869 if (!state.getSema().getLangOptions().ObjCAutoRefCount) 3870 break; 3871 // fallthrough into the function attrs 3872 3873 FUNCTION_TYPE_ATTRS_CASELIST: 3874 attr.setUsedAsTypeAttr(); 3875 3876 // Never process function type attributes as part of the 3877 // declaration-specifiers. 3878 if (isDeclSpec) 3879 distributeFunctionTypeAttrFromDeclSpec(state, attr, type); 3880 3881 // Otherwise, handle the possible delays. 3882 else if (!handleFunctionTypeAttr(state, attr, type)) 3883 distributeFunctionTypeAttr(state, attr, type); 3884 break; 3885 } 3886 } while ((attrs = next)); 3887 } 3888 3889 /// \brief Ensure that the type of the given expression is complete. 3890 /// 3891 /// This routine checks whether the expression \p E has a complete type. If the 3892 /// expression refers to an instantiable construct, that instantiation is 3893 /// performed as needed to complete its type. Furthermore 3894 /// Sema::RequireCompleteType is called for the expression's type (or in the 3895 /// case of a reference type, the referred-to type). 3896 /// 3897 /// \param E The expression whose type is required to be complete. 3898 /// \param PD The partial diagnostic that will be printed out if the type cannot 3899 /// be completed. 3900 /// 3901 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false 3902 /// otherwise. 3903 bool Sema::RequireCompleteExprType(Expr *E, const PartialDiagnostic &PD, 3904 std::pair<SourceLocation, 3905 PartialDiagnostic> Note) { 3906 QualType T = E->getType(); 3907 3908 // Fast path the case where the type is already complete. 3909 if (!T->isIncompleteType()) 3910 return false; 3911 3912 // Incomplete array types may be completed by the initializer attached to 3913 // their definitions. For static data members of class templates we need to 3914 // instantiate the definition to get this initializer and complete the type. 3915 if (T->isIncompleteArrayType()) { 3916 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3917 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 3918 if (Var->isStaticDataMember() && 3919 Var->getInstantiatedFromStaticDataMember()) { 3920 3921 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 3922 assert(MSInfo && "Missing member specialization information?"); 3923 if (MSInfo->getTemplateSpecializationKind() 3924 != TSK_ExplicitSpecialization) { 3925 // If we don't already have a point of instantiation, this is it. 3926 if (MSInfo->getPointOfInstantiation().isInvalid()) { 3927 MSInfo->setPointOfInstantiation(E->getLocStart()); 3928 3929 // This is a modification of an existing AST node. Notify 3930 // listeners. 3931 if (ASTMutationListener *L = getASTMutationListener()) 3932 L->StaticDataMemberInstantiated(Var); 3933 } 3934 3935 InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var); 3936 3937 // Update the type to the newly instantiated definition's type both 3938 // here and within the expression. 3939 if (VarDecl *Def = Var->getDefinition()) { 3940 DRE->setDecl(Def); 3941 T = Def->getType(); 3942 DRE->setType(T); 3943 E->setType(T); 3944 } 3945 } 3946 3947 // We still go on to try to complete the type independently, as it 3948 // may also require instantiations or diagnostics if it remains 3949 // incomplete. 3950 } 3951 } 3952 } 3953 } 3954 3955 // FIXME: Are there other cases which require instantiating something other 3956 // than the type to complete the type of an expression? 3957 3958 // Look through reference types and complete the referred type. 3959 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 3960 T = Ref->getPointeeType(); 3961 3962 return RequireCompleteType(E->getExprLoc(), T, PD, Note); 3963 } 3964 3965 /// @brief Ensure that the type T is a complete type. 3966 /// 3967 /// This routine checks whether the type @p T is complete in any 3968 /// context where a complete type is required. If @p T is a complete 3969 /// type, returns false. If @p T is a class template specialization, 3970 /// this routine then attempts to perform class template 3971 /// instantiation. If instantiation fails, or if @p T is incomplete 3972 /// and cannot be completed, issues the diagnostic @p diag (giving it 3973 /// the type @p T) and returns true. 3974 /// 3975 /// @param Loc The location in the source that the incomplete type 3976 /// diagnostic should refer to. 3977 /// 3978 /// @param T The type that this routine is examining for completeness. 3979 /// 3980 /// @param PD The partial diagnostic that will be printed out if T is not a 3981 /// complete type. 3982 /// 3983 /// @returns @c true if @p T is incomplete and a diagnostic was emitted, 3984 /// @c false otherwise. 3985 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 3986 const PartialDiagnostic &PD, 3987 std::pair<SourceLocation, 3988 PartialDiagnostic> Note) { 3989 unsigned diag = PD.getDiagID(); 3990 3991 // FIXME: Add this assertion to make sure we always get instantiation points. 3992 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 3993 // FIXME: Add this assertion to help us flush out problems with 3994 // checking for dependent types and type-dependent expressions. 3995 // 3996 // assert(!T->isDependentType() && 3997 // "Can't ask whether a dependent type is complete"); 3998 3999 // If we have a complete type, we're done. 4000 if (!T->isIncompleteType()) 4001 return false; 4002 4003 // If we have a class template specialization or a class member of a 4004 // class template specialization, or an array with known size of such, 4005 // try to instantiate it. 4006 QualType MaybeTemplate = T; 4007 if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T)) 4008 MaybeTemplate = Array->getElementType(); 4009 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) { 4010 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 4011 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 4012 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) 4013 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec, 4014 TSK_ImplicitInstantiation, 4015 /*Complain=*/diag != 0); 4016 } else if (CXXRecordDecl *Rec 4017 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 4018 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) { 4019 MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo(); 4020 assert(MSInfo && "Missing member specialization information?"); 4021 // This record was instantiated from a class within a template. 4022 if (MSInfo->getTemplateSpecializationKind() 4023 != TSK_ExplicitSpecialization) 4024 return InstantiateClass(Loc, Rec, Pattern, 4025 getTemplateInstantiationArgs(Rec), 4026 TSK_ImplicitInstantiation, 4027 /*Complain=*/diag != 0); 4028 } 4029 } 4030 } 4031 4032 if (diag == 0) 4033 return true; 4034 4035 const TagType *Tag = T->getAs<TagType>(); 4036 4037 // Avoid diagnosing invalid decls as incomplete. 4038 if (Tag && Tag->getDecl()->isInvalidDecl()) 4039 return true; 4040 4041 // Give the external AST source a chance to complete the type. 4042 if (Tag && Tag->getDecl()->hasExternalLexicalStorage()) { 4043 Context.getExternalSource()->CompleteType(Tag->getDecl()); 4044 if (!Tag->isIncompleteType()) 4045 return false; 4046 } 4047 4048 // We have an incomplete type. Produce a diagnostic. 4049 Diag(Loc, PD) << T; 4050 4051 // If we have a note, produce it. 4052 if (!Note.first.isInvalid()) 4053 Diag(Note.first, Note.second); 4054 4055 // If the type was a forward declaration of a class/struct/union 4056 // type, produce a note. 4057 if (Tag && !Tag->getDecl()->isInvalidDecl()) 4058 Diag(Tag->getDecl()->getLocation(), 4059 Tag->isBeingDefined() ? diag::note_type_being_defined 4060 : diag::note_forward_declaration) 4061 << QualType(Tag, 0); 4062 4063 return true; 4064 } 4065 4066 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 4067 const PartialDiagnostic &PD) { 4068 return RequireCompleteType(Loc, T, PD, 4069 std::make_pair(SourceLocation(), PDiag(0))); 4070 } 4071 4072 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 4073 unsigned DiagID) { 4074 return RequireCompleteType(Loc, T, PDiag(DiagID), 4075 std::make_pair(SourceLocation(), PDiag(0))); 4076 } 4077 4078 /// @brief Ensure that the type T is a literal type. 4079 /// 4080 /// This routine checks whether the type @p T is a literal type. If @p T is an 4081 /// incomplete type, an attempt is made to complete it. If @p T is a literal 4082 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, 4083 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving 4084 /// it the type @p T), along with notes explaining why the type is not a 4085 /// literal type, and returns true. 4086 /// 4087 /// @param Loc The location in the source that the non-literal type 4088 /// diagnostic should refer to. 4089 /// 4090 /// @param T The type that this routine is examining for literalness. 4091 /// 4092 /// @param PD The partial diagnostic that will be printed out if T is not a 4093 /// literal type. 4094 /// 4095 /// @param AllowIncompleteType If true, an incomplete type will be considered 4096 /// acceptable. 4097 /// 4098 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, 4099 /// @c false otherwise. 4100 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, 4101 const PartialDiagnostic &PD, 4102 bool AllowIncompleteType) { 4103 assert(!T->isDependentType() && "type should not be dependent"); 4104 4105 bool Incomplete = RequireCompleteType(Loc, T, 0); 4106 if (T->isLiteralType() || (AllowIncompleteType && Incomplete)) 4107 return false; 4108 4109 if (PD.getDiagID() == 0) 4110 return true; 4111 4112 Diag(Loc, PD) << T; 4113 4114 if (T->isVariableArrayType()) 4115 return true; 4116 4117 const RecordType *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>(); 4118 if (!RT) 4119 return true; 4120 4121 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4122 4123 // If the class has virtual base classes, then it's not an aggregate, and 4124 // cannot have any constexpr constructors, so is non-literal. This is better 4125 // to diagnose than the resulting absence of constexpr constructors. 4126 if (RD->getNumVBases()) { 4127 Diag(RD->getLocation(), diag::note_non_literal_virtual_base) 4128 << RD->isStruct() << RD->getNumVBases(); 4129 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 4130 E = RD->vbases_end(); I != E; ++I) 4131 Diag(I->getSourceRange().getBegin(), 4132 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 4133 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor()) { 4134 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; 4135 4136 switch (RD->getTemplateSpecializationKind()) { 4137 case TSK_Undeclared: 4138 case TSK_ExplicitSpecialization: 4139 break; 4140 4141 case TSK_ImplicitInstantiation: 4142 case TSK_ExplicitInstantiationDeclaration: 4143 case TSK_ExplicitInstantiationDefinition: 4144 // If the base template had constexpr constructors which were 4145 // instantiated as non-constexpr constructors, explain why. 4146 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 4147 E = RD->ctor_end(); I != E; ++I) { 4148 if ((*I)->isCopyConstructor() || (*I)->isMoveConstructor()) 4149 continue; 4150 4151 FunctionDecl *Base = (*I)->getInstantiatedFromMemberFunction(); 4152 if (Base && Base->isConstexpr()) 4153 CheckConstexprFunctionDecl(*I, CCK_NoteNonConstexprInstantiation); 4154 } 4155 } 4156 } else if (RD->hasNonLiteralTypeFieldsOrBases()) { 4157 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4158 E = RD->bases_end(); I != E; ++I) { 4159 if (!I->getType()->isLiteralType()) { 4160 Diag(I->getSourceRange().getBegin(), 4161 diag::note_non_literal_base_class) 4162 << RD << I->getType() << I->getSourceRange(); 4163 return true; 4164 } 4165 } 4166 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 4167 E = RD->field_end(); I != E; ++I) { 4168 if (!(*I)->getType()->isLiteralType()) { 4169 Diag((*I)->getLocation(), diag::note_non_literal_field) 4170 << RD << (*I) << (*I)->getType(); 4171 return true; 4172 } else if ((*I)->isMutable()) { 4173 Diag((*I)->getLocation(), diag::note_non_literal_mutable_field) << RD; 4174 return true; 4175 } 4176 } 4177 } else if (!RD->hasTrivialDestructor()) { 4178 // All fields and bases are of literal types, so have trivial destructors. 4179 // If this class's destructor is non-trivial it must be user-declared. 4180 CXXDestructorDecl *Dtor = RD->getDestructor(); 4181 assert(Dtor && "class has literal fields and bases but no dtor?"); 4182 if (!Dtor) 4183 return true; 4184 4185 Diag(Dtor->getLocation(), Dtor->isUserProvided() ? 4186 diag::note_non_literal_user_provided_dtor : 4187 diag::note_non_literal_nontrivial_dtor) << RD; 4188 } 4189 4190 return true; 4191 } 4192 4193 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword 4194 /// and qualified by the nested-name-specifier contained in SS. 4195 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 4196 const CXXScopeSpec &SS, QualType T) { 4197 if (T.isNull()) 4198 return T; 4199 NestedNameSpecifier *NNS; 4200 if (SS.isValid()) 4201 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 4202 else { 4203 if (Keyword == ETK_None) 4204 return T; 4205 NNS = 0; 4206 } 4207 return Context.getElaboratedType(Keyword, NNS, T); 4208 } 4209 4210 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { 4211 ExprResult ER = CheckPlaceholderExpr(E); 4212 if (ER.isInvalid()) return QualType(); 4213 E = ER.take(); 4214 4215 if (!E->isTypeDependent()) { 4216 QualType T = E->getType(); 4217 if (const TagType *TT = T->getAs<TagType>()) 4218 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); 4219 } 4220 return Context.getTypeOfExprType(E); 4221 } 4222 4223 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) { 4224 ExprResult ER = CheckPlaceholderExpr(E); 4225 if (ER.isInvalid()) return QualType(); 4226 E = ER.take(); 4227 4228 return Context.getDecltypeType(E); 4229 } 4230 4231 QualType Sema::BuildUnaryTransformType(QualType BaseType, 4232 UnaryTransformType::UTTKind UKind, 4233 SourceLocation Loc) { 4234 switch (UKind) { 4235 case UnaryTransformType::EnumUnderlyingType: 4236 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { 4237 Diag(Loc, diag::err_only_enums_have_underlying_types); 4238 return QualType(); 4239 } else { 4240 QualType Underlying = BaseType; 4241 if (!BaseType->isDependentType()) { 4242 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl(); 4243 assert(ED && "EnumType has no EnumDecl"); 4244 DiagnoseUseOfDecl(ED, Loc); 4245 Underlying = ED->getIntegerType(); 4246 } 4247 assert(!Underlying.isNull()); 4248 return Context.getUnaryTransformType(BaseType, Underlying, 4249 UnaryTransformType::EnumUnderlyingType); 4250 } 4251 } 4252 llvm_unreachable("unknown unary transform type"); 4253 } 4254 4255 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { 4256 if (!T->isDependentType()) { 4257 int DisallowedKind = -1; 4258 if (T->isIncompleteType()) 4259 // FIXME: It isn't entirely clear whether incomplete atomic types 4260 // are allowed or not; for simplicity, ban them for the moment. 4261 DisallowedKind = 0; 4262 else if (T->isArrayType()) 4263 DisallowedKind = 1; 4264 else if (T->isFunctionType()) 4265 DisallowedKind = 2; 4266 else if (T->isReferenceType()) 4267 DisallowedKind = 3; 4268 else if (T->isAtomicType()) 4269 DisallowedKind = 4; 4270 else if (T.hasQualifiers()) 4271 DisallowedKind = 5; 4272 else if (!T.isTriviallyCopyableType(Context)) 4273 // Some other non-trivially-copyable type (probably a C++ class) 4274 DisallowedKind = 6; 4275 4276 if (DisallowedKind != -1) { 4277 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; 4278 return QualType(); 4279 } 4280 4281 // FIXME: Do we need any handling for ARC here? 4282 } 4283 4284 // Build the pointer type. 4285 return Context.getAtomicType(T); 4286 } 4287