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