SemaType.cpp revision 1652ed1cd2cb63e0d0cb74c67a40d9dc5cab6b89
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/AST/ASTConsumer.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/ASTMutationListener.h" 18#include "clang/AST/CXXInheritance.h" 19#include "clang/AST/DeclObjC.h" 20#include "clang/AST/DeclTemplate.h" 21#include "clang/AST/Expr.h" 22#include "clang/AST/TypeLoc.h" 23#include "clang/AST/TypeLocVisitor.h" 24#include "clang/Basic/OpenCL.h" 25#include "clang/Basic/PartialDiagnostic.h" 26#include "clang/Basic/TargetInfo.h" 27#include "clang/Lex/Preprocessor.h" 28#include "clang/Parse/ParseDiagnostic.h" 29#include "clang/Sema/DeclSpec.h" 30#include "clang/Sema/DelayedDiagnostic.h" 31#include "clang/Sema/Lookup.h" 32#include "clang/Sema/ScopeInfo.h" 33#include "clang/Sema/Template.h" 34#include "llvm/ADT/SmallPtrSet.h" 35#include "llvm/ADT/SmallString.h" 36#include "llvm/Support/ErrorHandling.h" 37#include "TypeLocBuilder.h" 38 39using namespace clang; 40 41enum TypeDiagSelector { 42 TDS_Function, 43 TDS_Pointer, 44 TDS_ObjCObjOrBlock 45}; 46 47/// isOmittedBlockReturnType - Return true if this declarator is missing a 48/// return type because this is a omitted return type on a block literal. 49static bool isOmittedBlockReturnType(const Declarator &D) { 50 if (D.getContext() != Declarator::BlockLiteralContext || 51 D.getDeclSpec().hasTypeSpecifier()) 52 return false; 53 54 if (D.getNumTypeObjects() == 0) 55 return true; // ^{ ... } 56 57 if (D.getNumTypeObjects() == 1 && 58 D.getTypeObject(0).Kind == DeclaratorChunk::Function) 59 return true; // ^(int X, float Y) { ... } 60 61 return false; 62} 63 64/// diagnoseBadTypeAttribute - Diagnoses a type attribute which 65/// doesn't apply to the given type. 66static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr, 67 QualType type) { 68 TypeDiagSelector WhichType; 69 bool useExpansionLoc = true; 70 switch (attr.getKind()) { 71 case AttributeList::AT_ObjCGC: WhichType = TDS_Pointer; break; 72 case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break; 73 default: 74 // Assume everything else was a function attribute. 75 WhichType = TDS_Function; 76 useExpansionLoc = false; 77 break; 78 } 79 80 SourceLocation loc = attr.getLoc(); 81 StringRef name = attr.getName()->getName(); 82 83 // The GC attributes are usually written with macros; special-case them. 84 if (useExpansionLoc && loc.isMacroID() && attr.getParameterName()) { 85 if (attr.getParameterName()->isStr("strong")) { 86 if (S.findMacroSpelling(loc, "__strong")) name = "__strong"; 87 } else if (attr.getParameterName()->isStr("weak")) { 88 if (S.findMacroSpelling(loc, "__weak")) name = "__weak"; 89 } 90 } 91 92 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType 93 << type; 94} 95 96// objc_gc applies to Objective-C pointers or, otherwise, to the 97// smallest available pointer type (i.e. 'void*' in 'void**'). 98#define OBJC_POINTER_TYPE_ATTRS_CASELIST \ 99 case AttributeList::AT_ObjCGC: \ 100 case AttributeList::AT_ObjCOwnership 101 102// Function type attributes. 103#define FUNCTION_TYPE_ATTRS_CASELIST \ 104 case AttributeList::AT_NoReturn: \ 105 case AttributeList::AT_CDecl: \ 106 case AttributeList::AT_FastCall: \ 107 case AttributeList::AT_StdCall: \ 108 case AttributeList::AT_ThisCall: \ 109 case AttributeList::AT_Pascal: \ 110 case AttributeList::AT_Regparm: \ 111 case AttributeList::AT_Pcs: \ 112 case AttributeList::AT_PnaclCall: \ 113 case AttributeList::AT_IntelOclBicc 114 115// Microsoft-specific type qualifiers. 116#define MS_TYPE_ATTRS_CASELIST \ 117 case AttributeList::AT_Ptr32: \ 118 case AttributeList::AT_Ptr64: \ 119 case AttributeList::AT_SPtr: \ 120 case AttributeList::AT_UPtr 121 122namespace { 123 /// An object which stores processing state for the entire 124 /// GetTypeForDeclarator process. 125 class TypeProcessingState { 126 Sema &sema; 127 128 /// The declarator being processed. 129 Declarator &declarator; 130 131 /// The index of the declarator chunk we're currently processing. 132 /// May be the total number of valid chunks, indicating the 133 /// DeclSpec. 134 unsigned chunkIndex; 135 136 /// Whether there are non-trivial modifications to the decl spec. 137 bool trivial; 138 139 /// Whether we saved the attributes in the decl spec. 140 bool hasSavedAttrs; 141 142 /// The original set of attributes on the DeclSpec. 143 SmallVector<AttributeList*, 2> savedAttrs; 144 145 /// A list of attributes to diagnose the uselessness of when the 146 /// processing is complete. 147 SmallVector<AttributeList*, 2> ignoredTypeAttrs; 148 149 public: 150 TypeProcessingState(Sema &sema, Declarator &declarator) 151 : sema(sema), declarator(declarator), 152 chunkIndex(declarator.getNumTypeObjects()), 153 trivial(true), hasSavedAttrs(false) {} 154 155 Sema &getSema() const { 156 return sema; 157 } 158 159 Declarator &getDeclarator() const { 160 return declarator; 161 } 162 163 bool isProcessingDeclSpec() const { 164 return chunkIndex == declarator.getNumTypeObjects(); 165 } 166 167 unsigned getCurrentChunkIndex() const { 168 return chunkIndex; 169 } 170 171 void setCurrentChunkIndex(unsigned idx) { 172 assert(idx <= declarator.getNumTypeObjects()); 173 chunkIndex = idx; 174 } 175 176 AttributeList *&getCurrentAttrListRef() const { 177 if (isProcessingDeclSpec()) 178 return getMutableDeclSpec().getAttributes().getListRef(); 179 return declarator.getTypeObject(chunkIndex).getAttrListRef(); 180 } 181 182 /// Save the current set of attributes on the DeclSpec. 183 void saveDeclSpecAttrs() { 184 // Don't try to save them multiple times. 185 if (hasSavedAttrs) return; 186 187 DeclSpec &spec = getMutableDeclSpec(); 188 for (AttributeList *attr = spec.getAttributes().getList(); attr; 189 attr = attr->getNext()) 190 savedAttrs.push_back(attr); 191 trivial &= savedAttrs.empty(); 192 hasSavedAttrs = true; 193 } 194 195 /// Record that we had nowhere to put the given type attribute. 196 /// We will diagnose such attributes later. 197 void addIgnoredTypeAttr(AttributeList &attr) { 198 ignoredTypeAttrs.push_back(&attr); 199 } 200 201 /// Diagnose all the ignored type attributes, given that the 202 /// declarator worked out to the given type. 203 void diagnoseIgnoredTypeAttrs(QualType type) const { 204 for (SmallVectorImpl<AttributeList*>::const_iterator 205 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end(); 206 i != e; ++i) 207 diagnoseBadTypeAttribute(getSema(), **i, type); 208 } 209 210 ~TypeProcessingState() { 211 if (trivial) return; 212 213 restoreDeclSpecAttrs(); 214 } 215 216 private: 217 DeclSpec &getMutableDeclSpec() const { 218 return const_cast<DeclSpec&>(declarator.getDeclSpec()); 219 } 220 221 void restoreDeclSpecAttrs() { 222 assert(hasSavedAttrs); 223 224 if (savedAttrs.empty()) { 225 getMutableDeclSpec().getAttributes().set(0); 226 return; 227 } 228 229 getMutableDeclSpec().getAttributes().set(savedAttrs[0]); 230 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i) 231 savedAttrs[i]->setNext(savedAttrs[i+1]); 232 savedAttrs.back()->setNext(0); 233 } 234 }; 235 236 /// Basically std::pair except that we really want to avoid an 237 /// implicit operator= for safety concerns. It's also a minor 238 /// link-time optimization for this to be a private type. 239 struct AttrAndList { 240 /// The attribute. 241 AttributeList &first; 242 243 /// The head of the list the attribute is currently in. 244 AttributeList *&second; 245 246 AttrAndList(AttributeList &attr, AttributeList *&head) 247 : first(attr), second(head) {} 248 }; 249} 250 251namespace llvm { 252 template <> struct isPodLike<AttrAndList> { 253 static const bool value = true; 254 }; 255} 256 257static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) { 258 attr.setNext(head); 259 head = &attr; 260} 261 262static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) { 263 if (head == &attr) { 264 head = attr.getNext(); 265 return; 266 } 267 268 AttributeList *cur = head; 269 while (true) { 270 assert(cur && cur->getNext() && "ran out of attrs?"); 271 if (cur->getNext() == &attr) { 272 cur->setNext(attr.getNext()); 273 return; 274 } 275 cur = cur->getNext(); 276 } 277} 278 279static void moveAttrFromListToList(AttributeList &attr, 280 AttributeList *&fromList, 281 AttributeList *&toList) { 282 spliceAttrOutOfList(attr, fromList); 283 spliceAttrIntoList(attr, toList); 284} 285 286/// The location of a type attribute. 287enum TypeAttrLocation { 288 /// The attribute is in the decl-specifier-seq. 289 TAL_DeclSpec, 290 /// The attribute is part of a DeclaratorChunk. 291 TAL_DeclChunk, 292 /// The attribute is immediately after the declaration's name. 293 TAL_DeclName 294}; 295 296static void processTypeAttrs(TypeProcessingState &state, 297 QualType &type, TypeAttrLocation TAL, 298 AttributeList *attrs); 299 300static bool handleFunctionTypeAttr(TypeProcessingState &state, 301 AttributeList &attr, 302 QualType &type); 303 304static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, 305 AttributeList &attr, 306 QualType &type); 307 308static bool handleObjCGCTypeAttr(TypeProcessingState &state, 309 AttributeList &attr, QualType &type); 310 311static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 312 AttributeList &attr, QualType &type); 313 314static bool handleObjCPointerTypeAttr(TypeProcessingState &state, 315 AttributeList &attr, QualType &type) { 316 if (attr.getKind() == AttributeList::AT_ObjCGC) 317 return handleObjCGCTypeAttr(state, attr, type); 318 assert(attr.getKind() == AttributeList::AT_ObjCOwnership); 319 return handleObjCOwnershipTypeAttr(state, attr, type); 320} 321 322/// Given the index of a declarator chunk, check whether that chunk 323/// directly specifies the return type of a function and, if so, find 324/// an appropriate place for it. 325/// 326/// \param i - a notional index which the search will start 327/// immediately inside 328static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator, 329 unsigned i) { 330 assert(i <= declarator.getNumTypeObjects()); 331 332 DeclaratorChunk *result = 0; 333 334 // First, look inwards past parens for a function declarator. 335 for (; i != 0; --i) { 336 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1); 337 switch (fnChunk.Kind) { 338 case DeclaratorChunk::Paren: 339 continue; 340 341 // If we find anything except a function, bail out. 342 case DeclaratorChunk::Pointer: 343 case DeclaratorChunk::BlockPointer: 344 case DeclaratorChunk::Array: 345 case DeclaratorChunk::Reference: 346 case DeclaratorChunk::MemberPointer: 347 return result; 348 349 // If we do find a function declarator, scan inwards from that, 350 // looking for a block-pointer declarator. 351 case DeclaratorChunk::Function: 352 for (--i; i != 0; --i) { 353 DeclaratorChunk &blockChunk = declarator.getTypeObject(i-1); 354 switch (blockChunk.Kind) { 355 case DeclaratorChunk::Paren: 356 case DeclaratorChunk::Pointer: 357 case DeclaratorChunk::Array: 358 case DeclaratorChunk::Function: 359 case DeclaratorChunk::Reference: 360 case DeclaratorChunk::MemberPointer: 361 continue; 362 case DeclaratorChunk::BlockPointer: 363 result = &blockChunk; 364 goto continue_outer; 365 } 366 llvm_unreachable("bad declarator chunk kind"); 367 } 368 369 // If we run out of declarators doing that, we're done. 370 return result; 371 } 372 llvm_unreachable("bad declarator chunk kind"); 373 374 // Okay, reconsider from our new point. 375 continue_outer: ; 376 } 377 378 // Ran out of chunks, bail out. 379 return result; 380} 381 382/// Given that an objc_gc attribute was written somewhere on a 383/// declaration *other* than on the declarator itself (for which, use 384/// distributeObjCPointerTypeAttrFromDeclarator), and given that it 385/// didn't apply in whatever position it was written in, try to move 386/// it to a more appropriate position. 387static void distributeObjCPointerTypeAttr(TypeProcessingState &state, 388 AttributeList &attr, 389 QualType type) { 390 Declarator &declarator = state.getDeclarator(); 391 392 // Move it to the outermost normal or block pointer declarator. 393 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 394 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 395 switch (chunk.Kind) { 396 case DeclaratorChunk::Pointer: 397 case DeclaratorChunk::BlockPointer: { 398 // But don't move an ARC ownership attribute to the return type 399 // of a block. 400 DeclaratorChunk *destChunk = 0; 401 if (state.isProcessingDeclSpec() && 402 attr.getKind() == AttributeList::AT_ObjCOwnership) 403 destChunk = maybeMovePastReturnType(declarator, i - 1); 404 if (!destChunk) destChunk = &chunk; 405 406 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 407 destChunk->getAttrListRef()); 408 return; 409 } 410 411 case DeclaratorChunk::Paren: 412 case DeclaratorChunk::Array: 413 continue; 414 415 // We may be starting at the return type of a block. 416 case DeclaratorChunk::Function: 417 if (state.isProcessingDeclSpec() && 418 attr.getKind() == AttributeList::AT_ObjCOwnership) { 419 if (DeclaratorChunk *dest = maybeMovePastReturnType(declarator, i)) { 420 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 421 dest->getAttrListRef()); 422 return; 423 } 424 } 425 goto error; 426 427 // Don't walk through these. 428 case DeclaratorChunk::Reference: 429 case DeclaratorChunk::MemberPointer: 430 goto error; 431 } 432 } 433 error: 434 435 diagnoseBadTypeAttribute(state.getSema(), attr, type); 436} 437 438/// Distribute an objc_gc type attribute that was written on the 439/// declarator. 440static void 441distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state, 442 AttributeList &attr, 443 QualType &declSpecType) { 444 Declarator &declarator = state.getDeclarator(); 445 446 // objc_gc goes on the innermost pointer to something that's not a 447 // pointer. 448 unsigned innermost = -1U; 449 bool considerDeclSpec = true; 450 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 451 DeclaratorChunk &chunk = declarator.getTypeObject(i); 452 switch (chunk.Kind) { 453 case DeclaratorChunk::Pointer: 454 case DeclaratorChunk::BlockPointer: 455 innermost = i; 456 continue; 457 458 case DeclaratorChunk::Reference: 459 case DeclaratorChunk::MemberPointer: 460 case DeclaratorChunk::Paren: 461 case DeclaratorChunk::Array: 462 continue; 463 464 case DeclaratorChunk::Function: 465 considerDeclSpec = false; 466 goto done; 467 } 468 } 469 done: 470 471 // That might actually be the decl spec if we weren't blocked by 472 // anything in the declarator. 473 if (considerDeclSpec) { 474 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) { 475 // Splice the attribute into the decl spec. Prevents the 476 // attribute from being applied multiple times and gives 477 // the source-location-filler something to work with. 478 state.saveDeclSpecAttrs(); 479 moveAttrFromListToList(attr, declarator.getAttrListRef(), 480 declarator.getMutableDeclSpec().getAttributes().getListRef()); 481 return; 482 } 483 } 484 485 // Otherwise, if we found an appropriate chunk, splice the attribute 486 // into it. 487 if (innermost != -1U) { 488 moveAttrFromListToList(attr, declarator.getAttrListRef(), 489 declarator.getTypeObject(innermost).getAttrListRef()); 490 return; 491 } 492 493 // Otherwise, diagnose when we're done building the type. 494 spliceAttrOutOfList(attr, declarator.getAttrListRef()); 495 state.addIgnoredTypeAttr(attr); 496} 497 498/// A function type attribute was written somewhere in a declaration 499/// *other* than on the declarator itself or in the decl spec. Given 500/// that it didn't apply in whatever position it was written in, try 501/// to move it to a more appropriate position. 502static void distributeFunctionTypeAttr(TypeProcessingState &state, 503 AttributeList &attr, 504 QualType type) { 505 Declarator &declarator = state.getDeclarator(); 506 507 // Try to push the attribute from the return type of a function to 508 // the function itself. 509 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 510 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 511 switch (chunk.Kind) { 512 case DeclaratorChunk::Function: 513 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 514 chunk.getAttrListRef()); 515 return; 516 517 case DeclaratorChunk::Paren: 518 case DeclaratorChunk::Pointer: 519 case DeclaratorChunk::BlockPointer: 520 case DeclaratorChunk::Array: 521 case DeclaratorChunk::Reference: 522 case DeclaratorChunk::MemberPointer: 523 continue; 524 } 525 } 526 527 diagnoseBadTypeAttribute(state.getSema(), attr, type); 528} 529 530/// Try to distribute a function type attribute to the innermost 531/// function chunk or type. Returns true if the attribute was 532/// distributed, false if no location was found. 533static bool 534distributeFunctionTypeAttrToInnermost(TypeProcessingState &state, 535 AttributeList &attr, 536 AttributeList *&attrList, 537 QualType &declSpecType) { 538 Declarator &declarator = state.getDeclarator(); 539 540 // Put it on the innermost function chunk, if there is one. 541 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 542 DeclaratorChunk &chunk = declarator.getTypeObject(i); 543 if (chunk.Kind != DeclaratorChunk::Function) continue; 544 545 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef()); 546 return true; 547 } 548 549 return handleFunctionTypeAttr(state, attr, declSpecType); 550} 551 552/// A function type attribute was written in the decl spec. Try to 553/// apply it somewhere. 554static void 555distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, 556 AttributeList &attr, 557 QualType &declSpecType) { 558 state.saveDeclSpecAttrs(); 559 560 // C++11 attributes before the decl specifiers actually appertain to 561 // the declarators. Move them straight there. We don't support the 562 // 'put them wherever you like' semantics we allow for GNU attributes. 563 if (attr.isCXX11Attribute()) { 564 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 565 state.getDeclarator().getAttrListRef()); 566 return; 567 } 568 569 // Try to distribute to the innermost. 570 if (distributeFunctionTypeAttrToInnermost(state, attr, 571 state.getCurrentAttrListRef(), 572 declSpecType)) 573 return; 574 575 // If that failed, diagnose the bad attribute when the declarator is 576 // fully built. 577 state.addIgnoredTypeAttr(attr); 578} 579 580/// A function type attribute was written on the declarator. Try to 581/// apply it somewhere. 582static void 583distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, 584 AttributeList &attr, 585 QualType &declSpecType) { 586 Declarator &declarator = state.getDeclarator(); 587 588 // Try to distribute to the innermost. 589 if (distributeFunctionTypeAttrToInnermost(state, attr, 590 declarator.getAttrListRef(), 591 declSpecType)) 592 return; 593 594 // If that failed, diagnose the bad attribute when the declarator is 595 // fully built. 596 spliceAttrOutOfList(attr, declarator.getAttrListRef()); 597 state.addIgnoredTypeAttr(attr); 598} 599 600/// \brief Given that there are attributes written on the declarator 601/// itself, try to distribute any type attributes to the appropriate 602/// declarator chunk. 603/// 604/// These are attributes like the following: 605/// int f ATTR; 606/// int (f ATTR)(); 607/// but not necessarily this: 608/// int f() ATTR; 609static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, 610 QualType &declSpecType) { 611 // Collect all the type attributes from the declarator itself. 612 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!"); 613 AttributeList *attr = state.getDeclarator().getAttributes(); 614 AttributeList *next; 615 do { 616 next = attr->getNext(); 617 618 // Do not distribute C++11 attributes. They have strict rules for what 619 // they appertain to. 620 if (attr->isCXX11Attribute()) 621 continue; 622 623 switch (attr->getKind()) { 624 OBJC_POINTER_TYPE_ATTRS_CASELIST: 625 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType); 626 break; 627 628 case AttributeList::AT_NSReturnsRetained: 629 if (!state.getSema().getLangOpts().ObjCAutoRefCount) 630 break; 631 // fallthrough 632 633 FUNCTION_TYPE_ATTRS_CASELIST: 634 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType); 635 break; 636 637 MS_TYPE_ATTRS_CASELIST: 638 // Microsoft type attributes cannot go after the declarator-id. 639 continue; 640 641 default: 642 break; 643 } 644 } while ((attr = next)); 645} 646 647/// Add a synthetic '()' to a block-literal declarator if it is 648/// required, given the return type. 649static void maybeSynthesizeBlockSignature(TypeProcessingState &state, 650 QualType declSpecType) { 651 Declarator &declarator = state.getDeclarator(); 652 653 // First, check whether the declarator would produce a function, 654 // i.e. whether the innermost semantic chunk is a function. 655 if (declarator.isFunctionDeclarator()) { 656 // If so, make that declarator a prototyped declarator. 657 declarator.getFunctionTypeInfo().hasPrototype = true; 658 return; 659 } 660 661 // If there are any type objects, the type as written won't name a 662 // function, regardless of the decl spec type. This is because a 663 // block signature declarator is always an abstract-declarator, and 664 // abstract-declarators can't just be parentheses chunks. Therefore 665 // we need to build a function chunk unless there are no type 666 // objects and the decl spec type is a function. 667 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType()) 668 return; 669 670 // Note that there *are* cases with invalid declarators where 671 // declarators consist solely of parentheses. In general, these 672 // occur only in failed efforts to make function declarators, so 673 // faking up the function chunk is still the right thing to do. 674 675 // Otherwise, we need to fake up a function declarator. 676 SourceLocation loc = declarator.getLocStart(); 677 678 // ...and *prepend* it to the declarator. 679 SourceLocation NoLoc; 680 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction( 681 /*HasProto=*/true, 682 /*IsAmbiguous=*/false, 683 /*LParenLoc=*/NoLoc, 684 /*ArgInfo=*/0, 685 /*NumArgs=*/0, 686 /*EllipsisLoc=*/NoLoc, 687 /*RParenLoc=*/NoLoc, 688 /*TypeQuals=*/0, 689 /*RefQualifierIsLvalueRef=*/true, 690 /*RefQualifierLoc=*/NoLoc, 691 /*ConstQualifierLoc=*/NoLoc, 692 /*VolatileQualifierLoc=*/NoLoc, 693 /*MutableLoc=*/NoLoc, 694 EST_None, 695 /*ESpecLoc=*/NoLoc, 696 /*Exceptions=*/0, 697 /*ExceptionRanges=*/0, 698 /*NumExceptions=*/0, 699 /*NoexceptExpr=*/0, 700 loc, loc, declarator)); 701 702 // For consistency, make sure the state still has us as processing 703 // the decl spec. 704 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1); 705 state.setCurrentChunkIndex(declarator.getNumTypeObjects()); 706} 707 708/// \brief Convert the specified declspec to the appropriate type 709/// object. 710/// \param state Specifies the declarator containing the declaration specifier 711/// to be converted, along with other associated processing state. 712/// \returns The type described by the declaration specifiers. This function 713/// never returns null. 714static QualType ConvertDeclSpecToType(TypeProcessingState &state) { 715 // FIXME: Should move the logic from DeclSpec::Finish to here for validity 716 // checking. 717 718 Sema &S = state.getSema(); 719 Declarator &declarator = state.getDeclarator(); 720 const DeclSpec &DS = declarator.getDeclSpec(); 721 SourceLocation DeclLoc = declarator.getIdentifierLoc(); 722 if (DeclLoc.isInvalid()) 723 DeclLoc = DS.getLocStart(); 724 725 ASTContext &Context = S.Context; 726 727 QualType Result; 728 switch (DS.getTypeSpecType()) { 729 case DeclSpec::TST_void: 730 Result = Context.VoidTy; 731 break; 732 case DeclSpec::TST_char: 733 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 734 Result = Context.CharTy; 735 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) 736 Result = Context.SignedCharTy; 737 else { 738 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 739 "Unknown TSS value"); 740 Result = Context.UnsignedCharTy; 741 } 742 break; 743 case DeclSpec::TST_wchar: 744 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 745 Result = Context.WCharTy; 746 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { 747 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 748 << DS.getSpecifierName(DS.getTypeSpecType()); 749 Result = Context.getSignedWCharType(); 750 } else { 751 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 752 "Unknown TSS value"); 753 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 754 << DS.getSpecifierName(DS.getTypeSpecType()); 755 Result = Context.getUnsignedWCharType(); 756 } 757 break; 758 case DeclSpec::TST_char16: 759 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 760 "Unknown TSS value"); 761 Result = Context.Char16Ty; 762 break; 763 case DeclSpec::TST_char32: 764 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 765 "Unknown TSS value"); 766 Result = Context.Char32Ty; 767 break; 768 case DeclSpec::TST_unspecified: 769 // "<proto1,proto2>" is an objc qualified ID with a missing id. 770 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { 771 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 772 (ObjCProtocolDecl*const*)PQ, 773 DS.getNumProtocolQualifiers()); 774 Result = Context.getObjCObjectPointerType(Result); 775 break; 776 } 777 778 // If this is a missing declspec in a block literal return context, then it 779 // is inferred from the return statements inside the block. 780 // The declspec is always missing in a lambda expr context; it is either 781 // specified with a trailing return type or inferred. 782 if (declarator.getContext() == Declarator::LambdaExprContext || 783 isOmittedBlockReturnType(declarator)) { 784 Result = Context.DependentTy; 785 break; 786 } 787 788 // Unspecified typespec defaults to int in C90. However, the C90 grammar 789 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, 790 // type-qualifier, or storage-class-specifier. If not, emit an extwarn. 791 // Note that the one exception to this is function definitions, which are 792 // allowed to be completely missing a declspec. This is handled in the 793 // parser already though by it pretending to have seen an 'int' in this 794 // case. 795 if (S.getLangOpts().ImplicitInt) { 796 // In C89 mode, we only warn if there is a completely missing declspec 797 // when one is not allowed. 798 if (DS.isEmpty()) { 799 S.Diag(DeclLoc, diag::ext_missing_declspec) 800 << DS.getSourceRange() 801 << FixItHint::CreateInsertion(DS.getLocStart(), "int"); 802 } 803 } else if (!DS.hasTypeSpecifier()) { 804 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: 805 // "At least one type specifier shall be given in the declaration 806 // specifiers in each declaration, and in the specifier-qualifier list in 807 // each struct declaration and type name." 808 if (S.getLangOpts().CPlusPlus) { 809 S.Diag(DeclLoc, diag::err_missing_type_specifier) 810 << DS.getSourceRange(); 811 812 // When this occurs in C++ code, often something is very broken with the 813 // value being declared, poison it as invalid so we don't get chains of 814 // errors. 815 declarator.setInvalidType(true); 816 } else { 817 S.Diag(DeclLoc, diag::ext_missing_type_specifier) 818 << DS.getSourceRange(); 819 } 820 } 821 822 // FALL THROUGH. 823 case DeclSpec::TST_int: { 824 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { 825 switch (DS.getTypeSpecWidth()) { 826 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; 827 case DeclSpec::TSW_short: Result = Context.ShortTy; break; 828 case DeclSpec::TSW_long: Result = Context.LongTy; break; 829 case DeclSpec::TSW_longlong: 830 Result = Context.LongLongTy; 831 832 // 'long long' is a C99 or C++11 feature. 833 if (!S.getLangOpts().C99) { 834 if (S.getLangOpts().CPlusPlus) 835 S.Diag(DS.getTypeSpecWidthLoc(), 836 S.getLangOpts().CPlusPlus11 ? 837 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 838 else 839 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); 840 } 841 break; 842 } 843 } else { 844 switch (DS.getTypeSpecWidth()) { 845 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; 846 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; 847 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; 848 case DeclSpec::TSW_longlong: 849 Result = Context.UnsignedLongLongTy; 850 851 // 'long long' is a C99 or C++11 feature. 852 if (!S.getLangOpts().C99) { 853 if (S.getLangOpts().CPlusPlus) 854 S.Diag(DS.getTypeSpecWidthLoc(), 855 S.getLangOpts().CPlusPlus11 ? 856 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 857 else 858 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); 859 } 860 break; 861 } 862 } 863 break; 864 } 865 case DeclSpec::TST_int128: 866 if (!S.PP.getTargetInfo().hasInt128Type()) 867 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported); 868 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned) 869 Result = Context.UnsignedInt128Ty; 870 else 871 Result = Context.Int128Ty; 872 break; 873 case DeclSpec::TST_half: Result = Context.HalfTy; break; 874 case DeclSpec::TST_float: Result = Context.FloatTy; break; 875 case DeclSpec::TST_double: 876 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) 877 Result = Context.LongDoubleTy; 878 else 879 Result = Context.DoubleTy; 880 881 if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) { 882 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64); 883 declarator.setInvalidType(true); 884 } 885 break; 886 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool 887 case DeclSpec::TST_decimal32: // _Decimal32 888 case DeclSpec::TST_decimal64: // _Decimal64 889 case DeclSpec::TST_decimal128: // _Decimal128 890 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); 891 Result = Context.IntTy; 892 declarator.setInvalidType(true); 893 break; 894 case DeclSpec::TST_class: 895 case DeclSpec::TST_enum: 896 case DeclSpec::TST_union: 897 case DeclSpec::TST_struct: 898 case DeclSpec::TST_interface: { 899 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl()); 900 if (!D) { 901 // This can happen in C++ with ambiguous lookups. 902 Result = Context.IntTy; 903 declarator.setInvalidType(true); 904 break; 905 } 906 907 // If the type is deprecated or unavailable, diagnose it. 908 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc()); 909 910 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 911 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!"); 912 913 // TypeQuals handled by caller. 914 Result = Context.getTypeDeclType(D); 915 916 // In both C and C++, make an ElaboratedType. 917 ElaboratedTypeKeyword Keyword 918 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType()); 919 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result); 920 break; 921 } 922 case DeclSpec::TST_typename: { 923 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 924 DS.getTypeSpecSign() == 0 && 925 "Can't handle qualifiers on typedef names yet!"); 926 Result = S.GetTypeFromParser(DS.getRepAsType()); 927 if (Result.isNull()) 928 declarator.setInvalidType(true); 929 else if (DeclSpec::ProtocolQualifierListTy PQ 930 = DS.getProtocolQualifiers()) { 931 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) { 932 // Silently drop any existing protocol qualifiers. 933 // TODO: determine whether that's the right thing to do. 934 if (ObjT->getNumProtocols()) 935 Result = ObjT->getBaseType(); 936 937 if (DS.getNumProtocolQualifiers()) 938 Result = Context.getObjCObjectType(Result, 939 (ObjCProtocolDecl*const*) PQ, 940 DS.getNumProtocolQualifiers()); 941 } else if (Result->isObjCIdType()) { 942 // id<protocol-list> 943 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 944 (ObjCProtocolDecl*const*) PQ, 945 DS.getNumProtocolQualifiers()); 946 Result = Context.getObjCObjectPointerType(Result); 947 } else if (Result->isObjCClassType()) { 948 // Class<protocol-list> 949 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 950 (ObjCProtocolDecl*const*) PQ, 951 DS.getNumProtocolQualifiers()); 952 Result = Context.getObjCObjectPointerType(Result); 953 } else { 954 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers) 955 << DS.getSourceRange(); 956 declarator.setInvalidType(true); 957 } 958 } 959 960 // TypeQuals handled by caller. 961 break; 962 } 963 case DeclSpec::TST_typeofType: 964 // FIXME: Preserve type source info. 965 Result = S.GetTypeFromParser(DS.getRepAsType()); 966 assert(!Result.isNull() && "Didn't get a type for typeof?"); 967 if (!Result->isDependentType()) 968 if (const TagType *TT = Result->getAs<TagType>()) 969 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc()); 970 // TypeQuals handled by caller. 971 Result = Context.getTypeOfType(Result); 972 break; 973 case DeclSpec::TST_typeofExpr: { 974 Expr *E = DS.getRepAsExpr(); 975 assert(E && "Didn't get an expression for typeof?"); 976 // TypeQuals handled by caller. 977 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc()); 978 if (Result.isNull()) { 979 Result = Context.IntTy; 980 declarator.setInvalidType(true); 981 } 982 break; 983 } 984 case DeclSpec::TST_decltype: { 985 Expr *E = DS.getRepAsExpr(); 986 assert(E && "Didn't get an expression for decltype?"); 987 // TypeQuals handled by caller. 988 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc()); 989 if (Result.isNull()) { 990 Result = Context.IntTy; 991 declarator.setInvalidType(true); 992 } 993 break; 994 } 995 case DeclSpec::TST_underlyingType: 996 Result = S.GetTypeFromParser(DS.getRepAsType()); 997 assert(!Result.isNull() && "Didn't get a type for __underlying_type?"); 998 Result = S.BuildUnaryTransformType(Result, 999 UnaryTransformType::EnumUnderlyingType, 1000 DS.getTypeSpecTypeLoc()); 1001 if (Result.isNull()) { 1002 Result = Context.IntTy; 1003 declarator.setInvalidType(true); 1004 } 1005 break; 1006 1007 case DeclSpec::TST_auto: 1008 // TypeQuals handled by caller. 1009 Result = Context.getAutoType(QualType(), /*decltype(auto)*/false); 1010 break; 1011 1012 case DeclSpec::TST_decltype_auto: 1013 Result = Context.getAutoType(QualType(), /*decltype(auto)*/true); 1014 break; 1015 1016 case DeclSpec::TST_unknown_anytype: 1017 Result = Context.UnknownAnyTy; 1018 break; 1019 1020 case DeclSpec::TST_atomic: 1021 Result = S.GetTypeFromParser(DS.getRepAsType()); 1022 assert(!Result.isNull() && "Didn't get a type for _Atomic?"); 1023 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc()); 1024 if (Result.isNull()) { 1025 Result = Context.IntTy; 1026 declarator.setInvalidType(true); 1027 } 1028 break; 1029 1030 case DeclSpec::TST_image1d_t: 1031 Result = Context.OCLImage1dTy; 1032 break; 1033 1034 case DeclSpec::TST_image1d_array_t: 1035 Result = Context.OCLImage1dArrayTy; 1036 break; 1037 1038 case DeclSpec::TST_image1d_buffer_t: 1039 Result = Context.OCLImage1dBufferTy; 1040 break; 1041 1042 case DeclSpec::TST_image2d_t: 1043 Result = Context.OCLImage2dTy; 1044 break; 1045 1046 case DeclSpec::TST_image2d_array_t: 1047 Result = Context.OCLImage2dArrayTy; 1048 break; 1049 1050 case DeclSpec::TST_image3d_t: 1051 Result = Context.OCLImage3dTy; 1052 break; 1053 1054 case DeclSpec::TST_sampler_t: 1055 Result = Context.OCLSamplerTy; 1056 break; 1057 1058 case DeclSpec::TST_event_t: 1059 Result = Context.OCLEventTy; 1060 break; 1061 1062 case DeclSpec::TST_error: 1063 Result = Context.IntTy; 1064 declarator.setInvalidType(true); 1065 break; 1066 } 1067 1068 // Handle complex types. 1069 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { 1070 if (S.getLangOpts().Freestanding) 1071 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); 1072 Result = Context.getComplexType(Result); 1073 } else if (DS.isTypeAltiVecVector()) { 1074 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result)); 1075 assert(typeSize > 0 && "type size for vector must be greater than 0 bits"); 1076 VectorType::VectorKind VecKind = VectorType::AltiVecVector; 1077 if (DS.isTypeAltiVecPixel()) 1078 VecKind = VectorType::AltiVecPixel; 1079 else if (DS.isTypeAltiVecBool()) 1080 VecKind = VectorType::AltiVecBool; 1081 Result = Context.getVectorType(Result, 128/typeSize, VecKind); 1082 } 1083 1084 // FIXME: Imaginary. 1085 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary) 1086 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported); 1087 1088 // Before we process any type attributes, synthesize a block literal 1089 // function declarator if necessary. 1090 if (declarator.getContext() == Declarator::BlockLiteralContext) 1091 maybeSynthesizeBlockSignature(state, Result); 1092 1093 // Apply any type attributes from the decl spec. This may cause the 1094 // list of type attributes to be temporarily saved while the type 1095 // attributes are pushed around. 1096 if (AttributeList *attrs = DS.getAttributes().getList()) 1097 processTypeAttrs(state, Result, TAL_DeclSpec, attrs); 1098 1099 // Apply const/volatile/restrict qualifiers to T. 1100 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 1101 1102 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification 1103 // of a function type includes any type qualifiers, the behavior is 1104 // undefined." 1105 if (Result->isFunctionType() && TypeQuals) { 1106 if (TypeQuals & DeclSpec::TQ_const) 1107 S.Diag(DS.getConstSpecLoc(), diag::warn_typecheck_function_qualifiers) 1108 << Result << DS.getSourceRange(); 1109 else if (TypeQuals & DeclSpec::TQ_volatile) 1110 S.Diag(DS.getVolatileSpecLoc(), diag::warn_typecheck_function_qualifiers) 1111 << Result << DS.getSourceRange(); 1112 else { 1113 assert((TypeQuals & (DeclSpec::TQ_restrict | DeclSpec::TQ_atomic)) && 1114 "Has CVRA quals but not C, V, R, or A?"); 1115 // No diagnostic; we'll diagnose 'restrict' or '_Atomic' applied to a 1116 // function type later, in BuildQualifiedType. 1117 } 1118 } 1119 1120 // C++ [dcl.ref]p1: 1121 // Cv-qualified references are ill-formed except when the 1122 // cv-qualifiers are introduced through the use of a typedef 1123 // (7.1.3) or of a template type argument (14.3), in which 1124 // case the cv-qualifiers are ignored. 1125 // FIXME: Shouldn't we be checking SCS_typedef here? 1126 if (DS.getTypeSpecType() == DeclSpec::TST_typename && 1127 TypeQuals && Result->isReferenceType()) { 1128 TypeQuals &= ~DeclSpec::TQ_const; 1129 TypeQuals &= ~DeclSpec::TQ_volatile; 1130 TypeQuals &= ~DeclSpec::TQ_atomic; 1131 } 1132 1133 // C90 6.5.3 constraints: "The same type qualifier shall not appear more 1134 // than once in the same specifier-list or qualifier-list, either directly 1135 // or via one or more typedefs." 1136 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus 1137 && TypeQuals & Result.getCVRQualifiers()) { 1138 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) { 1139 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec) 1140 << "const"; 1141 } 1142 1143 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) { 1144 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec) 1145 << "volatile"; 1146 } 1147 1148 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to 1149 // produce a warning in this case. 1150 } 1151 1152 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS); 1153 1154 // If adding qualifiers fails, just use the unqualified type. 1155 if (Qualified.isNull()) 1156 declarator.setInvalidType(true); 1157 else 1158 Result = Qualified; 1159 } 1160 1161 return Result; 1162} 1163 1164static std::string getPrintableNameForEntity(DeclarationName Entity) { 1165 if (Entity) 1166 return Entity.getAsString(); 1167 1168 return "type name"; 1169} 1170 1171QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, 1172 Qualifiers Qs, const DeclSpec *DS) { 1173 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 1174 // object or incomplete types shall not be restrict-qualified." 1175 if (Qs.hasRestrict()) { 1176 unsigned DiagID = 0; 1177 QualType ProblemTy; 1178 1179 if (T->isAnyPointerType() || T->isReferenceType() || 1180 T->isMemberPointerType()) { 1181 QualType EltTy; 1182 if (T->isObjCObjectPointerType()) 1183 EltTy = T; 1184 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>()) 1185 EltTy = PTy->getPointeeType(); 1186 else 1187 EltTy = T->getPointeeType(); 1188 1189 // If we have a pointer or reference, the pointee must have an object 1190 // incomplete type. 1191 if (!EltTy->isIncompleteOrObjectType()) { 1192 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 1193 ProblemTy = EltTy; 1194 } 1195 } else if (!T->isDependentType()) { 1196 DiagID = diag::err_typecheck_invalid_restrict_not_pointer; 1197 ProblemTy = T; 1198 } 1199 1200 if (DiagID) { 1201 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy; 1202 Qs.removeRestrict(); 1203 } 1204 } 1205 1206 return Context.getQualifiedType(T, Qs); 1207} 1208 1209QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, 1210 unsigned CVRA, const DeclSpec *DS) { 1211 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic. 1212 unsigned CVR = CVRA & ~DeclSpec::TQ_atomic; 1213 1214 // C11 6.7.3/5: 1215 // If the same qualifier appears more than once in the same 1216 // specifier-qualifier-list, either directly or via one or more typedefs, 1217 // the behavior is the same as if it appeared only once. 1218 // 1219 // It's not specified what happens when the _Atomic qualifier is applied to 1220 // a type specified with the _Atomic specifier, but we assume that this 1221 // should be treated as if the _Atomic qualifier appeared multiple times. 1222 if (CVRA & DeclSpec::TQ_atomic && !T->isAtomicType()) { 1223 // C11 6.7.3/5: 1224 // If other qualifiers appear along with the _Atomic qualifier in a 1225 // specifier-qualifier-list, the resulting type is the so-qualified 1226 // atomic type. 1227 // 1228 // Don't need to worry about array types here, since _Atomic can't be 1229 // applied to such types. 1230 SplitQualType Split = T.getSplitUnqualifiedType(); 1231 T = BuildAtomicType(QualType(Split.Ty, 0), 1232 DS ? DS->getAtomicSpecLoc() : Loc); 1233 if (T.isNull()) 1234 return T; 1235 Split.Quals.addCVRQualifiers(CVR); 1236 return BuildQualifiedType(T, Loc, Split.Quals); 1237 } 1238 1239 return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR), DS); 1240} 1241 1242/// \brief Build a paren type including \p T. 1243QualType Sema::BuildParenType(QualType T) { 1244 return Context.getParenType(T); 1245} 1246 1247/// Given that we're building a pointer or reference to the given 1248static QualType inferARCLifetimeForPointee(Sema &S, QualType type, 1249 SourceLocation loc, 1250 bool isReference) { 1251 // Bail out if retention is unrequired or already specified. 1252 if (!type->isObjCLifetimeType() || 1253 type.getObjCLifetime() != Qualifiers::OCL_None) 1254 return type; 1255 1256 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None; 1257 1258 // If the object type is const-qualified, we can safely use 1259 // __unsafe_unretained. This is safe (because there are no read 1260 // barriers), and it'll be safe to coerce anything but __weak* to 1261 // the resulting type. 1262 if (type.isConstQualified()) { 1263 implicitLifetime = Qualifiers::OCL_ExplicitNone; 1264 1265 // Otherwise, check whether the static type does not require 1266 // retaining. This currently only triggers for Class (possibly 1267 // protocol-qualifed, and arrays thereof). 1268 } else if (type->isObjCARCImplicitlyUnretainedType()) { 1269 implicitLifetime = Qualifiers::OCL_ExplicitNone; 1270 1271 // If we are in an unevaluated context, like sizeof, skip adding a 1272 // qualification. 1273 } else if (S.isUnevaluatedContext()) { 1274 return type; 1275 1276 // If that failed, give an error and recover using __strong. __strong 1277 // is the option most likely to prevent spurious second-order diagnostics, 1278 // like when binding a reference to a field. 1279 } else { 1280 // These types can show up in private ivars in system headers, so 1281 // we need this to not be an error in those cases. Instead we 1282 // want to delay. 1283 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 1284 S.DelayedDiagnostics.add( 1285 sema::DelayedDiagnostic::makeForbiddenType(loc, 1286 diag::err_arc_indirect_no_ownership, type, isReference)); 1287 } else { 1288 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference; 1289 } 1290 implicitLifetime = Qualifiers::OCL_Strong; 1291 } 1292 assert(implicitLifetime && "didn't infer any lifetime!"); 1293 1294 Qualifiers qs; 1295 qs.addObjCLifetime(implicitLifetime); 1296 return S.Context.getQualifiedType(type, qs); 1297} 1298 1299/// \brief Build a pointer type. 1300/// 1301/// \param T The type to which we'll be building a pointer. 1302/// 1303/// \param Loc The location of the entity whose type involves this 1304/// pointer type or, if there is no such entity, the location of the 1305/// type that will have pointer type. 1306/// 1307/// \param Entity The name of the entity that involves the pointer 1308/// type, if known. 1309/// 1310/// \returns A suitable pointer type, if there are no 1311/// errors. Otherwise, returns a NULL type. 1312QualType Sema::BuildPointerType(QualType T, 1313 SourceLocation Loc, DeclarationName Entity) { 1314 if (T->isReferenceType()) { 1315 // C++ 8.3.2p4: There shall be no ... pointers to references ... 1316 Diag(Loc, diag::err_illegal_decl_pointer_to_reference) 1317 << getPrintableNameForEntity(Entity) << T; 1318 return QualType(); 1319 } 1320 1321 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType"); 1322 1323 // In ARC, it is forbidden to build pointers to unqualified pointers. 1324 if (getLangOpts().ObjCAutoRefCount) 1325 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false); 1326 1327 // Build the pointer type. 1328 return Context.getPointerType(T); 1329} 1330 1331/// \brief Build a reference type. 1332/// 1333/// \param T The type to which we'll be building a reference. 1334/// 1335/// \param Loc The location of the entity whose type involves this 1336/// reference type or, if there is no such entity, the location of the 1337/// type that will have reference type. 1338/// 1339/// \param Entity The name of the entity that involves the reference 1340/// type, if known. 1341/// 1342/// \returns A suitable reference type, if there are no 1343/// errors. Otherwise, returns a NULL type. 1344QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, 1345 SourceLocation Loc, 1346 DeclarationName Entity) { 1347 assert(Context.getCanonicalType(T) != Context.OverloadTy && 1348 "Unresolved overloaded function type"); 1349 1350 // C++0x [dcl.ref]p6: 1351 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a 1352 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a 1353 // type T, an attempt to create the type "lvalue reference to cv TR" creates 1354 // the type "lvalue reference to T", while an attempt to create the type 1355 // "rvalue reference to cv TR" creates the type TR. 1356 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); 1357 1358 // C++ [dcl.ref]p4: There shall be no references to references. 1359 // 1360 // According to C++ DR 106, references to references are only 1361 // diagnosed when they are written directly (e.g., "int & &"), 1362 // but not when they happen via a typedef: 1363 // 1364 // typedef int& intref; 1365 // typedef intref& intref2; 1366 // 1367 // Parser::ParseDeclaratorInternal diagnoses the case where 1368 // references are written directly; here, we handle the 1369 // collapsing of references-to-references as described in C++0x. 1370 // DR 106 and 540 introduce reference-collapsing into C++98/03. 1371 1372 // C++ [dcl.ref]p1: 1373 // A declarator that specifies the type "reference to cv void" 1374 // is ill-formed. 1375 if (T->isVoidType()) { 1376 Diag(Loc, diag::err_reference_to_void); 1377 return QualType(); 1378 } 1379 1380 // In ARC, it is forbidden to build references to unqualified pointers. 1381 if (getLangOpts().ObjCAutoRefCount) 1382 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true); 1383 1384 // Handle restrict on references. 1385 if (LValueRef) 1386 return Context.getLValueReferenceType(T, SpelledAsLValue); 1387 return Context.getRValueReferenceType(T); 1388} 1389 1390/// Check whether the specified array size makes the array type a VLA. If so, 1391/// return true, if not, return the size of the array in SizeVal. 1392static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) { 1393 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode 1394 // (like gnu99, but not c99) accept any evaluatable value as an extension. 1395 class VLADiagnoser : public Sema::VerifyICEDiagnoser { 1396 public: 1397 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {} 1398 1399 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1400 } 1401 1402 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) { 1403 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR; 1404 } 1405 } Diagnoser; 1406 1407 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser, 1408 S.LangOpts.GNUMode).isInvalid(); 1409} 1410 1411 1412/// \brief Build an array type. 1413/// 1414/// \param T The type of each element in the array. 1415/// 1416/// \param ASM C99 array size modifier (e.g., '*', 'static'). 1417/// 1418/// \param ArraySize Expression describing the size of the array. 1419/// 1420/// \param Brackets The range from the opening '[' to the closing ']'. 1421/// 1422/// \param Entity The name of the entity that involves the array 1423/// type, if known. 1424/// 1425/// \returns A suitable array type, if there are no errors. Otherwise, 1426/// returns a NULL type. 1427QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 1428 Expr *ArraySize, unsigned Quals, 1429 SourceRange Brackets, DeclarationName Entity) { 1430 1431 SourceLocation Loc = Brackets.getBegin(); 1432 if (getLangOpts().CPlusPlus) { 1433 // C++ [dcl.array]p1: 1434 // T is called the array element type; this type shall not be a reference 1435 // type, the (possibly cv-qualified) type void, a function type or an 1436 // abstract class type. 1437 // 1438 // C++ [dcl.array]p3: 1439 // When several "array of" specifications are adjacent, [...] only the 1440 // first of the constant expressions that specify the bounds of the arrays 1441 // may be omitted. 1442 // 1443 // Note: function types are handled in the common path with C. 1444 if (T->isReferenceType()) { 1445 Diag(Loc, diag::err_illegal_decl_array_of_references) 1446 << getPrintableNameForEntity(Entity) << T; 1447 return QualType(); 1448 } 1449 1450 if (T->isVoidType() || T->isIncompleteArrayType()) { 1451 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T; 1452 return QualType(); 1453 } 1454 1455 if (RequireNonAbstractType(Brackets.getBegin(), T, 1456 diag::err_array_of_abstract_type)) 1457 return QualType(); 1458 1459 } else { 1460 // C99 6.7.5.2p1: If the element type is an incomplete or function type, 1461 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) 1462 if (RequireCompleteType(Loc, T, 1463 diag::err_illegal_decl_array_incomplete_type)) 1464 return QualType(); 1465 } 1466 1467 if (T->isFunctionType()) { 1468 Diag(Loc, diag::err_illegal_decl_array_of_functions) 1469 << getPrintableNameForEntity(Entity) << T; 1470 return QualType(); 1471 } 1472 1473 if (const RecordType *EltTy = T->getAs<RecordType>()) { 1474 // If the element type is a struct or union that contains a variadic 1475 // array, accept it as a GNU extension: C99 6.7.2.1p2. 1476 if (EltTy->getDecl()->hasFlexibleArrayMember()) 1477 Diag(Loc, diag::ext_flexible_array_in_array) << T; 1478 } else if (T->isObjCObjectType()) { 1479 Diag(Loc, diag::err_objc_array_of_interfaces) << T; 1480 return QualType(); 1481 } 1482 1483 // Do placeholder conversions on the array size expression. 1484 if (ArraySize && ArraySize->hasPlaceholderType()) { 1485 ExprResult Result = CheckPlaceholderExpr(ArraySize); 1486 if (Result.isInvalid()) return QualType(); 1487 ArraySize = Result.take(); 1488 } 1489 1490 // Do lvalue-to-rvalue conversions on the array size expression. 1491 if (ArraySize && !ArraySize->isRValue()) { 1492 ExprResult Result = DefaultLvalueConversion(ArraySize); 1493 if (Result.isInvalid()) 1494 return QualType(); 1495 1496 ArraySize = Result.take(); 1497 } 1498 1499 // C99 6.7.5.2p1: The size expression shall have integer type. 1500 // C++11 allows contextual conversions to such types. 1501 if (!getLangOpts().CPlusPlus11 && 1502 ArraySize && !ArraySize->isTypeDependent() && 1503 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { 1504 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 1505 << ArraySize->getType() << ArraySize->getSourceRange(); 1506 return QualType(); 1507 } 1508 1509 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType())); 1510 if (!ArraySize) { 1511 if (ASM == ArrayType::Star) 1512 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets); 1513 else 1514 T = Context.getIncompleteArrayType(T, ASM, Quals); 1515 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) { 1516 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); 1517 } else if ((!T->isDependentType() && !T->isIncompleteType() && 1518 !T->isConstantSizeType()) || 1519 isArraySizeVLA(*this, ArraySize, ConstVal)) { 1520 // Even in C++11, don't allow contextual conversions in the array bound 1521 // of a VLA. 1522 if (getLangOpts().CPlusPlus11 && 1523 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { 1524 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 1525 << ArraySize->getType() << ArraySize->getSourceRange(); 1526 return QualType(); 1527 } 1528 1529 // C99: an array with an element type that has a non-constant-size is a VLA. 1530 // C99: an array with a non-ICE size is a VLA. We accept any expression 1531 // that we can fold to a non-zero positive value as an extension. 1532 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); 1533 } else { 1534 // C99 6.7.5.2p1: If the expression is a constant expression, it shall 1535 // have a value greater than zero. 1536 if (ConstVal.isSigned() && ConstVal.isNegative()) { 1537 if (Entity) 1538 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size) 1539 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange(); 1540 else 1541 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size) 1542 << ArraySize->getSourceRange(); 1543 return QualType(); 1544 } 1545 if (ConstVal == 0) { 1546 // GCC accepts zero sized static arrays. We allow them when 1547 // we're not in a SFINAE context. 1548 Diag(ArraySize->getLocStart(), 1549 isSFINAEContext()? diag::err_typecheck_zero_array_size 1550 : diag::ext_typecheck_zero_array_size) 1551 << ArraySize->getSourceRange(); 1552 1553 if (ASM == ArrayType::Static) { 1554 Diag(ArraySize->getLocStart(), 1555 diag::warn_typecheck_zero_static_array_size) 1556 << ArraySize->getSourceRange(); 1557 ASM = ArrayType::Normal; 1558 } 1559 } else if (!T->isDependentType() && !T->isVariablyModifiedType() && 1560 !T->isIncompleteType()) { 1561 // Is the array too large? 1562 unsigned ActiveSizeBits 1563 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal); 1564 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 1565 Diag(ArraySize->getLocStart(), diag::err_array_too_large) 1566 << ConstVal.toString(10) 1567 << ArraySize->getSourceRange(); 1568 return QualType(); 1569 } 1570 } 1571 1572 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals); 1573 } 1574 1575 // OpenCL v1.2 s6.9.d: variable length arrays are not supported. 1576 if (getLangOpts().OpenCL && T->isVariableArrayType()) { 1577 Diag(Loc, diag::err_opencl_vla); 1578 return QualType(); 1579 } 1580 // If this is not C99, extwarn about VLA's and C99 array size modifiers. 1581 if (!getLangOpts().C99) { 1582 if (T->isVariableArrayType()) { 1583 // Prohibit the use of non-POD types in VLAs. 1584 // FIXME: C++1y allows this. 1585 QualType BaseT = Context.getBaseElementType(T); 1586 if (!T->isDependentType() && 1587 !BaseT.isPODType(Context) && 1588 !BaseT->isObjCLifetimeType()) { 1589 Diag(Loc, diag::err_vla_non_pod) 1590 << BaseT; 1591 return QualType(); 1592 } 1593 // Prohibit the use of VLAs during template argument deduction. 1594 else if (isSFINAEContext()) { 1595 Diag(Loc, diag::err_vla_in_sfinae); 1596 return QualType(); 1597 } 1598 // Just extwarn about VLAs. 1599 else 1600 Diag(Loc, getLangOpts().CPlusPlus1y 1601 ? diag::warn_cxx11_compat_array_of_runtime_bound 1602 : diag::ext_vla); 1603 } else if (ASM != ArrayType::Normal || Quals != 0) 1604 Diag(Loc, 1605 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx 1606 : diag::ext_c99_array_usage) << ASM; 1607 } 1608 1609 if (T->isVariableArrayType()) { 1610 // Warn about VLAs for -Wvla. 1611 Diag(Loc, diag::warn_vla_used); 1612 } 1613 1614 return T; 1615} 1616 1617/// \brief Build an ext-vector type. 1618/// 1619/// Run the required checks for the extended vector type. 1620QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, 1621 SourceLocation AttrLoc) { 1622 // unlike gcc's vector_size attribute, we do not allow vectors to be defined 1623 // in conjunction with complex types (pointers, arrays, functions, etc.). 1624 if (!T->isDependentType() && 1625 !T->isIntegerType() && !T->isRealFloatingType()) { 1626 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; 1627 return QualType(); 1628 } 1629 1630 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { 1631 llvm::APSInt vecSize(32); 1632 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) { 1633 Diag(AttrLoc, diag::err_attribute_argument_not_int) 1634 << "ext_vector_type" << ArraySize->getSourceRange(); 1635 return QualType(); 1636 } 1637 1638 // unlike gcc's vector_size attribute, the size is specified as the 1639 // number of elements, not the number of bytes. 1640 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); 1641 1642 if (vectorSize == 0) { 1643 Diag(AttrLoc, diag::err_attribute_zero_size) 1644 << ArraySize->getSourceRange(); 1645 return QualType(); 1646 } 1647 1648 if (VectorType::isVectorSizeTooLarge(vectorSize)) { 1649 Diag(AttrLoc, diag::err_attribute_size_too_large) 1650 << ArraySize->getSourceRange(); 1651 return QualType(); 1652 } 1653 1654 return Context.getExtVectorType(T, vectorSize); 1655 } 1656 1657 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc); 1658} 1659 1660bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) { 1661 if (T->isArrayType() || T->isFunctionType()) { 1662 Diag(Loc, diag::err_func_returning_array_function) 1663 << T->isFunctionType() << T; 1664 return true; 1665 } 1666 1667 // Functions cannot return half FP. 1668 if (T->isHalfType()) { 1669 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 << 1670 FixItHint::CreateInsertion(Loc, "*"); 1671 return true; 1672 } 1673 1674 // Methods cannot return interface types. All ObjC objects are 1675 // passed by reference. 1676 if (T->isObjCObjectType()) { 1677 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T; 1678 return 0; 1679 } 1680 1681 return false; 1682} 1683 1684QualType Sema::BuildFunctionType(QualType T, 1685 llvm::MutableArrayRef<QualType> ParamTypes, 1686 SourceLocation Loc, DeclarationName Entity, 1687 const FunctionProtoType::ExtProtoInfo &EPI) { 1688 bool Invalid = false; 1689 1690 Invalid |= CheckFunctionReturnType(T, Loc); 1691 1692 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) { 1693 // FIXME: Loc is too inprecise here, should use proper locations for args. 1694 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]); 1695 if (ParamType->isVoidType()) { 1696 Diag(Loc, diag::err_param_with_void_type); 1697 Invalid = true; 1698 } else if (ParamType->isHalfType()) { 1699 // Disallow half FP arguments. 1700 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 << 1701 FixItHint::CreateInsertion(Loc, "*"); 1702 Invalid = true; 1703 } 1704 1705 ParamTypes[Idx] = ParamType; 1706 } 1707 1708 if (Invalid) 1709 return QualType(); 1710 1711 return Context.getFunctionType(T, ParamTypes, EPI); 1712} 1713 1714/// \brief Build a member pointer type \c T Class::*. 1715/// 1716/// \param T the type to which the member pointer refers. 1717/// \param Class the class type into which the member pointer points. 1718/// \param Loc the location where this type begins 1719/// \param Entity the name of the entity that will have this member pointer type 1720/// 1721/// \returns a member pointer type, if successful, or a NULL type if there was 1722/// an error. 1723QualType Sema::BuildMemberPointerType(QualType T, QualType Class, 1724 SourceLocation Loc, 1725 DeclarationName Entity) { 1726 // Verify that we're not building a pointer to pointer to function with 1727 // exception specification. 1728 if (CheckDistantExceptionSpec(T)) { 1729 Diag(Loc, diag::err_distant_exception_spec); 1730 1731 // FIXME: If we're doing this as part of template instantiation, 1732 // we should return immediately. 1733 1734 // Build the type anyway, but use the canonical type so that the 1735 // exception specifiers are stripped off. 1736 T = Context.getCanonicalType(T); 1737 } 1738 1739 // C++ 8.3.3p3: A pointer to member shall not point to ... a member 1740 // with reference type, or "cv void." 1741 if (T->isReferenceType()) { 1742 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) 1743 << (Entity? Entity.getAsString() : "type name") << T; 1744 return QualType(); 1745 } 1746 1747 if (T->isVoidType()) { 1748 Diag(Loc, diag::err_illegal_decl_mempointer_to_void) 1749 << (Entity? Entity.getAsString() : "type name"); 1750 return QualType(); 1751 } 1752 1753 if (!Class->isDependentType() && !Class->isRecordType()) { 1754 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; 1755 return QualType(); 1756 } 1757 1758 // C++ allows the class type in a member pointer to be an incomplete type. 1759 // In the Microsoft ABI, the size of the member pointer can vary 1760 // according to the class type, which means that we really need a 1761 // complete type if possible, which means we need to instantiate templates. 1762 // 1763 // If template instantiation fails or the type is just incomplete, we have to 1764 // add an extra slot to the member pointer. Yes, this does cause problems 1765 // when passing pointers between TUs that disagree about the size. 1766 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1767 CXXRecordDecl *RD = Class->getAsCXXRecordDecl(); 1768 if (RD && !RD->hasAttr<MSInheritanceAttr>()) { 1769 // Lock in the inheritance model on the first use of a member pointer. 1770 // Otherwise we may disagree about the size at different points in the TU. 1771 // FIXME: MSVC picks a model on the first use that needs to know the size, 1772 // rather than on the first mention of the type, e.g. typedefs. 1773 if (RequireCompleteType(Loc, Class, 0) && !RD->isBeingDefined()) { 1774 // We know it doesn't have an attribute and it's incomplete, so use the 1775 // unspecified inheritance model. If we're in the record body, we can 1776 // figure out the inheritance model. 1777 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(), 1778 E = RD->redecls_end(); I != E; ++I) { 1779 I->addAttr(::new (Context) UnspecifiedInheritanceAttr( 1780 RD->getSourceRange(), Context)); 1781 } 1782 } 1783 } 1784 } 1785 1786 return Context.getMemberPointerType(T, Class.getTypePtr()); 1787} 1788 1789/// \brief Build a block pointer type. 1790/// 1791/// \param T The type to which we'll be building a block pointer. 1792/// 1793/// \param Loc The source location, used for diagnostics. 1794/// 1795/// \param Entity The name of the entity that involves the block pointer 1796/// type, if known. 1797/// 1798/// \returns A suitable block pointer type, if there are no 1799/// errors. Otherwise, returns a NULL type. 1800QualType Sema::BuildBlockPointerType(QualType T, 1801 SourceLocation Loc, 1802 DeclarationName Entity) { 1803 if (!T->isFunctionType()) { 1804 Diag(Loc, diag::err_nonfunction_block_type); 1805 return QualType(); 1806 } 1807 1808 return Context.getBlockPointerType(T); 1809} 1810 1811QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { 1812 QualType QT = Ty.get(); 1813 if (QT.isNull()) { 1814 if (TInfo) *TInfo = 0; 1815 return QualType(); 1816 } 1817 1818 TypeSourceInfo *DI = 0; 1819 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { 1820 QT = LIT->getType(); 1821 DI = LIT->getTypeSourceInfo(); 1822 } 1823 1824 if (TInfo) *TInfo = DI; 1825 return QT; 1826} 1827 1828static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 1829 Qualifiers::ObjCLifetime ownership, 1830 unsigned chunkIndex); 1831 1832/// Given that this is the declaration of a parameter under ARC, 1833/// attempt to infer attributes and such for pointer-to-whatever 1834/// types. 1835static void inferARCWriteback(TypeProcessingState &state, 1836 QualType &declSpecType) { 1837 Sema &S = state.getSema(); 1838 Declarator &declarator = state.getDeclarator(); 1839 1840 // TODO: should we care about decl qualifiers? 1841 1842 // Check whether the declarator has the expected form. We walk 1843 // from the inside out in order to make the block logic work. 1844 unsigned outermostPointerIndex = 0; 1845 bool isBlockPointer = false; 1846 unsigned numPointers = 0; 1847 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 1848 unsigned chunkIndex = i; 1849 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex); 1850 switch (chunk.Kind) { 1851 case DeclaratorChunk::Paren: 1852 // Ignore parens. 1853 break; 1854 1855 case DeclaratorChunk::Reference: 1856 case DeclaratorChunk::Pointer: 1857 // Count the number of pointers. Treat references 1858 // interchangeably as pointers; if they're mis-ordered, normal 1859 // type building will discover that. 1860 outermostPointerIndex = chunkIndex; 1861 numPointers++; 1862 break; 1863 1864 case DeclaratorChunk::BlockPointer: 1865 // If we have a pointer to block pointer, that's an acceptable 1866 // indirect reference; anything else is not an application of 1867 // the rules. 1868 if (numPointers != 1) return; 1869 numPointers++; 1870 outermostPointerIndex = chunkIndex; 1871 isBlockPointer = true; 1872 1873 // We don't care about pointer structure in return values here. 1874 goto done; 1875 1876 case DeclaratorChunk::Array: // suppress if written (id[])? 1877 case DeclaratorChunk::Function: 1878 case DeclaratorChunk::MemberPointer: 1879 return; 1880 } 1881 } 1882 done: 1883 1884 // If we have *one* pointer, then we want to throw the qualifier on 1885 // the declaration-specifiers, which means that it needs to be a 1886 // retainable object type. 1887 if (numPointers == 1) { 1888 // If it's not a retainable object type, the rule doesn't apply. 1889 if (!declSpecType->isObjCRetainableType()) return; 1890 1891 // If it already has lifetime, don't do anything. 1892 if (declSpecType.getObjCLifetime()) return; 1893 1894 // Otherwise, modify the type in-place. 1895 Qualifiers qs; 1896 1897 if (declSpecType->isObjCARCImplicitlyUnretainedType()) 1898 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone); 1899 else 1900 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing); 1901 declSpecType = S.Context.getQualifiedType(declSpecType, qs); 1902 1903 // If we have *two* pointers, then we want to throw the qualifier on 1904 // the outermost pointer. 1905 } else if (numPointers == 2) { 1906 // If we don't have a block pointer, we need to check whether the 1907 // declaration-specifiers gave us something that will turn into a 1908 // retainable object pointer after we slap the first pointer on it. 1909 if (!isBlockPointer && !declSpecType->isObjCObjectType()) 1910 return; 1911 1912 // Look for an explicit lifetime attribute there. 1913 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex); 1914 if (chunk.Kind != DeclaratorChunk::Pointer && 1915 chunk.Kind != DeclaratorChunk::BlockPointer) 1916 return; 1917 for (const AttributeList *attr = chunk.getAttrs(); attr; 1918 attr = attr->getNext()) 1919 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 1920 return; 1921 1922 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing, 1923 outermostPointerIndex); 1924 1925 // Any other number of pointers/references does not trigger the rule. 1926 } else return; 1927 1928 // TODO: mark whether we did this inference? 1929} 1930 1931static void diagnoseIgnoredQualifiers( 1932 Sema &S, unsigned Quals, 1933 SourceLocation FallbackLoc, 1934 SourceLocation ConstQualLoc = SourceLocation(), 1935 SourceLocation VolatileQualLoc = SourceLocation(), 1936 SourceLocation RestrictQualLoc = SourceLocation(), 1937 SourceLocation AtomicQualLoc = SourceLocation()) { 1938 if (!Quals) 1939 return; 1940 1941 const SourceManager &SM = S.getSourceManager(); 1942 1943 struct Qual { 1944 unsigned Mask; 1945 const char *Name; 1946 SourceLocation Loc; 1947 } const QualKinds[4] = { 1948 { DeclSpec::TQ_const, "const", ConstQualLoc }, 1949 { DeclSpec::TQ_volatile, "volatile", VolatileQualLoc }, 1950 { DeclSpec::TQ_restrict, "restrict", RestrictQualLoc }, 1951 { DeclSpec::TQ_atomic, "_Atomic", AtomicQualLoc } 1952 }; 1953 1954 llvm::SmallString<32> QualStr; 1955 unsigned NumQuals = 0; 1956 SourceLocation Loc; 1957 FixItHint FixIts[4]; 1958 1959 // Build a string naming the redundant qualifiers. 1960 for (unsigned I = 0; I != 4; ++I) { 1961 if (Quals & QualKinds[I].Mask) { 1962 if (!QualStr.empty()) QualStr += ' '; 1963 QualStr += QualKinds[I].Name; 1964 1965 // If we have a location for the qualifier, offer a fixit. 1966 SourceLocation QualLoc = QualKinds[I].Loc; 1967 if (!QualLoc.isInvalid()) { 1968 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc); 1969 if (Loc.isInvalid() || SM.isBeforeInTranslationUnit(QualLoc, Loc)) 1970 Loc = QualLoc; 1971 } 1972 1973 ++NumQuals; 1974 } 1975 } 1976 1977 S.Diag(Loc.isInvalid() ? FallbackLoc : Loc, diag::warn_qual_return_type) 1978 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3]; 1979} 1980 1981// Diagnose pointless type qualifiers on the return type of a function. 1982static void diagnoseIgnoredFunctionQualifiers(Sema &S, QualType RetTy, 1983 Declarator &D, 1984 unsigned FunctionChunkIndex) { 1985 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) { 1986 // FIXME: TypeSourceInfo doesn't preserve location information for 1987 // qualifiers. 1988 diagnoseIgnoredQualifiers(S, RetTy.getLocalCVRQualifiers(), 1989 D.getIdentifierLoc()); 1990 return; 1991 } 1992 1993 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1, 1994 End = D.getNumTypeObjects(); 1995 OuterChunkIndex != End; ++OuterChunkIndex) { 1996 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex); 1997 switch (OuterChunk.Kind) { 1998 case DeclaratorChunk::Paren: 1999 continue; 2000 2001 case DeclaratorChunk::Pointer: { 2002 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr; 2003 diagnoseIgnoredQualifiers( 2004 S, PTI.TypeQuals, 2005 SourceLocation(), 2006 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc), 2007 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc), 2008 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc), 2009 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc)); 2010 return; 2011 } 2012 2013 case DeclaratorChunk::Function: 2014 case DeclaratorChunk::BlockPointer: 2015 case DeclaratorChunk::Reference: 2016 case DeclaratorChunk::Array: 2017 case DeclaratorChunk::MemberPointer: 2018 // FIXME: We can't currently provide an accurate source location and a 2019 // fix-it hint for these. 2020 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0; 2021 diagnoseIgnoredQualifiers(S, RetTy.getCVRQualifiers() | AtomicQual, 2022 D.getIdentifierLoc()); 2023 return; 2024 } 2025 2026 llvm_unreachable("unknown declarator chunk kind"); 2027 } 2028 2029 // If the qualifiers come from a conversion function type, don't diagnose 2030 // them -- they're not necessarily redundant, since such a conversion 2031 // operator can be explicitly called as "x.operator const int()". 2032 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) 2033 return; 2034 2035 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers 2036 // which are present there. 2037 diagnoseIgnoredQualifiers(S, D.getDeclSpec().getTypeQualifiers(), 2038 D.getIdentifierLoc(), 2039 D.getDeclSpec().getConstSpecLoc(), 2040 D.getDeclSpec().getVolatileSpecLoc(), 2041 D.getDeclSpec().getRestrictSpecLoc(), 2042 D.getDeclSpec().getAtomicSpecLoc()); 2043} 2044 2045static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, 2046 TypeSourceInfo *&ReturnTypeInfo) { 2047 Sema &SemaRef = state.getSema(); 2048 Declarator &D = state.getDeclarator(); 2049 QualType T; 2050 ReturnTypeInfo = 0; 2051 2052 // The TagDecl owned by the DeclSpec. 2053 TagDecl *OwnedTagDecl = 0; 2054 2055 bool ContainsPlaceholderType = false; 2056 2057 switch (D.getName().getKind()) { 2058 case UnqualifiedId::IK_ImplicitSelfParam: 2059 case UnqualifiedId::IK_OperatorFunctionId: 2060 case UnqualifiedId::IK_Identifier: 2061 case UnqualifiedId::IK_LiteralOperatorId: 2062 case UnqualifiedId::IK_TemplateId: 2063 T = ConvertDeclSpecToType(state); 2064 ContainsPlaceholderType = D.getDeclSpec().containsPlaceholderType(); 2065 2066 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { 2067 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 2068 // Owned declaration is embedded in declarator. 2069 OwnedTagDecl->setEmbeddedInDeclarator(true); 2070 } 2071 break; 2072 2073 case UnqualifiedId::IK_ConstructorName: 2074 case UnqualifiedId::IK_ConstructorTemplateId: 2075 case UnqualifiedId::IK_DestructorName: 2076 // Constructors and destructors don't have return types. Use 2077 // "void" instead. 2078 T = SemaRef.Context.VoidTy; 2079 if (AttributeList *attrs = D.getDeclSpec().getAttributes().getList()) 2080 processTypeAttrs(state, T, TAL_DeclSpec, attrs); 2081 break; 2082 2083 case UnqualifiedId::IK_ConversionFunctionId: 2084 // The result type of a conversion function is the type that it 2085 // converts to. 2086 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId, 2087 &ReturnTypeInfo); 2088 ContainsPlaceholderType = T->getContainedAutoType(); 2089 break; 2090 } 2091 2092 if (D.getAttributes()) 2093 distributeTypeAttrsFromDeclarator(state, T); 2094 2095 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. 2096 // In C++11, a function declarator using 'auto' must have a trailing return 2097 // type (this is checked later) and we can skip this. In other languages 2098 // using auto, we need to check regardless. 2099 if (ContainsPlaceholderType && 2100 (!SemaRef.getLangOpts().CPlusPlus11 || !D.isFunctionDeclarator())) { 2101 int Error = -1; 2102 2103 switch (D.getContext()) { 2104 case Declarator::KNRTypeListContext: 2105 llvm_unreachable("K&R type lists aren't allowed in C++"); 2106 case Declarator::LambdaExprContext: 2107 llvm_unreachable("Can't specify a type specifier in lambda grammar"); 2108 case Declarator::ObjCParameterContext: 2109 case Declarator::ObjCResultContext: 2110 case Declarator::PrototypeContext: 2111 Error = 0; // Function prototype 2112 break; 2113 case Declarator::MemberContext: 2114 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) 2115 break; 2116 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) { 2117 case TTK_Enum: llvm_unreachable("unhandled tag kind"); 2118 case TTK_Struct: Error = 1; /* Struct member */ break; 2119 case TTK_Union: Error = 2; /* Union member */ break; 2120 case TTK_Class: Error = 3; /* Class member */ break; 2121 case TTK_Interface: Error = 4; /* Interface member */ break; 2122 } 2123 break; 2124 case Declarator::CXXCatchContext: 2125 case Declarator::ObjCCatchContext: 2126 Error = 5; // Exception declaration 2127 break; 2128 case Declarator::TemplateParamContext: 2129 Error = 6; // Template parameter 2130 break; 2131 case Declarator::BlockLiteralContext: 2132 Error = 7; // Block literal 2133 break; 2134 case Declarator::TemplateTypeArgContext: 2135 Error = 8; // Template type argument 2136 break; 2137 case Declarator::AliasDeclContext: 2138 case Declarator::AliasTemplateContext: 2139 Error = 10; // Type alias 2140 break; 2141 case Declarator::TrailingReturnContext: 2142 if (!SemaRef.getLangOpts().CPlusPlus1y) 2143 Error = 11; // Function return type 2144 break; 2145 case Declarator::ConversionIdContext: 2146 if (!SemaRef.getLangOpts().CPlusPlus1y) 2147 Error = 12; // conversion-type-id 2148 break; 2149 case Declarator::TypeNameContext: 2150 Error = 13; // Generic 2151 break; 2152 case Declarator::FileContext: 2153 case Declarator::BlockContext: 2154 case Declarator::ForContext: 2155 case Declarator::ConditionContext: 2156 case Declarator::CXXNewContext: 2157 break; 2158 } 2159 2160 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 2161 Error = 9; 2162 2163 // In Objective-C it is an error to use 'auto' on a function declarator. 2164 if (D.isFunctionDeclarator()) 2165 Error = 11; 2166 2167 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator 2168 // contains a trailing return type. That is only legal at the outermost 2169 // level. Check all declarator chunks (outermost first) anyway, to give 2170 // better diagnostics. 2171 if (SemaRef.getLangOpts().CPlusPlus11 && Error != -1) { 2172 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 2173 unsigned chunkIndex = e - i - 1; 2174 state.setCurrentChunkIndex(chunkIndex); 2175 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 2176 if (DeclType.Kind == DeclaratorChunk::Function) { 2177 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 2178 if (FTI.hasTrailingReturnType()) { 2179 Error = -1; 2180 break; 2181 } 2182 } 2183 } 2184 } 2185 2186 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc(); 2187 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) 2188 AutoRange = D.getName().getSourceRange(); 2189 2190 if (Error != -1) { 2191 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed) 2192 << Error << AutoRange; 2193 T = SemaRef.Context.IntTy; 2194 D.setInvalidType(true); 2195 } else 2196 SemaRef.Diag(AutoRange.getBegin(), 2197 diag::warn_cxx98_compat_auto_type_specifier) 2198 << AutoRange; 2199 } 2200 2201 if (SemaRef.getLangOpts().CPlusPlus && 2202 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { 2203 // Check the contexts where C++ forbids the declaration of a new class 2204 // or enumeration in a type-specifier-seq. 2205 switch (D.getContext()) { 2206 case Declarator::TrailingReturnContext: 2207 // Class and enumeration definitions are syntactically not allowed in 2208 // trailing return types. 2209 llvm_unreachable("parser should not have allowed this"); 2210 break; 2211 case Declarator::FileContext: 2212 case Declarator::MemberContext: 2213 case Declarator::BlockContext: 2214 case Declarator::ForContext: 2215 case Declarator::BlockLiteralContext: 2216 case Declarator::LambdaExprContext: 2217 // C++11 [dcl.type]p3: 2218 // A type-specifier-seq shall not define a class or enumeration unless 2219 // it appears in the type-id of an alias-declaration (7.1.3) that is not 2220 // the declaration of a template-declaration. 2221 case Declarator::AliasDeclContext: 2222 break; 2223 case Declarator::AliasTemplateContext: 2224 SemaRef.Diag(OwnedTagDecl->getLocation(), 2225 diag::err_type_defined_in_alias_template) 2226 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 2227 D.setInvalidType(true); 2228 break; 2229 case Declarator::TypeNameContext: 2230 case Declarator::ConversionIdContext: 2231 case Declarator::TemplateParamContext: 2232 case Declarator::CXXNewContext: 2233 case Declarator::CXXCatchContext: 2234 case Declarator::ObjCCatchContext: 2235 case Declarator::TemplateTypeArgContext: 2236 SemaRef.Diag(OwnedTagDecl->getLocation(), 2237 diag::err_type_defined_in_type_specifier) 2238 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 2239 D.setInvalidType(true); 2240 break; 2241 case Declarator::PrototypeContext: 2242 case Declarator::ObjCParameterContext: 2243 case Declarator::ObjCResultContext: 2244 case Declarator::KNRTypeListContext: 2245 // C++ [dcl.fct]p6: 2246 // Types shall not be defined in return or parameter types. 2247 SemaRef.Diag(OwnedTagDecl->getLocation(), 2248 diag::err_type_defined_in_param_type) 2249 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 2250 D.setInvalidType(true); 2251 break; 2252 case Declarator::ConditionContext: 2253 // C++ 6.4p2: 2254 // The type-specifier-seq shall not contain typedef and shall not declare 2255 // a new class or enumeration. 2256 SemaRef.Diag(OwnedTagDecl->getLocation(), 2257 diag::err_type_defined_in_condition); 2258 D.setInvalidType(true); 2259 break; 2260 } 2261 } 2262 2263 return T; 2264} 2265 2266static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){ 2267 std::string Quals = 2268 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString(); 2269 2270 switch (FnTy->getRefQualifier()) { 2271 case RQ_None: 2272 break; 2273 2274 case RQ_LValue: 2275 if (!Quals.empty()) 2276 Quals += ' '; 2277 Quals += '&'; 2278 break; 2279 2280 case RQ_RValue: 2281 if (!Quals.empty()) 2282 Quals += ' '; 2283 Quals += "&&"; 2284 break; 2285 } 2286 2287 return Quals; 2288} 2289 2290/// Check that the function type T, which has a cv-qualifier or a ref-qualifier, 2291/// can be contained within the declarator chunk DeclType, and produce an 2292/// appropriate diagnostic if not. 2293static void checkQualifiedFunction(Sema &S, QualType T, 2294 DeclaratorChunk &DeclType) { 2295 // C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: a function type with a 2296 // cv-qualifier or a ref-qualifier can only appear at the topmost level 2297 // of a type. 2298 int DiagKind = -1; 2299 switch (DeclType.Kind) { 2300 case DeclaratorChunk::Paren: 2301 case DeclaratorChunk::MemberPointer: 2302 // These cases are permitted. 2303 return; 2304 case DeclaratorChunk::Array: 2305 case DeclaratorChunk::Function: 2306 // These cases don't allow function types at all; no need to diagnose the 2307 // qualifiers separately. 2308 return; 2309 case DeclaratorChunk::BlockPointer: 2310 DiagKind = 0; 2311 break; 2312 case DeclaratorChunk::Pointer: 2313 DiagKind = 1; 2314 break; 2315 case DeclaratorChunk::Reference: 2316 DiagKind = 2; 2317 break; 2318 } 2319 2320 assert(DiagKind != -1); 2321 S.Diag(DeclType.Loc, diag::err_compound_qualified_function_type) 2322 << DiagKind << isa<FunctionType>(T.IgnoreParens()) << T 2323 << getFunctionQualifiersAsString(T->castAs<FunctionProtoType>()); 2324} 2325 2326/// Produce an approprioate diagnostic for an ambiguity between a function 2327/// declarator and a C++ direct-initializer. 2328static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, 2329 DeclaratorChunk &DeclType, QualType RT) { 2330 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 2331 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity"); 2332 2333 // If the return type is void there is no ambiguity. 2334 if (RT->isVoidType()) 2335 return; 2336 2337 // An initializer for a non-class type can have at most one argument. 2338 if (!RT->isRecordType() && FTI.NumArgs > 1) 2339 return; 2340 2341 // An initializer for a reference must have exactly one argument. 2342 if (RT->isReferenceType() && FTI.NumArgs != 1) 2343 return; 2344 2345 // Only warn if this declarator is declaring a function at block scope, and 2346 // doesn't have a storage class (such as 'extern') specified. 2347 if (!D.isFunctionDeclarator() || 2348 D.getFunctionDefinitionKind() != FDK_Declaration || 2349 !S.CurContext->isFunctionOrMethod() || 2350 D.getDeclSpec().getStorageClassSpec() 2351 != DeclSpec::SCS_unspecified) 2352 return; 2353 2354 // Inside a condition, a direct initializer is not permitted. We allow one to 2355 // be parsed in order to give better diagnostics in condition parsing. 2356 if (D.getContext() == Declarator::ConditionContext) 2357 return; 2358 2359 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc); 2360 2361 S.Diag(DeclType.Loc, 2362 FTI.NumArgs ? diag::warn_parens_disambiguated_as_function_declaration 2363 : diag::warn_empty_parens_are_function_decl) 2364 << ParenRange; 2365 2366 // If the declaration looks like: 2367 // T var1, 2368 // f(); 2369 // and name lookup finds a function named 'f', then the ',' was 2370 // probably intended to be a ';'. 2371 if (!D.isFirstDeclarator() && D.getIdentifier()) { 2372 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr); 2373 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr); 2374 if (Comma.getFileID() != Name.getFileID() || 2375 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { 2376 LookupResult Result(S, D.getIdentifier(), SourceLocation(), 2377 Sema::LookupOrdinaryName); 2378 if (S.LookupName(Result, S.getCurScope())) 2379 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) 2380 << FixItHint::CreateReplacement(D.getCommaLoc(), ";") 2381 << D.getIdentifier(); 2382 } 2383 } 2384 2385 if (FTI.NumArgs > 0) { 2386 // For a declaration with parameters, eg. "T var(T());", suggest adding parens 2387 // around the first parameter to turn the declaration into a variable 2388 // declaration. 2389 SourceRange Range = FTI.ArgInfo[0].Param->getSourceRange(); 2390 SourceLocation B = Range.getBegin(); 2391 SourceLocation E = S.PP.getLocForEndOfToken(Range.getEnd()); 2392 // FIXME: Maybe we should suggest adding braces instead of parens 2393 // in C++11 for classes that don't have an initializer_list constructor. 2394 S.Diag(B, diag::note_additional_parens_for_variable_declaration) 2395 << FixItHint::CreateInsertion(B, "(") 2396 << FixItHint::CreateInsertion(E, ")"); 2397 } else { 2398 // For a declaration without parameters, eg. "T var();", suggest replacing the 2399 // parens with an initializer to turn the declaration into a variable 2400 // declaration. 2401 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); 2402 2403 // Empty parens mean value-initialization, and no parens mean 2404 // default initialization. These are equivalent if the default 2405 // constructor is user-provided or if zero-initialization is a 2406 // no-op. 2407 if (RD && RD->hasDefinition() && 2408 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) 2409 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor) 2410 << FixItHint::CreateRemoval(ParenRange); 2411 else { 2412 std::string Init = S.getFixItZeroInitializerForType(RT); 2413 if (Init.empty() && S.LangOpts.CPlusPlus11) 2414 Init = "{}"; 2415 if (!Init.empty()) 2416 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize) 2417 << FixItHint::CreateReplacement(ParenRange, Init); 2418 } 2419 } 2420} 2421 2422static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, 2423 QualType declSpecType, 2424 TypeSourceInfo *TInfo) { 2425 2426 QualType T = declSpecType; 2427 Declarator &D = state.getDeclarator(); 2428 Sema &S = state.getSema(); 2429 ASTContext &Context = S.Context; 2430 const LangOptions &LangOpts = S.getLangOpts(); 2431 2432 // The name we're declaring, if any. 2433 DeclarationName Name; 2434 if (D.getIdentifier()) 2435 Name = D.getIdentifier(); 2436 2437 // Does this declaration declare a typedef-name? 2438 bool IsTypedefName = 2439 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || 2440 D.getContext() == Declarator::AliasDeclContext || 2441 D.getContext() == Declarator::AliasTemplateContext; 2442 2443 // Does T refer to a function type with a cv-qualifier or a ref-qualifier? 2444 bool IsQualifiedFunction = T->isFunctionProtoType() && 2445 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 || 2446 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); 2447 2448 // If T is 'decltype(auto)', the only declarators we can have are parens 2449 // and at most one function declarator if this is a function declaration. 2450 if (const AutoType *AT = T->getAs<AutoType>()) { 2451 if (AT->isDecltypeAuto()) { 2452 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 2453 unsigned Index = E - I - 1; 2454 DeclaratorChunk &DeclChunk = D.getTypeObject(Index); 2455 unsigned DiagId = diag::err_decltype_auto_compound_type; 2456 unsigned DiagKind = 0; 2457 switch (DeclChunk.Kind) { 2458 case DeclaratorChunk::Paren: 2459 continue; 2460 case DeclaratorChunk::Function: { 2461 unsigned FnIndex; 2462 if (D.isFunctionDeclarationContext() && 2463 D.isFunctionDeclarator(FnIndex) && FnIndex == Index) 2464 continue; 2465 DiagId = diag::err_decltype_auto_function_declarator_not_declaration; 2466 break; 2467 } 2468 case DeclaratorChunk::Pointer: 2469 case DeclaratorChunk::BlockPointer: 2470 case DeclaratorChunk::MemberPointer: 2471 DiagKind = 0; 2472 break; 2473 case DeclaratorChunk::Reference: 2474 DiagKind = 1; 2475 break; 2476 case DeclaratorChunk::Array: 2477 DiagKind = 2; 2478 break; 2479 } 2480 2481 S.Diag(DeclChunk.Loc, DiagId) << DiagKind; 2482 D.setInvalidType(true); 2483 break; 2484 } 2485 } 2486 } 2487 2488 // Walk the DeclTypeInfo, building the recursive type as we go. 2489 // DeclTypeInfos are ordered from the identifier out, which is 2490 // opposite of what we want :). 2491 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 2492 unsigned chunkIndex = e - i - 1; 2493 state.setCurrentChunkIndex(chunkIndex); 2494 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 2495 if (IsQualifiedFunction) { 2496 checkQualifiedFunction(S, T, DeclType); 2497 IsQualifiedFunction = DeclType.Kind == DeclaratorChunk::Paren; 2498 } 2499 switch (DeclType.Kind) { 2500 case DeclaratorChunk::Paren: 2501 T = S.BuildParenType(T); 2502 break; 2503 case DeclaratorChunk::BlockPointer: 2504 // If blocks are disabled, emit an error. 2505 if (!LangOpts.Blocks) 2506 S.Diag(DeclType.Loc, diag::err_blocks_disable); 2507 2508 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); 2509 if (DeclType.Cls.TypeQuals) 2510 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); 2511 break; 2512 case DeclaratorChunk::Pointer: 2513 // Verify that we're not building a pointer to pointer to function with 2514 // exception specification. 2515 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 2516 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 2517 D.setInvalidType(true); 2518 // Build the type anyway. 2519 } 2520 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) { 2521 T = Context.getObjCObjectPointerType(T); 2522 if (DeclType.Ptr.TypeQuals) 2523 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 2524 break; 2525 } 2526 T = S.BuildPointerType(T, DeclType.Loc, Name); 2527 if (DeclType.Ptr.TypeQuals) 2528 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 2529 2530 break; 2531 case DeclaratorChunk::Reference: { 2532 // Verify that we're not building a reference to pointer to function with 2533 // exception specification. 2534 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 2535 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 2536 D.setInvalidType(true); 2537 // Build the type anyway. 2538 } 2539 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); 2540 2541 Qualifiers Quals; 2542 if (DeclType.Ref.HasRestrict) 2543 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); 2544 break; 2545 } 2546 case DeclaratorChunk::Array: { 2547 // Verify that we're not building an array of pointers to function with 2548 // exception specification. 2549 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 2550 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 2551 D.setInvalidType(true); 2552 // Build the type anyway. 2553 } 2554 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 2555 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 2556 ArrayType::ArraySizeModifier ASM; 2557 if (ATI.isStar) 2558 ASM = ArrayType::Star; 2559 else if (ATI.hasStatic) 2560 ASM = ArrayType::Static; 2561 else 2562 ASM = ArrayType::Normal; 2563 if (ASM == ArrayType::Star && !D.isPrototypeContext()) { 2564 // FIXME: This check isn't quite right: it allows star in prototypes 2565 // for function definitions, and disallows some edge cases detailed 2566 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 2567 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 2568 ASM = ArrayType::Normal; 2569 D.setInvalidType(true); 2570 } 2571 2572 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static 2573 // shall appear only in a declaration of a function parameter with an 2574 // array type, ... 2575 if (ASM == ArrayType::Static || ATI.TypeQuals) { 2576 if (!(D.isPrototypeContext() || 2577 D.getContext() == Declarator::KNRTypeListContext)) { 2578 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) << 2579 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 2580 // Remove the 'static' and the type qualifiers. 2581 if (ASM == ArrayType::Static) 2582 ASM = ArrayType::Normal; 2583 ATI.TypeQuals = 0; 2584 D.setInvalidType(true); 2585 } 2586 2587 // C99 6.7.5.2p1: ... and then only in the outermost array type 2588 // derivation. 2589 unsigned x = chunkIndex; 2590 while (x != 0) { 2591 // Walk outwards along the declarator chunks. 2592 x--; 2593 const DeclaratorChunk &DC = D.getTypeObject(x); 2594 switch (DC.Kind) { 2595 case DeclaratorChunk::Paren: 2596 continue; 2597 case DeclaratorChunk::Array: 2598 case DeclaratorChunk::Pointer: 2599 case DeclaratorChunk::Reference: 2600 case DeclaratorChunk::MemberPointer: 2601 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) << 2602 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 2603 if (ASM == ArrayType::Static) 2604 ASM = ArrayType::Normal; 2605 ATI.TypeQuals = 0; 2606 D.setInvalidType(true); 2607 break; 2608 case DeclaratorChunk::Function: 2609 case DeclaratorChunk::BlockPointer: 2610 // These are invalid anyway, so just ignore. 2611 break; 2612 } 2613 } 2614 } 2615 2616 if (const AutoType *AT = T->getContainedAutoType()) { 2617 // We've already diagnosed this for decltype(auto). 2618 if (!AT->isDecltypeAuto()) 2619 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto) 2620 << getPrintableNameForEntity(Name) << T; 2621 T = QualType(); 2622 break; 2623 } 2624 2625 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, 2626 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 2627 break; 2628 } 2629 case DeclaratorChunk::Function: { 2630 // If the function declarator has a prototype (i.e. it is not () and 2631 // does not have a K&R-style identifier list), then the arguments are part 2632 // of the type, otherwise the argument list is (). 2633 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 2634 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier(); 2635 2636 // Check for auto functions and trailing return type and adjust the 2637 // return type accordingly. 2638 if (!D.isInvalidType()) { 2639 // trailing-return-type is only required if we're declaring a function, 2640 // and not, for instance, a pointer to a function. 2641 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 2642 !FTI.hasTrailingReturnType() && chunkIndex == 0 && 2643 !S.getLangOpts().CPlusPlus1y) { 2644 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2645 diag::err_auto_missing_trailing_return); 2646 T = Context.IntTy; 2647 D.setInvalidType(true); 2648 } else if (FTI.hasTrailingReturnType()) { 2649 // T must be exactly 'auto' at this point. See CWG issue 681. 2650 if (isa<ParenType>(T)) { 2651 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2652 diag::err_trailing_return_in_parens) 2653 << T << D.getDeclSpec().getSourceRange(); 2654 D.setInvalidType(true); 2655 } else if (D.getContext() != Declarator::LambdaExprContext && 2656 (T.hasQualifiers() || !isa<AutoType>(T) || 2657 cast<AutoType>(T)->isDecltypeAuto())) { 2658 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2659 diag::err_trailing_return_without_auto) 2660 << T << D.getDeclSpec().getSourceRange(); 2661 D.setInvalidType(true); 2662 } 2663 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo); 2664 if (T.isNull()) { 2665 // An error occurred parsing the trailing return type. 2666 T = Context.IntTy; 2667 D.setInvalidType(true); 2668 } 2669 } 2670 } 2671 2672 // C99 6.7.5.3p1: The return type may not be a function or array type. 2673 // For conversion functions, we'll diagnose this particular error later. 2674 if ((T->isArrayType() || T->isFunctionType()) && 2675 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) { 2676 unsigned diagID = diag::err_func_returning_array_function; 2677 // Last processing chunk in block context means this function chunk 2678 // represents the block. 2679 if (chunkIndex == 0 && 2680 D.getContext() == Declarator::BlockLiteralContext) 2681 diagID = diag::err_block_returning_array_function; 2682 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; 2683 T = Context.IntTy; 2684 D.setInvalidType(true); 2685 } 2686 2687 // Do not allow returning half FP value. 2688 // FIXME: This really should be in BuildFunctionType. 2689 if (T->isHalfType()) { 2690 if (S.getLangOpts().OpenCL) { 2691 if (!S.getOpenCLOptions().cl_khr_fp16) { 2692 S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T; 2693 D.setInvalidType(true); 2694 } 2695 } else { 2696 S.Diag(D.getIdentifierLoc(), 2697 diag::err_parameters_retval_cannot_have_fp16_type) << 1; 2698 D.setInvalidType(true); 2699 } 2700 } 2701 2702 // Methods cannot return interface types. All ObjC objects are 2703 // passed by reference. 2704 if (T->isObjCObjectType()) { 2705 SourceLocation DiagLoc, FixitLoc; 2706 if (TInfo) { 2707 DiagLoc = TInfo->getTypeLoc().getLocStart(); 2708 FixitLoc = S.PP.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd()); 2709 } else { 2710 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 2711 FixitLoc = S.PP.getLocForEndOfToken(D.getDeclSpec().getLocEnd()); 2712 } 2713 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value) 2714 << 0 << T 2715 << FixItHint::CreateInsertion(FixitLoc, "*"); 2716 2717 T = Context.getObjCObjectPointerType(T); 2718 if (TInfo) { 2719 TypeLocBuilder TLB; 2720 TLB.pushFullCopy(TInfo->getTypeLoc()); 2721 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T); 2722 TLoc.setStarLoc(FixitLoc); 2723 TInfo = TLB.getTypeSourceInfo(Context, T); 2724 } 2725 2726 D.setInvalidType(true); 2727 } 2728 2729 // cv-qualifiers on return types are pointless except when the type is a 2730 // class type in C++. 2731 if ((T.getCVRQualifiers() || T->isAtomicType()) && 2732 !(S.getLangOpts().CPlusPlus && 2733 (T->isDependentType() || T->isRecordType()))) 2734 diagnoseIgnoredFunctionQualifiers(S, T, D, chunkIndex); 2735 2736 // Objective-C ARC ownership qualifiers are ignored on the function 2737 // return type (by type canonicalization). Complain if this attribute 2738 // was written here. 2739 if (T.getQualifiers().hasObjCLifetime()) { 2740 SourceLocation AttrLoc; 2741 if (chunkIndex + 1 < D.getNumTypeObjects()) { 2742 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); 2743 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs(); 2744 Attr; Attr = Attr->getNext()) { 2745 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 2746 AttrLoc = Attr->getLoc(); 2747 break; 2748 } 2749 } 2750 } 2751 if (AttrLoc.isInvalid()) { 2752 for (const AttributeList *Attr 2753 = D.getDeclSpec().getAttributes().getList(); 2754 Attr; Attr = Attr->getNext()) { 2755 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 2756 AttrLoc = Attr->getLoc(); 2757 break; 2758 } 2759 } 2760 } 2761 2762 if (AttrLoc.isValid()) { 2763 // The ownership attributes are almost always written via 2764 // the predefined 2765 // __strong/__weak/__autoreleasing/__unsafe_unretained. 2766 if (AttrLoc.isMacroID()) 2767 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first; 2768 2769 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) 2770 << T.getQualifiers().getObjCLifetime(); 2771 } 2772 } 2773 2774 if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) { 2775 // C++ [dcl.fct]p6: 2776 // Types shall not be defined in return or parameter types. 2777 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 2778 if (Tag->isCompleteDefinition()) 2779 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 2780 << Context.getTypeDeclType(Tag); 2781 } 2782 2783 // Exception specs are not allowed in typedefs. Complain, but add it 2784 // anyway. 2785 if (IsTypedefName && FTI.getExceptionSpecType()) 2786 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef) 2787 << (D.getContext() == Declarator::AliasDeclContext || 2788 D.getContext() == Declarator::AliasTemplateContext); 2789 2790 // If we see "T var();" or "T var(T());" at block scope, it is probably 2791 // an attempt to initialize a variable, not a function declaration. 2792 if (FTI.isAmbiguous) 2793 warnAboutAmbiguousFunction(S, D, DeclType, T); 2794 2795 if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) { 2796 // Simple void foo(), where the incoming T is the result type. 2797 T = Context.getFunctionNoProtoType(T); 2798 } else { 2799 // We allow a zero-parameter variadic function in C if the 2800 // function is marked with the "overloadable" attribute. Scan 2801 // for this attribute now. 2802 if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) { 2803 bool Overloadable = false; 2804 for (const AttributeList *Attrs = D.getAttributes(); 2805 Attrs; Attrs = Attrs->getNext()) { 2806 if (Attrs->getKind() == AttributeList::AT_Overloadable) { 2807 Overloadable = true; 2808 break; 2809 } 2810 } 2811 2812 if (!Overloadable) 2813 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg); 2814 } 2815 2816 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) { 2817 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function 2818 // definition. 2819 S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration); 2820 D.setInvalidType(true); 2821 // Recover by creating a K&R-style function type. 2822 T = Context.getFunctionNoProtoType(T); 2823 break; 2824 } 2825 2826 FunctionProtoType::ExtProtoInfo EPI; 2827 EPI.Variadic = FTI.isVariadic; 2828 EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); 2829 EPI.TypeQuals = FTI.TypeQuals; 2830 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None 2831 : FTI.RefQualifierIsLValueRef? RQ_LValue 2832 : RQ_RValue; 2833 2834 // Otherwise, we have a function with an argument list that is 2835 // potentially variadic. 2836 SmallVector<QualType, 16> ArgTys; 2837 ArgTys.reserve(FTI.NumArgs); 2838 2839 SmallVector<bool, 16> ConsumedArguments; 2840 ConsumedArguments.reserve(FTI.NumArgs); 2841 bool HasAnyConsumedArguments = false; 2842 2843 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 2844 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 2845 QualType ArgTy = Param->getType(); 2846 assert(!ArgTy.isNull() && "Couldn't parse type?"); 2847 2848 // Look for 'void'. void is allowed only as a single argument to a 2849 // function with no other parameters (C99 6.7.5.3p10). We record 2850 // int(void) as a FunctionProtoType with an empty argument list. 2851 if (ArgTy->isVoidType()) { 2852 // If this is something like 'float(int, void)', reject it. 'void' 2853 // is an incomplete type (C99 6.2.5p19) and function decls cannot 2854 // have arguments of incomplete type. 2855 if (FTI.NumArgs != 1 || FTI.isVariadic) { 2856 S.Diag(DeclType.Loc, diag::err_void_only_param); 2857 ArgTy = Context.IntTy; 2858 Param->setType(ArgTy); 2859 } else if (FTI.ArgInfo[i].Ident) { 2860 // Reject, but continue to parse 'int(void abc)'. 2861 S.Diag(FTI.ArgInfo[i].IdentLoc, 2862 diag::err_param_with_void_type); 2863 ArgTy = Context.IntTy; 2864 Param->setType(ArgTy); 2865 } else { 2866 // Reject, but continue to parse 'float(const void)'. 2867 if (ArgTy.hasQualifiers()) 2868 S.Diag(DeclType.Loc, diag::err_void_param_qualified); 2869 2870 // Do not add 'void' to the ArgTys list. 2871 break; 2872 } 2873 } else if (ArgTy->isHalfType()) { 2874 // Disallow half FP arguments. 2875 // FIXME: This really should be in BuildFunctionType. 2876 if (S.getLangOpts().OpenCL) { 2877 if (!S.getOpenCLOptions().cl_khr_fp16) { 2878 S.Diag(Param->getLocation(), 2879 diag::err_opencl_half_argument) << ArgTy; 2880 D.setInvalidType(); 2881 Param->setInvalidDecl(); 2882 } 2883 } else { 2884 S.Diag(Param->getLocation(), 2885 diag::err_parameters_retval_cannot_have_fp16_type) << 0; 2886 D.setInvalidType(); 2887 } 2888 } else if (!FTI.hasPrototype) { 2889 if (ArgTy->isPromotableIntegerType()) { 2890 ArgTy = Context.getPromotedIntegerType(ArgTy); 2891 Param->setKNRPromoted(true); 2892 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) { 2893 if (BTy->getKind() == BuiltinType::Float) { 2894 ArgTy = Context.DoubleTy; 2895 Param->setKNRPromoted(true); 2896 } 2897 } 2898 } 2899 2900 if (LangOpts.ObjCAutoRefCount) { 2901 bool Consumed = Param->hasAttr<NSConsumedAttr>(); 2902 ConsumedArguments.push_back(Consumed); 2903 HasAnyConsumedArguments |= Consumed; 2904 } 2905 2906 ArgTys.push_back(ArgTy); 2907 } 2908 2909 if (HasAnyConsumedArguments) 2910 EPI.ConsumedArguments = ConsumedArguments.data(); 2911 2912 SmallVector<QualType, 4> Exceptions; 2913 SmallVector<ParsedType, 2> DynamicExceptions; 2914 SmallVector<SourceRange, 2> DynamicExceptionRanges; 2915 Expr *NoexceptExpr = 0; 2916 2917 if (FTI.getExceptionSpecType() == EST_Dynamic) { 2918 // FIXME: It's rather inefficient to have to split into two vectors 2919 // here. 2920 unsigned N = FTI.NumExceptions; 2921 DynamicExceptions.reserve(N); 2922 DynamicExceptionRanges.reserve(N); 2923 for (unsigned I = 0; I != N; ++I) { 2924 DynamicExceptions.push_back(FTI.Exceptions[I].Ty); 2925 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); 2926 } 2927 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) { 2928 NoexceptExpr = FTI.NoexceptExpr; 2929 } 2930 2931 S.checkExceptionSpecification(FTI.getExceptionSpecType(), 2932 DynamicExceptions, 2933 DynamicExceptionRanges, 2934 NoexceptExpr, 2935 Exceptions, 2936 EPI); 2937 2938 T = Context.getFunctionType(T, ArgTys, EPI); 2939 } 2940 2941 break; 2942 } 2943 case DeclaratorChunk::MemberPointer: 2944 // The scope spec must refer to a class, or be dependent. 2945 CXXScopeSpec &SS = DeclType.Mem.Scope(); 2946 QualType ClsType; 2947 if (SS.isInvalid()) { 2948 // Avoid emitting extra errors if we already errored on the scope. 2949 D.setInvalidType(true); 2950 } else if (S.isDependentScopeSpecifier(SS) || 2951 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) { 2952 NestedNameSpecifier *NNS 2953 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 2954 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 2955 switch (NNS->getKind()) { 2956 case NestedNameSpecifier::Identifier: 2957 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, 2958 NNS->getAsIdentifier()); 2959 break; 2960 2961 case NestedNameSpecifier::Namespace: 2962 case NestedNameSpecifier::NamespaceAlias: 2963 case NestedNameSpecifier::Global: 2964 llvm_unreachable("Nested-name-specifier must name a type"); 2965 2966 case NestedNameSpecifier::TypeSpec: 2967 case NestedNameSpecifier::TypeSpecWithTemplate: 2968 ClsType = QualType(NNS->getAsType(), 0); 2969 // Note: if the NNS has a prefix and ClsType is a nondependent 2970 // TemplateSpecializationType, then the NNS prefix is NOT included 2971 // in ClsType; hence we wrap ClsType into an ElaboratedType. 2972 // NOTE: in particular, no wrap occurs if ClsType already is an 2973 // Elaborated, DependentName, or DependentTemplateSpecialization. 2974 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) 2975 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); 2976 break; 2977 } 2978 } else { 2979 S.Diag(DeclType.Mem.Scope().getBeginLoc(), 2980 diag::err_illegal_decl_mempointer_in_nonclass) 2981 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 2982 << DeclType.Mem.Scope().getRange(); 2983 D.setInvalidType(true); 2984 } 2985 2986 if (!ClsType.isNull()) 2987 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier()); 2988 if (T.isNull()) { 2989 T = Context.IntTy; 2990 D.setInvalidType(true); 2991 } else if (DeclType.Mem.TypeQuals) { 2992 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); 2993 } 2994 break; 2995 } 2996 2997 if (T.isNull()) { 2998 D.setInvalidType(true); 2999 T = Context.IntTy; 3000 } 3001 3002 // See if there are any attributes on this declarator chunk. 3003 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs())) 3004 processTypeAttrs(state, T, TAL_DeclChunk, attrs); 3005 } 3006 3007 if (LangOpts.CPlusPlus && T->isFunctionType()) { 3008 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 3009 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 3010 3011 // C++ 8.3.5p4: 3012 // A cv-qualifier-seq shall only be part of the function type 3013 // for a nonstatic member function, the function type to which a pointer 3014 // to member refers, or the top-level function type of a function typedef 3015 // declaration. 3016 // 3017 // Core issue 547 also allows cv-qualifiers on function types that are 3018 // top-level template type arguments. 3019 bool FreeFunction; 3020 if (!D.getCXXScopeSpec().isSet()) { 3021 FreeFunction = ((D.getContext() != Declarator::MemberContext && 3022 D.getContext() != Declarator::LambdaExprContext) || 3023 D.getDeclSpec().isFriendSpecified()); 3024 } else { 3025 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); 3026 FreeFunction = (DC && !DC->isRecord()); 3027 } 3028 3029 // C++11 [dcl.fct]p6 (w/DR1417): 3030 // An attempt to specify a function type with a cv-qualifier-seq or a 3031 // ref-qualifier (including by typedef-name) is ill-formed unless it is: 3032 // - the function type for a non-static member function, 3033 // - the function type to which a pointer to member refers, 3034 // - the top-level function type of a function typedef declaration or 3035 // alias-declaration, 3036 // - the type-id in the default argument of a type-parameter, or 3037 // - the type-id of a template-argument for a type-parameter 3038 if (IsQualifiedFunction && 3039 !(!FreeFunction && 3040 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && 3041 !IsTypedefName && 3042 D.getContext() != Declarator::TemplateTypeArgContext) { 3043 SourceLocation Loc = D.getLocStart(); 3044 SourceRange RemovalRange; 3045 unsigned I; 3046 if (D.isFunctionDeclarator(I)) { 3047 SmallVector<SourceLocation, 4> RemovalLocs; 3048 const DeclaratorChunk &Chunk = D.getTypeObject(I); 3049 assert(Chunk.Kind == DeclaratorChunk::Function); 3050 if (Chunk.Fun.hasRefQualifier()) 3051 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); 3052 if (Chunk.Fun.TypeQuals & Qualifiers::Const) 3053 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc()); 3054 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile) 3055 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc()); 3056 // FIXME: We do not track the location of the __restrict qualifier. 3057 //if (Chunk.Fun.TypeQuals & Qualifiers::Restrict) 3058 // RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc()); 3059 if (!RemovalLocs.empty()) { 3060 std::sort(RemovalLocs.begin(), RemovalLocs.end(), 3061 BeforeThanCompare<SourceLocation>(S.getSourceManager())); 3062 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); 3063 Loc = RemovalLocs.front(); 3064 } 3065 } 3066 3067 S.Diag(Loc, diag::err_invalid_qualified_function_type) 3068 << FreeFunction << D.isFunctionDeclarator() << T 3069 << getFunctionQualifiersAsString(FnTy) 3070 << FixItHint::CreateRemoval(RemovalRange); 3071 3072 // Strip the cv-qualifiers and ref-qualifiers from the type. 3073 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 3074 EPI.TypeQuals = 0; 3075 EPI.RefQualifier = RQ_None; 3076 3077 T = Context.getFunctionType(FnTy->getResultType(), FnTy->getArgTypes(), 3078 EPI); 3079 // Rebuild any parens around the identifier in the function type. 3080 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 3081 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) 3082 break; 3083 T = S.BuildParenType(T); 3084 } 3085 } 3086 } 3087 3088 // Apply any undistributed attributes from the declarator. 3089 if (!T.isNull()) 3090 if (AttributeList *attrs = D.getAttributes()) 3091 processTypeAttrs(state, T, TAL_DeclName, attrs); 3092 3093 // Diagnose any ignored type attributes. 3094 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T); 3095 3096 // C++0x [dcl.constexpr]p9: 3097 // A constexpr specifier used in an object declaration declares the object 3098 // as const. 3099 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) { 3100 T.addConst(); 3101 } 3102 3103 // If there was an ellipsis in the declarator, the declaration declares a 3104 // parameter pack whose type may be a pack expansion type. 3105 if (D.hasEllipsis() && !T.isNull()) { 3106 // C++0x [dcl.fct]p13: 3107 // A declarator-id or abstract-declarator containing an ellipsis shall 3108 // only be used in a parameter-declaration. Such a parameter-declaration 3109 // is a parameter pack (14.5.3). [...] 3110 switch (D.getContext()) { 3111 case Declarator::PrototypeContext: 3112 // C++0x [dcl.fct]p13: 3113 // [...] When it is part of a parameter-declaration-clause, the 3114 // parameter pack is a function parameter pack (14.5.3). The type T 3115 // of the declarator-id of the function parameter pack shall contain 3116 // a template parameter pack; each template parameter pack in T is 3117 // expanded by the function parameter pack. 3118 // 3119 // We represent function parameter packs as function parameters whose 3120 // type is a pack expansion. 3121 if (!T->containsUnexpandedParameterPack()) { 3122 S.Diag(D.getEllipsisLoc(), 3123 diag::err_function_parameter_pack_without_parameter_packs) 3124 << T << D.getSourceRange(); 3125 D.setEllipsisLoc(SourceLocation()); 3126 } else { 3127 T = Context.getPackExpansionType(T, None); 3128 } 3129 break; 3130 3131 case Declarator::TemplateParamContext: 3132 // C++0x [temp.param]p15: 3133 // If a template-parameter is a [...] is a parameter-declaration that 3134 // declares a parameter pack (8.3.5), then the template-parameter is a 3135 // template parameter pack (14.5.3). 3136 // 3137 // Note: core issue 778 clarifies that, if there are any unexpanded 3138 // parameter packs in the type of the non-type template parameter, then 3139 // it expands those parameter packs. 3140 if (T->containsUnexpandedParameterPack()) 3141 T = Context.getPackExpansionType(T, None); 3142 else 3143 S.Diag(D.getEllipsisLoc(), 3144 LangOpts.CPlusPlus11 3145 ? diag::warn_cxx98_compat_variadic_templates 3146 : diag::ext_variadic_templates); 3147 break; 3148 3149 case Declarator::FileContext: 3150 case Declarator::KNRTypeListContext: 3151 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here? 3152 case Declarator::ObjCResultContext: // FIXME: special diagnostic here? 3153 case Declarator::TypeNameContext: 3154 case Declarator::CXXNewContext: 3155 case Declarator::AliasDeclContext: 3156 case Declarator::AliasTemplateContext: 3157 case Declarator::MemberContext: 3158 case Declarator::BlockContext: 3159 case Declarator::ForContext: 3160 case Declarator::ConditionContext: 3161 case Declarator::CXXCatchContext: 3162 case Declarator::ObjCCatchContext: 3163 case Declarator::BlockLiteralContext: 3164 case Declarator::LambdaExprContext: 3165 case Declarator::ConversionIdContext: 3166 case Declarator::TrailingReturnContext: 3167 case Declarator::TemplateTypeArgContext: 3168 // FIXME: We may want to allow parameter packs in block-literal contexts 3169 // in the future. 3170 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter); 3171 D.setEllipsisLoc(SourceLocation()); 3172 break; 3173 } 3174 } 3175 3176 if (T.isNull()) 3177 return Context.getNullTypeSourceInfo(); 3178 else if (D.isInvalidType()) 3179 return Context.getTrivialTypeSourceInfo(T); 3180 3181 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo); 3182} 3183 3184/// GetTypeForDeclarator - Convert the type for the specified 3185/// declarator to Type instances. 3186/// 3187/// The result of this call will never be null, but the associated 3188/// type may be a null type if there's an unrecoverable error. 3189TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { 3190 // Determine the type of the declarator. Not all forms of declarator 3191 // have a type. 3192 3193 TypeProcessingState state(*this, D); 3194 3195 TypeSourceInfo *ReturnTypeInfo = 0; 3196 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 3197 if (T.isNull()) 3198 return Context.getNullTypeSourceInfo(); 3199 3200 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) 3201 inferARCWriteback(state, T); 3202 3203 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); 3204} 3205 3206static void transferARCOwnershipToDeclSpec(Sema &S, 3207 QualType &declSpecTy, 3208 Qualifiers::ObjCLifetime ownership) { 3209 if (declSpecTy->isObjCRetainableType() && 3210 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { 3211 Qualifiers qs; 3212 qs.addObjCLifetime(ownership); 3213 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); 3214 } 3215} 3216 3217static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 3218 Qualifiers::ObjCLifetime ownership, 3219 unsigned chunkIndex) { 3220 Sema &S = state.getSema(); 3221 Declarator &D = state.getDeclarator(); 3222 3223 // Look for an explicit lifetime attribute. 3224 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); 3225 for (const AttributeList *attr = chunk.getAttrs(); attr; 3226 attr = attr->getNext()) 3227 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 3228 return; 3229 3230 const char *attrStr = 0; 3231 switch (ownership) { 3232 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); 3233 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; 3234 case Qualifiers::OCL_Strong: attrStr = "strong"; break; 3235 case Qualifiers::OCL_Weak: attrStr = "weak"; break; 3236 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; 3237 } 3238 3239 // If there wasn't one, add one (with an invalid source location 3240 // so that we don't make an AttributedType for it). 3241 AttributeList *attr = D.getAttributePool() 3242 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(), 3243 /*scope*/ 0, SourceLocation(), 3244 &S.Context.Idents.get(attrStr), SourceLocation(), 3245 /*args*/ 0, 0, AttributeList::AS_GNU); 3246 spliceAttrIntoList(*attr, chunk.getAttrListRef()); 3247 3248 // TODO: mark whether we did this inference? 3249} 3250 3251/// \brief Used for transferring ownership in casts resulting in l-values. 3252static void transferARCOwnership(TypeProcessingState &state, 3253 QualType &declSpecTy, 3254 Qualifiers::ObjCLifetime ownership) { 3255 Sema &S = state.getSema(); 3256 Declarator &D = state.getDeclarator(); 3257 3258 int inner = -1; 3259 bool hasIndirection = false; 3260 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 3261 DeclaratorChunk &chunk = D.getTypeObject(i); 3262 switch (chunk.Kind) { 3263 case DeclaratorChunk::Paren: 3264 // Ignore parens. 3265 break; 3266 3267 case DeclaratorChunk::Array: 3268 case DeclaratorChunk::Reference: 3269 case DeclaratorChunk::Pointer: 3270 if (inner != -1) 3271 hasIndirection = true; 3272 inner = i; 3273 break; 3274 3275 case DeclaratorChunk::BlockPointer: 3276 if (inner != -1) 3277 transferARCOwnershipToDeclaratorChunk(state, ownership, i); 3278 return; 3279 3280 case DeclaratorChunk::Function: 3281 case DeclaratorChunk::MemberPointer: 3282 return; 3283 } 3284 } 3285 3286 if (inner == -1) 3287 return; 3288 3289 DeclaratorChunk &chunk = D.getTypeObject(inner); 3290 if (chunk.Kind == DeclaratorChunk::Pointer) { 3291 if (declSpecTy->isObjCRetainableType()) 3292 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 3293 if (declSpecTy->isObjCObjectType() && hasIndirection) 3294 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); 3295 } else { 3296 assert(chunk.Kind == DeclaratorChunk::Array || 3297 chunk.Kind == DeclaratorChunk::Reference); 3298 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 3299 } 3300} 3301 3302TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { 3303 TypeProcessingState state(*this, D); 3304 3305 TypeSourceInfo *ReturnTypeInfo = 0; 3306 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 3307 if (declSpecTy.isNull()) 3308 return Context.getNullTypeSourceInfo(); 3309 3310 if (getLangOpts().ObjCAutoRefCount) { 3311 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); 3312 if (ownership != Qualifiers::OCL_None) 3313 transferARCOwnership(state, declSpecTy, ownership); 3314 } 3315 3316 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); 3317} 3318 3319/// Map an AttributedType::Kind to an AttributeList::Kind. 3320static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) { 3321 switch (kind) { 3322 case AttributedType::attr_address_space: 3323 return AttributeList::AT_AddressSpace; 3324 case AttributedType::attr_regparm: 3325 return AttributeList::AT_Regparm; 3326 case AttributedType::attr_vector_size: 3327 return AttributeList::AT_VectorSize; 3328 case AttributedType::attr_neon_vector_type: 3329 return AttributeList::AT_NeonVectorType; 3330 case AttributedType::attr_neon_polyvector_type: 3331 return AttributeList::AT_NeonPolyVectorType; 3332 case AttributedType::attr_objc_gc: 3333 return AttributeList::AT_ObjCGC; 3334 case AttributedType::attr_objc_ownership: 3335 return AttributeList::AT_ObjCOwnership; 3336 case AttributedType::attr_noreturn: 3337 return AttributeList::AT_NoReturn; 3338 case AttributedType::attr_cdecl: 3339 return AttributeList::AT_CDecl; 3340 case AttributedType::attr_fastcall: 3341 return AttributeList::AT_FastCall; 3342 case AttributedType::attr_stdcall: 3343 return AttributeList::AT_StdCall; 3344 case AttributedType::attr_thiscall: 3345 return AttributeList::AT_ThisCall; 3346 case AttributedType::attr_pascal: 3347 return AttributeList::AT_Pascal; 3348 case AttributedType::attr_pcs: 3349 case AttributedType::attr_pcs_vfp: 3350 return AttributeList::AT_Pcs; 3351 case AttributedType::attr_pnaclcall: 3352 return AttributeList::AT_PnaclCall; 3353 case AttributedType::attr_inteloclbicc: 3354 return AttributeList::AT_IntelOclBicc; 3355 case AttributedType::attr_ptr32: 3356 return AttributeList::AT_Ptr32; 3357 case AttributedType::attr_ptr64: 3358 return AttributeList::AT_Ptr64; 3359 case AttributedType::attr_sptr: 3360 return AttributeList::AT_SPtr; 3361 case AttributedType::attr_uptr: 3362 return AttributeList::AT_UPtr; 3363 } 3364 llvm_unreachable("unexpected attribute kind!"); 3365} 3366 3367static void fillAttributedTypeLoc(AttributedTypeLoc TL, 3368 const AttributeList *attrs) { 3369 AttributedType::Kind kind = TL.getAttrKind(); 3370 3371 assert(attrs && "no type attributes in the expected location!"); 3372 AttributeList::Kind parsedKind = getAttrListKind(kind); 3373 while (attrs->getKind() != parsedKind) { 3374 attrs = attrs->getNext(); 3375 assert(attrs && "no matching attribute in expected location!"); 3376 } 3377 3378 TL.setAttrNameLoc(attrs->getLoc()); 3379 if (TL.hasAttrExprOperand()) 3380 TL.setAttrExprOperand(attrs->getArg(0)); 3381 else if (TL.hasAttrEnumOperand()) 3382 TL.setAttrEnumOperandLoc(attrs->getParameterLoc()); 3383 3384 // FIXME: preserve this information to here. 3385 if (TL.hasAttrOperand()) 3386 TL.setAttrOperandParensRange(SourceRange()); 3387} 3388 3389namespace { 3390 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 3391 ASTContext &Context; 3392 const DeclSpec &DS; 3393 3394 public: 3395 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS) 3396 : Context(Context), DS(DS) {} 3397 3398 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 3399 fillAttributedTypeLoc(TL, DS.getAttributes().getList()); 3400 Visit(TL.getModifiedLoc()); 3401 } 3402 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 3403 Visit(TL.getUnqualifiedLoc()); 3404 } 3405 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 3406 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 3407 } 3408 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 3409 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 3410 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires 3411 // addition field. What we have is good enough for dispay of location 3412 // of 'fixit' on interface name. 3413 TL.setNameEndLoc(DS.getLocEnd()); 3414 } 3415 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 3416 // Handle the base type, which might not have been written explicitly. 3417 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) { 3418 TL.setHasBaseTypeAsWritten(false); 3419 TL.getBaseLoc().initialize(Context, SourceLocation()); 3420 } else { 3421 TL.setHasBaseTypeAsWritten(true); 3422 Visit(TL.getBaseLoc()); 3423 } 3424 3425 // Protocol qualifiers. 3426 if (DS.getProtocolQualifiers()) { 3427 assert(TL.getNumProtocols() > 0); 3428 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers()); 3429 TL.setLAngleLoc(DS.getProtocolLAngleLoc()); 3430 TL.setRAngleLoc(DS.getSourceRange().getEnd()); 3431 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i) 3432 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]); 3433 } else { 3434 assert(TL.getNumProtocols() == 0); 3435 TL.setLAngleLoc(SourceLocation()); 3436 TL.setRAngleLoc(SourceLocation()); 3437 } 3438 } 3439 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 3440 TL.setStarLoc(SourceLocation()); 3441 Visit(TL.getPointeeLoc()); 3442 } 3443 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 3444 TypeSourceInfo *TInfo = 0; 3445 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3446 3447 // If we got no declarator info from previous Sema routines, 3448 // just fill with the typespec loc. 3449 if (!TInfo) { 3450 TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); 3451 return; 3452 } 3453 3454 TypeLoc OldTL = TInfo->getTypeLoc(); 3455 if (TInfo->getType()->getAs<ElaboratedType>()) { 3456 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); 3457 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() 3458 .castAs<TemplateSpecializationTypeLoc>(); 3459 TL.copy(NamedTL); 3460 } else { 3461 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); 3462 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()); 3463 } 3464 3465 } 3466 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 3467 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 3468 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 3469 TL.setParensRange(DS.getTypeofParensRange()); 3470 } 3471 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 3472 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 3473 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 3474 TL.setParensRange(DS.getTypeofParensRange()); 3475 assert(DS.getRepAsType()); 3476 TypeSourceInfo *TInfo = 0; 3477 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3478 TL.setUnderlyingTInfo(TInfo); 3479 } 3480 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 3481 // FIXME: This holds only because we only have one unary transform. 3482 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType); 3483 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 3484 TL.setParensRange(DS.getTypeofParensRange()); 3485 assert(DS.getRepAsType()); 3486 TypeSourceInfo *TInfo = 0; 3487 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3488 TL.setUnderlyingTInfo(TInfo); 3489 } 3490 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 3491 // By default, use the source location of the type specifier. 3492 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 3493 if (TL.needsExtraLocalData()) { 3494 // Set info for the written builtin specifiers. 3495 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 3496 // Try to have a meaningful source location. 3497 if (TL.getWrittenSignSpec() != TSS_unspecified) 3498 // Sign spec loc overrides the others (e.g., 'unsigned long'). 3499 TL.setBuiltinLoc(DS.getTypeSpecSignLoc()); 3500 else if (TL.getWrittenWidthSpec() != TSW_unspecified) 3501 // Width spec loc overrides type spec loc (e.g., 'short int'). 3502 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc()); 3503 } 3504 } 3505 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 3506 ElaboratedTypeKeyword Keyword 3507 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 3508 if (DS.getTypeSpecType() == TST_typename) { 3509 TypeSourceInfo *TInfo = 0; 3510 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3511 if (TInfo) { 3512 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); 3513 return; 3514 } 3515 } 3516 TL.setElaboratedKeywordLoc(Keyword != ETK_None 3517 ? DS.getTypeSpecTypeLoc() 3518 : SourceLocation()); 3519 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 3520 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3521 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 3522 } 3523 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 3524 assert(DS.getTypeSpecType() == TST_typename); 3525 TypeSourceInfo *TInfo = 0; 3526 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3527 assert(TInfo); 3528 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); 3529 } 3530 void VisitDependentTemplateSpecializationTypeLoc( 3531 DependentTemplateSpecializationTypeLoc TL) { 3532 assert(DS.getTypeSpecType() == TST_typename); 3533 TypeSourceInfo *TInfo = 0; 3534 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3535 assert(TInfo); 3536 TL.copy( 3537 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); 3538 } 3539 void VisitTagTypeLoc(TagTypeLoc TL) { 3540 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 3541 } 3542 void VisitAtomicTypeLoc(AtomicTypeLoc TL) { 3543 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier 3544 // or an _Atomic qualifier. 3545 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { 3546 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 3547 TL.setParensRange(DS.getTypeofParensRange()); 3548 3549 TypeSourceInfo *TInfo = 0; 3550 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3551 assert(TInfo); 3552 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 3553 } else { 3554 TL.setKWLoc(DS.getAtomicSpecLoc()); 3555 // No parens, to indicate this was spelled as an _Atomic qualifier. 3556 TL.setParensRange(SourceRange()); 3557 Visit(TL.getValueLoc()); 3558 } 3559 } 3560 3561 void VisitTypeLoc(TypeLoc TL) { 3562 // FIXME: add other typespec types and change this to an assert. 3563 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 3564 } 3565 }; 3566 3567 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 3568 ASTContext &Context; 3569 const DeclaratorChunk &Chunk; 3570 3571 public: 3572 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk) 3573 : Context(Context), Chunk(Chunk) {} 3574 3575 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 3576 llvm_unreachable("qualified type locs not expected here!"); 3577 } 3578 void VisitDecayedTypeLoc(DecayedTypeLoc TL) { 3579 llvm_unreachable("decayed type locs not expected here!"); 3580 } 3581 3582 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 3583 fillAttributedTypeLoc(TL, Chunk.getAttrs()); 3584 } 3585 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 3586 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 3587 TL.setCaretLoc(Chunk.Loc); 3588 } 3589 void VisitPointerTypeLoc(PointerTypeLoc TL) { 3590 assert(Chunk.Kind == DeclaratorChunk::Pointer); 3591 TL.setStarLoc(Chunk.Loc); 3592 } 3593 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 3594 assert(Chunk.Kind == DeclaratorChunk::Pointer); 3595 TL.setStarLoc(Chunk.Loc); 3596 } 3597 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 3598 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 3599 const CXXScopeSpec& SS = Chunk.Mem.Scope(); 3600 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); 3601 3602 const Type* ClsTy = TL.getClass(); 3603 QualType ClsQT = QualType(ClsTy, 0); 3604 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); 3605 // Now copy source location info into the type loc component. 3606 TypeLoc ClsTL = ClsTInfo->getTypeLoc(); 3607 switch (NNSLoc.getNestedNameSpecifier()->getKind()) { 3608 case NestedNameSpecifier::Identifier: 3609 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); 3610 { 3611 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); 3612 DNTLoc.setElaboratedKeywordLoc(SourceLocation()); 3613 DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); 3614 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); 3615 } 3616 break; 3617 3618 case NestedNameSpecifier::TypeSpec: 3619 case NestedNameSpecifier::TypeSpecWithTemplate: 3620 if (isa<ElaboratedType>(ClsTy)) { 3621 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); 3622 ETLoc.setElaboratedKeywordLoc(SourceLocation()); 3623 ETLoc.setQualifierLoc(NNSLoc.getPrefix()); 3624 TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); 3625 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); 3626 } else { 3627 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); 3628 } 3629 break; 3630 3631 case NestedNameSpecifier::Namespace: 3632 case NestedNameSpecifier::NamespaceAlias: 3633 case NestedNameSpecifier::Global: 3634 llvm_unreachable("Nested-name-specifier must name a type"); 3635 } 3636 3637 // Finally fill in MemberPointerLocInfo fields. 3638 TL.setStarLoc(Chunk.Loc); 3639 TL.setClassTInfo(ClsTInfo); 3640 } 3641 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 3642 assert(Chunk.Kind == DeclaratorChunk::Reference); 3643 // 'Amp' is misleading: this might have been originally 3644 /// spelled with AmpAmp. 3645 TL.setAmpLoc(Chunk.Loc); 3646 } 3647 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 3648 assert(Chunk.Kind == DeclaratorChunk::Reference); 3649 assert(!Chunk.Ref.LValueRef); 3650 TL.setAmpAmpLoc(Chunk.Loc); 3651 } 3652 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 3653 assert(Chunk.Kind == DeclaratorChunk::Array); 3654 TL.setLBracketLoc(Chunk.Loc); 3655 TL.setRBracketLoc(Chunk.EndLoc); 3656 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 3657 } 3658 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 3659 assert(Chunk.Kind == DeclaratorChunk::Function); 3660 TL.setLocalRangeBegin(Chunk.Loc); 3661 TL.setLocalRangeEnd(Chunk.EndLoc); 3662 3663 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 3664 TL.setLParenLoc(FTI.getLParenLoc()); 3665 TL.setRParenLoc(FTI.getRParenLoc()); 3666 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) { 3667 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 3668 TL.setArg(tpi++, Param); 3669 } 3670 // FIXME: exception specs 3671 } 3672 void VisitParenTypeLoc(ParenTypeLoc TL) { 3673 assert(Chunk.Kind == DeclaratorChunk::Paren); 3674 TL.setLParenLoc(Chunk.Loc); 3675 TL.setRParenLoc(Chunk.EndLoc); 3676 } 3677 3678 void VisitTypeLoc(TypeLoc TL) { 3679 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 3680 } 3681 }; 3682} 3683 3684static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { 3685 SourceLocation Loc; 3686 switch (Chunk.Kind) { 3687 case DeclaratorChunk::Function: 3688 case DeclaratorChunk::Array: 3689 case DeclaratorChunk::Paren: 3690 llvm_unreachable("cannot be _Atomic qualified"); 3691 3692 case DeclaratorChunk::Pointer: 3693 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc); 3694 break; 3695 3696 case DeclaratorChunk::BlockPointer: 3697 case DeclaratorChunk::Reference: 3698 case DeclaratorChunk::MemberPointer: 3699 // FIXME: Provide a source location for the _Atomic keyword. 3700 break; 3701 } 3702 3703 ATL.setKWLoc(Loc); 3704 ATL.setParensRange(SourceRange()); 3705} 3706 3707/// \brief Create and instantiate a TypeSourceInfo with type source information. 3708/// 3709/// \param T QualType referring to the type as written in source code. 3710/// 3711/// \param ReturnTypeInfo For declarators whose return type does not show 3712/// up in the normal place in the declaration specifiers (such as a C++ 3713/// conversion function), this pointer will refer to a type source information 3714/// for that return type. 3715TypeSourceInfo * 3716Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 3717 TypeSourceInfo *ReturnTypeInfo) { 3718 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T); 3719 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 3720 3721 // Handle parameter packs whose type is a pack expansion. 3722 if (isa<PackExpansionType>(T)) { 3723 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); 3724 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 3725 } 3726 3727 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 3728 // An AtomicTypeLoc might be produced by an atomic qualifier in this 3729 // declarator chunk. 3730 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { 3731 fillAtomicQualLoc(ATL, D.getTypeObject(i)); 3732 CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); 3733 } 3734 3735 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { 3736 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs()); 3737 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 3738 } 3739 3740 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL); 3741 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 3742 } 3743 3744 // If we have different source information for the return type, use 3745 // that. This really only applies to C++ conversion functions. 3746 if (ReturnTypeInfo) { 3747 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 3748 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 3749 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 3750 } else { 3751 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL); 3752 } 3753 3754 return TInfo; 3755} 3756 3757/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo. 3758ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { 3759 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 3760 // and Sema during declaration parsing. Try deallocating/caching them when 3761 // it's appropriate, instead of allocating them and keeping them around. 3762 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 3763 TypeAlignment); 3764 new (LocT) LocInfoType(T, TInfo); 3765 assert(LocT->getTypeClass() != T->getTypeClass() && 3766 "LocInfoType's TypeClass conflicts with an existing Type class"); 3767 return ParsedType::make(QualType(LocT, 0)); 3768} 3769 3770void LocInfoType::getAsStringInternal(std::string &Str, 3771 const PrintingPolicy &Policy) const { 3772 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" 3773 " was used directly instead of getting the QualType through" 3774 " GetTypeFromParser"); 3775} 3776 3777TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 3778 // C99 6.7.6: Type names have no identifier. This is already validated by 3779 // the parser. 3780 assert(D.getIdentifier() == 0 && "Type name should have no identifier!"); 3781 3782 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 3783 QualType T = TInfo->getType(); 3784 if (D.isInvalidType()) 3785 return true; 3786 3787 // Make sure there are no unused decl attributes on the declarator. 3788 // We don't want to do this for ObjC parameters because we're going 3789 // to apply them to the actual parameter declaration. 3790 // Likewise, we don't want to do this for alias declarations, because 3791 // we are actually going to build a declaration from this eventually. 3792 if (D.getContext() != Declarator::ObjCParameterContext && 3793 D.getContext() != Declarator::AliasDeclContext && 3794 D.getContext() != Declarator::AliasTemplateContext) 3795 checkUnusedDeclAttributes(D); 3796 3797 if (getLangOpts().CPlusPlus) { 3798 // Check that there are no default arguments (C++ only). 3799 CheckExtraCXXDefaultArguments(D); 3800 } 3801 3802 return CreateParsedType(T, TInfo); 3803} 3804 3805ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { 3806 QualType T = Context.getObjCInstanceType(); 3807 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 3808 return CreateParsedType(T, TInfo); 3809} 3810 3811 3812//===----------------------------------------------------------------------===// 3813// Type Attribute Processing 3814//===----------------------------------------------------------------------===// 3815 3816/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 3817/// specified type. The attribute contains 1 argument, the id of the address 3818/// space for the type. 3819static void HandleAddressSpaceTypeAttribute(QualType &Type, 3820 const AttributeList &Attr, Sema &S){ 3821 3822 // If this type is already address space qualified, reject it. 3823 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by 3824 // qualifiers for two or more different address spaces." 3825 if (Type.getAddressSpace()) { 3826 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 3827 Attr.setInvalid(); 3828 return; 3829 } 3830 3831 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be 3832 // qualified by an address-space qualifier." 3833 if (Type->isFunctionType()) { 3834 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); 3835 Attr.setInvalid(); 3836 return; 3837 } 3838 3839 // Check the attribute arguments. 3840 if (Attr.getNumArgs() != 1) { 3841 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 3842 << Attr.getName() << 1; 3843 Attr.setInvalid(); 3844 return; 3845 } 3846 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0)); 3847 llvm::APSInt addrSpace(32); 3848 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() || 3849 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 3850 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 3851 << Attr.getName()->getName() << ASArgExpr->getSourceRange(); 3852 Attr.setInvalid(); 3853 return; 3854 } 3855 3856 // Bounds checking. 3857 if (addrSpace.isSigned()) { 3858 if (addrSpace.isNegative()) { 3859 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative) 3860 << ASArgExpr->getSourceRange(); 3861 Attr.setInvalid(); 3862 return; 3863 } 3864 addrSpace.setIsSigned(false); 3865 } 3866 llvm::APSInt max(addrSpace.getBitWidth()); 3867 max = Qualifiers::MaxAddressSpace; 3868 if (addrSpace > max) { 3869 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high) 3870 << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange(); 3871 Attr.setInvalid(); 3872 return; 3873 } 3874 3875 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 3876 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 3877} 3878 3879/// Does this type have a "direct" ownership qualifier? That is, 3880/// is it written like "__strong id", as opposed to something like 3881/// "typeof(foo)", where that happens to be strong? 3882static bool hasDirectOwnershipQualifier(QualType type) { 3883 // Fast path: no qualifier at all. 3884 assert(type.getQualifiers().hasObjCLifetime()); 3885 3886 while (true) { 3887 // __strong id 3888 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) { 3889 if (attr->getAttrKind() == AttributedType::attr_objc_ownership) 3890 return true; 3891 3892 type = attr->getModifiedType(); 3893 3894 // X *__strong (...) 3895 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) { 3896 type = paren->getInnerType(); 3897 3898 // That's it for things we want to complain about. In particular, 3899 // we do not want to look through typedefs, typeof(expr), 3900 // typeof(type), or any other way that the type is somehow 3901 // abstracted. 3902 } else { 3903 3904 return false; 3905 } 3906 } 3907} 3908 3909/// handleObjCOwnershipTypeAttr - Process an objc_ownership 3910/// attribute on the specified type. 3911/// 3912/// Returns 'true' if the attribute was handled. 3913static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 3914 AttributeList &attr, 3915 QualType &type) { 3916 bool NonObjCPointer = false; 3917 3918 if (!type->isDependentType() && !type->isUndeducedType()) { 3919 if (const PointerType *ptr = type->getAs<PointerType>()) { 3920 QualType pointee = ptr->getPointeeType(); 3921 if (pointee->isObjCRetainableType() || pointee->isPointerType()) 3922 return false; 3923 // It is important not to lose the source info that there was an attribute 3924 // applied to non-objc pointer. We will create an attributed type but 3925 // its type will be the same as the original type. 3926 NonObjCPointer = true; 3927 } else if (!type->isObjCRetainableType()) { 3928 return false; 3929 } 3930 3931 // Don't accept an ownership attribute in the declspec if it would 3932 // just be the return type of a block pointer. 3933 if (state.isProcessingDeclSpec()) { 3934 Declarator &D = state.getDeclarator(); 3935 if (maybeMovePastReturnType(D, D.getNumTypeObjects())) 3936 return false; 3937 } 3938 } 3939 3940 Sema &S = state.getSema(); 3941 SourceLocation AttrLoc = attr.getLoc(); 3942 if (AttrLoc.isMacroID()) 3943 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first; 3944 3945 if (!attr.getParameterName()) { 3946 S.Diag(AttrLoc, diag::err_attribute_argument_n_type) 3947 << attr.getName() << 1 << 2 /*string*/; 3948 attr.setInvalid(); 3949 return true; 3950 } 3951 3952 // Consume lifetime attributes without further comment outside of 3953 // ARC mode. 3954 if (!S.getLangOpts().ObjCAutoRefCount) 3955 return true; 3956 3957 Qualifiers::ObjCLifetime lifetime; 3958 if (attr.getParameterName()->isStr("none")) 3959 lifetime = Qualifiers::OCL_ExplicitNone; 3960 else if (attr.getParameterName()->isStr("strong")) 3961 lifetime = Qualifiers::OCL_Strong; 3962 else if (attr.getParameterName()->isStr("weak")) 3963 lifetime = Qualifiers::OCL_Weak; 3964 else if (attr.getParameterName()->isStr("autoreleasing")) 3965 lifetime = Qualifiers::OCL_Autoreleasing; 3966 else { 3967 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) 3968 << "objc_ownership" << attr.getParameterName(); 3969 attr.setInvalid(); 3970 return true; 3971 } 3972 3973 SplitQualType underlyingType = type.split(); 3974 3975 // Check for redundant/conflicting ownership qualifiers. 3976 if (Qualifiers::ObjCLifetime previousLifetime 3977 = type.getQualifiers().getObjCLifetime()) { 3978 // If it's written directly, that's an error. 3979 if (hasDirectOwnershipQualifier(type)) { 3980 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) 3981 << type; 3982 return true; 3983 } 3984 3985 // Otherwise, if the qualifiers actually conflict, pull sugar off 3986 // until we reach a type that is directly qualified. 3987 if (previousLifetime != lifetime) { 3988 // This should always terminate: the canonical type is 3989 // qualified, so some bit of sugar must be hiding it. 3990 while (!underlyingType.Quals.hasObjCLifetime()) { 3991 underlyingType = underlyingType.getSingleStepDesugaredType(); 3992 } 3993 underlyingType.Quals.removeObjCLifetime(); 3994 } 3995 } 3996 3997 underlyingType.Quals.addObjCLifetime(lifetime); 3998 3999 if (NonObjCPointer) { 4000 StringRef name = attr.getName()->getName(); 4001 switch (lifetime) { 4002 case Qualifiers::OCL_None: 4003 case Qualifiers::OCL_ExplicitNone: 4004 break; 4005 case Qualifiers::OCL_Strong: name = "__strong"; break; 4006 case Qualifiers::OCL_Weak: name = "__weak"; break; 4007 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; 4008 } 4009 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name 4010 << TDS_ObjCObjOrBlock << type; 4011 } 4012 4013 QualType origType = type; 4014 if (!NonObjCPointer) 4015 type = S.Context.getQualifiedType(underlyingType); 4016 4017 // If we have a valid source location for the attribute, use an 4018 // AttributedType instead. 4019 if (AttrLoc.isValid()) 4020 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership, 4021 origType, type); 4022 4023 // Forbid __weak if the runtime doesn't support it. 4024 if (lifetime == Qualifiers::OCL_Weak && 4025 !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) { 4026 4027 // Actually, delay this until we know what we're parsing. 4028 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 4029 S.DelayedDiagnostics.add( 4030 sema::DelayedDiagnostic::makeForbiddenType( 4031 S.getSourceManager().getExpansionLoc(AttrLoc), 4032 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0)); 4033 } else { 4034 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime); 4035 } 4036 4037 attr.setInvalid(); 4038 return true; 4039 } 4040 4041 // Forbid __weak for class objects marked as 4042 // objc_arc_weak_reference_unavailable 4043 if (lifetime == Qualifiers::OCL_Weak) { 4044 if (const ObjCObjectPointerType *ObjT = 4045 type->getAs<ObjCObjectPointerType>()) { 4046 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { 4047 if (Class->isArcWeakrefUnavailable()) { 4048 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); 4049 S.Diag(ObjT->getInterfaceDecl()->getLocation(), 4050 diag::note_class_declared); 4051 } 4052 } 4053 } 4054 } 4055 4056 return true; 4057} 4058 4059/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type 4060/// attribute on the specified type. Returns true to indicate that 4061/// the attribute was handled, false to indicate that the type does 4062/// not permit the attribute. 4063static bool handleObjCGCTypeAttr(TypeProcessingState &state, 4064 AttributeList &attr, 4065 QualType &type) { 4066 Sema &S = state.getSema(); 4067 4068 // Delay if this isn't some kind of pointer. 4069 if (!type->isPointerType() && 4070 !type->isObjCObjectPointerType() && 4071 !type->isBlockPointerType()) 4072 return false; 4073 4074 if (type.getObjCGCAttr() != Qualifiers::GCNone) { 4075 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); 4076 attr.setInvalid(); 4077 return true; 4078 } 4079 4080 // Check the attribute arguments. 4081 if (!attr.getParameterName()) { 4082 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_type) 4083 << attr.getName() << 1 << 2 /*string*/; 4084 attr.setInvalid(); 4085 return true; 4086 } 4087 Qualifiers::GC GCAttr; 4088 if (attr.getNumArgs() != 0) { 4089 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) 4090 << attr.getName() << 1; 4091 attr.setInvalid(); 4092 return true; 4093 } 4094 if (attr.getParameterName()->isStr("weak")) 4095 GCAttr = Qualifiers::Weak; 4096 else if (attr.getParameterName()->isStr("strong")) 4097 GCAttr = Qualifiers::Strong; 4098 else { 4099 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) 4100 << "objc_gc" << attr.getParameterName(); 4101 attr.setInvalid(); 4102 return true; 4103 } 4104 4105 QualType origType = type; 4106 type = S.Context.getObjCGCQualType(origType, GCAttr); 4107 4108 // Make an attributed type to preserve the source information. 4109 if (attr.getLoc().isValid()) 4110 type = S.Context.getAttributedType(AttributedType::attr_objc_gc, 4111 origType, type); 4112 4113 return true; 4114} 4115 4116namespace { 4117 /// A helper class to unwrap a type down to a function for the 4118 /// purposes of applying attributes there. 4119 /// 4120 /// Use: 4121 /// FunctionTypeUnwrapper unwrapped(SemaRef, T); 4122 /// if (unwrapped.isFunctionType()) { 4123 /// const FunctionType *fn = unwrapped.get(); 4124 /// // change fn somehow 4125 /// T = unwrapped.wrap(fn); 4126 /// } 4127 struct FunctionTypeUnwrapper { 4128 enum WrapKind { 4129 Desugar, 4130 Parens, 4131 Pointer, 4132 BlockPointer, 4133 Reference, 4134 MemberPointer 4135 }; 4136 4137 QualType Original; 4138 const FunctionType *Fn; 4139 SmallVector<unsigned char /*WrapKind*/, 8> Stack; 4140 4141 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { 4142 while (true) { 4143 const Type *Ty = T.getTypePtr(); 4144 if (isa<FunctionType>(Ty)) { 4145 Fn = cast<FunctionType>(Ty); 4146 return; 4147 } else if (isa<ParenType>(Ty)) { 4148 T = cast<ParenType>(Ty)->getInnerType(); 4149 Stack.push_back(Parens); 4150 } else if (isa<PointerType>(Ty)) { 4151 T = cast<PointerType>(Ty)->getPointeeType(); 4152 Stack.push_back(Pointer); 4153 } else if (isa<BlockPointerType>(Ty)) { 4154 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4155 Stack.push_back(BlockPointer); 4156 } else if (isa<MemberPointerType>(Ty)) { 4157 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4158 Stack.push_back(MemberPointer); 4159 } else if (isa<ReferenceType>(Ty)) { 4160 T = cast<ReferenceType>(Ty)->getPointeeType(); 4161 Stack.push_back(Reference); 4162 } else { 4163 const Type *DTy = Ty->getUnqualifiedDesugaredType(); 4164 if (Ty == DTy) { 4165 Fn = 0; 4166 return; 4167 } 4168 4169 T = QualType(DTy, 0); 4170 Stack.push_back(Desugar); 4171 } 4172 } 4173 } 4174 4175 bool isFunctionType() const { return (Fn != 0); } 4176 const FunctionType *get() const { return Fn; } 4177 4178 QualType wrap(Sema &S, const FunctionType *New) { 4179 // If T wasn't modified from the unwrapped type, do nothing. 4180 if (New == get()) return Original; 4181 4182 Fn = New; 4183 return wrap(S.Context, Original, 0); 4184 } 4185 4186 private: 4187 QualType wrap(ASTContext &C, QualType Old, unsigned I) { 4188 if (I == Stack.size()) 4189 return C.getQualifiedType(Fn, Old.getQualifiers()); 4190 4191 // Build up the inner type, applying the qualifiers from the old 4192 // type to the new type. 4193 SplitQualType SplitOld = Old.split(); 4194 4195 // As a special case, tail-recurse if there are no qualifiers. 4196 if (SplitOld.Quals.empty()) 4197 return wrap(C, SplitOld.Ty, I); 4198 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); 4199 } 4200 4201 QualType wrap(ASTContext &C, const Type *Old, unsigned I) { 4202 if (I == Stack.size()) return QualType(Fn, 0); 4203 4204 switch (static_cast<WrapKind>(Stack[I++])) { 4205 case Desugar: 4206 // This is the point at which we potentially lose source 4207 // information. 4208 return wrap(C, Old->getUnqualifiedDesugaredType(), I); 4209 4210 case Parens: { 4211 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); 4212 return C.getParenType(New); 4213 } 4214 4215 case Pointer: { 4216 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); 4217 return C.getPointerType(New); 4218 } 4219 4220 case BlockPointer: { 4221 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); 4222 return C.getBlockPointerType(New); 4223 } 4224 4225 case MemberPointer: { 4226 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); 4227 QualType New = wrap(C, OldMPT->getPointeeType(), I); 4228 return C.getMemberPointerType(New, OldMPT->getClass()); 4229 } 4230 4231 case Reference: { 4232 const ReferenceType *OldRef = cast<ReferenceType>(Old); 4233 QualType New = wrap(C, OldRef->getPointeeType(), I); 4234 if (isa<LValueReferenceType>(OldRef)) 4235 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); 4236 else 4237 return C.getRValueReferenceType(New); 4238 } 4239 } 4240 4241 llvm_unreachable("unknown wrapping kind"); 4242 } 4243 }; 4244} 4245 4246static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, 4247 AttributeList &Attr, 4248 QualType &Type) { 4249 Sema &S = State.getSema(); 4250 4251 AttributeList::Kind Kind = Attr.getKind(); 4252 QualType Desugared = Type; 4253 const AttributedType *AT = dyn_cast<AttributedType>(Type); 4254 while (AT) { 4255 AttributedType::Kind CurAttrKind = AT->getAttrKind(); 4256 4257 // You cannot specify duplicate type attributes, so if the attribute has 4258 // already been applied, flag it. 4259 if (getAttrListKind(CurAttrKind) == Kind) { 4260 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact) 4261 << Attr.getName(); 4262 return true; 4263 } 4264 4265 // You cannot have both __sptr and __uptr on the same type, nor can you 4266 // have __ptr32 and __ptr64. 4267 if ((CurAttrKind == AttributedType::attr_ptr32 && 4268 Kind == AttributeList::AT_Ptr64) || 4269 (CurAttrKind == AttributedType::attr_ptr64 && 4270 Kind == AttributeList::AT_Ptr32)) { 4271 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 4272 << "'__ptr32'" << "'__ptr64'"; 4273 return true; 4274 } else if ((CurAttrKind == AttributedType::attr_sptr && 4275 Kind == AttributeList::AT_UPtr) || 4276 (CurAttrKind == AttributedType::attr_uptr && 4277 Kind == AttributeList::AT_SPtr)) { 4278 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 4279 << "'__sptr'" << "'__uptr'"; 4280 return true; 4281 } 4282 4283 Desugared = AT->getEquivalentType(); 4284 AT = dyn_cast<AttributedType>(Desugared); 4285 } 4286 4287 // Pointer type qualifiers can only operate on pointer types, but not 4288 // pointer-to-member types. 4289 if (!isa<PointerType>(Desugared)) { 4290 S.Diag(Attr.getLoc(), Type->isMemberPointerType() ? 4291 diag::err_attribute_no_member_pointers : 4292 diag::err_attribute_pointers_only) << Attr.getName(); 4293 return true; 4294 } 4295 4296 AttributedType::Kind TAK; 4297 switch (Kind) { 4298 default: llvm_unreachable("Unknown attribute kind"); 4299 case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break; 4300 case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break; 4301 case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break; 4302 case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break; 4303 } 4304 4305 Type = S.Context.getAttributedType(TAK, Type, Type); 4306 return false; 4307} 4308 4309static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) { 4310 assert(!Attr.isInvalid()); 4311 switch (Attr.getKind()) { 4312 default: 4313 llvm_unreachable("not a calling convention attribute"); 4314 case AttributeList::AT_CDecl: 4315 return AttributedType::attr_cdecl; 4316 case AttributeList::AT_FastCall: 4317 return AttributedType::attr_fastcall; 4318 case AttributeList::AT_StdCall: 4319 return AttributedType::attr_stdcall; 4320 case AttributeList::AT_ThisCall: 4321 return AttributedType::attr_thiscall; 4322 case AttributeList::AT_Pascal: 4323 return AttributedType::attr_pascal; 4324 case AttributeList::AT_Pcs: { 4325 // We know attr is valid so it can only have one of two strings args. 4326 StringLiteral *Str = cast<StringLiteral>(Attr.getArg(0)); 4327 return llvm::StringSwitch<AttributedType::Kind>(Str->getString()) 4328 .Case("aapcs", AttributedType::attr_pcs) 4329 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp); 4330 } 4331 case AttributeList::AT_PnaclCall: 4332 return AttributedType::attr_pnaclcall; 4333 case AttributeList::AT_IntelOclBicc: 4334 return AttributedType::attr_inteloclbicc; 4335 } 4336 llvm_unreachable("unexpected attribute kind!"); 4337} 4338 4339/// Process an individual function attribute. Returns true to 4340/// indicate that the attribute was handled, false if it wasn't. 4341static bool handleFunctionTypeAttr(TypeProcessingState &state, 4342 AttributeList &attr, 4343 QualType &type) { 4344 Sema &S = state.getSema(); 4345 4346 FunctionTypeUnwrapper unwrapped(S, type); 4347 4348 if (attr.getKind() == AttributeList::AT_NoReturn) { 4349 if (S.CheckNoReturnAttr(attr)) 4350 return true; 4351 4352 // Delay if this is not a function type. 4353 if (!unwrapped.isFunctionType()) 4354 return false; 4355 4356 // Otherwise we can process right away. 4357 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); 4358 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4359 return true; 4360 } 4361 4362 // ns_returns_retained is not always a type attribute, but if we got 4363 // here, we're treating it as one right now. 4364 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) { 4365 assert(S.getLangOpts().ObjCAutoRefCount && 4366 "ns_returns_retained treated as type attribute in non-ARC"); 4367 if (attr.getNumArgs()) return true; 4368 4369 // Delay if this is not a function type. 4370 if (!unwrapped.isFunctionType()) 4371 return false; 4372 4373 FunctionType::ExtInfo EI 4374 = unwrapped.get()->getExtInfo().withProducesResult(true); 4375 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4376 return true; 4377 } 4378 4379 if (attr.getKind() == AttributeList::AT_Regparm) { 4380 unsigned value; 4381 if (S.CheckRegparmAttr(attr, value)) 4382 return true; 4383 4384 // Delay if this is not a function type. 4385 if (!unwrapped.isFunctionType()) 4386 return false; 4387 4388 // Diagnose regparm with fastcall. 4389 const FunctionType *fn = unwrapped.get(); 4390 CallingConv CC = fn->getCallConv(); 4391 if (CC == CC_X86FastCall) { 4392 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 4393 << FunctionType::getNameForCallConv(CC) 4394 << "regparm"; 4395 attr.setInvalid(); 4396 return true; 4397 } 4398 4399 FunctionType::ExtInfo EI = 4400 unwrapped.get()->getExtInfo().withRegParm(value); 4401 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4402 return true; 4403 } 4404 4405 // Delay if the type didn't work out to a function. 4406 if (!unwrapped.isFunctionType()) return false; 4407 4408 // Otherwise, a calling convention. 4409 CallingConv CC; 4410 if (S.CheckCallingConvAttr(attr, CC)) 4411 return true; 4412 4413 const FunctionType *fn = unwrapped.get(); 4414 CallingConv CCOld = fn->getCallConv(); 4415 if (S.Context.getCanonicalCallConv(CC) == 4416 S.Context.getCanonicalCallConv(CCOld)) { 4417 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC); 4418 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4419 return true; 4420 } 4421 4422 if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) { 4423 // Should we diagnose reapplications of the same convention? 4424 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 4425 << FunctionType::getNameForCallConv(CC) 4426 << FunctionType::getNameForCallConv(CCOld); 4427 attr.setInvalid(); 4428 return true; 4429 } 4430 4431 // Diagnose the use of X86 fastcall on varargs or unprototyped functions. 4432 if (CC == CC_X86FastCall) { 4433 if (isa<FunctionNoProtoType>(fn)) { 4434 S.Diag(attr.getLoc(), diag::err_cconv_knr) 4435 << FunctionType::getNameForCallConv(CC); 4436 attr.setInvalid(); 4437 return true; 4438 } 4439 4440 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn); 4441 if (FnP->isVariadic()) { 4442 S.Diag(attr.getLoc(), diag::err_cconv_varargs) 4443 << FunctionType::getNameForCallConv(CC); 4444 attr.setInvalid(); 4445 return true; 4446 } 4447 4448 // Also diagnose fastcall with regparm. 4449 if (fn->getHasRegParm()) { 4450 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 4451 << "regparm" 4452 << FunctionType::getNameForCallConv(CC); 4453 attr.setInvalid(); 4454 return true; 4455 } 4456 } 4457 4458 // Modify the CC from the wrapped function type, wrap it all back, and then 4459 // wrap the whole thing in an AttributedType as written. The modified type 4460 // might have a different CC if we ignored the attribute. 4461 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC); 4462 QualType Equivalent = 4463 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4464 type = S.Context.getAttributedType(getCCTypeAttrKind(attr), type, Equivalent); 4465 return true; 4466} 4467 4468/// Handle OpenCL image access qualifiers: read_only, write_only, read_write 4469static void HandleOpenCLImageAccessAttribute(QualType& CurType, 4470 const AttributeList &Attr, 4471 Sema &S) { 4472 // Check the attribute arguments. 4473 if (Attr.getNumArgs() != 1) { 4474 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 4475 << Attr.getName() << 1; 4476 Attr.setInvalid(); 4477 return; 4478 } 4479 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0)); 4480 llvm::APSInt arg(32); 4481 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 4482 !sizeExpr->isIntegerConstantExpr(arg, S.Context)) { 4483 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 4484 << "opencl_image_access" << sizeExpr->getSourceRange(); 4485 Attr.setInvalid(); 4486 return; 4487 } 4488 unsigned iarg = static_cast<unsigned>(arg.getZExtValue()); 4489 switch (iarg) { 4490 case CLIA_read_only: 4491 case CLIA_write_only: 4492 case CLIA_read_write: 4493 // Implemented in a separate patch 4494 break; 4495 default: 4496 // Implemented in a separate patch 4497 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 4498 << sizeExpr->getSourceRange(); 4499 Attr.setInvalid(); 4500 break; 4501 } 4502} 4503 4504/// HandleVectorSizeAttribute - this attribute is only applicable to integral 4505/// and float scalars, although arrays, pointers, and function return values are 4506/// allowed in conjunction with this construct. Aggregates with this attribute 4507/// are invalid, even if they are of the same size as a corresponding scalar. 4508/// The raw attribute should contain precisely 1 argument, the vector size for 4509/// the variable, measured in bytes. If curType and rawAttr are well formed, 4510/// this routine will return a new vector type. 4511static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, 4512 Sema &S) { 4513 // Check the attribute arguments. 4514 if (Attr.getNumArgs() != 1) { 4515 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 4516 << Attr.getName() << 1; 4517 Attr.setInvalid(); 4518 return; 4519 } 4520 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0)); 4521 llvm::APSInt vecSize(32); 4522 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 4523 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) { 4524 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 4525 << "vector_size" << sizeExpr->getSourceRange(); 4526 Attr.setInvalid(); 4527 return; 4528 } 4529 // the base type must be integer or float, and can't already be a vector. 4530 if (!CurType->isBuiltinType() || 4531 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) { 4532 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 4533 Attr.setInvalid(); 4534 return; 4535 } 4536 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 4537 // vecSize is specified in bytes - convert to bits. 4538 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); 4539 4540 // the vector size needs to be an integral multiple of the type size. 4541 if (vectorSize % typeSize) { 4542 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 4543 << sizeExpr->getSourceRange(); 4544 Attr.setInvalid(); 4545 return; 4546 } 4547 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) { 4548 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large) 4549 << sizeExpr->getSourceRange(); 4550 Attr.setInvalid(); 4551 return; 4552 } 4553 if (vectorSize == 0) { 4554 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size) 4555 << sizeExpr->getSourceRange(); 4556 Attr.setInvalid(); 4557 return; 4558 } 4559 4560 // Success! Instantiate the vector type, the number of elements is > 0, and 4561 // not required to be a power of 2, unlike GCC. 4562 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, 4563 VectorType::GenericVector); 4564} 4565 4566/// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on 4567/// a type. 4568static void HandleExtVectorTypeAttr(QualType &CurType, 4569 const AttributeList &Attr, 4570 Sema &S) { 4571 Expr *sizeExpr; 4572 4573 // Special case where the argument is a template id. 4574 if (Attr.getParameterName()) { 4575 CXXScopeSpec SS; 4576 SourceLocation TemplateKWLoc; 4577 UnqualifiedId id; 4578 id.setIdentifier(Attr.getParameterName(), Attr.getLoc()); 4579 4580 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, 4581 id, false, false); 4582 if (Size.isInvalid()) 4583 return; 4584 4585 sizeExpr = Size.get(); 4586 } else { 4587 // check the attribute arguments. 4588 if (Attr.getNumArgs() != 1) { 4589 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 4590 << Attr.getName() << 1; 4591 return; 4592 } 4593 sizeExpr = Attr.getArg(0); 4594 } 4595 4596 // Create the vector type. 4597 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc()); 4598 if (!T.isNull()) 4599 CurType = T; 4600} 4601 4602/// HandleNeonVectorTypeAttr - The "neon_vector_type" and 4603/// "neon_polyvector_type" attributes are used to create vector types that 4604/// are mangled according to ARM's ABI. Otherwise, these types are identical 4605/// to those created with the "vector_size" attribute. Unlike "vector_size" 4606/// the argument to these Neon attributes is the number of vector elements, 4607/// not the vector size in bytes. The vector width and element type must 4608/// match one of the standard Neon vector types. 4609static void HandleNeonVectorTypeAttr(QualType& CurType, 4610 const AttributeList &Attr, Sema &S, 4611 VectorType::VectorKind VecKind, 4612 const char *AttrName) { 4613 // Check the attribute arguments. 4614 if (Attr.getNumArgs() != 1) { 4615 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 4616 << Attr.getName() << 1; 4617 Attr.setInvalid(); 4618 return; 4619 } 4620 // The number of elements must be an ICE. 4621 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0)); 4622 llvm::APSInt numEltsInt(32); 4623 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() || 4624 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) { 4625 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 4626 << AttrName << numEltsExpr->getSourceRange(); 4627 Attr.setInvalid(); 4628 return; 4629 } 4630 // Only certain element types are supported for Neon vectors. 4631 const BuiltinType* BTy = CurType->getAs<BuiltinType>(); 4632 if (!BTy || 4633 (VecKind == VectorType::NeonPolyVector && 4634 BTy->getKind() != BuiltinType::SChar && 4635 BTy->getKind() != BuiltinType::Short) || 4636 (BTy->getKind() != BuiltinType::SChar && 4637 BTy->getKind() != BuiltinType::UChar && 4638 BTy->getKind() != BuiltinType::Short && 4639 BTy->getKind() != BuiltinType::UShort && 4640 BTy->getKind() != BuiltinType::Int && 4641 BTy->getKind() != BuiltinType::UInt && 4642 BTy->getKind() != BuiltinType::LongLong && 4643 BTy->getKind() != BuiltinType::ULongLong && 4644 BTy->getKind() != BuiltinType::Float)) { 4645 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType; 4646 Attr.setInvalid(); 4647 return; 4648 } 4649 // The total size of the vector must be 64 or 128 bits. 4650 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 4651 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); 4652 unsigned vecSize = typeSize * numElts; 4653 if (vecSize != 64 && vecSize != 128) { 4654 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; 4655 Attr.setInvalid(); 4656 return; 4657 } 4658 4659 CurType = S.Context.getVectorType(CurType, numElts, VecKind); 4660} 4661 4662static void processTypeAttrs(TypeProcessingState &state, QualType &type, 4663 TypeAttrLocation TAL, AttributeList *attrs) { 4664 // Scan through and apply attributes to this type where it makes sense. Some 4665 // attributes (such as __address_space__, __vector_size__, etc) apply to the 4666 // type, but others can be present in the type specifiers even though they 4667 // apply to the decl. Here we apply type attributes and ignore the rest. 4668 4669 AttributeList *next; 4670 do { 4671 AttributeList &attr = *attrs; 4672 next = attr.getNext(); 4673 4674 // Skip attributes that were marked to be invalid. 4675 if (attr.isInvalid()) 4676 continue; 4677 4678 if (attr.isCXX11Attribute()) { 4679 // [[gnu::...]] attributes are treated as declaration attributes, so may 4680 // not appertain to a DeclaratorChunk, even if we handle them as type 4681 // attributes. 4682 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) { 4683 if (TAL == TAL_DeclChunk) { 4684 state.getSema().Diag(attr.getLoc(), 4685 diag::warn_cxx11_gnu_attribute_on_type) 4686 << attr.getName(); 4687 continue; 4688 } 4689 } else if (TAL != TAL_DeclChunk) { 4690 // Otherwise, only consider type processing for a C++11 attribute if 4691 // it's actually been applied to a type. 4692 continue; 4693 } 4694 } 4695 4696 // If this is an attribute we can handle, do so now, 4697 // otherwise, add it to the FnAttrs list for rechaining. 4698 switch (attr.getKind()) { 4699 default: 4700 // A C++11 attribute on a declarator chunk must appertain to a type. 4701 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) { 4702 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) 4703 << attr.getName(); 4704 attr.setUsedAsTypeAttr(); 4705 } 4706 break; 4707 4708 case AttributeList::UnknownAttribute: 4709 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) 4710 state.getSema().Diag(attr.getLoc(), 4711 diag::warn_unknown_attribute_ignored) 4712 << attr.getName(); 4713 break; 4714 4715 case AttributeList::IgnoredAttribute: 4716 break; 4717 4718 case AttributeList::AT_MayAlias: 4719 // FIXME: This attribute needs to actually be handled, but if we ignore 4720 // it it breaks large amounts of Linux software. 4721 attr.setUsedAsTypeAttr(); 4722 break; 4723 case AttributeList::AT_AddressSpace: 4724 HandleAddressSpaceTypeAttribute(type, attr, state.getSema()); 4725 attr.setUsedAsTypeAttr(); 4726 break; 4727 OBJC_POINTER_TYPE_ATTRS_CASELIST: 4728 if (!handleObjCPointerTypeAttr(state, attr, type)) 4729 distributeObjCPointerTypeAttr(state, attr, type); 4730 attr.setUsedAsTypeAttr(); 4731 break; 4732 case AttributeList::AT_VectorSize: 4733 HandleVectorSizeAttr(type, attr, state.getSema()); 4734 attr.setUsedAsTypeAttr(); 4735 break; 4736 case AttributeList::AT_ExtVectorType: 4737 HandleExtVectorTypeAttr(type, attr, state.getSema()); 4738 attr.setUsedAsTypeAttr(); 4739 break; 4740 case AttributeList::AT_NeonVectorType: 4741 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 4742 VectorType::NeonVector, "neon_vector_type"); 4743 attr.setUsedAsTypeAttr(); 4744 break; 4745 case AttributeList::AT_NeonPolyVectorType: 4746 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 4747 VectorType::NeonPolyVector, 4748 "neon_polyvector_type"); 4749 attr.setUsedAsTypeAttr(); 4750 break; 4751 case AttributeList::AT_OpenCLImageAccess: 4752 HandleOpenCLImageAccessAttribute(type, attr, state.getSema()); 4753 attr.setUsedAsTypeAttr(); 4754 break; 4755 4756 case AttributeList::AT_Win64: 4757 attr.setUsedAsTypeAttr(); 4758 break; 4759 MS_TYPE_ATTRS_CASELIST: 4760 if (!handleMSPointerTypeQualifierAttr(state, attr, type)) 4761 attr.setUsedAsTypeAttr(); 4762 break; 4763 4764 case AttributeList::AT_NSReturnsRetained: 4765 if (!state.getSema().getLangOpts().ObjCAutoRefCount) 4766 break; 4767 // fallthrough into the function attrs 4768 4769 FUNCTION_TYPE_ATTRS_CASELIST: 4770 attr.setUsedAsTypeAttr(); 4771 4772 // Never process function type attributes as part of the 4773 // declaration-specifiers. 4774 if (TAL == TAL_DeclSpec) 4775 distributeFunctionTypeAttrFromDeclSpec(state, attr, type); 4776 4777 // Otherwise, handle the possible delays. 4778 else if (!handleFunctionTypeAttr(state, attr, type)) 4779 distributeFunctionTypeAttr(state, attr, type); 4780 break; 4781 } 4782 } while ((attrs = next)); 4783} 4784 4785/// \brief Ensure that the type of the given expression is complete. 4786/// 4787/// This routine checks whether the expression \p E has a complete type. If the 4788/// expression refers to an instantiable construct, that instantiation is 4789/// performed as needed to complete its type. Furthermore 4790/// Sema::RequireCompleteType is called for the expression's type (or in the 4791/// case of a reference type, the referred-to type). 4792/// 4793/// \param E The expression whose type is required to be complete. 4794/// \param Diagnoser The object that will emit a diagnostic if the type is 4795/// incomplete. 4796/// 4797/// \returns \c true if the type of \p E is incomplete and diagnosed, \c false 4798/// otherwise. 4799bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){ 4800 QualType T = E->getType(); 4801 4802 // Fast path the case where the type is already complete. 4803 if (!T->isIncompleteType()) 4804 return false; 4805 4806 // Incomplete array types may be completed by the initializer attached to 4807 // their definitions. For static data members of class templates we need to 4808 // instantiate the definition to get this initializer and complete the type. 4809 if (T->isIncompleteArrayType()) { 4810 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4811 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 4812 if (Var->isStaticDataMember() && 4813 Var->getInstantiatedFromStaticDataMember()) { 4814 4815 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 4816 assert(MSInfo && "Missing member specialization information?"); 4817 if (MSInfo->getTemplateSpecializationKind() 4818 != TSK_ExplicitSpecialization) { 4819 // If we don't already have a point of instantiation, this is it. 4820 if (MSInfo->getPointOfInstantiation().isInvalid()) { 4821 MSInfo->setPointOfInstantiation(E->getLocStart()); 4822 4823 // This is a modification of an existing AST node. Notify 4824 // listeners. 4825 if (ASTMutationListener *L = getASTMutationListener()) 4826 L->StaticDataMemberInstantiated(Var); 4827 } 4828 4829 InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var); 4830 4831 // Update the type to the newly instantiated definition's type both 4832 // here and within the expression. 4833 if (VarDecl *Def = Var->getDefinition()) { 4834 DRE->setDecl(Def); 4835 T = Def->getType(); 4836 DRE->setType(T); 4837 E->setType(T); 4838 } 4839 } 4840 4841 // We still go on to try to complete the type independently, as it 4842 // may also require instantiations or diagnostics if it remains 4843 // incomplete. 4844 } 4845 } 4846 } 4847 } 4848 4849 // FIXME: Are there other cases which require instantiating something other 4850 // than the type to complete the type of an expression? 4851 4852 // Look through reference types and complete the referred type. 4853 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 4854 T = Ref->getPointeeType(); 4855 4856 return RequireCompleteType(E->getExprLoc(), T, Diagnoser); 4857} 4858 4859namespace { 4860 struct TypeDiagnoserDiag : Sema::TypeDiagnoser { 4861 unsigned DiagID; 4862 4863 TypeDiagnoserDiag(unsigned DiagID) 4864 : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {} 4865 4866 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 4867 if (Suppressed) return; 4868 S.Diag(Loc, DiagID) << T; 4869 } 4870 }; 4871} 4872 4873bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { 4874 TypeDiagnoserDiag Diagnoser(DiagID); 4875 return RequireCompleteExprType(E, Diagnoser); 4876} 4877 4878/// @brief Ensure that the type T is a complete type. 4879/// 4880/// This routine checks whether the type @p T is complete in any 4881/// context where a complete type is required. If @p T is a complete 4882/// type, returns false. If @p T is a class template specialization, 4883/// this routine then attempts to perform class template 4884/// instantiation. If instantiation fails, or if @p T is incomplete 4885/// and cannot be completed, issues the diagnostic @p diag (giving it 4886/// the type @p T) and returns true. 4887/// 4888/// @param Loc The location in the source that the incomplete type 4889/// diagnostic should refer to. 4890/// 4891/// @param T The type that this routine is examining for completeness. 4892/// 4893/// @returns @c true if @p T is incomplete and a diagnostic was emitted, 4894/// @c false otherwise. 4895bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 4896 TypeDiagnoser &Diagnoser) { 4897 if (RequireCompleteTypeImpl(Loc, T, Diagnoser)) 4898 return true; 4899 if (const TagType *Tag = T->getAs<TagType>()) { 4900 if (!Tag->getDecl()->isCompleteDefinitionRequired()) { 4901 Tag->getDecl()->setCompleteDefinitionRequired(); 4902 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); 4903 } 4904 } 4905 return false; 4906} 4907 4908/// \brief The implementation of RequireCompleteType 4909bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 4910 TypeDiagnoser &Diagnoser) { 4911 // FIXME: Add this assertion to make sure we always get instantiation points. 4912 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 4913 // FIXME: Add this assertion to help us flush out problems with 4914 // checking for dependent types and type-dependent expressions. 4915 // 4916 // assert(!T->isDependentType() && 4917 // "Can't ask whether a dependent type is complete"); 4918 4919 // If we have a complete type, we're done. 4920 NamedDecl *Def = 0; 4921 if (!T->isIncompleteType(&Def)) { 4922 // If we know about the definition but it is not visible, complain. 4923 if (!Diagnoser.Suppressed && Def && !LookupResult::isVisible(*this, Def)) { 4924 // Suppress this error outside of a SFINAE context if we've already 4925 // emitted the error once for this type. There's no usefulness in 4926 // repeating the diagnostic. 4927 // FIXME: Add a Fix-It that imports the corresponding module or includes 4928 // the header. 4929 Module *Owner = Def->getOwningModule(); 4930 Diag(Loc, diag::err_module_private_definition) 4931 << T << Owner->getFullModuleName(); 4932 Diag(Def->getLocation(), diag::note_previous_definition); 4933 4934 if (!isSFINAEContext()) { 4935 // Recover by implicitly importing this module. 4936 createImplicitModuleImport(Loc, Owner); 4937 } 4938 } 4939 4940 return false; 4941 } 4942 4943 const TagType *Tag = T->getAs<TagType>(); 4944 const ObjCInterfaceType *IFace = 0; 4945 4946 if (Tag) { 4947 // Avoid diagnosing invalid decls as incomplete. 4948 if (Tag->getDecl()->isInvalidDecl()) 4949 return true; 4950 4951 // Give the external AST source a chance to complete the type. 4952 if (Tag->getDecl()->hasExternalLexicalStorage()) { 4953 Context.getExternalSource()->CompleteType(Tag->getDecl()); 4954 if (!Tag->isIncompleteType()) 4955 return false; 4956 } 4957 } 4958 else if ((IFace = T->getAs<ObjCInterfaceType>())) { 4959 // Avoid diagnosing invalid decls as incomplete. 4960 if (IFace->getDecl()->isInvalidDecl()) 4961 return true; 4962 4963 // Give the external AST source a chance to complete the type. 4964 if (IFace->getDecl()->hasExternalLexicalStorage()) { 4965 Context.getExternalSource()->CompleteType(IFace->getDecl()); 4966 if (!IFace->isIncompleteType()) 4967 return false; 4968 } 4969 } 4970 4971 // If we have a class template specialization or a class member of a 4972 // class template specialization, or an array with known size of such, 4973 // try to instantiate it. 4974 QualType MaybeTemplate = T; 4975 while (const ConstantArrayType *Array 4976 = Context.getAsConstantArrayType(MaybeTemplate)) 4977 MaybeTemplate = Array->getElementType(); 4978 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) { 4979 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 4980 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 4981 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) 4982 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec, 4983 TSK_ImplicitInstantiation, 4984 /*Complain=*/!Diagnoser.Suppressed); 4985 } else if (CXXRecordDecl *Rec 4986 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 4987 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass(); 4988 if (!Rec->isBeingDefined() && Pattern) { 4989 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo(); 4990 assert(MSI && "Missing member specialization information?"); 4991 // This record was instantiated from a class within a template. 4992 if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 4993 return InstantiateClass(Loc, Rec, Pattern, 4994 getTemplateInstantiationArgs(Rec), 4995 TSK_ImplicitInstantiation, 4996 /*Complain=*/!Diagnoser.Suppressed); 4997 } 4998 } 4999 } 5000 5001 if (Diagnoser.Suppressed) 5002 return true; 5003 5004 // We have an incomplete type. Produce a diagnostic. 5005 if (Ident___float128 && 5006 T == Context.getTypeDeclType(Context.getFloat128StubType())) { 5007 Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128); 5008 return true; 5009 } 5010 5011 Diagnoser.diagnose(*this, Loc, T); 5012 5013 // If the type was a forward declaration of a class/struct/union 5014 // type, produce a note. 5015 if (Tag && !Tag->getDecl()->isInvalidDecl()) 5016 Diag(Tag->getDecl()->getLocation(), 5017 Tag->isBeingDefined() ? diag::note_type_being_defined 5018 : diag::note_forward_declaration) 5019 << QualType(Tag, 0); 5020 5021 // If the Objective-C class was a forward declaration, produce a note. 5022 if (IFace && !IFace->getDecl()->isInvalidDecl()) 5023 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class); 5024 5025 return true; 5026} 5027 5028bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 5029 unsigned DiagID) { 5030 TypeDiagnoserDiag Diagnoser(DiagID); 5031 return RequireCompleteType(Loc, T, Diagnoser); 5032} 5033 5034/// \brief Get diagnostic %select index for tag kind for 5035/// literal type diagnostic message. 5036/// WARNING: Indexes apply to particular diagnostics only! 5037/// 5038/// \returns diagnostic %select index. 5039static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { 5040 switch (Tag) { 5041 case TTK_Struct: return 0; 5042 case TTK_Interface: return 1; 5043 case TTK_Class: return 2; 5044 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!"); 5045 } 5046} 5047 5048/// @brief Ensure that the type T is a literal type. 5049/// 5050/// This routine checks whether the type @p T is a literal type. If @p T is an 5051/// incomplete type, an attempt is made to complete it. If @p T is a literal 5052/// type, or @p AllowIncompleteType is true and @p T is an incomplete type, 5053/// returns false. Otherwise, this routine issues the diagnostic @p PD (giving 5054/// it the type @p T), along with notes explaining why the type is not a 5055/// literal type, and returns true. 5056/// 5057/// @param Loc The location in the source that the non-literal type 5058/// diagnostic should refer to. 5059/// 5060/// @param T The type that this routine is examining for literalness. 5061/// 5062/// @param Diagnoser Emits a diagnostic if T is not a literal type. 5063/// 5064/// @returns @c true if @p T is not a literal type and a diagnostic was emitted, 5065/// @c false otherwise. 5066bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, 5067 TypeDiagnoser &Diagnoser) { 5068 assert(!T->isDependentType() && "type should not be dependent"); 5069 5070 QualType ElemType = Context.getBaseElementType(T); 5071 RequireCompleteType(Loc, ElemType, 0); 5072 5073 if (T->isLiteralType(Context)) 5074 return false; 5075 5076 if (Diagnoser.Suppressed) 5077 return true; 5078 5079 Diagnoser.diagnose(*this, Loc, T); 5080 5081 if (T->isVariableArrayType()) 5082 return true; 5083 5084 const RecordType *RT = ElemType->getAs<RecordType>(); 5085 if (!RT) 5086 return true; 5087 5088 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 5089 5090 // A partially-defined class type can't be a literal type, because a literal 5091 // class type must have a trivial destructor (which can't be checked until 5092 // the class definition is complete). 5093 if (!RD->isCompleteDefinition()) { 5094 RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T); 5095 return true; 5096 } 5097 5098 // If the class has virtual base classes, then it's not an aggregate, and 5099 // cannot have any constexpr constructors or a trivial default constructor, 5100 // so is non-literal. This is better to diagnose than the resulting absence 5101 // of constexpr constructors. 5102 if (RD->getNumVBases()) { 5103 Diag(RD->getLocation(), diag::note_non_literal_virtual_base) 5104 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 5105 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 5106 E = RD->vbases_end(); I != E; ++I) 5107 Diag(I->getLocStart(), 5108 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 5109 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && 5110 !RD->hasTrivialDefaultConstructor()) { 5111 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; 5112 } else if (RD->hasNonLiteralTypeFieldsOrBases()) { 5113 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 5114 E = RD->bases_end(); I != E; ++I) { 5115 if (!I->getType()->isLiteralType(Context)) { 5116 Diag(I->getLocStart(), 5117 diag::note_non_literal_base_class) 5118 << RD << I->getType() << I->getSourceRange(); 5119 return true; 5120 } 5121 } 5122 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 5123 E = RD->field_end(); I != E; ++I) { 5124 if (!I->getType()->isLiteralType(Context) || 5125 I->getType().isVolatileQualified()) { 5126 Diag(I->getLocation(), diag::note_non_literal_field) 5127 << RD << *I << I->getType() 5128 << I->getType().isVolatileQualified(); 5129 return true; 5130 } 5131 } 5132 } else if (!RD->hasTrivialDestructor()) { 5133 // All fields and bases are of literal types, so have trivial destructors. 5134 // If this class's destructor is non-trivial it must be user-declared. 5135 CXXDestructorDecl *Dtor = RD->getDestructor(); 5136 assert(Dtor && "class has literal fields and bases but no dtor?"); 5137 if (!Dtor) 5138 return true; 5139 5140 Diag(Dtor->getLocation(), Dtor->isUserProvided() ? 5141 diag::note_non_literal_user_provided_dtor : 5142 diag::note_non_literal_nontrivial_dtor) << RD; 5143 if (!Dtor->isUserProvided()) 5144 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true); 5145 } 5146 5147 return true; 5148} 5149 5150bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { 5151 TypeDiagnoserDiag Diagnoser(DiagID); 5152 return RequireLiteralType(Loc, T, Diagnoser); 5153} 5154 5155/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword 5156/// and qualified by the nested-name-specifier contained in SS. 5157QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 5158 const CXXScopeSpec &SS, QualType T) { 5159 if (T.isNull()) 5160 return T; 5161 NestedNameSpecifier *NNS; 5162 if (SS.isValid()) 5163 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 5164 else { 5165 if (Keyword == ETK_None) 5166 return T; 5167 NNS = 0; 5168 } 5169 return Context.getElaboratedType(Keyword, NNS, T); 5170} 5171 5172QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { 5173 ExprResult ER = CheckPlaceholderExpr(E); 5174 if (ER.isInvalid()) return QualType(); 5175 E = ER.take(); 5176 5177 if (!E->isTypeDependent()) { 5178 QualType T = E->getType(); 5179 if (const TagType *TT = T->getAs<TagType>()) 5180 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); 5181 } 5182 return Context.getTypeOfExprType(E); 5183} 5184 5185/// getDecltypeForExpr - Given an expr, will return the decltype for 5186/// that expression, according to the rules in C++11 5187/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. 5188static QualType getDecltypeForExpr(Sema &S, Expr *E) { 5189 if (E->isTypeDependent()) 5190 return S.Context.DependentTy; 5191 5192 // C++11 [dcl.type.simple]p4: 5193 // The type denoted by decltype(e) is defined as follows: 5194 // 5195 // - if e is an unparenthesized id-expression or an unparenthesized class 5196 // member access (5.2.5), decltype(e) is the type of the entity named 5197 // by e. If there is no such entity, or if e names a set of overloaded 5198 // functions, the program is ill-formed; 5199 // 5200 // We apply the same rules for Objective-C ivar and property references. 5201 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 5202 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) 5203 return VD->getType(); 5204 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 5205 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 5206 return FD->getType(); 5207 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) { 5208 return IR->getDecl()->getType(); 5209 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) { 5210 if (PR->isExplicitProperty()) 5211 return PR->getExplicitProperty()->getType(); 5212 } 5213 5214 // C++11 [expr.lambda.prim]p18: 5215 // Every occurrence of decltype((x)) where x is a possibly 5216 // parenthesized id-expression that names an entity of automatic 5217 // storage duration is treated as if x were transformed into an 5218 // access to a corresponding data member of the closure type that 5219 // would have been declared if x were an odr-use of the denoted 5220 // entity. 5221 using namespace sema; 5222 if (S.getCurLambda()) { 5223 if (isa<ParenExpr>(E)) { 5224 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 5225 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 5226 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation()); 5227 if (!T.isNull()) 5228 return S.Context.getLValueReferenceType(T); 5229 } 5230 } 5231 } 5232 } 5233 5234 5235 // C++11 [dcl.type.simple]p4: 5236 // [...] 5237 QualType T = E->getType(); 5238 switch (E->getValueKind()) { 5239 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 5240 // type of e; 5241 case VK_XValue: T = S.Context.getRValueReferenceType(T); break; 5242 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 5243 // type of e; 5244 case VK_LValue: T = S.Context.getLValueReferenceType(T); break; 5245 // - otherwise, decltype(e) is the type of e. 5246 case VK_RValue: break; 5247 } 5248 5249 return T; 5250} 5251 5252QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) { 5253 ExprResult ER = CheckPlaceholderExpr(E); 5254 if (ER.isInvalid()) return QualType(); 5255 E = ER.take(); 5256 5257 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E)); 5258} 5259 5260QualType Sema::BuildUnaryTransformType(QualType BaseType, 5261 UnaryTransformType::UTTKind UKind, 5262 SourceLocation Loc) { 5263 switch (UKind) { 5264 case UnaryTransformType::EnumUnderlyingType: 5265 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { 5266 Diag(Loc, diag::err_only_enums_have_underlying_types); 5267 return QualType(); 5268 } else { 5269 QualType Underlying = BaseType; 5270 if (!BaseType->isDependentType()) { 5271 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl(); 5272 assert(ED && "EnumType has no EnumDecl"); 5273 DiagnoseUseOfDecl(ED, Loc); 5274 Underlying = ED->getIntegerType(); 5275 } 5276 assert(!Underlying.isNull()); 5277 return Context.getUnaryTransformType(BaseType, Underlying, 5278 UnaryTransformType::EnumUnderlyingType); 5279 } 5280 } 5281 llvm_unreachable("unknown unary transform type"); 5282} 5283 5284QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { 5285 if (!T->isDependentType()) { 5286 // FIXME: It isn't entirely clear whether incomplete atomic types 5287 // are allowed or not; for simplicity, ban them for the moment. 5288 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) 5289 return QualType(); 5290 5291 int DisallowedKind = -1; 5292 if (T->isArrayType()) 5293 DisallowedKind = 1; 5294 else if (T->isFunctionType()) 5295 DisallowedKind = 2; 5296 else if (T->isReferenceType()) 5297 DisallowedKind = 3; 5298 else if (T->isAtomicType()) 5299 DisallowedKind = 4; 5300 else if (T.hasQualifiers()) 5301 DisallowedKind = 5; 5302 else if (!T.isTriviallyCopyableType(Context)) 5303 // Some other non-trivially-copyable type (probably a C++ class) 5304 DisallowedKind = 6; 5305 5306 if (DisallowedKind != -1) { 5307 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; 5308 return QualType(); 5309 } 5310 5311 // FIXME: Do we need any handling for ARC here? 5312 } 5313 5314 // Build the pointer type. 5315 return Context.getAtomicType(T); 5316} 5317