1 //===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===// 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 the ASTContext interface. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/ASTContext.h" 15 #include "CXXABI.h" 16 #include "clang/AST/APValue.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/ASTTypeTraits.h" 19 #include "clang/AST/Attr.h" 20 #include "clang/AST/AttrIterator.h" 21 #include "clang/AST/CharUnits.h" 22 #include "clang/AST/Comment.h" 23 #include "clang/AST/Decl.h" 24 #include "clang/AST/DeclBase.h" 25 #include "clang/AST/DeclCXX.h" 26 #include "clang/AST/DeclContextInternals.h" 27 #include "clang/AST/DeclObjC.h" 28 #include "clang/AST/DeclOpenMP.h" 29 #include "clang/AST/DeclTemplate.h" 30 #include "clang/AST/DeclarationName.h" 31 #include "clang/AST/Expr.h" 32 #include "clang/AST/ExprCXX.h" 33 #include "clang/AST/ExternalASTSource.h" 34 #include "clang/AST/Mangle.h" 35 #include "clang/AST/MangleNumberingContext.h" 36 #include "clang/AST/NestedNameSpecifier.h" 37 #include "clang/AST/RawCommentList.h" 38 #include "clang/AST/RecordLayout.h" 39 #include "clang/AST/RecursiveASTVisitor.h" 40 #include "clang/AST/Stmt.h" 41 #include "clang/AST/TemplateBase.h" 42 #include "clang/AST/TemplateName.h" 43 #include "clang/AST/Type.h" 44 #include "clang/AST/TypeLoc.h" 45 #include "clang/AST/UnresolvedSet.h" 46 #include "clang/AST/VTableBuilder.h" 47 #include "clang/Basic/AddressSpaces.h" 48 #include "clang/Basic/Builtins.h" 49 #include "clang/Basic/CommentOptions.h" 50 #include "clang/Basic/ExceptionSpecificationType.h" 51 #include "clang/Basic/FixedPoint.h" 52 #include "clang/Basic/IdentifierTable.h" 53 #include "clang/Basic/LLVM.h" 54 #include "clang/Basic/LangOptions.h" 55 #include "clang/Basic/Linkage.h" 56 #include "clang/Basic/ObjCRuntime.h" 57 #include "clang/Basic/SanitizerBlacklist.h" 58 #include "clang/Basic/SourceLocation.h" 59 #include "clang/Basic/SourceManager.h" 60 #include "clang/Basic/Specifiers.h" 61 #include "clang/Basic/TargetCXXABI.h" 62 #include "clang/Basic/TargetInfo.h" 63 #include "clang/Basic/XRayLists.h" 64 #include "llvm/ADT/APInt.h" 65 #include "llvm/ADT/APSInt.h" 66 #include "llvm/ADT/ArrayRef.h" 67 #include "llvm/ADT/DenseMap.h" 68 #include "llvm/ADT/DenseSet.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/PointerUnion.h" 73 #include "llvm/ADT/STLExtras.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/StringExtras.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/Triple.h" 79 #include "llvm/Support/Capacity.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/Compiler.h" 82 #include "llvm/Support/ErrorHandling.h" 83 #include "llvm/Support/MathExtras.h" 84 #include "llvm/Support/raw_ostream.h" 85 #include <algorithm> 86 #include <cassert> 87 #include <cstddef> 88 #include <cstdint> 89 #include <cstdlib> 90 #include <map> 91 #include <memory> 92 #include <string> 93 #include <tuple> 94 #include <utility> 95 96 using namespace clang; 97 98 unsigned ASTContext::NumImplicitDefaultConstructors; 99 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared; 100 unsigned ASTContext::NumImplicitCopyConstructors; 101 unsigned ASTContext::NumImplicitCopyConstructorsDeclared; 102 unsigned ASTContext::NumImplicitMoveConstructors; 103 unsigned ASTContext::NumImplicitMoveConstructorsDeclared; 104 unsigned ASTContext::NumImplicitCopyAssignmentOperators; 105 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 106 unsigned ASTContext::NumImplicitMoveAssignmentOperators; 107 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 108 unsigned ASTContext::NumImplicitDestructors; 109 unsigned ASTContext::NumImplicitDestructorsDeclared; 110 111 enum FloatingRank { 112 Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank 113 }; 114 115 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const { 116 if (!CommentsLoaded && ExternalSource) { 117 ExternalSource->ReadComments(); 118 119 #ifndef NDEBUG 120 ArrayRef<RawComment *> RawComments = Comments.getComments(); 121 assert(std::is_sorted(RawComments.begin(), RawComments.end(), 122 BeforeThanCompare<RawComment>(SourceMgr))); 123 #endif 124 125 CommentsLoaded = true; 126 } 127 128 assert(D); 129 130 // User can not attach documentation to implicit declarations. 131 if (D->isImplicit()) 132 return nullptr; 133 134 // User can not attach documentation to implicit instantiations. 135 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 136 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 137 return nullptr; 138 } 139 140 if (const auto *VD = dyn_cast<VarDecl>(D)) { 141 if (VD->isStaticDataMember() && 142 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 143 return nullptr; 144 } 145 146 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) { 147 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 148 return nullptr; 149 } 150 151 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 152 TemplateSpecializationKind TSK = CTSD->getSpecializationKind(); 153 if (TSK == TSK_ImplicitInstantiation || 154 TSK == TSK_Undeclared) 155 return nullptr; 156 } 157 158 if (const auto *ED = dyn_cast<EnumDecl>(D)) { 159 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 160 return nullptr; 161 } 162 if (const auto *TD = dyn_cast<TagDecl>(D)) { 163 // When tag declaration (but not definition!) is part of the 164 // decl-specifier-seq of some other declaration, it doesn't get comment 165 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition()) 166 return nullptr; 167 } 168 // TODO: handle comments for function parameters properly. 169 if (isa<ParmVarDecl>(D)) 170 return nullptr; 171 172 // TODO: we could look up template parameter documentation in the template 173 // documentation. 174 if (isa<TemplateTypeParmDecl>(D) || 175 isa<NonTypeTemplateParmDecl>(D) || 176 isa<TemplateTemplateParmDecl>(D)) 177 return nullptr; 178 179 ArrayRef<RawComment *> RawComments = Comments.getComments(); 180 181 // If there are no comments anywhere, we won't find anything. 182 if (RawComments.empty()) 183 return nullptr; 184 185 // Find declaration location. 186 // For Objective-C declarations we generally don't expect to have multiple 187 // declarators, thus use declaration starting location as the "declaration 188 // location". 189 // For all other declarations multiple declarators are used quite frequently, 190 // so we use the location of the identifier as the "declaration location". 191 SourceLocation DeclLoc; 192 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) || 193 isa<ObjCPropertyDecl>(D) || 194 isa<RedeclarableTemplateDecl>(D) || 195 isa<ClassTemplateSpecializationDecl>(D)) 196 DeclLoc = D->getBeginLoc(); 197 else { 198 DeclLoc = D->getLocation(); 199 if (DeclLoc.isMacroID()) { 200 if (isa<TypedefDecl>(D)) { 201 // If location of the typedef name is in a macro, it is because being 202 // declared via a macro. Try using declaration's starting location as 203 // the "declaration location". 204 DeclLoc = D->getBeginLoc(); 205 } else if (const auto *TD = dyn_cast<TagDecl>(D)) { 206 // If location of the tag decl is inside a macro, but the spelling of 207 // the tag name comes from a macro argument, it looks like a special 208 // macro like NS_ENUM is being used to define the tag decl. In that 209 // case, adjust the source location to the expansion loc so that we can 210 // attach the comment to the tag decl. 211 if (SourceMgr.isMacroArgExpansion(DeclLoc) && 212 TD->isCompleteDefinition()) 213 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc); 214 } 215 } 216 } 217 218 // If the declaration doesn't map directly to a location in a file, we 219 // can't find the comment. 220 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 221 return nullptr; 222 223 // Find the comment that occurs just after this declaration. 224 ArrayRef<RawComment *>::iterator Comment; 225 { 226 // When searching for comments during parsing, the comment we are looking 227 // for is usually among the last two comments we parsed -- check them 228 // first. 229 RawComment CommentAtDeclLoc( 230 SourceMgr, SourceRange(DeclLoc), LangOpts.CommentOpts, false); 231 BeforeThanCompare<RawComment> Compare(SourceMgr); 232 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1; 233 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc); 234 if (!Found && RawComments.size() >= 2) { 235 MaybeBeforeDecl--; 236 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc); 237 } 238 239 if (Found) { 240 Comment = MaybeBeforeDecl + 1; 241 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(), 242 &CommentAtDeclLoc, Compare)); 243 } else { 244 // Slow path. 245 Comment = std::lower_bound(RawComments.begin(), RawComments.end(), 246 &CommentAtDeclLoc, Compare); 247 } 248 } 249 250 // Decompose the location for the declaration and find the beginning of the 251 // file buffer. 252 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc); 253 254 // First check whether we have a trailing comment. 255 if (Comment != RawComments.end() && 256 ((*Comment)->isDocumentation() || LangOpts.CommentOpts.ParseAllComments) 257 && (*Comment)->isTrailingComment() && 258 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) || 259 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) { 260 std::pair<FileID, unsigned> CommentBeginDecomp 261 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin()); 262 // Check that Doxygen trailing comment comes after the declaration, starts 263 // on the same line and in the same file as the declaration. 264 if (DeclLocDecomp.first == CommentBeginDecomp.first && 265 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) 266 == SourceMgr.getLineNumber(CommentBeginDecomp.first, 267 CommentBeginDecomp.second)) { 268 return *Comment; 269 } 270 } 271 272 // The comment just after the declaration was not a trailing comment. 273 // Let's look at the previous comment. 274 if (Comment == RawComments.begin()) 275 return nullptr; 276 --Comment; 277 278 // Check that we actually have a non-member Doxygen comment. 279 if (!((*Comment)->isDocumentation() || 280 LangOpts.CommentOpts.ParseAllComments) || 281 (*Comment)->isTrailingComment()) 282 return nullptr; 283 284 // Decompose the end of the comment. 285 std::pair<FileID, unsigned> CommentEndDecomp 286 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd()); 287 288 // If the comment and the declaration aren't in the same file, then they 289 // aren't related. 290 if (DeclLocDecomp.first != CommentEndDecomp.first) 291 return nullptr; 292 293 // Get the corresponding buffer. 294 bool Invalid = false; 295 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first, 296 &Invalid).data(); 297 if (Invalid) 298 return nullptr; 299 300 // Extract text between the comment and declaration. 301 StringRef Text(Buffer + CommentEndDecomp.second, 302 DeclLocDecomp.second - CommentEndDecomp.second); 303 304 // There should be no other declarations or preprocessor directives between 305 // comment and declaration. 306 if (Text.find_first_of(";{}#@") != StringRef::npos) 307 return nullptr; 308 309 return *Comment; 310 } 311 312 /// If we have a 'templated' declaration for a template, adjust 'D' to 313 /// refer to the actual template. 314 /// If we have an implicit instantiation, adjust 'D' to refer to template. 315 static const Decl *adjustDeclToTemplate(const Decl *D) { 316 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 317 // Is this function declaration part of a function template? 318 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 319 return FTD; 320 321 // Nothing to do if function is not an implicit instantiation. 322 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) 323 return D; 324 325 // Function is an implicit instantiation of a function template? 326 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate()) 327 return FTD; 328 329 // Function is instantiated from a member definition of a class template? 330 if (const FunctionDecl *MemberDecl = 331 FD->getInstantiatedFromMemberFunction()) 332 return MemberDecl; 333 334 return D; 335 } 336 if (const auto *VD = dyn_cast<VarDecl>(D)) { 337 // Static data member is instantiated from a member definition of a class 338 // template? 339 if (VD->isStaticDataMember()) 340 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember()) 341 return MemberDecl; 342 343 return D; 344 } 345 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) { 346 // Is this class declaration part of a class template? 347 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate()) 348 return CTD; 349 350 // Class is an implicit instantiation of a class template or partial 351 // specialization? 352 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) { 353 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation) 354 return D; 355 llvm::PointerUnion<ClassTemplateDecl *, 356 ClassTemplatePartialSpecializationDecl *> 357 PU = CTSD->getSpecializedTemplateOrPartial(); 358 return PU.is<ClassTemplateDecl*>() ? 359 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) : 360 static_cast<const Decl*>( 361 PU.get<ClassTemplatePartialSpecializationDecl *>()); 362 } 363 364 // Class is instantiated from a member definition of a class template? 365 if (const MemberSpecializationInfo *Info = 366 CRD->getMemberSpecializationInfo()) 367 return Info->getInstantiatedFrom(); 368 369 return D; 370 } 371 if (const auto *ED = dyn_cast<EnumDecl>(D)) { 372 // Enum is instantiated from a member definition of a class template? 373 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum()) 374 return MemberDecl; 375 376 return D; 377 } 378 // FIXME: Adjust alias templates? 379 return D; 380 } 381 382 const RawComment *ASTContext::getRawCommentForAnyRedecl( 383 const Decl *D, 384 const Decl **OriginalDecl) const { 385 D = adjustDeclToTemplate(D); 386 387 // Check whether we have cached a comment for this declaration already. 388 { 389 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos = 390 RedeclComments.find(D); 391 if (Pos != RedeclComments.end()) { 392 const RawCommentAndCacheFlags &Raw = Pos->second; 393 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) { 394 if (OriginalDecl) 395 *OriginalDecl = Raw.getOriginalDecl(); 396 return Raw.getRaw(); 397 } 398 } 399 } 400 401 // Search for comments attached to declarations in the redeclaration chain. 402 const RawComment *RC = nullptr; 403 const Decl *OriginalDeclForRC = nullptr; 404 for (auto I : D->redecls()) { 405 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos = 406 RedeclComments.find(I); 407 if (Pos != RedeclComments.end()) { 408 const RawCommentAndCacheFlags &Raw = Pos->second; 409 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) { 410 RC = Raw.getRaw(); 411 OriginalDeclForRC = Raw.getOriginalDecl(); 412 break; 413 } 414 } else { 415 RC = getRawCommentForDeclNoCache(I); 416 OriginalDeclForRC = I; 417 RawCommentAndCacheFlags Raw; 418 if (RC) { 419 // Call order swapped to work around ICE in VS2015 RTM (Release Win32) 420 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530 421 Raw.setKind(RawCommentAndCacheFlags::FromDecl); 422 Raw.setRaw(RC); 423 } else 424 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl); 425 Raw.setOriginalDecl(I); 426 RedeclComments[I] = Raw; 427 if (RC) 428 break; 429 } 430 } 431 432 // If we found a comment, it should be a documentation comment. 433 assert(!RC || RC->isDocumentation() || LangOpts.CommentOpts.ParseAllComments); 434 435 if (OriginalDecl) 436 *OriginalDecl = OriginalDeclForRC; 437 438 // Update cache for every declaration in the redeclaration chain. 439 RawCommentAndCacheFlags Raw; 440 Raw.setRaw(RC); 441 Raw.setKind(RawCommentAndCacheFlags::FromRedecl); 442 Raw.setOriginalDecl(OriginalDeclForRC); 443 444 for (auto I : D->redecls()) { 445 RawCommentAndCacheFlags &R = RedeclComments[I]; 446 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl) 447 R = Raw; 448 } 449 450 return RC; 451 } 452 453 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, 454 SmallVectorImpl<const NamedDecl *> &Redeclared) { 455 const DeclContext *DC = ObjCMethod->getDeclContext(); 456 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) { 457 const ObjCInterfaceDecl *ID = IMD->getClassInterface(); 458 if (!ID) 459 return; 460 // Add redeclared method here. 461 for (const auto *Ext : ID->known_extensions()) { 462 if (ObjCMethodDecl *RedeclaredMethod = 463 Ext->getMethod(ObjCMethod->getSelector(), 464 ObjCMethod->isInstanceMethod())) 465 Redeclared.push_back(RedeclaredMethod); 466 } 467 } 468 } 469 470 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC, 471 const Decl *D) const { 472 auto *ThisDeclInfo = new (*this) comments::DeclInfo; 473 ThisDeclInfo->CommentDecl = D; 474 ThisDeclInfo->IsFilled = false; 475 ThisDeclInfo->fill(); 476 ThisDeclInfo->CommentDecl = FC->getDecl(); 477 if (!ThisDeclInfo->TemplateParameters) 478 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters; 479 comments::FullComment *CFC = 480 new (*this) comments::FullComment(FC->getBlocks(), 481 ThisDeclInfo); 482 return CFC; 483 } 484 485 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const { 486 const RawComment *RC = getRawCommentForDeclNoCache(D); 487 return RC ? RC->parse(*this, nullptr, D) : nullptr; 488 } 489 490 comments::FullComment *ASTContext::getCommentForDecl( 491 const Decl *D, 492 const Preprocessor *PP) const { 493 if (D->isInvalidDecl()) 494 return nullptr; 495 D = adjustDeclToTemplate(D); 496 497 const Decl *Canonical = D->getCanonicalDecl(); 498 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos = 499 ParsedComments.find(Canonical); 500 501 if (Pos != ParsedComments.end()) { 502 if (Canonical != D) { 503 comments::FullComment *FC = Pos->second; 504 comments::FullComment *CFC = cloneFullComment(FC, D); 505 return CFC; 506 } 507 return Pos->second; 508 } 509 510 const Decl *OriginalDecl; 511 512 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl); 513 if (!RC) { 514 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) { 515 SmallVector<const NamedDecl*, 8> Overridden; 516 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 517 if (OMD && OMD->isPropertyAccessor()) 518 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) 519 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP)) 520 return cloneFullComment(FC, D); 521 if (OMD) 522 addRedeclaredMethods(OMD, Overridden); 523 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden); 524 for (unsigned i = 0, e = Overridden.size(); i < e; i++) 525 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) 526 return cloneFullComment(FC, D); 527 } 528 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 529 // Attach any tag type's documentation to its typedef if latter 530 // does not have one of its own. 531 QualType QT = TD->getUnderlyingType(); 532 if (const auto *TT = QT->getAs<TagType>()) 533 if (const Decl *TD = TT->getDecl()) 534 if (comments::FullComment *FC = getCommentForDecl(TD, PP)) 535 return cloneFullComment(FC, D); 536 } 537 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) { 538 while (IC->getSuperClass()) { 539 IC = IC->getSuperClass(); 540 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 541 return cloneFullComment(FC, D); 542 } 543 } 544 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) { 545 if (const ObjCInterfaceDecl *IC = CD->getClassInterface()) 546 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 547 return cloneFullComment(FC, D); 548 } 549 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) { 550 if (!(RD = RD->getDefinition())) 551 return nullptr; 552 // Check non-virtual bases. 553 for (const auto &I : RD->bases()) { 554 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public)) 555 continue; 556 QualType Ty = I.getType(); 557 if (Ty.isNull()) 558 continue; 559 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) { 560 if (!(NonVirtualBase= NonVirtualBase->getDefinition())) 561 continue; 562 563 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP)) 564 return cloneFullComment(FC, D); 565 } 566 } 567 // Check virtual bases. 568 for (const auto &I : RD->vbases()) { 569 if (I.getAccessSpecifier() != AS_public) 570 continue; 571 QualType Ty = I.getType(); 572 if (Ty.isNull()) 573 continue; 574 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) { 575 if (!(VirtualBase= VirtualBase->getDefinition())) 576 continue; 577 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP)) 578 return cloneFullComment(FC, D); 579 } 580 } 581 } 582 return nullptr; 583 } 584 585 // If the RawComment was attached to other redeclaration of this Decl, we 586 // should parse the comment in context of that other Decl. This is important 587 // because comments can contain references to parameter names which can be 588 // different across redeclarations. 589 if (D != OriginalDecl) 590 return getCommentForDecl(OriginalDecl, PP); 591 592 comments::FullComment *FC = RC->parse(*this, PP, D); 593 ParsedComments[Canonical] = FC; 594 return FC; 595 } 596 597 void 598 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 599 TemplateTemplateParmDecl *Parm) { 600 ID.AddInteger(Parm->getDepth()); 601 ID.AddInteger(Parm->getPosition()); 602 ID.AddBoolean(Parm->isParameterPack()); 603 604 TemplateParameterList *Params = Parm->getTemplateParameters(); 605 ID.AddInteger(Params->size()); 606 for (TemplateParameterList::const_iterator P = Params->begin(), 607 PEnd = Params->end(); 608 P != PEnd; ++P) { 609 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 610 ID.AddInteger(0); 611 ID.AddBoolean(TTP->isParameterPack()); 612 continue; 613 } 614 615 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 616 ID.AddInteger(1); 617 ID.AddBoolean(NTTP->isParameterPack()); 618 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr()); 619 if (NTTP->isExpandedParameterPack()) { 620 ID.AddBoolean(true); 621 ID.AddInteger(NTTP->getNumExpansionTypes()); 622 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 623 QualType T = NTTP->getExpansionType(I); 624 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); 625 } 626 } else 627 ID.AddBoolean(false); 628 continue; 629 } 630 631 auto *TTP = cast<TemplateTemplateParmDecl>(*P); 632 ID.AddInteger(2); 633 Profile(ID, TTP); 634 } 635 } 636 637 TemplateTemplateParmDecl * 638 ASTContext::getCanonicalTemplateTemplateParmDecl( 639 TemplateTemplateParmDecl *TTP) const { 640 // Check if we already have a canonical template template parameter. 641 llvm::FoldingSetNodeID ID; 642 CanonicalTemplateTemplateParm::Profile(ID, TTP); 643 void *InsertPos = nullptr; 644 CanonicalTemplateTemplateParm *Canonical 645 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 646 if (Canonical) 647 return Canonical->getParam(); 648 649 // Build a canonical template parameter list. 650 TemplateParameterList *Params = TTP->getTemplateParameters(); 651 SmallVector<NamedDecl *, 4> CanonParams; 652 CanonParams.reserve(Params->size()); 653 for (TemplateParameterList::const_iterator P = Params->begin(), 654 PEnd = Params->end(); 655 P != PEnd; ++P) { 656 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) 657 CanonParams.push_back( 658 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(), 659 SourceLocation(), 660 SourceLocation(), 661 TTP->getDepth(), 662 TTP->getIndex(), nullptr, false, 663 TTP->isParameterPack())); 664 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 665 QualType T = getCanonicalType(NTTP->getType()); 666 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 667 NonTypeTemplateParmDecl *Param; 668 if (NTTP->isExpandedParameterPack()) { 669 SmallVector<QualType, 2> ExpandedTypes; 670 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; 671 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 672 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); 673 ExpandedTInfos.push_back( 674 getTrivialTypeSourceInfo(ExpandedTypes.back())); 675 } 676 677 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 678 SourceLocation(), 679 SourceLocation(), 680 NTTP->getDepth(), 681 NTTP->getPosition(), nullptr, 682 T, 683 TInfo, 684 ExpandedTypes, 685 ExpandedTInfos); 686 } else { 687 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 688 SourceLocation(), 689 SourceLocation(), 690 NTTP->getDepth(), 691 NTTP->getPosition(), nullptr, 692 T, 693 NTTP->isParameterPack(), 694 TInfo); 695 } 696 CanonParams.push_back(Param); 697 698 } else 699 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 700 cast<TemplateTemplateParmDecl>(*P))); 701 } 702 703 assert(!TTP->getRequiresClause() && 704 "Unexpected requires-clause on template template-parameter"); 705 Expr *const CanonRequiresClause = nullptr; 706 707 TemplateTemplateParmDecl *CanonTTP 708 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 709 SourceLocation(), TTP->getDepth(), 710 TTP->getPosition(), 711 TTP->isParameterPack(), 712 nullptr, 713 TemplateParameterList::Create(*this, SourceLocation(), 714 SourceLocation(), 715 CanonParams, 716 SourceLocation(), 717 CanonRequiresClause)); 718 719 // Get the new insert position for the node we care about. 720 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 721 assert(!Canonical && "Shouldn't be in the map!"); 722 (void)Canonical; 723 724 // Create the canonical template template parameter entry. 725 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 726 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 727 return CanonTTP; 728 } 729 730 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 731 if (!LangOpts.CPlusPlus) return nullptr; 732 733 switch (T.getCXXABI().getKind()) { 734 case TargetCXXABI::GenericARM: // Same as Itanium at this level 735 case TargetCXXABI::iOS: 736 case TargetCXXABI::iOS64: 737 case TargetCXXABI::WatchOS: 738 case TargetCXXABI::GenericAArch64: 739 case TargetCXXABI::GenericMIPS: 740 case TargetCXXABI::GenericItanium: 741 case TargetCXXABI::WebAssembly: 742 return CreateItaniumCXXABI(*this); 743 case TargetCXXABI::Microsoft: 744 return CreateMicrosoftCXXABI(*this); 745 } 746 llvm_unreachable("Invalid CXXABI type!"); 747 } 748 749 static const LangASMap *getAddressSpaceMap(const TargetInfo &T, 750 const LangOptions &LOpts) { 751 if (LOpts.FakeAddressSpaceMap) { 752 // The fake address space map must have a distinct entry for each 753 // language-specific address space. 754 static const unsigned FakeAddrSpaceMap[] = { 755 0, // Default 756 1, // opencl_global 757 3, // opencl_local 758 2, // opencl_constant 759 0, // opencl_private 760 4, // opencl_generic 761 5, // cuda_device 762 6, // cuda_constant 763 7 // cuda_shared 764 }; 765 return &FakeAddrSpaceMap; 766 } else { 767 return &T.getAddressSpaceMap(); 768 } 769 } 770 771 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, 772 const LangOptions &LangOpts) { 773 switch (LangOpts.getAddressSpaceMapMangling()) { 774 case LangOptions::ASMM_Target: 775 return TI.useAddressSpaceMapMangling(); 776 case LangOptions::ASMM_On: 777 return true; 778 case LangOptions::ASMM_Off: 779 return false; 780 } 781 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything."); 782 } 783 784 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM, 785 IdentifierTable &idents, SelectorTable &sels, 786 Builtin::Context &builtins) 787 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()), 788 DependentTemplateSpecializationTypes(this_()), 789 SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts), 790 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)), 791 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles, 792 LangOpts.XRayNeverInstrumentFiles, 793 LangOpts.XRayAttrListFiles, SM)), 794 PrintingPolicy(LOpts), Idents(idents), Selectors(sels), 795 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM), 796 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), 797 CompCategories(this_()), LastSDM(nullptr, 0) { 798 TUDecl = TranslationUnitDecl::Create(*this); 799 } 800 801 ASTContext::~ASTContext() { 802 ReleaseParentMapEntries(); 803 804 // Release the DenseMaps associated with DeclContext objects. 805 // FIXME: Is this the ideal solution? 806 ReleaseDeclContextMaps(); 807 808 // Call all of the deallocation functions on all of their targets. 809 for (auto &Pair : Deallocations) 810 (Pair.first)(Pair.second); 811 812 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 813 // because they can contain DenseMaps. 814 for (llvm::DenseMap<const ObjCContainerDecl*, 815 const ASTRecordLayout*>::iterator 816 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 817 // Increment in loop to prevent using deallocated memory. 818 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 819 R->Destroy(*this); 820 821 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 822 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 823 // Increment in loop to prevent using deallocated memory. 824 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) 825 R->Destroy(*this); 826 } 827 828 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 829 AEnd = DeclAttrs.end(); 830 A != AEnd; ++A) 831 A->second->~AttrVec(); 832 833 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair : 834 MaterializedTemporaryValues) 835 MTVPair.second->~APValue(); 836 837 for (const auto &Value : ModuleInitializers) 838 Value.second->~PerModuleInitializers(); 839 } 840 841 void ASTContext::ReleaseParentMapEntries() { 842 if (!PointerParents) return; 843 for (const auto &Entry : *PointerParents) { 844 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) { 845 delete Entry.second.get<ast_type_traits::DynTypedNode *>(); 846 } else if (Entry.second.is<ParentVector *>()) { 847 delete Entry.second.get<ParentVector *>(); 848 } 849 } 850 for (const auto &Entry : *OtherParents) { 851 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) { 852 delete Entry.second.get<ast_type_traits::DynTypedNode *>(); 853 } else if (Entry.second.is<ParentVector *>()) { 854 delete Entry.second.get<ParentVector *>(); 855 } 856 } 857 } 858 859 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) { 860 Deallocations.push_back({Callback, Data}); 861 } 862 863 void 864 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) { 865 ExternalSource = std::move(Source); 866 } 867 868 void ASTContext::PrintStats() const { 869 llvm::errs() << "\n*** AST Context Stats:\n"; 870 llvm::errs() << " " << Types.size() << " types total.\n"; 871 872 unsigned counts[] = { 873 #define TYPE(Name, Parent) 0, 874 #define ABSTRACT_TYPE(Name, Parent) 875 #include "clang/AST/TypeNodes.def" 876 0 // Extra 877 }; 878 879 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 880 Type *T = Types[i]; 881 counts[(unsigned)T->getTypeClass()]++; 882 } 883 884 unsigned Idx = 0; 885 unsigned TotalBytes = 0; 886 #define TYPE(Name, Parent) \ 887 if (counts[Idx]) \ 888 llvm::errs() << " " << counts[Idx] << " " << #Name \ 889 << " types, " << sizeof(Name##Type) << " each " \ 890 << "(" << counts[Idx] * sizeof(Name##Type) \ 891 << " bytes)\n"; \ 892 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 893 ++Idx; 894 #define ABSTRACT_TYPE(Name, Parent) 895 #include "clang/AST/TypeNodes.def" 896 897 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 898 899 // Implicit special member functions. 900 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 901 << NumImplicitDefaultConstructors 902 << " implicit default constructors created\n"; 903 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 904 << NumImplicitCopyConstructors 905 << " implicit copy constructors created\n"; 906 if (getLangOpts().CPlusPlus) 907 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 908 << NumImplicitMoveConstructors 909 << " implicit move constructors created\n"; 910 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 911 << NumImplicitCopyAssignmentOperators 912 << " implicit copy assignment operators created\n"; 913 if (getLangOpts().CPlusPlus) 914 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 915 << NumImplicitMoveAssignmentOperators 916 << " implicit move assignment operators created\n"; 917 llvm::errs() << NumImplicitDestructorsDeclared << "/" 918 << NumImplicitDestructors 919 << " implicit destructors created\n"; 920 921 if (ExternalSource) { 922 llvm::errs() << "\n"; 923 ExternalSource->PrintStats(); 924 } 925 926 BumpAlloc.PrintStats(); 927 } 928 929 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M, 930 bool NotifyListeners) { 931 if (NotifyListeners) 932 if (auto *Listener = getASTMutationListener()) 933 Listener->RedefinedHiddenDefinition(ND, M); 934 935 if (getLangOpts().ModulesLocalVisibility) 936 MergedDefModules[ND].push_back(M); 937 else 938 ND->setVisibleDespiteOwningModule(); 939 } 940 941 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) { 942 auto It = MergedDefModules.find(ND); 943 if (It == MergedDefModules.end()) 944 return; 945 946 auto &Merged = It->second; 947 llvm::DenseSet<Module*> Found; 948 for (Module *&M : Merged) 949 if (!Found.insert(M).second) 950 M = nullptr; 951 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end()); 952 } 953 954 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) { 955 if (LazyInitializers.empty()) 956 return; 957 958 auto *Source = Ctx.getExternalSource(); 959 assert(Source && "lazy initializers but no external source"); 960 961 auto LazyInits = std::move(LazyInitializers); 962 LazyInitializers.clear(); 963 964 for (auto ID : LazyInits) 965 Initializers.push_back(Source->GetExternalDecl(ID)); 966 967 assert(LazyInitializers.empty() && 968 "GetExternalDecl for lazy module initializer added more inits"); 969 } 970 971 void ASTContext::addModuleInitializer(Module *M, Decl *D) { 972 // One special case: if we add a module initializer that imports another 973 // module, and that module's only initializer is an ImportDecl, simplify. 974 if (const auto *ID = dyn_cast<ImportDecl>(D)) { 975 auto It = ModuleInitializers.find(ID->getImportedModule()); 976 977 // Maybe the ImportDecl does nothing at all. (Common case.) 978 if (It == ModuleInitializers.end()) 979 return; 980 981 // Maybe the ImportDecl only imports another ImportDecl. 982 auto &Imported = *It->second; 983 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) { 984 Imported.resolve(*this); 985 auto *OnlyDecl = Imported.Initializers.front(); 986 if (isa<ImportDecl>(OnlyDecl)) 987 D = OnlyDecl; 988 } 989 } 990 991 auto *&Inits = ModuleInitializers[M]; 992 if (!Inits) 993 Inits = new (*this) PerModuleInitializers; 994 Inits->Initializers.push_back(D); 995 } 996 997 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) { 998 auto *&Inits = ModuleInitializers[M]; 999 if (!Inits) 1000 Inits = new (*this) PerModuleInitializers; 1001 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(), 1002 IDs.begin(), IDs.end()); 1003 } 1004 1005 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) { 1006 auto It = ModuleInitializers.find(M); 1007 if (It == ModuleInitializers.end()) 1008 return None; 1009 1010 auto *Inits = It->second; 1011 Inits->resolve(*this); 1012 return Inits->Initializers; 1013 } 1014 1015 ExternCContextDecl *ASTContext::getExternCContextDecl() const { 1016 if (!ExternCContext) 1017 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl()); 1018 1019 return ExternCContext; 1020 } 1021 1022 BuiltinTemplateDecl * 1023 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, 1024 const IdentifierInfo *II) const { 1025 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK); 1026 BuiltinTemplate->setImplicit(); 1027 TUDecl->addDecl(BuiltinTemplate); 1028 1029 return BuiltinTemplate; 1030 } 1031 1032 BuiltinTemplateDecl * 1033 ASTContext::getMakeIntegerSeqDecl() const { 1034 if (!MakeIntegerSeqDecl) 1035 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq, 1036 getMakeIntegerSeqName()); 1037 return MakeIntegerSeqDecl; 1038 } 1039 1040 BuiltinTemplateDecl * 1041 ASTContext::getTypePackElementDecl() const { 1042 if (!TypePackElementDecl) 1043 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element, 1044 getTypePackElementName()); 1045 return TypePackElementDecl; 1046 } 1047 1048 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name, 1049 RecordDecl::TagKind TK) const { 1050 SourceLocation Loc; 1051 RecordDecl *NewDecl; 1052 if (getLangOpts().CPlusPlus) 1053 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, 1054 Loc, &Idents.get(Name)); 1055 else 1056 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc, 1057 &Idents.get(Name)); 1058 NewDecl->setImplicit(); 1059 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit( 1060 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default)); 1061 return NewDecl; 1062 } 1063 1064 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T, 1065 StringRef Name) const { 1066 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 1067 TypedefDecl *NewDecl = TypedefDecl::Create( 1068 const_cast<ASTContext &>(*this), getTranslationUnitDecl(), 1069 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo); 1070 NewDecl->setImplicit(); 1071 return NewDecl; 1072 } 1073 1074 TypedefDecl *ASTContext::getInt128Decl() const { 1075 if (!Int128Decl) 1076 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t"); 1077 return Int128Decl; 1078 } 1079 1080 TypedefDecl *ASTContext::getUInt128Decl() const { 1081 if (!UInt128Decl) 1082 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t"); 1083 return UInt128Decl; 1084 } 1085 1086 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 1087 auto *Ty = new (*this, TypeAlignment) BuiltinType(K); 1088 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 1089 Types.push_back(Ty); 1090 } 1091 1092 void ASTContext::InitBuiltinTypes(const TargetInfo &Target, 1093 const TargetInfo *AuxTarget) { 1094 assert((!this->Target || this->Target == &Target) && 1095 "Incorrect target reinitialization"); 1096 assert(VoidTy.isNull() && "Context reinitialized?"); 1097 1098 this->Target = &Target; 1099 this->AuxTarget = AuxTarget; 1100 1101 ABI.reset(createCXXABI(Target)); 1102 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 1103 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); 1104 1105 // C99 6.2.5p19. 1106 InitBuiltinType(VoidTy, BuiltinType::Void); 1107 1108 // C99 6.2.5p2. 1109 InitBuiltinType(BoolTy, BuiltinType::Bool); 1110 // C99 6.2.5p3. 1111 if (LangOpts.CharIsSigned) 1112 InitBuiltinType(CharTy, BuiltinType::Char_S); 1113 else 1114 InitBuiltinType(CharTy, BuiltinType::Char_U); 1115 // C99 6.2.5p4. 1116 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 1117 InitBuiltinType(ShortTy, BuiltinType::Short); 1118 InitBuiltinType(IntTy, BuiltinType::Int); 1119 InitBuiltinType(LongTy, BuiltinType::Long); 1120 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 1121 1122 // C99 6.2.5p6. 1123 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 1124 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 1125 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 1126 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 1127 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 1128 1129 // C99 6.2.5p10. 1130 InitBuiltinType(FloatTy, BuiltinType::Float); 1131 InitBuiltinType(DoubleTy, BuiltinType::Double); 1132 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 1133 1134 // GNU extension, __float128 for IEEE quadruple precision 1135 InitBuiltinType(Float128Ty, BuiltinType::Float128); 1136 1137 // C11 extension ISO/IEC TS 18661-3 1138 InitBuiltinType(Float16Ty, BuiltinType::Float16); 1139 1140 // ISO/IEC JTC1 SC22 WG14 N1169 Extension 1141 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum); 1142 InitBuiltinType(AccumTy, BuiltinType::Accum); 1143 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum); 1144 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum); 1145 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum); 1146 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum); 1147 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract); 1148 InitBuiltinType(FractTy, BuiltinType::Fract); 1149 InitBuiltinType(LongFractTy, BuiltinType::LongFract); 1150 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract); 1151 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract); 1152 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract); 1153 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum); 1154 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum); 1155 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum); 1156 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum); 1157 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum); 1158 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum); 1159 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract); 1160 InitBuiltinType(SatFractTy, BuiltinType::SatFract); 1161 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract); 1162 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract); 1163 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract); 1164 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract); 1165 1166 // GNU extension, 128-bit integers. 1167 InitBuiltinType(Int128Ty, BuiltinType::Int128); 1168 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 1169 1170 // C++ 3.9.1p5 1171 if (TargetInfo::isTypeSigned(Target.getWCharType())) 1172 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 1173 else // -fshort-wchar makes wchar_t be unsigned. 1174 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 1175 if (LangOpts.CPlusPlus && LangOpts.WChar) 1176 WideCharTy = WCharTy; 1177 else { 1178 // C99 (or C++ using -fno-wchar). 1179 WideCharTy = getFromTargetType(Target.getWCharType()); 1180 } 1181 1182 WIntTy = getFromTargetType(Target.getWIntType()); 1183 1184 // C++20 (proposed) 1185 InitBuiltinType(Char8Ty, BuiltinType::Char8); 1186 1187 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1188 InitBuiltinType(Char16Ty, BuiltinType::Char16); 1189 else // C99 1190 Char16Ty = getFromTargetType(Target.getChar16Type()); 1191 1192 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1193 InitBuiltinType(Char32Ty, BuiltinType::Char32); 1194 else // C99 1195 Char32Ty = getFromTargetType(Target.getChar32Type()); 1196 1197 // Placeholder type for type-dependent expressions whose type is 1198 // completely unknown. No code should ever check a type against 1199 // DependentTy and users should never see it; however, it is here to 1200 // help diagnose failures to properly check for type-dependent 1201 // expressions. 1202 InitBuiltinType(DependentTy, BuiltinType::Dependent); 1203 1204 // Placeholder type for functions. 1205 InitBuiltinType(OverloadTy, BuiltinType::Overload); 1206 1207 // Placeholder type for bound members. 1208 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 1209 1210 // Placeholder type for pseudo-objects. 1211 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 1212 1213 // "any" type; useful for debugger-like clients. 1214 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 1215 1216 // Placeholder type for unbridged ARC casts. 1217 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 1218 1219 // Placeholder type for builtin functions. 1220 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); 1221 1222 // Placeholder type for OMP array sections. 1223 if (LangOpts.OpenMP) 1224 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection); 1225 1226 // C99 6.2.5p11. 1227 FloatComplexTy = getComplexType(FloatTy); 1228 DoubleComplexTy = getComplexType(DoubleTy); 1229 LongDoubleComplexTy = getComplexType(LongDoubleTy); 1230 Float128ComplexTy = getComplexType(Float128Ty); 1231 1232 // Builtin types for 'id', 'Class', and 'SEL'. 1233 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 1234 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 1235 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 1236 1237 if (LangOpts.OpenCL) { 1238 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1239 InitBuiltinType(SingletonId, BuiltinType::Id); 1240 #include "clang/Basic/OpenCLImageTypes.def" 1241 1242 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); 1243 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent); 1244 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent); 1245 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue); 1246 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID); 1247 } 1248 1249 // Builtin type for __objc_yes and __objc_no 1250 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 1251 SignedCharTy : BoolTy); 1252 1253 ObjCConstantStringType = QualType(); 1254 1255 ObjCSuperType = QualType(); 1256 1257 // void * type 1258 if (LangOpts.OpenCLVersion >= 200) { 1259 auto Q = VoidTy.getQualifiers(); 1260 Q.setAddressSpace(LangAS::opencl_generic); 1261 VoidPtrTy = getPointerType(getCanonicalType( 1262 getQualifiedType(VoidTy.getUnqualifiedType(), Q))); 1263 } else { 1264 VoidPtrTy = getPointerType(VoidTy); 1265 } 1266 1267 // nullptr type (C++0x 2.14.7) 1268 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 1269 1270 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 1271 InitBuiltinType(HalfTy, BuiltinType::Half); 1272 1273 // Builtin type used to help define __builtin_va_list. 1274 VaListTagDecl = nullptr; 1275 } 1276 1277 DiagnosticsEngine &ASTContext::getDiagnostics() const { 1278 return SourceMgr.getDiagnostics(); 1279 } 1280 1281 AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 1282 AttrVec *&Result = DeclAttrs[D]; 1283 if (!Result) { 1284 void *Mem = Allocate(sizeof(AttrVec)); 1285 Result = new (Mem) AttrVec; 1286 } 1287 1288 return *Result; 1289 } 1290 1291 /// Erase the attributes corresponding to the given declaration. 1292 void ASTContext::eraseDeclAttrs(const Decl *D) { 1293 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 1294 if (Pos != DeclAttrs.end()) { 1295 Pos->second->~AttrVec(); 1296 DeclAttrs.erase(Pos); 1297 } 1298 } 1299 1300 // FIXME: Remove ? 1301 MemberSpecializationInfo * 1302 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 1303 assert(Var->isStaticDataMember() && "Not a static data member"); 1304 return getTemplateOrSpecializationInfo(Var) 1305 .dyn_cast<MemberSpecializationInfo *>(); 1306 } 1307 1308 ASTContext::TemplateOrSpecializationInfo 1309 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) { 1310 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos = 1311 TemplateOrInstantiation.find(Var); 1312 if (Pos == TemplateOrInstantiation.end()) 1313 return {}; 1314 1315 return Pos->second; 1316 } 1317 1318 void 1319 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 1320 TemplateSpecializationKind TSK, 1321 SourceLocation PointOfInstantiation) { 1322 assert(Inst->isStaticDataMember() && "Not a static data member"); 1323 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 1324 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo( 1325 Tmpl, TSK, PointOfInstantiation)); 1326 } 1327 1328 void 1329 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst, 1330 TemplateOrSpecializationInfo TSI) { 1331 assert(!TemplateOrInstantiation[Inst] && 1332 "Already noted what the variable was instantiated from"); 1333 TemplateOrInstantiation[Inst] = TSI; 1334 } 1335 1336 FunctionDecl *ASTContext::getClassScopeSpecializationPattern( 1337 const FunctionDecl *FD){ 1338 assert(FD && "Specialization is 0"); 1339 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos 1340 = ClassScopeSpecializationPattern.find(FD); 1341 if (Pos == ClassScopeSpecializationPattern.end()) 1342 return nullptr; 1343 1344 return Pos->second; 1345 } 1346 1347 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD, 1348 FunctionDecl *Pattern) { 1349 assert(FD && "Specialization is 0"); 1350 assert(Pattern && "Class scope specialization pattern is 0"); 1351 ClassScopeSpecializationPattern[FD] = Pattern; 1352 } 1353 1354 NamedDecl * 1355 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) { 1356 auto Pos = InstantiatedFromUsingDecl.find(UUD); 1357 if (Pos == InstantiatedFromUsingDecl.end()) 1358 return nullptr; 1359 1360 return Pos->second; 1361 } 1362 1363 void 1364 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) { 1365 assert((isa<UsingDecl>(Pattern) || 1366 isa<UnresolvedUsingValueDecl>(Pattern) || 1367 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 1368 "pattern decl is not a using decl"); 1369 assert((isa<UsingDecl>(Inst) || 1370 isa<UnresolvedUsingValueDecl>(Inst) || 1371 isa<UnresolvedUsingTypenameDecl>(Inst)) && 1372 "instantiation did not produce a using decl"); 1373 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 1374 InstantiatedFromUsingDecl[Inst] = Pattern; 1375 } 1376 1377 UsingShadowDecl * 1378 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 1379 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 1380 = InstantiatedFromUsingShadowDecl.find(Inst); 1381 if (Pos == InstantiatedFromUsingShadowDecl.end()) 1382 return nullptr; 1383 1384 return Pos->second; 1385 } 1386 1387 void 1388 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 1389 UsingShadowDecl *Pattern) { 1390 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 1391 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 1392 } 1393 1394 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 1395 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 1396 = InstantiatedFromUnnamedFieldDecl.find(Field); 1397 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 1398 return nullptr; 1399 1400 return Pos->second; 1401 } 1402 1403 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 1404 FieldDecl *Tmpl) { 1405 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 1406 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 1407 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 1408 "Already noted what unnamed field was instantiated from"); 1409 1410 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 1411 } 1412 1413 ASTContext::overridden_cxx_method_iterator 1414 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 1415 return overridden_methods(Method).begin(); 1416 } 1417 1418 ASTContext::overridden_cxx_method_iterator 1419 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 1420 return overridden_methods(Method).end(); 1421 } 1422 1423 unsigned 1424 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 1425 auto Range = overridden_methods(Method); 1426 return Range.end() - Range.begin(); 1427 } 1428 1429 ASTContext::overridden_method_range 1430 ASTContext::overridden_methods(const CXXMethodDecl *Method) const { 1431 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos = 1432 OverriddenMethods.find(Method->getCanonicalDecl()); 1433 if (Pos == OverriddenMethods.end()) 1434 return overridden_method_range(nullptr, nullptr); 1435 return overridden_method_range(Pos->second.begin(), Pos->second.end()); 1436 } 1437 1438 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 1439 const CXXMethodDecl *Overridden) { 1440 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); 1441 OverriddenMethods[Method].push_back(Overridden); 1442 } 1443 1444 void ASTContext::getOverriddenMethods( 1445 const NamedDecl *D, 1446 SmallVectorImpl<const NamedDecl *> &Overridden) const { 1447 assert(D); 1448 1449 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 1450 Overridden.append(overridden_methods_begin(CXXMethod), 1451 overridden_methods_end(CXXMethod)); 1452 return; 1453 } 1454 1455 const auto *Method = dyn_cast<ObjCMethodDecl>(D); 1456 if (!Method) 1457 return; 1458 1459 SmallVector<const ObjCMethodDecl *, 8> OverDecls; 1460 Method->getOverriddenMethods(OverDecls); 1461 Overridden.append(OverDecls.begin(), OverDecls.end()); 1462 } 1463 1464 void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 1465 assert(!Import->NextLocalImport && "Import declaration already in the chain"); 1466 assert(!Import->isFromASTFile() && "Non-local import declaration"); 1467 if (!FirstLocalImport) { 1468 FirstLocalImport = Import; 1469 LastLocalImport = Import; 1470 return; 1471 } 1472 1473 LastLocalImport->NextLocalImport = Import; 1474 LastLocalImport = Import; 1475 } 1476 1477 //===----------------------------------------------------------------------===// 1478 // Type Sizing and Analysis 1479 //===----------------------------------------------------------------------===// 1480 1481 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 1482 /// scalar floating point type. 1483 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 1484 const auto *BT = T->getAs<BuiltinType>(); 1485 assert(BT && "Not a floating point type!"); 1486 switch (BT->getKind()) { 1487 default: llvm_unreachable("Not a floating point type!"); 1488 case BuiltinType::Float16: 1489 case BuiltinType::Half: 1490 return Target->getHalfFormat(); 1491 case BuiltinType::Float: return Target->getFloatFormat(); 1492 case BuiltinType::Double: return Target->getDoubleFormat(); 1493 case BuiltinType::LongDouble: return Target->getLongDoubleFormat(); 1494 case BuiltinType::Float128: return Target->getFloat128Format(); 1495 } 1496 } 1497 1498 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { 1499 unsigned Align = Target->getCharWidth(); 1500 1501 bool UseAlignAttrOnly = false; 1502 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 1503 Align = AlignFromAttr; 1504 1505 // __attribute__((aligned)) can increase or decrease alignment 1506 // *except* on a struct or struct member, where it only increases 1507 // alignment unless 'packed' is also specified. 1508 // 1509 // It is an error for alignas to decrease alignment, so we can 1510 // ignore that possibility; Sema should diagnose it. 1511 if (isa<FieldDecl>(D)) { 1512 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 1513 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1514 } else { 1515 UseAlignAttrOnly = true; 1516 } 1517 } 1518 else if (isa<FieldDecl>(D)) 1519 UseAlignAttrOnly = 1520 D->hasAttr<PackedAttr>() || 1521 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1522 1523 // If we're using the align attribute only, just ignore everything 1524 // else about the declaration and its type. 1525 if (UseAlignAttrOnly) { 1526 // do nothing 1527 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) { 1528 QualType T = VD->getType(); 1529 if (const auto *RT = T->getAs<ReferenceType>()) { 1530 if (ForAlignof) 1531 T = RT->getPointeeType(); 1532 else 1533 T = getPointerType(RT->getPointeeType()); 1534 } 1535 QualType BaseT = getBaseElementType(T); 1536 if (T->isFunctionType()) 1537 Align = getTypeInfoImpl(T.getTypePtr()).Align; 1538 else if (!BaseT->isIncompleteType()) { 1539 // Adjust alignments of declarations with array type by the 1540 // large-array alignment on the target. 1541 if (const ArrayType *arrayType = getAsArrayType(T)) { 1542 unsigned MinWidth = Target->getLargeArrayMinWidth(); 1543 if (!ForAlignof && MinWidth) { 1544 if (isa<VariableArrayType>(arrayType)) 1545 Align = std::max(Align, Target->getLargeArrayAlign()); 1546 else if (isa<ConstantArrayType>(arrayType) && 1547 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 1548 Align = std::max(Align, Target->getLargeArrayAlign()); 1549 } 1550 } 1551 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 1552 if (BaseT.getQualifiers().hasUnaligned()) 1553 Align = Target->getCharWidth(); 1554 if (const auto *VD = dyn_cast<VarDecl>(D)) { 1555 if (VD->hasGlobalStorage() && !ForAlignof) 1556 Align = std::max(Align, getTargetInfo().getMinGlobalAlign()); 1557 } 1558 } 1559 1560 // Fields can be subject to extra alignment constraints, like if 1561 // the field is packed, the struct is packed, or the struct has a 1562 // a max-field-alignment constraint (#pragma pack). So calculate 1563 // the actual alignment of the field within the struct, and then 1564 // (as we're expected to) constrain that by the alignment of the type. 1565 if (const auto *Field = dyn_cast<FieldDecl>(VD)) { 1566 const RecordDecl *Parent = Field->getParent(); 1567 // We can only produce a sensible answer if the record is valid. 1568 if (!Parent->isInvalidDecl()) { 1569 const ASTRecordLayout &Layout = getASTRecordLayout(Parent); 1570 1571 // Start with the record's overall alignment. 1572 unsigned FieldAlign = toBits(Layout.getAlignment()); 1573 1574 // Use the GCD of that and the offset within the record. 1575 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex()); 1576 if (Offset > 0) { 1577 // Alignment is always a power of 2, so the GCD will be a power of 2, 1578 // which means we get to do this crazy thing instead of Euclid's. 1579 uint64_t LowBitOfOffset = Offset & (~Offset + 1); 1580 if (LowBitOfOffset < FieldAlign) 1581 FieldAlign = static_cast<unsigned>(LowBitOfOffset); 1582 } 1583 1584 Align = std::min(Align, FieldAlign); 1585 } 1586 } 1587 } 1588 1589 return toCharUnitsFromBits(Align); 1590 } 1591 1592 // getTypeInfoDataSizeInChars - Return the size of a type, in 1593 // chars. If the type is a record, its data size is returned. This is 1594 // the size of the memcpy that's performed when assigning this type 1595 // using a trivial copy/move assignment operator. 1596 std::pair<CharUnits, CharUnits> 1597 ASTContext::getTypeInfoDataSizeInChars(QualType T) const { 1598 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T); 1599 1600 // In C++, objects can sometimes be allocated into the tail padding 1601 // of a base-class subobject. We decide whether that's possible 1602 // during class layout, so here we can just trust the layout results. 1603 if (getLangOpts().CPlusPlus) { 1604 if (const auto *RT = T->getAs<RecordType>()) { 1605 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); 1606 sizeAndAlign.first = layout.getDataSize(); 1607 } 1608 } 1609 1610 return sizeAndAlign; 1611 } 1612 1613 /// getConstantArrayInfoInChars - Performing the computation in CharUnits 1614 /// instead of in bits prevents overflowing the uint64_t for some large arrays. 1615 std::pair<CharUnits, CharUnits> 1616 static getConstantArrayInfoInChars(const ASTContext &Context, 1617 const ConstantArrayType *CAT) { 1618 std::pair<CharUnits, CharUnits> EltInfo = 1619 Context.getTypeInfoInChars(CAT->getElementType()); 1620 uint64_t Size = CAT->getSize().getZExtValue(); 1621 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <= 1622 (uint64_t)(-1)/Size) && 1623 "Overflow in array type char size evaluation"); 1624 uint64_t Width = EltInfo.first.getQuantity() * Size; 1625 unsigned Align = EltInfo.second.getQuantity(); 1626 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() || 1627 Context.getTargetInfo().getPointerWidth(0) == 64) 1628 Width = llvm::alignTo(Width, Align); 1629 return std::make_pair(CharUnits::fromQuantity(Width), 1630 CharUnits::fromQuantity(Align)); 1631 } 1632 1633 std::pair<CharUnits, CharUnits> 1634 ASTContext::getTypeInfoInChars(const Type *T) const { 1635 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) 1636 return getConstantArrayInfoInChars(*this, CAT); 1637 TypeInfo Info = getTypeInfo(T); 1638 return std::make_pair(toCharUnitsFromBits(Info.Width), 1639 toCharUnitsFromBits(Info.Align)); 1640 } 1641 1642 std::pair<CharUnits, CharUnits> 1643 ASTContext::getTypeInfoInChars(QualType T) const { 1644 return getTypeInfoInChars(T.getTypePtr()); 1645 } 1646 1647 bool ASTContext::isAlignmentRequired(const Type *T) const { 1648 return getTypeInfo(T).AlignIsRequired; 1649 } 1650 1651 bool ASTContext::isAlignmentRequired(QualType T) const { 1652 return isAlignmentRequired(T.getTypePtr()); 1653 } 1654 1655 unsigned ASTContext::getTypeAlignIfKnown(QualType T) const { 1656 // An alignment on a typedef overrides anything else. 1657 if (const auto *TT = T->getAs<TypedefType>()) 1658 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1659 return Align; 1660 1661 // If we have an (array of) complete type, we're done. 1662 T = getBaseElementType(T); 1663 if (!T->isIncompleteType()) 1664 return getTypeAlign(T); 1665 1666 // If we had an array type, its element type might be a typedef 1667 // type with an alignment attribute. 1668 if (const auto *TT = T->getAs<TypedefType>()) 1669 if (unsigned Align = TT->getDecl()->getMaxAlignment()) 1670 return Align; 1671 1672 // Otherwise, see if the declaration of the type had an attribute. 1673 if (const auto *TT = T->getAs<TagType>()) 1674 return TT->getDecl()->getMaxAlignment(); 1675 1676 return 0; 1677 } 1678 1679 TypeInfo ASTContext::getTypeInfo(const Type *T) const { 1680 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T); 1681 if (I != MemoizedTypeInfo.end()) 1682 return I->second; 1683 1684 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup. 1685 TypeInfo TI = getTypeInfoImpl(T); 1686 MemoizedTypeInfo[T] = TI; 1687 return TI; 1688 } 1689 1690 /// getTypeInfoImpl - Return the size of the specified type, in bits. This 1691 /// method does not work on incomplete types. 1692 /// 1693 /// FIXME: Pointers into different addr spaces could have different sizes and 1694 /// alignment requirements: getPointerInfo should take an AddrSpace, this 1695 /// should take a QualType, &c. 1696 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { 1697 uint64_t Width = 0; 1698 unsigned Align = 8; 1699 bool AlignIsRequired = false; 1700 unsigned AS = 0; 1701 switch (T->getTypeClass()) { 1702 #define TYPE(Class, Base) 1703 #define ABSTRACT_TYPE(Class, Base) 1704 #define NON_CANONICAL_TYPE(Class, Base) 1705 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1706 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \ 1707 case Type::Class: \ 1708 assert(!T->isDependentType() && "should not see dependent types here"); \ 1709 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr()); 1710 #include "clang/AST/TypeNodes.def" 1711 llvm_unreachable("Should not see dependent types"); 1712 1713 case Type::FunctionNoProto: 1714 case Type::FunctionProto: 1715 // GCC extension: alignof(function) = 32 bits 1716 Width = 0; 1717 Align = 32; 1718 break; 1719 1720 case Type::IncompleteArray: 1721 case Type::VariableArray: 1722 Width = 0; 1723 Align = getTypeAlign(cast<ArrayType>(T)->getElementType()); 1724 break; 1725 1726 case Type::ConstantArray: { 1727 const auto *CAT = cast<ConstantArrayType>(T); 1728 1729 TypeInfo EltInfo = getTypeInfo(CAT->getElementType()); 1730 uint64_t Size = CAT->getSize().getZExtValue(); 1731 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && 1732 "Overflow in array type bit size evaluation"); 1733 Width = EltInfo.Width * Size; 1734 Align = EltInfo.Align; 1735 if (!getTargetInfo().getCXXABI().isMicrosoft() || 1736 getTargetInfo().getPointerWidth(0) == 64) 1737 Width = llvm::alignTo(Width, Align); 1738 break; 1739 } 1740 case Type::ExtVector: 1741 case Type::Vector: { 1742 const auto *VT = cast<VectorType>(T); 1743 TypeInfo EltInfo = getTypeInfo(VT->getElementType()); 1744 Width = EltInfo.Width * VT->getNumElements(); 1745 Align = Width; 1746 // If the alignment is not a power of 2, round up to the next power of 2. 1747 // This happens for non-power-of-2 length vectors. 1748 if (Align & (Align-1)) { 1749 Align = llvm::NextPowerOf2(Align); 1750 Width = llvm::alignTo(Width, Align); 1751 } 1752 // Adjust the alignment based on the target max. 1753 uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); 1754 if (TargetVectorAlign && TargetVectorAlign < Align) 1755 Align = TargetVectorAlign; 1756 break; 1757 } 1758 1759 case Type::Builtin: 1760 switch (cast<BuiltinType>(T)->getKind()) { 1761 default: llvm_unreachable("Unknown builtin type!"); 1762 case BuiltinType::Void: 1763 // GCC extension: alignof(void) = 8 bits. 1764 Width = 0; 1765 Align = 8; 1766 break; 1767 case BuiltinType::Bool: 1768 Width = Target->getBoolWidth(); 1769 Align = Target->getBoolAlign(); 1770 break; 1771 case BuiltinType::Char_S: 1772 case BuiltinType::Char_U: 1773 case BuiltinType::UChar: 1774 case BuiltinType::SChar: 1775 case BuiltinType::Char8: 1776 Width = Target->getCharWidth(); 1777 Align = Target->getCharAlign(); 1778 break; 1779 case BuiltinType::WChar_S: 1780 case BuiltinType::WChar_U: 1781 Width = Target->getWCharWidth(); 1782 Align = Target->getWCharAlign(); 1783 break; 1784 case BuiltinType::Char16: 1785 Width = Target->getChar16Width(); 1786 Align = Target->getChar16Align(); 1787 break; 1788 case BuiltinType::Char32: 1789 Width = Target->getChar32Width(); 1790 Align = Target->getChar32Align(); 1791 break; 1792 case BuiltinType::UShort: 1793 case BuiltinType::Short: 1794 Width = Target->getShortWidth(); 1795 Align = Target->getShortAlign(); 1796 break; 1797 case BuiltinType::UInt: 1798 case BuiltinType::Int: 1799 Width = Target->getIntWidth(); 1800 Align = Target->getIntAlign(); 1801 break; 1802 case BuiltinType::ULong: 1803 case BuiltinType::Long: 1804 Width = Target->getLongWidth(); 1805 Align = Target->getLongAlign(); 1806 break; 1807 case BuiltinType::ULongLong: 1808 case BuiltinType::LongLong: 1809 Width = Target->getLongLongWidth(); 1810 Align = Target->getLongLongAlign(); 1811 break; 1812 case BuiltinType::Int128: 1813 case BuiltinType::UInt128: 1814 Width = 128; 1815 Align = 128; // int128_t is 128-bit aligned on all targets. 1816 break; 1817 case BuiltinType::ShortAccum: 1818 case BuiltinType::UShortAccum: 1819 case BuiltinType::SatShortAccum: 1820 case BuiltinType::SatUShortAccum: 1821 Width = Target->getShortAccumWidth(); 1822 Align = Target->getShortAccumAlign(); 1823 break; 1824 case BuiltinType::Accum: 1825 case BuiltinType::UAccum: 1826 case BuiltinType::SatAccum: 1827 case BuiltinType::SatUAccum: 1828 Width = Target->getAccumWidth(); 1829 Align = Target->getAccumAlign(); 1830 break; 1831 case BuiltinType::LongAccum: 1832 case BuiltinType::ULongAccum: 1833 case BuiltinType::SatLongAccum: 1834 case BuiltinType::SatULongAccum: 1835 Width = Target->getLongAccumWidth(); 1836 Align = Target->getLongAccumAlign(); 1837 break; 1838 case BuiltinType::ShortFract: 1839 case BuiltinType::UShortFract: 1840 case BuiltinType::SatShortFract: 1841 case BuiltinType::SatUShortFract: 1842 Width = Target->getShortFractWidth(); 1843 Align = Target->getShortFractAlign(); 1844 break; 1845 case BuiltinType::Fract: 1846 case BuiltinType::UFract: 1847 case BuiltinType::SatFract: 1848 case BuiltinType::SatUFract: 1849 Width = Target->getFractWidth(); 1850 Align = Target->getFractAlign(); 1851 break; 1852 case BuiltinType::LongFract: 1853 case BuiltinType::ULongFract: 1854 case BuiltinType::SatLongFract: 1855 case BuiltinType::SatULongFract: 1856 Width = Target->getLongFractWidth(); 1857 Align = Target->getLongFractAlign(); 1858 break; 1859 case BuiltinType::Float16: 1860 case BuiltinType::Half: 1861 Width = Target->getHalfWidth(); 1862 Align = Target->getHalfAlign(); 1863 break; 1864 case BuiltinType::Float: 1865 Width = Target->getFloatWidth(); 1866 Align = Target->getFloatAlign(); 1867 break; 1868 case BuiltinType::Double: 1869 Width = Target->getDoubleWidth(); 1870 Align = Target->getDoubleAlign(); 1871 break; 1872 case BuiltinType::LongDouble: 1873 Width = Target->getLongDoubleWidth(); 1874 Align = Target->getLongDoubleAlign(); 1875 break; 1876 case BuiltinType::Float128: 1877 Width = Target->getFloat128Width(); 1878 Align = Target->getFloat128Align(); 1879 break; 1880 case BuiltinType::NullPtr: 1881 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 1882 Align = Target->getPointerAlign(0); // == sizeof(void*) 1883 break; 1884 case BuiltinType::ObjCId: 1885 case BuiltinType::ObjCClass: 1886 case BuiltinType::ObjCSel: 1887 Width = Target->getPointerWidth(0); 1888 Align = Target->getPointerAlign(0); 1889 break; 1890 case BuiltinType::OCLSampler: 1891 case BuiltinType::OCLEvent: 1892 case BuiltinType::OCLClkEvent: 1893 case BuiltinType::OCLQueue: 1894 case BuiltinType::OCLReserveID: 1895 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1896 case BuiltinType::Id: 1897 #include "clang/Basic/OpenCLImageTypes.def" 1898 AS = getTargetAddressSpace( 1899 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T))); 1900 Width = Target->getPointerWidth(AS); 1901 Align = Target->getPointerAlign(AS); 1902 break; 1903 } 1904 break; 1905 case Type::ObjCObjectPointer: 1906 Width = Target->getPointerWidth(0); 1907 Align = Target->getPointerAlign(0); 1908 break; 1909 case Type::BlockPointer: 1910 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType()); 1911 Width = Target->getPointerWidth(AS); 1912 Align = Target->getPointerAlign(AS); 1913 break; 1914 case Type::LValueReference: 1915 case Type::RValueReference: 1916 // alignof and sizeof should never enter this code path here, so we go 1917 // the pointer route. 1918 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType()); 1919 Width = Target->getPointerWidth(AS); 1920 Align = Target->getPointerAlign(AS); 1921 break; 1922 case Type::Pointer: 1923 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 1924 Width = Target->getPointerWidth(AS); 1925 Align = Target->getPointerAlign(AS); 1926 break; 1927 case Type::MemberPointer: { 1928 const auto *MPT = cast<MemberPointerType>(T); 1929 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT); 1930 Width = MPI.Width; 1931 Align = MPI.Align; 1932 break; 1933 } 1934 case Type::Complex: { 1935 // Complex types have the same alignment as their elements, but twice the 1936 // size. 1937 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType()); 1938 Width = EltInfo.Width * 2; 1939 Align = EltInfo.Align; 1940 break; 1941 } 1942 case Type::ObjCObject: 1943 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 1944 case Type::Adjusted: 1945 case Type::Decayed: 1946 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr()); 1947 case Type::ObjCInterface: { 1948 const auto *ObjCI = cast<ObjCInterfaceType>(T); 1949 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 1950 Width = toBits(Layout.getSize()); 1951 Align = toBits(Layout.getAlignment()); 1952 break; 1953 } 1954 case Type::Record: 1955 case Type::Enum: { 1956 const auto *TT = cast<TagType>(T); 1957 1958 if (TT->getDecl()->isInvalidDecl()) { 1959 Width = 8; 1960 Align = 8; 1961 break; 1962 } 1963 1964 if (const auto *ET = dyn_cast<EnumType>(TT)) { 1965 const EnumDecl *ED = ET->getDecl(); 1966 TypeInfo Info = 1967 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType()); 1968 if (unsigned AttrAlign = ED->getMaxAlignment()) { 1969 Info.Align = AttrAlign; 1970 Info.AlignIsRequired = true; 1971 } 1972 return Info; 1973 } 1974 1975 const auto *RT = cast<RecordType>(TT); 1976 const RecordDecl *RD = RT->getDecl(); 1977 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 1978 Width = toBits(Layout.getSize()); 1979 Align = toBits(Layout.getAlignment()); 1980 AlignIsRequired = RD->hasAttr<AlignedAttr>(); 1981 break; 1982 } 1983 1984 case Type::SubstTemplateTypeParm: 1985 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 1986 getReplacementType().getTypePtr()); 1987 1988 case Type::Auto: 1989 case Type::DeducedTemplateSpecialization: { 1990 const auto *A = cast<DeducedType>(T); 1991 assert(!A->getDeducedType().isNull() && 1992 "cannot request the size of an undeduced or dependent auto type"); 1993 return getTypeInfo(A->getDeducedType().getTypePtr()); 1994 } 1995 1996 case Type::Paren: 1997 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 1998 1999 case Type::ObjCTypeParam: 2000 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr()); 2001 2002 case Type::Typedef: { 2003 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 2004 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 2005 // If the typedef has an aligned attribute on it, it overrides any computed 2006 // alignment we have. This violates the GCC documentation (which says that 2007 // attribute(aligned) can only round up) but matches its implementation. 2008 if (unsigned AttrAlign = Typedef->getMaxAlignment()) { 2009 Align = AttrAlign; 2010 AlignIsRequired = true; 2011 } else { 2012 Align = Info.Align; 2013 AlignIsRequired = Info.AlignIsRequired; 2014 } 2015 Width = Info.Width; 2016 break; 2017 } 2018 2019 case Type::Elaborated: 2020 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 2021 2022 case Type::Attributed: 2023 return getTypeInfo( 2024 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 2025 2026 case Type::Atomic: { 2027 // Start with the base type information. 2028 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType()); 2029 Width = Info.Width; 2030 Align = Info.Align; 2031 2032 if (!Width) { 2033 // An otherwise zero-sized type should still generate an 2034 // atomic operation. 2035 Width = Target->getCharWidth(); 2036 assert(Align); 2037 } else if (Width <= Target->getMaxAtomicPromoteWidth()) { 2038 // If the size of the type doesn't exceed the platform's max 2039 // atomic promotion width, make the size and alignment more 2040 // favorable to atomic operations: 2041 2042 // Round the size up to a power of 2. 2043 if (!llvm::isPowerOf2_64(Width)) 2044 Width = llvm::NextPowerOf2(Width); 2045 2046 // Set the alignment equal to the size. 2047 Align = static_cast<unsigned>(Width); 2048 } 2049 } 2050 break; 2051 2052 case Type::Pipe: 2053 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global)); 2054 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global)); 2055 break; 2056 } 2057 2058 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 2059 return TypeInfo(Width, Align, AlignIsRequired); 2060 } 2061 2062 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const { 2063 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T); 2064 if (I != MemoizedUnadjustedAlign.end()) 2065 return I->second; 2066 2067 unsigned UnadjustedAlign; 2068 if (const auto *RT = T->getAs<RecordType>()) { 2069 const RecordDecl *RD = RT->getDecl(); 2070 const ASTRecordLayout &Layout = getASTRecordLayout(RD); 2071 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2072 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) { 2073 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 2074 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); 2075 } else { 2076 UnadjustedAlign = getTypeAlign(T); 2077 } 2078 2079 MemoizedUnadjustedAlign[T] = UnadjustedAlign; 2080 return UnadjustedAlign; 2081 } 2082 2083 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const { 2084 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign(); 2085 // Target ppc64 with QPX: simd default alignment for pointer to double is 32. 2086 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 || 2087 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) && 2088 getTargetInfo().getABI() == "elfv1-qpx" && 2089 T->isSpecificBuiltinType(BuiltinType::Double)) 2090 SimdAlign = 256; 2091 return SimdAlign; 2092 } 2093 2094 /// toCharUnitsFromBits - Convert a size in bits to a size in characters. 2095 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 2096 return CharUnits::fromQuantity(BitSize / getCharWidth()); 2097 } 2098 2099 /// toBits - Convert a size in characters to a size in characters. 2100 int64_t ASTContext::toBits(CharUnits CharSize) const { 2101 return CharSize.getQuantity() * getCharWidth(); 2102 } 2103 2104 /// getTypeSizeInChars - Return the size of the specified type, in characters. 2105 /// This method does not work on incomplete types. 2106 CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 2107 return getTypeInfoInChars(T).first; 2108 } 2109 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 2110 return getTypeInfoInChars(T).first; 2111 } 2112 2113 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 2114 /// characters. This method does not work on incomplete types. 2115 CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 2116 return toCharUnitsFromBits(getTypeAlign(T)); 2117 } 2118 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 2119 return toCharUnitsFromBits(getTypeAlign(T)); 2120 } 2121 2122 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a 2123 /// type, in characters, before alignment adustments. This method does 2124 /// not work on incomplete types. 2125 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const { 2126 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2127 } 2128 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const { 2129 return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); 2130 } 2131 2132 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified 2133 /// type for the current target in bits. This can be different than the ABI 2134 /// alignment in cases where it is beneficial for performance to overalign 2135 /// a data type. 2136 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 2137 TypeInfo TI = getTypeInfo(T); 2138 unsigned ABIAlign = TI.Align; 2139 2140 T = T->getBaseElementTypeUnsafe(); 2141 2142 // The preferred alignment of member pointers is that of a pointer. 2143 if (T->isMemberPointerType()) 2144 return getPreferredTypeAlign(getPointerDiffType().getTypePtr()); 2145 2146 if (!Target->allowsLargerPreferedTypeAlignment()) 2147 return ABIAlign; 2148 2149 // Double and long long should be naturally aligned if possible. 2150 if (const auto *CT = T->getAs<ComplexType>()) 2151 T = CT->getElementType().getTypePtr(); 2152 if (const auto *ET = T->getAs<EnumType>()) 2153 T = ET->getDecl()->getIntegerType().getTypePtr(); 2154 if (T->isSpecificBuiltinType(BuiltinType::Double) || 2155 T->isSpecificBuiltinType(BuiltinType::LongLong) || 2156 T->isSpecificBuiltinType(BuiltinType::ULongLong)) 2157 // Don't increase the alignment if an alignment attribute was specified on a 2158 // typedef declaration. 2159 if (!TI.AlignIsRequired) 2160 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 2161 2162 return ABIAlign; 2163 } 2164 2165 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment 2166 /// for __attribute__((aligned)) on this target, to be used if no alignment 2167 /// value is specified. 2168 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const { 2169 return getTargetInfo().getDefaultAlignForAttributeAligned(); 2170 } 2171 2172 /// getAlignOfGlobalVar - Return the alignment in bits that should be given 2173 /// to a global variable of the specified type. 2174 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const { 2175 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign()); 2176 } 2177 2178 /// getAlignOfGlobalVarInChars - Return the alignment in characters that 2179 /// should be given to a global variable of the specified type. 2180 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const { 2181 return toCharUnitsFromBits(getAlignOfGlobalVar(T)); 2182 } 2183 2184 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const { 2185 CharUnits Offset = CharUnits::Zero(); 2186 const ASTRecordLayout *Layout = &getASTRecordLayout(RD); 2187 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) { 2188 Offset += Layout->getBaseClassOffset(Base); 2189 Layout = &getASTRecordLayout(Base); 2190 } 2191 return Offset; 2192 } 2193 2194 /// DeepCollectObjCIvars - 2195 /// This routine first collects all declared, but not synthesized, ivars in 2196 /// super class and then collects all ivars, including those synthesized for 2197 /// current class. This routine is used for implementation of current class 2198 /// when all ivars, declared and synthesized are known. 2199 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 2200 bool leafClass, 2201 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 2202 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 2203 DeepCollectObjCIvars(SuperClass, false, Ivars); 2204 if (!leafClass) { 2205 for (const auto *I : OI->ivars()) 2206 Ivars.push_back(I); 2207 } else { 2208 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 2209 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 2210 Iv= Iv->getNextIvar()) 2211 Ivars.push_back(Iv); 2212 } 2213 } 2214 2215 /// CollectInheritedProtocols - Collect all protocols in current class and 2216 /// those inherited by it. 2217 void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 2218 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 2219 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 2220 // We can use protocol_iterator here instead of 2221 // all_referenced_protocol_iterator since we are walking all categories. 2222 for (auto *Proto : OI->all_referenced_protocols()) { 2223 CollectInheritedProtocols(Proto, Protocols); 2224 } 2225 2226 // Categories of this Interface. 2227 for (const auto *Cat : OI->visible_categories()) 2228 CollectInheritedProtocols(Cat, Protocols); 2229 2230 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 2231 while (SD) { 2232 CollectInheritedProtocols(SD, Protocols); 2233 SD = SD->getSuperClass(); 2234 } 2235 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 2236 for (auto *Proto : OC->protocols()) { 2237 CollectInheritedProtocols(Proto, Protocols); 2238 } 2239 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 2240 // Insert the protocol. 2241 if (!Protocols.insert( 2242 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second) 2243 return; 2244 2245 for (auto *Proto : OP->protocols()) 2246 CollectInheritedProtocols(Proto, Protocols); 2247 } 2248 } 2249 2250 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, 2251 const RecordDecl *RD) { 2252 assert(RD->isUnion() && "Must be union type"); 2253 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl()); 2254 2255 for (const auto *Field : RD->fields()) { 2256 if (!Context.hasUniqueObjectRepresentations(Field->getType())) 2257 return false; 2258 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType()); 2259 if (FieldSize != UnionSize) 2260 return false; 2261 } 2262 return !RD->field_empty(); 2263 } 2264 2265 static bool isStructEmpty(QualType Ty) { 2266 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl(); 2267 2268 if (!RD->field_empty()) 2269 return false; 2270 2271 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) 2272 return ClassDecl->isEmpty(); 2273 2274 return true; 2275 } 2276 2277 static llvm::Optional<int64_t> 2278 structHasUniqueObjectRepresentations(const ASTContext &Context, 2279 const RecordDecl *RD) { 2280 assert(!RD->isUnion() && "Must be struct/class type"); 2281 const auto &Layout = Context.getASTRecordLayout(RD); 2282 2283 int64_t CurOffsetInBits = 0; 2284 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) { 2285 if (ClassDecl->isDynamicClass()) 2286 return llvm::None; 2287 2288 SmallVector<std::pair<QualType, int64_t>, 4> Bases; 2289 for (const auto Base : ClassDecl->bases()) { 2290 // Empty types can be inherited from, and non-empty types can potentially 2291 // have tail padding, so just make sure there isn't an error. 2292 if (!isStructEmpty(Base.getType())) { 2293 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations( 2294 Context, Base.getType()->getAs<RecordType>()->getDecl()); 2295 if (!Size) 2296 return llvm::None; 2297 Bases.emplace_back(Base.getType(), Size.getValue()); 2298 } 2299 } 2300 2301 llvm::sort( 2302 Bases.begin(), Bases.end(), [&](const std::pair<QualType, int64_t> &L, 2303 const std::pair<QualType, int64_t> &R) { 2304 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) < 2305 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl()); 2306 }); 2307 2308 for (const auto Base : Bases) { 2309 int64_t BaseOffset = Context.toBits( 2310 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl())); 2311 int64_t BaseSize = Base.second; 2312 if (BaseOffset != CurOffsetInBits) 2313 return llvm::None; 2314 CurOffsetInBits = BaseOffset + BaseSize; 2315 } 2316 } 2317 2318 for (const auto *Field : RD->fields()) { 2319 if (!Field->getType()->isReferenceType() && 2320 !Context.hasUniqueObjectRepresentations(Field->getType())) 2321 return llvm::None; 2322 2323 int64_t FieldSizeInBits = 2324 Context.toBits(Context.getTypeSizeInChars(Field->getType())); 2325 if (Field->isBitField()) { 2326 int64_t BitfieldSize = Field->getBitWidthValue(Context); 2327 2328 if (BitfieldSize > FieldSizeInBits) 2329 return llvm::None; 2330 FieldSizeInBits = BitfieldSize; 2331 } 2332 2333 int64_t FieldOffsetInBits = Context.getFieldOffset(Field); 2334 2335 if (FieldOffsetInBits != CurOffsetInBits) 2336 return llvm::None; 2337 2338 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits; 2339 } 2340 2341 return CurOffsetInBits; 2342 } 2343 2344 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const { 2345 // C++17 [meta.unary.prop]: 2346 // The predicate condition for a template specialization 2347 // has_unique_object_representations<T> shall be 2348 // satisfied if and only if: 2349 // (9.1) - T is trivially copyable, and 2350 // (9.2) - any two objects of type T with the same value have the same 2351 // object representation, where two objects 2352 // of array or non-union class type are considered to have the same value 2353 // if their respective sequences of 2354 // direct subobjects have the same values, and two objects of union type 2355 // are considered to have the same 2356 // value if they have the same active member and the corresponding members 2357 // have the same value. 2358 // The set of scalar types for which this condition holds is 2359 // implementation-defined. [ Note: If a type has padding 2360 // bits, the condition does not hold; otherwise, the condition holds true 2361 // for unsigned integral types. -- end note ] 2362 assert(!Ty.isNull() && "Null QualType sent to unique object rep check"); 2363 2364 // Arrays are unique only if their element type is unique. 2365 if (Ty->isArrayType()) 2366 return hasUniqueObjectRepresentations(getBaseElementType(Ty)); 2367 2368 // (9.1) - T is trivially copyable... 2369 if (!Ty.isTriviallyCopyableType(*this)) 2370 return false; 2371 2372 // All integrals and enums are unique. 2373 if (Ty->isIntegralOrEnumerationType()) 2374 return true; 2375 2376 // All other pointers are unique. 2377 if (Ty->isPointerType()) 2378 return true; 2379 2380 if (Ty->isMemberPointerType()) { 2381 const auto *MPT = Ty->getAs<MemberPointerType>(); 2382 return !ABI->getMemberPointerInfo(MPT).HasPadding; 2383 } 2384 2385 if (Ty->isRecordType()) { 2386 const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl(); 2387 2388 if (Record->isInvalidDecl()) 2389 return false; 2390 2391 if (Record->isUnion()) 2392 return unionHasUniqueObjectRepresentations(*this, Record); 2393 2394 Optional<int64_t> StructSize = 2395 structHasUniqueObjectRepresentations(*this, Record); 2396 2397 return StructSize && 2398 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty)); 2399 } 2400 2401 // FIXME: More cases to handle here (list by rsmith): 2402 // vectors (careful about, eg, vector of 3 foo) 2403 // _Complex int and friends 2404 // _Atomic T 2405 // Obj-C block pointers 2406 // Obj-C object pointers 2407 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t, 2408 // clk_event_t, queue_t, reserve_id_t) 2409 // There're also Obj-C class types and the Obj-C selector type, but I think it 2410 // makes sense for those to return false here. 2411 2412 return false; 2413 } 2414 2415 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 2416 unsigned count = 0; 2417 // Count ivars declared in class extension. 2418 for (const auto *Ext : OI->known_extensions()) 2419 count += Ext->ivar_size(); 2420 2421 // Count ivar defined in this class's implementation. This 2422 // includes synthesized ivars. 2423 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 2424 count += ImplDecl->ivar_size(); 2425 2426 return count; 2427 } 2428 2429 bool ASTContext::isSentinelNullExpr(const Expr *E) { 2430 if (!E) 2431 return false; 2432 2433 // nullptr_t is always treated as null. 2434 if (E->getType()->isNullPtrType()) return true; 2435 2436 if (E->getType()->isAnyPointerType() && 2437 E->IgnoreParenCasts()->isNullPointerConstant(*this, 2438 Expr::NPC_ValueDependentIsNull)) 2439 return true; 2440 2441 // Unfortunately, __null has type 'int'. 2442 if (isa<GNUNullExpr>(E)) return true; 2443 2444 return false; 2445 } 2446 2447 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none 2448 /// exists. 2449 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 2450 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2451 I = ObjCImpls.find(D); 2452 if (I != ObjCImpls.end()) 2453 return cast<ObjCImplementationDecl>(I->second); 2454 return nullptr; 2455 } 2456 2457 /// Get the implementation of ObjCCategoryDecl, or nullptr if none 2458 /// exists. 2459 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 2460 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 2461 I = ObjCImpls.find(D); 2462 if (I != ObjCImpls.end()) 2463 return cast<ObjCCategoryImplDecl>(I->second); 2464 return nullptr; 2465 } 2466 2467 /// Set the implementation of ObjCInterfaceDecl. 2468 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 2469 ObjCImplementationDecl *ImplD) { 2470 assert(IFaceD && ImplD && "Passed null params"); 2471 ObjCImpls[IFaceD] = ImplD; 2472 } 2473 2474 /// Set the implementation of ObjCCategoryDecl. 2475 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 2476 ObjCCategoryImplDecl *ImplD) { 2477 assert(CatD && ImplD && "Passed null params"); 2478 ObjCImpls[CatD] = ImplD; 2479 } 2480 2481 const ObjCMethodDecl * 2482 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const { 2483 return ObjCMethodRedecls.lookup(MD); 2484 } 2485 2486 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD, 2487 const ObjCMethodDecl *Redecl) { 2488 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration"); 2489 ObjCMethodRedecls[MD] = Redecl; 2490 } 2491 2492 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( 2493 const NamedDecl *ND) const { 2494 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 2495 return ID; 2496 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 2497 return CD->getClassInterface(); 2498 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 2499 return IMD->getClassInterface(); 2500 2501 return nullptr; 2502 } 2503 2504 /// Get the copy initialization expression of VarDecl, or nullptr if 2505 /// none exists. 2506 ASTContext::BlockVarCopyInit 2507 ASTContext::getBlockVarCopyInit(const VarDecl*VD) const { 2508 assert(VD && "Passed null params"); 2509 assert(VD->hasAttr<BlocksAttr>() && 2510 "getBlockVarCopyInits - not __block var"); 2511 auto I = BlockVarCopyInits.find(VD); 2512 if (I != BlockVarCopyInits.end()) 2513 return I->second; 2514 return {nullptr, false}; 2515 } 2516 2517 /// Set the copy inialization expression of a block var decl. 2518 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr, 2519 bool CanThrow) { 2520 assert(VD && CopyExpr && "Passed null params"); 2521 assert(VD->hasAttr<BlocksAttr>() && 2522 "setBlockVarCopyInits - not __block var"); 2523 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow); 2524 } 2525 2526 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 2527 unsigned DataSize) const { 2528 if (!DataSize) 2529 DataSize = TypeLoc::getFullDataSizeForType(T); 2530 else 2531 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 2532 "incorrect data size provided to CreateTypeSourceInfo!"); 2533 2534 auto *TInfo = 2535 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 2536 new (TInfo) TypeSourceInfo(T); 2537 return TInfo; 2538 } 2539 2540 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 2541 SourceLocation L) const { 2542 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 2543 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 2544 return DI; 2545 } 2546 2547 const ASTRecordLayout & 2548 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 2549 return getObjCLayout(D, nullptr); 2550 } 2551 2552 const ASTRecordLayout & 2553 ASTContext::getASTObjCImplementationLayout( 2554 const ObjCImplementationDecl *D) const { 2555 return getObjCLayout(D->getClassInterface(), D); 2556 } 2557 2558 //===----------------------------------------------------------------------===// 2559 // Type creation/memoization methods 2560 //===----------------------------------------------------------------------===// 2561 2562 QualType 2563 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 2564 unsigned fastQuals = quals.getFastQualifiers(); 2565 quals.removeFastQualifiers(); 2566 2567 // Check if we've already instantiated this type. 2568 llvm::FoldingSetNodeID ID; 2569 ExtQuals::Profile(ID, baseType, quals); 2570 void *insertPos = nullptr; 2571 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 2572 assert(eq->getQualifiers() == quals); 2573 return QualType(eq, fastQuals); 2574 } 2575 2576 // If the base type is not canonical, make the appropriate canonical type. 2577 QualType canon; 2578 if (!baseType->isCanonicalUnqualified()) { 2579 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 2580 canonSplit.Quals.addConsistentQualifiers(quals); 2581 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 2582 2583 // Re-find the insert position. 2584 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 2585 } 2586 2587 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 2588 ExtQualNodes.InsertNode(eq, insertPos); 2589 return QualType(eq, fastQuals); 2590 } 2591 2592 QualType ASTContext::getAddrSpaceQualType(QualType T, 2593 LangAS AddressSpace) const { 2594 QualType CanT = getCanonicalType(T); 2595 if (CanT.getAddressSpace() == AddressSpace) 2596 return T; 2597 2598 // If we are composing extended qualifiers together, merge together 2599 // into one ExtQuals node. 2600 QualifierCollector Quals; 2601 const Type *TypeNode = Quals.strip(T); 2602 2603 // If this type already has an address space specified, it cannot get 2604 // another one. 2605 assert(!Quals.hasAddressSpace() && 2606 "Type cannot be in multiple addr spaces!"); 2607 Quals.addAddressSpace(AddressSpace); 2608 2609 return getExtQualType(TypeNode, Quals); 2610 } 2611 2612 QualType ASTContext::removeAddrSpaceQualType(QualType T) const { 2613 // If we are composing extended qualifiers together, merge together 2614 // into one ExtQuals node. 2615 QualifierCollector Quals; 2616 const Type *TypeNode = Quals.strip(T); 2617 2618 // If the qualifier doesn't have an address space just return it. 2619 if (!Quals.hasAddressSpace()) 2620 return T; 2621 2622 Quals.removeAddressSpace(); 2623 2624 // Removal of the address space can mean there are no longer any 2625 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts) 2626 // or required. 2627 if (Quals.hasNonFastQualifiers()) 2628 return getExtQualType(TypeNode, Quals); 2629 else 2630 return QualType(TypeNode, Quals.getFastQualifiers()); 2631 } 2632 2633 QualType ASTContext::getObjCGCQualType(QualType T, 2634 Qualifiers::GC GCAttr) const { 2635 QualType CanT = getCanonicalType(T); 2636 if (CanT.getObjCGCAttr() == GCAttr) 2637 return T; 2638 2639 if (const auto *ptr = T->getAs<PointerType>()) { 2640 QualType Pointee = ptr->getPointeeType(); 2641 if (Pointee->isAnyPointerType()) { 2642 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 2643 return getPointerType(ResultType); 2644 } 2645 } 2646 2647 // If we are composing extended qualifiers together, merge together 2648 // into one ExtQuals node. 2649 QualifierCollector Quals; 2650 const Type *TypeNode = Quals.strip(T); 2651 2652 // If this type already has an ObjCGC specified, it cannot get 2653 // another one. 2654 assert(!Quals.hasObjCGCAttr() && 2655 "Type cannot have multiple ObjCGCs!"); 2656 Quals.addObjCGCAttr(GCAttr); 2657 2658 return getExtQualType(TypeNode, Quals); 2659 } 2660 2661 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 2662 FunctionType::ExtInfo Info) { 2663 if (T->getExtInfo() == Info) 2664 return T; 2665 2666 QualType Result; 2667 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 2668 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info); 2669 } else { 2670 const auto *FPT = cast<FunctionProtoType>(T); 2671 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 2672 EPI.ExtInfo = Info; 2673 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI); 2674 } 2675 2676 return cast<FunctionType>(Result.getTypePtr()); 2677 } 2678 2679 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, 2680 QualType ResultType) { 2681 FD = FD->getMostRecentDecl(); 2682 while (true) { 2683 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 2684 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 2685 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI)); 2686 if (FunctionDecl *Next = FD->getPreviousDecl()) 2687 FD = Next; 2688 else 2689 break; 2690 } 2691 if (ASTMutationListener *L = getASTMutationListener()) 2692 L->DeducedReturnType(FD, ResultType); 2693 } 2694 2695 /// Get a function type and produce the equivalent function type with the 2696 /// specified exception specification. Type sugar that can be present on a 2697 /// declaration of a function with an exception specification is permitted 2698 /// and preserved. Other type sugar (for instance, typedefs) is not. 2699 QualType ASTContext::getFunctionTypeWithExceptionSpec( 2700 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) { 2701 // Might have some parens. 2702 if (const auto *PT = dyn_cast<ParenType>(Orig)) 2703 return getParenType( 2704 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI)); 2705 2706 // Might have a calling-convention attribute. 2707 if (const auto *AT = dyn_cast<AttributedType>(Orig)) 2708 return getAttributedType( 2709 AT->getAttrKind(), 2710 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI), 2711 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI)); 2712 2713 // Anything else must be a function type. Rebuild it with the new exception 2714 // specification. 2715 const auto *Proto = cast<FunctionProtoType>(Orig); 2716 return getFunctionType( 2717 Proto->getReturnType(), Proto->getParamTypes(), 2718 Proto->getExtProtoInfo().withExceptionSpec(ESI)); 2719 } 2720 2721 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T, 2722 QualType U) { 2723 return hasSameType(T, U) || 2724 (getLangOpts().CPlusPlus17 && 2725 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None), 2726 getFunctionTypeWithExceptionSpec(U, EST_None))); 2727 } 2728 2729 void ASTContext::adjustExceptionSpec( 2730 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, 2731 bool AsWritten) { 2732 // Update the type. 2733 QualType Updated = 2734 getFunctionTypeWithExceptionSpec(FD->getType(), ESI); 2735 FD->setType(Updated); 2736 2737 if (!AsWritten) 2738 return; 2739 2740 // Update the type in the type source information too. 2741 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) { 2742 // If the type and the type-as-written differ, we may need to update 2743 // the type-as-written too. 2744 if (TSInfo->getType() != FD->getType()) 2745 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI); 2746 2747 // FIXME: When we get proper type location information for exceptions, 2748 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch 2749 // up the TypeSourceInfo; 2750 assert(TypeLoc::getFullDataSizeForType(Updated) == 2751 TypeLoc::getFullDataSizeForType(TSInfo->getType()) && 2752 "TypeLoc size mismatch from updating exception specification"); 2753 TSInfo->overrideType(Updated); 2754 } 2755 } 2756 2757 /// getComplexType - Return the uniqued reference to the type for a complex 2758 /// number with the specified element type. 2759 QualType ASTContext::getComplexType(QualType T) const { 2760 // Unique pointers, to guarantee there is only one pointer of a particular 2761 // structure. 2762 llvm::FoldingSetNodeID ID; 2763 ComplexType::Profile(ID, T); 2764 2765 void *InsertPos = nullptr; 2766 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 2767 return QualType(CT, 0); 2768 2769 // If the pointee type isn't canonical, this won't be a canonical type either, 2770 // so fill in the canonical type field. 2771 QualType Canonical; 2772 if (!T.isCanonical()) { 2773 Canonical = getComplexType(getCanonicalType(T)); 2774 2775 // Get the new insert position for the node we care about. 2776 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 2777 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2778 } 2779 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 2780 Types.push_back(New); 2781 ComplexTypes.InsertNode(New, InsertPos); 2782 return QualType(New, 0); 2783 } 2784 2785 /// getPointerType - Return the uniqued reference to the type for a pointer to 2786 /// the specified type. 2787 QualType ASTContext::getPointerType(QualType T) const { 2788 // Unique pointers, to guarantee there is only one pointer of a particular 2789 // structure. 2790 llvm::FoldingSetNodeID ID; 2791 PointerType::Profile(ID, T); 2792 2793 void *InsertPos = nullptr; 2794 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2795 return QualType(PT, 0); 2796 2797 // If the pointee type isn't canonical, this won't be a canonical type either, 2798 // so fill in the canonical type field. 2799 QualType Canonical; 2800 if (!T.isCanonical()) { 2801 Canonical = getPointerType(getCanonicalType(T)); 2802 2803 // Get the new insert position for the node we care about. 2804 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2805 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2806 } 2807 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical); 2808 Types.push_back(New); 2809 PointerTypes.InsertNode(New, InsertPos); 2810 return QualType(New, 0); 2811 } 2812 2813 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const { 2814 llvm::FoldingSetNodeID ID; 2815 AdjustedType::Profile(ID, Orig, New); 2816 void *InsertPos = nullptr; 2817 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2818 if (AT) 2819 return QualType(AT, 0); 2820 2821 QualType Canonical = getCanonicalType(New); 2822 2823 // Get the new insert position for the node we care about. 2824 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2825 assert(!AT && "Shouldn't be in the map!"); 2826 2827 AT = new (*this, TypeAlignment) 2828 AdjustedType(Type::Adjusted, Orig, New, Canonical); 2829 Types.push_back(AT); 2830 AdjustedTypes.InsertNode(AT, InsertPos); 2831 return QualType(AT, 0); 2832 } 2833 2834 QualType ASTContext::getDecayedType(QualType T) const { 2835 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay"); 2836 2837 QualType Decayed; 2838 2839 // C99 6.7.5.3p7: 2840 // A declaration of a parameter as "array of type" shall be 2841 // adjusted to "qualified pointer to type", where the type 2842 // qualifiers (if any) are those specified within the [ and ] of 2843 // the array type derivation. 2844 if (T->isArrayType()) 2845 Decayed = getArrayDecayedType(T); 2846 2847 // C99 6.7.5.3p8: 2848 // A declaration of a parameter as "function returning type" 2849 // shall be adjusted to "pointer to function returning type", as 2850 // in 6.3.2.1. 2851 if (T->isFunctionType()) 2852 Decayed = getPointerType(T); 2853 2854 llvm::FoldingSetNodeID ID; 2855 AdjustedType::Profile(ID, T, Decayed); 2856 void *InsertPos = nullptr; 2857 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2858 if (AT) 2859 return QualType(AT, 0); 2860 2861 QualType Canonical = getCanonicalType(Decayed); 2862 2863 // Get the new insert position for the node we care about. 2864 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2865 assert(!AT && "Shouldn't be in the map!"); 2866 2867 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical); 2868 Types.push_back(AT); 2869 AdjustedTypes.InsertNode(AT, InsertPos); 2870 return QualType(AT, 0); 2871 } 2872 2873 /// getBlockPointerType - Return the uniqued reference to the type for 2874 /// a pointer to the specified block. 2875 QualType ASTContext::getBlockPointerType(QualType T) const { 2876 assert(T->isFunctionType() && "block of function types only"); 2877 // Unique pointers, to guarantee there is only one block of a particular 2878 // structure. 2879 llvm::FoldingSetNodeID ID; 2880 BlockPointerType::Profile(ID, T); 2881 2882 void *InsertPos = nullptr; 2883 if (BlockPointerType *PT = 2884 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2885 return QualType(PT, 0); 2886 2887 // If the block pointee type isn't canonical, this won't be a canonical 2888 // type either so fill in the canonical type field. 2889 QualType Canonical; 2890 if (!T.isCanonical()) { 2891 Canonical = getBlockPointerType(getCanonicalType(T)); 2892 2893 // Get the new insert position for the node we care about. 2894 BlockPointerType *NewIP = 2895 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2896 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2897 } 2898 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 2899 Types.push_back(New); 2900 BlockPointerTypes.InsertNode(New, InsertPos); 2901 return QualType(New, 0); 2902 } 2903 2904 /// getLValueReferenceType - Return the uniqued reference to the type for an 2905 /// lvalue reference to the specified type. 2906 QualType 2907 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 2908 assert(getCanonicalType(T) != OverloadTy && 2909 "Unresolved overloaded function type"); 2910 2911 // Unique pointers, to guarantee there is only one pointer of a particular 2912 // structure. 2913 llvm::FoldingSetNodeID ID; 2914 ReferenceType::Profile(ID, T, SpelledAsLValue); 2915 2916 void *InsertPos = nullptr; 2917 if (LValueReferenceType *RT = 2918 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 2919 return QualType(RT, 0); 2920 2921 const auto *InnerRef = T->getAs<ReferenceType>(); 2922 2923 // If the referencee type isn't canonical, this won't be a canonical type 2924 // either, so fill in the canonical type field. 2925 QualType Canonical; 2926 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 2927 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 2928 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 2929 2930 // Get the new insert position for the node we care about. 2931 LValueReferenceType *NewIP = 2932 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 2933 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2934 } 2935 2936 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 2937 SpelledAsLValue); 2938 Types.push_back(New); 2939 LValueReferenceTypes.InsertNode(New, InsertPos); 2940 2941 return QualType(New, 0); 2942 } 2943 2944 /// getRValueReferenceType - Return the uniqued reference to the type for an 2945 /// rvalue reference to the specified type. 2946 QualType ASTContext::getRValueReferenceType(QualType T) const { 2947 // Unique pointers, to guarantee there is only one pointer of a particular 2948 // structure. 2949 llvm::FoldingSetNodeID ID; 2950 ReferenceType::Profile(ID, T, false); 2951 2952 void *InsertPos = nullptr; 2953 if (RValueReferenceType *RT = 2954 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 2955 return QualType(RT, 0); 2956 2957 const auto *InnerRef = T->getAs<ReferenceType>(); 2958 2959 // If the referencee type isn't canonical, this won't be a canonical type 2960 // either, so fill in the canonical type field. 2961 QualType Canonical; 2962 if (InnerRef || !T.isCanonical()) { 2963 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 2964 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 2965 2966 // Get the new insert position for the node we care about. 2967 RValueReferenceType *NewIP = 2968 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 2969 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2970 } 2971 2972 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 2973 Types.push_back(New); 2974 RValueReferenceTypes.InsertNode(New, InsertPos); 2975 return QualType(New, 0); 2976 } 2977 2978 /// getMemberPointerType - Return the uniqued reference to the type for a 2979 /// member pointer to the specified type, in the specified class. 2980 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 2981 // Unique pointers, to guarantee there is only one pointer of a particular 2982 // structure. 2983 llvm::FoldingSetNodeID ID; 2984 MemberPointerType::Profile(ID, T, Cls); 2985 2986 void *InsertPos = nullptr; 2987 if (MemberPointerType *PT = 2988 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2989 return QualType(PT, 0); 2990 2991 // If the pointee or class type isn't canonical, this won't be a canonical 2992 // type either, so fill in the canonical type field. 2993 QualType Canonical; 2994 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 2995 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 2996 2997 // Get the new insert position for the node we care about. 2998 MemberPointerType *NewIP = 2999 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3000 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3001 } 3002 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 3003 Types.push_back(New); 3004 MemberPointerTypes.InsertNode(New, InsertPos); 3005 return QualType(New, 0); 3006 } 3007 3008 /// getConstantArrayType - Return the unique reference to the type for an 3009 /// array of the specified element type. 3010 QualType ASTContext::getConstantArrayType(QualType EltTy, 3011 const llvm::APInt &ArySizeIn, 3012 ArrayType::ArraySizeModifier ASM, 3013 unsigned IndexTypeQuals) const { 3014 assert((EltTy->isDependentType() || 3015 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 3016 "Constant array of VLAs is illegal!"); 3017 3018 // Convert the array size into a canonical width matching the pointer size for 3019 // the target. 3020 llvm::APInt ArySize(ArySizeIn); 3021 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth()); 3022 3023 llvm::FoldingSetNodeID ID; 3024 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals); 3025 3026 void *InsertPos = nullptr; 3027 if (ConstantArrayType *ATP = 3028 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 3029 return QualType(ATP, 0); 3030 3031 // If the element type isn't canonical or has qualifiers, this won't 3032 // be a canonical type either, so fill in the canonical type field. 3033 QualType Canon; 3034 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 3035 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3036 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, 3037 ASM, IndexTypeQuals); 3038 Canon = getQualifiedType(Canon, canonSplit.Quals); 3039 3040 // Get the new insert position for the node we care about. 3041 ConstantArrayType *NewIP = 3042 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 3043 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3044 } 3045 3046 auto *New = new (*this,TypeAlignment) 3047 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals); 3048 ConstantArrayTypes.InsertNode(New, InsertPos); 3049 Types.push_back(New); 3050 return QualType(New, 0); 3051 } 3052 3053 /// getVariableArrayDecayedType - Turns the given type, which may be 3054 /// variably-modified, into the corresponding type with all the known 3055 /// sizes replaced with [*]. 3056 QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 3057 // Vastly most common case. 3058 if (!type->isVariablyModifiedType()) return type; 3059 3060 QualType result; 3061 3062 SplitQualType split = type.getSplitDesugaredType(); 3063 const Type *ty = split.Ty; 3064 switch (ty->getTypeClass()) { 3065 #define TYPE(Class, Base) 3066 #define ABSTRACT_TYPE(Class, Base) 3067 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3068 #include "clang/AST/TypeNodes.def" 3069 llvm_unreachable("didn't desugar past all non-canonical types?"); 3070 3071 // These types should never be variably-modified. 3072 case Type::Builtin: 3073 case Type::Complex: 3074 case Type::Vector: 3075 case Type::DependentVector: 3076 case Type::ExtVector: 3077 case Type::DependentSizedExtVector: 3078 case Type::DependentAddressSpace: 3079 case Type::ObjCObject: 3080 case Type::ObjCInterface: 3081 case Type::ObjCObjectPointer: 3082 case Type::Record: 3083 case Type::Enum: 3084 case Type::UnresolvedUsing: 3085 case Type::TypeOfExpr: 3086 case Type::TypeOf: 3087 case Type::Decltype: 3088 case Type::UnaryTransform: 3089 case Type::DependentName: 3090 case Type::InjectedClassName: 3091 case Type::TemplateSpecialization: 3092 case Type::DependentTemplateSpecialization: 3093 case Type::TemplateTypeParm: 3094 case Type::SubstTemplateTypeParmPack: 3095 case Type::Auto: 3096 case Type::DeducedTemplateSpecialization: 3097 case Type::PackExpansion: 3098 llvm_unreachable("type should never be variably-modified"); 3099 3100 // These types can be variably-modified but should never need to 3101 // further decay. 3102 case Type::FunctionNoProto: 3103 case Type::FunctionProto: 3104 case Type::BlockPointer: 3105 case Type::MemberPointer: 3106 case Type::Pipe: 3107 return type; 3108 3109 // These types can be variably-modified. All these modifications 3110 // preserve structure except as noted by comments. 3111 // TODO: if we ever care about optimizing VLAs, there are no-op 3112 // optimizations available here. 3113 case Type::Pointer: 3114 result = getPointerType(getVariableArrayDecayedType( 3115 cast<PointerType>(ty)->getPointeeType())); 3116 break; 3117 3118 case Type::LValueReference: { 3119 const auto *lv = cast<LValueReferenceType>(ty); 3120 result = getLValueReferenceType( 3121 getVariableArrayDecayedType(lv->getPointeeType()), 3122 lv->isSpelledAsLValue()); 3123 break; 3124 } 3125 3126 case Type::RValueReference: { 3127 const auto *lv = cast<RValueReferenceType>(ty); 3128 result = getRValueReferenceType( 3129 getVariableArrayDecayedType(lv->getPointeeType())); 3130 break; 3131 } 3132 3133 case Type::Atomic: { 3134 const auto *at = cast<AtomicType>(ty); 3135 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 3136 break; 3137 } 3138 3139 case Type::ConstantArray: { 3140 const auto *cat = cast<ConstantArrayType>(ty); 3141 result = getConstantArrayType( 3142 getVariableArrayDecayedType(cat->getElementType()), 3143 cat->getSize(), 3144 cat->getSizeModifier(), 3145 cat->getIndexTypeCVRQualifiers()); 3146 break; 3147 } 3148 3149 case Type::DependentSizedArray: { 3150 const auto *dat = cast<DependentSizedArrayType>(ty); 3151 result = getDependentSizedArrayType( 3152 getVariableArrayDecayedType(dat->getElementType()), 3153 dat->getSizeExpr(), 3154 dat->getSizeModifier(), 3155 dat->getIndexTypeCVRQualifiers(), 3156 dat->getBracketsRange()); 3157 break; 3158 } 3159 3160 // Turn incomplete types into [*] types. 3161 case Type::IncompleteArray: { 3162 const auto *iat = cast<IncompleteArrayType>(ty); 3163 result = getVariableArrayType( 3164 getVariableArrayDecayedType(iat->getElementType()), 3165 /*size*/ nullptr, 3166 ArrayType::Normal, 3167 iat->getIndexTypeCVRQualifiers(), 3168 SourceRange()); 3169 break; 3170 } 3171 3172 // Turn VLA types into [*] types. 3173 case Type::VariableArray: { 3174 const auto *vat = cast<VariableArrayType>(ty); 3175 result = getVariableArrayType( 3176 getVariableArrayDecayedType(vat->getElementType()), 3177 /*size*/ nullptr, 3178 ArrayType::Star, 3179 vat->getIndexTypeCVRQualifiers(), 3180 vat->getBracketsRange()); 3181 break; 3182 } 3183 } 3184 3185 // Apply the top-level qualifiers from the original. 3186 return getQualifiedType(result, split.Quals); 3187 } 3188 3189 /// getVariableArrayType - Returns a non-unique reference to the type for a 3190 /// variable array of the specified element type. 3191 QualType ASTContext::getVariableArrayType(QualType EltTy, 3192 Expr *NumElts, 3193 ArrayType::ArraySizeModifier ASM, 3194 unsigned IndexTypeQuals, 3195 SourceRange Brackets) const { 3196 // Since we don't unique expressions, it isn't possible to unique VLA's 3197 // that have an expression provided for their size. 3198 QualType Canon; 3199 3200 // Be sure to pull qualifiers off the element type. 3201 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 3202 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3203 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 3204 IndexTypeQuals, Brackets); 3205 Canon = getQualifiedType(Canon, canonSplit.Quals); 3206 } 3207 3208 auto *New = new (*this, TypeAlignment) 3209 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 3210 3211 VariableArrayTypes.push_back(New); 3212 Types.push_back(New); 3213 return QualType(New, 0); 3214 } 3215 3216 /// getDependentSizedArrayType - Returns a non-unique reference to 3217 /// the type for a dependently-sized array of the specified element 3218 /// type. 3219 QualType ASTContext::getDependentSizedArrayType(QualType elementType, 3220 Expr *numElements, 3221 ArrayType::ArraySizeModifier ASM, 3222 unsigned elementTypeQuals, 3223 SourceRange brackets) const { 3224 assert((!numElements || numElements->isTypeDependent() || 3225 numElements->isValueDependent()) && 3226 "Size must be type- or value-dependent!"); 3227 3228 // Dependently-sized array types that do not have a specified number 3229 // of elements will have their sizes deduced from a dependent 3230 // initializer. We do no canonicalization here at all, which is okay 3231 // because they can't be used in most locations. 3232 if (!numElements) { 3233 auto *newType 3234 = new (*this, TypeAlignment) 3235 DependentSizedArrayType(*this, elementType, QualType(), 3236 numElements, ASM, elementTypeQuals, 3237 brackets); 3238 Types.push_back(newType); 3239 return QualType(newType, 0); 3240 } 3241 3242 // Otherwise, we actually build a new type every time, but we 3243 // also build a canonical type. 3244 3245 SplitQualType canonElementType = getCanonicalType(elementType).split(); 3246 3247 void *insertPos = nullptr; 3248 llvm::FoldingSetNodeID ID; 3249 DependentSizedArrayType::Profile(ID, *this, 3250 QualType(canonElementType.Ty, 0), 3251 ASM, elementTypeQuals, numElements); 3252 3253 // Look for an existing type with these properties. 3254 DependentSizedArrayType *canonTy = 3255 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3256 3257 // If we don't have one, build one. 3258 if (!canonTy) { 3259 canonTy = new (*this, TypeAlignment) 3260 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 3261 QualType(), numElements, ASM, elementTypeQuals, 3262 brackets); 3263 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 3264 Types.push_back(canonTy); 3265 } 3266 3267 // Apply qualifiers from the element type to the array. 3268 QualType canon = getQualifiedType(QualType(canonTy,0), 3269 canonElementType.Quals); 3270 3271 // If we didn't need extra canonicalization for the element type or the size 3272 // expression, then just use that as our result. 3273 if (QualType(canonElementType.Ty, 0) == elementType && 3274 canonTy->getSizeExpr() == numElements) 3275 return canon; 3276 3277 // Otherwise, we need to build a type which follows the spelling 3278 // of the element type. 3279 auto *sugaredType 3280 = new (*this, TypeAlignment) 3281 DependentSizedArrayType(*this, elementType, canon, numElements, 3282 ASM, elementTypeQuals, brackets); 3283 Types.push_back(sugaredType); 3284 return QualType(sugaredType, 0); 3285 } 3286 3287 QualType ASTContext::getIncompleteArrayType(QualType elementType, 3288 ArrayType::ArraySizeModifier ASM, 3289 unsigned elementTypeQuals) const { 3290 llvm::FoldingSetNodeID ID; 3291 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 3292 3293 void *insertPos = nullptr; 3294 if (IncompleteArrayType *iat = 3295 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 3296 return QualType(iat, 0); 3297 3298 // If the element type isn't canonical, this won't be a canonical type 3299 // either, so fill in the canonical type field. We also have to pull 3300 // qualifiers off the element type. 3301 QualType canon; 3302 3303 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 3304 SplitQualType canonSplit = getCanonicalType(elementType).split(); 3305 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 3306 ASM, elementTypeQuals); 3307 canon = getQualifiedType(canon, canonSplit.Quals); 3308 3309 // Get the new insert position for the node we care about. 3310 IncompleteArrayType *existing = 3311 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3312 assert(!existing && "Shouldn't be in the map!"); (void) existing; 3313 } 3314 3315 auto *newType = new (*this, TypeAlignment) 3316 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 3317 3318 IncompleteArrayTypes.InsertNode(newType, insertPos); 3319 Types.push_back(newType); 3320 return QualType(newType, 0); 3321 } 3322 3323 /// getVectorType - Return the unique reference to a vector type of 3324 /// the specified element type and size. VectorType must be a built-in type. 3325 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 3326 VectorType::VectorKind VecKind) const { 3327 assert(vecType->isBuiltinType()); 3328 3329 // Check if we've already instantiated a vector of this type. 3330 llvm::FoldingSetNodeID ID; 3331 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 3332 3333 void *InsertPos = nullptr; 3334 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 3335 return QualType(VTP, 0); 3336 3337 // If the element type isn't canonical, this won't be a canonical type either, 3338 // so fill in the canonical type field. 3339 QualType Canonical; 3340 if (!vecType.isCanonical()) { 3341 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 3342 3343 // Get the new insert position for the node we care about. 3344 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3345 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3346 } 3347 auto *New = new (*this, TypeAlignment) 3348 VectorType(vecType, NumElts, Canonical, VecKind); 3349 VectorTypes.InsertNode(New, InsertPos); 3350 Types.push_back(New); 3351 return QualType(New, 0); 3352 } 3353 3354 QualType 3355 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr, 3356 SourceLocation AttrLoc, 3357 VectorType::VectorKind VecKind) const { 3358 llvm::FoldingSetNodeID ID; 3359 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr, 3360 VecKind); 3361 void *InsertPos = nullptr; 3362 DependentVectorType *Canon = 3363 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3364 DependentVectorType *New; 3365 3366 if (Canon) { 3367 New = new (*this, TypeAlignment) DependentVectorType( 3368 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind); 3369 } else { 3370 QualType CanonVecTy = getCanonicalType(VecType); 3371 if (CanonVecTy == VecType) { 3372 New = new (*this, TypeAlignment) DependentVectorType( 3373 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind); 3374 3375 DependentVectorType *CanonCheck = 3376 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3377 assert(!CanonCheck && 3378 "Dependent-sized vector_size canonical type broken"); 3379 (void)CanonCheck; 3380 DependentVectorTypes.InsertNode(New, InsertPos); 3381 } else { 3382 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 3383 SourceLocation()); 3384 New = new (*this, TypeAlignment) DependentVectorType( 3385 *this, VecType, Canon, SizeExpr, AttrLoc, VecKind); 3386 } 3387 } 3388 3389 Types.push_back(New); 3390 return QualType(New, 0); 3391 } 3392 3393 /// getExtVectorType - Return the unique reference to an extended vector type of 3394 /// the specified element type and size. VectorType must be a built-in type. 3395 QualType 3396 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 3397 assert(vecType->isBuiltinType() || vecType->isDependentType()); 3398 3399 // Check if we've already instantiated a vector of this type. 3400 llvm::FoldingSetNodeID ID; 3401 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 3402 VectorType::GenericVector); 3403 void *InsertPos = nullptr; 3404 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 3405 return QualType(VTP, 0); 3406 3407 // If the element type isn't canonical, this won't be a canonical type either, 3408 // so fill in the canonical type field. 3409 QualType Canonical; 3410 if (!vecType.isCanonical()) { 3411 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 3412 3413 // Get the new insert position for the node we care about. 3414 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3415 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3416 } 3417 auto *New = new (*this, TypeAlignment) 3418 ExtVectorType(vecType, NumElts, Canonical); 3419 VectorTypes.InsertNode(New, InsertPos); 3420 Types.push_back(New); 3421 return QualType(New, 0); 3422 } 3423 3424 QualType 3425 ASTContext::getDependentSizedExtVectorType(QualType vecType, 3426 Expr *SizeExpr, 3427 SourceLocation AttrLoc) const { 3428 llvm::FoldingSetNodeID ID; 3429 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 3430 SizeExpr); 3431 3432 void *InsertPos = nullptr; 3433 DependentSizedExtVectorType *Canon 3434 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3435 DependentSizedExtVectorType *New; 3436 if (Canon) { 3437 // We already have a canonical version of this array type; use it as 3438 // the canonical type for a newly-built type. 3439 New = new (*this, TypeAlignment) 3440 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 3441 SizeExpr, AttrLoc); 3442 } else { 3443 QualType CanonVecTy = getCanonicalType(vecType); 3444 if (CanonVecTy == vecType) { 3445 New = new (*this, TypeAlignment) 3446 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 3447 AttrLoc); 3448 3449 DependentSizedExtVectorType *CanonCheck 3450 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3451 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 3452 (void)CanonCheck; 3453 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 3454 } else { 3455 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 3456 SourceLocation()); 3457 New = new (*this, TypeAlignment) 3458 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc); 3459 } 3460 } 3461 3462 Types.push_back(New); 3463 return QualType(New, 0); 3464 } 3465 3466 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, 3467 Expr *AddrSpaceExpr, 3468 SourceLocation AttrLoc) const { 3469 assert(AddrSpaceExpr->isInstantiationDependent()); 3470 3471 QualType canonPointeeType = getCanonicalType(PointeeType); 3472 3473 void *insertPos = nullptr; 3474 llvm::FoldingSetNodeID ID; 3475 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType, 3476 AddrSpaceExpr); 3477 3478 DependentAddressSpaceType *canonTy = 3479 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos); 3480 3481 if (!canonTy) { 3482 canonTy = new (*this, TypeAlignment) 3483 DependentAddressSpaceType(*this, canonPointeeType, 3484 QualType(), AddrSpaceExpr, AttrLoc); 3485 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos); 3486 Types.push_back(canonTy); 3487 } 3488 3489 if (canonPointeeType == PointeeType && 3490 canonTy->getAddrSpaceExpr() == AddrSpaceExpr) 3491 return QualType(canonTy, 0); 3492 3493 auto *sugaredType 3494 = new (*this, TypeAlignment) 3495 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0), 3496 AddrSpaceExpr, AttrLoc); 3497 Types.push_back(sugaredType); 3498 return QualType(sugaredType, 0); 3499 } 3500 3501 /// Determine whether \p T is canonical as the result type of a function. 3502 static bool isCanonicalResultType(QualType T) { 3503 return T.isCanonical() && 3504 (T.getObjCLifetime() == Qualifiers::OCL_None || 3505 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone); 3506 } 3507 3508 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 3509 QualType 3510 ASTContext::getFunctionNoProtoType(QualType ResultTy, 3511 const FunctionType::ExtInfo &Info) const { 3512 // Unique functions, to guarantee there is only one function of a particular 3513 // structure. 3514 llvm::FoldingSetNodeID ID; 3515 FunctionNoProtoType::Profile(ID, ResultTy, Info); 3516 3517 void *InsertPos = nullptr; 3518 if (FunctionNoProtoType *FT = 3519 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 3520 return QualType(FT, 0); 3521 3522 QualType Canonical; 3523 if (!isCanonicalResultType(ResultTy)) { 3524 Canonical = 3525 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info); 3526 3527 // Get the new insert position for the node we care about. 3528 FunctionNoProtoType *NewIP = 3529 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 3530 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3531 } 3532 3533 auto *New = new (*this, TypeAlignment) 3534 FunctionNoProtoType(ResultTy, Canonical, Info); 3535 Types.push_back(New); 3536 FunctionNoProtoTypes.InsertNode(New, InsertPos); 3537 return QualType(New, 0); 3538 } 3539 3540 CanQualType 3541 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const { 3542 CanQualType CanResultType = getCanonicalType(ResultType); 3543 3544 // Canonical result types do not have ARC lifetime qualifiers. 3545 if (CanResultType.getQualifiers().hasObjCLifetime()) { 3546 Qualifiers Qs = CanResultType.getQualifiers(); 3547 Qs.removeObjCLifetime(); 3548 return CanQualType::CreateUnsafe( 3549 getQualifiedType(CanResultType.getUnqualifiedType(), Qs)); 3550 } 3551 3552 return CanResultType; 3553 } 3554 3555 static bool isCanonicalExceptionSpecification( 3556 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) { 3557 if (ESI.Type == EST_None) 3558 return true; 3559 if (!NoexceptInType) 3560 return false; 3561 3562 // C++17 onwards: exception specification is part of the type, as a simple 3563 // boolean "can this function type throw". 3564 if (ESI.Type == EST_BasicNoexcept) 3565 return true; 3566 3567 // A noexcept(expr) specification is (possibly) canonical if expr is 3568 // value-dependent. 3569 if (ESI.Type == EST_DependentNoexcept) 3570 return true; 3571 3572 // A dynamic exception specification is canonical if it only contains pack 3573 // expansions (so we can't tell whether it's non-throwing) and all its 3574 // contained types are canonical. 3575 if (ESI.Type == EST_Dynamic) { 3576 bool AnyPackExpansions = false; 3577 for (QualType ET : ESI.Exceptions) { 3578 if (!ET.isCanonical()) 3579 return false; 3580 if (ET->getAs<PackExpansionType>()) 3581 AnyPackExpansions = true; 3582 } 3583 return AnyPackExpansions; 3584 } 3585 3586 return false; 3587 } 3588 3589 QualType ASTContext::getFunctionTypeInternal( 3590 QualType ResultTy, ArrayRef<QualType> ArgArray, 3591 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const { 3592 size_t NumArgs = ArgArray.size(); 3593 3594 // Unique functions, to guarantee there is only one function of a particular 3595 // structure. 3596 llvm::FoldingSetNodeID ID; 3597 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, 3598 *this, true); 3599 3600 QualType Canonical; 3601 bool Unique = false; 3602 3603 void *InsertPos = nullptr; 3604 if (FunctionProtoType *FPT = 3605 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) { 3606 QualType Existing = QualType(FPT, 0); 3607 3608 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse 3609 // it so long as our exception specification doesn't contain a dependent 3610 // noexcept expression, or we're just looking for a canonical type. 3611 // Otherwise, we're going to need to create a type 3612 // sugar node to hold the concrete expression. 3613 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) || 3614 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr()) 3615 return Existing; 3616 3617 // We need a new type sugar node for this one, to hold the new noexcept 3618 // expression. We do no canonicalization here, but that's OK since we don't 3619 // expect to see the same noexcept expression much more than once. 3620 Canonical = getCanonicalType(Existing); 3621 Unique = true; 3622 } 3623 3624 bool NoexceptInType = getLangOpts().CPlusPlus17; 3625 bool IsCanonicalExceptionSpec = 3626 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType); 3627 3628 // Determine whether the type being created is already canonical or not. 3629 bool isCanonical = !Unique && IsCanonicalExceptionSpec && 3630 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn; 3631 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 3632 if (!ArgArray[i].isCanonicalAsParam()) 3633 isCanonical = false; 3634 3635 if (OnlyWantCanonical) 3636 assert(isCanonical && 3637 "given non-canonical parameters constructing canonical type"); 3638 3639 // If this type isn't canonical, get the canonical version of it if we don't 3640 // already have it. The exception spec is only partially part of the 3641 // canonical type, and only in C++17 onwards. 3642 if (!isCanonical && Canonical.isNull()) { 3643 SmallVector<QualType, 16> CanonicalArgs; 3644 CanonicalArgs.reserve(NumArgs); 3645 for (unsigned i = 0; i != NumArgs; ++i) 3646 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 3647 3648 llvm::SmallVector<QualType, 8> ExceptionTypeStorage; 3649 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 3650 CanonicalEPI.HasTrailingReturn = false; 3651 3652 if (IsCanonicalExceptionSpec) { 3653 // Exception spec is already OK. 3654 } else if (NoexceptInType) { 3655 switch (EPI.ExceptionSpec.Type) { 3656 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated: 3657 // We don't know yet. It shouldn't matter what we pick here; no-one 3658 // should ever look at this. 3659 LLVM_FALLTHROUGH; 3660 case EST_None: case EST_MSAny: case EST_NoexceptFalse: 3661 CanonicalEPI.ExceptionSpec.Type = EST_None; 3662 break; 3663 3664 // A dynamic exception specification is almost always "not noexcept", 3665 // with the exception that a pack expansion might expand to no types. 3666 case EST_Dynamic: { 3667 bool AnyPacks = false; 3668 for (QualType ET : EPI.ExceptionSpec.Exceptions) { 3669 if (ET->getAs<PackExpansionType>()) 3670 AnyPacks = true; 3671 ExceptionTypeStorage.push_back(getCanonicalType(ET)); 3672 } 3673 if (!AnyPacks) 3674 CanonicalEPI.ExceptionSpec.Type = EST_None; 3675 else { 3676 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic; 3677 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage; 3678 } 3679 break; 3680 } 3681 3682 case EST_DynamicNone: case EST_BasicNoexcept: case EST_NoexceptTrue: 3683 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept; 3684 break; 3685 3686 case EST_DependentNoexcept: 3687 llvm_unreachable("dependent noexcept is already canonical"); 3688 } 3689 } else { 3690 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo(); 3691 } 3692 3693 // Adjust the canonical function result type. 3694 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy); 3695 Canonical = 3696 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true); 3697 3698 // Get the new insert position for the node we care about. 3699 FunctionProtoType *NewIP = 3700 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 3701 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3702 } 3703 3704 // FunctionProtoType objects are allocated with extra bytes after 3705 // them for three variable size arrays at the end: 3706 // - parameter types 3707 // - exception types 3708 // - extended parameter information 3709 // Instead of the exception types, there could be a noexcept 3710 // expression, or information used to resolve the exception 3711 // specification. 3712 size_t Size = 3713 sizeof(FunctionProtoType) + NumArgs * sizeof(QualType) + 3714 FunctionProtoType::getExceptionSpecSize( 3715 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size()); 3716 3717 // Put the ExtParameterInfos last. If all were equal, it would make 3718 // more sense to put these before the exception specification, because 3719 // it's much easier to skip past them compared to the elaborate switch 3720 // required to skip the exception specification. However, all is not 3721 // equal; ExtParameterInfos are used to model very uncommon features, 3722 // and it's better not to burden the more common paths. 3723 if (EPI.ExtParameterInfos) { 3724 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo); 3725 } 3726 3727 auto *FTP = (FunctionProtoType *) Allocate(Size, TypeAlignment); 3728 FunctionProtoType::ExtProtoInfo newEPI = EPI; 3729 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI); 3730 Types.push_back(FTP); 3731 if (!Unique) 3732 FunctionProtoTypes.InsertNode(FTP, InsertPos); 3733 return QualType(FTP, 0); 3734 } 3735 3736 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const { 3737 llvm::FoldingSetNodeID ID; 3738 PipeType::Profile(ID, T, ReadOnly); 3739 3740 void *InsertPos = nullptr; 3741 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos)) 3742 return QualType(PT, 0); 3743 3744 // If the pipe element type isn't canonical, this won't be a canonical type 3745 // either, so fill in the canonical type field. 3746 QualType Canonical; 3747 if (!T.isCanonical()) { 3748 Canonical = getPipeType(getCanonicalType(T), ReadOnly); 3749 3750 // Get the new insert position for the node we care about. 3751 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos); 3752 assert(!NewIP && "Shouldn't be in the map!"); 3753 (void)NewIP; 3754 } 3755 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly); 3756 Types.push_back(New); 3757 PipeTypes.InsertNode(New, InsertPos); 3758 return QualType(New, 0); 3759 } 3760 3761 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const { 3762 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 3763 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant) 3764 : Ty; 3765 } 3766 3767 QualType ASTContext::getReadPipeType(QualType T) const { 3768 return getPipeType(T, true); 3769 } 3770 3771 QualType ASTContext::getWritePipeType(QualType T) const { 3772 return getPipeType(T, false); 3773 } 3774 3775 #ifndef NDEBUG 3776 static bool NeedsInjectedClassNameType(const RecordDecl *D) { 3777 if (!isa<CXXRecordDecl>(D)) return false; 3778 const auto *RD = cast<CXXRecordDecl>(D); 3779 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 3780 return true; 3781 if (RD->getDescribedClassTemplate() && 3782 !isa<ClassTemplateSpecializationDecl>(RD)) 3783 return true; 3784 return false; 3785 } 3786 #endif 3787 3788 /// getInjectedClassNameType - Return the unique reference to the 3789 /// injected class name type for the specified templated declaration. 3790 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 3791 QualType TST) const { 3792 assert(NeedsInjectedClassNameType(Decl)); 3793 if (Decl->TypeForDecl) { 3794 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 3795 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 3796 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 3797 Decl->TypeForDecl = PrevDecl->TypeForDecl; 3798 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 3799 } else { 3800 Type *newType = 3801 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 3802 Decl->TypeForDecl = newType; 3803 Types.push_back(newType); 3804 } 3805 return QualType(Decl->TypeForDecl, 0); 3806 } 3807 3808 /// getTypeDeclType - Return the unique reference to the type for the 3809 /// specified type declaration. 3810 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 3811 assert(Decl && "Passed null for Decl param"); 3812 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 3813 3814 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 3815 return getTypedefType(Typedef); 3816 3817 assert(!isa<TemplateTypeParmDecl>(Decl) && 3818 "Template type parameter types are always available."); 3819 3820 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) { 3821 assert(Record->isFirstDecl() && "struct/union has previous declaration"); 3822 assert(!NeedsInjectedClassNameType(Record)); 3823 return getRecordType(Record); 3824 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) { 3825 assert(Enum->isFirstDecl() && "enum has previous declaration"); 3826 return getEnumType(Enum); 3827 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 3828 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using); 3829 Decl->TypeForDecl = newType; 3830 Types.push_back(newType); 3831 } else 3832 llvm_unreachable("TypeDecl without a type?"); 3833 3834 return QualType(Decl->TypeForDecl, 0); 3835 } 3836 3837 /// getTypedefType - Return the unique reference to the type for the 3838 /// specified typedef name decl. 3839 QualType 3840 ASTContext::getTypedefType(const TypedefNameDecl *Decl, 3841 QualType Canonical) const { 3842 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 3843 3844 if (Canonical.isNull()) 3845 Canonical = getCanonicalType(Decl->getUnderlyingType()); 3846 auto *newType = new (*this, TypeAlignment) 3847 TypedefType(Type::Typedef, Decl, Canonical); 3848 Decl->TypeForDecl = newType; 3849 Types.push_back(newType); 3850 return QualType(newType, 0); 3851 } 3852 3853 QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 3854 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 3855 3856 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 3857 if (PrevDecl->TypeForDecl) 3858 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 3859 3860 auto *newType = new (*this, TypeAlignment) RecordType(Decl); 3861 Decl->TypeForDecl = newType; 3862 Types.push_back(newType); 3863 return QualType(newType, 0); 3864 } 3865 3866 QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 3867 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 3868 3869 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 3870 if (PrevDecl->TypeForDecl) 3871 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 3872 3873 auto *newType = new (*this, TypeAlignment) EnumType(Decl); 3874 Decl->TypeForDecl = newType; 3875 Types.push_back(newType); 3876 return QualType(newType, 0); 3877 } 3878 3879 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind, 3880 QualType modifiedType, 3881 QualType equivalentType) { 3882 llvm::FoldingSetNodeID id; 3883 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 3884 3885 void *insertPos = nullptr; 3886 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 3887 if (type) return QualType(type, 0); 3888 3889 QualType canon = getCanonicalType(equivalentType); 3890 type = new (*this, TypeAlignment) 3891 AttributedType(canon, attrKind, modifiedType, equivalentType); 3892 3893 Types.push_back(type); 3894 AttributedTypes.InsertNode(type, insertPos); 3895 3896 return QualType(type, 0); 3897 } 3898 3899 /// Retrieve a substitution-result type. 3900 QualType 3901 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 3902 QualType Replacement) const { 3903 assert(Replacement.isCanonical() 3904 && "replacement types must always be canonical"); 3905 3906 llvm::FoldingSetNodeID ID; 3907 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 3908 void *InsertPos = nullptr; 3909 SubstTemplateTypeParmType *SubstParm 3910 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3911 3912 if (!SubstParm) { 3913 SubstParm = new (*this, TypeAlignment) 3914 SubstTemplateTypeParmType(Parm, Replacement); 3915 Types.push_back(SubstParm); 3916 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 3917 } 3918 3919 return QualType(SubstParm, 0); 3920 } 3921 3922 /// Retrieve a 3923 QualType ASTContext::getSubstTemplateTypeParmPackType( 3924 const TemplateTypeParmType *Parm, 3925 const TemplateArgument &ArgPack) { 3926 #ifndef NDEBUG 3927 for (const auto &P : ArgPack.pack_elements()) { 3928 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 3929 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); 3930 } 3931 #endif 3932 3933 llvm::FoldingSetNodeID ID; 3934 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 3935 void *InsertPos = nullptr; 3936 if (SubstTemplateTypeParmPackType *SubstParm 3937 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 3938 return QualType(SubstParm, 0); 3939 3940 QualType Canon; 3941 if (!Parm->isCanonicalUnqualified()) { 3942 Canon = getCanonicalType(QualType(Parm, 0)); 3943 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 3944 ArgPack); 3945 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 3946 } 3947 3948 auto *SubstParm 3949 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 3950 ArgPack); 3951 Types.push_back(SubstParm); 3952 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos); 3953 return QualType(SubstParm, 0); 3954 } 3955 3956 /// Retrieve the template type parameter type for a template 3957 /// parameter or parameter pack with the given depth, index, and (optionally) 3958 /// name. 3959 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 3960 bool ParameterPack, 3961 TemplateTypeParmDecl *TTPDecl) const { 3962 llvm::FoldingSetNodeID ID; 3963 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 3964 void *InsertPos = nullptr; 3965 TemplateTypeParmType *TypeParm 3966 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3967 3968 if (TypeParm) 3969 return QualType(TypeParm, 0); 3970 3971 if (TTPDecl) { 3972 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 3973 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 3974 3975 TemplateTypeParmType *TypeCheck 3976 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3977 assert(!TypeCheck && "Template type parameter canonical type broken"); 3978 (void)TypeCheck; 3979 } else 3980 TypeParm = new (*this, TypeAlignment) 3981 TemplateTypeParmType(Depth, Index, ParameterPack); 3982 3983 Types.push_back(TypeParm); 3984 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 3985 3986 return QualType(TypeParm, 0); 3987 } 3988 3989 TypeSourceInfo * 3990 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 3991 SourceLocation NameLoc, 3992 const TemplateArgumentListInfo &Args, 3993 QualType Underlying) const { 3994 assert(!Name.getAsDependentTemplateName() && 3995 "No dependent template names here!"); 3996 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 3997 3998 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 3999 TemplateSpecializationTypeLoc TL = 4000 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>(); 4001 TL.setTemplateKeywordLoc(SourceLocation()); 4002 TL.setTemplateNameLoc(NameLoc); 4003 TL.setLAngleLoc(Args.getLAngleLoc()); 4004 TL.setRAngleLoc(Args.getRAngleLoc()); 4005 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 4006 TL.setArgLocInfo(i, Args[i].getLocInfo()); 4007 return DI; 4008 } 4009 4010 QualType 4011 ASTContext::getTemplateSpecializationType(TemplateName Template, 4012 const TemplateArgumentListInfo &Args, 4013 QualType Underlying) const { 4014 assert(!Template.getAsDependentTemplateName() && 4015 "No dependent template names here!"); 4016 4017 SmallVector<TemplateArgument, 4> ArgVec; 4018 ArgVec.reserve(Args.size()); 4019 for (const TemplateArgumentLoc &Arg : Args.arguments()) 4020 ArgVec.push_back(Arg.getArgument()); 4021 4022 return getTemplateSpecializationType(Template, ArgVec, Underlying); 4023 } 4024 4025 #ifndef NDEBUG 4026 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) { 4027 for (const TemplateArgument &Arg : Args) 4028 if (Arg.isPackExpansion()) 4029 return true; 4030 4031 return true; 4032 } 4033 #endif 4034 4035 QualType 4036 ASTContext::getTemplateSpecializationType(TemplateName Template, 4037 ArrayRef<TemplateArgument> Args, 4038 QualType Underlying) const { 4039 assert(!Template.getAsDependentTemplateName() && 4040 "No dependent template names here!"); 4041 // Look through qualified template names. 4042 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4043 Template = TemplateName(QTN->getTemplateDecl()); 4044 4045 bool IsTypeAlias = 4046 Template.getAsTemplateDecl() && 4047 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 4048 QualType CanonType; 4049 if (!Underlying.isNull()) 4050 CanonType = getCanonicalType(Underlying); 4051 else { 4052 // We can get here with an alias template when the specialization contains 4053 // a pack expansion that does not match up with a parameter pack. 4054 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) && 4055 "Caller must compute aliased type"); 4056 IsTypeAlias = false; 4057 CanonType = getCanonicalTemplateSpecializationType(Template, Args); 4058 } 4059 4060 // Allocate the (non-canonical) template specialization type, but don't 4061 // try to unique it: these types typically have location information that 4062 // we don't unique and don't want to lose. 4063 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 4064 sizeof(TemplateArgument) * Args.size() + 4065 (IsTypeAlias? sizeof(QualType) : 0), 4066 TypeAlignment); 4067 auto *Spec 4068 = new (Mem) TemplateSpecializationType(Template, Args, CanonType, 4069 IsTypeAlias ? Underlying : QualType()); 4070 4071 Types.push_back(Spec); 4072 return QualType(Spec, 0); 4073 } 4074 4075 QualType ASTContext::getCanonicalTemplateSpecializationType( 4076 TemplateName Template, ArrayRef<TemplateArgument> Args) const { 4077 assert(!Template.getAsDependentTemplateName() && 4078 "No dependent template names here!"); 4079 4080 // Look through qualified template names. 4081 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4082 Template = TemplateName(QTN->getTemplateDecl()); 4083 4084 // Build the canonical template specialization type. 4085 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 4086 SmallVector<TemplateArgument, 4> CanonArgs; 4087 unsigned NumArgs = Args.size(); 4088 CanonArgs.reserve(NumArgs); 4089 for (const TemplateArgument &Arg : Args) 4090 CanonArgs.push_back(getCanonicalTemplateArgument(Arg)); 4091 4092 // Determine whether this canonical template specialization type already 4093 // exists. 4094 llvm::FoldingSetNodeID ID; 4095 TemplateSpecializationType::Profile(ID, CanonTemplate, 4096 CanonArgs, *this); 4097 4098 void *InsertPos = nullptr; 4099 TemplateSpecializationType *Spec 4100 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4101 4102 if (!Spec) { 4103 // Allocate a new canonical template specialization type. 4104 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 4105 sizeof(TemplateArgument) * NumArgs), 4106 TypeAlignment); 4107 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 4108 CanonArgs, 4109 QualType(), QualType()); 4110 Types.push_back(Spec); 4111 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 4112 } 4113 4114 assert(Spec->isDependentType() && 4115 "Non-dependent template-id type must have a canonical type"); 4116 return QualType(Spec, 0); 4117 } 4118 4119 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 4120 NestedNameSpecifier *NNS, 4121 QualType NamedType, 4122 TagDecl *OwnedTagDecl) const { 4123 llvm::FoldingSetNodeID ID; 4124 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl); 4125 4126 void *InsertPos = nullptr; 4127 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4128 if (T) 4129 return QualType(T, 0); 4130 4131 QualType Canon = NamedType; 4132 if (!Canon.isCanonical()) { 4133 Canon = getCanonicalType(NamedType); 4134 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4135 assert(!CheckT && "Elaborated canonical type broken"); 4136 (void)CheckT; 4137 } 4138 4139 T = new (*this, TypeAlignment) 4140 ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl); 4141 Types.push_back(T); 4142 ElaboratedTypes.InsertNode(T, InsertPos); 4143 return QualType(T, 0); 4144 } 4145 4146 QualType 4147 ASTContext::getParenType(QualType InnerType) const { 4148 llvm::FoldingSetNodeID ID; 4149 ParenType::Profile(ID, InnerType); 4150 4151 void *InsertPos = nullptr; 4152 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4153 if (T) 4154 return QualType(T, 0); 4155 4156 QualType Canon = InnerType; 4157 if (!Canon.isCanonical()) { 4158 Canon = getCanonicalType(InnerType); 4159 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4160 assert(!CheckT && "Paren canonical type broken"); 4161 (void)CheckT; 4162 } 4163 4164 T = new (*this, TypeAlignment) ParenType(InnerType, Canon); 4165 Types.push_back(T); 4166 ParenTypes.InsertNode(T, InsertPos); 4167 return QualType(T, 0); 4168 } 4169 4170 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 4171 NestedNameSpecifier *NNS, 4172 const IdentifierInfo *Name, 4173 QualType Canon) const { 4174 if (Canon.isNull()) { 4175 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4176 if (CanonNNS != NNS) 4177 Canon = getDependentNameType(Keyword, CanonNNS, Name); 4178 } 4179 4180 llvm::FoldingSetNodeID ID; 4181 DependentNameType::Profile(ID, Keyword, NNS, Name); 4182 4183 void *InsertPos = nullptr; 4184 DependentNameType *T 4185 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 4186 if (T) 4187 return QualType(T, 0); 4188 4189 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon); 4190 Types.push_back(T); 4191 DependentNameTypes.InsertNode(T, InsertPos); 4192 return QualType(T, 0); 4193 } 4194 4195 QualType 4196 ASTContext::getDependentTemplateSpecializationType( 4197 ElaboratedTypeKeyword Keyword, 4198 NestedNameSpecifier *NNS, 4199 const IdentifierInfo *Name, 4200 const TemplateArgumentListInfo &Args) const { 4201 // TODO: avoid this copy 4202 SmallVector<TemplateArgument, 16> ArgCopy; 4203 for (unsigned I = 0, E = Args.size(); I != E; ++I) 4204 ArgCopy.push_back(Args[I].getArgument()); 4205 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy); 4206 } 4207 4208 QualType 4209 ASTContext::getDependentTemplateSpecializationType( 4210 ElaboratedTypeKeyword Keyword, 4211 NestedNameSpecifier *NNS, 4212 const IdentifierInfo *Name, 4213 ArrayRef<TemplateArgument> Args) const { 4214 assert((!NNS || NNS->isDependent()) && 4215 "nested-name-specifier must be dependent"); 4216 4217 llvm::FoldingSetNodeID ID; 4218 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 4219 Name, Args); 4220 4221 void *InsertPos = nullptr; 4222 DependentTemplateSpecializationType *T 4223 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4224 if (T) 4225 return QualType(T, 0); 4226 4227 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4228 4229 ElaboratedTypeKeyword CanonKeyword = Keyword; 4230 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 4231 4232 bool AnyNonCanonArgs = false; 4233 unsigned NumArgs = Args.size(); 4234 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs); 4235 for (unsigned I = 0; I != NumArgs; ++I) { 4236 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]); 4237 if (!CanonArgs[I].structurallyEquals(Args[I])) 4238 AnyNonCanonArgs = true; 4239 } 4240 4241 QualType Canon; 4242 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 4243 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 4244 Name, 4245 CanonArgs); 4246 4247 // Find the insert position again. 4248 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4249 } 4250 4251 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 4252 sizeof(TemplateArgument) * NumArgs), 4253 TypeAlignment); 4254 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 4255 Name, Args, Canon); 4256 Types.push_back(T); 4257 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 4258 return QualType(T, 0); 4259 } 4260 4261 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) { 4262 TemplateArgument Arg; 4263 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 4264 QualType ArgType = getTypeDeclType(TTP); 4265 if (TTP->isParameterPack()) 4266 ArgType = getPackExpansionType(ArgType, None); 4267 4268 Arg = TemplateArgument(ArgType); 4269 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 4270 Expr *E = new (*this) DeclRefExpr( 4271 NTTP, /*enclosing*/false, 4272 NTTP->getType().getNonLValueExprType(*this), 4273 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation()); 4274 4275 if (NTTP->isParameterPack()) 4276 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(), 4277 None); 4278 Arg = TemplateArgument(E); 4279 } else { 4280 auto *TTP = cast<TemplateTemplateParmDecl>(Param); 4281 if (TTP->isParameterPack()) 4282 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>()); 4283 else 4284 Arg = TemplateArgument(TemplateName(TTP)); 4285 } 4286 4287 if (Param->isTemplateParameterPack()) 4288 Arg = TemplateArgument::CreatePackCopy(*this, Arg); 4289 4290 return Arg; 4291 } 4292 4293 void 4294 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params, 4295 SmallVectorImpl<TemplateArgument> &Args) { 4296 Args.reserve(Args.size() + Params->size()); 4297 4298 for (NamedDecl *Param : *Params) 4299 Args.push_back(getInjectedTemplateArg(Param)); 4300 } 4301 4302 QualType ASTContext::getPackExpansionType(QualType Pattern, 4303 Optional<unsigned> NumExpansions) { 4304 llvm::FoldingSetNodeID ID; 4305 PackExpansionType::Profile(ID, Pattern, NumExpansions); 4306 4307 assert(Pattern->containsUnexpandedParameterPack() && 4308 "Pack expansions must expand one or more parameter packs"); 4309 void *InsertPos = nullptr; 4310 PackExpansionType *T 4311 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 4312 if (T) 4313 return QualType(T, 0); 4314 4315 QualType Canon; 4316 if (!Pattern.isCanonical()) { 4317 Canon = getCanonicalType(Pattern); 4318 // The canonical type might not contain an unexpanded parameter pack, if it 4319 // contains an alias template specialization which ignores one of its 4320 // parameters. 4321 if (Canon->containsUnexpandedParameterPack()) { 4322 Canon = getPackExpansionType(Canon, NumExpansions); 4323 4324 // Find the insert position again, in case we inserted an element into 4325 // PackExpansionTypes and invalidated our insert position. 4326 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 4327 } 4328 } 4329 4330 T = new (*this, TypeAlignment) 4331 PackExpansionType(Pattern, Canon, NumExpansions); 4332 Types.push_back(T); 4333 PackExpansionTypes.InsertNode(T, InsertPos); 4334 return QualType(T, 0); 4335 } 4336 4337 /// CmpProtocolNames - Comparison predicate for sorting protocols 4338 /// alphabetically. 4339 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, 4340 ObjCProtocolDecl *const *RHS) { 4341 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName()); 4342 } 4343 4344 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) { 4345 if (Protocols.empty()) return true; 4346 4347 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 4348 return false; 4349 4350 for (unsigned i = 1; i != Protocols.size(); ++i) 4351 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 || 4352 Protocols[i]->getCanonicalDecl() != Protocols[i]) 4353 return false; 4354 return true; 4355 } 4356 4357 static void 4358 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) { 4359 // Sort protocols, keyed by name. 4360 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames); 4361 4362 // Canonicalize. 4363 for (ObjCProtocolDecl *&P : Protocols) 4364 P = P->getCanonicalDecl(); 4365 4366 // Remove duplicates. 4367 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end()); 4368 Protocols.erase(ProtocolsEnd, Protocols.end()); 4369 } 4370 4371 QualType ASTContext::getObjCObjectType(QualType BaseType, 4372 ObjCProtocolDecl * const *Protocols, 4373 unsigned NumProtocols) const { 4374 return getObjCObjectType(BaseType, {}, 4375 llvm::makeArrayRef(Protocols, NumProtocols), 4376 /*isKindOf=*/false); 4377 } 4378 4379 QualType ASTContext::getObjCObjectType( 4380 QualType baseType, 4381 ArrayRef<QualType> typeArgs, 4382 ArrayRef<ObjCProtocolDecl *> protocols, 4383 bool isKindOf) const { 4384 // If the base type is an interface and there aren't any protocols or 4385 // type arguments to add, then the interface type will do just fine. 4386 if (typeArgs.empty() && protocols.empty() && !isKindOf && 4387 isa<ObjCInterfaceType>(baseType)) 4388 return baseType; 4389 4390 // Look in the folding set for an existing type. 4391 llvm::FoldingSetNodeID ID; 4392 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf); 4393 void *InsertPos = nullptr; 4394 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 4395 return QualType(QT, 0); 4396 4397 // Determine the type arguments to be used for canonicalization, 4398 // which may be explicitly specified here or written on the base 4399 // type. 4400 ArrayRef<QualType> effectiveTypeArgs = typeArgs; 4401 if (effectiveTypeArgs.empty()) { 4402 if (const auto *baseObject = baseType->getAs<ObjCObjectType>()) 4403 effectiveTypeArgs = baseObject->getTypeArgs(); 4404 } 4405 4406 // Build the canonical type, which has the canonical base type and a 4407 // sorted-and-uniqued list of protocols and the type arguments 4408 // canonicalized. 4409 QualType canonical; 4410 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(), 4411 effectiveTypeArgs.end(), 4412 [&](QualType type) { 4413 return type.isCanonical(); 4414 }); 4415 bool protocolsSorted = areSortedAndUniqued(protocols); 4416 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) { 4417 // Determine the canonical type arguments. 4418 ArrayRef<QualType> canonTypeArgs; 4419 SmallVector<QualType, 4> canonTypeArgsVec; 4420 if (!typeArgsAreCanonical) { 4421 canonTypeArgsVec.reserve(effectiveTypeArgs.size()); 4422 for (auto typeArg : effectiveTypeArgs) 4423 canonTypeArgsVec.push_back(getCanonicalType(typeArg)); 4424 canonTypeArgs = canonTypeArgsVec; 4425 } else { 4426 canonTypeArgs = effectiveTypeArgs; 4427 } 4428 4429 ArrayRef<ObjCProtocolDecl *> canonProtocols; 4430 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec; 4431 if (!protocolsSorted) { 4432 canonProtocolsVec.append(protocols.begin(), protocols.end()); 4433 SortAndUniqueProtocols(canonProtocolsVec); 4434 canonProtocols = canonProtocolsVec; 4435 } else { 4436 canonProtocols = protocols; 4437 } 4438 4439 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs, 4440 canonProtocols, isKindOf); 4441 4442 // Regenerate InsertPos. 4443 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 4444 } 4445 4446 unsigned size = sizeof(ObjCObjectTypeImpl); 4447 size += typeArgs.size() * sizeof(QualType); 4448 size += protocols.size() * sizeof(ObjCProtocolDecl *); 4449 void *mem = Allocate(size, TypeAlignment); 4450 auto *T = 4451 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols, 4452 isKindOf); 4453 4454 Types.push_back(T); 4455 ObjCObjectTypes.InsertNode(T, InsertPos); 4456 return QualType(T, 0); 4457 } 4458 4459 /// Apply Objective-C protocol qualifiers to the given type. 4460 /// If this is for the canonical type of a type parameter, we can apply 4461 /// protocol qualifiers on the ObjCObjectPointerType. 4462 QualType 4463 ASTContext::applyObjCProtocolQualifiers(QualType type, 4464 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, 4465 bool allowOnPointerType) const { 4466 hasError = false; 4467 4468 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) { 4469 return getObjCTypeParamType(objT->getDecl(), protocols); 4470 } 4471 4472 // Apply protocol qualifiers to ObjCObjectPointerType. 4473 if (allowOnPointerType) { 4474 if (const auto *objPtr = 4475 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) { 4476 const ObjCObjectType *objT = objPtr->getObjectType(); 4477 // Merge protocol lists and construct ObjCObjectType. 4478 SmallVector<ObjCProtocolDecl*, 8> protocolsVec; 4479 protocolsVec.append(objT->qual_begin(), 4480 objT->qual_end()); 4481 protocolsVec.append(protocols.begin(), protocols.end()); 4482 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec; 4483 type = getObjCObjectType( 4484 objT->getBaseType(), 4485 objT->getTypeArgsAsWritten(), 4486 protocols, 4487 objT->isKindOfTypeAsWritten()); 4488 return getObjCObjectPointerType(type); 4489 } 4490 } 4491 4492 // Apply protocol qualifiers to ObjCObjectType. 4493 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){ 4494 // FIXME: Check for protocols to which the class type is already 4495 // known to conform. 4496 4497 return getObjCObjectType(objT->getBaseType(), 4498 objT->getTypeArgsAsWritten(), 4499 protocols, 4500 objT->isKindOfTypeAsWritten()); 4501 } 4502 4503 // If the canonical type is ObjCObjectType, ... 4504 if (type->isObjCObjectType()) { 4505 // Silently overwrite any existing protocol qualifiers. 4506 // TODO: determine whether that's the right thing to do. 4507 4508 // FIXME: Check for protocols to which the class type is already 4509 // known to conform. 4510 return getObjCObjectType(type, {}, protocols, false); 4511 } 4512 4513 // id<protocol-list> 4514 if (type->isObjCIdType()) { 4515 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 4516 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols, 4517 objPtr->isKindOfType()); 4518 return getObjCObjectPointerType(type); 4519 } 4520 4521 // Class<protocol-list> 4522 if (type->isObjCClassType()) { 4523 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 4524 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols, 4525 objPtr->isKindOfType()); 4526 return getObjCObjectPointerType(type); 4527 } 4528 4529 hasError = true; 4530 return type; 4531 } 4532 4533 QualType 4534 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl, 4535 ArrayRef<ObjCProtocolDecl *> protocols, 4536 QualType Canonical) const { 4537 // Look in the folding set for an existing type. 4538 llvm::FoldingSetNodeID ID; 4539 ObjCTypeParamType::Profile(ID, Decl, protocols); 4540 void *InsertPos = nullptr; 4541 if (ObjCTypeParamType *TypeParam = 4542 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos)) 4543 return QualType(TypeParam, 0); 4544 4545 if (Canonical.isNull()) { 4546 // We canonicalize to the underlying type. 4547 Canonical = getCanonicalType(Decl->getUnderlyingType()); 4548 if (!protocols.empty()) { 4549 // Apply the protocol qualifers. 4550 bool hasError; 4551 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError, 4552 true/*allowOnPointerType*/); 4553 assert(!hasError && "Error when apply protocol qualifier to bound type"); 4554 } 4555 } 4556 4557 unsigned size = sizeof(ObjCTypeParamType); 4558 size += protocols.size() * sizeof(ObjCProtocolDecl *); 4559 void *mem = Allocate(size, TypeAlignment); 4560 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols); 4561 4562 Types.push_back(newType); 4563 ObjCTypeParamTypes.InsertNode(newType, InsertPos); 4564 return QualType(newType, 0); 4565 } 4566 4567 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's 4568 /// protocol list adopt all protocols in QT's qualified-id protocol 4569 /// list. 4570 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, 4571 ObjCInterfaceDecl *IC) { 4572 if (!QT->isObjCQualifiedIdType()) 4573 return false; 4574 4575 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) { 4576 // If both the right and left sides have qualifiers. 4577 for (auto *Proto : OPT->quals()) { 4578 if (!IC->ClassImplementsProtocol(Proto, false)) 4579 return false; 4580 } 4581 return true; 4582 } 4583 return false; 4584 } 4585 4586 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in 4587 /// QT's qualified-id protocol list adopt all protocols in IDecl's list 4588 /// of protocols. 4589 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, 4590 ObjCInterfaceDecl *IDecl) { 4591 if (!QT->isObjCQualifiedIdType()) 4592 return false; 4593 const auto *OPT = QT->getAs<ObjCObjectPointerType>(); 4594 if (!OPT) 4595 return false; 4596 if (!IDecl->hasDefinition()) 4597 return false; 4598 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols; 4599 CollectInheritedProtocols(IDecl, InheritedProtocols); 4600 if (InheritedProtocols.empty()) 4601 return false; 4602 // Check that if every protocol in list of id<plist> conforms to a protocol 4603 // of IDecl's, then bridge casting is ok. 4604 bool Conforms = false; 4605 for (auto *Proto : OPT->quals()) { 4606 Conforms = false; 4607 for (auto *PI : InheritedProtocols) { 4608 if (ProtocolCompatibleWithProtocol(Proto, PI)) { 4609 Conforms = true; 4610 break; 4611 } 4612 } 4613 if (!Conforms) 4614 break; 4615 } 4616 if (Conforms) 4617 return true; 4618 4619 for (auto *PI : InheritedProtocols) { 4620 // If both the right and left sides have qualifiers. 4621 bool Adopts = false; 4622 for (auto *Proto : OPT->quals()) { 4623 // return 'true' if 'PI' is in the inheritance hierarchy of Proto 4624 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto))) 4625 break; 4626 } 4627 if (!Adopts) 4628 return false; 4629 } 4630 return true; 4631 } 4632 4633 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 4634 /// the given object type. 4635 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 4636 llvm::FoldingSetNodeID ID; 4637 ObjCObjectPointerType::Profile(ID, ObjectT); 4638 4639 void *InsertPos = nullptr; 4640 if (ObjCObjectPointerType *QT = 4641 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 4642 return QualType(QT, 0); 4643 4644 // Find the canonical object type. 4645 QualType Canonical; 4646 if (!ObjectT.isCanonical()) { 4647 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 4648 4649 // Regenerate InsertPos. 4650 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 4651 } 4652 4653 // No match. 4654 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 4655 auto *QType = 4656 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 4657 4658 Types.push_back(QType); 4659 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 4660 return QualType(QType, 0); 4661 } 4662 4663 /// getObjCInterfaceType - Return the unique reference to the type for the 4664 /// specified ObjC interface decl. The list of protocols is optional. 4665 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 4666 ObjCInterfaceDecl *PrevDecl) const { 4667 if (Decl->TypeForDecl) 4668 return QualType(Decl->TypeForDecl, 0); 4669 4670 if (PrevDecl) { 4671 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 4672 Decl->TypeForDecl = PrevDecl->TypeForDecl; 4673 return QualType(PrevDecl->TypeForDecl, 0); 4674 } 4675 4676 // Prefer the definition, if there is one. 4677 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 4678 Decl = Def; 4679 4680 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 4681 auto *T = new (Mem) ObjCInterfaceType(Decl); 4682 Decl->TypeForDecl = T; 4683 Types.push_back(T); 4684 return QualType(T, 0); 4685 } 4686 4687 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 4688 /// TypeOfExprType AST's (since expression's are never shared). For example, 4689 /// multiple declarations that refer to "typeof(x)" all contain different 4690 /// DeclRefExpr's. This doesn't effect the type checker, since it operates 4691 /// on canonical type's (which are always unique). 4692 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 4693 TypeOfExprType *toe; 4694 if (tofExpr->isTypeDependent()) { 4695 llvm::FoldingSetNodeID ID; 4696 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 4697 4698 void *InsertPos = nullptr; 4699 DependentTypeOfExprType *Canon 4700 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 4701 if (Canon) { 4702 // We already have a "canonical" version of an identical, dependent 4703 // typeof(expr) type. Use that as our canonical type. 4704 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 4705 QualType((TypeOfExprType*)Canon, 0)); 4706 } else { 4707 // Build a new, canonical typeof(expr) type. 4708 Canon 4709 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 4710 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 4711 toe = Canon; 4712 } 4713 } else { 4714 QualType Canonical = getCanonicalType(tofExpr->getType()); 4715 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 4716 } 4717 Types.push_back(toe); 4718 return QualType(toe, 0); 4719 } 4720 4721 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 4722 /// TypeOfType nodes. The only motivation to unique these nodes would be 4723 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 4724 /// an issue. This doesn't affect the type checker, since it operates 4725 /// on canonical types (which are always unique). 4726 QualType ASTContext::getTypeOfType(QualType tofType) const { 4727 QualType Canonical = getCanonicalType(tofType); 4728 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 4729 Types.push_back(tot); 4730 return QualType(tot, 0); 4731 } 4732 4733 /// Unlike many "get<Type>" functions, we don't unique DecltypeType 4734 /// nodes. This would never be helpful, since each such type has its own 4735 /// expression, and would not give a significant memory saving, since there 4736 /// is an Expr tree under each such type. 4737 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 4738 DecltypeType *dt; 4739 4740 // C++11 [temp.type]p2: 4741 // If an expression e involves a template parameter, decltype(e) denotes a 4742 // unique dependent type. Two such decltype-specifiers refer to the same 4743 // type only if their expressions are equivalent (14.5.6.1). 4744 if (e->isInstantiationDependent()) { 4745 llvm::FoldingSetNodeID ID; 4746 DependentDecltypeType::Profile(ID, *this, e); 4747 4748 void *InsertPos = nullptr; 4749 DependentDecltypeType *Canon 4750 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 4751 if (!Canon) { 4752 // Build a new, canonical decltype(expr) type. 4753 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 4754 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 4755 } 4756 dt = new (*this, TypeAlignment) 4757 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0)); 4758 } else { 4759 dt = new (*this, TypeAlignment) 4760 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType)); 4761 } 4762 Types.push_back(dt); 4763 return QualType(dt, 0); 4764 } 4765 4766 /// getUnaryTransformationType - We don't unique these, since the memory 4767 /// savings are minimal and these are rare. 4768 QualType ASTContext::getUnaryTransformType(QualType BaseType, 4769 QualType UnderlyingType, 4770 UnaryTransformType::UTTKind Kind) 4771 const { 4772 UnaryTransformType *ut = nullptr; 4773 4774 if (BaseType->isDependentType()) { 4775 // Look in the folding set for an existing type. 4776 llvm::FoldingSetNodeID ID; 4777 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind); 4778 4779 void *InsertPos = nullptr; 4780 DependentUnaryTransformType *Canon 4781 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos); 4782 4783 if (!Canon) { 4784 // Build a new, canonical __underlying_type(type) type. 4785 Canon = new (*this, TypeAlignment) 4786 DependentUnaryTransformType(*this, getCanonicalType(BaseType), 4787 Kind); 4788 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos); 4789 } 4790 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 4791 QualType(), Kind, 4792 QualType(Canon, 0)); 4793 } else { 4794 QualType CanonType = getCanonicalType(UnderlyingType); 4795 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 4796 UnderlyingType, Kind, 4797 CanonType); 4798 } 4799 Types.push_back(ut); 4800 return QualType(ut, 0); 4801 } 4802 4803 /// getAutoType - Return the uniqued reference to the 'auto' type which has been 4804 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the 4805 /// canonical deduced-but-dependent 'auto' type. 4806 QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, 4807 bool IsDependent) const { 4808 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent) 4809 return getAutoDeductType(); 4810 4811 // Look in the folding set for an existing type. 4812 void *InsertPos = nullptr; 4813 llvm::FoldingSetNodeID ID; 4814 AutoType::Profile(ID, DeducedType, Keyword, IsDependent); 4815 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 4816 return QualType(AT, 0); 4817 4818 auto *AT = new (*this, TypeAlignment) 4819 AutoType(DeducedType, Keyword, IsDependent); 4820 Types.push_back(AT); 4821 if (InsertPos) 4822 AutoTypes.InsertNode(AT, InsertPos); 4823 return QualType(AT, 0); 4824 } 4825 4826 /// Return the uniqued reference to the deduced template specialization type 4827 /// which has been deduced to the given type, or to the canonical undeduced 4828 /// such type, or the canonical deduced-but-dependent such type. 4829 QualType ASTContext::getDeducedTemplateSpecializationType( 4830 TemplateName Template, QualType DeducedType, bool IsDependent) const { 4831 // Look in the folding set for an existing type. 4832 void *InsertPos = nullptr; 4833 llvm::FoldingSetNodeID ID; 4834 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType, 4835 IsDependent); 4836 if (DeducedTemplateSpecializationType *DTST = 4837 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos)) 4838 return QualType(DTST, 0); 4839 4840 auto *DTST = new (*this, TypeAlignment) 4841 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent); 4842 Types.push_back(DTST); 4843 if (InsertPos) 4844 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos); 4845 return QualType(DTST, 0); 4846 } 4847 4848 /// getAtomicType - Return the uniqued reference to the atomic type for 4849 /// the given value type. 4850 QualType ASTContext::getAtomicType(QualType T) const { 4851 // Unique pointers, to guarantee there is only one pointer of a particular 4852 // structure. 4853 llvm::FoldingSetNodeID ID; 4854 AtomicType::Profile(ID, T); 4855 4856 void *InsertPos = nullptr; 4857 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 4858 return QualType(AT, 0); 4859 4860 // If the atomic value type isn't canonical, this won't be a canonical type 4861 // either, so fill in the canonical type field. 4862 QualType Canonical; 4863 if (!T.isCanonical()) { 4864 Canonical = getAtomicType(getCanonicalType(T)); 4865 4866 // Get the new insert position for the node we care about. 4867 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 4868 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4869 } 4870 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 4871 Types.push_back(New); 4872 AtomicTypes.InsertNode(New, InsertPos); 4873 return QualType(New, 0); 4874 } 4875 4876 /// getAutoDeductType - Get type pattern for deducing against 'auto'. 4877 QualType ASTContext::getAutoDeductType() const { 4878 if (AutoDeductTy.isNull()) 4879 AutoDeductTy = QualType( 4880 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto, 4881 /*dependent*/false), 4882 0); 4883 return AutoDeductTy; 4884 } 4885 4886 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 4887 QualType ASTContext::getAutoRRefDeductType() const { 4888 if (AutoRRefDeductTy.isNull()) 4889 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 4890 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 4891 return AutoRRefDeductTy; 4892 } 4893 4894 /// getTagDeclType - Return the unique reference to the type for the 4895 /// specified TagDecl (struct/union/class/enum) decl. 4896 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 4897 assert(Decl); 4898 // FIXME: What is the design on getTagDeclType when it requires casting 4899 // away const? mutable? 4900 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 4901 } 4902 4903 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 4904 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 4905 /// needs to agree with the definition in <stddef.h>. 4906 CanQualType ASTContext::getSizeType() const { 4907 return getFromTargetType(Target->getSizeType()); 4908 } 4909 4910 /// Return the unique signed counterpart of the integer type 4911 /// corresponding to size_t. 4912 CanQualType ASTContext::getSignedSizeType() const { 4913 return getFromTargetType(Target->getSignedSizeType()); 4914 } 4915 4916 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 4917 CanQualType ASTContext::getIntMaxType() const { 4918 return getFromTargetType(Target->getIntMaxType()); 4919 } 4920 4921 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 4922 CanQualType ASTContext::getUIntMaxType() const { 4923 return getFromTargetType(Target->getUIntMaxType()); 4924 } 4925 4926 /// getSignedWCharType - Return the type of "signed wchar_t". 4927 /// Used when in C++, as a GCC extension. 4928 QualType ASTContext::getSignedWCharType() const { 4929 // FIXME: derive from "Target" ? 4930 return WCharTy; 4931 } 4932 4933 /// getUnsignedWCharType - Return the type of "unsigned wchar_t". 4934 /// Used when in C++, as a GCC extension. 4935 QualType ASTContext::getUnsignedWCharType() const { 4936 // FIXME: derive from "Target" ? 4937 return UnsignedIntTy; 4938 } 4939 4940 QualType ASTContext::getIntPtrType() const { 4941 return getFromTargetType(Target->getIntPtrType()); 4942 } 4943 4944 QualType ASTContext::getUIntPtrType() const { 4945 return getCorrespondingUnsignedType(getIntPtrType()); 4946 } 4947 4948 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 4949 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 4950 QualType ASTContext::getPointerDiffType() const { 4951 return getFromTargetType(Target->getPtrDiffType(0)); 4952 } 4953 4954 /// Return the unique unsigned counterpart of "ptrdiff_t" 4955 /// integer type. The standard (C11 7.21.6.1p7) refers to this type 4956 /// in the definition of %tu format specifier. 4957 QualType ASTContext::getUnsignedPointerDiffType() const { 4958 return getFromTargetType(Target->getUnsignedPtrDiffType(0)); 4959 } 4960 4961 /// Return the unique type for "pid_t" defined in 4962 /// <sys/types.h>. We need this to compute the correct type for vfork(). 4963 QualType ASTContext::getProcessIDType() const { 4964 return getFromTargetType(Target->getProcessIDType()); 4965 } 4966 4967 //===----------------------------------------------------------------------===// 4968 // Type Operators 4969 //===----------------------------------------------------------------------===// 4970 4971 CanQualType ASTContext::getCanonicalParamType(QualType T) const { 4972 // Push qualifiers into arrays, and then discard any remaining 4973 // qualifiers. 4974 T = getCanonicalType(T); 4975 T = getVariableArrayDecayedType(T); 4976 const Type *Ty = T.getTypePtr(); 4977 QualType Result; 4978 if (isa<ArrayType>(Ty)) { 4979 Result = getArrayDecayedType(QualType(Ty,0)); 4980 } else if (isa<FunctionType>(Ty)) { 4981 Result = getPointerType(QualType(Ty, 0)); 4982 } else { 4983 Result = QualType(Ty, 0); 4984 } 4985 4986 return CanQualType::CreateUnsafe(Result); 4987 } 4988 4989 QualType ASTContext::getUnqualifiedArrayType(QualType type, 4990 Qualifiers &quals) { 4991 SplitQualType splitType = type.getSplitUnqualifiedType(); 4992 4993 // FIXME: getSplitUnqualifiedType() actually walks all the way to 4994 // the unqualified desugared type and then drops it on the floor. 4995 // We then have to strip that sugar back off with 4996 // getUnqualifiedDesugaredType(), which is silly. 4997 const auto *AT = 4998 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 4999 5000 // If we don't have an array, just use the results in splitType. 5001 if (!AT) { 5002 quals = splitType.Quals; 5003 return QualType(splitType.Ty, 0); 5004 } 5005 5006 // Otherwise, recurse on the array's element type. 5007 QualType elementType = AT->getElementType(); 5008 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 5009 5010 // If that didn't change the element type, AT has no qualifiers, so we 5011 // can just use the results in splitType. 5012 if (elementType == unqualElementType) { 5013 assert(quals.empty()); // from the recursive call 5014 quals = splitType.Quals; 5015 return QualType(splitType.Ty, 0); 5016 } 5017 5018 // Otherwise, add in the qualifiers from the outermost type, then 5019 // build the type back up. 5020 quals.addConsistentQualifiers(splitType.Quals); 5021 5022 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 5023 return getConstantArrayType(unqualElementType, CAT->getSize(), 5024 CAT->getSizeModifier(), 0); 5025 } 5026 5027 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) { 5028 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 5029 } 5030 5031 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) { 5032 return getVariableArrayType(unqualElementType, 5033 VAT->getSizeExpr(), 5034 VAT->getSizeModifier(), 5035 VAT->getIndexTypeCVRQualifiers(), 5036 VAT->getBracketsRange()); 5037 } 5038 5039 const auto *DSAT = cast<DependentSizedArrayType>(AT); 5040 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 5041 DSAT->getSizeModifier(), 0, 5042 SourceRange()); 5043 } 5044 5045 /// Attempt to unwrap two types that may both be array types with the same bound 5046 /// (or both be array types of unknown bound) for the purpose of comparing the 5047 /// cv-decomposition of two types per C++ [conv.qual]. 5048 bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) { 5049 bool UnwrappedAny = false; 5050 while (true) { 5051 auto *AT1 = getAsArrayType(T1); 5052 if (!AT1) return UnwrappedAny; 5053 5054 auto *AT2 = getAsArrayType(T2); 5055 if (!AT2) return UnwrappedAny; 5056 5057 // If we don't have two array types with the same constant bound nor two 5058 // incomplete array types, we've unwrapped everything we can. 5059 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) { 5060 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2); 5061 if (!CAT2 || CAT1->getSize() != CAT2->getSize()) 5062 return UnwrappedAny; 5063 } else if (!isa<IncompleteArrayType>(AT1) || 5064 !isa<IncompleteArrayType>(AT2)) { 5065 return UnwrappedAny; 5066 } 5067 5068 T1 = AT1->getElementType(); 5069 T2 = AT2->getElementType(); 5070 UnwrappedAny = true; 5071 } 5072 } 5073 5074 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]). 5075 /// 5076 /// If T1 and T2 are both pointer types of the same kind, or both array types 5077 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is 5078 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored. 5079 /// 5080 /// This function will typically be called in a loop that successively 5081 /// "unwraps" pointer and pointer-to-member types to compare them at each 5082 /// level. 5083 /// 5084 /// \return \c true if a pointer type was unwrapped, \c false if we reached a 5085 /// pair of types that can't be unwrapped further. 5086 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) { 5087 UnwrapSimilarArrayTypes(T1, T2); 5088 5089 const auto *T1PtrType = T1->getAs<PointerType>(); 5090 const auto *T2PtrType = T2->getAs<PointerType>(); 5091 if (T1PtrType && T2PtrType) { 5092 T1 = T1PtrType->getPointeeType(); 5093 T2 = T2PtrType->getPointeeType(); 5094 return true; 5095 } 5096 5097 const auto *T1MPType = T1->getAs<MemberPointerType>(); 5098 const auto *T2MPType = T2->getAs<MemberPointerType>(); 5099 if (T1MPType && T2MPType && 5100 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 5101 QualType(T2MPType->getClass(), 0))) { 5102 T1 = T1MPType->getPointeeType(); 5103 T2 = T2MPType->getPointeeType(); 5104 return true; 5105 } 5106 5107 if (getLangOpts().ObjC1) { 5108 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>(); 5109 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>(); 5110 if (T1OPType && T2OPType) { 5111 T1 = T1OPType->getPointeeType(); 5112 T2 = T2OPType->getPointeeType(); 5113 return true; 5114 } 5115 } 5116 5117 // FIXME: Block pointers, too? 5118 5119 return false; 5120 } 5121 5122 bool ASTContext::hasSimilarType(QualType T1, QualType T2) { 5123 while (true) { 5124 Qualifiers Quals; 5125 T1 = getUnqualifiedArrayType(T1, Quals); 5126 T2 = getUnqualifiedArrayType(T2, Quals); 5127 if (hasSameType(T1, T2)) 5128 return true; 5129 if (!UnwrapSimilarTypes(T1, T2)) 5130 return false; 5131 } 5132 } 5133 5134 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) { 5135 while (true) { 5136 Qualifiers Quals1, Quals2; 5137 T1 = getUnqualifiedArrayType(T1, Quals1); 5138 T2 = getUnqualifiedArrayType(T2, Quals2); 5139 5140 Quals1.removeCVRQualifiers(); 5141 Quals2.removeCVRQualifiers(); 5142 if (Quals1 != Quals2) 5143 return false; 5144 5145 if (hasSameType(T1, T2)) 5146 return true; 5147 5148 if (!UnwrapSimilarTypes(T1, T2)) 5149 return false; 5150 } 5151 } 5152 5153 DeclarationNameInfo 5154 ASTContext::getNameForTemplate(TemplateName Name, 5155 SourceLocation NameLoc) const { 5156 switch (Name.getKind()) { 5157 case TemplateName::QualifiedTemplate: 5158 case TemplateName::Template: 5159 // DNInfo work in progress: CHECKME: what about DNLoc? 5160 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 5161 NameLoc); 5162 5163 case TemplateName::OverloadedTemplate: { 5164 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 5165 // DNInfo work in progress: CHECKME: what about DNLoc? 5166 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 5167 } 5168 5169 case TemplateName::DependentTemplate: { 5170 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 5171 DeclarationName DName; 5172 if (DTN->isIdentifier()) { 5173 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 5174 return DeclarationNameInfo(DName, NameLoc); 5175 } else { 5176 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 5177 // DNInfo work in progress: FIXME: source locations? 5178 DeclarationNameLoc DNLoc; 5179 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding(); 5180 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding(); 5181 return DeclarationNameInfo(DName, NameLoc, DNLoc); 5182 } 5183 } 5184 5185 case TemplateName::SubstTemplateTemplateParm: { 5186 SubstTemplateTemplateParmStorage *subst 5187 = Name.getAsSubstTemplateTemplateParm(); 5188 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 5189 NameLoc); 5190 } 5191 5192 case TemplateName::SubstTemplateTemplateParmPack: { 5193 SubstTemplateTemplateParmPackStorage *subst 5194 = Name.getAsSubstTemplateTemplateParmPack(); 5195 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 5196 NameLoc); 5197 } 5198 } 5199 5200 llvm_unreachable("bad template name kind!"); 5201 } 5202 5203 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { 5204 switch (Name.getKind()) { 5205 case TemplateName::QualifiedTemplate: 5206 case TemplateName::Template: { 5207 TemplateDecl *Template = Name.getAsTemplateDecl(); 5208 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template)) 5209 Template = getCanonicalTemplateTemplateParmDecl(TTP); 5210 5211 // The canonical template name is the canonical template declaration. 5212 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 5213 } 5214 5215 case TemplateName::OverloadedTemplate: 5216 llvm_unreachable("cannot canonicalize overloaded template"); 5217 5218 case TemplateName::DependentTemplate: { 5219 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 5220 assert(DTN && "Non-dependent template names must refer to template decls."); 5221 return DTN->CanonicalTemplateName; 5222 } 5223 5224 case TemplateName::SubstTemplateTemplateParm: { 5225 SubstTemplateTemplateParmStorage *subst 5226 = Name.getAsSubstTemplateTemplateParm(); 5227 return getCanonicalTemplateName(subst->getReplacement()); 5228 } 5229 5230 case TemplateName::SubstTemplateTemplateParmPack: { 5231 SubstTemplateTemplateParmPackStorage *subst 5232 = Name.getAsSubstTemplateTemplateParmPack(); 5233 TemplateTemplateParmDecl *canonParameter 5234 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 5235 TemplateArgument canonArgPack 5236 = getCanonicalTemplateArgument(subst->getArgumentPack()); 5237 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 5238 } 5239 } 5240 5241 llvm_unreachable("bad template name!"); 5242 } 5243 5244 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 5245 X = getCanonicalTemplateName(X); 5246 Y = getCanonicalTemplateName(Y); 5247 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 5248 } 5249 5250 TemplateArgument 5251 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 5252 switch (Arg.getKind()) { 5253 case TemplateArgument::Null: 5254 return Arg; 5255 5256 case TemplateArgument::Expression: 5257 return Arg; 5258 5259 case TemplateArgument::Declaration: { 5260 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); 5261 return TemplateArgument(D, Arg.getParamTypeForDecl()); 5262 } 5263 5264 case TemplateArgument::NullPtr: 5265 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), 5266 /*isNullPtr*/true); 5267 5268 case TemplateArgument::Template: 5269 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 5270 5271 case TemplateArgument::TemplateExpansion: 5272 return TemplateArgument(getCanonicalTemplateName( 5273 Arg.getAsTemplateOrTemplatePattern()), 5274 Arg.getNumTemplateExpansions()); 5275 5276 case TemplateArgument::Integral: 5277 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 5278 5279 case TemplateArgument::Type: 5280 return TemplateArgument(getCanonicalType(Arg.getAsType())); 5281 5282 case TemplateArgument::Pack: { 5283 if (Arg.pack_size() == 0) 5284 return Arg; 5285 5286 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()]; 5287 unsigned Idx = 0; 5288 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 5289 AEnd = Arg.pack_end(); 5290 A != AEnd; (void)++A, ++Idx) 5291 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 5292 5293 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size())); 5294 } 5295 } 5296 5297 // Silence GCC warning 5298 llvm_unreachable("Unhandled template argument kind"); 5299 } 5300 5301 NestedNameSpecifier * 5302 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 5303 if (!NNS) 5304 return nullptr; 5305 5306 switch (NNS->getKind()) { 5307 case NestedNameSpecifier::Identifier: 5308 // Canonicalize the prefix but keep the identifier the same. 5309 return NestedNameSpecifier::Create(*this, 5310 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 5311 NNS->getAsIdentifier()); 5312 5313 case NestedNameSpecifier::Namespace: 5314 // A namespace is canonical; build a nested-name-specifier with 5315 // this namespace and no prefix. 5316 return NestedNameSpecifier::Create(*this, nullptr, 5317 NNS->getAsNamespace()->getOriginalNamespace()); 5318 5319 case NestedNameSpecifier::NamespaceAlias: 5320 // A namespace is canonical; build a nested-name-specifier with 5321 // this namespace and no prefix. 5322 return NestedNameSpecifier::Create(*this, nullptr, 5323 NNS->getAsNamespaceAlias()->getNamespace() 5324 ->getOriginalNamespace()); 5325 5326 case NestedNameSpecifier::TypeSpec: 5327 case NestedNameSpecifier::TypeSpecWithTemplate: { 5328 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 5329 5330 // If we have some kind of dependent-named type (e.g., "typename T::type"), 5331 // break it apart into its prefix and identifier, then reconsititute those 5332 // as the canonical nested-name-specifier. This is required to canonicalize 5333 // a dependent nested-name-specifier involving typedefs of dependent-name 5334 // types, e.g., 5335 // typedef typename T::type T1; 5336 // typedef typename T1::type T2; 5337 if (const auto *DNT = T->getAs<DependentNameType>()) 5338 return NestedNameSpecifier::Create(*this, DNT->getQualifier(), 5339 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 5340 5341 // Otherwise, just canonicalize the type, and force it to be a TypeSpec. 5342 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the 5343 // first place? 5344 return NestedNameSpecifier::Create(*this, nullptr, false, 5345 const_cast<Type *>(T.getTypePtr())); 5346 } 5347 5348 case NestedNameSpecifier::Global: 5349 case NestedNameSpecifier::Super: 5350 // The global specifier and __super specifer are canonical and unique. 5351 return NNS; 5352 } 5353 5354 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 5355 } 5356 5357 const ArrayType *ASTContext::getAsArrayType(QualType T) const { 5358 // Handle the non-qualified case efficiently. 5359 if (!T.hasLocalQualifiers()) { 5360 // Handle the common positive case fast. 5361 if (const auto *AT = dyn_cast<ArrayType>(T)) 5362 return AT; 5363 } 5364 5365 // Handle the common negative case fast. 5366 if (!isa<ArrayType>(T.getCanonicalType())) 5367 return nullptr; 5368 5369 // Apply any qualifiers from the array type to the element type. This 5370 // implements C99 6.7.3p8: "If the specification of an array type includes 5371 // any type qualifiers, the element type is so qualified, not the array type." 5372 5373 // If we get here, we either have type qualifiers on the type, or we have 5374 // sugar such as a typedef in the way. If we have type qualifiers on the type 5375 // we must propagate them down into the element type. 5376 5377 SplitQualType split = T.getSplitDesugaredType(); 5378 Qualifiers qs = split.Quals; 5379 5380 // If we have a simple case, just return now. 5381 const auto *ATy = dyn_cast<ArrayType>(split.Ty); 5382 if (!ATy || qs.empty()) 5383 return ATy; 5384 5385 // Otherwise, we have an array and we have qualifiers on it. Push the 5386 // qualifiers into the array element type and return a new array type. 5387 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 5388 5389 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy)) 5390 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 5391 CAT->getSizeModifier(), 5392 CAT->getIndexTypeCVRQualifiers())); 5393 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy)) 5394 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 5395 IAT->getSizeModifier(), 5396 IAT->getIndexTypeCVRQualifiers())); 5397 5398 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy)) 5399 return cast<ArrayType>( 5400 getDependentSizedArrayType(NewEltTy, 5401 DSAT->getSizeExpr(), 5402 DSAT->getSizeModifier(), 5403 DSAT->getIndexTypeCVRQualifiers(), 5404 DSAT->getBracketsRange())); 5405 5406 const auto *VAT = cast<VariableArrayType>(ATy); 5407 return cast<ArrayType>(getVariableArrayType(NewEltTy, 5408 VAT->getSizeExpr(), 5409 VAT->getSizeModifier(), 5410 VAT->getIndexTypeCVRQualifiers(), 5411 VAT->getBracketsRange())); 5412 } 5413 5414 QualType ASTContext::getAdjustedParameterType(QualType T) const { 5415 if (T->isArrayType() || T->isFunctionType()) 5416 return getDecayedType(T); 5417 return T; 5418 } 5419 5420 QualType ASTContext::getSignatureParameterType(QualType T) const { 5421 T = getVariableArrayDecayedType(T); 5422 T = getAdjustedParameterType(T); 5423 return T.getUnqualifiedType(); 5424 } 5425 5426 QualType ASTContext::getExceptionObjectType(QualType T) const { 5427 // C++ [except.throw]p3: 5428 // A throw-expression initializes a temporary object, called the exception 5429 // object, the type of which is determined by removing any top-level 5430 // cv-qualifiers from the static type of the operand of throw and adjusting 5431 // the type from "array of T" or "function returning T" to "pointer to T" 5432 // or "pointer to function returning T", [...] 5433 T = getVariableArrayDecayedType(T); 5434 if (T->isArrayType() || T->isFunctionType()) 5435 T = getDecayedType(T); 5436 return T.getUnqualifiedType(); 5437 } 5438 5439 /// getArrayDecayedType - Return the properly qualified result of decaying the 5440 /// specified array type to a pointer. This operation is non-trivial when 5441 /// handling typedefs etc. The canonical type of "T" must be an array type, 5442 /// this returns a pointer to a properly qualified element of the array. 5443 /// 5444 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 5445 QualType ASTContext::getArrayDecayedType(QualType Ty) const { 5446 // Get the element type with 'getAsArrayType' so that we don't lose any 5447 // typedefs in the element type of the array. This also handles propagation 5448 // of type qualifiers from the array type into the element type if present 5449 // (C99 6.7.3p8). 5450 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 5451 assert(PrettyArrayType && "Not an array type!"); 5452 5453 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 5454 5455 // int x[restrict 4] -> int *restrict 5456 QualType Result = getQualifiedType(PtrTy, 5457 PrettyArrayType->getIndexTypeQualifiers()); 5458 5459 // int x[_Nullable] -> int * _Nullable 5460 if (auto Nullability = Ty->getNullability(*this)) { 5461 Result = const_cast<ASTContext *>(this)->getAttributedType( 5462 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result); 5463 } 5464 return Result; 5465 } 5466 5467 QualType ASTContext::getBaseElementType(const ArrayType *array) const { 5468 return getBaseElementType(array->getElementType()); 5469 } 5470 5471 QualType ASTContext::getBaseElementType(QualType type) const { 5472 Qualifiers qs; 5473 while (true) { 5474 SplitQualType split = type.getSplitDesugaredType(); 5475 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 5476 if (!array) break; 5477 5478 type = array->getElementType(); 5479 qs.addConsistentQualifiers(split.Quals); 5480 } 5481 5482 return getQualifiedType(type, qs); 5483 } 5484 5485 /// getConstantArrayElementCount - Returns number of constant array elements. 5486 uint64_t 5487 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 5488 uint64_t ElementCount = 1; 5489 do { 5490 ElementCount *= CA->getSize().getZExtValue(); 5491 CA = dyn_cast_or_null<ConstantArrayType>( 5492 CA->getElementType()->getAsArrayTypeUnsafe()); 5493 } while (CA); 5494 return ElementCount; 5495 } 5496 5497 /// getFloatingRank - Return a relative rank for floating point types. 5498 /// This routine will assert if passed a built-in type that isn't a float. 5499 static FloatingRank getFloatingRank(QualType T) { 5500 if (const auto *CT = T->getAs<ComplexType>()) 5501 return getFloatingRank(CT->getElementType()); 5502 5503 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type"); 5504 switch (T->getAs<BuiltinType>()->getKind()) { 5505 default: llvm_unreachable("getFloatingRank(): not a floating type"); 5506 case BuiltinType::Float16: return Float16Rank; 5507 case BuiltinType::Half: return HalfRank; 5508 case BuiltinType::Float: return FloatRank; 5509 case BuiltinType::Double: return DoubleRank; 5510 case BuiltinType::LongDouble: return LongDoubleRank; 5511 case BuiltinType::Float128: return Float128Rank; 5512 } 5513 } 5514 5515 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating 5516 /// point or a complex type (based on typeDomain/typeSize). 5517 /// 'typeDomain' is a real floating point or complex type. 5518 /// 'typeSize' is a real floating point or complex type. 5519 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 5520 QualType Domain) const { 5521 FloatingRank EltRank = getFloatingRank(Size); 5522 if (Domain->isComplexType()) { 5523 switch (EltRank) { 5524 case Float16Rank: 5525 case HalfRank: llvm_unreachable("Complex half is not supported"); 5526 case FloatRank: return FloatComplexTy; 5527 case DoubleRank: return DoubleComplexTy; 5528 case LongDoubleRank: return LongDoubleComplexTy; 5529 case Float128Rank: return Float128ComplexTy; 5530 } 5531 } 5532 5533 assert(Domain->isRealFloatingType() && "Unknown domain!"); 5534 switch (EltRank) { 5535 case Float16Rank: return HalfTy; 5536 case HalfRank: return HalfTy; 5537 case FloatRank: return FloatTy; 5538 case DoubleRank: return DoubleTy; 5539 case LongDoubleRank: return LongDoubleTy; 5540 case Float128Rank: return Float128Ty; 5541 } 5542 llvm_unreachable("getFloatingRank(): illegal value for rank"); 5543 } 5544 5545 /// getFloatingTypeOrder - Compare the rank of the two specified floating 5546 /// point types, ignoring the domain of the type (i.e. 'double' == 5547 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 5548 /// LHS < RHS, return -1. 5549 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 5550 FloatingRank LHSR = getFloatingRank(LHS); 5551 FloatingRank RHSR = getFloatingRank(RHS); 5552 5553 if (LHSR == RHSR) 5554 return 0; 5555 if (LHSR > RHSR) 5556 return 1; 5557 return -1; 5558 } 5559 5560 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 5561 /// routine will assert if passed a built-in type that isn't an integer or enum, 5562 /// or if it is not canonicalized. 5563 unsigned ASTContext::getIntegerRank(const Type *T) const { 5564 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 5565 5566 switch (cast<BuiltinType>(T)->getKind()) { 5567 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 5568 case BuiltinType::Bool: 5569 return 1 + (getIntWidth(BoolTy) << 3); 5570 case BuiltinType::Char_S: 5571 case BuiltinType::Char_U: 5572 case BuiltinType::SChar: 5573 case BuiltinType::UChar: 5574 return 2 + (getIntWidth(CharTy) << 3); 5575 case BuiltinType::Short: 5576 case BuiltinType::UShort: 5577 return 3 + (getIntWidth(ShortTy) << 3); 5578 case BuiltinType::Int: 5579 case BuiltinType::UInt: 5580 return 4 + (getIntWidth(IntTy) << 3); 5581 case BuiltinType::Long: 5582 case BuiltinType::ULong: 5583 return 5 + (getIntWidth(LongTy) << 3); 5584 case BuiltinType::LongLong: 5585 case BuiltinType::ULongLong: 5586 return 6 + (getIntWidth(LongLongTy) << 3); 5587 case BuiltinType::Int128: 5588 case BuiltinType::UInt128: 5589 return 7 + (getIntWidth(Int128Ty) << 3); 5590 } 5591 } 5592 5593 /// Whether this is a promotable bitfield reference according 5594 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 5595 /// 5596 /// \returns the type this bit-field will promote to, or NULL if no 5597 /// promotion occurs. 5598 QualType ASTContext::isPromotableBitField(Expr *E) const { 5599 if (E->isTypeDependent() || E->isValueDependent()) 5600 return {}; 5601 5602 // C++ [conv.prom]p5: 5603 // If the bit-field has an enumerated type, it is treated as any other 5604 // value of that type for promotion purposes. 5605 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType()) 5606 return {}; 5607 5608 // FIXME: We should not do this unless E->refersToBitField() is true. This 5609 // matters in C where getSourceBitField() will find bit-fields for various 5610 // cases where the source expression is not a bit-field designator. 5611 5612 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? 5613 if (!Field) 5614 return {}; 5615 5616 QualType FT = Field->getType(); 5617 5618 uint64_t BitWidth = Field->getBitWidthValue(*this); 5619 uint64_t IntSize = getTypeSize(IntTy); 5620 // C++ [conv.prom]p5: 5621 // A prvalue for an integral bit-field can be converted to a prvalue of type 5622 // int if int can represent all the values of the bit-field; otherwise, it 5623 // can be converted to unsigned int if unsigned int can represent all the 5624 // values of the bit-field. If the bit-field is larger yet, no integral 5625 // promotion applies to it. 5626 // C11 6.3.1.1/2: 5627 // [For a bit-field of type _Bool, int, signed int, or unsigned int:] 5628 // If an int can represent all values of the original type (as restricted by 5629 // the width, for a bit-field), the value is converted to an int; otherwise, 5630 // it is converted to an unsigned int. 5631 // 5632 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int. 5633 // We perform that promotion here to match GCC and C++. 5634 // FIXME: C does not permit promotion of an enum bit-field whose rank is 5635 // greater than that of 'int'. We perform that promotion to match GCC. 5636 if (BitWidth < IntSize) 5637 return IntTy; 5638 5639 if (BitWidth == IntSize) 5640 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 5641 5642 // Bit-fields wider than int are not subject to promotions, and therefore act 5643 // like the base type. GCC has some weird bugs in this area that we 5644 // deliberately do not follow (GCC follows a pre-standard resolution to 5645 // C's DR315 which treats bit-width as being part of the type, and this leaks 5646 // into their semantics in some cases). 5647 return {}; 5648 } 5649 5650 /// getPromotedIntegerType - Returns the type that Promotable will 5651 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 5652 /// integer type. 5653 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 5654 assert(!Promotable.isNull()); 5655 assert(Promotable->isPromotableIntegerType()); 5656 if (const auto *ET = Promotable->getAs<EnumType>()) 5657 return ET->getDecl()->getPromotionType(); 5658 5659 if (const auto *BT = Promotable->getAs<BuiltinType>()) { 5660 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 5661 // (3.9.1) can be converted to a prvalue of the first of the following 5662 // types that can represent all the values of its underlying type: 5663 // int, unsigned int, long int, unsigned long int, long long int, or 5664 // unsigned long long int [...] 5665 // FIXME: Is there some better way to compute this? 5666 if (BT->getKind() == BuiltinType::WChar_S || 5667 BT->getKind() == BuiltinType::WChar_U || 5668 BT->getKind() == BuiltinType::Char8 || 5669 BT->getKind() == BuiltinType::Char16 || 5670 BT->getKind() == BuiltinType::Char32) { 5671 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 5672 uint64_t FromSize = getTypeSize(BT); 5673 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 5674 LongLongTy, UnsignedLongLongTy }; 5675 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 5676 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 5677 if (FromSize < ToSize || 5678 (FromSize == ToSize && 5679 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 5680 return PromoteTypes[Idx]; 5681 } 5682 llvm_unreachable("char type should fit into long long"); 5683 } 5684 } 5685 5686 // At this point, we should have a signed or unsigned integer type. 5687 if (Promotable->isSignedIntegerType()) 5688 return IntTy; 5689 uint64_t PromotableSize = getIntWidth(Promotable); 5690 uint64_t IntSize = getIntWidth(IntTy); 5691 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 5692 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 5693 } 5694 5695 /// Recurses in pointer/array types until it finds an objc retainable 5696 /// type and returns its ownership. 5697 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 5698 while (!T.isNull()) { 5699 if (T.getObjCLifetime() != Qualifiers::OCL_None) 5700 return T.getObjCLifetime(); 5701 if (T->isArrayType()) 5702 T = getBaseElementType(T); 5703 else if (const auto *PT = T->getAs<PointerType>()) 5704 T = PT->getPointeeType(); 5705 else if (const auto *RT = T->getAs<ReferenceType>()) 5706 T = RT->getPointeeType(); 5707 else 5708 break; 5709 } 5710 5711 return Qualifiers::OCL_None; 5712 } 5713 5714 static const Type *getIntegerTypeForEnum(const EnumType *ET) { 5715 // Incomplete enum types are not treated as integer types. 5716 // FIXME: In C++, enum types are never integer types. 5717 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 5718 return ET->getDecl()->getIntegerType().getTypePtr(); 5719 return nullptr; 5720 } 5721 5722 /// getIntegerTypeOrder - Returns the highest ranked integer type: 5723 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 5724 /// LHS < RHS, return -1. 5725 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 5726 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 5727 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 5728 5729 // Unwrap enums to their underlying type. 5730 if (const auto *ET = dyn_cast<EnumType>(LHSC)) 5731 LHSC = getIntegerTypeForEnum(ET); 5732 if (const auto *ET = dyn_cast<EnumType>(RHSC)) 5733 RHSC = getIntegerTypeForEnum(ET); 5734 5735 if (LHSC == RHSC) return 0; 5736 5737 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 5738 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 5739 5740 unsigned LHSRank = getIntegerRank(LHSC); 5741 unsigned RHSRank = getIntegerRank(RHSC); 5742 5743 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 5744 if (LHSRank == RHSRank) return 0; 5745 return LHSRank > RHSRank ? 1 : -1; 5746 } 5747 5748 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 5749 if (LHSUnsigned) { 5750 // If the unsigned [LHS] type is larger, return it. 5751 if (LHSRank >= RHSRank) 5752 return 1; 5753 5754 // If the signed type can represent all values of the unsigned type, it 5755 // wins. Because we are dealing with 2's complement and types that are 5756 // powers of two larger than each other, this is always safe. 5757 return -1; 5758 } 5759 5760 // If the unsigned [RHS] type is larger, return it. 5761 if (RHSRank >= LHSRank) 5762 return -1; 5763 5764 // If the signed type can represent all values of the unsigned type, it 5765 // wins. Because we are dealing with 2's complement and types that are 5766 // powers of two larger than each other, this is always safe. 5767 return 1; 5768 } 5769 5770 TypedefDecl *ASTContext::getCFConstantStringDecl() const { 5771 if (!CFConstantStringTypeDecl) { 5772 assert(!CFConstantStringTagDecl && 5773 "tag and typedef should be initialized together"); 5774 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag"); 5775 CFConstantStringTagDecl->startDefinition(); 5776 5777 QualType FieldTypes[4]; 5778 const char *FieldNames[4]; 5779 5780 // const int *isa; 5781 FieldTypes[0] = getPointerType(IntTy.withConst()); 5782 FieldNames[0] = "isa"; 5783 // int flags; 5784 FieldTypes[1] = IntTy; 5785 FieldNames[1] = "flags"; 5786 // const char *str; 5787 FieldTypes[2] = getPointerType(CharTy.withConst()); 5788 FieldNames[2] = "str"; 5789 // long length; 5790 FieldTypes[3] = LongTy; 5791 FieldNames[3] = "length"; 5792 5793 // Create fields 5794 for (unsigned i = 0; i < 4; ++i) { 5795 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl, 5796 SourceLocation(), 5797 SourceLocation(), 5798 &Idents.get(FieldNames[i]), 5799 FieldTypes[i], /*TInfo=*/nullptr, 5800 /*BitWidth=*/nullptr, 5801 /*Mutable=*/false, 5802 ICIS_NoInit); 5803 Field->setAccess(AS_public); 5804 CFConstantStringTagDecl->addDecl(Field); 5805 } 5806 5807 CFConstantStringTagDecl->completeDefinition(); 5808 // This type is designed to be compatible with NSConstantString, but cannot 5809 // use the same name, since NSConstantString is an interface. 5810 auto tagType = getTagDeclType(CFConstantStringTagDecl); 5811 CFConstantStringTypeDecl = 5812 buildImplicitTypedef(tagType, "__NSConstantString"); 5813 } 5814 5815 return CFConstantStringTypeDecl; 5816 } 5817 5818 RecordDecl *ASTContext::getCFConstantStringTagDecl() const { 5819 if (!CFConstantStringTagDecl) 5820 getCFConstantStringDecl(); // Build the tag and the typedef. 5821 return CFConstantStringTagDecl; 5822 } 5823 5824 // getCFConstantStringType - Return the type used for constant CFStrings. 5825 QualType ASTContext::getCFConstantStringType() const { 5826 return getTypedefType(getCFConstantStringDecl()); 5827 } 5828 5829 QualType ASTContext::getObjCSuperType() const { 5830 if (ObjCSuperType.isNull()) { 5831 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super"); 5832 TUDecl->addDecl(ObjCSuperTypeDecl); 5833 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); 5834 } 5835 return ObjCSuperType; 5836 } 5837 5838 void ASTContext::setCFConstantStringType(QualType T) { 5839 const auto *TD = T->getAs<TypedefType>(); 5840 assert(TD && "Invalid CFConstantStringType"); 5841 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl()); 5842 const auto *TagType = 5843 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>(); 5844 assert(TagType && "Invalid CFConstantStringType"); 5845 CFConstantStringTagDecl = TagType->getDecl(); 5846 } 5847 5848 QualType ASTContext::getBlockDescriptorType() const { 5849 if (BlockDescriptorType) 5850 return getTagDeclType(BlockDescriptorType); 5851 5852 RecordDecl *RD; 5853 // FIXME: Needs the FlagAppleBlock bit. 5854 RD = buildImplicitRecord("__block_descriptor"); 5855 RD->startDefinition(); 5856 5857 QualType FieldTypes[] = { 5858 UnsignedLongTy, 5859 UnsignedLongTy, 5860 }; 5861 5862 static const char *const FieldNames[] = { 5863 "reserved", 5864 "Size" 5865 }; 5866 5867 for (size_t i = 0; i < 2; ++i) { 5868 FieldDecl *Field = FieldDecl::Create( 5869 *this, RD, SourceLocation(), SourceLocation(), 5870 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 5871 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 5872 Field->setAccess(AS_public); 5873 RD->addDecl(Field); 5874 } 5875 5876 RD->completeDefinition(); 5877 5878 BlockDescriptorType = RD; 5879 5880 return getTagDeclType(BlockDescriptorType); 5881 } 5882 5883 QualType ASTContext::getBlockDescriptorExtendedType() const { 5884 if (BlockDescriptorExtendedType) 5885 return getTagDeclType(BlockDescriptorExtendedType); 5886 5887 RecordDecl *RD; 5888 // FIXME: Needs the FlagAppleBlock bit. 5889 RD = buildImplicitRecord("__block_descriptor_withcopydispose"); 5890 RD->startDefinition(); 5891 5892 QualType FieldTypes[] = { 5893 UnsignedLongTy, 5894 UnsignedLongTy, 5895 getPointerType(VoidPtrTy), 5896 getPointerType(VoidPtrTy) 5897 }; 5898 5899 static const char *const FieldNames[] = { 5900 "reserved", 5901 "Size", 5902 "CopyFuncPtr", 5903 "DestroyFuncPtr" 5904 }; 5905 5906 for (size_t i = 0; i < 4; ++i) { 5907 FieldDecl *Field = FieldDecl::Create( 5908 *this, RD, SourceLocation(), SourceLocation(), 5909 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 5910 /*BitWidth=*/nullptr, 5911 /*Mutable=*/false, ICIS_NoInit); 5912 Field->setAccess(AS_public); 5913 RD->addDecl(Field); 5914 } 5915 5916 RD->completeDefinition(); 5917 5918 BlockDescriptorExtendedType = RD; 5919 return getTagDeclType(BlockDescriptorExtendedType); 5920 } 5921 5922 TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const { 5923 const auto *BT = dyn_cast<BuiltinType>(T); 5924 5925 if (!BT) { 5926 if (isa<PipeType>(T)) 5927 return TargetInfo::OCLTK_Pipe; 5928 5929 return TargetInfo::OCLTK_Default; 5930 } 5931 5932 switch (BT->getKind()) { 5933 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5934 case BuiltinType::Id: \ 5935 return TargetInfo::OCLTK_Image; 5936 #include "clang/Basic/OpenCLImageTypes.def" 5937 5938 case BuiltinType::OCLClkEvent: 5939 return TargetInfo::OCLTK_ClkEvent; 5940 5941 case BuiltinType::OCLEvent: 5942 return TargetInfo::OCLTK_Event; 5943 5944 case BuiltinType::OCLQueue: 5945 return TargetInfo::OCLTK_Queue; 5946 5947 case BuiltinType::OCLReserveID: 5948 return TargetInfo::OCLTK_ReserveID; 5949 5950 case BuiltinType::OCLSampler: 5951 return TargetInfo::OCLTK_Sampler; 5952 5953 default: 5954 return TargetInfo::OCLTK_Default; 5955 } 5956 } 5957 5958 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const { 5959 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)); 5960 } 5961 5962 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" 5963 /// requires copy/dispose. Note that this must match the logic 5964 /// in buildByrefHelpers. 5965 bool ASTContext::BlockRequiresCopying(QualType Ty, 5966 const VarDecl *D) { 5967 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { 5968 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr(); 5969 if (!copyExpr && record->hasTrivialDestructor()) return false; 5970 5971 return true; 5972 } 5973 5974 // The block needs copy/destroy helpers if Ty is non-trivial to destructively 5975 // move or destroy. 5976 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType()) 5977 return true; 5978 5979 if (!Ty->isObjCRetainableType()) return false; 5980 5981 Qualifiers qs = Ty.getQualifiers(); 5982 5983 // If we have lifetime, that dominates. 5984 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { 5985 switch (lifetime) { 5986 case Qualifiers::OCL_None: llvm_unreachable("impossible"); 5987 5988 // These are just bits as far as the runtime is concerned. 5989 case Qualifiers::OCL_ExplicitNone: 5990 case Qualifiers::OCL_Autoreleasing: 5991 return false; 5992 5993 // These cases should have been taken care of when checking the type's 5994 // non-triviality. 5995 case Qualifiers::OCL_Weak: 5996 case Qualifiers::OCL_Strong: 5997 llvm_unreachable("impossible"); 5998 } 5999 llvm_unreachable("fell out of lifetime switch!"); 6000 } 6001 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || 6002 Ty->isObjCObjectPointerType()); 6003 } 6004 6005 bool ASTContext::getByrefLifetime(QualType Ty, 6006 Qualifiers::ObjCLifetime &LifeTime, 6007 bool &HasByrefExtendedLayout) const { 6008 if (!getLangOpts().ObjC1 || 6009 getLangOpts().getGC() != LangOptions::NonGC) 6010 return false; 6011 6012 HasByrefExtendedLayout = false; 6013 if (Ty->isRecordType()) { 6014 HasByrefExtendedLayout = true; 6015 LifeTime = Qualifiers::OCL_None; 6016 } else if ((LifeTime = Ty.getObjCLifetime())) { 6017 // Honor the ARC qualifiers. 6018 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) { 6019 // The MRR rule. 6020 LifeTime = Qualifiers::OCL_ExplicitNone; 6021 } else { 6022 LifeTime = Qualifiers::OCL_None; 6023 } 6024 return true; 6025 } 6026 6027 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 6028 if (!ObjCInstanceTypeDecl) 6029 ObjCInstanceTypeDecl = 6030 buildImplicitTypedef(getObjCIdType(), "instancetype"); 6031 return ObjCInstanceTypeDecl; 6032 } 6033 6034 // This returns true if a type has been typedefed to BOOL: 6035 // typedef <type> BOOL; 6036 static bool isTypeTypedefedAsBOOL(QualType T) { 6037 if (const auto *TT = dyn_cast<TypedefType>(T)) 6038 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 6039 return II->isStr("BOOL"); 6040 6041 return false; 6042 } 6043 6044 /// getObjCEncodingTypeSize returns size of type for objective-c encoding 6045 /// purpose. 6046 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 6047 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 6048 return CharUnits::Zero(); 6049 6050 CharUnits sz = getTypeSizeInChars(type); 6051 6052 // Make all integer and enum types at least as large as an int 6053 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 6054 sz = std::max(sz, getTypeSizeInChars(IntTy)); 6055 // Treat arrays as pointers, since that's how they're passed in. 6056 else if (type->isArrayType()) 6057 sz = getTypeSizeInChars(VoidPtrTy); 6058 return sz; 6059 } 6060 6061 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { 6062 return getTargetInfo().getCXXABI().isMicrosoft() && 6063 VD->isStaticDataMember() && 6064 VD->getType()->isIntegralOrEnumerationType() && 6065 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit(); 6066 } 6067 6068 ASTContext::InlineVariableDefinitionKind 6069 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const { 6070 if (!VD->isInline()) 6071 return InlineVariableDefinitionKind::None; 6072 6073 // In almost all cases, it's a weak definition. 6074 auto *First = VD->getFirstDecl(); 6075 if (First->isInlineSpecified() || !First->isStaticDataMember()) 6076 return InlineVariableDefinitionKind::Weak; 6077 6078 // If there's a file-context declaration in this translation unit, it's a 6079 // non-discardable definition. 6080 for (auto *D : VD->redecls()) 6081 if (D->getLexicalDeclContext()->isFileContext() && 6082 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr())) 6083 return InlineVariableDefinitionKind::Strong; 6084 6085 // If we've not seen one yet, we don't know. 6086 return InlineVariableDefinitionKind::WeakUnknown; 6087 } 6088 6089 static std::string charUnitsToString(const CharUnits &CU) { 6090 return llvm::itostr(CU.getQuantity()); 6091 } 6092 6093 /// getObjCEncodingForBlock - Return the encoded type for this block 6094 /// declaration. 6095 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 6096 std::string S; 6097 6098 const BlockDecl *Decl = Expr->getBlockDecl(); 6099 QualType BlockTy = 6100 Expr->getType()->getAs<BlockPointerType>()->getPointeeType(); 6101 // Encode result type. 6102 if (getLangOpts().EncodeExtendedBlockSig) 6103 getObjCEncodingForMethodParameter( 6104 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S, 6105 true /*Extended*/); 6106 else 6107 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S); 6108 // Compute size of all parameters. 6109 // Start with computing size of a pointer in number of bytes. 6110 // FIXME: There might(should) be a better way of doing this computation! 6111 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 6112 CharUnits ParmOffset = PtrSize; 6113 for (auto PI : Decl->parameters()) { 6114 QualType PType = PI->getType(); 6115 CharUnits sz = getObjCEncodingTypeSize(PType); 6116 if (sz.isZero()) 6117 continue; 6118 assert(sz.isPositive() && "BlockExpr - Incomplete param type"); 6119 ParmOffset += sz; 6120 } 6121 // Size of the argument frame 6122 S += charUnitsToString(ParmOffset); 6123 // Block pointer and offset. 6124 S += "@?0"; 6125 6126 // Argument types. 6127 ParmOffset = PtrSize; 6128 for (auto PVDecl : Decl->parameters()) { 6129 QualType PType = PVDecl->getOriginalType(); 6130 if (const auto *AT = 6131 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 6132 // Use array's original type only if it has known number of 6133 // elements. 6134 if (!isa<ConstantArrayType>(AT)) 6135 PType = PVDecl->getType(); 6136 } else if (PType->isFunctionType()) 6137 PType = PVDecl->getType(); 6138 if (getLangOpts().EncodeExtendedBlockSig) 6139 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, 6140 S, true /*Extended*/); 6141 else 6142 getObjCEncodingForType(PType, S); 6143 S += charUnitsToString(ParmOffset); 6144 ParmOffset += getObjCEncodingTypeSize(PType); 6145 } 6146 6147 return S; 6148 } 6149 6150 std::string 6151 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { 6152 std::string S; 6153 // Encode result type. 6154 getObjCEncodingForType(Decl->getReturnType(), S); 6155 CharUnits ParmOffset; 6156 // Compute size of all parameters. 6157 for (auto PI : Decl->parameters()) { 6158 QualType PType = PI->getType(); 6159 CharUnits sz = getObjCEncodingTypeSize(PType); 6160 if (sz.isZero()) 6161 continue; 6162 6163 assert(sz.isPositive() && 6164 "getObjCEncodingForFunctionDecl - Incomplete param type"); 6165 ParmOffset += sz; 6166 } 6167 S += charUnitsToString(ParmOffset); 6168 ParmOffset = CharUnits::Zero(); 6169 6170 // Argument types. 6171 for (auto PVDecl : Decl->parameters()) { 6172 QualType PType = PVDecl->getOriginalType(); 6173 if (const auto *AT = 6174 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 6175 // Use array's original type only if it has known number of 6176 // elements. 6177 if (!isa<ConstantArrayType>(AT)) 6178 PType = PVDecl->getType(); 6179 } else if (PType->isFunctionType()) 6180 PType = PVDecl->getType(); 6181 getObjCEncodingForType(PType, S); 6182 S += charUnitsToString(ParmOffset); 6183 ParmOffset += getObjCEncodingTypeSize(PType); 6184 } 6185 6186 return S; 6187 } 6188 6189 /// getObjCEncodingForMethodParameter - Return the encoded type for a single 6190 /// method parameter or return type. If Extended, include class names and 6191 /// block object types. 6192 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 6193 QualType T, std::string& S, 6194 bool Extended) const { 6195 // Encode type qualifer, 'in', 'inout', etc. for the parameter. 6196 getObjCEncodingForTypeQualifier(QT, S); 6197 // Encode parameter type. 6198 getObjCEncodingForTypeImpl(T, S, true, true, nullptr, 6199 true /*OutermostType*/, 6200 false /*EncodingProperty*/, 6201 false /*StructField*/, 6202 Extended /*EncodeBlockParameters*/, 6203 Extended /*EncodeClassNames*/); 6204 } 6205 6206 /// getObjCEncodingForMethodDecl - Return the encoded type for this method 6207 /// declaration. 6208 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 6209 bool Extended) const { 6210 // FIXME: This is not very efficient. 6211 // Encode return type. 6212 std::string S; 6213 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 6214 Decl->getReturnType(), S, Extended); 6215 // Compute size of all parameters. 6216 // Start with computing size of a pointer in number of bytes. 6217 // FIXME: There might(should) be a better way of doing this computation! 6218 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 6219 // The first two arguments (self and _cmd) are pointers; account for 6220 // their size. 6221 CharUnits ParmOffset = 2 * PtrSize; 6222 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 6223 E = Decl->sel_param_end(); PI != E; ++PI) { 6224 QualType PType = (*PI)->getType(); 6225 CharUnits sz = getObjCEncodingTypeSize(PType); 6226 if (sz.isZero()) 6227 continue; 6228 6229 assert(sz.isPositive() && 6230 "getObjCEncodingForMethodDecl - Incomplete param type"); 6231 ParmOffset += sz; 6232 } 6233 S += charUnitsToString(ParmOffset); 6234 S += "@0:"; 6235 S += charUnitsToString(PtrSize); 6236 6237 // Argument types. 6238 ParmOffset = 2 * PtrSize; 6239 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 6240 E = Decl->sel_param_end(); PI != E; ++PI) { 6241 const ParmVarDecl *PVDecl = *PI; 6242 QualType PType = PVDecl->getOriginalType(); 6243 if (const auto *AT = 6244 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 6245 // Use array's original type only if it has known number of 6246 // elements. 6247 if (!isa<ConstantArrayType>(AT)) 6248 PType = PVDecl->getType(); 6249 } else if (PType->isFunctionType()) 6250 PType = PVDecl->getType(); 6251 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 6252 PType, S, Extended); 6253 S += charUnitsToString(ParmOffset); 6254 ParmOffset += getObjCEncodingTypeSize(PType); 6255 } 6256 6257 return S; 6258 } 6259 6260 ObjCPropertyImplDecl * 6261 ASTContext::getObjCPropertyImplDeclForPropertyDecl( 6262 const ObjCPropertyDecl *PD, 6263 const Decl *Container) const { 6264 if (!Container) 6265 return nullptr; 6266 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) { 6267 for (auto *PID : CID->property_impls()) 6268 if (PID->getPropertyDecl() == PD) 6269 return PID; 6270 } else { 6271 const auto *OID = cast<ObjCImplementationDecl>(Container); 6272 for (auto *PID : OID->property_impls()) 6273 if (PID->getPropertyDecl() == PD) 6274 return PID; 6275 } 6276 return nullptr; 6277 } 6278 6279 /// getObjCEncodingForPropertyDecl - Return the encoded type for this 6280 /// property declaration. If non-NULL, Container must be either an 6281 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 6282 /// NULL when getting encodings for protocol properties. 6283 /// Property attributes are stored as a comma-delimited C string. The simple 6284 /// attributes readonly and bycopy are encoded as single characters. The 6285 /// parametrized attributes, getter=name, setter=name, and ivar=name, are 6286 /// encoded as single characters, followed by an identifier. Property types 6287 /// are also encoded as a parametrized attribute. The characters used to encode 6288 /// these attributes are defined by the following enumeration: 6289 /// @code 6290 /// enum PropertyAttributes { 6291 /// kPropertyReadOnly = 'R', // property is read-only. 6292 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned 6293 /// kPropertyByref = '&', // property is a reference to the value last assigned 6294 /// kPropertyDynamic = 'D', // property is dynamic 6295 /// kPropertyGetter = 'G', // followed by getter selector name 6296 /// kPropertySetter = 'S', // followed by setter selector name 6297 /// kPropertyInstanceVariable = 'V' // followed by instance variable name 6298 /// kPropertyType = 'T' // followed by old-style type encoding. 6299 /// kPropertyWeak = 'W' // 'weak' property 6300 /// kPropertyStrong = 'P' // property GC'able 6301 /// kPropertyNonAtomic = 'N' // property non-atomic 6302 /// }; 6303 /// @endcode 6304 std::string 6305 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 6306 const Decl *Container) const { 6307 // Collect information from the property implementation decl(s). 6308 bool Dynamic = false; 6309 ObjCPropertyImplDecl *SynthesizePID = nullptr; 6310 6311 if (ObjCPropertyImplDecl *PropertyImpDecl = 6312 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { 6313 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 6314 Dynamic = true; 6315 else 6316 SynthesizePID = PropertyImpDecl; 6317 } 6318 6319 // FIXME: This is not very efficient. 6320 std::string S = "T"; 6321 6322 // Encode result type. 6323 // GCC has some special rules regarding encoding of properties which 6324 // closely resembles encoding of ivars. 6325 getObjCEncodingForPropertyType(PD->getType(), S); 6326 6327 if (PD->isReadOnly()) { 6328 S += ",R"; 6329 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) 6330 S += ",C"; 6331 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) 6332 S += ",&"; 6333 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak) 6334 S += ",W"; 6335 } else { 6336 switch (PD->getSetterKind()) { 6337 case ObjCPropertyDecl::Assign: break; 6338 case ObjCPropertyDecl::Copy: S += ",C"; break; 6339 case ObjCPropertyDecl::Retain: S += ",&"; break; 6340 case ObjCPropertyDecl::Weak: S += ",W"; break; 6341 } 6342 } 6343 6344 // It really isn't clear at all what this means, since properties 6345 // are "dynamic by default". 6346 if (Dynamic) 6347 S += ",D"; 6348 6349 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 6350 S += ",N"; 6351 6352 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 6353 S += ",G"; 6354 S += PD->getGetterName().getAsString(); 6355 } 6356 6357 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 6358 S += ",S"; 6359 S += PD->getSetterName().getAsString(); 6360 } 6361 6362 if (SynthesizePID) { 6363 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 6364 S += ",V"; 6365 S += OID->getNameAsString(); 6366 } 6367 6368 // FIXME: OBJCGC: weak & strong 6369 return S; 6370 } 6371 6372 /// getLegacyIntegralTypeEncoding - 6373 /// Another legacy compatibility encoding: 32-bit longs are encoded as 6374 /// 'l' or 'L' , but not always. For typedefs, we need to use 6375 /// 'i' or 'I' instead if encoding a struct field, or a pointer! 6376 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 6377 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 6378 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) { 6379 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 6380 PointeeTy = UnsignedIntTy; 6381 else 6382 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 6383 PointeeTy = IntTy; 6384 } 6385 } 6386 } 6387 6388 void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 6389 const FieldDecl *Field, 6390 QualType *NotEncodedT) const { 6391 // We follow the behavior of gcc, expanding structures which are 6392 // directly pointed to, and expanding embedded structures. Note that 6393 // these rules are sufficient to prevent recursive encoding of the 6394 // same type. 6395 getObjCEncodingForTypeImpl(T, S, true, true, Field, 6396 true /* outermost type */, false, false, 6397 false, false, false, NotEncodedT); 6398 } 6399 6400 void ASTContext::getObjCEncodingForPropertyType(QualType T, 6401 std::string& S) const { 6402 // Encode result type. 6403 // GCC has some special rules regarding encoding of properties which 6404 // closely resembles encoding of ivars. 6405 getObjCEncodingForTypeImpl(T, S, true, true, nullptr, 6406 true /* outermost type */, 6407 true /* encoding property */); 6408 } 6409 6410 static char getObjCEncodingForPrimitiveKind(const ASTContext *C, 6411 BuiltinType::Kind kind) { 6412 switch (kind) { 6413 case BuiltinType::Void: return 'v'; 6414 case BuiltinType::Bool: return 'B'; 6415 case BuiltinType::Char8: 6416 case BuiltinType::Char_U: 6417 case BuiltinType::UChar: return 'C'; 6418 case BuiltinType::Char16: 6419 case BuiltinType::UShort: return 'S'; 6420 case BuiltinType::Char32: 6421 case BuiltinType::UInt: return 'I'; 6422 case BuiltinType::ULong: 6423 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; 6424 case BuiltinType::UInt128: return 'T'; 6425 case BuiltinType::ULongLong: return 'Q'; 6426 case BuiltinType::Char_S: 6427 case BuiltinType::SChar: return 'c'; 6428 case BuiltinType::Short: return 's'; 6429 case BuiltinType::WChar_S: 6430 case BuiltinType::WChar_U: 6431 case BuiltinType::Int: return 'i'; 6432 case BuiltinType::Long: 6433 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; 6434 case BuiltinType::LongLong: return 'q'; 6435 case BuiltinType::Int128: return 't'; 6436 case BuiltinType::Float: return 'f'; 6437 case BuiltinType::Double: return 'd'; 6438 case BuiltinType::LongDouble: return 'D'; 6439 case BuiltinType::NullPtr: return '*'; // like char* 6440 6441 case BuiltinType::Float16: 6442 case BuiltinType::Float128: 6443 case BuiltinType::Half: 6444 case BuiltinType::ShortAccum: 6445 case BuiltinType::Accum: 6446 case BuiltinType::LongAccum: 6447 case BuiltinType::UShortAccum: 6448 case BuiltinType::UAccum: 6449 case BuiltinType::ULongAccum: 6450 case BuiltinType::ShortFract: 6451 case BuiltinType::Fract: 6452 case BuiltinType::LongFract: 6453 case BuiltinType::UShortFract: 6454 case BuiltinType::UFract: 6455 case BuiltinType::ULongFract: 6456 case BuiltinType::SatShortAccum: 6457 case BuiltinType::SatAccum: 6458 case BuiltinType::SatLongAccum: 6459 case BuiltinType::SatUShortAccum: 6460 case BuiltinType::SatUAccum: 6461 case BuiltinType::SatULongAccum: 6462 case BuiltinType::SatShortFract: 6463 case BuiltinType::SatFract: 6464 case BuiltinType::SatLongFract: 6465 case BuiltinType::SatUShortFract: 6466 case BuiltinType::SatUFract: 6467 case BuiltinType::SatULongFract: 6468 // FIXME: potentially need @encodes for these! 6469 return ' '; 6470 6471 case BuiltinType::ObjCId: 6472 case BuiltinType::ObjCClass: 6473 case BuiltinType::ObjCSel: 6474 llvm_unreachable("@encoding ObjC primitive type"); 6475 6476 // OpenCL and placeholder types don't need @encodings. 6477 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6478 case BuiltinType::Id: 6479 #include "clang/Basic/OpenCLImageTypes.def" 6480 case BuiltinType::OCLEvent: 6481 case BuiltinType::OCLClkEvent: 6482 case BuiltinType::OCLQueue: 6483 case BuiltinType::OCLReserveID: 6484 case BuiltinType::OCLSampler: 6485 case BuiltinType::Dependent: 6486 #define BUILTIN_TYPE(KIND, ID) 6487 #define PLACEHOLDER_TYPE(KIND, ID) \ 6488 case BuiltinType::KIND: 6489 #include "clang/AST/BuiltinTypes.def" 6490 llvm_unreachable("invalid builtin type for @encode"); 6491 } 6492 llvm_unreachable("invalid BuiltinType::Kind value"); 6493 } 6494 6495 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 6496 EnumDecl *Enum = ET->getDecl(); 6497 6498 // The encoding of an non-fixed enum type is always 'i', regardless of size. 6499 if (!Enum->isFixed()) 6500 return 'i'; 6501 6502 // The encoding of a fixed enum type matches its fixed underlying type. 6503 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>(); 6504 return getObjCEncodingForPrimitiveKind(C, BT->getKind()); 6505 } 6506 6507 static void EncodeBitField(const ASTContext *Ctx, std::string& S, 6508 QualType T, const FieldDecl *FD) { 6509 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 6510 S += 'b'; 6511 // The NeXT runtime encodes bit fields as b followed by the number of bits. 6512 // The GNU runtime requires more information; bitfields are encoded as b, 6513 // then the offset (in bits) of the first element, then the type of the 6514 // bitfield, then the size in bits. For example, in this structure: 6515 // 6516 // struct 6517 // { 6518 // int integer; 6519 // int flags:2; 6520 // }; 6521 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 6522 // runtime, but b32i2 for the GNU runtime. The reason for this extra 6523 // information is not especially sensible, but we're stuck with it for 6524 // compatibility with GCC, although providing it breaks anything that 6525 // actually uses runtime introspection and wants to work on both runtimes... 6526 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 6527 uint64_t Offset; 6528 6529 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) { 6530 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr, 6531 IVD); 6532 } else { 6533 const RecordDecl *RD = FD->getParent(); 6534 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 6535 Offset = RL.getFieldOffset(FD->getFieldIndex()); 6536 } 6537 6538 S += llvm::utostr(Offset); 6539 6540 if (const auto *ET = T->getAs<EnumType>()) 6541 S += ObjCEncodingForEnumType(Ctx, ET); 6542 else { 6543 const auto *BT = T->castAs<BuiltinType>(); 6544 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind()); 6545 } 6546 } 6547 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 6548 } 6549 6550 // FIXME: Use SmallString for accumulating string. 6551 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 6552 bool ExpandPointedToStructures, 6553 bool ExpandStructures, 6554 const FieldDecl *FD, 6555 bool OutermostType, 6556 bool EncodingProperty, 6557 bool StructField, 6558 bool EncodeBlockParameters, 6559 bool EncodeClassNames, 6560 bool EncodePointerToObjCTypedef, 6561 QualType *NotEncodedT) const { 6562 CanQualType CT = getCanonicalType(T); 6563 switch (CT->getTypeClass()) { 6564 case Type::Builtin: 6565 case Type::Enum: 6566 if (FD && FD->isBitField()) 6567 return EncodeBitField(this, S, T, FD); 6568 if (const auto *BT = dyn_cast<BuiltinType>(CT)) 6569 S += getObjCEncodingForPrimitiveKind(this, BT->getKind()); 6570 else 6571 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); 6572 return; 6573 6574 case Type::Complex: { 6575 const auto *CT = T->castAs<ComplexType>(); 6576 S += 'j'; 6577 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr); 6578 return; 6579 } 6580 6581 case Type::Atomic: { 6582 const auto *AT = T->castAs<AtomicType>(); 6583 S += 'A'; 6584 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr); 6585 return; 6586 } 6587 6588 // encoding for pointer or reference types. 6589 case Type::Pointer: 6590 case Type::LValueReference: 6591 case Type::RValueReference: { 6592 QualType PointeeTy; 6593 if (isa<PointerType>(CT)) { 6594 const auto *PT = T->castAs<PointerType>(); 6595 if (PT->isObjCSelType()) { 6596 S += ':'; 6597 return; 6598 } 6599 PointeeTy = PT->getPointeeType(); 6600 } else { 6601 PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); 6602 } 6603 6604 bool isReadOnly = false; 6605 // For historical/compatibility reasons, the read-only qualifier of the 6606 // pointee gets emitted _before_ the '^'. The read-only qualifier of 6607 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 6608 // Also, do not emit the 'r' for anything but the outermost type! 6609 if (isa<TypedefType>(T.getTypePtr())) { 6610 if (OutermostType && T.isConstQualified()) { 6611 isReadOnly = true; 6612 S += 'r'; 6613 } 6614 } else if (OutermostType) { 6615 QualType P = PointeeTy; 6616 while (P->getAs<PointerType>()) 6617 P = P->getAs<PointerType>()->getPointeeType(); 6618 if (P.isConstQualified()) { 6619 isReadOnly = true; 6620 S += 'r'; 6621 } 6622 } 6623 if (isReadOnly) { 6624 // Another legacy compatibility encoding. Some ObjC qualifier and type 6625 // combinations need to be rearranged. 6626 // Rewrite "in const" from "nr" to "rn" 6627 if (StringRef(S).endswith("nr")) 6628 S.replace(S.end()-2, S.end(), "rn"); 6629 } 6630 6631 if (PointeeTy->isCharType()) { 6632 // char pointer types should be encoded as '*' unless it is a 6633 // type that has been typedef'd to 'BOOL'. 6634 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 6635 S += '*'; 6636 return; 6637 } 6638 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) { 6639 // GCC binary compat: Need to convert "struct objc_class *" to "#". 6640 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 6641 S += '#'; 6642 return; 6643 } 6644 // GCC binary compat: Need to convert "struct objc_object *" to "@". 6645 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 6646 S += '@'; 6647 return; 6648 } 6649 // fall through... 6650 } 6651 S += '^'; 6652 getLegacyIntegralTypeEncoding(PointeeTy); 6653 6654 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures, 6655 nullptr, false, false, false, false, false, false, 6656 NotEncodedT); 6657 return; 6658 } 6659 6660 case Type::ConstantArray: 6661 case Type::IncompleteArray: 6662 case Type::VariableArray: { 6663 const auto *AT = cast<ArrayType>(CT); 6664 6665 if (isa<IncompleteArrayType>(AT) && !StructField) { 6666 // Incomplete arrays are encoded as a pointer to the array element. 6667 S += '^'; 6668 6669 getObjCEncodingForTypeImpl(AT->getElementType(), S, 6670 false, ExpandStructures, FD); 6671 } else { 6672 S += '['; 6673 6674 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) 6675 S += llvm::utostr(CAT->getSize().getZExtValue()); 6676 else { 6677 //Variable length arrays are encoded as a regular array with 0 elements. 6678 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 6679 "Unknown array type!"); 6680 S += '0'; 6681 } 6682 6683 getObjCEncodingForTypeImpl(AT->getElementType(), S, 6684 false, ExpandStructures, FD, 6685 false, false, false, false, false, false, 6686 NotEncodedT); 6687 S += ']'; 6688 } 6689 return; 6690 } 6691 6692 case Type::FunctionNoProto: 6693 case Type::FunctionProto: 6694 S += '?'; 6695 return; 6696 6697 case Type::Record: { 6698 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); 6699 S += RDecl->isUnion() ? '(' : '{'; 6700 // Anonymous structures print as '?' 6701 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 6702 S += II->getName(); 6703 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 6704 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 6705 llvm::raw_string_ostream OS(S); 6706 printTemplateArgumentList(OS, TemplateArgs.asArray(), 6707 getPrintingPolicy()); 6708 } 6709 } else { 6710 S += '?'; 6711 } 6712 if (ExpandStructures) { 6713 S += '='; 6714 if (!RDecl->isUnion()) { 6715 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); 6716 } else { 6717 for (const auto *Field : RDecl->fields()) { 6718 if (FD) { 6719 S += '"'; 6720 S += Field->getNameAsString(); 6721 S += '"'; 6722 } 6723 6724 // Special case bit-fields. 6725 if (Field->isBitField()) { 6726 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 6727 Field); 6728 } else { 6729 QualType qt = Field->getType(); 6730 getLegacyIntegralTypeEncoding(qt); 6731 getObjCEncodingForTypeImpl(qt, S, false, true, 6732 FD, /*OutermostType*/false, 6733 /*EncodingProperty*/false, 6734 /*StructField*/true, 6735 false, false, false, NotEncodedT); 6736 } 6737 } 6738 } 6739 } 6740 S += RDecl->isUnion() ? ')' : '}'; 6741 return; 6742 } 6743 6744 case Type::BlockPointer: { 6745 const auto *BT = T->castAs<BlockPointerType>(); 6746 S += "@?"; // Unlike a pointer-to-function, which is "^?". 6747 if (EncodeBlockParameters) { 6748 const auto *FT = BT->getPointeeType()->castAs<FunctionType>(); 6749 6750 S += '<'; 6751 // Block return type 6752 getObjCEncodingForTypeImpl( 6753 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures, 6754 FD, false /* OutermostType */, EncodingProperty, 6755 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false, 6756 NotEncodedT); 6757 // Block self 6758 S += "@?"; 6759 // Block parameters 6760 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) { 6761 for (const auto &I : FPT->param_types()) 6762 getObjCEncodingForTypeImpl( 6763 I, S, ExpandPointedToStructures, ExpandStructures, FD, 6764 false /* OutermostType */, EncodingProperty, 6765 false /* StructField */, EncodeBlockParameters, EncodeClassNames, 6766 false, NotEncodedT); 6767 } 6768 S += '>'; 6769 } 6770 return; 6771 } 6772 6773 case Type::ObjCObject: { 6774 // hack to match legacy encoding of *id and *Class 6775 QualType Ty = getObjCObjectPointerType(CT); 6776 if (Ty->isObjCIdType()) { 6777 S += "{objc_object=}"; 6778 return; 6779 } 6780 else if (Ty->isObjCClassType()) { 6781 S += "{objc_class=}"; 6782 return; 6783 } 6784 // TODO: Double check to make sure this intentionally falls through. 6785 LLVM_FALLTHROUGH; 6786 } 6787 6788 case Type::ObjCInterface: { 6789 // Ignore protocol qualifiers when mangling at this level. 6790 // @encode(class_name) 6791 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface(); 6792 S += '{'; 6793 S += OI->getObjCRuntimeNameAsString(); 6794 if (ExpandStructures) { 6795 S += '='; 6796 SmallVector<const ObjCIvarDecl*, 32> Ivars; 6797 DeepCollectObjCIvars(OI, true, Ivars); 6798 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 6799 const FieldDecl *Field = Ivars[i]; 6800 if (Field->isBitField()) 6801 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field); 6802 else 6803 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD, 6804 false, false, false, false, false, 6805 EncodePointerToObjCTypedef, 6806 NotEncodedT); 6807 } 6808 } 6809 S += '}'; 6810 return; 6811 } 6812 6813 case Type::ObjCObjectPointer: { 6814 const auto *OPT = T->castAs<ObjCObjectPointerType>(); 6815 if (OPT->isObjCIdType()) { 6816 S += '@'; 6817 return; 6818 } 6819 6820 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 6821 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 6822 // Since this is a binary compatibility issue, need to consult with runtime 6823 // folks. Fortunately, this is a *very* obscure construct. 6824 S += '#'; 6825 return; 6826 } 6827 6828 if (OPT->isObjCQualifiedIdType()) { 6829 getObjCEncodingForTypeImpl(getObjCIdType(), S, 6830 ExpandPointedToStructures, 6831 ExpandStructures, FD); 6832 if (FD || EncodingProperty || EncodeClassNames) { 6833 // Note that we do extended encoding of protocol qualifer list 6834 // Only when doing ivar or property encoding. 6835 S += '"'; 6836 for (const auto *I : OPT->quals()) { 6837 S += '<'; 6838 S += I->getObjCRuntimeNameAsString(); 6839 S += '>'; 6840 } 6841 S += '"'; 6842 } 6843 return; 6844 } 6845 6846 QualType PointeeTy = OPT->getPointeeType(); 6847 if (!EncodingProperty && 6848 isa<TypedefType>(PointeeTy.getTypePtr()) && 6849 !EncodePointerToObjCTypedef) { 6850 // Another historical/compatibility reason. 6851 // We encode the underlying type which comes out as 6852 // {...}; 6853 S += '^'; 6854 if (FD && OPT->getInterfaceDecl()) { 6855 // Prevent recursive encoding of fields in some rare cases. 6856 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl(); 6857 SmallVector<const ObjCIvarDecl*, 32> Ivars; 6858 DeepCollectObjCIvars(OI, true, Ivars); 6859 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 6860 if (Ivars[i] == FD) { 6861 S += '{'; 6862 S += OI->getObjCRuntimeNameAsString(); 6863 S += '}'; 6864 return; 6865 } 6866 } 6867 } 6868 getObjCEncodingForTypeImpl(PointeeTy, S, 6869 false, ExpandPointedToStructures, 6870 nullptr, 6871 false, false, false, false, false, 6872 /*EncodePointerToObjCTypedef*/true); 6873 return; 6874 } 6875 6876 S += '@'; 6877 if (OPT->getInterfaceDecl() && 6878 (FD || EncodingProperty || EncodeClassNames)) { 6879 S += '"'; 6880 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString(); 6881 for (const auto *I : OPT->quals()) { 6882 S += '<'; 6883 S += I->getObjCRuntimeNameAsString(); 6884 S += '>'; 6885 } 6886 S += '"'; 6887 } 6888 return; 6889 } 6890 6891 // gcc just blithely ignores member pointers. 6892 // FIXME: we shoul do better than that. 'M' is available. 6893 case Type::MemberPointer: 6894 // This matches gcc's encoding, even though technically it is insufficient. 6895 //FIXME. We should do a better job than gcc. 6896 case Type::Vector: 6897 case Type::ExtVector: 6898 // Until we have a coherent encoding of these three types, issue warning. 6899 if (NotEncodedT) 6900 *NotEncodedT = T; 6901 return; 6902 6903 // We could see an undeduced auto type here during error recovery. 6904 // Just ignore it. 6905 case Type::Auto: 6906 case Type::DeducedTemplateSpecialization: 6907 return; 6908 6909 case Type::Pipe: 6910 #define ABSTRACT_TYPE(KIND, BASE) 6911 #define TYPE(KIND, BASE) 6912 #define DEPENDENT_TYPE(KIND, BASE) \ 6913 case Type::KIND: 6914 #define NON_CANONICAL_TYPE(KIND, BASE) \ 6915 case Type::KIND: 6916 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ 6917 case Type::KIND: 6918 #include "clang/AST/TypeNodes.def" 6919 llvm_unreachable("@encode for dependent type!"); 6920 } 6921 llvm_unreachable("bad type kind!"); 6922 } 6923 6924 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 6925 std::string &S, 6926 const FieldDecl *FD, 6927 bool includeVBases, 6928 QualType *NotEncodedT) const { 6929 assert(RDecl && "Expected non-null RecordDecl"); 6930 assert(!RDecl->isUnion() && "Should not be called for unions"); 6931 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl()) 6932 return; 6933 6934 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 6935 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 6936 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 6937 6938 if (CXXRec) { 6939 for (const auto &BI : CXXRec->bases()) { 6940 if (!BI.isVirtual()) { 6941 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 6942 if (base->isEmpty()) 6943 continue; 6944 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 6945 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 6946 std::make_pair(offs, base)); 6947 } 6948 } 6949 } 6950 6951 unsigned i = 0; 6952 for (auto *Field : RDecl->fields()) { 6953 uint64_t offs = layout.getFieldOffset(i); 6954 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 6955 std::make_pair(offs, Field)); 6956 ++i; 6957 } 6958 6959 if (CXXRec && includeVBases) { 6960 for (const auto &BI : CXXRec->vbases()) { 6961 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 6962 if (base->isEmpty()) 6963 continue; 6964 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 6965 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && 6966 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 6967 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 6968 std::make_pair(offs, base)); 6969 } 6970 } 6971 6972 CharUnits size; 6973 if (CXXRec) { 6974 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 6975 } else { 6976 size = layout.getSize(); 6977 } 6978 6979 #ifndef NDEBUG 6980 uint64_t CurOffs = 0; 6981 #endif 6982 std::multimap<uint64_t, NamedDecl *>::iterator 6983 CurLayObj = FieldOrBaseOffsets.begin(); 6984 6985 if (CXXRec && CXXRec->isDynamicClass() && 6986 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 6987 if (FD) { 6988 S += "\"_vptr$"; 6989 std::string recname = CXXRec->getNameAsString(); 6990 if (recname.empty()) recname = "?"; 6991 S += recname; 6992 S += '"'; 6993 } 6994 S += "^^?"; 6995 #ifndef NDEBUG 6996 CurOffs += getTypeSize(VoidPtrTy); 6997 #endif 6998 } 6999 7000 if (!RDecl->hasFlexibleArrayMember()) { 7001 // Mark the end of the structure. 7002 uint64_t offs = toBits(size); 7003 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 7004 std::make_pair(offs, nullptr)); 7005 } 7006 7007 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 7008 #ifndef NDEBUG 7009 assert(CurOffs <= CurLayObj->first); 7010 if (CurOffs < CurLayObj->first) { 7011 uint64_t padding = CurLayObj->first - CurOffs; 7012 // FIXME: There doesn't seem to be a way to indicate in the encoding that 7013 // packing/alignment of members is different that normal, in which case 7014 // the encoding will be out-of-sync with the real layout. 7015 // If the runtime switches to just consider the size of types without 7016 // taking into account alignment, we could make padding explicit in the 7017 // encoding (e.g. using arrays of chars). The encoding strings would be 7018 // longer then though. 7019 CurOffs += padding; 7020 } 7021 #endif 7022 7023 NamedDecl *dcl = CurLayObj->second; 7024 if (!dcl) 7025 break; // reached end of structure. 7026 7027 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) { 7028 // We expand the bases without their virtual bases since those are going 7029 // in the initial structure. Note that this differs from gcc which 7030 // expands virtual bases each time one is encountered in the hierarchy, 7031 // making the encoding type bigger than it really is. 7032 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, 7033 NotEncodedT); 7034 assert(!base->isEmpty()); 7035 #ifndef NDEBUG 7036 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 7037 #endif 7038 } else { 7039 const auto *field = cast<FieldDecl>(dcl); 7040 if (FD) { 7041 S += '"'; 7042 S += field->getNameAsString(); 7043 S += '"'; 7044 } 7045 7046 if (field->isBitField()) { 7047 EncodeBitField(this, S, field->getType(), field); 7048 #ifndef NDEBUG 7049 CurOffs += field->getBitWidthValue(*this); 7050 #endif 7051 } else { 7052 QualType qt = field->getType(); 7053 getLegacyIntegralTypeEncoding(qt); 7054 getObjCEncodingForTypeImpl(qt, S, false, true, FD, 7055 /*OutermostType*/false, 7056 /*EncodingProperty*/false, 7057 /*StructField*/true, 7058 false, false, false, NotEncodedT); 7059 #ifndef NDEBUG 7060 CurOffs += getTypeSize(field->getType()); 7061 #endif 7062 } 7063 } 7064 } 7065 } 7066 7067 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 7068 std::string& S) const { 7069 if (QT & Decl::OBJC_TQ_In) 7070 S += 'n'; 7071 if (QT & Decl::OBJC_TQ_Inout) 7072 S += 'N'; 7073 if (QT & Decl::OBJC_TQ_Out) 7074 S += 'o'; 7075 if (QT & Decl::OBJC_TQ_Bycopy) 7076 S += 'O'; 7077 if (QT & Decl::OBJC_TQ_Byref) 7078 S += 'R'; 7079 if (QT & Decl::OBJC_TQ_Oneway) 7080 S += 'V'; 7081 } 7082 7083 TypedefDecl *ASTContext::getObjCIdDecl() const { 7084 if (!ObjCIdDecl) { 7085 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {}); 7086 T = getObjCObjectPointerType(T); 7087 ObjCIdDecl = buildImplicitTypedef(T, "id"); 7088 } 7089 return ObjCIdDecl; 7090 } 7091 7092 TypedefDecl *ASTContext::getObjCSelDecl() const { 7093 if (!ObjCSelDecl) { 7094 QualType T = getPointerType(ObjCBuiltinSelTy); 7095 ObjCSelDecl = buildImplicitTypedef(T, "SEL"); 7096 } 7097 return ObjCSelDecl; 7098 } 7099 7100 TypedefDecl *ASTContext::getObjCClassDecl() const { 7101 if (!ObjCClassDecl) { 7102 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {}); 7103 T = getObjCObjectPointerType(T); 7104 ObjCClassDecl = buildImplicitTypedef(T, "Class"); 7105 } 7106 return ObjCClassDecl; 7107 } 7108 7109 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 7110 if (!ObjCProtocolClassDecl) { 7111 ObjCProtocolClassDecl 7112 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 7113 SourceLocation(), 7114 &Idents.get("Protocol"), 7115 /*typeParamList=*/nullptr, 7116 /*PrevDecl=*/nullptr, 7117 SourceLocation(), true); 7118 } 7119 7120 return ObjCProtocolClassDecl; 7121 } 7122 7123 //===----------------------------------------------------------------------===// 7124 // __builtin_va_list Construction Functions 7125 //===----------------------------------------------------------------------===// 7126 7127 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context, 7128 StringRef Name) { 7129 // typedef char* __builtin[_ms]_va_list; 7130 QualType T = Context->getPointerType(Context->CharTy); 7131 return Context->buildImplicitTypedef(T, Name); 7132 } 7133 7134 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) { 7135 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list"); 7136 } 7137 7138 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 7139 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list"); 7140 } 7141 7142 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 7143 // typedef void* __builtin_va_list; 7144 QualType T = Context->getPointerType(Context->VoidTy); 7145 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 7146 } 7147 7148 static TypedefDecl * 7149 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { 7150 // struct __va_list 7151 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); 7152 if (Context->getLangOpts().CPlusPlus) { 7153 // namespace std { struct __va_list { 7154 NamespaceDecl *NS; 7155 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 7156 Context->getTranslationUnitDecl(), 7157 /*Inline*/ false, SourceLocation(), 7158 SourceLocation(), &Context->Idents.get("std"), 7159 /*PrevDecl*/ nullptr); 7160 NS->setImplicit(); 7161 VaListTagDecl->setDeclContext(NS); 7162 } 7163 7164 VaListTagDecl->startDefinition(); 7165 7166 const size_t NumFields = 5; 7167 QualType FieldTypes[NumFields]; 7168 const char *FieldNames[NumFields]; 7169 7170 // void *__stack; 7171 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 7172 FieldNames[0] = "__stack"; 7173 7174 // void *__gr_top; 7175 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 7176 FieldNames[1] = "__gr_top"; 7177 7178 // void *__vr_top; 7179 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 7180 FieldNames[2] = "__vr_top"; 7181 7182 // int __gr_offs; 7183 FieldTypes[3] = Context->IntTy; 7184 FieldNames[3] = "__gr_offs"; 7185 7186 // int __vr_offs; 7187 FieldTypes[4] = Context->IntTy; 7188 FieldNames[4] = "__vr_offs"; 7189 7190 // Create fields 7191 for (unsigned i = 0; i < NumFields; ++i) { 7192 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 7193 VaListTagDecl, 7194 SourceLocation(), 7195 SourceLocation(), 7196 &Context->Idents.get(FieldNames[i]), 7197 FieldTypes[i], /*TInfo=*/nullptr, 7198 /*BitWidth=*/nullptr, 7199 /*Mutable=*/false, 7200 ICIS_NoInit); 7201 Field->setAccess(AS_public); 7202 VaListTagDecl->addDecl(Field); 7203 } 7204 VaListTagDecl->completeDefinition(); 7205 Context->VaListTagDecl = VaListTagDecl; 7206 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 7207 7208 // } __builtin_va_list; 7209 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 7210 } 7211 7212 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 7213 // typedef struct __va_list_tag { 7214 RecordDecl *VaListTagDecl; 7215 7216 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 7217 VaListTagDecl->startDefinition(); 7218 7219 const size_t NumFields = 5; 7220 QualType FieldTypes[NumFields]; 7221 const char *FieldNames[NumFields]; 7222 7223 // unsigned char gpr; 7224 FieldTypes[0] = Context->UnsignedCharTy; 7225 FieldNames[0] = "gpr"; 7226 7227 // unsigned char fpr; 7228 FieldTypes[1] = Context->UnsignedCharTy; 7229 FieldNames[1] = "fpr"; 7230 7231 // unsigned short reserved; 7232 FieldTypes[2] = Context->UnsignedShortTy; 7233 FieldNames[2] = "reserved"; 7234 7235 // void* overflow_arg_area; 7236 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 7237 FieldNames[3] = "overflow_arg_area"; 7238 7239 // void* reg_save_area; 7240 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 7241 FieldNames[4] = "reg_save_area"; 7242 7243 // Create fields 7244 for (unsigned i = 0; i < NumFields; ++i) { 7245 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 7246 SourceLocation(), 7247 SourceLocation(), 7248 &Context->Idents.get(FieldNames[i]), 7249 FieldTypes[i], /*TInfo=*/nullptr, 7250 /*BitWidth=*/nullptr, 7251 /*Mutable=*/false, 7252 ICIS_NoInit); 7253 Field->setAccess(AS_public); 7254 VaListTagDecl->addDecl(Field); 7255 } 7256 VaListTagDecl->completeDefinition(); 7257 Context->VaListTagDecl = VaListTagDecl; 7258 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 7259 7260 // } __va_list_tag; 7261 TypedefDecl *VaListTagTypedefDecl = 7262 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 7263 7264 QualType VaListTagTypedefType = 7265 Context->getTypedefType(VaListTagTypedefDecl); 7266 7267 // typedef __va_list_tag __builtin_va_list[1]; 7268 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 7269 QualType VaListTagArrayType 7270 = Context->getConstantArrayType(VaListTagTypedefType, 7271 Size, ArrayType::Normal, 0); 7272 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 7273 } 7274 7275 static TypedefDecl * 7276 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 7277 // struct __va_list_tag { 7278 RecordDecl *VaListTagDecl; 7279 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 7280 VaListTagDecl->startDefinition(); 7281 7282 const size_t NumFields = 4; 7283 QualType FieldTypes[NumFields]; 7284 const char *FieldNames[NumFields]; 7285 7286 // unsigned gp_offset; 7287 FieldTypes[0] = Context->UnsignedIntTy; 7288 FieldNames[0] = "gp_offset"; 7289 7290 // unsigned fp_offset; 7291 FieldTypes[1] = Context->UnsignedIntTy; 7292 FieldNames[1] = "fp_offset"; 7293 7294 // void* overflow_arg_area; 7295 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 7296 FieldNames[2] = "overflow_arg_area"; 7297 7298 // void* reg_save_area; 7299 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 7300 FieldNames[3] = "reg_save_area"; 7301 7302 // Create fields 7303 for (unsigned i = 0; i < NumFields; ++i) { 7304 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 7305 VaListTagDecl, 7306 SourceLocation(), 7307 SourceLocation(), 7308 &Context->Idents.get(FieldNames[i]), 7309 FieldTypes[i], /*TInfo=*/nullptr, 7310 /*BitWidth=*/nullptr, 7311 /*Mutable=*/false, 7312 ICIS_NoInit); 7313 Field->setAccess(AS_public); 7314 VaListTagDecl->addDecl(Field); 7315 } 7316 VaListTagDecl->completeDefinition(); 7317 Context->VaListTagDecl = VaListTagDecl; 7318 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 7319 7320 // }; 7321 7322 // typedef struct __va_list_tag __builtin_va_list[1]; 7323 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 7324 QualType VaListTagArrayType = 7325 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0); 7326 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 7327 } 7328 7329 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 7330 // typedef int __builtin_va_list[4]; 7331 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 7332 QualType IntArrayType = 7333 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0); 7334 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); 7335 } 7336 7337 static TypedefDecl * 7338 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { 7339 // struct __va_list 7340 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); 7341 if (Context->getLangOpts().CPlusPlus) { 7342 // namespace std { struct __va_list { 7343 NamespaceDecl *NS; 7344 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 7345 Context->getTranslationUnitDecl(), 7346 /*Inline*/false, SourceLocation(), 7347 SourceLocation(), &Context->Idents.get("std"), 7348 /*PrevDecl*/ nullptr); 7349 NS->setImplicit(); 7350 VaListDecl->setDeclContext(NS); 7351 } 7352 7353 VaListDecl->startDefinition(); 7354 7355 // void * __ap; 7356 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 7357 VaListDecl, 7358 SourceLocation(), 7359 SourceLocation(), 7360 &Context->Idents.get("__ap"), 7361 Context->getPointerType(Context->VoidTy), 7362 /*TInfo=*/nullptr, 7363 /*BitWidth=*/nullptr, 7364 /*Mutable=*/false, 7365 ICIS_NoInit); 7366 Field->setAccess(AS_public); 7367 VaListDecl->addDecl(Field); 7368 7369 // }; 7370 VaListDecl->completeDefinition(); 7371 Context->VaListTagDecl = VaListDecl; 7372 7373 // typedef struct __va_list __builtin_va_list; 7374 QualType T = Context->getRecordType(VaListDecl); 7375 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 7376 } 7377 7378 static TypedefDecl * 7379 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { 7380 // struct __va_list_tag { 7381 RecordDecl *VaListTagDecl; 7382 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 7383 VaListTagDecl->startDefinition(); 7384 7385 const size_t NumFields = 4; 7386 QualType FieldTypes[NumFields]; 7387 const char *FieldNames[NumFields]; 7388 7389 // long __gpr; 7390 FieldTypes[0] = Context->LongTy; 7391 FieldNames[0] = "__gpr"; 7392 7393 // long __fpr; 7394 FieldTypes[1] = Context->LongTy; 7395 FieldNames[1] = "__fpr"; 7396 7397 // void *__overflow_arg_area; 7398 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 7399 FieldNames[2] = "__overflow_arg_area"; 7400 7401 // void *__reg_save_area; 7402 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 7403 FieldNames[3] = "__reg_save_area"; 7404 7405 // Create fields 7406 for (unsigned i = 0; i < NumFields; ++i) { 7407 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 7408 VaListTagDecl, 7409 SourceLocation(), 7410 SourceLocation(), 7411 &Context->Idents.get(FieldNames[i]), 7412 FieldTypes[i], /*TInfo=*/nullptr, 7413 /*BitWidth=*/nullptr, 7414 /*Mutable=*/false, 7415 ICIS_NoInit); 7416 Field->setAccess(AS_public); 7417 VaListTagDecl->addDecl(Field); 7418 } 7419 VaListTagDecl->completeDefinition(); 7420 Context->VaListTagDecl = VaListTagDecl; 7421 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 7422 7423 // }; 7424 7425 // typedef __va_list_tag __builtin_va_list[1]; 7426 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 7427 QualType VaListTagArrayType = 7428 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0); 7429 7430 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 7431 } 7432 7433 static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 7434 TargetInfo::BuiltinVaListKind Kind) { 7435 switch (Kind) { 7436 case TargetInfo::CharPtrBuiltinVaList: 7437 return CreateCharPtrBuiltinVaListDecl(Context); 7438 case TargetInfo::VoidPtrBuiltinVaList: 7439 return CreateVoidPtrBuiltinVaListDecl(Context); 7440 case TargetInfo::AArch64ABIBuiltinVaList: 7441 return CreateAArch64ABIBuiltinVaListDecl(Context); 7442 case TargetInfo::PowerABIBuiltinVaList: 7443 return CreatePowerABIBuiltinVaListDecl(Context); 7444 case TargetInfo::X86_64ABIBuiltinVaList: 7445 return CreateX86_64ABIBuiltinVaListDecl(Context); 7446 case TargetInfo::PNaClABIBuiltinVaList: 7447 return CreatePNaClABIBuiltinVaListDecl(Context); 7448 case TargetInfo::AAPCSABIBuiltinVaList: 7449 return CreateAAPCSABIBuiltinVaListDecl(Context); 7450 case TargetInfo::SystemZBuiltinVaList: 7451 return CreateSystemZBuiltinVaListDecl(Context); 7452 } 7453 7454 llvm_unreachable("Unhandled __builtin_va_list type kind"); 7455 } 7456 7457 TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 7458 if (!BuiltinVaListDecl) { 7459 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 7460 assert(BuiltinVaListDecl->isImplicit()); 7461 } 7462 7463 return BuiltinVaListDecl; 7464 } 7465 7466 Decl *ASTContext::getVaListTagDecl() const { 7467 // Force the creation of VaListTagDecl by building the __builtin_va_list 7468 // declaration. 7469 if (!VaListTagDecl) 7470 (void)getBuiltinVaListDecl(); 7471 7472 return VaListTagDecl; 7473 } 7474 7475 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const { 7476 if (!BuiltinMSVaListDecl) 7477 BuiltinMSVaListDecl = CreateMSVaListDecl(this); 7478 7479 return BuiltinMSVaListDecl; 7480 } 7481 7482 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const { 7483 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID()); 7484 } 7485 7486 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 7487 assert(ObjCConstantStringType.isNull() && 7488 "'NSConstantString' type already set!"); 7489 7490 ObjCConstantStringType = getObjCInterfaceType(Decl); 7491 } 7492 7493 /// Retrieve the template name that corresponds to a non-empty 7494 /// lookup. 7495 TemplateName 7496 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 7497 UnresolvedSetIterator End) const { 7498 unsigned size = End - Begin; 7499 assert(size > 1 && "set is not overloaded!"); 7500 7501 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 7502 size * sizeof(FunctionTemplateDecl*)); 7503 auto *OT = new (memory) OverloadedTemplateStorage(size); 7504 7505 NamedDecl **Storage = OT->getStorage(); 7506 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 7507 NamedDecl *D = *I; 7508 assert(isa<FunctionTemplateDecl>(D) || 7509 isa<UnresolvedUsingValueDecl>(D) || 7510 (isa<UsingShadowDecl>(D) && 7511 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 7512 *Storage++ = D; 7513 } 7514 7515 return TemplateName(OT); 7516 } 7517 7518 /// Retrieve the template name that represents a qualified 7519 /// template name such as \c std::vector. 7520 TemplateName 7521 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 7522 bool TemplateKeyword, 7523 TemplateDecl *Template) const { 7524 assert(NNS && "Missing nested-name-specifier in qualified template name"); 7525 7526 // FIXME: Canonicalization? 7527 llvm::FoldingSetNodeID ID; 7528 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 7529 7530 void *InsertPos = nullptr; 7531 QualifiedTemplateName *QTN = 7532 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 7533 if (!QTN) { 7534 QTN = new (*this, alignof(QualifiedTemplateName)) 7535 QualifiedTemplateName(NNS, TemplateKeyword, Template); 7536 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 7537 } 7538 7539 return TemplateName(QTN); 7540 } 7541 7542 /// Retrieve the template name that represents a dependent 7543 /// template name such as \c MetaFun::template apply. 7544 TemplateName 7545 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 7546 const IdentifierInfo *Name) const { 7547 assert((!NNS || NNS->isDependent()) && 7548 "Nested name specifier must be dependent"); 7549 7550 llvm::FoldingSetNodeID ID; 7551 DependentTemplateName::Profile(ID, NNS, Name); 7552 7553 void *InsertPos = nullptr; 7554 DependentTemplateName *QTN = 7555 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 7556 7557 if (QTN) 7558 return TemplateName(QTN); 7559 7560 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 7561 if (CanonNNS == NNS) { 7562 QTN = new (*this, alignof(DependentTemplateName)) 7563 DependentTemplateName(NNS, Name); 7564 } else { 7565 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 7566 QTN = new (*this, alignof(DependentTemplateName)) 7567 DependentTemplateName(NNS, Name, Canon); 7568 DependentTemplateName *CheckQTN = 7569 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 7570 assert(!CheckQTN && "Dependent type name canonicalization broken"); 7571 (void)CheckQTN; 7572 } 7573 7574 DependentTemplateNames.InsertNode(QTN, InsertPos); 7575 return TemplateName(QTN); 7576 } 7577 7578 /// Retrieve the template name that represents a dependent 7579 /// template name such as \c MetaFun::template operator+. 7580 TemplateName 7581 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 7582 OverloadedOperatorKind Operator) const { 7583 assert((!NNS || NNS->isDependent()) && 7584 "Nested name specifier must be dependent"); 7585 7586 llvm::FoldingSetNodeID ID; 7587 DependentTemplateName::Profile(ID, NNS, Operator); 7588 7589 void *InsertPos = nullptr; 7590 DependentTemplateName *QTN 7591 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 7592 7593 if (QTN) 7594 return TemplateName(QTN); 7595 7596 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 7597 if (CanonNNS == NNS) { 7598 QTN = new (*this, alignof(DependentTemplateName)) 7599 DependentTemplateName(NNS, Operator); 7600 } else { 7601 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 7602 QTN = new (*this, alignof(DependentTemplateName)) 7603 DependentTemplateName(NNS, Operator, Canon); 7604 7605 DependentTemplateName *CheckQTN 7606 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 7607 assert(!CheckQTN && "Dependent template name canonicalization broken"); 7608 (void)CheckQTN; 7609 } 7610 7611 DependentTemplateNames.InsertNode(QTN, InsertPos); 7612 return TemplateName(QTN); 7613 } 7614 7615 TemplateName 7616 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 7617 TemplateName replacement) const { 7618 llvm::FoldingSetNodeID ID; 7619 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 7620 7621 void *insertPos = nullptr; 7622 SubstTemplateTemplateParmStorage *subst 7623 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 7624 7625 if (!subst) { 7626 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 7627 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 7628 } 7629 7630 return TemplateName(subst); 7631 } 7632 7633 TemplateName 7634 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 7635 const TemplateArgument &ArgPack) const { 7636 auto &Self = const_cast<ASTContext &>(*this); 7637 llvm::FoldingSetNodeID ID; 7638 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 7639 7640 void *InsertPos = nullptr; 7641 SubstTemplateTemplateParmPackStorage *Subst 7642 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 7643 7644 if (!Subst) { 7645 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 7646 ArgPack.pack_size(), 7647 ArgPack.pack_begin()); 7648 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 7649 } 7650 7651 return TemplateName(Subst); 7652 } 7653 7654 /// getFromTargetType - Given one of the integer types provided by 7655 /// TargetInfo, produce the corresponding type. The unsigned @p Type 7656 /// is actually a value of type @c TargetInfo::IntType. 7657 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 7658 switch (Type) { 7659 case TargetInfo::NoInt: return {}; 7660 case TargetInfo::SignedChar: return SignedCharTy; 7661 case TargetInfo::UnsignedChar: return UnsignedCharTy; 7662 case TargetInfo::SignedShort: return ShortTy; 7663 case TargetInfo::UnsignedShort: return UnsignedShortTy; 7664 case TargetInfo::SignedInt: return IntTy; 7665 case TargetInfo::UnsignedInt: return UnsignedIntTy; 7666 case TargetInfo::SignedLong: return LongTy; 7667 case TargetInfo::UnsignedLong: return UnsignedLongTy; 7668 case TargetInfo::SignedLongLong: return LongLongTy; 7669 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 7670 } 7671 7672 llvm_unreachable("Unhandled TargetInfo::IntType value"); 7673 } 7674 7675 //===----------------------------------------------------------------------===// 7676 // Type Predicates. 7677 //===----------------------------------------------------------------------===// 7678 7679 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 7680 /// garbage collection attribute. 7681 /// 7682 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 7683 if (getLangOpts().getGC() == LangOptions::NonGC) 7684 return Qualifiers::GCNone; 7685 7686 assert(getLangOpts().ObjC1); 7687 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 7688 7689 // Default behaviour under objective-C's gc is for ObjC pointers 7690 // (or pointers to them) be treated as though they were declared 7691 // as __strong. 7692 if (GCAttrs == Qualifiers::GCNone) { 7693 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 7694 return Qualifiers::Strong; 7695 else if (Ty->isPointerType()) 7696 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType()); 7697 } else { 7698 // It's not valid to set GC attributes on anything that isn't a 7699 // pointer. 7700 #ifndef NDEBUG 7701 QualType CT = Ty->getCanonicalTypeInternal(); 7702 while (const auto *AT = dyn_cast<ArrayType>(CT)) 7703 CT = AT->getElementType(); 7704 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 7705 #endif 7706 } 7707 return GCAttrs; 7708 } 7709 7710 //===----------------------------------------------------------------------===// 7711 // Type Compatibility Testing 7712 //===----------------------------------------------------------------------===// 7713 7714 /// areCompatVectorTypes - Return true if the two specified vector types are 7715 /// compatible. 7716 static bool areCompatVectorTypes(const VectorType *LHS, 7717 const VectorType *RHS) { 7718 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 7719 return LHS->getElementType() == RHS->getElementType() && 7720 LHS->getNumElements() == RHS->getNumElements(); 7721 } 7722 7723 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 7724 QualType SecondVec) { 7725 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 7726 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 7727 7728 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 7729 return true; 7730 7731 // Treat Neon vector types and most AltiVec vector types as if they are the 7732 // equivalent GCC vector types. 7733 const auto *First = FirstVec->getAs<VectorType>(); 7734 const auto *Second = SecondVec->getAs<VectorType>(); 7735 if (First->getNumElements() == Second->getNumElements() && 7736 hasSameType(First->getElementType(), Second->getElementType()) && 7737 First->getVectorKind() != VectorType::AltiVecPixel && 7738 First->getVectorKind() != VectorType::AltiVecBool && 7739 Second->getVectorKind() != VectorType::AltiVecPixel && 7740 Second->getVectorKind() != VectorType::AltiVecBool) 7741 return true; 7742 7743 return false; 7744 } 7745 7746 //===----------------------------------------------------------------------===// 7747 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 7748 //===----------------------------------------------------------------------===// 7749 7750 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 7751 /// inheritance hierarchy of 'rProto'. 7752 bool 7753 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 7754 ObjCProtocolDecl *rProto) const { 7755 if (declaresSameEntity(lProto, rProto)) 7756 return true; 7757 for (auto *PI : rProto->protocols()) 7758 if (ProtocolCompatibleWithProtocol(lProto, PI)) 7759 return true; 7760 return false; 7761 } 7762 7763 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 7764 /// Class<pr1, ...>. 7765 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs, 7766 QualType rhs) { 7767 const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>(); 7768 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 7769 assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible"); 7770 7771 for (auto *lhsProto : lhsQID->quals()) { 7772 bool match = false; 7773 for (auto *rhsProto : rhsOPT->quals()) { 7774 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 7775 match = true; 7776 break; 7777 } 7778 } 7779 if (!match) 7780 return false; 7781 } 7782 return true; 7783 } 7784 7785 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 7786 /// ObjCQualifiedIDType. 7787 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, 7788 bool compare) { 7789 // Allow id<P..> and an 'id' or void* type in all cases. 7790 if (lhs->isVoidPointerType() || 7791 lhs->isObjCIdType() || lhs->isObjCClassType()) 7792 return true; 7793 else if (rhs->isVoidPointerType() || 7794 rhs->isObjCIdType() || rhs->isObjCClassType()) 7795 return true; 7796 7797 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) { 7798 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 7799 7800 if (!rhsOPT) return false; 7801 7802 if (rhsOPT->qual_empty()) { 7803 // If the RHS is a unqualified interface pointer "NSString*", 7804 // make sure we check the class hierarchy. 7805 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 7806 for (auto *I : lhsQID->quals()) { 7807 // when comparing an id<P> on lhs with a static type on rhs, 7808 // see if static class implements all of id's protocols, directly or 7809 // through its super class and categories. 7810 if (!rhsID->ClassImplementsProtocol(I, true)) 7811 return false; 7812 } 7813 } 7814 // If there are no qualifiers and no interface, we have an 'id'. 7815 return true; 7816 } 7817 // Both the right and left sides have qualifiers. 7818 for (auto *lhsProto : lhsQID->quals()) { 7819 bool match = false; 7820 7821 // when comparing an id<P> on lhs with a static type on rhs, 7822 // see if static class implements all of id's protocols, directly or 7823 // through its super class and categories. 7824 for (auto *rhsProto : rhsOPT->quals()) { 7825 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 7826 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 7827 match = true; 7828 break; 7829 } 7830 } 7831 // If the RHS is a qualified interface pointer "NSString<P>*", 7832 // make sure we check the class hierarchy. 7833 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 7834 for (auto *I : lhsQID->quals()) { 7835 // when comparing an id<P> on lhs with a static type on rhs, 7836 // see if static class implements all of id's protocols, directly or 7837 // through its super class and categories. 7838 if (rhsID->ClassImplementsProtocol(I, true)) { 7839 match = true; 7840 break; 7841 } 7842 } 7843 } 7844 if (!match) 7845 return false; 7846 } 7847 7848 return true; 7849 } 7850 7851 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType(); 7852 assert(rhsQID && "One of the LHS/RHS should be id<x>"); 7853 7854 if (const ObjCObjectPointerType *lhsOPT = 7855 lhs->getAsObjCInterfacePointerType()) { 7856 // If both the right and left sides have qualifiers. 7857 for (auto *lhsProto : lhsOPT->quals()) { 7858 bool match = false; 7859 7860 // when comparing an id<P> on rhs with a static type on lhs, 7861 // see if static class implements all of id's protocols, directly or 7862 // through its super class and categories. 7863 // First, lhs protocols in the qualifier list must be found, direct 7864 // or indirect in rhs's qualifier list or it is a mismatch. 7865 for (auto *rhsProto : rhsQID->quals()) { 7866 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 7867 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 7868 match = true; 7869 break; 7870 } 7871 } 7872 if (!match) 7873 return false; 7874 } 7875 7876 // Static class's protocols, or its super class or category protocols 7877 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 7878 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) { 7879 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 7880 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 7881 // This is rather dubious but matches gcc's behavior. If lhs has 7882 // no type qualifier and its class has no static protocol(s) 7883 // assume that it is mismatch. 7884 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty()) 7885 return false; 7886 for (auto *lhsProto : LHSInheritedProtocols) { 7887 bool match = false; 7888 for (auto *rhsProto : rhsQID->quals()) { 7889 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 7890 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 7891 match = true; 7892 break; 7893 } 7894 } 7895 if (!match) 7896 return false; 7897 } 7898 } 7899 return true; 7900 } 7901 return false; 7902 } 7903 7904 /// canAssignObjCInterfaces - Return true if the two interface types are 7905 /// compatible for assignment from RHS to LHS. This handles validation of any 7906 /// protocol qualifiers on the LHS or RHS. 7907 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 7908 const ObjCObjectPointerType *RHSOPT) { 7909 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 7910 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 7911 7912 // If either type represents the built-in 'id' or 'Class' types, return true. 7913 if (LHS->isObjCUnqualifiedIdOrClass() || 7914 RHS->isObjCUnqualifiedIdOrClass()) 7915 return true; 7916 7917 // Function object that propagates a successful result or handles 7918 // __kindof types. 7919 auto finish = [&](bool succeeded) -> bool { 7920 if (succeeded) 7921 return true; 7922 7923 if (!RHS->isKindOfType()) 7924 return false; 7925 7926 // Strip off __kindof and protocol qualifiers, then check whether 7927 // we can assign the other way. 7928 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this), 7929 LHSOPT->stripObjCKindOfTypeAndQuals(*this)); 7930 }; 7931 7932 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) { 7933 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 7934 QualType(RHSOPT,0), 7935 false)); 7936 } 7937 7938 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { 7939 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0), 7940 QualType(RHSOPT,0))); 7941 } 7942 7943 // If we have 2 user-defined types, fall into that path. 7944 if (LHS->getInterface() && RHS->getInterface()) { 7945 return finish(canAssignObjCInterfaces(LHS, RHS)); 7946 } 7947 7948 return false; 7949 } 7950 7951 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 7952 /// for providing type-safety for objective-c pointers used to pass/return 7953 /// arguments in block literals. When passed as arguments, passing 'A*' where 7954 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 7955 /// not OK. For the return type, the opposite is not OK. 7956 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 7957 const ObjCObjectPointerType *LHSOPT, 7958 const ObjCObjectPointerType *RHSOPT, 7959 bool BlockReturnType) { 7960 7961 // Function object that propagates a successful result or handles 7962 // __kindof types. 7963 auto finish = [&](bool succeeded) -> bool { 7964 if (succeeded) 7965 return true; 7966 7967 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT; 7968 if (!Expected->isKindOfType()) 7969 return false; 7970 7971 // Strip off __kindof and protocol qualifiers, then check whether 7972 // we can assign the other way. 7973 return canAssignObjCInterfacesInBlockPointer( 7974 RHSOPT->stripObjCKindOfTypeAndQuals(*this), 7975 LHSOPT->stripObjCKindOfTypeAndQuals(*this), 7976 BlockReturnType); 7977 }; 7978 7979 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 7980 return true; 7981 7982 if (LHSOPT->isObjCBuiltinType()) { 7983 return finish(RHSOPT->isObjCBuiltinType() || 7984 RHSOPT->isObjCQualifiedIdType()); 7985 } 7986 7987 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) 7988 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 7989 QualType(RHSOPT,0), 7990 false)); 7991 7992 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 7993 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 7994 if (LHS && RHS) { // We have 2 user-defined types. 7995 if (LHS != RHS) { 7996 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 7997 return finish(BlockReturnType); 7998 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 7999 return finish(!BlockReturnType); 8000 } 8001 else 8002 return true; 8003 } 8004 return false; 8005 } 8006 8007 /// Comparison routine for Objective-C protocols to be used with 8008 /// llvm::array_pod_sort. 8009 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, 8010 ObjCProtocolDecl * const *rhs) { 8011 return (*lhs)->getName().compare((*rhs)->getName()); 8012 } 8013 8014 /// getIntersectionOfProtocols - This routine finds the intersection of set 8015 /// of protocols inherited from two distinct objective-c pointer objects with 8016 /// the given common base. 8017 /// It is used to build composite qualifier list of the composite type of 8018 /// the conditional expression involving two objective-c pointer objects. 8019 static 8020 void getIntersectionOfProtocols(ASTContext &Context, 8021 const ObjCInterfaceDecl *CommonBase, 8022 const ObjCObjectPointerType *LHSOPT, 8023 const ObjCObjectPointerType *RHSOPT, 8024 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { 8025 8026 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 8027 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 8028 assert(LHS->getInterface() && "LHS must have an interface base"); 8029 assert(RHS->getInterface() && "RHS must have an interface base"); 8030 8031 // Add all of the protocols for the LHS. 8032 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet; 8033 8034 // Start with the protocol qualifiers. 8035 for (auto proto : LHS->quals()) { 8036 Context.CollectInheritedProtocols(proto, LHSProtocolSet); 8037 } 8038 8039 // Also add the protocols associated with the LHS interface. 8040 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet); 8041 8042 // Add all of the protocls for the RHS. 8043 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet; 8044 8045 // Start with the protocol qualifiers. 8046 for (auto proto : RHS->quals()) { 8047 Context.CollectInheritedProtocols(proto, RHSProtocolSet); 8048 } 8049 8050 // Also add the protocols associated with the RHS interface. 8051 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet); 8052 8053 // Compute the intersection of the collected protocol sets. 8054 for (auto proto : LHSProtocolSet) { 8055 if (RHSProtocolSet.count(proto)) 8056 IntersectionSet.push_back(proto); 8057 } 8058 8059 // Compute the set of protocols that is implied by either the common type or 8060 // the protocols within the intersection. 8061 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols; 8062 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols); 8063 8064 // Remove any implied protocols from the list of inherited protocols. 8065 if (!ImpliedProtocols.empty()) { 8066 IntersectionSet.erase( 8067 std::remove_if(IntersectionSet.begin(), 8068 IntersectionSet.end(), 8069 [&](ObjCProtocolDecl *proto) -> bool { 8070 return ImpliedProtocols.count(proto) > 0; 8071 }), 8072 IntersectionSet.end()); 8073 } 8074 8075 // Sort the remaining protocols by name. 8076 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(), 8077 compareObjCProtocolsByName); 8078 } 8079 8080 /// Determine whether the first type is a subtype of the second. 8081 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, 8082 QualType rhs) { 8083 // Common case: two object pointers. 8084 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>(); 8085 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 8086 if (lhsOPT && rhsOPT) 8087 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT); 8088 8089 // Two block pointers. 8090 const auto *lhsBlock = lhs->getAs<BlockPointerType>(); 8091 const auto *rhsBlock = rhs->getAs<BlockPointerType>(); 8092 if (lhsBlock && rhsBlock) 8093 return ctx.typesAreBlockPointerCompatible(lhs, rhs); 8094 8095 // If either is an unqualified 'id' and the other is a block, it's 8096 // acceptable. 8097 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) || 8098 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock)) 8099 return true; 8100 8101 return false; 8102 } 8103 8104 // Check that the given Objective-C type argument lists are equivalent. 8105 static bool sameObjCTypeArgs(ASTContext &ctx, 8106 const ObjCInterfaceDecl *iface, 8107 ArrayRef<QualType> lhsArgs, 8108 ArrayRef<QualType> rhsArgs, 8109 bool stripKindOf) { 8110 if (lhsArgs.size() != rhsArgs.size()) 8111 return false; 8112 8113 ObjCTypeParamList *typeParams = iface->getTypeParamList(); 8114 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) { 8115 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i])) 8116 continue; 8117 8118 switch (typeParams->begin()[i]->getVariance()) { 8119 case ObjCTypeParamVariance::Invariant: 8120 if (!stripKindOf || 8121 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx), 8122 rhsArgs[i].stripObjCKindOfType(ctx))) { 8123 return false; 8124 } 8125 break; 8126 8127 case ObjCTypeParamVariance::Covariant: 8128 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i])) 8129 return false; 8130 break; 8131 8132 case ObjCTypeParamVariance::Contravariant: 8133 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i])) 8134 return false; 8135 break; 8136 } 8137 } 8138 8139 return true; 8140 } 8141 8142 QualType ASTContext::areCommonBaseCompatible( 8143 const ObjCObjectPointerType *Lptr, 8144 const ObjCObjectPointerType *Rptr) { 8145 const ObjCObjectType *LHS = Lptr->getObjectType(); 8146 const ObjCObjectType *RHS = Rptr->getObjectType(); 8147 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 8148 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 8149 8150 if (!LDecl || !RDecl) 8151 return {}; 8152 8153 // When either LHS or RHS is a kindof type, we should return a kindof type. 8154 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return 8155 // kindof(A). 8156 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType(); 8157 8158 // Follow the left-hand side up the class hierarchy until we either hit a 8159 // root or find the RHS. Record the ancestors in case we don't find it. 8160 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4> 8161 LHSAncestors; 8162 while (true) { 8163 // Record this ancestor. We'll need this if the common type isn't in the 8164 // path from the LHS to the root. 8165 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS; 8166 8167 if (declaresSameEntity(LHS->getInterface(), RDecl)) { 8168 // Get the type arguments. 8169 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten(); 8170 bool anyChanges = false; 8171 if (LHS->isSpecialized() && RHS->isSpecialized()) { 8172 // Both have type arguments, compare them. 8173 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 8174 LHS->getTypeArgs(), RHS->getTypeArgs(), 8175 /*stripKindOf=*/true)) 8176 return {}; 8177 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 8178 // If only one has type arguments, the result will not have type 8179 // arguments. 8180 LHSTypeArgs = {}; 8181 anyChanges = true; 8182 } 8183 8184 // Compute the intersection of protocols. 8185 SmallVector<ObjCProtocolDecl *, 8> Protocols; 8186 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr, 8187 Protocols); 8188 if (!Protocols.empty()) 8189 anyChanges = true; 8190 8191 // If anything in the LHS will have changed, build a new result type. 8192 // If we need to return a kindof type but LHS is not a kindof type, we 8193 // build a new result type. 8194 if (anyChanges || LHS->isKindOfType() != anyKindOf) { 8195 QualType Result = getObjCInterfaceType(LHS->getInterface()); 8196 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols, 8197 anyKindOf || LHS->isKindOfType()); 8198 return getObjCObjectPointerType(Result); 8199 } 8200 8201 return getObjCObjectPointerType(QualType(LHS, 0)); 8202 } 8203 8204 // Find the superclass. 8205 QualType LHSSuperType = LHS->getSuperClassType(); 8206 if (LHSSuperType.isNull()) 8207 break; 8208 8209 LHS = LHSSuperType->castAs<ObjCObjectType>(); 8210 } 8211 8212 // We didn't find anything by following the LHS to its root; now check 8213 // the RHS against the cached set of ancestors. 8214 while (true) { 8215 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl()); 8216 if (KnownLHS != LHSAncestors.end()) { 8217 LHS = KnownLHS->second; 8218 8219 // Get the type arguments. 8220 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten(); 8221 bool anyChanges = false; 8222 if (LHS->isSpecialized() && RHS->isSpecialized()) { 8223 // Both have type arguments, compare them. 8224 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 8225 LHS->getTypeArgs(), RHS->getTypeArgs(), 8226 /*stripKindOf=*/true)) 8227 return {}; 8228 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 8229 // If only one has type arguments, the result will not have type 8230 // arguments. 8231 RHSTypeArgs = {}; 8232 anyChanges = true; 8233 } 8234 8235 // Compute the intersection of protocols. 8236 SmallVector<ObjCProtocolDecl *, 8> Protocols; 8237 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr, 8238 Protocols); 8239 if (!Protocols.empty()) 8240 anyChanges = true; 8241 8242 // If we need to return a kindof type but RHS is not a kindof type, we 8243 // build a new result type. 8244 if (anyChanges || RHS->isKindOfType() != anyKindOf) { 8245 QualType Result = getObjCInterfaceType(RHS->getInterface()); 8246 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols, 8247 anyKindOf || RHS->isKindOfType()); 8248 return getObjCObjectPointerType(Result); 8249 } 8250 8251 return getObjCObjectPointerType(QualType(RHS, 0)); 8252 } 8253 8254 // Find the superclass of the RHS. 8255 QualType RHSSuperType = RHS->getSuperClassType(); 8256 if (RHSSuperType.isNull()) 8257 break; 8258 8259 RHS = RHSSuperType->castAs<ObjCObjectType>(); 8260 } 8261 8262 return {}; 8263 } 8264 8265 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 8266 const ObjCObjectType *RHS) { 8267 assert(LHS->getInterface() && "LHS is not an interface type"); 8268 assert(RHS->getInterface() && "RHS is not an interface type"); 8269 8270 // Verify that the base decls are compatible: the RHS must be a subclass of 8271 // the LHS. 8272 ObjCInterfaceDecl *LHSInterface = LHS->getInterface(); 8273 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface()); 8274 if (!IsSuperClass) 8275 return false; 8276 8277 // If the LHS has protocol qualifiers, determine whether all of them are 8278 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the 8279 // LHS). 8280 if (LHS->getNumProtocols() > 0) { 8281 // OK if conversion of LHS to SuperClass results in narrowing of types 8282 // ; i.e., SuperClass may implement at least one of the protocols 8283 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 8284 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 8285 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 8286 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 8287 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's 8288 // qualifiers. 8289 for (auto *RHSPI : RHS->quals()) 8290 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols); 8291 // If there is no protocols associated with RHS, it is not a match. 8292 if (SuperClassInheritedProtocols.empty()) 8293 return false; 8294 8295 for (const auto *LHSProto : LHS->quals()) { 8296 bool SuperImplementsProtocol = false; 8297 for (auto *SuperClassProto : SuperClassInheritedProtocols) 8298 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 8299 SuperImplementsProtocol = true; 8300 break; 8301 } 8302 if (!SuperImplementsProtocol) 8303 return false; 8304 } 8305 } 8306 8307 // If the LHS is specialized, we may need to check type arguments. 8308 if (LHS->isSpecialized()) { 8309 // Follow the superclass chain until we've matched the LHS class in the 8310 // hierarchy. This substitutes type arguments through. 8311 const ObjCObjectType *RHSSuper = RHS; 8312 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface)) 8313 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>(); 8314 8315 // If the RHS is specializd, compare type arguments. 8316 if (RHSSuper->isSpecialized() && 8317 !sameObjCTypeArgs(*this, LHS->getInterface(), 8318 LHS->getTypeArgs(), RHSSuper->getTypeArgs(), 8319 /*stripKindOf=*/true)) { 8320 return false; 8321 } 8322 } 8323 8324 return true; 8325 } 8326 8327 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 8328 // get the "pointed to" types 8329 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 8330 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 8331 8332 if (!LHSOPT || !RHSOPT) 8333 return false; 8334 8335 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 8336 canAssignObjCInterfaces(RHSOPT, LHSOPT); 8337 } 8338 8339 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 8340 return canAssignObjCInterfaces( 8341 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(), 8342 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>()); 8343 } 8344 8345 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 8346 /// both shall have the identically qualified version of a compatible type. 8347 /// C99 6.2.7p1: Two types have compatible types if their types are the 8348 /// same. See 6.7.[2,3,5] for additional rules. 8349 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 8350 bool CompareUnqualified) { 8351 if (getLangOpts().CPlusPlus) 8352 return hasSameType(LHS, RHS); 8353 8354 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 8355 } 8356 8357 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 8358 return typesAreCompatible(LHS, RHS); 8359 } 8360 8361 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 8362 return !mergeTypes(LHS, RHS, true).isNull(); 8363 } 8364 8365 /// mergeTransparentUnionType - if T is a transparent union type and a member 8366 /// of T is compatible with SubType, return the merged type, else return 8367 /// QualType() 8368 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 8369 bool OfBlockPointer, 8370 bool Unqualified) { 8371 if (const RecordType *UT = T->getAsUnionType()) { 8372 RecordDecl *UD = UT->getDecl(); 8373 if (UD->hasAttr<TransparentUnionAttr>()) { 8374 for (const auto *I : UD->fields()) { 8375 QualType ET = I->getType().getUnqualifiedType(); 8376 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 8377 if (!MT.isNull()) 8378 return MT; 8379 } 8380 } 8381 } 8382 8383 return {}; 8384 } 8385 8386 /// mergeFunctionParameterTypes - merge two types which appear as function 8387 /// parameter types 8388 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 8389 bool OfBlockPointer, 8390 bool Unqualified) { 8391 // GNU extension: two types are compatible if they appear as a function 8392 // argument, one of the types is a transparent union type and the other 8393 // type is compatible with a union member 8394 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 8395 Unqualified); 8396 if (!lmerge.isNull()) 8397 return lmerge; 8398 8399 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 8400 Unqualified); 8401 if (!rmerge.isNull()) 8402 return rmerge; 8403 8404 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 8405 } 8406 8407 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 8408 bool OfBlockPointer, 8409 bool Unqualified) { 8410 const auto *lbase = lhs->getAs<FunctionType>(); 8411 const auto *rbase = rhs->getAs<FunctionType>(); 8412 const auto *lproto = dyn_cast<FunctionProtoType>(lbase); 8413 const auto *rproto = dyn_cast<FunctionProtoType>(rbase); 8414 bool allLTypes = true; 8415 bool allRTypes = true; 8416 8417 // Check return type 8418 QualType retType; 8419 if (OfBlockPointer) { 8420 QualType RHS = rbase->getReturnType(); 8421 QualType LHS = lbase->getReturnType(); 8422 bool UnqualifiedResult = Unqualified; 8423 if (!UnqualifiedResult) 8424 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 8425 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 8426 } 8427 else 8428 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 8429 Unqualified); 8430 if (retType.isNull()) 8431 return {}; 8432 8433 if (Unqualified) 8434 retType = retType.getUnqualifiedType(); 8435 8436 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 8437 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 8438 if (Unqualified) { 8439 LRetType = LRetType.getUnqualifiedType(); 8440 RRetType = RRetType.getUnqualifiedType(); 8441 } 8442 8443 if (getCanonicalType(retType) != LRetType) 8444 allLTypes = false; 8445 if (getCanonicalType(retType) != RRetType) 8446 allRTypes = false; 8447 8448 // FIXME: double check this 8449 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 8450 // rbase->getRegParmAttr() != 0 && 8451 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 8452 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 8453 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 8454 8455 // Compatible functions must have compatible calling conventions 8456 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 8457 return {}; 8458 8459 // Regparm is part of the calling convention. 8460 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 8461 return {}; 8462 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 8463 return {}; 8464 8465 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 8466 return {}; 8467 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs()) 8468 return {}; 8469 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck()) 8470 return {}; 8471 8472 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 8473 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 8474 8475 if (lbaseInfo.getNoReturn() != NoReturn) 8476 allLTypes = false; 8477 if (rbaseInfo.getNoReturn() != NoReturn) 8478 allRTypes = false; 8479 8480 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 8481 8482 if (lproto && rproto) { // two C99 style function prototypes 8483 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() && 8484 "C++ shouldn't be here"); 8485 // Compatible functions must have the same number of parameters 8486 if (lproto->getNumParams() != rproto->getNumParams()) 8487 return {}; 8488 8489 // Variadic and non-variadic functions aren't compatible 8490 if (lproto->isVariadic() != rproto->isVariadic()) 8491 return {}; 8492 8493 if (lproto->getTypeQuals() != rproto->getTypeQuals()) 8494 return {}; 8495 8496 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos; 8497 bool canUseLeft, canUseRight; 8498 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight, 8499 newParamInfos)) 8500 return {}; 8501 8502 if (!canUseLeft) 8503 allLTypes = false; 8504 if (!canUseRight) 8505 allRTypes = false; 8506 8507 // Check parameter type compatibility 8508 SmallVector<QualType, 10> types; 8509 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 8510 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 8511 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 8512 QualType paramType = mergeFunctionParameterTypes( 8513 lParamType, rParamType, OfBlockPointer, Unqualified); 8514 if (paramType.isNull()) 8515 return {}; 8516 8517 if (Unqualified) 8518 paramType = paramType.getUnqualifiedType(); 8519 8520 types.push_back(paramType); 8521 if (Unqualified) { 8522 lParamType = lParamType.getUnqualifiedType(); 8523 rParamType = rParamType.getUnqualifiedType(); 8524 } 8525 8526 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 8527 allLTypes = false; 8528 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 8529 allRTypes = false; 8530 } 8531 8532 if (allLTypes) return lhs; 8533 if (allRTypes) return rhs; 8534 8535 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 8536 EPI.ExtInfo = einfo; 8537 EPI.ExtParameterInfos = 8538 newParamInfos.empty() ? nullptr : newParamInfos.data(); 8539 return getFunctionType(retType, types, EPI); 8540 } 8541 8542 if (lproto) allRTypes = false; 8543 if (rproto) allLTypes = false; 8544 8545 const FunctionProtoType *proto = lproto ? lproto : rproto; 8546 if (proto) { 8547 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here"); 8548 if (proto->isVariadic()) 8549 return {}; 8550 // Check that the types are compatible with the types that 8551 // would result from default argument promotions (C99 6.7.5.3p15). 8552 // The only types actually affected are promotable integer 8553 // types and floats, which would be passed as a different 8554 // type depending on whether the prototype is visible. 8555 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 8556 QualType paramTy = proto->getParamType(i); 8557 8558 // Look at the converted type of enum types, since that is the type used 8559 // to pass enum values. 8560 if (const auto *Enum = paramTy->getAs<EnumType>()) { 8561 paramTy = Enum->getDecl()->getIntegerType(); 8562 if (paramTy.isNull()) 8563 return {}; 8564 } 8565 8566 if (paramTy->isPromotableIntegerType() || 8567 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 8568 return {}; 8569 } 8570 8571 if (allLTypes) return lhs; 8572 if (allRTypes) return rhs; 8573 8574 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 8575 EPI.ExtInfo = einfo; 8576 return getFunctionType(retType, proto->getParamTypes(), EPI); 8577 } 8578 8579 if (allLTypes) return lhs; 8580 if (allRTypes) return rhs; 8581 return getFunctionNoProtoType(retType, einfo); 8582 } 8583 8584 /// Given that we have an enum type and a non-enum type, try to merge them. 8585 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 8586 QualType other, bool isBlockReturnType) { 8587 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 8588 // a signed integer type, or an unsigned integer type. 8589 // Compatibility is based on the underlying type, not the promotion 8590 // type. 8591 QualType underlyingType = ET->getDecl()->getIntegerType(); 8592 if (underlyingType.isNull()) 8593 return {}; 8594 if (Context.hasSameType(underlyingType, other)) 8595 return other; 8596 8597 // In block return types, we're more permissive and accept any 8598 // integral type of the same size. 8599 if (isBlockReturnType && other->isIntegerType() && 8600 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 8601 return other; 8602 8603 return {}; 8604 } 8605 8606 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 8607 bool OfBlockPointer, 8608 bool Unqualified, bool BlockReturnType) { 8609 // C++ [expr]: If an expression initially has the type "reference to T", the 8610 // type is adjusted to "T" prior to any further analysis, the expression 8611 // designates the object or function denoted by the reference, and the 8612 // expression is an lvalue unless the reference is an rvalue reference and 8613 // the expression is a function call (possibly inside parentheses). 8614 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?"); 8615 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?"); 8616 8617 if (Unqualified) { 8618 LHS = LHS.getUnqualifiedType(); 8619 RHS = RHS.getUnqualifiedType(); 8620 } 8621 8622 QualType LHSCan = getCanonicalType(LHS), 8623 RHSCan = getCanonicalType(RHS); 8624 8625 // If two types are identical, they are compatible. 8626 if (LHSCan == RHSCan) 8627 return LHS; 8628 8629 // If the qualifiers are different, the types aren't compatible... mostly. 8630 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 8631 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 8632 if (LQuals != RQuals) { 8633 // If any of these qualifiers are different, we have a type 8634 // mismatch. 8635 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 8636 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 8637 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() || 8638 LQuals.hasUnaligned() != RQuals.hasUnaligned()) 8639 return {}; 8640 8641 // Exactly one GC qualifier difference is allowed: __strong is 8642 // okay if the other type has no GC qualifier but is an Objective 8643 // C object pointer (i.e. implicitly strong by default). We fix 8644 // this by pretending that the unqualified type was actually 8645 // qualified __strong. 8646 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 8647 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 8648 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 8649 8650 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 8651 return {}; 8652 8653 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 8654 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 8655 } 8656 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 8657 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 8658 } 8659 return {}; 8660 } 8661 8662 // Okay, qualifiers are equal. 8663 8664 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 8665 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 8666 8667 // We want to consider the two function types to be the same for these 8668 // comparisons, just force one to the other. 8669 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 8670 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 8671 8672 // Same as above for arrays 8673 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 8674 LHSClass = Type::ConstantArray; 8675 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 8676 RHSClass = Type::ConstantArray; 8677 8678 // ObjCInterfaces are just specialized ObjCObjects. 8679 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 8680 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 8681 8682 // Canonicalize ExtVector -> Vector. 8683 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 8684 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 8685 8686 // If the canonical type classes don't match. 8687 if (LHSClass != RHSClass) { 8688 // Note that we only have special rules for turning block enum 8689 // returns into block int returns, not vice-versa. 8690 if (const auto *ETy = LHS->getAs<EnumType>()) { 8691 return mergeEnumWithInteger(*this, ETy, RHS, false); 8692 } 8693 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 8694 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 8695 } 8696 // allow block pointer type to match an 'id' type. 8697 if (OfBlockPointer && !BlockReturnType) { 8698 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 8699 return LHS; 8700 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 8701 return RHS; 8702 } 8703 8704 return {}; 8705 } 8706 8707 // The canonical type classes match. 8708 switch (LHSClass) { 8709 #define TYPE(Class, Base) 8710 #define ABSTRACT_TYPE(Class, Base) 8711 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 8712 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 8713 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 8714 #include "clang/AST/TypeNodes.def" 8715 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 8716 8717 case Type::Auto: 8718 case Type::DeducedTemplateSpecialization: 8719 case Type::LValueReference: 8720 case Type::RValueReference: 8721 case Type::MemberPointer: 8722 llvm_unreachable("C++ should never be in mergeTypes"); 8723 8724 case Type::ObjCInterface: 8725 case Type::IncompleteArray: 8726 case Type::VariableArray: 8727 case Type::FunctionProto: 8728 case Type::ExtVector: 8729 llvm_unreachable("Types are eliminated above"); 8730 8731 case Type::Pointer: 8732 { 8733 // Merge two pointer types, while trying to preserve typedef info 8734 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType(); 8735 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType(); 8736 if (Unqualified) { 8737 LHSPointee = LHSPointee.getUnqualifiedType(); 8738 RHSPointee = RHSPointee.getUnqualifiedType(); 8739 } 8740 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 8741 Unqualified); 8742 if (ResultType.isNull()) 8743 return {}; 8744 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 8745 return LHS; 8746 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 8747 return RHS; 8748 return getPointerType(ResultType); 8749 } 8750 case Type::BlockPointer: 8751 { 8752 // Merge two block pointer types, while trying to preserve typedef info 8753 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType(); 8754 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType(); 8755 if (Unqualified) { 8756 LHSPointee = LHSPointee.getUnqualifiedType(); 8757 RHSPointee = RHSPointee.getUnqualifiedType(); 8758 } 8759 if (getLangOpts().OpenCL) { 8760 Qualifiers LHSPteeQual = LHSPointee.getQualifiers(); 8761 Qualifiers RHSPteeQual = RHSPointee.getQualifiers(); 8762 // Blocks can't be an expression in a ternary operator (OpenCL v2.0 8763 // 6.12.5) thus the following check is asymmetric. 8764 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual)) 8765 return {}; 8766 LHSPteeQual.removeAddressSpace(); 8767 RHSPteeQual.removeAddressSpace(); 8768 LHSPointee = 8769 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue()); 8770 RHSPointee = 8771 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue()); 8772 } 8773 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 8774 Unqualified); 8775 if (ResultType.isNull()) 8776 return {}; 8777 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 8778 return LHS; 8779 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 8780 return RHS; 8781 return getBlockPointerType(ResultType); 8782 } 8783 case Type::Atomic: 8784 { 8785 // Merge two pointer types, while trying to preserve typedef info 8786 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType(); 8787 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType(); 8788 if (Unqualified) { 8789 LHSValue = LHSValue.getUnqualifiedType(); 8790 RHSValue = RHSValue.getUnqualifiedType(); 8791 } 8792 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 8793 Unqualified); 8794 if (ResultType.isNull()) 8795 return {}; 8796 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 8797 return LHS; 8798 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 8799 return RHS; 8800 return getAtomicType(ResultType); 8801 } 8802 case Type::ConstantArray: 8803 { 8804 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 8805 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 8806 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 8807 return {}; 8808 8809 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 8810 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 8811 if (Unqualified) { 8812 LHSElem = LHSElem.getUnqualifiedType(); 8813 RHSElem = RHSElem.getUnqualifiedType(); 8814 } 8815 8816 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 8817 if (ResultType.isNull()) 8818 return {}; 8819 8820 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 8821 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 8822 8823 // If either side is a variable array, and both are complete, check whether 8824 // the current dimension is definite. 8825 if (LVAT || RVAT) { 8826 auto SizeFetch = [this](const VariableArrayType* VAT, 8827 const ConstantArrayType* CAT) 8828 -> std::pair<bool,llvm::APInt> { 8829 if (VAT) { 8830 llvm::APSInt TheInt; 8831 Expr *E = VAT->getSizeExpr(); 8832 if (E && E->isIntegerConstantExpr(TheInt, *this)) 8833 return std::make_pair(true, TheInt); 8834 else 8835 return std::make_pair(false, TheInt); 8836 } else if (CAT) { 8837 return std::make_pair(true, CAT->getSize()); 8838 } else { 8839 return std::make_pair(false, llvm::APInt()); 8840 } 8841 }; 8842 8843 bool HaveLSize, HaveRSize; 8844 llvm::APInt LSize, RSize; 8845 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT); 8846 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT); 8847 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize)) 8848 return {}; // Definite, but unequal, array dimension 8849 } 8850 8851 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 8852 return LHS; 8853 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 8854 return RHS; 8855 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), 8856 ArrayType::ArraySizeModifier(), 0); 8857 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), 8858 ArrayType::ArraySizeModifier(), 0); 8859 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 8860 return LHS; 8861 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 8862 return RHS; 8863 if (LVAT) { 8864 // FIXME: This isn't correct! But tricky to implement because 8865 // the array's size has to be the size of LHS, but the type 8866 // has to be different. 8867 return LHS; 8868 } 8869 if (RVAT) { 8870 // FIXME: This isn't correct! But tricky to implement because 8871 // the array's size has to be the size of RHS, but the type 8872 // has to be different. 8873 return RHS; 8874 } 8875 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 8876 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 8877 return getIncompleteArrayType(ResultType, 8878 ArrayType::ArraySizeModifier(), 0); 8879 } 8880 case Type::FunctionNoProto: 8881 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 8882 case Type::Record: 8883 case Type::Enum: 8884 return {}; 8885 case Type::Builtin: 8886 // Only exactly equal builtin types are compatible, which is tested above. 8887 return {}; 8888 case Type::Complex: 8889 // Distinct complex types are incompatible. 8890 return {}; 8891 case Type::Vector: 8892 // FIXME: The merged type should be an ExtVector! 8893 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(), 8894 RHSCan->getAs<VectorType>())) 8895 return LHS; 8896 return {}; 8897 case Type::ObjCObject: { 8898 // Check if the types are assignment compatible. 8899 // FIXME: This should be type compatibility, e.g. whether 8900 // "LHS x; RHS x;" at global scope is legal. 8901 const auto *LHSIface = LHS->getAs<ObjCObjectType>(); 8902 const auto *RHSIface = RHS->getAs<ObjCObjectType>(); 8903 if (canAssignObjCInterfaces(LHSIface, RHSIface)) 8904 return LHS; 8905 8906 return {}; 8907 } 8908 case Type::ObjCObjectPointer: 8909 if (OfBlockPointer) { 8910 if (canAssignObjCInterfacesInBlockPointer( 8911 LHS->getAs<ObjCObjectPointerType>(), 8912 RHS->getAs<ObjCObjectPointerType>(), 8913 BlockReturnType)) 8914 return LHS; 8915 return {}; 8916 } 8917 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(), 8918 RHS->getAs<ObjCObjectPointerType>())) 8919 return LHS; 8920 8921 return {}; 8922 case Type::Pipe: 8923 assert(LHS != RHS && 8924 "Equivalent pipe types should have already been handled!"); 8925 return {}; 8926 } 8927 8928 llvm_unreachable("Invalid Type::Class!"); 8929 } 8930 8931 bool ASTContext::mergeExtParameterInfo( 8932 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, 8933 bool &CanUseFirst, bool &CanUseSecond, 8934 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) { 8935 assert(NewParamInfos.empty() && "param info list not empty"); 8936 CanUseFirst = CanUseSecond = true; 8937 bool FirstHasInfo = FirstFnType->hasExtParameterInfos(); 8938 bool SecondHasInfo = SecondFnType->hasExtParameterInfos(); 8939 8940 // Fast path: if the first type doesn't have ext parameter infos, 8941 // we match if and only if the second type also doesn't have them. 8942 if (!FirstHasInfo && !SecondHasInfo) 8943 return true; 8944 8945 bool NeedParamInfo = false; 8946 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size() 8947 : SecondFnType->getExtParameterInfos().size(); 8948 8949 for (size_t I = 0; I < E; ++I) { 8950 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam; 8951 if (FirstHasInfo) 8952 FirstParam = FirstFnType->getExtParameterInfo(I); 8953 if (SecondHasInfo) 8954 SecondParam = SecondFnType->getExtParameterInfo(I); 8955 8956 // Cannot merge unless everything except the noescape flag matches. 8957 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false)) 8958 return false; 8959 8960 bool FirstNoEscape = FirstParam.isNoEscape(); 8961 bool SecondNoEscape = SecondParam.isNoEscape(); 8962 bool IsNoEscape = FirstNoEscape && SecondNoEscape; 8963 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape)); 8964 if (NewParamInfos.back().getOpaqueValue()) 8965 NeedParamInfo = true; 8966 if (FirstNoEscape != IsNoEscape) 8967 CanUseFirst = false; 8968 if (SecondNoEscape != IsNoEscape) 8969 CanUseSecond = false; 8970 } 8971 8972 if (!NeedParamInfo) 8973 NewParamInfos.clear(); 8974 8975 return true; 8976 } 8977 8978 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) { 8979 ObjCLayouts[CD] = nullptr; 8980 } 8981 8982 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 8983 /// 'RHS' attributes and returns the merged version; including for function 8984 /// return types. 8985 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 8986 QualType LHSCan = getCanonicalType(LHS), 8987 RHSCan = getCanonicalType(RHS); 8988 // If two types are identical, they are compatible. 8989 if (LHSCan == RHSCan) 8990 return LHS; 8991 if (RHSCan->isFunctionType()) { 8992 if (!LHSCan->isFunctionType()) 8993 return {}; 8994 QualType OldReturnType = 8995 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 8996 QualType NewReturnType = 8997 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 8998 QualType ResReturnType = 8999 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 9000 if (ResReturnType.isNull()) 9001 return {}; 9002 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 9003 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 9004 // In either case, use OldReturnType to build the new function type. 9005 const auto *F = LHS->getAs<FunctionType>(); 9006 if (const auto *FPT = cast<FunctionProtoType>(F)) { 9007 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9008 EPI.ExtInfo = getFunctionExtInfo(LHS); 9009 QualType ResultType = 9010 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 9011 return ResultType; 9012 } 9013 } 9014 return {}; 9015 } 9016 9017 // If the qualifiers are different, the types can still be merged. 9018 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 9019 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 9020 if (LQuals != RQuals) { 9021 // If any of these qualifiers are different, we have a type mismatch. 9022 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 9023 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 9024 return {}; 9025 9026 // Exactly one GC qualifier difference is allowed: __strong is 9027 // okay if the other type has no GC qualifier but is an Objective 9028 // C object pointer (i.e. implicitly strong by default). We fix 9029 // this by pretending that the unqualified type was actually 9030 // qualified __strong. 9031 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 9032 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 9033 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 9034 9035 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 9036 return {}; 9037 9038 if (GC_L == Qualifiers::Strong) 9039 return LHS; 9040 if (GC_R == Qualifiers::Strong) 9041 return RHS; 9042 return {}; 9043 } 9044 9045 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 9046 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 9047 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 9048 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 9049 if (ResQT == LHSBaseQT) 9050 return LHS; 9051 if (ResQT == RHSBaseQT) 9052 return RHS; 9053 } 9054 return {}; 9055 } 9056 9057 //===----------------------------------------------------------------------===// 9058 // Integer Predicates 9059 //===----------------------------------------------------------------------===// 9060 9061 unsigned ASTContext::getIntWidth(QualType T) const { 9062 if (const auto *ET = T->getAs<EnumType>()) 9063 T = ET->getDecl()->getIntegerType(); 9064 if (T->isBooleanType()) 9065 return 1; 9066 // For builtin types, just use the standard type sizing method 9067 return (unsigned)getTypeSize(T); 9068 } 9069 9070 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 9071 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) && 9072 "Unexpected type"); 9073 9074 // Turn <4 x signed int> -> <4 x unsigned int> 9075 if (const auto *VTy = T->getAs<VectorType>()) 9076 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 9077 VTy->getNumElements(), VTy->getVectorKind()); 9078 9079 // For enums, we return the unsigned version of the base type. 9080 if (const auto *ETy = T->getAs<EnumType>()) 9081 T = ETy->getDecl()->getIntegerType(); 9082 9083 const auto *BTy = T->getAs<BuiltinType>(); 9084 assert(BTy && "Unexpected signed integer or fixed point type"); 9085 switch (BTy->getKind()) { 9086 case BuiltinType::Char_S: 9087 case BuiltinType::SChar: 9088 return UnsignedCharTy; 9089 case BuiltinType::Short: 9090 return UnsignedShortTy; 9091 case BuiltinType::Int: 9092 return UnsignedIntTy; 9093 case BuiltinType::Long: 9094 return UnsignedLongTy; 9095 case BuiltinType::LongLong: 9096 return UnsignedLongLongTy; 9097 case BuiltinType::Int128: 9098 return UnsignedInt128Ty; 9099 9100 case BuiltinType::ShortAccum: 9101 return UnsignedShortAccumTy; 9102 case BuiltinType::Accum: 9103 return UnsignedAccumTy; 9104 case BuiltinType::LongAccum: 9105 return UnsignedLongAccumTy; 9106 case BuiltinType::SatShortAccum: 9107 return SatUnsignedShortAccumTy; 9108 case BuiltinType::SatAccum: 9109 return SatUnsignedAccumTy; 9110 case BuiltinType::SatLongAccum: 9111 return SatUnsignedLongAccumTy; 9112 case BuiltinType::ShortFract: 9113 return UnsignedShortFractTy; 9114 case BuiltinType::Fract: 9115 return UnsignedFractTy; 9116 case BuiltinType::LongFract: 9117 return UnsignedLongFractTy; 9118 case BuiltinType::SatShortFract: 9119 return SatUnsignedShortFractTy; 9120 case BuiltinType::SatFract: 9121 return SatUnsignedFractTy; 9122 case BuiltinType::SatLongFract: 9123 return SatUnsignedLongFractTy; 9124 default: 9125 llvm_unreachable("Unexpected signed integer or fixed point type"); 9126 } 9127 } 9128 9129 ASTMutationListener::~ASTMutationListener() = default; 9130 9131 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 9132 QualType ReturnType) {} 9133 9134 //===----------------------------------------------------------------------===// 9135 // Builtin Type Computation 9136 //===----------------------------------------------------------------------===// 9137 9138 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 9139 /// pointer over the consumed characters. This returns the resultant type. If 9140 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic 9141 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 9142 /// a vector of "i*". 9143 /// 9144 /// RequiresICE is filled in on return to indicate whether the value is required 9145 /// to be an Integer Constant Expression. 9146 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 9147 ASTContext::GetBuiltinTypeError &Error, 9148 bool &RequiresICE, 9149 bool AllowTypeModifiers) { 9150 // Modifiers. 9151 int HowLong = 0; 9152 bool Signed = false, Unsigned = false; 9153 RequiresICE = false; 9154 9155 // Read the prefixed modifiers first. 9156 bool Done = false; 9157 #ifndef NDEBUG 9158 bool IsSpecialLong = false; 9159 #endif 9160 while (!Done) { 9161 switch (*Str++) { 9162 default: Done = true; --Str; break; 9163 case 'I': 9164 RequiresICE = true; 9165 break; 9166 case 'S': 9167 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 9168 assert(!Signed && "Can't use 'S' modifier multiple times!"); 9169 Signed = true; 9170 break; 9171 case 'U': 9172 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 9173 assert(!Unsigned && "Can't use 'U' modifier multiple times!"); 9174 Unsigned = true; 9175 break; 9176 case 'L': 9177 assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers"); 9178 assert(HowLong <= 2 && "Can't have LLLL modifier"); 9179 ++HowLong; 9180 break; 9181 case 'N': 9182 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise. 9183 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!"); 9184 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!"); 9185 #ifndef NDEBUG 9186 IsSpecialLong = true; 9187 #endif 9188 if (Context.getTargetInfo().getLongWidth() == 32) 9189 ++HowLong; 9190 break; 9191 case 'W': 9192 // This modifier represents int64 type. 9193 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!"); 9194 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 9195 #ifndef NDEBUG 9196 IsSpecialLong = true; 9197 #endif 9198 switch (Context.getTargetInfo().getInt64Type()) { 9199 default: 9200 llvm_unreachable("Unexpected integer type"); 9201 case TargetInfo::SignedLong: 9202 HowLong = 1; 9203 break; 9204 case TargetInfo::SignedLongLong: 9205 HowLong = 2; 9206 break; 9207 } 9208 break; 9209 } 9210 } 9211 9212 QualType Type; 9213 9214 // Read the base type. 9215 switch (*Str++) { 9216 default: llvm_unreachable("Unknown builtin type letter!"); 9217 case 'v': 9218 assert(HowLong == 0 && !Signed && !Unsigned && 9219 "Bad modifiers used with 'v'!"); 9220 Type = Context.VoidTy; 9221 break; 9222 case 'h': 9223 assert(HowLong == 0 && !Signed && !Unsigned && 9224 "Bad modifiers used with 'h'!"); 9225 Type = Context.HalfTy; 9226 break; 9227 case 'f': 9228 assert(HowLong == 0 && !Signed && !Unsigned && 9229 "Bad modifiers used with 'f'!"); 9230 Type = Context.FloatTy; 9231 break; 9232 case 'd': 9233 assert(HowLong < 3 && !Signed && !Unsigned && 9234 "Bad modifiers used with 'd'!"); 9235 if (HowLong == 1) 9236 Type = Context.LongDoubleTy; 9237 else if (HowLong == 2) 9238 Type = Context.Float128Ty; 9239 else 9240 Type = Context.DoubleTy; 9241 break; 9242 case 's': 9243 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 9244 if (Unsigned) 9245 Type = Context.UnsignedShortTy; 9246 else 9247 Type = Context.ShortTy; 9248 break; 9249 case 'i': 9250 if (HowLong == 3) 9251 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 9252 else if (HowLong == 2) 9253 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 9254 else if (HowLong == 1) 9255 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 9256 else 9257 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 9258 break; 9259 case 'c': 9260 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 9261 if (Signed) 9262 Type = Context.SignedCharTy; 9263 else if (Unsigned) 9264 Type = Context.UnsignedCharTy; 9265 else 9266 Type = Context.CharTy; 9267 break; 9268 case 'b': // boolean 9269 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 9270 Type = Context.BoolTy; 9271 break; 9272 case 'z': // size_t. 9273 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 9274 Type = Context.getSizeType(); 9275 break; 9276 case 'w': // wchar_t. 9277 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!"); 9278 Type = Context.getWideCharType(); 9279 break; 9280 case 'F': 9281 Type = Context.getCFConstantStringType(); 9282 break; 9283 case 'G': 9284 Type = Context.getObjCIdType(); 9285 break; 9286 case 'H': 9287 Type = Context.getObjCSelType(); 9288 break; 9289 case 'M': 9290 Type = Context.getObjCSuperType(); 9291 break; 9292 case 'a': 9293 Type = Context.getBuiltinVaListType(); 9294 assert(!Type.isNull() && "builtin va list type not initialized!"); 9295 break; 9296 case 'A': 9297 // This is a "reference" to a va_list; however, what exactly 9298 // this means depends on how va_list is defined. There are two 9299 // different kinds of va_list: ones passed by value, and ones 9300 // passed by reference. An example of a by-value va_list is 9301 // x86, where va_list is a char*. An example of by-ref va_list 9302 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 9303 // we want this argument to be a char*&; for x86-64, we want 9304 // it to be a __va_list_tag*. 9305 Type = Context.getBuiltinVaListType(); 9306 assert(!Type.isNull() && "builtin va list type not initialized!"); 9307 if (Type->isArrayType()) 9308 Type = Context.getArrayDecayedType(Type); 9309 else 9310 Type = Context.getLValueReferenceType(Type); 9311 break; 9312 case 'V': { 9313 char *End; 9314 unsigned NumElements = strtoul(Str, &End, 10); 9315 assert(End != Str && "Missing vector size"); 9316 Str = End; 9317 9318 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 9319 RequiresICE, false); 9320 assert(!RequiresICE && "Can't require vector ICE"); 9321 9322 // TODO: No way to make AltiVec vectors in builtins yet. 9323 Type = Context.getVectorType(ElementType, NumElements, 9324 VectorType::GenericVector); 9325 break; 9326 } 9327 case 'E': { 9328 char *End; 9329 9330 unsigned NumElements = strtoul(Str, &End, 10); 9331 assert(End != Str && "Missing vector size"); 9332 9333 Str = End; 9334 9335 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 9336 false); 9337 Type = Context.getExtVectorType(ElementType, NumElements); 9338 break; 9339 } 9340 case 'X': { 9341 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 9342 false); 9343 assert(!RequiresICE && "Can't require complex ICE"); 9344 Type = Context.getComplexType(ElementType); 9345 break; 9346 } 9347 case 'Y': 9348 Type = Context.getPointerDiffType(); 9349 break; 9350 case 'P': 9351 Type = Context.getFILEType(); 9352 if (Type.isNull()) { 9353 Error = ASTContext::GE_Missing_stdio; 9354 return {}; 9355 } 9356 break; 9357 case 'J': 9358 if (Signed) 9359 Type = Context.getsigjmp_bufType(); 9360 else 9361 Type = Context.getjmp_bufType(); 9362 9363 if (Type.isNull()) { 9364 Error = ASTContext::GE_Missing_setjmp; 9365 return {}; 9366 } 9367 break; 9368 case 'K': 9369 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 9370 Type = Context.getucontext_tType(); 9371 9372 if (Type.isNull()) { 9373 Error = ASTContext::GE_Missing_ucontext; 9374 return {}; 9375 } 9376 break; 9377 case 'p': 9378 Type = Context.getProcessIDType(); 9379 break; 9380 } 9381 9382 // If there are modifiers and if we're allowed to parse them, go for it. 9383 Done = !AllowTypeModifiers; 9384 while (!Done) { 9385 switch (char c = *Str++) { 9386 default: Done = true; --Str; break; 9387 case '*': 9388 case '&': { 9389 // Both pointers and references can have their pointee types 9390 // qualified with an address space. 9391 char *End; 9392 unsigned AddrSpace = strtoul(Str, &End, 10); 9393 if (End != Str) { 9394 // Note AddrSpace == 0 is not the same as an unspecified address space. 9395 Type = Context.getAddrSpaceQualType( 9396 Type, 9397 Context.getLangASForBuiltinAddressSpace(AddrSpace)); 9398 Str = End; 9399 } 9400 if (c == '*') 9401 Type = Context.getPointerType(Type); 9402 else 9403 Type = Context.getLValueReferenceType(Type); 9404 break; 9405 } 9406 // FIXME: There's no way to have a built-in with an rvalue ref arg. 9407 case 'C': 9408 Type = Type.withConst(); 9409 break; 9410 case 'D': 9411 Type = Context.getVolatileType(Type); 9412 break; 9413 case 'R': 9414 Type = Type.withRestrict(); 9415 break; 9416 } 9417 } 9418 9419 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 9420 "Integer constant 'I' type must be an integer"); 9421 9422 return Type; 9423 } 9424 9425 /// GetBuiltinType - Return the type for the specified builtin. 9426 QualType ASTContext::GetBuiltinType(unsigned Id, 9427 GetBuiltinTypeError &Error, 9428 unsigned *IntegerConstantArgs) const { 9429 const char *TypeStr = BuiltinInfo.getTypeString(Id); 9430 9431 SmallVector<QualType, 8> ArgTypes; 9432 9433 bool RequiresICE = false; 9434 Error = GE_None; 9435 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 9436 RequiresICE, true); 9437 if (Error != GE_None) 9438 return {}; 9439 9440 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 9441 9442 while (TypeStr[0] && TypeStr[0] != '.') { 9443 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 9444 if (Error != GE_None) 9445 return {}; 9446 9447 // If this argument is required to be an IntegerConstantExpression and the 9448 // caller cares, fill in the bitmask we return. 9449 if (RequiresICE && IntegerConstantArgs) 9450 *IntegerConstantArgs |= 1 << ArgTypes.size(); 9451 9452 // Do array -> pointer decay. The builtin should use the decayed type. 9453 if (Ty->isArrayType()) 9454 Ty = getArrayDecayedType(Ty); 9455 9456 ArgTypes.push_back(Ty); 9457 } 9458 9459 if (Id == Builtin::BI__GetExceptionInfo) 9460 return {}; 9461 9462 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 9463 "'.' should only occur at end of builtin type list!"); 9464 9465 FunctionType::ExtInfo EI(CC_C); 9466 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 9467 9468 bool Variadic = (TypeStr[0] == '.'); 9469 9470 // We really shouldn't be making a no-proto type here. 9471 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus) 9472 return getFunctionNoProtoType(ResType, EI); 9473 9474 FunctionProtoType::ExtProtoInfo EPI; 9475 EPI.ExtInfo = EI; 9476 EPI.Variadic = Variadic; 9477 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id)) 9478 EPI.ExceptionSpec.Type = 9479 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 9480 9481 return getFunctionType(ResType, ArgTypes, EPI); 9482 } 9483 9484 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 9485 const FunctionDecl *FD) { 9486 if (!FD->isExternallyVisible()) 9487 return GVA_Internal; 9488 9489 // Non-user-provided functions get emitted as weak definitions with every 9490 // use, no matter whether they've been explicitly instantiated etc. 9491 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 9492 if (!MD->isUserProvided()) 9493 return GVA_DiscardableODR; 9494 9495 GVALinkage External; 9496 switch (FD->getTemplateSpecializationKind()) { 9497 case TSK_Undeclared: 9498 case TSK_ExplicitSpecialization: 9499 External = GVA_StrongExternal; 9500 break; 9501 9502 case TSK_ExplicitInstantiationDefinition: 9503 return GVA_StrongODR; 9504 9505 // C++11 [temp.explicit]p10: 9506 // [ Note: The intent is that an inline function that is the subject of 9507 // an explicit instantiation declaration will still be implicitly 9508 // instantiated when used so that the body can be considered for 9509 // inlining, but that no out-of-line copy of the inline function would be 9510 // generated in the translation unit. -- end note ] 9511 case TSK_ExplicitInstantiationDeclaration: 9512 return GVA_AvailableExternally; 9513 9514 case TSK_ImplicitInstantiation: 9515 External = GVA_DiscardableODR; 9516 break; 9517 } 9518 9519 if (!FD->isInlined()) 9520 return External; 9521 9522 if ((!Context.getLangOpts().CPlusPlus && 9523 !Context.getTargetInfo().getCXXABI().isMicrosoft() && 9524 !FD->hasAttr<DLLExportAttr>()) || 9525 FD->hasAttr<GNUInlineAttr>()) { 9526 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 9527 9528 // GNU or C99 inline semantics. Determine whether this symbol should be 9529 // externally visible. 9530 if (FD->isInlineDefinitionExternallyVisible()) 9531 return External; 9532 9533 // C99 inline semantics, where the symbol is not externally visible. 9534 return GVA_AvailableExternally; 9535 } 9536 9537 // Functions specified with extern and inline in -fms-compatibility mode 9538 // forcibly get emitted. While the body of the function cannot be later 9539 // replaced, the function definition cannot be discarded. 9540 if (FD->isMSExternInline()) 9541 return GVA_StrongODR; 9542 9543 return GVA_DiscardableODR; 9544 } 9545 9546 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, 9547 const Decl *D, GVALinkage L) { 9548 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx 9549 // dllexport/dllimport on inline functions. 9550 if (D->hasAttr<DLLImportAttr>()) { 9551 if (L == GVA_DiscardableODR || L == GVA_StrongODR) 9552 return GVA_AvailableExternally; 9553 } else if (D->hasAttr<DLLExportAttr>()) { 9554 if (L == GVA_DiscardableODR) 9555 return GVA_StrongODR; 9556 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice && 9557 D->hasAttr<CUDAGlobalAttr>()) { 9558 // Device-side functions with __global__ attribute must always be 9559 // visible externally so they can be launched from host. 9560 if (L == GVA_DiscardableODR || L == GVA_Internal) 9561 return GVA_StrongODR; 9562 } 9563 return L; 9564 } 9565 9566 /// Adjust the GVALinkage for a declaration based on what an external AST source 9567 /// knows about whether there can be other definitions of this declaration. 9568 static GVALinkage 9569 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, 9570 GVALinkage L) { 9571 ExternalASTSource *Source = Ctx.getExternalSource(); 9572 if (!Source) 9573 return L; 9574 9575 switch (Source->hasExternalDefinitions(D)) { 9576 case ExternalASTSource::EK_Never: 9577 // Other translation units rely on us to provide the definition. 9578 if (L == GVA_DiscardableODR) 9579 return GVA_StrongODR; 9580 break; 9581 9582 case ExternalASTSource::EK_Always: 9583 return GVA_AvailableExternally; 9584 9585 case ExternalASTSource::EK_ReplyHazy: 9586 break; 9587 } 9588 return L; 9589 } 9590 9591 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { 9592 return adjustGVALinkageForExternalDefinitionKind(*this, FD, 9593 adjustGVALinkageForAttributes(*this, FD, 9594 basicGVALinkageForFunction(*this, FD))); 9595 } 9596 9597 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, 9598 const VarDecl *VD) { 9599 if (!VD->isExternallyVisible()) 9600 return GVA_Internal; 9601 9602 if (VD->isStaticLocal()) { 9603 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); 9604 while (LexicalContext && !isa<FunctionDecl>(LexicalContext)) 9605 LexicalContext = LexicalContext->getLexicalParent(); 9606 9607 // ObjC Blocks can create local variables that don't have a FunctionDecl 9608 // LexicalContext. 9609 if (!LexicalContext) 9610 return GVA_DiscardableODR; 9611 9612 // Otherwise, let the static local variable inherit its linkage from the 9613 // nearest enclosing function. 9614 auto StaticLocalLinkage = 9615 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext)); 9616 9617 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must 9618 // be emitted in any object with references to the symbol for the object it 9619 // contains, whether inline or out-of-line." 9620 // Similar behavior is observed with MSVC. An alternative ABI could use 9621 // StrongODR/AvailableExternally to match the function, but none are 9622 // known/supported currently. 9623 if (StaticLocalLinkage == GVA_StrongODR || 9624 StaticLocalLinkage == GVA_AvailableExternally) 9625 return GVA_DiscardableODR; 9626 return StaticLocalLinkage; 9627 } 9628 9629 // MSVC treats in-class initialized static data members as definitions. 9630 // By giving them non-strong linkage, out-of-line definitions won't 9631 // cause link errors. 9632 if (Context.isMSStaticDataMemberInlineDefinition(VD)) 9633 return GVA_DiscardableODR; 9634 9635 // Most non-template variables have strong linkage; inline variables are 9636 // linkonce_odr or (occasionally, for compatibility) weak_odr. 9637 GVALinkage StrongLinkage; 9638 switch (Context.getInlineVariableDefinitionKind(VD)) { 9639 case ASTContext::InlineVariableDefinitionKind::None: 9640 StrongLinkage = GVA_StrongExternal; 9641 break; 9642 case ASTContext::InlineVariableDefinitionKind::Weak: 9643 case ASTContext::InlineVariableDefinitionKind::WeakUnknown: 9644 StrongLinkage = GVA_DiscardableODR; 9645 break; 9646 case ASTContext::InlineVariableDefinitionKind::Strong: 9647 StrongLinkage = GVA_StrongODR; 9648 break; 9649 } 9650 9651 switch (VD->getTemplateSpecializationKind()) { 9652 case TSK_Undeclared: 9653 return StrongLinkage; 9654 9655 case TSK_ExplicitSpecialization: 9656 return Context.getTargetInfo().getCXXABI().isMicrosoft() && 9657 VD->isStaticDataMember() 9658 ? GVA_StrongODR 9659 : StrongLinkage; 9660 9661 case TSK_ExplicitInstantiationDefinition: 9662 return GVA_StrongODR; 9663 9664 case TSK_ExplicitInstantiationDeclaration: 9665 return GVA_AvailableExternally; 9666 9667 case TSK_ImplicitInstantiation: 9668 return GVA_DiscardableODR; 9669 } 9670 9671 llvm_unreachable("Invalid Linkage!"); 9672 } 9673 9674 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 9675 return adjustGVALinkageForExternalDefinitionKind(*this, VD, 9676 adjustGVALinkageForAttributes(*this, VD, 9677 basicGVALinkageForVariable(*this, VD))); 9678 } 9679 9680 bool ASTContext::DeclMustBeEmitted(const Decl *D) { 9681 if (const auto *VD = dyn_cast<VarDecl>(D)) { 9682 if (!VD->isFileVarDecl()) 9683 return false; 9684 // Global named register variables (GNU extension) are never emitted. 9685 if (VD->getStorageClass() == SC_Register) 9686 return false; 9687 if (VD->getDescribedVarTemplate() || 9688 isa<VarTemplatePartialSpecializationDecl>(VD)) 9689 return false; 9690 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 9691 // We never need to emit an uninstantiated function template. 9692 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 9693 return false; 9694 } else if (isa<PragmaCommentDecl>(D)) 9695 return true; 9696 else if (isa<OMPThreadPrivateDecl>(D)) 9697 return true; 9698 else if (isa<PragmaDetectMismatchDecl>(D)) 9699 return true; 9700 else if (isa<OMPThreadPrivateDecl>(D)) 9701 return !D->getDeclContext()->isDependentContext(); 9702 else if (isa<OMPDeclareReductionDecl>(D)) 9703 return !D->getDeclContext()->isDependentContext(); 9704 else if (isa<ImportDecl>(D)) 9705 return true; 9706 else 9707 return false; 9708 9709 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) { 9710 assert(getExternalSource() && "It's from an AST file; must have a source."); 9711 // On Windows, PCH files are built together with an object file. If this 9712 // declaration comes from such a PCH and DeclMustBeEmitted would return 9713 // true, it would have returned true and the decl would have been emitted 9714 // into that object file, so it doesn't need to be emitted here. 9715 // Note that decls are still emitted if they're referenced, as usual; 9716 // DeclMustBeEmitted is used to decide whether a decl must be emitted even 9717 // if it's not referenced. 9718 // 9719 // Explicit template instantiation definitions are tricky. If there was an 9720 // explicit template instantiation decl in the PCH before, it will look like 9721 // the definition comes from there, even if that was just the declaration. 9722 // (Explicit instantiation defs of variable templates always get emitted.) 9723 bool IsExpInstDef = 9724 isa<FunctionDecl>(D) && 9725 cast<FunctionDecl>(D)->getTemplateSpecializationKind() == 9726 TSK_ExplicitInstantiationDefinition; 9727 9728 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef) 9729 return false; 9730 } 9731 9732 // If this is a member of a class template, we do not need to emit it. 9733 if (D->getDeclContext()->isDependentContext()) 9734 return false; 9735 9736 // Weak references don't produce any output by themselves. 9737 if (D->hasAttr<WeakRefAttr>()) 9738 return false; 9739 9740 // Aliases and used decls are required. 9741 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 9742 return true; 9743 9744 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 9745 // Forward declarations aren't required. 9746 if (!FD->doesThisDeclarationHaveABody()) 9747 return FD->doesDeclarationForceExternallyVisibleDefinition(); 9748 9749 // Constructors and destructors are required. 9750 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 9751 return true; 9752 9753 // The key function for a class is required. This rule only comes 9754 // into play when inline functions can be key functions, though. 9755 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 9756 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 9757 const CXXRecordDecl *RD = MD->getParent(); 9758 if (MD->isOutOfLine() && RD->isDynamicClass()) { 9759 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); 9760 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 9761 return true; 9762 } 9763 } 9764 } 9765 9766 GVALinkage Linkage = GetGVALinkageForFunction(FD); 9767 9768 // static, static inline, always_inline, and extern inline functions can 9769 // always be deferred. Normal inline functions can be deferred in C99/C++. 9770 // Implicit template instantiations can also be deferred in C++. 9771 return !isDiscardableGVALinkage(Linkage); 9772 } 9773 9774 const auto *VD = cast<VarDecl>(D); 9775 assert(VD->isFileVarDecl() && "Expected file scoped var"); 9776 9777 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly && 9778 !isMSStaticDataMemberInlineDefinition(VD)) 9779 return false; 9780 9781 // Variables that can be needed in other TUs are required. 9782 auto Linkage = GetGVALinkageForVariable(VD); 9783 if (!isDiscardableGVALinkage(Linkage)) 9784 return true; 9785 9786 // We never need to emit a variable that is available in another TU. 9787 if (Linkage == GVA_AvailableExternally) 9788 return false; 9789 9790 // Variables that have destruction with side-effects are required. 9791 if (VD->getType().isDestructedType()) 9792 return true; 9793 9794 // Variables that have initialization with side-effects are required. 9795 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) && 9796 // We can get a value-dependent initializer during error recovery. 9797 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 9798 return true; 9799 9800 // Likewise, variables with tuple-like bindings are required if their 9801 // bindings have side-effects. 9802 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) 9803 for (const auto *BD : DD->bindings()) 9804 if (const auto *BindingVD = BD->getHoldingVar()) 9805 if (DeclMustBeEmitted(BindingVD)) 9806 return true; 9807 9808 // If the decl is marked as `declare target`, it should be emitted. 9809 for (const auto *Decl : D->redecls()) { 9810 if (!Decl->hasAttrs()) 9811 continue; 9812 if (const auto *Attr = Decl->getAttr<OMPDeclareTargetDeclAttr>()) 9813 if (Attr->getMapType() != OMPDeclareTargetDeclAttr::MT_Link) 9814 return true; 9815 } 9816 9817 return false; 9818 } 9819 9820 void ASTContext::forEachMultiversionedFunctionVersion( 9821 const FunctionDecl *FD, 9822 llvm::function_ref<void(const FunctionDecl *)> Pred) const { 9823 assert(FD->isMultiVersion() && "Only valid for multiversioned functions"); 9824 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls; 9825 FD = FD->getCanonicalDecl(); 9826 for (auto *CurDecl : 9827 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) { 9828 FunctionDecl *CurFD = CurDecl->getAsFunction()->getCanonicalDecl(); 9829 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) && 9830 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) { 9831 SeenDecls.insert(CurFD); 9832 Pred(CurFD); 9833 } 9834 } 9835 } 9836 9837 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic, 9838 bool IsCXXMethod) const { 9839 // Pass through to the C++ ABI object 9840 if (IsCXXMethod) 9841 return ABI->getDefaultMethodCallConv(IsVariadic); 9842 9843 switch (LangOpts.getDefaultCallingConv()) { 9844 case LangOptions::DCC_None: 9845 break; 9846 case LangOptions::DCC_CDecl: 9847 return CC_C; 9848 case LangOptions::DCC_FastCall: 9849 if (getTargetInfo().hasFeature("sse2") && !IsVariadic) 9850 return CC_X86FastCall; 9851 break; 9852 case LangOptions::DCC_StdCall: 9853 if (!IsVariadic) 9854 return CC_X86StdCall; 9855 break; 9856 case LangOptions::DCC_VectorCall: 9857 // __vectorcall cannot be applied to variadic functions. 9858 if (!IsVariadic) 9859 return CC_X86VectorCall; 9860 break; 9861 case LangOptions::DCC_RegCall: 9862 // __regcall cannot be applied to variadic functions. 9863 if (!IsVariadic) 9864 return CC_X86RegCall; 9865 break; 9866 } 9867 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown); 9868 } 9869 9870 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 9871 // Pass through to the C++ ABI object 9872 return ABI->isNearlyEmpty(RD); 9873 } 9874 9875 VTableContextBase *ASTContext::getVTableContext() { 9876 if (!VTContext.get()) { 9877 if (Target->getCXXABI().isMicrosoft()) 9878 VTContext.reset(new MicrosoftVTableContext(*this)); 9879 else 9880 VTContext.reset(new ItaniumVTableContext(*this)); 9881 } 9882 return VTContext.get(); 9883 } 9884 9885 MangleContext *ASTContext::createMangleContext() { 9886 switch (Target->getCXXABI().getKind()) { 9887 case TargetCXXABI::GenericAArch64: 9888 case TargetCXXABI::GenericItanium: 9889 case TargetCXXABI::GenericARM: 9890 case TargetCXXABI::GenericMIPS: 9891 case TargetCXXABI::iOS: 9892 case TargetCXXABI::iOS64: 9893 case TargetCXXABI::WebAssembly: 9894 case TargetCXXABI::WatchOS: 9895 return ItaniumMangleContext::create(*this, getDiagnostics()); 9896 case TargetCXXABI::Microsoft: 9897 return MicrosoftMangleContext::create(*this, getDiagnostics()); 9898 } 9899 llvm_unreachable("Unsupported ABI"); 9900 } 9901 9902 CXXABI::~CXXABI() = default; 9903 9904 size_t ASTContext::getSideTableAllocatedMemory() const { 9905 return ASTRecordLayouts.getMemorySize() + 9906 llvm::capacity_in_bytes(ObjCLayouts) + 9907 llvm::capacity_in_bytes(KeyFunctions) + 9908 llvm::capacity_in_bytes(ObjCImpls) + 9909 llvm::capacity_in_bytes(BlockVarCopyInits) + 9910 llvm::capacity_in_bytes(DeclAttrs) + 9911 llvm::capacity_in_bytes(TemplateOrInstantiation) + 9912 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) + 9913 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) + 9914 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) + 9915 llvm::capacity_in_bytes(OverriddenMethods) + 9916 llvm::capacity_in_bytes(Types) + 9917 llvm::capacity_in_bytes(VariableArrayTypes) + 9918 llvm::capacity_in_bytes(ClassScopeSpecializationPattern); 9919 } 9920 9921 /// getIntTypeForBitwidth - 9922 /// sets integer QualTy according to specified details: 9923 /// bitwidth, signed/unsigned. 9924 /// Returns empty type if there is no appropriate target types. 9925 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth, 9926 unsigned Signed) const { 9927 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed); 9928 CanQualType QualTy = getFromTargetType(Ty); 9929 if (!QualTy && DestWidth == 128) 9930 return Signed ? Int128Ty : UnsignedInt128Ty; 9931 return QualTy; 9932 } 9933 9934 /// getRealTypeForBitwidth - 9935 /// sets floating point QualTy according to specified bitwidth. 9936 /// Returns empty type if there is no appropriate target types. 9937 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const { 9938 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth); 9939 switch (Ty) { 9940 case TargetInfo::Float: 9941 return FloatTy; 9942 case TargetInfo::Double: 9943 return DoubleTy; 9944 case TargetInfo::LongDouble: 9945 return LongDoubleTy; 9946 case TargetInfo::Float128: 9947 return Float128Ty; 9948 case TargetInfo::NoFloat: 9949 return {}; 9950 } 9951 9952 llvm_unreachable("Unhandled TargetInfo::RealType value"); 9953 } 9954 9955 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { 9956 if (Number > 1) 9957 MangleNumbers[ND] = Number; 9958 } 9959 9960 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const { 9961 auto I = MangleNumbers.find(ND); 9962 return I != MangleNumbers.end() ? I->second : 1; 9963 } 9964 9965 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { 9966 if (Number > 1) 9967 StaticLocalNumbers[VD] = Number; 9968 } 9969 9970 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { 9971 auto I = StaticLocalNumbers.find(VD); 9972 return I != StaticLocalNumbers.end() ? I->second : 1; 9973 } 9974 9975 MangleNumberingContext & 9976 ASTContext::getManglingNumberContext(const DeclContext *DC) { 9977 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 9978 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC]; 9979 if (!MCtx) 9980 MCtx = createMangleNumberingContext(); 9981 return *MCtx; 9982 } 9983 9984 std::unique_ptr<MangleNumberingContext> 9985 ASTContext::createMangleNumberingContext() const { 9986 return ABI->createMangleNumberingContext(); 9987 } 9988 9989 const CXXConstructorDecl * 9990 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) { 9991 return ABI->getCopyConstructorForExceptionObject( 9992 cast<CXXRecordDecl>(RD->getFirstDecl())); 9993 } 9994 9995 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD, 9996 CXXConstructorDecl *CD) { 9997 return ABI->addCopyConstructorForExceptionObject( 9998 cast<CXXRecordDecl>(RD->getFirstDecl()), 9999 cast<CXXConstructorDecl>(CD->getFirstDecl())); 10000 } 10001 10002 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD, 10003 TypedefNameDecl *DD) { 10004 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD); 10005 } 10006 10007 TypedefNameDecl * 10008 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) { 10009 return ABI->getTypedefNameForUnnamedTagDecl(TD); 10010 } 10011 10012 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD, 10013 DeclaratorDecl *DD) { 10014 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD); 10015 } 10016 10017 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) { 10018 return ABI->getDeclaratorForUnnamedTagDecl(TD); 10019 } 10020 10021 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 10022 ParamIndices[D] = index; 10023 } 10024 10025 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 10026 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 10027 assert(I != ParamIndices.end() && 10028 "ParmIndices lacks entry set by ParmVarDecl"); 10029 return I->second; 10030 } 10031 10032 APValue * 10033 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E, 10034 bool MayCreate) { 10035 assert(E && E->getStorageDuration() == SD_Static && 10036 "don't need to cache the computed value for this temporary"); 10037 if (MayCreate) { 10038 APValue *&MTVI = MaterializedTemporaryValues[E]; 10039 if (!MTVI) 10040 MTVI = new (*this) APValue; 10041 return MTVI; 10042 } 10043 10044 return MaterializedTemporaryValues.lookup(E); 10045 } 10046 10047 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { 10048 const llvm::Triple &T = getTargetInfo().getTriple(); 10049 if (!T.isOSDarwin()) 10050 return false; 10051 10052 if (!(T.isiOS() && T.isOSVersionLT(7)) && 10053 !(T.isMacOSX() && T.isOSVersionLT(10, 9))) 10054 return false; 10055 10056 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 10057 CharUnits sizeChars = getTypeSizeInChars(AtomicTy); 10058 uint64_t Size = sizeChars.getQuantity(); 10059 CharUnits alignChars = getTypeAlignInChars(AtomicTy); 10060 unsigned Align = alignChars.getQuantity(); 10061 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth(); 10062 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); 10063 } 10064 10065 static ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap( 10066 ASTContext::ParentMapPointers::mapped_type U) { 10067 if (const auto *D = U.dyn_cast<const Decl *>()) 10068 return ast_type_traits::DynTypedNode::create(*D); 10069 if (const auto *S = U.dyn_cast<const Stmt *>()) 10070 return ast_type_traits::DynTypedNode::create(*S); 10071 return *U.get<ast_type_traits::DynTypedNode *>(); 10072 } 10073 10074 namespace { 10075 10076 /// Template specializations to abstract away from pointers and TypeLocs. 10077 /// @{ 10078 template <typename T> 10079 ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) { 10080 return ast_type_traits::DynTypedNode::create(*Node); 10081 } 10082 template <> 10083 ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) { 10084 return ast_type_traits::DynTypedNode::create(Node); 10085 } 10086 template <> 10087 ast_type_traits::DynTypedNode 10088 createDynTypedNode(const NestedNameSpecifierLoc &Node) { 10089 return ast_type_traits::DynTypedNode::create(Node); 10090 } 10091 /// @} 10092 10093 /// A \c RecursiveASTVisitor that builds a map from nodes to their 10094 /// parents as defined by the \c RecursiveASTVisitor. 10095 /// 10096 /// Note that the relationship described here is purely in terms of AST 10097 /// traversal - there are other relationships (for example declaration context) 10098 /// in the AST that are better modeled by special matchers. 10099 /// 10100 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes. 10101 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> { 10102 public: 10103 /// Builds and returns the translation unit's parent map. 10104 /// 10105 /// The caller takes ownership of the returned \c ParentMap. 10106 static std::pair<ASTContext::ParentMapPointers *, 10107 ASTContext::ParentMapOtherNodes *> 10108 buildMap(TranslationUnitDecl &TU) { 10109 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers, 10110 new ASTContext::ParentMapOtherNodes); 10111 Visitor.TraverseDecl(&TU); 10112 return std::make_pair(Visitor.Parents, Visitor.OtherParents); 10113 } 10114 10115 private: 10116 friend class RecursiveASTVisitor<ParentMapASTVisitor>; 10117 10118 using VisitorBase = RecursiveASTVisitor<ParentMapASTVisitor>; 10119 10120 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents, 10121 ASTContext::ParentMapOtherNodes *OtherParents) 10122 : Parents(Parents), OtherParents(OtherParents) {} 10123 10124 bool shouldVisitTemplateInstantiations() const { 10125 return true; 10126 } 10127 10128 bool shouldVisitImplicitCode() const { 10129 return true; 10130 } 10131 10132 template <typename T, typename MapNodeTy, typename BaseTraverseFn, 10133 typename MapTy> 10134 bool TraverseNode(T Node, MapNodeTy MapNode, 10135 BaseTraverseFn BaseTraverse, MapTy *Parents) { 10136 if (!Node) 10137 return true; 10138 if (ParentStack.size() > 0) { 10139 // FIXME: Currently we add the same parent multiple times, but only 10140 // when no memoization data is available for the type. 10141 // For example when we visit all subexpressions of template 10142 // instantiations; this is suboptimal, but benign: the only way to 10143 // visit those is with hasAncestor / hasParent, and those do not create 10144 // new matches. 10145 // The plan is to enable DynTypedNode to be storable in a map or hash 10146 // map. The main problem there is to implement hash functions / 10147 // comparison operators for all types that DynTypedNode supports that 10148 // do not have pointer identity. 10149 auto &NodeOrVector = (*Parents)[MapNode]; 10150 if (NodeOrVector.isNull()) { 10151 if (const auto *D = ParentStack.back().get<Decl>()) 10152 NodeOrVector = D; 10153 else if (const auto *S = ParentStack.back().get<Stmt>()) 10154 NodeOrVector = S; 10155 else 10156 NodeOrVector = 10157 new ast_type_traits::DynTypedNode(ParentStack.back()); 10158 } else { 10159 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) { 10160 auto *Vector = new ASTContext::ParentVector( 10161 1, getSingleDynTypedNodeFromParentMap(NodeOrVector)); 10162 delete NodeOrVector 10163 .template dyn_cast<ast_type_traits::DynTypedNode *>(); 10164 NodeOrVector = Vector; 10165 } 10166 10167 auto *Vector = 10168 NodeOrVector.template get<ASTContext::ParentVector *>(); 10169 // Skip duplicates for types that have memoization data. 10170 // We must check that the type has memoization data before calling 10171 // std::find() because DynTypedNode::operator== can't compare all 10172 // types. 10173 bool Found = ParentStack.back().getMemoizationData() && 10174 std::find(Vector->begin(), Vector->end(), 10175 ParentStack.back()) != Vector->end(); 10176 if (!Found) 10177 Vector->push_back(ParentStack.back()); 10178 } 10179 } 10180 ParentStack.push_back(createDynTypedNode(Node)); 10181 bool Result = BaseTraverse(); 10182 ParentStack.pop_back(); 10183 return Result; 10184 } 10185 10186 bool TraverseDecl(Decl *DeclNode) { 10187 return TraverseNode(DeclNode, DeclNode, 10188 [&] { return VisitorBase::TraverseDecl(DeclNode); }, 10189 Parents); 10190 } 10191 10192 bool TraverseStmt(Stmt *StmtNode) { 10193 return TraverseNode(StmtNode, StmtNode, 10194 [&] { return VisitorBase::TraverseStmt(StmtNode); }, 10195 Parents); 10196 } 10197 10198 bool TraverseTypeLoc(TypeLoc TypeLocNode) { 10199 return TraverseNode( 10200 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode), 10201 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); }, 10202 OtherParents); 10203 } 10204 10205 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) { 10206 return TraverseNode( 10207 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode), 10208 [&] { 10209 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); 10210 }, 10211 OtherParents); 10212 } 10213 10214 ASTContext::ParentMapPointers *Parents; 10215 ASTContext::ParentMapOtherNodes *OtherParents; 10216 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack; 10217 }; 10218 10219 } // namespace 10220 10221 template <typename NodeTy, typename MapTy> 10222 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node, 10223 const MapTy &Map) { 10224 auto I = Map.find(Node); 10225 if (I == Map.end()) { 10226 return llvm::ArrayRef<ast_type_traits::DynTypedNode>(); 10227 } 10228 if (const auto *V = 10229 I->second.template dyn_cast<ASTContext::ParentVector *>()) { 10230 return llvm::makeArrayRef(*V); 10231 } 10232 return getSingleDynTypedNodeFromParentMap(I->second); 10233 } 10234 10235 ASTContext::DynTypedNodeList 10236 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) { 10237 if (!PointerParents) { 10238 // We always need to run over the whole translation unit, as 10239 // hasAncestor can escape any subtree. 10240 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()); 10241 PointerParents.reset(Maps.first); 10242 OtherParents.reset(Maps.second); 10243 } 10244 if (Node.getNodeKind().hasPointerIdentity()) 10245 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents); 10246 return getDynNodeFromMap(Node, *OtherParents); 10247 } 10248 10249 bool 10250 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, 10251 const ObjCMethodDecl *MethodImpl) { 10252 // No point trying to match an unavailable/deprecated mothod. 10253 if (MethodDecl->hasAttr<UnavailableAttr>() 10254 || MethodDecl->hasAttr<DeprecatedAttr>()) 10255 return false; 10256 if (MethodDecl->getObjCDeclQualifier() != 10257 MethodImpl->getObjCDeclQualifier()) 10258 return false; 10259 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) 10260 return false; 10261 10262 if (MethodDecl->param_size() != MethodImpl->param_size()) 10263 return false; 10264 10265 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), 10266 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), 10267 EF = MethodDecl->param_end(); 10268 IM != EM && IF != EF; ++IM, ++IF) { 10269 const ParmVarDecl *DeclVar = (*IF); 10270 const ParmVarDecl *ImplVar = (*IM); 10271 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) 10272 return false; 10273 if (!hasSameType(DeclVar->getType(), ImplVar->getType())) 10274 return false; 10275 } 10276 10277 return (MethodDecl->isVariadic() == MethodImpl->isVariadic()); 10278 } 10279 10280 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const { 10281 LangAS AS; 10282 if (QT->getUnqualifiedDesugaredType()->isNullPtrType()) 10283 AS = LangAS::Default; 10284 else 10285 AS = QT->getPointeeType().getAddressSpace(); 10286 10287 return getTargetInfo().getNullPointerValue(AS); 10288 } 10289 10290 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const { 10291 if (isTargetAddressSpace(AS)) 10292 return toTargetAddressSpace(AS); 10293 else 10294 return (*AddrSpaceMap)[(unsigned)AS]; 10295 } 10296 10297 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const { 10298 assert(Ty->isFixedPointType()); 10299 10300 if (Ty->isSaturatedFixedPointType()) return Ty; 10301 10302 const auto &BT = Ty->getAs<BuiltinType>(); 10303 switch (BT->getKind()) { 10304 default: 10305 llvm_unreachable("Not a fixed point type!"); 10306 case BuiltinType::ShortAccum: 10307 return SatShortAccumTy; 10308 case BuiltinType::Accum: 10309 return SatAccumTy; 10310 case BuiltinType::LongAccum: 10311 return SatLongAccumTy; 10312 case BuiltinType::UShortAccum: 10313 return SatUnsignedShortAccumTy; 10314 case BuiltinType::UAccum: 10315 return SatUnsignedAccumTy; 10316 case BuiltinType::ULongAccum: 10317 return SatUnsignedLongAccumTy; 10318 case BuiltinType::ShortFract: 10319 return SatShortFractTy; 10320 case BuiltinType::Fract: 10321 return SatFractTy; 10322 case BuiltinType::LongFract: 10323 return SatLongFractTy; 10324 case BuiltinType::UShortFract: 10325 return SatUnsignedShortFractTy; 10326 case BuiltinType::UFract: 10327 return SatUnsignedFractTy; 10328 case BuiltinType::ULongFract: 10329 return SatUnsignedLongFractTy; 10330 } 10331 } 10332 10333 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const { 10334 if (LangOpts.OpenCL) 10335 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS); 10336 10337 if (LangOpts.CUDA) 10338 return getTargetInfo().getCUDABuiltinAddressSpace(AS); 10339 10340 return getLangASFromTargetAS(AS); 10341 } 10342 10343 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that 10344 // doesn't include ASTContext.h 10345 template 10346 clang::LazyGenerationalUpdatePtr< 10347 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType 10348 clang::LazyGenerationalUpdatePtr< 10349 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( 10350 const clang::ASTContext &Ctx, Decl *Value); 10351 10352 unsigned char ASTContext::getFixedPointScale(QualType Ty) const { 10353 assert(Ty->isFixedPointType()); 10354 10355 const auto *BT = Ty->getAs<BuiltinType>(); 10356 const TargetInfo &Target = getTargetInfo(); 10357 switch (BT->getKind()) { 10358 default: 10359 llvm_unreachable("Not a fixed point type!"); 10360 case BuiltinType::ShortAccum: 10361 case BuiltinType::SatShortAccum: 10362 return Target.getShortAccumScale(); 10363 case BuiltinType::Accum: 10364 case BuiltinType::SatAccum: 10365 return Target.getAccumScale(); 10366 case BuiltinType::LongAccum: 10367 case BuiltinType::SatLongAccum: 10368 return Target.getLongAccumScale(); 10369 case BuiltinType::UShortAccum: 10370 case BuiltinType::SatUShortAccum: 10371 return Target.getUnsignedShortAccumScale(); 10372 case BuiltinType::UAccum: 10373 case BuiltinType::SatUAccum: 10374 return Target.getUnsignedAccumScale(); 10375 case BuiltinType::ULongAccum: 10376 case BuiltinType::SatULongAccum: 10377 return Target.getUnsignedLongAccumScale(); 10378 case BuiltinType::ShortFract: 10379 case BuiltinType::SatShortFract: 10380 return Target.getShortFractScale(); 10381 case BuiltinType::Fract: 10382 case BuiltinType::SatFract: 10383 return Target.getFractScale(); 10384 case BuiltinType::LongFract: 10385 case BuiltinType::SatLongFract: 10386 return Target.getLongFractScale(); 10387 case BuiltinType::UShortFract: 10388 case BuiltinType::SatUShortFract: 10389 return Target.getUnsignedShortFractScale(); 10390 case BuiltinType::UFract: 10391 case BuiltinType::SatUFract: 10392 return Target.getUnsignedFractScale(); 10393 case BuiltinType::ULongFract: 10394 case BuiltinType::SatULongFract: 10395 return Target.getUnsignedLongFractScale(); 10396 } 10397 } 10398 10399 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const { 10400 assert(Ty->isFixedPointType()); 10401 10402 const auto *BT = Ty->getAs<BuiltinType>(); 10403 const TargetInfo &Target = getTargetInfo(); 10404 switch (BT->getKind()) { 10405 default: 10406 llvm_unreachable("Not a fixed point type!"); 10407 case BuiltinType::ShortAccum: 10408 case BuiltinType::SatShortAccum: 10409 return Target.getShortAccumIBits(); 10410 case BuiltinType::Accum: 10411 case BuiltinType::SatAccum: 10412 return Target.getAccumIBits(); 10413 case BuiltinType::LongAccum: 10414 case BuiltinType::SatLongAccum: 10415 return Target.getLongAccumIBits(); 10416 case BuiltinType::UShortAccum: 10417 case BuiltinType::SatUShortAccum: 10418 return Target.getUnsignedShortAccumIBits(); 10419 case BuiltinType::UAccum: 10420 case BuiltinType::SatUAccum: 10421 return Target.getUnsignedAccumIBits(); 10422 case BuiltinType::ULongAccum: 10423 case BuiltinType::SatULongAccum: 10424 return Target.getUnsignedLongAccumIBits(); 10425 case BuiltinType::ShortFract: 10426 case BuiltinType::SatShortFract: 10427 case BuiltinType::Fract: 10428 case BuiltinType::SatFract: 10429 case BuiltinType::LongFract: 10430 case BuiltinType::SatLongFract: 10431 case BuiltinType::UShortFract: 10432 case BuiltinType::SatUShortFract: 10433 case BuiltinType::UFract: 10434 case BuiltinType::SatUFract: 10435 case BuiltinType::ULongFract: 10436 case BuiltinType::SatULongFract: 10437 return 0; 10438 } 10439 } 10440 10441 FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const { 10442 assert(Ty->isFixedPointType()); 10443 bool isSigned = Ty->isSignedFixedPointType(); 10444 return FixedPointSemantics( 10445 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned, 10446 Ty->isSaturatedFixedPointType(), 10447 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding()); 10448 } 10449 10450 APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const { 10451 assert(Ty->isFixedPointType()); 10452 return APFixedPoint::getMax(getFixedPointSemantics(Ty)); 10453 } 10454 10455 APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const { 10456 assert(Ty->isFixedPointType()); 10457 return APFixedPoint::getMin(getFixedPointSemantics(Ty)); 10458 } 10459