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