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->getLocStart(); 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->getLocStart(); 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 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) { 2507 assert(VD && "Passed null params"); 2508 assert(VD->hasAttr<BlocksAttr>() && 2509 "getBlockVarCopyInits - not __block var"); 2510 llvm::DenseMap<const VarDecl*, Expr*>::iterator 2511 I = BlockVarCopyInits.find(VD); 2512 return (I != BlockVarCopyInits.end()) ? I->second : nullptr; 2513 } 2514 2515 /// Set the copy inialization expression of a block var decl. 2516 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) { 2517 assert(VD && Init && "Passed null params"); 2518 assert(VD->hasAttr<BlocksAttr>() && 2519 "setBlockVarCopyInits - not __block var"); 2520 BlockVarCopyInits[VD] = Init; 2521 } 2522 2523 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 2524 unsigned DataSize) const { 2525 if (!DataSize) 2526 DataSize = TypeLoc::getFullDataSizeForType(T); 2527 else 2528 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 2529 "incorrect data size provided to CreateTypeSourceInfo!"); 2530 2531 auto *TInfo = 2532 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 2533 new (TInfo) TypeSourceInfo(T); 2534 return TInfo; 2535 } 2536 2537 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 2538 SourceLocation L) const { 2539 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 2540 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 2541 return DI; 2542 } 2543 2544 const ASTRecordLayout & 2545 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 2546 return getObjCLayout(D, nullptr); 2547 } 2548 2549 const ASTRecordLayout & 2550 ASTContext::getASTObjCImplementationLayout( 2551 const ObjCImplementationDecl *D) const { 2552 return getObjCLayout(D->getClassInterface(), D); 2553 } 2554 2555 //===----------------------------------------------------------------------===// 2556 // Type creation/memoization methods 2557 //===----------------------------------------------------------------------===// 2558 2559 QualType 2560 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 2561 unsigned fastQuals = quals.getFastQualifiers(); 2562 quals.removeFastQualifiers(); 2563 2564 // Check if we've already instantiated this type. 2565 llvm::FoldingSetNodeID ID; 2566 ExtQuals::Profile(ID, baseType, quals); 2567 void *insertPos = nullptr; 2568 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 2569 assert(eq->getQualifiers() == quals); 2570 return QualType(eq, fastQuals); 2571 } 2572 2573 // If the base type is not canonical, make the appropriate canonical type. 2574 QualType canon; 2575 if (!baseType->isCanonicalUnqualified()) { 2576 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 2577 canonSplit.Quals.addConsistentQualifiers(quals); 2578 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 2579 2580 // Re-find the insert position. 2581 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 2582 } 2583 2584 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 2585 ExtQualNodes.InsertNode(eq, insertPos); 2586 return QualType(eq, fastQuals); 2587 } 2588 2589 QualType ASTContext::getAddrSpaceQualType(QualType T, 2590 LangAS AddressSpace) const { 2591 QualType CanT = getCanonicalType(T); 2592 if (CanT.getAddressSpace() == AddressSpace) 2593 return T; 2594 2595 // If we are composing extended qualifiers together, merge together 2596 // into one ExtQuals node. 2597 QualifierCollector Quals; 2598 const Type *TypeNode = Quals.strip(T); 2599 2600 // If this type already has an address space specified, it cannot get 2601 // another one. 2602 assert(!Quals.hasAddressSpace() && 2603 "Type cannot be in multiple addr spaces!"); 2604 Quals.addAddressSpace(AddressSpace); 2605 2606 return getExtQualType(TypeNode, Quals); 2607 } 2608 2609 QualType ASTContext::removeAddrSpaceQualType(QualType T) const { 2610 // If we are composing extended qualifiers together, merge together 2611 // into one ExtQuals node. 2612 QualifierCollector Quals; 2613 const Type *TypeNode = Quals.strip(T); 2614 2615 // If the qualifier doesn't have an address space just return it. 2616 if (!Quals.hasAddressSpace()) 2617 return T; 2618 2619 Quals.removeAddressSpace(); 2620 2621 // Removal of the address space can mean there are no longer any 2622 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts) 2623 // or required. 2624 if (Quals.hasNonFastQualifiers()) 2625 return getExtQualType(TypeNode, Quals); 2626 else 2627 return QualType(TypeNode, Quals.getFastQualifiers()); 2628 } 2629 2630 QualType ASTContext::getObjCGCQualType(QualType T, 2631 Qualifiers::GC GCAttr) const { 2632 QualType CanT = getCanonicalType(T); 2633 if (CanT.getObjCGCAttr() == GCAttr) 2634 return T; 2635 2636 if (const auto *ptr = T->getAs<PointerType>()) { 2637 QualType Pointee = ptr->getPointeeType(); 2638 if (Pointee->isAnyPointerType()) { 2639 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 2640 return getPointerType(ResultType); 2641 } 2642 } 2643 2644 // If we are composing extended qualifiers together, merge together 2645 // into one ExtQuals node. 2646 QualifierCollector Quals; 2647 const Type *TypeNode = Quals.strip(T); 2648 2649 // If this type already has an ObjCGC specified, it cannot get 2650 // another one. 2651 assert(!Quals.hasObjCGCAttr() && 2652 "Type cannot have multiple ObjCGCs!"); 2653 Quals.addObjCGCAttr(GCAttr); 2654 2655 return getExtQualType(TypeNode, Quals); 2656 } 2657 2658 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 2659 FunctionType::ExtInfo Info) { 2660 if (T->getExtInfo() == Info) 2661 return T; 2662 2663 QualType Result; 2664 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 2665 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info); 2666 } else { 2667 const auto *FPT = cast<FunctionProtoType>(T); 2668 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 2669 EPI.ExtInfo = Info; 2670 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI); 2671 } 2672 2673 return cast<FunctionType>(Result.getTypePtr()); 2674 } 2675 2676 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, 2677 QualType ResultType) { 2678 FD = FD->getMostRecentDecl(); 2679 while (true) { 2680 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 2681 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 2682 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI)); 2683 if (FunctionDecl *Next = FD->getPreviousDecl()) 2684 FD = Next; 2685 else 2686 break; 2687 } 2688 if (ASTMutationListener *L = getASTMutationListener()) 2689 L->DeducedReturnType(FD, ResultType); 2690 } 2691 2692 /// Get a function type and produce the equivalent function type with the 2693 /// specified exception specification. Type sugar that can be present on a 2694 /// declaration of a function with an exception specification is permitted 2695 /// and preserved. Other type sugar (for instance, typedefs) is not. 2696 QualType ASTContext::getFunctionTypeWithExceptionSpec( 2697 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) { 2698 // Might have some parens. 2699 if (const auto *PT = dyn_cast<ParenType>(Orig)) 2700 return getParenType( 2701 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI)); 2702 2703 // Might have a calling-convention attribute. 2704 if (const auto *AT = dyn_cast<AttributedType>(Orig)) 2705 return getAttributedType( 2706 AT->getAttrKind(), 2707 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI), 2708 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI)); 2709 2710 // Anything else must be a function type. Rebuild it with the new exception 2711 // specification. 2712 const auto *Proto = cast<FunctionProtoType>(Orig); 2713 return getFunctionType( 2714 Proto->getReturnType(), Proto->getParamTypes(), 2715 Proto->getExtProtoInfo().withExceptionSpec(ESI)); 2716 } 2717 2718 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T, 2719 QualType U) { 2720 return hasSameType(T, U) || 2721 (getLangOpts().CPlusPlus17 && 2722 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None), 2723 getFunctionTypeWithExceptionSpec(U, EST_None))); 2724 } 2725 2726 void ASTContext::adjustExceptionSpec( 2727 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, 2728 bool AsWritten) { 2729 // Update the type. 2730 QualType Updated = 2731 getFunctionTypeWithExceptionSpec(FD->getType(), ESI); 2732 FD->setType(Updated); 2733 2734 if (!AsWritten) 2735 return; 2736 2737 // Update the type in the type source information too. 2738 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) { 2739 // If the type and the type-as-written differ, we may need to update 2740 // the type-as-written too. 2741 if (TSInfo->getType() != FD->getType()) 2742 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI); 2743 2744 // FIXME: When we get proper type location information for exceptions, 2745 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch 2746 // up the TypeSourceInfo; 2747 assert(TypeLoc::getFullDataSizeForType(Updated) == 2748 TypeLoc::getFullDataSizeForType(TSInfo->getType()) && 2749 "TypeLoc size mismatch from updating exception specification"); 2750 TSInfo->overrideType(Updated); 2751 } 2752 } 2753 2754 /// getComplexType - Return the uniqued reference to the type for a complex 2755 /// number with the specified element type. 2756 QualType ASTContext::getComplexType(QualType T) const { 2757 // Unique pointers, to guarantee there is only one pointer of a particular 2758 // structure. 2759 llvm::FoldingSetNodeID ID; 2760 ComplexType::Profile(ID, T); 2761 2762 void *InsertPos = nullptr; 2763 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 2764 return QualType(CT, 0); 2765 2766 // If the pointee type isn't canonical, this won't be a canonical type either, 2767 // so fill in the canonical type field. 2768 QualType Canonical; 2769 if (!T.isCanonical()) { 2770 Canonical = getComplexType(getCanonicalType(T)); 2771 2772 // Get the new insert position for the node we care about. 2773 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 2774 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2775 } 2776 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 2777 Types.push_back(New); 2778 ComplexTypes.InsertNode(New, InsertPos); 2779 return QualType(New, 0); 2780 } 2781 2782 /// getPointerType - Return the uniqued reference to the type for a pointer to 2783 /// the specified type. 2784 QualType ASTContext::getPointerType(QualType T) const { 2785 // Unique pointers, to guarantee there is only one pointer of a particular 2786 // structure. 2787 llvm::FoldingSetNodeID ID; 2788 PointerType::Profile(ID, T); 2789 2790 void *InsertPos = nullptr; 2791 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2792 return QualType(PT, 0); 2793 2794 // If the pointee type isn't canonical, this won't be a canonical type either, 2795 // so fill in the canonical type field. 2796 QualType Canonical; 2797 if (!T.isCanonical()) { 2798 Canonical = getPointerType(getCanonicalType(T)); 2799 2800 // Get the new insert position for the node we care about. 2801 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2802 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2803 } 2804 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical); 2805 Types.push_back(New); 2806 PointerTypes.InsertNode(New, InsertPos); 2807 return QualType(New, 0); 2808 } 2809 2810 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const { 2811 llvm::FoldingSetNodeID ID; 2812 AdjustedType::Profile(ID, Orig, New); 2813 void *InsertPos = nullptr; 2814 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2815 if (AT) 2816 return QualType(AT, 0); 2817 2818 QualType Canonical = getCanonicalType(New); 2819 2820 // Get the new insert position for the node we care about. 2821 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2822 assert(!AT && "Shouldn't be in the map!"); 2823 2824 AT = new (*this, TypeAlignment) 2825 AdjustedType(Type::Adjusted, Orig, New, Canonical); 2826 Types.push_back(AT); 2827 AdjustedTypes.InsertNode(AT, InsertPos); 2828 return QualType(AT, 0); 2829 } 2830 2831 QualType ASTContext::getDecayedType(QualType T) const { 2832 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay"); 2833 2834 QualType Decayed; 2835 2836 // C99 6.7.5.3p7: 2837 // A declaration of a parameter as "array of type" shall be 2838 // adjusted to "qualified pointer to type", where the type 2839 // qualifiers (if any) are those specified within the [ and ] of 2840 // the array type derivation. 2841 if (T->isArrayType()) 2842 Decayed = getArrayDecayedType(T); 2843 2844 // C99 6.7.5.3p8: 2845 // A declaration of a parameter as "function returning type" 2846 // shall be adjusted to "pointer to function returning type", as 2847 // in 6.3.2.1. 2848 if (T->isFunctionType()) 2849 Decayed = getPointerType(T); 2850 2851 llvm::FoldingSetNodeID ID; 2852 AdjustedType::Profile(ID, T, Decayed); 2853 void *InsertPos = nullptr; 2854 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2855 if (AT) 2856 return QualType(AT, 0); 2857 2858 QualType Canonical = getCanonicalType(Decayed); 2859 2860 // Get the new insert position for the node we care about. 2861 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2862 assert(!AT && "Shouldn't be in the map!"); 2863 2864 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical); 2865 Types.push_back(AT); 2866 AdjustedTypes.InsertNode(AT, InsertPos); 2867 return QualType(AT, 0); 2868 } 2869 2870 /// getBlockPointerType - Return the uniqued reference to the type for 2871 /// a pointer to the specified block. 2872 QualType ASTContext::getBlockPointerType(QualType T) const { 2873 assert(T->isFunctionType() && "block of function types only"); 2874 // Unique pointers, to guarantee there is only one block of a particular 2875 // structure. 2876 llvm::FoldingSetNodeID ID; 2877 BlockPointerType::Profile(ID, T); 2878 2879 void *InsertPos = nullptr; 2880 if (BlockPointerType *PT = 2881 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2882 return QualType(PT, 0); 2883 2884 // If the block pointee type isn't canonical, this won't be a canonical 2885 // type either so fill in the canonical type field. 2886 QualType Canonical; 2887 if (!T.isCanonical()) { 2888 Canonical = getBlockPointerType(getCanonicalType(T)); 2889 2890 // Get the new insert position for the node we care about. 2891 BlockPointerType *NewIP = 2892 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2893 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2894 } 2895 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 2896 Types.push_back(New); 2897 BlockPointerTypes.InsertNode(New, InsertPos); 2898 return QualType(New, 0); 2899 } 2900 2901 /// getLValueReferenceType - Return the uniqued reference to the type for an 2902 /// lvalue reference to the specified type. 2903 QualType 2904 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 2905 assert(getCanonicalType(T) != OverloadTy && 2906 "Unresolved overloaded function type"); 2907 2908 // Unique pointers, to guarantee there is only one pointer of a particular 2909 // structure. 2910 llvm::FoldingSetNodeID ID; 2911 ReferenceType::Profile(ID, T, SpelledAsLValue); 2912 2913 void *InsertPos = nullptr; 2914 if (LValueReferenceType *RT = 2915 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 2916 return QualType(RT, 0); 2917 2918 const auto *InnerRef = T->getAs<ReferenceType>(); 2919 2920 // If the referencee type isn't canonical, this won't be a canonical type 2921 // either, so fill in the canonical type field. 2922 QualType Canonical; 2923 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 2924 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 2925 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 2926 2927 // Get the new insert position for the node we care about. 2928 LValueReferenceType *NewIP = 2929 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 2930 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2931 } 2932 2933 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 2934 SpelledAsLValue); 2935 Types.push_back(New); 2936 LValueReferenceTypes.InsertNode(New, InsertPos); 2937 2938 return QualType(New, 0); 2939 } 2940 2941 /// getRValueReferenceType - Return the uniqued reference to the type for an 2942 /// rvalue reference to the specified type. 2943 QualType ASTContext::getRValueReferenceType(QualType T) const { 2944 // Unique pointers, to guarantee there is only one pointer of a particular 2945 // structure. 2946 llvm::FoldingSetNodeID ID; 2947 ReferenceType::Profile(ID, T, false); 2948 2949 void *InsertPos = nullptr; 2950 if (RValueReferenceType *RT = 2951 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 2952 return QualType(RT, 0); 2953 2954 const auto *InnerRef = T->getAs<ReferenceType>(); 2955 2956 // If the referencee type isn't canonical, this won't be a canonical type 2957 // either, so fill in the canonical type field. 2958 QualType Canonical; 2959 if (InnerRef || !T.isCanonical()) { 2960 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 2961 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 2962 2963 // Get the new insert position for the node we care about. 2964 RValueReferenceType *NewIP = 2965 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 2966 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2967 } 2968 2969 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 2970 Types.push_back(New); 2971 RValueReferenceTypes.InsertNode(New, InsertPos); 2972 return QualType(New, 0); 2973 } 2974 2975 /// getMemberPointerType - Return the uniqued reference to the type for a 2976 /// member pointer to the specified type, in the specified class. 2977 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 2978 // Unique pointers, to guarantee there is only one pointer of a particular 2979 // structure. 2980 llvm::FoldingSetNodeID ID; 2981 MemberPointerType::Profile(ID, T, Cls); 2982 2983 void *InsertPos = nullptr; 2984 if (MemberPointerType *PT = 2985 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2986 return QualType(PT, 0); 2987 2988 // If the pointee or class type isn't canonical, this won't be a canonical 2989 // type either, so fill in the canonical type field. 2990 QualType Canonical; 2991 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 2992 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 2993 2994 // Get the new insert position for the node we care about. 2995 MemberPointerType *NewIP = 2996 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2997 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2998 } 2999 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 3000 Types.push_back(New); 3001 MemberPointerTypes.InsertNode(New, InsertPos); 3002 return QualType(New, 0); 3003 } 3004 3005 /// getConstantArrayType - Return the unique reference to the type for an 3006 /// array of the specified element type. 3007 QualType ASTContext::getConstantArrayType(QualType EltTy, 3008 const llvm::APInt &ArySizeIn, 3009 ArrayType::ArraySizeModifier ASM, 3010 unsigned IndexTypeQuals) const { 3011 assert((EltTy->isDependentType() || 3012 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 3013 "Constant array of VLAs is illegal!"); 3014 3015 // Convert the array size into a canonical width matching the pointer size for 3016 // the target. 3017 llvm::APInt ArySize(ArySizeIn); 3018 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth()); 3019 3020 llvm::FoldingSetNodeID ID; 3021 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals); 3022 3023 void *InsertPos = nullptr; 3024 if (ConstantArrayType *ATP = 3025 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 3026 return QualType(ATP, 0); 3027 3028 // If the element type isn't canonical or has qualifiers, this won't 3029 // be a canonical type either, so fill in the canonical type field. 3030 QualType Canon; 3031 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 3032 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3033 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, 3034 ASM, IndexTypeQuals); 3035 Canon = getQualifiedType(Canon, canonSplit.Quals); 3036 3037 // Get the new insert position for the node we care about. 3038 ConstantArrayType *NewIP = 3039 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 3040 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3041 } 3042 3043 auto *New = new (*this,TypeAlignment) 3044 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals); 3045 ConstantArrayTypes.InsertNode(New, InsertPos); 3046 Types.push_back(New); 3047 return QualType(New, 0); 3048 } 3049 3050 /// getVariableArrayDecayedType - Turns the given type, which may be 3051 /// variably-modified, into the corresponding type with all the known 3052 /// sizes replaced with [*]. 3053 QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 3054 // Vastly most common case. 3055 if (!type->isVariablyModifiedType()) return type; 3056 3057 QualType result; 3058 3059 SplitQualType split = type.getSplitDesugaredType(); 3060 const Type *ty = split.Ty; 3061 switch (ty->getTypeClass()) { 3062 #define TYPE(Class, Base) 3063 #define ABSTRACT_TYPE(Class, Base) 3064 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3065 #include "clang/AST/TypeNodes.def" 3066 llvm_unreachable("didn't desugar past all non-canonical types?"); 3067 3068 // These types should never be variably-modified. 3069 case Type::Builtin: 3070 case Type::Complex: 3071 case Type::Vector: 3072 case Type::DependentVector: 3073 case Type::ExtVector: 3074 case Type::DependentSizedExtVector: 3075 case Type::DependentAddressSpace: 3076 case Type::ObjCObject: 3077 case Type::ObjCInterface: 3078 case Type::ObjCObjectPointer: 3079 case Type::Record: 3080 case Type::Enum: 3081 case Type::UnresolvedUsing: 3082 case Type::TypeOfExpr: 3083 case Type::TypeOf: 3084 case Type::Decltype: 3085 case Type::UnaryTransform: 3086 case Type::DependentName: 3087 case Type::InjectedClassName: 3088 case Type::TemplateSpecialization: 3089 case Type::DependentTemplateSpecialization: 3090 case Type::TemplateTypeParm: 3091 case Type::SubstTemplateTypeParmPack: 3092 case Type::Auto: 3093 case Type::DeducedTemplateSpecialization: 3094 case Type::PackExpansion: 3095 llvm_unreachable("type should never be variably-modified"); 3096 3097 // These types can be variably-modified but should never need to 3098 // further decay. 3099 case Type::FunctionNoProto: 3100 case Type::FunctionProto: 3101 case Type::BlockPointer: 3102 case Type::MemberPointer: 3103 case Type::Pipe: 3104 return type; 3105 3106 // These types can be variably-modified. All these modifications 3107 // preserve structure except as noted by comments. 3108 // TODO: if we ever care about optimizing VLAs, there are no-op 3109 // optimizations available here. 3110 case Type::Pointer: 3111 result = getPointerType(getVariableArrayDecayedType( 3112 cast<PointerType>(ty)->getPointeeType())); 3113 break; 3114 3115 case Type::LValueReference: { 3116 const auto *lv = cast<LValueReferenceType>(ty); 3117 result = getLValueReferenceType( 3118 getVariableArrayDecayedType(lv->getPointeeType()), 3119 lv->isSpelledAsLValue()); 3120 break; 3121 } 3122 3123 case Type::RValueReference: { 3124 const auto *lv = cast<RValueReferenceType>(ty); 3125 result = getRValueReferenceType( 3126 getVariableArrayDecayedType(lv->getPointeeType())); 3127 break; 3128 } 3129 3130 case Type::Atomic: { 3131 const auto *at = cast<AtomicType>(ty); 3132 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 3133 break; 3134 } 3135 3136 case Type::ConstantArray: { 3137 const auto *cat = cast<ConstantArrayType>(ty); 3138 result = getConstantArrayType( 3139 getVariableArrayDecayedType(cat->getElementType()), 3140 cat->getSize(), 3141 cat->getSizeModifier(), 3142 cat->getIndexTypeCVRQualifiers()); 3143 break; 3144 } 3145 3146 case Type::DependentSizedArray: { 3147 const auto *dat = cast<DependentSizedArrayType>(ty); 3148 result = getDependentSizedArrayType( 3149 getVariableArrayDecayedType(dat->getElementType()), 3150 dat->getSizeExpr(), 3151 dat->getSizeModifier(), 3152 dat->getIndexTypeCVRQualifiers(), 3153 dat->getBracketsRange()); 3154 break; 3155 } 3156 3157 // Turn incomplete types into [*] types. 3158 case Type::IncompleteArray: { 3159 const auto *iat = cast<IncompleteArrayType>(ty); 3160 result = getVariableArrayType( 3161 getVariableArrayDecayedType(iat->getElementType()), 3162 /*size*/ nullptr, 3163 ArrayType::Normal, 3164 iat->getIndexTypeCVRQualifiers(), 3165 SourceRange()); 3166 break; 3167 } 3168 3169 // Turn VLA types into [*] types. 3170 case Type::VariableArray: { 3171 const auto *vat = cast<VariableArrayType>(ty); 3172 result = getVariableArrayType( 3173 getVariableArrayDecayedType(vat->getElementType()), 3174 /*size*/ nullptr, 3175 ArrayType::Star, 3176 vat->getIndexTypeCVRQualifiers(), 3177 vat->getBracketsRange()); 3178 break; 3179 } 3180 } 3181 3182 // Apply the top-level qualifiers from the original. 3183 return getQualifiedType(result, split.Quals); 3184 } 3185 3186 /// getVariableArrayType - Returns a non-unique reference to the type for a 3187 /// variable array of the specified element type. 3188 QualType ASTContext::getVariableArrayType(QualType EltTy, 3189 Expr *NumElts, 3190 ArrayType::ArraySizeModifier ASM, 3191 unsigned IndexTypeQuals, 3192 SourceRange Brackets) const { 3193 // Since we don't unique expressions, it isn't possible to unique VLA's 3194 // that have an expression provided for their size. 3195 QualType Canon; 3196 3197 // Be sure to pull qualifiers off the element type. 3198 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 3199 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 3200 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 3201 IndexTypeQuals, Brackets); 3202 Canon = getQualifiedType(Canon, canonSplit.Quals); 3203 } 3204 3205 auto *New = new (*this, TypeAlignment) 3206 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 3207 3208 VariableArrayTypes.push_back(New); 3209 Types.push_back(New); 3210 return QualType(New, 0); 3211 } 3212 3213 /// getDependentSizedArrayType - Returns a non-unique reference to 3214 /// the type for a dependently-sized array of the specified element 3215 /// type. 3216 QualType ASTContext::getDependentSizedArrayType(QualType elementType, 3217 Expr *numElements, 3218 ArrayType::ArraySizeModifier ASM, 3219 unsigned elementTypeQuals, 3220 SourceRange brackets) const { 3221 assert((!numElements || numElements->isTypeDependent() || 3222 numElements->isValueDependent()) && 3223 "Size must be type- or value-dependent!"); 3224 3225 // Dependently-sized array types that do not have a specified number 3226 // of elements will have their sizes deduced from a dependent 3227 // initializer. We do no canonicalization here at all, which is okay 3228 // because they can't be used in most locations. 3229 if (!numElements) { 3230 auto *newType 3231 = new (*this, TypeAlignment) 3232 DependentSizedArrayType(*this, elementType, QualType(), 3233 numElements, ASM, elementTypeQuals, 3234 brackets); 3235 Types.push_back(newType); 3236 return QualType(newType, 0); 3237 } 3238 3239 // Otherwise, we actually build a new type every time, but we 3240 // also build a canonical type. 3241 3242 SplitQualType canonElementType = getCanonicalType(elementType).split(); 3243 3244 void *insertPos = nullptr; 3245 llvm::FoldingSetNodeID ID; 3246 DependentSizedArrayType::Profile(ID, *this, 3247 QualType(canonElementType.Ty, 0), 3248 ASM, elementTypeQuals, numElements); 3249 3250 // Look for an existing type with these properties. 3251 DependentSizedArrayType *canonTy = 3252 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3253 3254 // If we don't have one, build one. 3255 if (!canonTy) { 3256 canonTy = new (*this, TypeAlignment) 3257 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 3258 QualType(), numElements, ASM, elementTypeQuals, 3259 brackets); 3260 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 3261 Types.push_back(canonTy); 3262 } 3263 3264 // Apply qualifiers from the element type to the array. 3265 QualType canon = getQualifiedType(QualType(canonTy,0), 3266 canonElementType.Quals); 3267 3268 // If we didn't need extra canonicalization for the element type or the size 3269 // expression, then just use that as our result. 3270 if (QualType(canonElementType.Ty, 0) == elementType && 3271 canonTy->getSizeExpr() == numElements) 3272 return canon; 3273 3274 // Otherwise, we need to build a type which follows the spelling 3275 // of the element type. 3276 auto *sugaredType 3277 = new (*this, TypeAlignment) 3278 DependentSizedArrayType(*this, elementType, canon, numElements, 3279 ASM, elementTypeQuals, brackets); 3280 Types.push_back(sugaredType); 3281 return QualType(sugaredType, 0); 3282 } 3283 3284 QualType ASTContext::getIncompleteArrayType(QualType elementType, 3285 ArrayType::ArraySizeModifier ASM, 3286 unsigned elementTypeQuals) const { 3287 llvm::FoldingSetNodeID ID; 3288 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 3289 3290 void *insertPos = nullptr; 3291 if (IncompleteArrayType *iat = 3292 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 3293 return QualType(iat, 0); 3294 3295 // If the element type isn't canonical, this won't be a canonical type 3296 // either, so fill in the canonical type field. We also have to pull 3297 // qualifiers off the element type. 3298 QualType canon; 3299 3300 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 3301 SplitQualType canonSplit = getCanonicalType(elementType).split(); 3302 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 3303 ASM, elementTypeQuals); 3304 canon = getQualifiedType(canon, canonSplit.Quals); 3305 3306 // Get the new insert position for the node we care about. 3307 IncompleteArrayType *existing = 3308 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 3309 assert(!existing && "Shouldn't be in the map!"); (void) existing; 3310 } 3311 3312 auto *newType = new (*this, TypeAlignment) 3313 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 3314 3315 IncompleteArrayTypes.InsertNode(newType, insertPos); 3316 Types.push_back(newType); 3317 return QualType(newType, 0); 3318 } 3319 3320 /// getVectorType - Return the unique reference to a vector type of 3321 /// the specified element type and size. VectorType must be a built-in type. 3322 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 3323 VectorType::VectorKind VecKind) const { 3324 assert(vecType->isBuiltinType()); 3325 3326 // Check if we've already instantiated a vector of this type. 3327 llvm::FoldingSetNodeID ID; 3328 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 3329 3330 void *InsertPos = nullptr; 3331 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 3332 return QualType(VTP, 0); 3333 3334 // If the element type isn't canonical, this won't be a canonical type either, 3335 // so fill in the canonical type field. 3336 QualType Canonical; 3337 if (!vecType.isCanonical()) { 3338 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 3339 3340 // Get the new insert position for the node we care about. 3341 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3342 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3343 } 3344 auto *New = new (*this, TypeAlignment) 3345 VectorType(vecType, NumElts, Canonical, VecKind); 3346 VectorTypes.InsertNode(New, InsertPos); 3347 Types.push_back(New); 3348 return QualType(New, 0); 3349 } 3350 3351 QualType 3352 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr, 3353 SourceLocation AttrLoc, 3354 VectorType::VectorKind VecKind) const { 3355 llvm::FoldingSetNodeID ID; 3356 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr, 3357 VecKind); 3358 void *InsertPos = nullptr; 3359 DependentVectorType *Canon = 3360 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3361 DependentVectorType *New; 3362 3363 if (Canon) { 3364 New = new (*this, TypeAlignment) DependentVectorType( 3365 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind); 3366 } else { 3367 QualType CanonVecTy = getCanonicalType(VecType); 3368 if (CanonVecTy == VecType) { 3369 New = new (*this, TypeAlignment) DependentVectorType( 3370 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind); 3371 3372 DependentVectorType *CanonCheck = 3373 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3374 assert(!CanonCheck && 3375 "Dependent-sized vector_size canonical type broken"); 3376 (void)CanonCheck; 3377 DependentVectorTypes.InsertNode(New, InsertPos); 3378 } else { 3379 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 3380 SourceLocation()); 3381 New = new (*this, TypeAlignment) DependentVectorType( 3382 *this, VecType, Canon, SizeExpr, AttrLoc, VecKind); 3383 } 3384 } 3385 3386 Types.push_back(New); 3387 return QualType(New, 0); 3388 } 3389 3390 /// getExtVectorType - Return the unique reference to an extended vector type of 3391 /// the specified element type and size. VectorType must be a built-in type. 3392 QualType 3393 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 3394 assert(vecType->isBuiltinType() || vecType->isDependentType()); 3395 3396 // Check if we've already instantiated a vector of this type. 3397 llvm::FoldingSetNodeID ID; 3398 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 3399 VectorType::GenericVector); 3400 void *InsertPos = nullptr; 3401 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 3402 return QualType(VTP, 0); 3403 3404 // If the element type isn't canonical, this won't be a canonical type either, 3405 // so fill in the canonical type field. 3406 QualType Canonical; 3407 if (!vecType.isCanonical()) { 3408 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 3409 3410 // Get the new insert position for the node we care about. 3411 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3412 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3413 } 3414 auto *New = new (*this, TypeAlignment) 3415 ExtVectorType(vecType, NumElts, Canonical); 3416 VectorTypes.InsertNode(New, InsertPos); 3417 Types.push_back(New); 3418 return QualType(New, 0); 3419 } 3420 3421 QualType 3422 ASTContext::getDependentSizedExtVectorType(QualType vecType, 3423 Expr *SizeExpr, 3424 SourceLocation AttrLoc) const { 3425 llvm::FoldingSetNodeID ID; 3426 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 3427 SizeExpr); 3428 3429 void *InsertPos = nullptr; 3430 DependentSizedExtVectorType *Canon 3431 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3432 DependentSizedExtVectorType *New; 3433 if (Canon) { 3434 // We already have a canonical version of this array type; use it as 3435 // the canonical type for a newly-built type. 3436 New = new (*this, TypeAlignment) 3437 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 3438 SizeExpr, AttrLoc); 3439 } else { 3440 QualType CanonVecTy = getCanonicalType(vecType); 3441 if (CanonVecTy == vecType) { 3442 New = new (*this, TypeAlignment) 3443 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 3444 AttrLoc); 3445 3446 DependentSizedExtVectorType *CanonCheck 3447 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 3448 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 3449 (void)CanonCheck; 3450 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 3451 } else { 3452 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 3453 SourceLocation()); 3454 New = new (*this, TypeAlignment) 3455 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc); 3456 } 3457 } 3458 3459 Types.push_back(New); 3460 return QualType(New, 0); 3461 } 3462 3463 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, 3464 Expr *AddrSpaceExpr, 3465 SourceLocation AttrLoc) const { 3466 assert(AddrSpaceExpr->isInstantiationDependent()); 3467 3468 QualType canonPointeeType = getCanonicalType(PointeeType); 3469 3470 void *insertPos = nullptr; 3471 llvm::FoldingSetNodeID ID; 3472 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType, 3473 AddrSpaceExpr); 3474 3475 DependentAddressSpaceType *canonTy = 3476 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos); 3477 3478 if (!canonTy) { 3479 canonTy = new (*this, TypeAlignment) 3480 DependentAddressSpaceType(*this, canonPointeeType, 3481 QualType(), AddrSpaceExpr, AttrLoc); 3482 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos); 3483 Types.push_back(canonTy); 3484 } 3485 3486 if (canonPointeeType == PointeeType && 3487 canonTy->getAddrSpaceExpr() == AddrSpaceExpr) 3488 return QualType(canonTy, 0); 3489 3490 auto *sugaredType 3491 = new (*this, TypeAlignment) 3492 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0), 3493 AddrSpaceExpr, AttrLoc); 3494 Types.push_back(sugaredType); 3495 return QualType(sugaredType, 0); 3496 } 3497 3498 /// Determine whether \p T is canonical as the result type of a function. 3499 static bool isCanonicalResultType(QualType T) { 3500 return T.isCanonical() && 3501 (T.getObjCLifetime() == Qualifiers::OCL_None || 3502 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone); 3503 } 3504 3505 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 3506 QualType 3507 ASTContext::getFunctionNoProtoType(QualType ResultTy, 3508 const FunctionType::ExtInfo &Info) const { 3509 // Unique functions, to guarantee there is only one function of a particular 3510 // structure. 3511 llvm::FoldingSetNodeID ID; 3512 FunctionNoProtoType::Profile(ID, ResultTy, Info); 3513 3514 void *InsertPos = nullptr; 3515 if (FunctionNoProtoType *FT = 3516 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 3517 return QualType(FT, 0); 3518 3519 QualType Canonical; 3520 if (!isCanonicalResultType(ResultTy)) { 3521 Canonical = 3522 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info); 3523 3524 // Get the new insert position for the node we care about. 3525 FunctionNoProtoType *NewIP = 3526 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 3527 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3528 } 3529 3530 auto *New = new (*this, TypeAlignment) 3531 FunctionNoProtoType(ResultTy, Canonical, Info); 3532 Types.push_back(New); 3533 FunctionNoProtoTypes.InsertNode(New, InsertPos); 3534 return QualType(New, 0); 3535 } 3536 3537 CanQualType 3538 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const { 3539 CanQualType CanResultType = getCanonicalType(ResultType); 3540 3541 // Canonical result types do not have ARC lifetime qualifiers. 3542 if (CanResultType.getQualifiers().hasObjCLifetime()) { 3543 Qualifiers Qs = CanResultType.getQualifiers(); 3544 Qs.removeObjCLifetime(); 3545 return CanQualType::CreateUnsafe( 3546 getQualifiedType(CanResultType.getUnqualifiedType(), Qs)); 3547 } 3548 3549 return CanResultType; 3550 } 3551 3552 static bool isCanonicalExceptionSpecification( 3553 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) { 3554 if (ESI.Type == EST_None) 3555 return true; 3556 if (!NoexceptInType) 3557 return false; 3558 3559 // C++17 onwards: exception specification is part of the type, as a simple 3560 // boolean "can this function type throw". 3561 if (ESI.Type == EST_BasicNoexcept) 3562 return true; 3563 3564 // A noexcept(expr) specification is (possibly) canonical if expr is 3565 // value-dependent. 3566 if (ESI.Type == EST_DependentNoexcept) 3567 return true; 3568 3569 // A dynamic exception specification is canonical if it only contains pack 3570 // expansions (so we can't tell whether it's non-throwing) and all its 3571 // contained types are canonical. 3572 if (ESI.Type == EST_Dynamic) { 3573 bool AnyPackExpansions = false; 3574 for (QualType ET : ESI.Exceptions) { 3575 if (!ET.isCanonical()) 3576 return false; 3577 if (ET->getAs<PackExpansionType>()) 3578 AnyPackExpansions = true; 3579 } 3580 return AnyPackExpansions; 3581 } 3582 3583 return false; 3584 } 3585 3586 QualType ASTContext::getFunctionTypeInternal( 3587 QualType ResultTy, ArrayRef<QualType> ArgArray, 3588 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const { 3589 size_t NumArgs = ArgArray.size(); 3590 3591 // Unique functions, to guarantee there is only one function of a particular 3592 // structure. 3593 llvm::FoldingSetNodeID ID; 3594 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, 3595 *this, true); 3596 3597 QualType Canonical; 3598 bool Unique = false; 3599 3600 void *InsertPos = nullptr; 3601 if (FunctionProtoType *FPT = 3602 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) { 3603 QualType Existing = QualType(FPT, 0); 3604 3605 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse 3606 // it so long as our exception specification doesn't contain a dependent 3607 // noexcept expression, or we're just looking for a canonical type. 3608 // Otherwise, we're going to need to create a type 3609 // sugar node to hold the concrete expression. 3610 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) || 3611 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr()) 3612 return Existing; 3613 3614 // We need a new type sugar node for this one, to hold the new noexcept 3615 // expression. We do no canonicalization here, but that's OK since we don't 3616 // expect to see the same noexcept expression much more than once. 3617 Canonical = getCanonicalType(Existing); 3618 Unique = true; 3619 } 3620 3621 bool NoexceptInType = getLangOpts().CPlusPlus17; 3622 bool IsCanonicalExceptionSpec = 3623 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType); 3624 3625 // Determine whether the type being created is already canonical or not. 3626 bool isCanonical = !Unique && IsCanonicalExceptionSpec && 3627 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn; 3628 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 3629 if (!ArgArray[i].isCanonicalAsParam()) 3630 isCanonical = false; 3631 3632 if (OnlyWantCanonical) 3633 assert(isCanonical && 3634 "given non-canonical parameters constructing canonical type"); 3635 3636 // If this type isn't canonical, get the canonical version of it if we don't 3637 // already have it. The exception spec is only partially part of the 3638 // canonical type, and only in C++17 onwards. 3639 if (!isCanonical && Canonical.isNull()) { 3640 SmallVector<QualType, 16> CanonicalArgs; 3641 CanonicalArgs.reserve(NumArgs); 3642 for (unsigned i = 0; i != NumArgs; ++i) 3643 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 3644 3645 llvm::SmallVector<QualType, 8> ExceptionTypeStorage; 3646 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 3647 CanonicalEPI.HasTrailingReturn = false; 3648 3649 if (IsCanonicalExceptionSpec) { 3650 // Exception spec is already OK. 3651 } else if (NoexceptInType) { 3652 switch (EPI.ExceptionSpec.Type) { 3653 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated: 3654 // We don't know yet. It shouldn't matter what we pick here; no-one 3655 // should ever look at this. 3656 LLVM_FALLTHROUGH; 3657 case EST_None: case EST_MSAny: case EST_NoexceptFalse: 3658 CanonicalEPI.ExceptionSpec.Type = EST_None; 3659 break; 3660 3661 // A dynamic exception specification is almost always "not noexcept", 3662 // with the exception that a pack expansion might expand to no types. 3663 case EST_Dynamic: { 3664 bool AnyPacks = false; 3665 for (QualType ET : EPI.ExceptionSpec.Exceptions) { 3666 if (ET->getAs<PackExpansionType>()) 3667 AnyPacks = true; 3668 ExceptionTypeStorage.push_back(getCanonicalType(ET)); 3669 } 3670 if (!AnyPacks) 3671 CanonicalEPI.ExceptionSpec.Type = EST_None; 3672 else { 3673 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic; 3674 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage; 3675 } 3676 break; 3677 } 3678 3679 case EST_DynamicNone: case EST_BasicNoexcept: case EST_NoexceptTrue: 3680 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept; 3681 break; 3682 3683 case EST_DependentNoexcept: 3684 llvm_unreachable("dependent noexcept is already canonical"); 3685 } 3686 } else { 3687 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo(); 3688 } 3689 3690 // Adjust the canonical function result type. 3691 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy); 3692 Canonical = 3693 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true); 3694 3695 // Get the new insert position for the node we care about. 3696 FunctionProtoType *NewIP = 3697 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 3698 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3699 } 3700 3701 // FunctionProtoType objects are allocated with extra bytes after 3702 // them for three variable size arrays at the end: 3703 // - parameter types 3704 // - exception types 3705 // - extended parameter information 3706 // Instead of the exception types, there could be a noexcept 3707 // expression, or information used to resolve the exception 3708 // specification. 3709 size_t Size = 3710 sizeof(FunctionProtoType) + NumArgs * sizeof(QualType) + 3711 FunctionProtoType::getExceptionSpecSize( 3712 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size()); 3713 3714 // Put the ExtParameterInfos last. If all were equal, it would make 3715 // more sense to put these before the exception specification, because 3716 // it's much easier to skip past them compared to the elaborate switch 3717 // required to skip the exception specification. However, all is not 3718 // equal; ExtParameterInfos are used to model very uncommon features, 3719 // and it's better not to burden the more common paths. 3720 if (EPI.ExtParameterInfos) { 3721 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo); 3722 } 3723 3724 auto *FTP = (FunctionProtoType *) Allocate(Size, TypeAlignment); 3725 FunctionProtoType::ExtProtoInfo newEPI = EPI; 3726 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI); 3727 Types.push_back(FTP); 3728 if (!Unique) 3729 FunctionProtoTypes.InsertNode(FTP, InsertPos); 3730 return QualType(FTP, 0); 3731 } 3732 3733 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const { 3734 llvm::FoldingSetNodeID ID; 3735 PipeType::Profile(ID, T, ReadOnly); 3736 3737 void *InsertPos = nullptr; 3738 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos)) 3739 return QualType(PT, 0); 3740 3741 // If the pipe element type isn't canonical, this won't be a canonical type 3742 // either, so fill in the canonical type field. 3743 QualType Canonical; 3744 if (!T.isCanonical()) { 3745 Canonical = getPipeType(getCanonicalType(T), ReadOnly); 3746 3747 // Get the new insert position for the node we care about. 3748 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos); 3749 assert(!NewIP && "Shouldn't be in the map!"); 3750 (void)NewIP; 3751 } 3752 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly); 3753 Types.push_back(New); 3754 PipeTypes.InsertNode(New, InsertPos); 3755 return QualType(New, 0); 3756 } 3757 3758 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const { 3759 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 3760 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant) 3761 : Ty; 3762 } 3763 3764 QualType ASTContext::getReadPipeType(QualType T) const { 3765 return getPipeType(T, true); 3766 } 3767 3768 QualType ASTContext::getWritePipeType(QualType T) const { 3769 return getPipeType(T, false); 3770 } 3771 3772 #ifndef NDEBUG 3773 static bool NeedsInjectedClassNameType(const RecordDecl *D) { 3774 if (!isa<CXXRecordDecl>(D)) return false; 3775 const auto *RD = cast<CXXRecordDecl>(D); 3776 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 3777 return true; 3778 if (RD->getDescribedClassTemplate() && 3779 !isa<ClassTemplateSpecializationDecl>(RD)) 3780 return true; 3781 return false; 3782 } 3783 #endif 3784 3785 /// getInjectedClassNameType - Return the unique reference to the 3786 /// injected class name type for the specified templated declaration. 3787 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 3788 QualType TST) const { 3789 assert(NeedsInjectedClassNameType(Decl)); 3790 if (Decl->TypeForDecl) { 3791 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 3792 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 3793 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 3794 Decl->TypeForDecl = PrevDecl->TypeForDecl; 3795 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 3796 } else { 3797 Type *newType = 3798 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 3799 Decl->TypeForDecl = newType; 3800 Types.push_back(newType); 3801 } 3802 return QualType(Decl->TypeForDecl, 0); 3803 } 3804 3805 /// getTypeDeclType - Return the unique reference to the type for the 3806 /// specified type declaration. 3807 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 3808 assert(Decl && "Passed null for Decl param"); 3809 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 3810 3811 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 3812 return getTypedefType(Typedef); 3813 3814 assert(!isa<TemplateTypeParmDecl>(Decl) && 3815 "Template type parameter types are always available."); 3816 3817 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) { 3818 assert(Record->isFirstDecl() && "struct/union has previous declaration"); 3819 assert(!NeedsInjectedClassNameType(Record)); 3820 return getRecordType(Record); 3821 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) { 3822 assert(Enum->isFirstDecl() && "enum has previous declaration"); 3823 return getEnumType(Enum); 3824 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 3825 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using); 3826 Decl->TypeForDecl = newType; 3827 Types.push_back(newType); 3828 } else 3829 llvm_unreachable("TypeDecl without a type?"); 3830 3831 return QualType(Decl->TypeForDecl, 0); 3832 } 3833 3834 /// getTypedefType - Return the unique reference to the type for the 3835 /// specified typedef name decl. 3836 QualType 3837 ASTContext::getTypedefType(const TypedefNameDecl *Decl, 3838 QualType Canonical) const { 3839 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 3840 3841 if (Canonical.isNull()) 3842 Canonical = getCanonicalType(Decl->getUnderlyingType()); 3843 auto *newType = new (*this, TypeAlignment) 3844 TypedefType(Type::Typedef, Decl, Canonical); 3845 Decl->TypeForDecl = newType; 3846 Types.push_back(newType); 3847 return QualType(newType, 0); 3848 } 3849 3850 QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 3851 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 3852 3853 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 3854 if (PrevDecl->TypeForDecl) 3855 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 3856 3857 auto *newType = new (*this, TypeAlignment) RecordType(Decl); 3858 Decl->TypeForDecl = newType; 3859 Types.push_back(newType); 3860 return QualType(newType, 0); 3861 } 3862 3863 QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 3864 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 3865 3866 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 3867 if (PrevDecl->TypeForDecl) 3868 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 3869 3870 auto *newType = new (*this, TypeAlignment) EnumType(Decl); 3871 Decl->TypeForDecl = newType; 3872 Types.push_back(newType); 3873 return QualType(newType, 0); 3874 } 3875 3876 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind, 3877 QualType modifiedType, 3878 QualType equivalentType) { 3879 llvm::FoldingSetNodeID id; 3880 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 3881 3882 void *insertPos = nullptr; 3883 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 3884 if (type) return QualType(type, 0); 3885 3886 QualType canon = getCanonicalType(equivalentType); 3887 type = new (*this, TypeAlignment) 3888 AttributedType(canon, attrKind, modifiedType, equivalentType); 3889 3890 Types.push_back(type); 3891 AttributedTypes.InsertNode(type, insertPos); 3892 3893 return QualType(type, 0); 3894 } 3895 3896 /// Retrieve a substitution-result type. 3897 QualType 3898 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 3899 QualType Replacement) const { 3900 assert(Replacement.isCanonical() 3901 && "replacement types must always be canonical"); 3902 3903 llvm::FoldingSetNodeID ID; 3904 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 3905 void *InsertPos = nullptr; 3906 SubstTemplateTypeParmType *SubstParm 3907 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3908 3909 if (!SubstParm) { 3910 SubstParm = new (*this, TypeAlignment) 3911 SubstTemplateTypeParmType(Parm, Replacement); 3912 Types.push_back(SubstParm); 3913 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 3914 } 3915 3916 return QualType(SubstParm, 0); 3917 } 3918 3919 /// Retrieve a 3920 QualType ASTContext::getSubstTemplateTypeParmPackType( 3921 const TemplateTypeParmType *Parm, 3922 const TemplateArgument &ArgPack) { 3923 #ifndef NDEBUG 3924 for (const auto &P : ArgPack.pack_elements()) { 3925 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 3926 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); 3927 } 3928 #endif 3929 3930 llvm::FoldingSetNodeID ID; 3931 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 3932 void *InsertPos = nullptr; 3933 if (SubstTemplateTypeParmPackType *SubstParm 3934 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 3935 return QualType(SubstParm, 0); 3936 3937 QualType Canon; 3938 if (!Parm->isCanonicalUnqualified()) { 3939 Canon = getCanonicalType(QualType(Parm, 0)); 3940 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 3941 ArgPack); 3942 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 3943 } 3944 3945 auto *SubstParm 3946 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 3947 ArgPack); 3948 Types.push_back(SubstParm); 3949 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos); 3950 return QualType(SubstParm, 0); 3951 } 3952 3953 /// Retrieve the template type parameter type for a template 3954 /// parameter or parameter pack with the given depth, index, and (optionally) 3955 /// name. 3956 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 3957 bool ParameterPack, 3958 TemplateTypeParmDecl *TTPDecl) const { 3959 llvm::FoldingSetNodeID ID; 3960 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 3961 void *InsertPos = nullptr; 3962 TemplateTypeParmType *TypeParm 3963 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3964 3965 if (TypeParm) 3966 return QualType(TypeParm, 0); 3967 3968 if (TTPDecl) { 3969 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 3970 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 3971 3972 TemplateTypeParmType *TypeCheck 3973 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3974 assert(!TypeCheck && "Template type parameter canonical type broken"); 3975 (void)TypeCheck; 3976 } else 3977 TypeParm = new (*this, TypeAlignment) 3978 TemplateTypeParmType(Depth, Index, ParameterPack); 3979 3980 Types.push_back(TypeParm); 3981 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 3982 3983 return QualType(TypeParm, 0); 3984 } 3985 3986 TypeSourceInfo * 3987 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 3988 SourceLocation NameLoc, 3989 const TemplateArgumentListInfo &Args, 3990 QualType Underlying) const { 3991 assert(!Name.getAsDependentTemplateName() && 3992 "No dependent template names here!"); 3993 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 3994 3995 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 3996 TemplateSpecializationTypeLoc TL = 3997 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>(); 3998 TL.setTemplateKeywordLoc(SourceLocation()); 3999 TL.setTemplateNameLoc(NameLoc); 4000 TL.setLAngleLoc(Args.getLAngleLoc()); 4001 TL.setRAngleLoc(Args.getRAngleLoc()); 4002 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 4003 TL.setArgLocInfo(i, Args[i].getLocInfo()); 4004 return DI; 4005 } 4006 4007 QualType 4008 ASTContext::getTemplateSpecializationType(TemplateName Template, 4009 const TemplateArgumentListInfo &Args, 4010 QualType Underlying) const { 4011 assert(!Template.getAsDependentTemplateName() && 4012 "No dependent template names here!"); 4013 4014 SmallVector<TemplateArgument, 4> ArgVec; 4015 ArgVec.reserve(Args.size()); 4016 for (const TemplateArgumentLoc &Arg : Args.arguments()) 4017 ArgVec.push_back(Arg.getArgument()); 4018 4019 return getTemplateSpecializationType(Template, ArgVec, Underlying); 4020 } 4021 4022 #ifndef NDEBUG 4023 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) { 4024 for (const TemplateArgument &Arg : Args) 4025 if (Arg.isPackExpansion()) 4026 return true; 4027 4028 return true; 4029 } 4030 #endif 4031 4032 QualType 4033 ASTContext::getTemplateSpecializationType(TemplateName Template, 4034 ArrayRef<TemplateArgument> Args, 4035 QualType Underlying) const { 4036 assert(!Template.getAsDependentTemplateName() && 4037 "No dependent template names here!"); 4038 // Look through qualified template names. 4039 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4040 Template = TemplateName(QTN->getTemplateDecl()); 4041 4042 bool IsTypeAlias = 4043 Template.getAsTemplateDecl() && 4044 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 4045 QualType CanonType; 4046 if (!Underlying.isNull()) 4047 CanonType = getCanonicalType(Underlying); 4048 else { 4049 // We can get here with an alias template when the specialization contains 4050 // a pack expansion that does not match up with a parameter pack. 4051 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) && 4052 "Caller must compute aliased type"); 4053 IsTypeAlias = false; 4054 CanonType = getCanonicalTemplateSpecializationType(Template, Args); 4055 } 4056 4057 // Allocate the (non-canonical) template specialization type, but don't 4058 // try to unique it: these types typically have location information that 4059 // we don't unique and don't want to lose. 4060 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 4061 sizeof(TemplateArgument) * Args.size() + 4062 (IsTypeAlias? sizeof(QualType) : 0), 4063 TypeAlignment); 4064 auto *Spec 4065 = new (Mem) TemplateSpecializationType(Template, Args, CanonType, 4066 IsTypeAlias ? Underlying : QualType()); 4067 4068 Types.push_back(Spec); 4069 return QualType(Spec, 0); 4070 } 4071 4072 QualType ASTContext::getCanonicalTemplateSpecializationType( 4073 TemplateName Template, ArrayRef<TemplateArgument> Args) const { 4074 assert(!Template.getAsDependentTemplateName() && 4075 "No dependent template names here!"); 4076 4077 // Look through qualified template names. 4078 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 4079 Template = TemplateName(QTN->getTemplateDecl()); 4080 4081 // Build the canonical template specialization type. 4082 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 4083 SmallVector<TemplateArgument, 4> CanonArgs; 4084 unsigned NumArgs = Args.size(); 4085 CanonArgs.reserve(NumArgs); 4086 for (const TemplateArgument &Arg : Args) 4087 CanonArgs.push_back(getCanonicalTemplateArgument(Arg)); 4088 4089 // Determine whether this canonical template specialization type already 4090 // exists. 4091 llvm::FoldingSetNodeID ID; 4092 TemplateSpecializationType::Profile(ID, CanonTemplate, 4093 CanonArgs, *this); 4094 4095 void *InsertPos = nullptr; 4096 TemplateSpecializationType *Spec 4097 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4098 4099 if (!Spec) { 4100 // Allocate a new canonical template specialization type. 4101 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 4102 sizeof(TemplateArgument) * NumArgs), 4103 TypeAlignment); 4104 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 4105 CanonArgs, 4106 QualType(), QualType()); 4107 Types.push_back(Spec); 4108 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 4109 } 4110 4111 assert(Spec->isDependentType() && 4112 "Non-dependent template-id type must have a canonical type"); 4113 return QualType(Spec, 0); 4114 } 4115 4116 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 4117 NestedNameSpecifier *NNS, 4118 QualType NamedType, 4119 TagDecl *OwnedTagDecl) const { 4120 llvm::FoldingSetNodeID ID; 4121 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl); 4122 4123 void *InsertPos = nullptr; 4124 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4125 if (T) 4126 return QualType(T, 0); 4127 4128 QualType Canon = NamedType; 4129 if (!Canon.isCanonical()) { 4130 Canon = getCanonicalType(NamedType); 4131 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 4132 assert(!CheckT && "Elaborated canonical type broken"); 4133 (void)CheckT; 4134 } 4135 4136 T = new (*this, TypeAlignment) 4137 ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl); 4138 Types.push_back(T); 4139 ElaboratedTypes.InsertNode(T, InsertPos); 4140 return QualType(T, 0); 4141 } 4142 4143 QualType 4144 ASTContext::getParenType(QualType InnerType) const { 4145 llvm::FoldingSetNodeID ID; 4146 ParenType::Profile(ID, InnerType); 4147 4148 void *InsertPos = nullptr; 4149 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4150 if (T) 4151 return QualType(T, 0); 4152 4153 QualType Canon = InnerType; 4154 if (!Canon.isCanonical()) { 4155 Canon = getCanonicalType(InnerType); 4156 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 4157 assert(!CheckT && "Paren canonical type broken"); 4158 (void)CheckT; 4159 } 4160 4161 T = new (*this, TypeAlignment) ParenType(InnerType, Canon); 4162 Types.push_back(T); 4163 ParenTypes.InsertNode(T, InsertPos); 4164 return QualType(T, 0); 4165 } 4166 4167 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 4168 NestedNameSpecifier *NNS, 4169 const IdentifierInfo *Name, 4170 QualType Canon) const { 4171 if (Canon.isNull()) { 4172 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4173 if (CanonNNS != NNS) 4174 Canon = getDependentNameType(Keyword, CanonNNS, Name); 4175 } 4176 4177 llvm::FoldingSetNodeID ID; 4178 DependentNameType::Profile(ID, Keyword, NNS, Name); 4179 4180 void *InsertPos = nullptr; 4181 DependentNameType *T 4182 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 4183 if (T) 4184 return QualType(T, 0); 4185 4186 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon); 4187 Types.push_back(T); 4188 DependentNameTypes.InsertNode(T, InsertPos); 4189 return QualType(T, 0); 4190 } 4191 4192 QualType 4193 ASTContext::getDependentTemplateSpecializationType( 4194 ElaboratedTypeKeyword Keyword, 4195 NestedNameSpecifier *NNS, 4196 const IdentifierInfo *Name, 4197 const TemplateArgumentListInfo &Args) const { 4198 // TODO: avoid this copy 4199 SmallVector<TemplateArgument, 16> ArgCopy; 4200 for (unsigned I = 0, E = Args.size(); I != E; ++I) 4201 ArgCopy.push_back(Args[I].getArgument()); 4202 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy); 4203 } 4204 4205 QualType 4206 ASTContext::getDependentTemplateSpecializationType( 4207 ElaboratedTypeKeyword Keyword, 4208 NestedNameSpecifier *NNS, 4209 const IdentifierInfo *Name, 4210 ArrayRef<TemplateArgument> Args) const { 4211 assert((!NNS || NNS->isDependent()) && 4212 "nested-name-specifier must be dependent"); 4213 4214 llvm::FoldingSetNodeID ID; 4215 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 4216 Name, Args); 4217 4218 void *InsertPos = nullptr; 4219 DependentTemplateSpecializationType *T 4220 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4221 if (T) 4222 return QualType(T, 0); 4223 4224 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4225 4226 ElaboratedTypeKeyword CanonKeyword = Keyword; 4227 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 4228 4229 bool AnyNonCanonArgs = false; 4230 unsigned NumArgs = Args.size(); 4231 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs); 4232 for (unsigned I = 0; I != NumArgs; ++I) { 4233 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]); 4234 if (!CanonArgs[I].structurallyEquals(Args[I])) 4235 AnyNonCanonArgs = true; 4236 } 4237 4238 QualType Canon; 4239 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 4240 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 4241 Name, 4242 CanonArgs); 4243 4244 // Find the insert position again. 4245 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 4246 } 4247 4248 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 4249 sizeof(TemplateArgument) * NumArgs), 4250 TypeAlignment); 4251 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 4252 Name, Args, Canon); 4253 Types.push_back(T); 4254 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 4255 return QualType(T, 0); 4256 } 4257 4258 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) { 4259 TemplateArgument Arg; 4260 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 4261 QualType ArgType = getTypeDeclType(TTP); 4262 if (TTP->isParameterPack()) 4263 ArgType = getPackExpansionType(ArgType, None); 4264 4265 Arg = TemplateArgument(ArgType); 4266 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 4267 Expr *E = new (*this) DeclRefExpr( 4268 NTTP, /*enclosing*/false, 4269 NTTP->getType().getNonLValueExprType(*this), 4270 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation()); 4271 4272 if (NTTP->isParameterPack()) 4273 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(), 4274 None); 4275 Arg = TemplateArgument(E); 4276 } else { 4277 auto *TTP = cast<TemplateTemplateParmDecl>(Param); 4278 if (TTP->isParameterPack()) 4279 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>()); 4280 else 4281 Arg = TemplateArgument(TemplateName(TTP)); 4282 } 4283 4284 if (Param->isTemplateParameterPack()) 4285 Arg = TemplateArgument::CreatePackCopy(*this, Arg); 4286 4287 return Arg; 4288 } 4289 4290 void 4291 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params, 4292 SmallVectorImpl<TemplateArgument> &Args) { 4293 Args.reserve(Args.size() + Params->size()); 4294 4295 for (NamedDecl *Param : *Params) 4296 Args.push_back(getInjectedTemplateArg(Param)); 4297 } 4298 4299 QualType ASTContext::getPackExpansionType(QualType Pattern, 4300 Optional<unsigned> NumExpansions) { 4301 llvm::FoldingSetNodeID ID; 4302 PackExpansionType::Profile(ID, Pattern, NumExpansions); 4303 4304 assert(Pattern->containsUnexpandedParameterPack() && 4305 "Pack expansions must expand one or more parameter packs"); 4306 void *InsertPos = nullptr; 4307 PackExpansionType *T 4308 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 4309 if (T) 4310 return QualType(T, 0); 4311 4312 QualType Canon; 4313 if (!Pattern.isCanonical()) { 4314 Canon = getCanonicalType(Pattern); 4315 // The canonical type might not contain an unexpanded parameter pack, if it 4316 // contains an alias template specialization which ignores one of its 4317 // parameters. 4318 if (Canon->containsUnexpandedParameterPack()) { 4319 Canon = getPackExpansionType(Canon, NumExpansions); 4320 4321 // Find the insert position again, in case we inserted an element into 4322 // PackExpansionTypes and invalidated our insert position. 4323 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 4324 } 4325 } 4326 4327 T = new (*this, TypeAlignment) 4328 PackExpansionType(Pattern, Canon, NumExpansions); 4329 Types.push_back(T); 4330 PackExpansionTypes.InsertNode(T, InsertPos); 4331 return QualType(T, 0); 4332 } 4333 4334 /// CmpProtocolNames - Comparison predicate for sorting protocols 4335 /// alphabetically. 4336 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, 4337 ObjCProtocolDecl *const *RHS) { 4338 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName()); 4339 } 4340 4341 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) { 4342 if (Protocols.empty()) return true; 4343 4344 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 4345 return false; 4346 4347 for (unsigned i = 1; i != Protocols.size(); ++i) 4348 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 || 4349 Protocols[i]->getCanonicalDecl() != Protocols[i]) 4350 return false; 4351 return true; 4352 } 4353 4354 static void 4355 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) { 4356 // Sort protocols, keyed by name. 4357 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames); 4358 4359 // Canonicalize. 4360 for (ObjCProtocolDecl *&P : Protocols) 4361 P = P->getCanonicalDecl(); 4362 4363 // Remove duplicates. 4364 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end()); 4365 Protocols.erase(ProtocolsEnd, Protocols.end()); 4366 } 4367 4368 QualType ASTContext::getObjCObjectType(QualType BaseType, 4369 ObjCProtocolDecl * const *Protocols, 4370 unsigned NumProtocols) const { 4371 return getObjCObjectType(BaseType, {}, 4372 llvm::makeArrayRef(Protocols, NumProtocols), 4373 /*isKindOf=*/false); 4374 } 4375 4376 QualType ASTContext::getObjCObjectType( 4377 QualType baseType, 4378 ArrayRef<QualType> typeArgs, 4379 ArrayRef<ObjCProtocolDecl *> protocols, 4380 bool isKindOf) const { 4381 // If the base type is an interface and there aren't any protocols or 4382 // type arguments to add, then the interface type will do just fine. 4383 if (typeArgs.empty() && protocols.empty() && !isKindOf && 4384 isa<ObjCInterfaceType>(baseType)) 4385 return baseType; 4386 4387 // Look in the folding set for an existing type. 4388 llvm::FoldingSetNodeID ID; 4389 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf); 4390 void *InsertPos = nullptr; 4391 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 4392 return QualType(QT, 0); 4393 4394 // Determine the type arguments to be used for canonicalization, 4395 // which may be explicitly specified here or written on the base 4396 // type. 4397 ArrayRef<QualType> effectiveTypeArgs = typeArgs; 4398 if (effectiveTypeArgs.empty()) { 4399 if (const auto *baseObject = baseType->getAs<ObjCObjectType>()) 4400 effectiveTypeArgs = baseObject->getTypeArgs(); 4401 } 4402 4403 // Build the canonical type, which has the canonical base type and a 4404 // sorted-and-uniqued list of protocols and the type arguments 4405 // canonicalized. 4406 QualType canonical; 4407 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(), 4408 effectiveTypeArgs.end(), 4409 [&](QualType type) { 4410 return type.isCanonical(); 4411 }); 4412 bool protocolsSorted = areSortedAndUniqued(protocols); 4413 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) { 4414 // Determine the canonical type arguments. 4415 ArrayRef<QualType> canonTypeArgs; 4416 SmallVector<QualType, 4> canonTypeArgsVec; 4417 if (!typeArgsAreCanonical) { 4418 canonTypeArgsVec.reserve(effectiveTypeArgs.size()); 4419 for (auto typeArg : effectiveTypeArgs) 4420 canonTypeArgsVec.push_back(getCanonicalType(typeArg)); 4421 canonTypeArgs = canonTypeArgsVec; 4422 } else { 4423 canonTypeArgs = effectiveTypeArgs; 4424 } 4425 4426 ArrayRef<ObjCProtocolDecl *> canonProtocols; 4427 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec; 4428 if (!protocolsSorted) { 4429 canonProtocolsVec.append(protocols.begin(), protocols.end()); 4430 SortAndUniqueProtocols(canonProtocolsVec); 4431 canonProtocols = canonProtocolsVec; 4432 } else { 4433 canonProtocols = protocols; 4434 } 4435 4436 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs, 4437 canonProtocols, isKindOf); 4438 4439 // Regenerate InsertPos. 4440 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 4441 } 4442 4443 unsigned size = sizeof(ObjCObjectTypeImpl); 4444 size += typeArgs.size() * sizeof(QualType); 4445 size += protocols.size() * sizeof(ObjCProtocolDecl *); 4446 void *mem = Allocate(size, TypeAlignment); 4447 auto *T = 4448 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols, 4449 isKindOf); 4450 4451 Types.push_back(T); 4452 ObjCObjectTypes.InsertNode(T, InsertPos); 4453 return QualType(T, 0); 4454 } 4455 4456 /// Apply Objective-C protocol qualifiers to the given type. 4457 /// If this is for the canonical type of a type parameter, we can apply 4458 /// protocol qualifiers on the ObjCObjectPointerType. 4459 QualType 4460 ASTContext::applyObjCProtocolQualifiers(QualType type, 4461 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, 4462 bool allowOnPointerType) const { 4463 hasError = false; 4464 4465 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) { 4466 return getObjCTypeParamType(objT->getDecl(), protocols); 4467 } 4468 4469 // Apply protocol qualifiers to ObjCObjectPointerType. 4470 if (allowOnPointerType) { 4471 if (const auto *objPtr = 4472 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) { 4473 const ObjCObjectType *objT = objPtr->getObjectType(); 4474 // Merge protocol lists and construct ObjCObjectType. 4475 SmallVector<ObjCProtocolDecl*, 8> protocolsVec; 4476 protocolsVec.append(objT->qual_begin(), 4477 objT->qual_end()); 4478 protocolsVec.append(protocols.begin(), protocols.end()); 4479 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec; 4480 type = getObjCObjectType( 4481 objT->getBaseType(), 4482 objT->getTypeArgsAsWritten(), 4483 protocols, 4484 objT->isKindOfTypeAsWritten()); 4485 return getObjCObjectPointerType(type); 4486 } 4487 } 4488 4489 // Apply protocol qualifiers to ObjCObjectType. 4490 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){ 4491 // FIXME: Check for protocols to which the class type is already 4492 // known to conform. 4493 4494 return getObjCObjectType(objT->getBaseType(), 4495 objT->getTypeArgsAsWritten(), 4496 protocols, 4497 objT->isKindOfTypeAsWritten()); 4498 } 4499 4500 // If the canonical type is ObjCObjectType, ... 4501 if (type->isObjCObjectType()) { 4502 // Silently overwrite any existing protocol qualifiers. 4503 // TODO: determine whether that's the right thing to do. 4504 4505 // FIXME: Check for protocols to which the class type is already 4506 // known to conform. 4507 return getObjCObjectType(type, {}, protocols, false); 4508 } 4509 4510 // id<protocol-list> 4511 if (type->isObjCIdType()) { 4512 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 4513 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols, 4514 objPtr->isKindOfType()); 4515 return getObjCObjectPointerType(type); 4516 } 4517 4518 // Class<protocol-list> 4519 if (type->isObjCClassType()) { 4520 const auto *objPtr = type->castAs<ObjCObjectPointerType>(); 4521 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols, 4522 objPtr->isKindOfType()); 4523 return getObjCObjectPointerType(type); 4524 } 4525 4526 hasError = true; 4527 return type; 4528 } 4529 4530 QualType 4531 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl, 4532 ArrayRef<ObjCProtocolDecl *> protocols, 4533 QualType Canonical) const { 4534 // Look in the folding set for an existing type. 4535 llvm::FoldingSetNodeID ID; 4536 ObjCTypeParamType::Profile(ID, Decl, protocols); 4537 void *InsertPos = nullptr; 4538 if (ObjCTypeParamType *TypeParam = 4539 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos)) 4540 return QualType(TypeParam, 0); 4541 4542 if (Canonical.isNull()) { 4543 // We canonicalize to the underlying type. 4544 Canonical = getCanonicalType(Decl->getUnderlyingType()); 4545 if (!protocols.empty()) { 4546 // Apply the protocol qualifers. 4547 bool hasError; 4548 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError, 4549 true/*allowOnPointerType*/); 4550 assert(!hasError && "Error when apply protocol qualifier to bound type"); 4551 } 4552 } 4553 4554 unsigned size = sizeof(ObjCTypeParamType); 4555 size += protocols.size() * sizeof(ObjCProtocolDecl *); 4556 void *mem = Allocate(size, TypeAlignment); 4557 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols); 4558 4559 Types.push_back(newType); 4560 ObjCTypeParamTypes.InsertNode(newType, InsertPos); 4561 return QualType(newType, 0); 4562 } 4563 4564 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's 4565 /// protocol list adopt all protocols in QT's qualified-id protocol 4566 /// list. 4567 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, 4568 ObjCInterfaceDecl *IC) { 4569 if (!QT->isObjCQualifiedIdType()) 4570 return false; 4571 4572 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) { 4573 // If both the right and left sides have qualifiers. 4574 for (auto *Proto : OPT->quals()) { 4575 if (!IC->ClassImplementsProtocol(Proto, false)) 4576 return false; 4577 } 4578 return true; 4579 } 4580 return false; 4581 } 4582 4583 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in 4584 /// QT's qualified-id protocol list adopt all protocols in IDecl's list 4585 /// of protocols. 4586 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, 4587 ObjCInterfaceDecl *IDecl) { 4588 if (!QT->isObjCQualifiedIdType()) 4589 return false; 4590 const auto *OPT = QT->getAs<ObjCObjectPointerType>(); 4591 if (!OPT) 4592 return false; 4593 if (!IDecl->hasDefinition()) 4594 return false; 4595 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols; 4596 CollectInheritedProtocols(IDecl, InheritedProtocols); 4597 if (InheritedProtocols.empty()) 4598 return false; 4599 // Check that if every protocol in list of id<plist> conforms to a protocol 4600 // of IDecl's, then bridge casting is ok. 4601 bool Conforms = false; 4602 for (auto *Proto : OPT->quals()) { 4603 Conforms = false; 4604 for (auto *PI : InheritedProtocols) { 4605 if (ProtocolCompatibleWithProtocol(Proto, PI)) { 4606 Conforms = true; 4607 break; 4608 } 4609 } 4610 if (!Conforms) 4611 break; 4612 } 4613 if (Conforms) 4614 return true; 4615 4616 for (auto *PI : InheritedProtocols) { 4617 // If both the right and left sides have qualifiers. 4618 bool Adopts = false; 4619 for (auto *Proto : OPT->quals()) { 4620 // return 'true' if 'PI' is in the inheritance hierarchy of Proto 4621 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto))) 4622 break; 4623 } 4624 if (!Adopts) 4625 return false; 4626 } 4627 return true; 4628 } 4629 4630 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 4631 /// the given object type. 4632 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 4633 llvm::FoldingSetNodeID ID; 4634 ObjCObjectPointerType::Profile(ID, ObjectT); 4635 4636 void *InsertPos = nullptr; 4637 if (ObjCObjectPointerType *QT = 4638 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 4639 return QualType(QT, 0); 4640 4641 // Find the canonical object type. 4642 QualType Canonical; 4643 if (!ObjectT.isCanonical()) { 4644 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 4645 4646 // Regenerate InsertPos. 4647 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 4648 } 4649 4650 // No match. 4651 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 4652 auto *QType = 4653 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 4654 4655 Types.push_back(QType); 4656 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 4657 return QualType(QType, 0); 4658 } 4659 4660 /// getObjCInterfaceType - Return the unique reference to the type for the 4661 /// specified ObjC interface decl. The list of protocols is optional. 4662 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 4663 ObjCInterfaceDecl *PrevDecl) const { 4664 if (Decl->TypeForDecl) 4665 return QualType(Decl->TypeForDecl, 0); 4666 4667 if (PrevDecl) { 4668 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 4669 Decl->TypeForDecl = PrevDecl->TypeForDecl; 4670 return QualType(PrevDecl->TypeForDecl, 0); 4671 } 4672 4673 // Prefer the definition, if there is one. 4674 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 4675 Decl = Def; 4676 4677 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 4678 auto *T = new (Mem) ObjCInterfaceType(Decl); 4679 Decl->TypeForDecl = T; 4680 Types.push_back(T); 4681 return QualType(T, 0); 4682 } 4683 4684 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 4685 /// TypeOfExprType AST's (since expression's are never shared). For example, 4686 /// multiple declarations that refer to "typeof(x)" all contain different 4687 /// DeclRefExpr's. This doesn't effect the type checker, since it operates 4688 /// on canonical type's (which are always unique). 4689 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 4690 TypeOfExprType *toe; 4691 if (tofExpr->isTypeDependent()) { 4692 llvm::FoldingSetNodeID ID; 4693 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 4694 4695 void *InsertPos = nullptr; 4696 DependentTypeOfExprType *Canon 4697 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 4698 if (Canon) { 4699 // We already have a "canonical" version of an identical, dependent 4700 // typeof(expr) type. Use that as our canonical type. 4701 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 4702 QualType((TypeOfExprType*)Canon, 0)); 4703 } else { 4704 // Build a new, canonical typeof(expr) type. 4705 Canon 4706 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 4707 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 4708 toe = Canon; 4709 } 4710 } else { 4711 QualType Canonical = getCanonicalType(tofExpr->getType()); 4712 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 4713 } 4714 Types.push_back(toe); 4715 return QualType(toe, 0); 4716 } 4717 4718 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 4719 /// TypeOfType nodes. The only motivation to unique these nodes would be 4720 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 4721 /// an issue. This doesn't affect the type checker, since it operates 4722 /// on canonical types (which are always unique). 4723 QualType ASTContext::getTypeOfType(QualType tofType) const { 4724 QualType Canonical = getCanonicalType(tofType); 4725 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 4726 Types.push_back(tot); 4727 return QualType(tot, 0); 4728 } 4729 4730 /// Unlike many "get<Type>" functions, we don't unique DecltypeType 4731 /// nodes. This would never be helpful, since each such type has its own 4732 /// expression, and would not give a significant memory saving, since there 4733 /// is an Expr tree under each such type. 4734 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 4735 DecltypeType *dt; 4736 4737 // C++11 [temp.type]p2: 4738 // If an expression e involves a template parameter, decltype(e) denotes a 4739 // unique dependent type. Two such decltype-specifiers refer to the same 4740 // type only if their expressions are equivalent (14.5.6.1). 4741 if (e->isInstantiationDependent()) { 4742 llvm::FoldingSetNodeID ID; 4743 DependentDecltypeType::Profile(ID, *this, e); 4744 4745 void *InsertPos = nullptr; 4746 DependentDecltypeType *Canon 4747 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 4748 if (!Canon) { 4749 // Build a new, canonical decltype(expr) type. 4750 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 4751 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 4752 } 4753 dt = new (*this, TypeAlignment) 4754 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0)); 4755 } else { 4756 dt = new (*this, TypeAlignment) 4757 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType)); 4758 } 4759 Types.push_back(dt); 4760 return QualType(dt, 0); 4761 } 4762 4763 /// getUnaryTransformationType - We don't unique these, since the memory 4764 /// savings are minimal and these are rare. 4765 QualType ASTContext::getUnaryTransformType(QualType BaseType, 4766 QualType UnderlyingType, 4767 UnaryTransformType::UTTKind Kind) 4768 const { 4769 UnaryTransformType *ut = nullptr; 4770 4771 if (BaseType->isDependentType()) { 4772 // Look in the folding set for an existing type. 4773 llvm::FoldingSetNodeID ID; 4774 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind); 4775 4776 void *InsertPos = nullptr; 4777 DependentUnaryTransformType *Canon 4778 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos); 4779 4780 if (!Canon) { 4781 // Build a new, canonical __underlying_type(type) type. 4782 Canon = new (*this, TypeAlignment) 4783 DependentUnaryTransformType(*this, getCanonicalType(BaseType), 4784 Kind); 4785 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos); 4786 } 4787 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 4788 QualType(), Kind, 4789 QualType(Canon, 0)); 4790 } else { 4791 QualType CanonType = getCanonicalType(UnderlyingType); 4792 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, 4793 UnderlyingType, Kind, 4794 CanonType); 4795 } 4796 Types.push_back(ut); 4797 return QualType(ut, 0); 4798 } 4799 4800 /// getAutoType - Return the uniqued reference to the 'auto' type which has been 4801 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the 4802 /// canonical deduced-but-dependent 'auto' type. 4803 QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, 4804 bool IsDependent) const { 4805 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent) 4806 return getAutoDeductType(); 4807 4808 // Look in the folding set for an existing type. 4809 void *InsertPos = nullptr; 4810 llvm::FoldingSetNodeID ID; 4811 AutoType::Profile(ID, DeducedType, Keyword, IsDependent); 4812 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 4813 return QualType(AT, 0); 4814 4815 auto *AT = new (*this, TypeAlignment) 4816 AutoType(DeducedType, Keyword, IsDependent); 4817 Types.push_back(AT); 4818 if (InsertPos) 4819 AutoTypes.InsertNode(AT, InsertPos); 4820 return QualType(AT, 0); 4821 } 4822 4823 /// Return the uniqued reference to the deduced template specialization type 4824 /// which has been deduced to the given type, or to the canonical undeduced 4825 /// such type, or the canonical deduced-but-dependent such type. 4826 QualType ASTContext::getDeducedTemplateSpecializationType( 4827 TemplateName Template, QualType DeducedType, bool IsDependent) const { 4828 // Look in the folding set for an existing type. 4829 void *InsertPos = nullptr; 4830 llvm::FoldingSetNodeID ID; 4831 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType, 4832 IsDependent); 4833 if (DeducedTemplateSpecializationType *DTST = 4834 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos)) 4835 return QualType(DTST, 0); 4836 4837 auto *DTST = new (*this, TypeAlignment) 4838 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent); 4839 Types.push_back(DTST); 4840 if (InsertPos) 4841 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos); 4842 return QualType(DTST, 0); 4843 } 4844 4845 /// getAtomicType - Return the uniqued reference to the atomic type for 4846 /// the given value type. 4847 QualType ASTContext::getAtomicType(QualType T) const { 4848 // Unique pointers, to guarantee there is only one pointer of a particular 4849 // structure. 4850 llvm::FoldingSetNodeID ID; 4851 AtomicType::Profile(ID, T); 4852 4853 void *InsertPos = nullptr; 4854 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 4855 return QualType(AT, 0); 4856 4857 // If the atomic value type isn't canonical, this won't be a canonical type 4858 // either, so fill in the canonical type field. 4859 QualType Canonical; 4860 if (!T.isCanonical()) { 4861 Canonical = getAtomicType(getCanonicalType(T)); 4862 4863 // Get the new insert position for the node we care about. 4864 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 4865 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 4866 } 4867 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 4868 Types.push_back(New); 4869 AtomicTypes.InsertNode(New, InsertPos); 4870 return QualType(New, 0); 4871 } 4872 4873 /// getAutoDeductType - Get type pattern for deducing against 'auto'. 4874 QualType ASTContext::getAutoDeductType() const { 4875 if (AutoDeductTy.isNull()) 4876 AutoDeductTy = QualType( 4877 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto, 4878 /*dependent*/false), 4879 0); 4880 return AutoDeductTy; 4881 } 4882 4883 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 4884 QualType ASTContext::getAutoRRefDeductType() const { 4885 if (AutoRRefDeductTy.isNull()) 4886 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 4887 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 4888 return AutoRRefDeductTy; 4889 } 4890 4891 /// getTagDeclType - Return the unique reference to the type for the 4892 /// specified TagDecl (struct/union/class/enum) decl. 4893 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 4894 assert(Decl); 4895 // FIXME: What is the design on getTagDeclType when it requires casting 4896 // away const? mutable? 4897 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 4898 } 4899 4900 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 4901 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 4902 /// needs to agree with the definition in <stddef.h>. 4903 CanQualType ASTContext::getSizeType() const { 4904 return getFromTargetType(Target->getSizeType()); 4905 } 4906 4907 /// Return the unique signed counterpart of the integer type 4908 /// corresponding to size_t. 4909 CanQualType ASTContext::getSignedSizeType() const { 4910 return getFromTargetType(Target->getSignedSizeType()); 4911 } 4912 4913 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 4914 CanQualType ASTContext::getIntMaxType() const { 4915 return getFromTargetType(Target->getIntMaxType()); 4916 } 4917 4918 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 4919 CanQualType ASTContext::getUIntMaxType() const { 4920 return getFromTargetType(Target->getUIntMaxType()); 4921 } 4922 4923 /// getSignedWCharType - Return the type of "signed wchar_t". 4924 /// Used when in C++, as a GCC extension. 4925 QualType ASTContext::getSignedWCharType() const { 4926 // FIXME: derive from "Target" ? 4927 return WCharTy; 4928 } 4929 4930 /// getUnsignedWCharType - Return the type of "unsigned wchar_t". 4931 /// Used when in C++, as a GCC extension. 4932 QualType ASTContext::getUnsignedWCharType() const { 4933 // FIXME: derive from "Target" ? 4934 return UnsignedIntTy; 4935 } 4936 4937 QualType ASTContext::getIntPtrType() const { 4938 return getFromTargetType(Target->getIntPtrType()); 4939 } 4940 4941 QualType ASTContext::getUIntPtrType() const { 4942 return getCorrespondingUnsignedType(getIntPtrType()); 4943 } 4944 4945 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 4946 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 4947 QualType ASTContext::getPointerDiffType() const { 4948 return getFromTargetType(Target->getPtrDiffType(0)); 4949 } 4950 4951 /// Return the unique unsigned counterpart of "ptrdiff_t" 4952 /// integer type. The standard (C11 7.21.6.1p7) refers to this type 4953 /// in the definition of %tu format specifier. 4954 QualType ASTContext::getUnsignedPointerDiffType() const { 4955 return getFromTargetType(Target->getUnsignedPtrDiffType(0)); 4956 } 4957 4958 /// Return the unique type for "pid_t" defined in 4959 /// <sys/types.h>. We need this to compute the correct type for vfork(). 4960 QualType ASTContext::getProcessIDType() const { 4961 return getFromTargetType(Target->getProcessIDType()); 4962 } 4963 4964 //===----------------------------------------------------------------------===// 4965 // Type Operators 4966 //===----------------------------------------------------------------------===// 4967 4968 CanQualType ASTContext::getCanonicalParamType(QualType T) const { 4969 // Push qualifiers into arrays, and then discard any remaining 4970 // qualifiers. 4971 T = getCanonicalType(T); 4972 T = getVariableArrayDecayedType(T); 4973 const Type *Ty = T.getTypePtr(); 4974 QualType Result; 4975 if (isa<ArrayType>(Ty)) { 4976 Result = getArrayDecayedType(QualType(Ty,0)); 4977 } else if (isa<FunctionType>(Ty)) { 4978 Result = getPointerType(QualType(Ty, 0)); 4979 } else { 4980 Result = QualType(Ty, 0); 4981 } 4982 4983 return CanQualType::CreateUnsafe(Result); 4984 } 4985 4986 QualType ASTContext::getUnqualifiedArrayType(QualType type, 4987 Qualifiers &quals) { 4988 SplitQualType splitType = type.getSplitUnqualifiedType(); 4989 4990 // FIXME: getSplitUnqualifiedType() actually walks all the way to 4991 // the unqualified desugared type and then drops it on the floor. 4992 // We then have to strip that sugar back off with 4993 // getUnqualifiedDesugaredType(), which is silly. 4994 const auto *AT = 4995 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 4996 4997 // If we don't have an array, just use the results in splitType. 4998 if (!AT) { 4999 quals = splitType.Quals; 5000 return QualType(splitType.Ty, 0); 5001 } 5002 5003 // Otherwise, recurse on the array's element type. 5004 QualType elementType = AT->getElementType(); 5005 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 5006 5007 // If that didn't change the element type, AT has no qualifiers, so we 5008 // can just use the results in splitType. 5009 if (elementType == unqualElementType) { 5010 assert(quals.empty()); // from the recursive call 5011 quals = splitType.Quals; 5012 return QualType(splitType.Ty, 0); 5013 } 5014 5015 // Otherwise, add in the qualifiers from the outermost type, then 5016 // build the type back up. 5017 quals.addConsistentQualifiers(splitType.Quals); 5018 5019 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 5020 return getConstantArrayType(unqualElementType, CAT->getSize(), 5021 CAT->getSizeModifier(), 0); 5022 } 5023 5024 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) { 5025 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 5026 } 5027 5028 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) { 5029 return getVariableArrayType(unqualElementType, 5030 VAT->getSizeExpr(), 5031 VAT->getSizeModifier(), 5032 VAT->getIndexTypeCVRQualifiers(), 5033 VAT->getBracketsRange()); 5034 } 5035 5036 const auto *DSAT = cast<DependentSizedArrayType>(AT); 5037 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 5038 DSAT->getSizeModifier(), 0, 5039 SourceRange()); 5040 } 5041 5042 /// Attempt to unwrap two types that may both be array types with the same bound 5043 /// (or both be array types of unknown bound) for the purpose of comparing the 5044 /// cv-decomposition of two types per C++ [conv.qual]. 5045 bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) { 5046 bool UnwrappedAny = false; 5047 while (true) { 5048 auto *AT1 = getAsArrayType(T1); 5049 if (!AT1) return UnwrappedAny; 5050 5051 auto *AT2 = getAsArrayType(T2); 5052 if (!AT2) return UnwrappedAny; 5053 5054 // If we don't have two array types with the same constant bound nor two 5055 // incomplete array types, we've unwrapped everything we can. 5056 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) { 5057 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2); 5058 if (!CAT2 || CAT1->getSize() != CAT2->getSize()) 5059 return UnwrappedAny; 5060 } else if (!isa<IncompleteArrayType>(AT1) || 5061 !isa<IncompleteArrayType>(AT2)) { 5062 return UnwrappedAny; 5063 } 5064 5065 T1 = AT1->getElementType(); 5066 T2 = AT2->getElementType(); 5067 UnwrappedAny = true; 5068 } 5069 } 5070 5071 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]). 5072 /// 5073 /// If T1 and T2 are both pointer types of the same kind, or both array types 5074 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is 5075 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored. 5076 /// 5077 /// This function will typically be called in a loop that successively 5078 /// "unwraps" pointer and pointer-to-member types to compare them at each 5079 /// level. 5080 /// 5081 /// \return \c true if a pointer type was unwrapped, \c false if we reached a 5082 /// pair of types that can't be unwrapped further. 5083 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) { 5084 UnwrapSimilarArrayTypes(T1, T2); 5085 5086 const auto *T1PtrType = T1->getAs<PointerType>(); 5087 const auto *T2PtrType = T2->getAs<PointerType>(); 5088 if (T1PtrType && T2PtrType) { 5089 T1 = T1PtrType->getPointeeType(); 5090 T2 = T2PtrType->getPointeeType(); 5091 return true; 5092 } 5093 5094 const auto *T1MPType = T1->getAs<MemberPointerType>(); 5095 const auto *T2MPType = T2->getAs<MemberPointerType>(); 5096 if (T1MPType && T2MPType && 5097 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 5098 QualType(T2MPType->getClass(), 0))) { 5099 T1 = T1MPType->getPointeeType(); 5100 T2 = T2MPType->getPointeeType(); 5101 return true; 5102 } 5103 5104 if (getLangOpts().ObjC1) { 5105 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>(); 5106 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>(); 5107 if (T1OPType && T2OPType) { 5108 T1 = T1OPType->getPointeeType(); 5109 T2 = T2OPType->getPointeeType(); 5110 return true; 5111 } 5112 } 5113 5114 // FIXME: Block pointers, too? 5115 5116 return false; 5117 } 5118 5119 bool ASTContext::hasSimilarType(QualType T1, QualType T2) { 5120 while (true) { 5121 Qualifiers Quals; 5122 T1 = getUnqualifiedArrayType(T1, Quals); 5123 T2 = getUnqualifiedArrayType(T2, Quals); 5124 if (hasSameType(T1, T2)) 5125 return true; 5126 if (!UnwrapSimilarTypes(T1, T2)) 5127 return false; 5128 } 5129 } 5130 5131 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) { 5132 while (true) { 5133 Qualifiers Quals1, Quals2; 5134 T1 = getUnqualifiedArrayType(T1, Quals1); 5135 T2 = getUnqualifiedArrayType(T2, Quals2); 5136 5137 Quals1.removeCVRQualifiers(); 5138 Quals2.removeCVRQualifiers(); 5139 if (Quals1 != Quals2) 5140 return false; 5141 5142 if (hasSameType(T1, T2)) 5143 return true; 5144 5145 if (!UnwrapSimilarTypes(T1, T2)) 5146 return false; 5147 } 5148 } 5149 5150 DeclarationNameInfo 5151 ASTContext::getNameForTemplate(TemplateName Name, 5152 SourceLocation NameLoc) const { 5153 switch (Name.getKind()) { 5154 case TemplateName::QualifiedTemplate: 5155 case TemplateName::Template: 5156 // DNInfo work in progress: CHECKME: what about DNLoc? 5157 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 5158 NameLoc); 5159 5160 case TemplateName::OverloadedTemplate: { 5161 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 5162 // DNInfo work in progress: CHECKME: what about DNLoc? 5163 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 5164 } 5165 5166 case TemplateName::DependentTemplate: { 5167 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 5168 DeclarationName DName; 5169 if (DTN->isIdentifier()) { 5170 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 5171 return DeclarationNameInfo(DName, NameLoc); 5172 } else { 5173 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 5174 // DNInfo work in progress: FIXME: source locations? 5175 DeclarationNameLoc DNLoc; 5176 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding(); 5177 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding(); 5178 return DeclarationNameInfo(DName, NameLoc, DNLoc); 5179 } 5180 } 5181 5182 case TemplateName::SubstTemplateTemplateParm: { 5183 SubstTemplateTemplateParmStorage *subst 5184 = Name.getAsSubstTemplateTemplateParm(); 5185 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 5186 NameLoc); 5187 } 5188 5189 case TemplateName::SubstTemplateTemplateParmPack: { 5190 SubstTemplateTemplateParmPackStorage *subst 5191 = Name.getAsSubstTemplateTemplateParmPack(); 5192 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 5193 NameLoc); 5194 } 5195 } 5196 5197 llvm_unreachable("bad template name kind!"); 5198 } 5199 5200 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { 5201 switch (Name.getKind()) { 5202 case TemplateName::QualifiedTemplate: 5203 case TemplateName::Template: { 5204 TemplateDecl *Template = Name.getAsTemplateDecl(); 5205 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template)) 5206 Template = getCanonicalTemplateTemplateParmDecl(TTP); 5207 5208 // The canonical template name is the canonical template declaration. 5209 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 5210 } 5211 5212 case TemplateName::OverloadedTemplate: 5213 llvm_unreachable("cannot canonicalize overloaded template"); 5214 5215 case TemplateName::DependentTemplate: { 5216 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 5217 assert(DTN && "Non-dependent template names must refer to template decls."); 5218 return DTN->CanonicalTemplateName; 5219 } 5220 5221 case TemplateName::SubstTemplateTemplateParm: { 5222 SubstTemplateTemplateParmStorage *subst 5223 = Name.getAsSubstTemplateTemplateParm(); 5224 return getCanonicalTemplateName(subst->getReplacement()); 5225 } 5226 5227 case TemplateName::SubstTemplateTemplateParmPack: { 5228 SubstTemplateTemplateParmPackStorage *subst 5229 = Name.getAsSubstTemplateTemplateParmPack(); 5230 TemplateTemplateParmDecl *canonParameter 5231 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 5232 TemplateArgument canonArgPack 5233 = getCanonicalTemplateArgument(subst->getArgumentPack()); 5234 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 5235 } 5236 } 5237 5238 llvm_unreachable("bad template name!"); 5239 } 5240 5241 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 5242 X = getCanonicalTemplateName(X); 5243 Y = getCanonicalTemplateName(Y); 5244 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 5245 } 5246 5247 TemplateArgument 5248 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 5249 switch (Arg.getKind()) { 5250 case TemplateArgument::Null: 5251 return Arg; 5252 5253 case TemplateArgument::Expression: 5254 return Arg; 5255 5256 case TemplateArgument::Declaration: { 5257 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); 5258 return TemplateArgument(D, Arg.getParamTypeForDecl()); 5259 } 5260 5261 case TemplateArgument::NullPtr: 5262 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), 5263 /*isNullPtr*/true); 5264 5265 case TemplateArgument::Template: 5266 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 5267 5268 case TemplateArgument::TemplateExpansion: 5269 return TemplateArgument(getCanonicalTemplateName( 5270 Arg.getAsTemplateOrTemplatePattern()), 5271 Arg.getNumTemplateExpansions()); 5272 5273 case TemplateArgument::Integral: 5274 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 5275 5276 case TemplateArgument::Type: 5277 return TemplateArgument(getCanonicalType(Arg.getAsType())); 5278 5279 case TemplateArgument::Pack: { 5280 if (Arg.pack_size() == 0) 5281 return Arg; 5282 5283 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()]; 5284 unsigned Idx = 0; 5285 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 5286 AEnd = Arg.pack_end(); 5287 A != AEnd; (void)++A, ++Idx) 5288 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 5289 5290 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size())); 5291 } 5292 } 5293 5294 // Silence GCC warning 5295 llvm_unreachable("Unhandled template argument kind"); 5296 } 5297 5298 NestedNameSpecifier * 5299 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 5300 if (!NNS) 5301 return nullptr; 5302 5303 switch (NNS->getKind()) { 5304 case NestedNameSpecifier::Identifier: 5305 // Canonicalize the prefix but keep the identifier the same. 5306 return NestedNameSpecifier::Create(*this, 5307 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 5308 NNS->getAsIdentifier()); 5309 5310 case NestedNameSpecifier::Namespace: 5311 // A namespace is canonical; build a nested-name-specifier with 5312 // this namespace and no prefix. 5313 return NestedNameSpecifier::Create(*this, nullptr, 5314 NNS->getAsNamespace()->getOriginalNamespace()); 5315 5316 case NestedNameSpecifier::NamespaceAlias: 5317 // A namespace is canonical; build a nested-name-specifier with 5318 // this namespace and no prefix. 5319 return NestedNameSpecifier::Create(*this, nullptr, 5320 NNS->getAsNamespaceAlias()->getNamespace() 5321 ->getOriginalNamespace()); 5322 5323 case NestedNameSpecifier::TypeSpec: 5324 case NestedNameSpecifier::TypeSpecWithTemplate: { 5325 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 5326 5327 // If we have some kind of dependent-named type (e.g., "typename T::type"), 5328 // break it apart into its prefix and identifier, then reconsititute those 5329 // as the canonical nested-name-specifier. This is required to canonicalize 5330 // a dependent nested-name-specifier involving typedefs of dependent-name 5331 // types, e.g., 5332 // typedef typename T::type T1; 5333 // typedef typename T1::type T2; 5334 if (const auto *DNT = T->getAs<DependentNameType>()) 5335 return NestedNameSpecifier::Create(*this, DNT->getQualifier(), 5336 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 5337 5338 // Otherwise, just canonicalize the type, and force it to be a TypeSpec. 5339 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the 5340 // first place? 5341 return NestedNameSpecifier::Create(*this, nullptr, false, 5342 const_cast<Type *>(T.getTypePtr())); 5343 } 5344 5345 case NestedNameSpecifier::Global: 5346 case NestedNameSpecifier::Super: 5347 // The global specifier and __super specifer are canonical and unique. 5348 return NNS; 5349 } 5350 5351 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 5352 } 5353 5354 const ArrayType *ASTContext::getAsArrayType(QualType T) const { 5355 // Handle the non-qualified case efficiently. 5356 if (!T.hasLocalQualifiers()) { 5357 // Handle the common positive case fast. 5358 if (const auto *AT = dyn_cast<ArrayType>(T)) 5359 return AT; 5360 } 5361 5362 // Handle the common negative case fast. 5363 if (!isa<ArrayType>(T.getCanonicalType())) 5364 return nullptr; 5365 5366 // Apply any qualifiers from the array type to the element type. This 5367 // implements C99 6.7.3p8: "If the specification of an array type includes 5368 // any type qualifiers, the element type is so qualified, not the array type." 5369 5370 // If we get here, we either have type qualifiers on the type, or we have 5371 // sugar such as a typedef in the way. If we have type qualifiers on the type 5372 // we must propagate them down into the element type. 5373 5374 SplitQualType split = T.getSplitDesugaredType(); 5375 Qualifiers qs = split.Quals; 5376 5377 // If we have a simple case, just return now. 5378 const auto *ATy = dyn_cast<ArrayType>(split.Ty); 5379 if (!ATy || qs.empty()) 5380 return ATy; 5381 5382 // Otherwise, we have an array and we have qualifiers on it. Push the 5383 // qualifiers into the array element type and return a new array type. 5384 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 5385 5386 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy)) 5387 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 5388 CAT->getSizeModifier(), 5389 CAT->getIndexTypeCVRQualifiers())); 5390 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy)) 5391 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 5392 IAT->getSizeModifier(), 5393 IAT->getIndexTypeCVRQualifiers())); 5394 5395 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy)) 5396 return cast<ArrayType>( 5397 getDependentSizedArrayType(NewEltTy, 5398 DSAT->getSizeExpr(), 5399 DSAT->getSizeModifier(), 5400 DSAT->getIndexTypeCVRQualifiers(), 5401 DSAT->getBracketsRange())); 5402 5403 const auto *VAT = cast<VariableArrayType>(ATy); 5404 return cast<ArrayType>(getVariableArrayType(NewEltTy, 5405 VAT->getSizeExpr(), 5406 VAT->getSizeModifier(), 5407 VAT->getIndexTypeCVRQualifiers(), 5408 VAT->getBracketsRange())); 5409 } 5410 5411 QualType ASTContext::getAdjustedParameterType(QualType T) const { 5412 if (T->isArrayType() || T->isFunctionType()) 5413 return getDecayedType(T); 5414 return T; 5415 } 5416 5417 QualType ASTContext::getSignatureParameterType(QualType T) const { 5418 T = getVariableArrayDecayedType(T); 5419 T = getAdjustedParameterType(T); 5420 return T.getUnqualifiedType(); 5421 } 5422 5423 QualType ASTContext::getExceptionObjectType(QualType T) const { 5424 // C++ [except.throw]p3: 5425 // A throw-expression initializes a temporary object, called the exception 5426 // object, the type of which is determined by removing any top-level 5427 // cv-qualifiers from the static type of the operand of throw and adjusting 5428 // the type from "array of T" or "function returning T" to "pointer to T" 5429 // or "pointer to function returning T", [...] 5430 T = getVariableArrayDecayedType(T); 5431 if (T->isArrayType() || T->isFunctionType()) 5432 T = getDecayedType(T); 5433 return T.getUnqualifiedType(); 5434 } 5435 5436 /// getArrayDecayedType - Return the properly qualified result of decaying the 5437 /// specified array type to a pointer. This operation is non-trivial when 5438 /// handling typedefs etc. The canonical type of "T" must be an array type, 5439 /// this returns a pointer to a properly qualified element of the array. 5440 /// 5441 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 5442 QualType ASTContext::getArrayDecayedType(QualType Ty) const { 5443 // Get the element type with 'getAsArrayType' so that we don't lose any 5444 // typedefs in the element type of the array. This also handles propagation 5445 // of type qualifiers from the array type into the element type if present 5446 // (C99 6.7.3p8). 5447 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 5448 assert(PrettyArrayType && "Not an array type!"); 5449 5450 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 5451 5452 // int x[restrict 4] -> int *restrict 5453 QualType Result = getQualifiedType(PtrTy, 5454 PrettyArrayType->getIndexTypeQualifiers()); 5455 5456 // int x[_Nullable] -> int * _Nullable 5457 if (auto Nullability = Ty->getNullability(*this)) { 5458 Result = const_cast<ASTContext *>(this)->getAttributedType( 5459 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result); 5460 } 5461 return Result; 5462 } 5463 5464 QualType ASTContext::getBaseElementType(const ArrayType *array) const { 5465 return getBaseElementType(array->getElementType()); 5466 } 5467 5468 QualType ASTContext::getBaseElementType(QualType type) const { 5469 Qualifiers qs; 5470 while (true) { 5471 SplitQualType split = type.getSplitDesugaredType(); 5472 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 5473 if (!array) break; 5474 5475 type = array->getElementType(); 5476 qs.addConsistentQualifiers(split.Quals); 5477 } 5478 5479 return getQualifiedType(type, qs); 5480 } 5481 5482 /// getConstantArrayElementCount - Returns number of constant array elements. 5483 uint64_t 5484 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 5485 uint64_t ElementCount = 1; 5486 do { 5487 ElementCount *= CA->getSize().getZExtValue(); 5488 CA = dyn_cast_or_null<ConstantArrayType>( 5489 CA->getElementType()->getAsArrayTypeUnsafe()); 5490 } while (CA); 5491 return ElementCount; 5492 } 5493 5494 /// getFloatingRank - Return a relative rank for floating point types. 5495 /// This routine will assert if passed a built-in type that isn't a float. 5496 static FloatingRank getFloatingRank(QualType T) { 5497 if (const auto *CT = T->getAs<ComplexType>()) 5498 return getFloatingRank(CT->getElementType()); 5499 5500 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type"); 5501 switch (T->getAs<BuiltinType>()->getKind()) { 5502 default: llvm_unreachable("getFloatingRank(): not a floating type"); 5503 case BuiltinType::Float16: return Float16Rank; 5504 case BuiltinType::Half: return HalfRank; 5505 case BuiltinType::Float: return FloatRank; 5506 case BuiltinType::Double: return DoubleRank; 5507 case BuiltinType::LongDouble: return LongDoubleRank; 5508 case BuiltinType::Float128: return Float128Rank; 5509 } 5510 } 5511 5512 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating 5513 /// point or a complex type (based on typeDomain/typeSize). 5514 /// 'typeDomain' is a real floating point or complex type. 5515 /// 'typeSize' is a real floating point or complex type. 5516 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 5517 QualType Domain) const { 5518 FloatingRank EltRank = getFloatingRank(Size); 5519 if (Domain->isComplexType()) { 5520 switch (EltRank) { 5521 case Float16Rank: 5522 case HalfRank: llvm_unreachable("Complex half is not supported"); 5523 case FloatRank: return FloatComplexTy; 5524 case DoubleRank: return DoubleComplexTy; 5525 case LongDoubleRank: return LongDoubleComplexTy; 5526 case Float128Rank: return Float128ComplexTy; 5527 } 5528 } 5529 5530 assert(Domain->isRealFloatingType() && "Unknown domain!"); 5531 switch (EltRank) { 5532 case Float16Rank: return HalfTy; 5533 case HalfRank: return HalfTy; 5534 case FloatRank: return FloatTy; 5535 case DoubleRank: return DoubleTy; 5536 case LongDoubleRank: return LongDoubleTy; 5537 case Float128Rank: return Float128Ty; 5538 } 5539 llvm_unreachable("getFloatingRank(): illegal value for rank"); 5540 } 5541 5542 /// getFloatingTypeOrder - Compare the rank of the two specified floating 5543 /// point types, ignoring the domain of the type (i.e. 'double' == 5544 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 5545 /// LHS < RHS, return -1. 5546 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 5547 FloatingRank LHSR = getFloatingRank(LHS); 5548 FloatingRank RHSR = getFloatingRank(RHS); 5549 5550 if (LHSR == RHSR) 5551 return 0; 5552 if (LHSR > RHSR) 5553 return 1; 5554 return -1; 5555 } 5556 5557 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 5558 /// routine will assert if passed a built-in type that isn't an integer or enum, 5559 /// or if it is not canonicalized. 5560 unsigned ASTContext::getIntegerRank(const Type *T) const { 5561 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 5562 5563 switch (cast<BuiltinType>(T)->getKind()) { 5564 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 5565 case BuiltinType::Bool: 5566 return 1 + (getIntWidth(BoolTy) << 3); 5567 case BuiltinType::Char_S: 5568 case BuiltinType::Char_U: 5569 case BuiltinType::SChar: 5570 case BuiltinType::UChar: 5571 return 2 + (getIntWidth(CharTy) << 3); 5572 case BuiltinType::Short: 5573 case BuiltinType::UShort: 5574 return 3 + (getIntWidth(ShortTy) << 3); 5575 case BuiltinType::Int: 5576 case BuiltinType::UInt: 5577 return 4 + (getIntWidth(IntTy) << 3); 5578 case BuiltinType::Long: 5579 case BuiltinType::ULong: 5580 return 5 + (getIntWidth(LongTy) << 3); 5581 case BuiltinType::LongLong: 5582 case BuiltinType::ULongLong: 5583 return 6 + (getIntWidth(LongLongTy) << 3); 5584 case BuiltinType::Int128: 5585 case BuiltinType::UInt128: 5586 return 7 + (getIntWidth(Int128Ty) << 3); 5587 } 5588 } 5589 5590 /// Whether this is a promotable bitfield reference according 5591 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 5592 /// 5593 /// \returns the type this bit-field will promote to, or NULL if no 5594 /// promotion occurs. 5595 QualType ASTContext::isPromotableBitField(Expr *E) const { 5596 if (E->isTypeDependent() || E->isValueDependent()) 5597 return {}; 5598 5599 // C++ [conv.prom]p5: 5600 // If the bit-field has an enumerated type, it is treated as any other 5601 // value of that type for promotion purposes. 5602 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType()) 5603 return {}; 5604 5605 // FIXME: We should not do this unless E->refersToBitField() is true. This 5606 // matters in C where getSourceBitField() will find bit-fields for various 5607 // cases where the source expression is not a bit-field designator. 5608 5609 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? 5610 if (!Field) 5611 return {}; 5612 5613 QualType FT = Field->getType(); 5614 5615 uint64_t BitWidth = Field->getBitWidthValue(*this); 5616 uint64_t IntSize = getTypeSize(IntTy); 5617 // C++ [conv.prom]p5: 5618 // A prvalue for an integral bit-field can be converted to a prvalue of type 5619 // int if int can represent all the values of the bit-field; otherwise, it 5620 // can be converted to unsigned int if unsigned int can represent all the 5621 // values of the bit-field. If the bit-field is larger yet, no integral 5622 // promotion applies to it. 5623 // C11 6.3.1.1/2: 5624 // [For a bit-field of type _Bool, int, signed int, or unsigned int:] 5625 // If an int can represent all values of the original type (as restricted by 5626 // the width, for a bit-field), the value is converted to an int; otherwise, 5627 // it is converted to an unsigned int. 5628 // 5629 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int. 5630 // We perform that promotion here to match GCC and C++. 5631 // FIXME: C does not permit promotion of an enum bit-field whose rank is 5632 // greater than that of 'int'. We perform that promotion to match GCC. 5633 if (BitWidth < IntSize) 5634 return IntTy; 5635 5636 if (BitWidth == IntSize) 5637 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 5638 5639 // Bit-fields wider than int are not subject to promotions, and therefore act 5640 // like the base type. GCC has some weird bugs in this area that we 5641 // deliberately do not follow (GCC follows a pre-standard resolution to 5642 // C's DR315 which treats bit-width as being part of the type, and this leaks 5643 // into their semantics in some cases). 5644 return {}; 5645 } 5646 5647 /// getPromotedIntegerType - Returns the type that Promotable will 5648 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 5649 /// integer type. 5650 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 5651 assert(!Promotable.isNull()); 5652 assert(Promotable->isPromotableIntegerType()); 5653 if (const auto *ET = Promotable->getAs<EnumType>()) 5654 return ET->getDecl()->getPromotionType(); 5655 5656 if (const auto *BT = Promotable->getAs<BuiltinType>()) { 5657 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 5658 // (3.9.1) can be converted to a prvalue of the first of the following 5659 // types that can represent all the values of its underlying type: 5660 // int, unsigned int, long int, unsigned long int, long long int, or 5661 // unsigned long long int [...] 5662 // FIXME: Is there some better way to compute this? 5663 if (BT->getKind() == BuiltinType::WChar_S || 5664 BT->getKind() == BuiltinType::WChar_U || 5665 BT->getKind() == BuiltinType::Char8 || 5666 BT->getKind() == BuiltinType::Char16 || 5667 BT->getKind() == BuiltinType::Char32) { 5668 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 5669 uint64_t FromSize = getTypeSize(BT); 5670 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 5671 LongLongTy, UnsignedLongLongTy }; 5672 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 5673 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 5674 if (FromSize < ToSize || 5675 (FromSize == ToSize && 5676 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 5677 return PromoteTypes[Idx]; 5678 } 5679 llvm_unreachable("char type should fit into long long"); 5680 } 5681 } 5682 5683 // At this point, we should have a signed or unsigned integer type. 5684 if (Promotable->isSignedIntegerType()) 5685 return IntTy; 5686 uint64_t PromotableSize = getIntWidth(Promotable); 5687 uint64_t IntSize = getIntWidth(IntTy); 5688 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 5689 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 5690 } 5691 5692 /// Recurses in pointer/array types until it finds an objc retainable 5693 /// type and returns its ownership. 5694 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 5695 while (!T.isNull()) { 5696 if (T.getObjCLifetime() != Qualifiers::OCL_None) 5697 return T.getObjCLifetime(); 5698 if (T->isArrayType()) 5699 T = getBaseElementType(T); 5700 else if (const auto *PT = T->getAs<PointerType>()) 5701 T = PT->getPointeeType(); 5702 else if (const auto *RT = T->getAs<ReferenceType>()) 5703 T = RT->getPointeeType(); 5704 else 5705 break; 5706 } 5707 5708 return Qualifiers::OCL_None; 5709 } 5710 5711 static const Type *getIntegerTypeForEnum(const EnumType *ET) { 5712 // Incomplete enum types are not treated as integer types. 5713 // FIXME: In C++, enum types are never integer types. 5714 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 5715 return ET->getDecl()->getIntegerType().getTypePtr(); 5716 return nullptr; 5717 } 5718 5719 /// getIntegerTypeOrder - Returns the highest ranked integer type: 5720 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 5721 /// LHS < RHS, return -1. 5722 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 5723 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 5724 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 5725 5726 // Unwrap enums to their underlying type. 5727 if (const auto *ET = dyn_cast<EnumType>(LHSC)) 5728 LHSC = getIntegerTypeForEnum(ET); 5729 if (const auto *ET = dyn_cast<EnumType>(RHSC)) 5730 RHSC = getIntegerTypeForEnum(ET); 5731 5732 if (LHSC == RHSC) return 0; 5733 5734 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 5735 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 5736 5737 unsigned LHSRank = getIntegerRank(LHSC); 5738 unsigned RHSRank = getIntegerRank(RHSC); 5739 5740 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 5741 if (LHSRank == RHSRank) return 0; 5742 return LHSRank > RHSRank ? 1 : -1; 5743 } 5744 5745 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 5746 if (LHSUnsigned) { 5747 // If the unsigned [LHS] type is larger, return it. 5748 if (LHSRank >= RHSRank) 5749 return 1; 5750 5751 // If the signed type can represent all values of the unsigned type, it 5752 // wins. Because we are dealing with 2's complement and types that are 5753 // powers of two larger than each other, this is always safe. 5754 return -1; 5755 } 5756 5757 // If the unsigned [RHS] type is larger, return it. 5758 if (RHSRank >= LHSRank) 5759 return -1; 5760 5761 // If the signed type can represent all values of the unsigned type, it 5762 // wins. Because we are dealing with 2's complement and types that are 5763 // powers of two larger than each other, this is always safe. 5764 return 1; 5765 } 5766 5767 TypedefDecl *ASTContext::getCFConstantStringDecl() const { 5768 if (!CFConstantStringTypeDecl) { 5769 assert(!CFConstantStringTagDecl && 5770 "tag and typedef should be initialized together"); 5771 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag"); 5772 CFConstantStringTagDecl->startDefinition(); 5773 5774 QualType FieldTypes[4]; 5775 const char *FieldNames[4]; 5776 5777 // const int *isa; 5778 FieldTypes[0] = getPointerType(IntTy.withConst()); 5779 FieldNames[0] = "isa"; 5780 // int flags; 5781 FieldTypes[1] = IntTy; 5782 FieldNames[1] = "flags"; 5783 // const char *str; 5784 FieldTypes[2] = getPointerType(CharTy.withConst()); 5785 FieldNames[2] = "str"; 5786 // long length; 5787 FieldTypes[3] = LongTy; 5788 FieldNames[3] = "length"; 5789 5790 // Create fields 5791 for (unsigned i = 0; i < 4; ++i) { 5792 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl, 5793 SourceLocation(), 5794 SourceLocation(), 5795 &Idents.get(FieldNames[i]), 5796 FieldTypes[i], /*TInfo=*/nullptr, 5797 /*BitWidth=*/nullptr, 5798 /*Mutable=*/false, 5799 ICIS_NoInit); 5800 Field->setAccess(AS_public); 5801 CFConstantStringTagDecl->addDecl(Field); 5802 } 5803 5804 CFConstantStringTagDecl->completeDefinition(); 5805 // This type is designed to be compatible with NSConstantString, but cannot 5806 // use the same name, since NSConstantString is an interface. 5807 auto tagType = getTagDeclType(CFConstantStringTagDecl); 5808 CFConstantStringTypeDecl = 5809 buildImplicitTypedef(tagType, "__NSConstantString"); 5810 } 5811 5812 return CFConstantStringTypeDecl; 5813 } 5814 5815 RecordDecl *ASTContext::getCFConstantStringTagDecl() const { 5816 if (!CFConstantStringTagDecl) 5817 getCFConstantStringDecl(); // Build the tag and the typedef. 5818 return CFConstantStringTagDecl; 5819 } 5820 5821 // getCFConstantStringType - Return the type used for constant CFStrings. 5822 QualType ASTContext::getCFConstantStringType() const { 5823 return getTypedefType(getCFConstantStringDecl()); 5824 } 5825 5826 QualType ASTContext::getObjCSuperType() const { 5827 if (ObjCSuperType.isNull()) { 5828 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super"); 5829 TUDecl->addDecl(ObjCSuperTypeDecl); 5830 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); 5831 } 5832 return ObjCSuperType; 5833 } 5834 5835 void ASTContext::setCFConstantStringType(QualType T) { 5836 const auto *TD = T->getAs<TypedefType>(); 5837 assert(TD && "Invalid CFConstantStringType"); 5838 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl()); 5839 const auto *TagType = 5840 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>(); 5841 assert(TagType && "Invalid CFConstantStringType"); 5842 CFConstantStringTagDecl = TagType->getDecl(); 5843 } 5844 5845 QualType ASTContext::getBlockDescriptorType() const { 5846 if (BlockDescriptorType) 5847 return getTagDeclType(BlockDescriptorType); 5848 5849 RecordDecl *RD; 5850 // FIXME: Needs the FlagAppleBlock bit. 5851 RD = buildImplicitRecord("__block_descriptor"); 5852 RD->startDefinition(); 5853 5854 QualType FieldTypes[] = { 5855 UnsignedLongTy, 5856 UnsignedLongTy, 5857 }; 5858 5859 static const char *const FieldNames[] = { 5860 "reserved", 5861 "Size" 5862 }; 5863 5864 for (size_t i = 0; i < 2; ++i) { 5865 FieldDecl *Field = FieldDecl::Create( 5866 *this, RD, SourceLocation(), SourceLocation(), 5867 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 5868 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 5869 Field->setAccess(AS_public); 5870 RD->addDecl(Field); 5871 } 5872 5873 RD->completeDefinition(); 5874 5875 BlockDescriptorType = RD; 5876 5877 return getTagDeclType(BlockDescriptorType); 5878 } 5879 5880 QualType ASTContext::getBlockDescriptorExtendedType() const { 5881 if (BlockDescriptorExtendedType) 5882 return getTagDeclType(BlockDescriptorExtendedType); 5883 5884 RecordDecl *RD; 5885 // FIXME: Needs the FlagAppleBlock bit. 5886 RD = buildImplicitRecord("__block_descriptor_withcopydispose"); 5887 RD->startDefinition(); 5888 5889 QualType FieldTypes[] = { 5890 UnsignedLongTy, 5891 UnsignedLongTy, 5892 getPointerType(VoidPtrTy), 5893 getPointerType(VoidPtrTy) 5894 }; 5895 5896 static const char *const FieldNames[] = { 5897 "reserved", 5898 "Size", 5899 "CopyFuncPtr", 5900 "DestroyFuncPtr" 5901 }; 5902 5903 for (size_t i = 0; i < 4; ++i) { 5904 FieldDecl *Field = FieldDecl::Create( 5905 *this, RD, SourceLocation(), SourceLocation(), 5906 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 5907 /*BitWidth=*/nullptr, 5908 /*Mutable=*/false, ICIS_NoInit); 5909 Field->setAccess(AS_public); 5910 RD->addDecl(Field); 5911 } 5912 5913 RD->completeDefinition(); 5914 5915 BlockDescriptorExtendedType = RD; 5916 return getTagDeclType(BlockDescriptorExtendedType); 5917 } 5918 5919 TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const { 5920 const auto *BT = dyn_cast<BuiltinType>(T); 5921 5922 if (!BT) { 5923 if (isa<PipeType>(T)) 5924 return TargetInfo::OCLTK_Pipe; 5925 5926 return TargetInfo::OCLTK_Default; 5927 } 5928 5929 switch (BT->getKind()) { 5930 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5931 case BuiltinType::Id: \ 5932 return TargetInfo::OCLTK_Image; 5933 #include "clang/Basic/OpenCLImageTypes.def" 5934 5935 case BuiltinType::OCLClkEvent: 5936 return TargetInfo::OCLTK_ClkEvent; 5937 5938 case BuiltinType::OCLEvent: 5939 return TargetInfo::OCLTK_Event; 5940 5941 case BuiltinType::OCLQueue: 5942 return TargetInfo::OCLTK_Queue; 5943 5944 case BuiltinType::OCLReserveID: 5945 return TargetInfo::OCLTK_ReserveID; 5946 5947 case BuiltinType::OCLSampler: 5948 return TargetInfo::OCLTK_Sampler; 5949 5950 default: 5951 return TargetInfo::OCLTK_Default; 5952 } 5953 } 5954 5955 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const { 5956 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)); 5957 } 5958 5959 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" 5960 /// requires copy/dispose. Note that this must match the logic 5961 /// in buildByrefHelpers. 5962 bool ASTContext::BlockRequiresCopying(QualType Ty, 5963 const VarDecl *D) { 5964 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { 5965 const Expr *copyExpr = getBlockVarCopyInits(D); 5966 if (!copyExpr && record->hasTrivialDestructor()) return false; 5967 5968 return true; 5969 } 5970 5971 // The block needs copy/destroy helpers if Ty is non-trivial to destructively 5972 // move or destroy. 5973 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType()) 5974 return true; 5975 5976 if (!Ty->isObjCRetainableType()) return false; 5977 5978 Qualifiers qs = Ty.getQualifiers(); 5979 5980 // If we have lifetime, that dominates. 5981 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { 5982 switch (lifetime) { 5983 case Qualifiers::OCL_None: llvm_unreachable("impossible"); 5984 5985 // These are just bits as far as the runtime is concerned. 5986 case Qualifiers::OCL_ExplicitNone: 5987 case Qualifiers::OCL_Autoreleasing: 5988 return false; 5989 5990 // These cases should have been taken care of when checking the type's 5991 // non-triviality. 5992 case Qualifiers::OCL_Weak: 5993 case Qualifiers::OCL_Strong: 5994 llvm_unreachable("impossible"); 5995 } 5996 llvm_unreachable("fell out of lifetime switch!"); 5997 } 5998 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || 5999 Ty->isObjCObjectPointerType()); 6000 } 6001 6002 bool ASTContext::getByrefLifetime(QualType Ty, 6003 Qualifiers::ObjCLifetime &LifeTime, 6004 bool &HasByrefExtendedLayout) const { 6005 if (!getLangOpts().ObjC1 || 6006 getLangOpts().getGC() != LangOptions::NonGC) 6007 return false; 6008 6009 HasByrefExtendedLayout = false; 6010 if (Ty->isRecordType()) { 6011 HasByrefExtendedLayout = true; 6012 LifeTime = Qualifiers::OCL_None; 6013 } else if ((LifeTime = Ty.getObjCLifetime())) { 6014 // Honor the ARC qualifiers. 6015 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) { 6016 // The MRR rule. 6017 LifeTime = Qualifiers::OCL_ExplicitNone; 6018 } else { 6019 LifeTime = Qualifiers::OCL_None; 6020 } 6021 return true; 6022 } 6023 6024 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 6025 if (!ObjCInstanceTypeDecl) 6026 ObjCInstanceTypeDecl = 6027 buildImplicitTypedef(getObjCIdType(), "instancetype"); 6028 return ObjCInstanceTypeDecl; 6029 } 6030 6031 // This returns true if a type has been typedefed to BOOL: 6032 // typedef <type> BOOL; 6033 static bool isTypeTypedefedAsBOOL(QualType T) { 6034 if (const auto *TT = dyn_cast<TypedefType>(T)) 6035 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 6036 return II->isStr("BOOL"); 6037 6038 return false; 6039 } 6040 6041 /// getObjCEncodingTypeSize returns size of type for objective-c encoding 6042 /// purpose. 6043 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 6044 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 6045 return CharUnits::Zero(); 6046 6047 CharUnits sz = getTypeSizeInChars(type); 6048 6049 // Make all integer and enum types at least as large as an int 6050 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 6051 sz = std::max(sz, getTypeSizeInChars(IntTy)); 6052 // Treat arrays as pointers, since that's how they're passed in. 6053 else if (type->isArrayType()) 6054 sz = getTypeSizeInChars(VoidPtrTy); 6055 return sz; 6056 } 6057 6058 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { 6059 return getTargetInfo().getCXXABI().isMicrosoft() && 6060 VD->isStaticDataMember() && 6061 VD->getType()->isIntegralOrEnumerationType() && 6062 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit(); 6063 } 6064 6065 ASTContext::InlineVariableDefinitionKind 6066 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const { 6067 if (!VD->isInline()) 6068 return InlineVariableDefinitionKind::None; 6069 6070 // In almost all cases, it's a weak definition. 6071 auto *First = VD->getFirstDecl(); 6072 if (First->isInlineSpecified() || !First->isStaticDataMember()) 6073 return InlineVariableDefinitionKind::Weak; 6074 6075 // If there's a file-context declaration in this translation unit, it's a 6076 // non-discardable definition. 6077 for (auto *D : VD->redecls()) 6078 if (D->getLexicalDeclContext()->isFileContext() && 6079 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr())) 6080 return InlineVariableDefinitionKind::Strong; 6081 6082 // If we've not seen one yet, we don't know. 6083 return InlineVariableDefinitionKind::WeakUnknown; 6084 } 6085 6086 static std::string charUnitsToString(const CharUnits &CU) { 6087 return llvm::itostr(CU.getQuantity()); 6088 } 6089 6090 /// getObjCEncodingForBlock - Return the encoded type for this block 6091 /// declaration. 6092 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 6093 std::string S; 6094 6095 const BlockDecl *Decl = Expr->getBlockDecl(); 6096 QualType BlockTy = 6097 Expr->getType()->getAs<BlockPointerType>()->getPointeeType(); 6098 // Encode result type. 6099 if (getLangOpts().EncodeExtendedBlockSig) 6100 getObjCEncodingForMethodParameter( 6101 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S, 6102 true /*Extended*/); 6103 else 6104 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S); 6105 // Compute size of all parameters. 6106 // Start with computing size of a pointer in number of bytes. 6107 // FIXME: There might(should) be a better way of doing this computation! 6108 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 6109 CharUnits ParmOffset = PtrSize; 6110 for (auto PI : Decl->parameters()) { 6111 QualType PType = PI->getType(); 6112 CharUnits sz = getObjCEncodingTypeSize(PType); 6113 if (sz.isZero()) 6114 continue; 6115 assert(sz.isPositive() && "BlockExpr - Incomplete param type"); 6116 ParmOffset += sz; 6117 } 6118 // Size of the argument frame 6119 S += charUnitsToString(ParmOffset); 6120 // Block pointer and offset. 6121 S += "@?0"; 6122 6123 // Argument types. 6124 ParmOffset = PtrSize; 6125 for (auto PVDecl : Decl->parameters()) { 6126 QualType PType = PVDecl->getOriginalType(); 6127 if (const auto *AT = 6128 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 6129 // Use array's original type only if it has known number of 6130 // elements. 6131 if (!isa<ConstantArrayType>(AT)) 6132 PType = PVDecl->getType(); 6133 } else if (PType->isFunctionType()) 6134 PType = PVDecl->getType(); 6135 if (getLangOpts().EncodeExtendedBlockSig) 6136 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, 6137 S, true /*Extended*/); 6138 else 6139 getObjCEncodingForType(PType, S); 6140 S += charUnitsToString(ParmOffset); 6141 ParmOffset += getObjCEncodingTypeSize(PType); 6142 } 6143 6144 return S; 6145 } 6146 6147 std::string 6148 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { 6149 std::string S; 6150 // Encode result type. 6151 getObjCEncodingForType(Decl->getReturnType(), S); 6152 CharUnits ParmOffset; 6153 // Compute size of all parameters. 6154 for (auto PI : Decl->parameters()) { 6155 QualType PType = PI->getType(); 6156 CharUnits sz = getObjCEncodingTypeSize(PType); 6157 if (sz.isZero()) 6158 continue; 6159 6160 assert(sz.isPositive() && 6161 "getObjCEncodingForFunctionDecl - Incomplete param type"); 6162 ParmOffset += sz; 6163 } 6164 S += charUnitsToString(ParmOffset); 6165 ParmOffset = CharUnits::Zero(); 6166 6167 // Argument types. 6168 for (auto PVDecl : Decl->parameters()) { 6169 QualType PType = PVDecl->getOriginalType(); 6170 if (const auto *AT = 6171 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 6172 // Use array's original type only if it has known number of 6173 // elements. 6174 if (!isa<ConstantArrayType>(AT)) 6175 PType = PVDecl->getType(); 6176 } else if (PType->isFunctionType()) 6177 PType = PVDecl->getType(); 6178 getObjCEncodingForType(PType, S); 6179 S += charUnitsToString(ParmOffset); 6180 ParmOffset += getObjCEncodingTypeSize(PType); 6181 } 6182 6183 return S; 6184 } 6185 6186 /// getObjCEncodingForMethodParameter - Return the encoded type for a single 6187 /// method parameter or return type. If Extended, include class names and 6188 /// block object types. 6189 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 6190 QualType T, std::string& S, 6191 bool Extended) const { 6192 // Encode type qualifer, 'in', 'inout', etc. for the parameter. 6193 getObjCEncodingForTypeQualifier(QT, S); 6194 // Encode parameter type. 6195 getObjCEncodingForTypeImpl(T, S, true, true, nullptr, 6196 true /*OutermostType*/, 6197 false /*EncodingProperty*/, 6198 false /*StructField*/, 6199 Extended /*EncodeBlockParameters*/, 6200 Extended /*EncodeClassNames*/); 6201 } 6202 6203 /// getObjCEncodingForMethodDecl - Return the encoded type for this method 6204 /// declaration. 6205 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 6206 bool Extended) const { 6207 // FIXME: This is not very efficient. 6208 // Encode return type. 6209 std::string S; 6210 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 6211 Decl->getReturnType(), S, Extended); 6212 // Compute size of all parameters. 6213 // Start with computing size of a pointer in number of bytes. 6214 // FIXME: There might(should) be a better way of doing this computation! 6215 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 6216 // The first two arguments (self and _cmd) are pointers; account for 6217 // their size. 6218 CharUnits ParmOffset = 2 * PtrSize; 6219 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 6220 E = Decl->sel_param_end(); PI != E; ++PI) { 6221 QualType PType = (*PI)->getType(); 6222 CharUnits sz = getObjCEncodingTypeSize(PType); 6223 if (sz.isZero()) 6224 continue; 6225 6226 assert(sz.isPositive() && 6227 "getObjCEncodingForMethodDecl - Incomplete param type"); 6228 ParmOffset += sz; 6229 } 6230 S += charUnitsToString(ParmOffset); 6231 S += "@0:"; 6232 S += charUnitsToString(PtrSize); 6233 6234 // Argument types. 6235 ParmOffset = 2 * PtrSize; 6236 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 6237 E = Decl->sel_param_end(); PI != E; ++PI) { 6238 const ParmVarDecl *PVDecl = *PI; 6239 QualType PType = PVDecl->getOriginalType(); 6240 if (const auto *AT = 6241 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 6242 // Use array's original type only if it has known number of 6243 // elements. 6244 if (!isa<ConstantArrayType>(AT)) 6245 PType = PVDecl->getType(); 6246 } else if (PType->isFunctionType()) 6247 PType = PVDecl->getType(); 6248 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 6249 PType, S, Extended); 6250 S += charUnitsToString(ParmOffset); 6251 ParmOffset += getObjCEncodingTypeSize(PType); 6252 } 6253 6254 return S; 6255 } 6256 6257 ObjCPropertyImplDecl * 6258 ASTContext::getObjCPropertyImplDeclForPropertyDecl( 6259 const ObjCPropertyDecl *PD, 6260 const Decl *Container) const { 6261 if (!Container) 6262 return nullptr; 6263 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) { 6264 for (auto *PID : CID->property_impls()) 6265 if (PID->getPropertyDecl() == PD) 6266 return PID; 6267 } else { 6268 const auto *OID = cast<ObjCImplementationDecl>(Container); 6269 for (auto *PID : OID->property_impls()) 6270 if (PID->getPropertyDecl() == PD) 6271 return PID; 6272 } 6273 return nullptr; 6274 } 6275 6276 /// getObjCEncodingForPropertyDecl - Return the encoded type for this 6277 /// property declaration. If non-NULL, Container must be either an 6278 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 6279 /// NULL when getting encodings for protocol properties. 6280 /// Property attributes are stored as a comma-delimited C string. The simple 6281 /// attributes readonly and bycopy are encoded as single characters. The 6282 /// parametrized attributes, getter=name, setter=name, and ivar=name, are 6283 /// encoded as single characters, followed by an identifier. Property types 6284 /// are also encoded as a parametrized attribute. The characters used to encode 6285 /// these attributes are defined by the following enumeration: 6286 /// @code 6287 /// enum PropertyAttributes { 6288 /// kPropertyReadOnly = 'R', // property is read-only. 6289 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned 6290 /// kPropertyByref = '&', // property is a reference to the value last assigned 6291 /// kPropertyDynamic = 'D', // property is dynamic 6292 /// kPropertyGetter = 'G', // followed by getter selector name 6293 /// kPropertySetter = 'S', // followed by setter selector name 6294 /// kPropertyInstanceVariable = 'V' // followed by instance variable name 6295 /// kPropertyType = 'T' // followed by old-style type encoding. 6296 /// kPropertyWeak = 'W' // 'weak' property 6297 /// kPropertyStrong = 'P' // property GC'able 6298 /// kPropertyNonAtomic = 'N' // property non-atomic 6299 /// }; 6300 /// @endcode 6301 std::string 6302 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 6303 const Decl *Container) const { 6304 // Collect information from the property implementation decl(s). 6305 bool Dynamic = false; 6306 ObjCPropertyImplDecl *SynthesizePID = nullptr; 6307 6308 if (ObjCPropertyImplDecl *PropertyImpDecl = 6309 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { 6310 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 6311 Dynamic = true; 6312 else 6313 SynthesizePID = PropertyImpDecl; 6314 } 6315 6316 // FIXME: This is not very efficient. 6317 std::string S = "T"; 6318 6319 // Encode result type. 6320 // GCC has some special rules regarding encoding of properties which 6321 // closely resembles encoding of ivars. 6322 getObjCEncodingForPropertyType(PD->getType(), S); 6323 6324 if (PD->isReadOnly()) { 6325 S += ",R"; 6326 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) 6327 S += ",C"; 6328 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) 6329 S += ",&"; 6330 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak) 6331 S += ",W"; 6332 } else { 6333 switch (PD->getSetterKind()) { 6334 case ObjCPropertyDecl::Assign: break; 6335 case ObjCPropertyDecl::Copy: S += ",C"; break; 6336 case ObjCPropertyDecl::Retain: S += ",&"; break; 6337 case ObjCPropertyDecl::Weak: S += ",W"; break; 6338 } 6339 } 6340 6341 // It really isn't clear at all what this means, since properties 6342 // are "dynamic by default". 6343 if (Dynamic) 6344 S += ",D"; 6345 6346 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 6347 S += ",N"; 6348 6349 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 6350 S += ",G"; 6351 S += PD->getGetterName().getAsString(); 6352 } 6353 6354 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 6355 S += ",S"; 6356 S += PD->getSetterName().getAsString(); 6357 } 6358 6359 if (SynthesizePID) { 6360 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 6361 S += ",V"; 6362 S += OID->getNameAsString(); 6363 } 6364 6365 // FIXME: OBJCGC: weak & strong 6366 return S; 6367 } 6368 6369 /// getLegacyIntegralTypeEncoding - 6370 /// Another legacy compatibility encoding: 32-bit longs are encoded as 6371 /// 'l' or 'L' , but not always. For typedefs, we need to use 6372 /// 'i' or 'I' instead if encoding a struct field, or a pointer! 6373 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 6374 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 6375 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) { 6376 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 6377 PointeeTy = UnsignedIntTy; 6378 else 6379 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 6380 PointeeTy = IntTy; 6381 } 6382 } 6383 } 6384 6385 void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 6386 const FieldDecl *Field, 6387 QualType *NotEncodedT) const { 6388 // We follow the behavior of gcc, expanding structures which are 6389 // directly pointed to, and expanding embedded structures. Note that 6390 // these rules are sufficient to prevent recursive encoding of the 6391 // same type. 6392 getObjCEncodingForTypeImpl(T, S, true, true, Field, 6393 true /* outermost type */, false, false, 6394 false, false, false, NotEncodedT); 6395 } 6396 6397 void ASTContext::getObjCEncodingForPropertyType(QualType T, 6398 std::string& S) const { 6399 // Encode result type. 6400 // GCC has some special rules regarding encoding of properties which 6401 // closely resembles encoding of ivars. 6402 getObjCEncodingForTypeImpl(T, S, true, true, nullptr, 6403 true /* outermost type */, 6404 true /* encoding property */); 6405 } 6406 6407 static char getObjCEncodingForPrimitiveKind(const ASTContext *C, 6408 BuiltinType::Kind kind) { 6409 switch (kind) { 6410 case BuiltinType::Void: return 'v'; 6411 case BuiltinType::Bool: return 'B'; 6412 case BuiltinType::Char8: 6413 case BuiltinType::Char_U: 6414 case BuiltinType::UChar: return 'C'; 6415 case BuiltinType::Char16: 6416 case BuiltinType::UShort: return 'S'; 6417 case BuiltinType::Char32: 6418 case BuiltinType::UInt: return 'I'; 6419 case BuiltinType::ULong: 6420 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; 6421 case BuiltinType::UInt128: return 'T'; 6422 case BuiltinType::ULongLong: return 'Q'; 6423 case BuiltinType::Char_S: 6424 case BuiltinType::SChar: return 'c'; 6425 case BuiltinType::Short: return 's'; 6426 case BuiltinType::WChar_S: 6427 case BuiltinType::WChar_U: 6428 case BuiltinType::Int: return 'i'; 6429 case BuiltinType::Long: 6430 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; 6431 case BuiltinType::LongLong: return 'q'; 6432 case BuiltinType::Int128: return 't'; 6433 case BuiltinType::Float: return 'f'; 6434 case BuiltinType::Double: return 'd'; 6435 case BuiltinType::LongDouble: return 'D'; 6436 case BuiltinType::NullPtr: return '*'; // like char* 6437 6438 case BuiltinType::Float16: 6439 case BuiltinType::Float128: 6440 case BuiltinType::Half: 6441 case BuiltinType::ShortAccum: 6442 case BuiltinType::Accum: 6443 case BuiltinType::LongAccum: 6444 case BuiltinType::UShortAccum: 6445 case BuiltinType::UAccum: 6446 case BuiltinType::ULongAccum: 6447 case BuiltinType::ShortFract: 6448 case BuiltinType::Fract: 6449 case BuiltinType::LongFract: 6450 case BuiltinType::UShortFract: 6451 case BuiltinType::UFract: 6452 case BuiltinType::ULongFract: 6453 case BuiltinType::SatShortAccum: 6454 case BuiltinType::SatAccum: 6455 case BuiltinType::SatLongAccum: 6456 case BuiltinType::SatUShortAccum: 6457 case BuiltinType::SatUAccum: 6458 case BuiltinType::SatULongAccum: 6459 case BuiltinType::SatShortFract: 6460 case BuiltinType::SatFract: 6461 case BuiltinType::SatLongFract: 6462 case BuiltinType::SatUShortFract: 6463 case BuiltinType::SatUFract: 6464 case BuiltinType::SatULongFract: 6465 // FIXME: potentially need @encodes for these! 6466 return ' '; 6467 6468 case BuiltinType::ObjCId: 6469 case BuiltinType::ObjCClass: 6470 case BuiltinType::ObjCSel: 6471 llvm_unreachable("@encoding ObjC primitive type"); 6472 6473 // OpenCL and placeholder types don't need @encodings. 6474 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6475 case BuiltinType::Id: 6476 #include "clang/Basic/OpenCLImageTypes.def" 6477 case BuiltinType::OCLEvent: 6478 case BuiltinType::OCLClkEvent: 6479 case BuiltinType::OCLQueue: 6480 case BuiltinType::OCLReserveID: 6481 case BuiltinType::OCLSampler: 6482 case BuiltinType::Dependent: 6483 #define BUILTIN_TYPE(KIND, ID) 6484 #define PLACEHOLDER_TYPE(KIND, ID) \ 6485 case BuiltinType::KIND: 6486 #include "clang/AST/BuiltinTypes.def" 6487 llvm_unreachable("invalid builtin type for @encode"); 6488 } 6489 llvm_unreachable("invalid BuiltinType::Kind value"); 6490 } 6491 6492 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 6493 EnumDecl *Enum = ET->getDecl(); 6494 6495 // The encoding of an non-fixed enum type is always 'i', regardless of size. 6496 if (!Enum->isFixed()) 6497 return 'i'; 6498 6499 // The encoding of a fixed enum type matches its fixed underlying type. 6500 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>(); 6501 return getObjCEncodingForPrimitiveKind(C, BT->getKind()); 6502 } 6503 6504 static void EncodeBitField(const ASTContext *Ctx, std::string& S, 6505 QualType T, const FieldDecl *FD) { 6506 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 6507 S += 'b'; 6508 // The NeXT runtime encodes bit fields as b followed by the number of bits. 6509 // The GNU runtime requires more information; bitfields are encoded as b, 6510 // then the offset (in bits) of the first element, then the type of the 6511 // bitfield, then the size in bits. For example, in this structure: 6512 // 6513 // struct 6514 // { 6515 // int integer; 6516 // int flags:2; 6517 // }; 6518 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 6519 // runtime, but b32i2 for the GNU runtime. The reason for this extra 6520 // information is not especially sensible, but we're stuck with it for 6521 // compatibility with GCC, although providing it breaks anything that 6522 // actually uses runtime introspection and wants to work on both runtimes... 6523 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 6524 uint64_t Offset; 6525 6526 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) { 6527 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr, 6528 IVD); 6529 } else { 6530 const RecordDecl *RD = FD->getParent(); 6531 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 6532 Offset = RL.getFieldOffset(FD->getFieldIndex()); 6533 } 6534 6535 S += llvm::utostr(Offset); 6536 6537 if (const auto *ET = T->getAs<EnumType>()) 6538 S += ObjCEncodingForEnumType(Ctx, ET); 6539 else { 6540 const auto *BT = T->castAs<BuiltinType>(); 6541 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind()); 6542 } 6543 } 6544 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 6545 } 6546 6547 // FIXME: Use SmallString for accumulating string. 6548 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 6549 bool ExpandPointedToStructures, 6550 bool ExpandStructures, 6551 const FieldDecl *FD, 6552 bool OutermostType, 6553 bool EncodingProperty, 6554 bool StructField, 6555 bool EncodeBlockParameters, 6556 bool EncodeClassNames, 6557 bool EncodePointerToObjCTypedef, 6558 QualType *NotEncodedT) const { 6559 CanQualType CT = getCanonicalType(T); 6560 switch (CT->getTypeClass()) { 6561 case Type::Builtin: 6562 case Type::Enum: 6563 if (FD && FD->isBitField()) 6564 return EncodeBitField(this, S, T, FD); 6565 if (const auto *BT = dyn_cast<BuiltinType>(CT)) 6566 S += getObjCEncodingForPrimitiveKind(this, BT->getKind()); 6567 else 6568 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); 6569 return; 6570 6571 case Type::Complex: { 6572 const auto *CT = T->castAs<ComplexType>(); 6573 S += 'j'; 6574 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr); 6575 return; 6576 } 6577 6578 case Type::Atomic: { 6579 const auto *AT = T->castAs<AtomicType>(); 6580 S += 'A'; 6581 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr); 6582 return; 6583 } 6584 6585 // encoding for pointer or reference types. 6586 case Type::Pointer: 6587 case Type::LValueReference: 6588 case Type::RValueReference: { 6589 QualType PointeeTy; 6590 if (isa<PointerType>(CT)) { 6591 const auto *PT = T->castAs<PointerType>(); 6592 if (PT->isObjCSelType()) { 6593 S += ':'; 6594 return; 6595 } 6596 PointeeTy = PT->getPointeeType(); 6597 } else { 6598 PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); 6599 } 6600 6601 bool isReadOnly = false; 6602 // For historical/compatibility reasons, the read-only qualifier of the 6603 // pointee gets emitted _before_ the '^'. The read-only qualifier of 6604 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 6605 // Also, do not emit the 'r' for anything but the outermost type! 6606 if (isa<TypedefType>(T.getTypePtr())) { 6607 if (OutermostType && T.isConstQualified()) { 6608 isReadOnly = true; 6609 S += 'r'; 6610 } 6611 } else if (OutermostType) { 6612 QualType P = PointeeTy; 6613 while (P->getAs<PointerType>()) 6614 P = P->getAs<PointerType>()->getPointeeType(); 6615 if (P.isConstQualified()) { 6616 isReadOnly = true; 6617 S += 'r'; 6618 } 6619 } 6620 if (isReadOnly) { 6621 // Another legacy compatibility encoding. Some ObjC qualifier and type 6622 // combinations need to be rearranged. 6623 // Rewrite "in const" from "nr" to "rn" 6624 if (StringRef(S).endswith("nr")) 6625 S.replace(S.end()-2, S.end(), "rn"); 6626 } 6627 6628 if (PointeeTy->isCharType()) { 6629 // char pointer types should be encoded as '*' unless it is a 6630 // type that has been typedef'd to 'BOOL'. 6631 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 6632 S += '*'; 6633 return; 6634 } 6635 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) { 6636 // GCC binary compat: Need to convert "struct objc_class *" to "#". 6637 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 6638 S += '#'; 6639 return; 6640 } 6641 // GCC binary compat: Need to convert "struct objc_object *" to "@". 6642 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 6643 S += '@'; 6644 return; 6645 } 6646 // fall through... 6647 } 6648 S += '^'; 6649 getLegacyIntegralTypeEncoding(PointeeTy); 6650 6651 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures, 6652 nullptr, false, false, false, false, false, false, 6653 NotEncodedT); 6654 return; 6655 } 6656 6657 case Type::ConstantArray: 6658 case Type::IncompleteArray: 6659 case Type::VariableArray: { 6660 const auto *AT = cast<ArrayType>(CT); 6661 6662 if (isa<IncompleteArrayType>(AT) && !StructField) { 6663 // Incomplete arrays are encoded as a pointer to the array element. 6664 S += '^'; 6665 6666 getObjCEncodingForTypeImpl(AT->getElementType(), S, 6667 false, ExpandStructures, FD); 6668 } else { 6669 S += '['; 6670 6671 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) 6672 S += llvm::utostr(CAT->getSize().getZExtValue()); 6673 else { 6674 //Variable length arrays are encoded as a regular array with 0 elements. 6675 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 6676 "Unknown array type!"); 6677 S += '0'; 6678 } 6679 6680 getObjCEncodingForTypeImpl(AT->getElementType(), S, 6681 false, ExpandStructures, FD, 6682 false, false, false, false, false, false, 6683 NotEncodedT); 6684 S += ']'; 6685 } 6686 return; 6687 } 6688 6689 case Type::FunctionNoProto: 6690 case Type::FunctionProto: 6691 S += '?'; 6692 return; 6693 6694 case Type::Record: { 6695 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); 6696 S += RDecl->isUnion() ? '(' : '{'; 6697 // Anonymous structures print as '?' 6698 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 6699 S += II->getName(); 6700 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 6701 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 6702 llvm::raw_string_ostream OS(S); 6703 printTemplateArgumentList(OS, TemplateArgs.asArray(), 6704 getPrintingPolicy()); 6705 } 6706 } else { 6707 S += '?'; 6708 } 6709 if (ExpandStructures) { 6710 S += '='; 6711 if (!RDecl->isUnion()) { 6712 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); 6713 } else { 6714 for (const auto *Field : RDecl->fields()) { 6715 if (FD) { 6716 S += '"'; 6717 S += Field->getNameAsString(); 6718 S += '"'; 6719 } 6720 6721 // Special case bit-fields. 6722 if (Field->isBitField()) { 6723 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 6724 Field); 6725 } else { 6726 QualType qt = Field->getType(); 6727 getLegacyIntegralTypeEncoding(qt); 6728 getObjCEncodingForTypeImpl(qt, S, false, true, 6729 FD, /*OutermostType*/false, 6730 /*EncodingProperty*/false, 6731 /*StructField*/true, 6732 false, false, false, NotEncodedT); 6733 } 6734 } 6735 } 6736 } 6737 S += RDecl->isUnion() ? ')' : '}'; 6738 return; 6739 } 6740 6741 case Type::BlockPointer: { 6742 const auto *BT = T->castAs<BlockPointerType>(); 6743 S += "@?"; // Unlike a pointer-to-function, which is "^?". 6744 if (EncodeBlockParameters) { 6745 const auto *FT = BT->getPointeeType()->castAs<FunctionType>(); 6746 6747 S += '<'; 6748 // Block return type 6749 getObjCEncodingForTypeImpl( 6750 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures, 6751 FD, false /* OutermostType */, EncodingProperty, 6752 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false, 6753 NotEncodedT); 6754 // Block self 6755 S += "@?"; 6756 // Block parameters 6757 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) { 6758 for (const auto &I : FPT->param_types()) 6759 getObjCEncodingForTypeImpl( 6760 I, S, ExpandPointedToStructures, ExpandStructures, FD, 6761 false /* OutermostType */, EncodingProperty, 6762 false /* StructField */, EncodeBlockParameters, EncodeClassNames, 6763 false, NotEncodedT); 6764 } 6765 S += '>'; 6766 } 6767 return; 6768 } 6769 6770 case Type::ObjCObject: { 6771 // hack to match legacy encoding of *id and *Class 6772 QualType Ty = getObjCObjectPointerType(CT); 6773 if (Ty->isObjCIdType()) { 6774 S += "{objc_object=}"; 6775 return; 6776 } 6777 else if (Ty->isObjCClassType()) { 6778 S += "{objc_class=}"; 6779 return; 6780 } 6781 // TODO: Double check to make sure this intentionally falls through. 6782 LLVM_FALLTHROUGH; 6783 } 6784 6785 case Type::ObjCInterface: { 6786 // Ignore protocol qualifiers when mangling at this level. 6787 // @encode(class_name) 6788 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface(); 6789 S += '{'; 6790 S += OI->getObjCRuntimeNameAsString(); 6791 if (ExpandStructures) { 6792 S += '='; 6793 SmallVector<const ObjCIvarDecl*, 32> Ivars; 6794 DeepCollectObjCIvars(OI, true, Ivars); 6795 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 6796 const FieldDecl *Field = Ivars[i]; 6797 if (Field->isBitField()) 6798 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field); 6799 else 6800 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD, 6801 false, false, false, false, false, 6802 EncodePointerToObjCTypedef, 6803 NotEncodedT); 6804 } 6805 } 6806 S += '}'; 6807 return; 6808 } 6809 6810 case Type::ObjCObjectPointer: { 6811 const auto *OPT = T->castAs<ObjCObjectPointerType>(); 6812 if (OPT->isObjCIdType()) { 6813 S += '@'; 6814 return; 6815 } 6816 6817 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 6818 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 6819 // Since this is a binary compatibility issue, need to consult with runtime 6820 // folks. Fortunately, this is a *very* obscure construct. 6821 S += '#'; 6822 return; 6823 } 6824 6825 if (OPT->isObjCQualifiedIdType()) { 6826 getObjCEncodingForTypeImpl(getObjCIdType(), S, 6827 ExpandPointedToStructures, 6828 ExpandStructures, FD); 6829 if (FD || EncodingProperty || EncodeClassNames) { 6830 // Note that we do extended encoding of protocol qualifer list 6831 // Only when doing ivar or property encoding. 6832 S += '"'; 6833 for (const auto *I : OPT->quals()) { 6834 S += '<'; 6835 S += I->getObjCRuntimeNameAsString(); 6836 S += '>'; 6837 } 6838 S += '"'; 6839 } 6840 return; 6841 } 6842 6843 QualType PointeeTy = OPT->getPointeeType(); 6844 if (!EncodingProperty && 6845 isa<TypedefType>(PointeeTy.getTypePtr()) && 6846 !EncodePointerToObjCTypedef) { 6847 // Another historical/compatibility reason. 6848 // We encode the underlying type which comes out as 6849 // {...}; 6850 S += '^'; 6851 if (FD && OPT->getInterfaceDecl()) { 6852 // Prevent recursive encoding of fields in some rare cases. 6853 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl(); 6854 SmallVector<const ObjCIvarDecl*, 32> Ivars; 6855 DeepCollectObjCIvars(OI, true, Ivars); 6856 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 6857 if (Ivars[i] == FD) { 6858 S += '{'; 6859 S += OI->getObjCRuntimeNameAsString(); 6860 S += '}'; 6861 return; 6862 } 6863 } 6864 } 6865 getObjCEncodingForTypeImpl(PointeeTy, S, 6866 false, ExpandPointedToStructures, 6867 nullptr, 6868 false, false, false, false, false, 6869 /*EncodePointerToObjCTypedef*/true); 6870 return; 6871 } 6872 6873 S += '@'; 6874 if (OPT->getInterfaceDecl() && 6875 (FD || EncodingProperty || EncodeClassNames)) { 6876 S += '"'; 6877 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString(); 6878 for (const auto *I : OPT->quals()) { 6879 S += '<'; 6880 S += I->getObjCRuntimeNameAsString(); 6881 S += '>'; 6882 } 6883 S += '"'; 6884 } 6885 return; 6886 } 6887 6888 // gcc just blithely ignores member pointers. 6889 // FIXME: we shoul do better than that. 'M' is available. 6890 case Type::MemberPointer: 6891 // This matches gcc's encoding, even though technically it is insufficient. 6892 //FIXME. We should do a better job than gcc. 6893 case Type::Vector: 6894 case Type::ExtVector: 6895 // Until we have a coherent encoding of these three types, issue warning. 6896 if (NotEncodedT) 6897 *NotEncodedT = T; 6898 return; 6899 6900 // We could see an undeduced auto type here during error recovery. 6901 // Just ignore it. 6902 case Type::Auto: 6903 case Type::DeducedTemplateSpecialization: 6904 return; 6905 6906 case Type::Pipe: 6907 #define ABSTRACT_TYPE(KIND, BASE) 6908 #define TYPE(KIND, BASE) 6909 #define DEPENDENT_TYPE(KIND, BASE) \ 6910 case Type::KIND: 6911 #define NON_CANONICAL_TYPE(KIND, BASE) \ 6912 case Type::KIND: 6913 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ 6914 case Type::KIND: 6915 #include "clang/AST/TypeNodes.def" 6916 llvm_unreachable("@encode for dependent type!"); 6917 } 6918 llvm_unreachable("bad type kind!"); 6919 } 6920 6921 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 6922 std::string &S, 6923 const FieldDecl *FD, 6924 bool includeVBases, 6925 QualType *NotEncodedT) const { 6926 assert(RDecl && "Expected non-null RecordDecl"); 6927 assert(!RDecl->isUnion() && "Should not be called for unions"); 6928 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl()) 6929 return; 6930 6931 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 6932 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 6933 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 6934 6935 if (CXXRec) { 6936 for (const auto &BI : CXXRec->bases()) { 6937 if (!BI.isVirtual()) { 6938 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 6939 if (base->isEmpty()) 6940 continue; 6941 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 6942 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 6943 std::make_pair(offs, base)); 6944 } 6945 } 6946 } 6947 6948 unsigned i = 0; 6949 for (auto *Field : RDecl->fields()) { 6950 uint64_t offs = layout.getFieldOffset(i); 6951 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 6952 std::make_pair(offs, Field)); 6953 ++i; 6954 } 6955 6956 if (CXXRec && includeVBases) { 6957 for (const auto &BI : CXXRec->vbases()) { 6958 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 6959 if (base->isEmpty()) 6960 continue; 6961 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 6962 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && 6963 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 6964 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 6965 std::make_pair(offs, base)); 6966 } 6967 } 6968 6969 CharUnits size; 6970 if (CXXRec) { 6971 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 6972 } else { 6973 size = layout.getSize(); 6974 } 6975 6976 #ifndef NDEBUG 6977 uint64_t CurOffs = 0; 6978 #endif 6979 std::multimap<uint64_t, NamedDecl *>::iterator 6980 CurLayObj = FieldOrBaseOffsets.begin(); 6981 6982 if (CXXRec && CXXRec->isDynamicClass() && 6983 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 6984 if (FD) { 6985 S += "\"_vptr$"; 6986 std::string recname = CXXRec->getNameAsString(); 6987 if (recname.empty()) recname = "?"; 6988 S += recname; 6989 S += '"'; 6990 } 6991 S += "^^?"; 6992 #ifndef NDEBUG 6993 CurOffs += getTypeSize(VoidPtrTy); 6994 #endif 6995 } 6996 6997 if (!RDecl->hasFlexibleArrayMember()) { 6998 // Mark the end of the structure. 6999 uint64_t offs = toBits(size); 7000 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 7001 std::make_pair(offs, nullptr)); 7002 } 7003 7004 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 7005 #ifndef NDEBUG 7006 assert(CurOffs <= CurLayObj->first); 7007 if (CurOffs < CurLayObj->first) { 7008 uint64_t padding = CurLayObj->first - CurOffs; 7009 // FIXME: There doesn't seem to be a way to indicate in the encoding that 7010 // packing/alignment of members is different that normal, in which case 7011 // the encoding will be out-of-sync with the real layout. 7012 // If the runtime switches to just consider the size of types without 7013 // taking into account alignment, we could make padding explicit in the 7014 // encoding (e.g. using arrays of chars). The encoding strings would be 7015 // longer then though. 7016 CurOffs += padding; 7017 } 7018 #endif 7019 7020 NamedDecl *dcl = CurLayObj->second; 7021 if (!dcl) 7022 break; // reached end of structure. 7023 7024 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) { 7025 // We expand the bases without their virtual bases since those are going 7026 // in the initial structure. Note that this differs from gcc which 7027 // expands virtual bases each time one is encountered in the hierarchy, 7028 // making the encoding type bigger than it really is. 7029 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, 7030 NotEncodedT); 7031 assert(!base->isEmpty()); 7032 #ifndef NDEBUG 7033 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 7034 #endif 7035 } else { 7036 const auto *field = cast<FieldDecl>(dcl); 7037 if (FD) { 7038 S += '"'; 7039 S += field->getNameAsString(); 7040 S += '"'; 7041 } 7042 7043 if (field->isBitField()) { 7044 EncodeBitField(this, S, field->getType(), field); 7045 #ifndef NDEBUG 7046 CurOffs += field->getBitWidthValue(*this); 7047 #endif 7048 } else { 7049 QualType qt = field->getType(); 7050 getLegacyIntegralTypeEncoding(qt); 7051 getObjCEncodingForTypeImpl(qt, S, false, true, FD, 7052 /*OutermostType*/false, 7053 /*EncodingProperty*/false, 7054 /*StructField*/true, 7055 false, false, false, NotEncodedT); 7056 #ifndef NDEBUG 7057 CurOffs += getTypeSize(field->getType()); 7058 #endif 7059 } 7060 } 7061 } 7062 } 7063 7064 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 7065 std::string& S) const { 7066 if (QT & Decl::OBJC_TQ_In) 7067 S += 'n'; 7068 if (QT & Decl::OBJC_TQ_Inout) 7069 S += 'N'; 7070 if (QT & Decl::OBJC_TQ_Out) 7071 S += 'o'; 7072 if (QT & Decl::OBJC_TQ_Bycopy) 7073 S += 'O'; 7074 if (QT & Decl::OBJC_TQ_Byref) 7075 S += 'R'; 7076 if (QT & Decl::OBJC_TQ_Oneway) 7077 S += 'V'; 7078 } 7079 7080 TypedefDecl *ASTContext::getObjCIdDecl() const { 7081 if (!ObjCIdDecl) { 7082 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {}); 7083 T = getObjCObjectPointerType(T); 7084 ObjCIdDecl = buildImplicitTypedef(T, "id"); 7085 } 7086 return ObjCIdDecl; 7087 } 7088 7089 TypedefDecl *ASTContext::getObjCSelDecl() const { 7090 if (!ObjCSelDecl) { 7091 QualType T = getPointerType(ObjCBuiltinSelTy); 7092 ObjCSelDecl = buildImplicitTypedef(T, "SEL"); 7093 } 7094 return ObjCSelDecl; 7095 } 7096 7097 TypedefDecl *ASTContext::getObjCClassDecl() const { 7098 if (!ObjCClassDecl) { 7099 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {}); 7100 T = getObjCObjectPointerType(T); 7101 ObjCClassDecl = buildImplicitTypedef(T, "Class"); 7102 } 7103 return ObjCClassDecl; 7104 } 7105 7106 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 7107 if (!ObjCProtocolClassDecl) { 7108 ObjCProtocolClassDecl 7109 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 7110 SourceLocation(), 7111 &Idents.get("Protocol"), 7112 /*typeParamList=*/nullptr, 7113 /*PrevDecl=*/nullptr, 7114 SourceLocation(), true); 7115 } 7116 7117 return ObjCProtocolClassDecl; 7118 } 7119 7120 //===----------------------------------------------------------------------===// 7121 // __builtin_va_list Construction Functions 7122 //===----------------------------------------------------------------------===// 7123 7124 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context, 7125 StringRef Name) { 7126 // typedef char* __builtin[_ms]_va_list; 7127 QualType T = Context->getPointerType(Context->CharTy); 7128 return Context->buildImplicitTypedef(T, Name); 7129 } 7130 7131 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) { 7132 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list"); 7133 } 7134 7135 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 7136 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list"); 7137 } 7138 7139 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 7140 // typedef void* __builtin_va_list; 7141 QualType T = Context->getPointerType(Context->VoidTy); 7142 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 7143 } 7144 7145 static TypedefDecl * 7146 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { 7147 // struct __va_list 7148 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); 7149 if (Context->getLangOpts().CPlusPlus) { 7150 // namespace std { struct __va_list { 7151 NamespaceDecl *NS; 7152 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 7153 Context->getTranslationUnitDecl(), 7154 /*Inline*/ false, SourceLocation(), 7155 SourceLocation(), &Context->Idents.get("std"), 7156 /*PrevDecl*/ nullptr); 7157 NS->setImplicit(); 7158 VaListTagDecl->setDeclContext(NS); 7159 } 7160 7161 VaListTagDecl->startDefinition(); 7162 7163 const size_t NumFields = 5; 7164 QualType FieldTypes[NumFields]; 7165 const char *FieldNames[NumFields]; 7166 7167 // void *__stack; 7168 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 7169 FieldNames[0] = "__stack"; 7170 7171 // void *__gr_top; 7172 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 7173 FieldNames[1] = "__gr_top"; 7174 7175 // void *__vr_top; 7176 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 7177 FieldNames[2] = "__vr_top"; 7178 7179 // int __gr_offs; 7180 FieldTypes[3] = Context->IntTy; 7181 FieldNames[3] = "__gr_offs"; 7182 7183 // int __vr_offs; 7184 FieldTypes[4] = Context->IntTy; 7185 FieldNames[4] = "__vr_offs"; 7186 7187 // Create fields 7188 for (unsigned i = 0; i < NumFields; ++i) { 7189 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 7190 VaListTagDecl, 7191 SourceLocation(), 7192 SourceLocation(), 7193 &Context->Idents.get(FieldNames[i]), 7194 FieldTypes[i], /*TInfo=*/nullptr, 7195 /*BitWidth=*/nullptr, 7196 /*Mutable=*/false, 7197 ICIS_NoInit); 7198 Field->setAccess(AS_public); 7199 VaListTagDecl->addDecl(Field); 7200 } 7201 VaListTagDecl->completeDefinition(); 7202 Context->VaListTagDecl = VaListTagDecl; 7203 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 7204 7205 // } __builtin_va_list; 7206 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 7207 } 7208 7209 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 7210 // typedef struct __va_list_tag { 7211 RecordDecl *VaListTagDecl; 7212 7213 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 7214 VaListTagDecl->startDefinition(); 7215 7216 const size_t NumFields = 5; 7217 QualType FieldTypes[NumFields]; 7218 const char *FieldNames[NumFields]; 7219 7220 // unsigned char gpr; 7221 FieldTypes[0] = Context->UnsignedCharTy; 7222 FieldNames[0] = "gpr"; 7223 7224 // unsigned char fpr; 7225 FieldTypes[1] = Context->UnsignedCharTy; 7226 FieldNames[1] = "fpr"; 7227 7228 // unsigned short reserved; 7229 FieldTypes[2] = Context->UnsignedShortTy; 7230 FieldNames[2] = "reserved"; 7231 7232 // void* overflow_arg_area; 7233 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 7234 FieldNames[3] = "overflow_arg_area"; 7235 7236 // void* reg_save_area; 7237 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 7238 FieldNames[4] = "reg_save_area"; 7239 7240 // Create fields 7241 for (unsigned i = 0; i < NumFields; ++i) { 7242 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 7243 SourceLocation(), 7244 SourceLocation(), 7245 &Context->Idents.get(FieldNames[i]), 7246 FieldTypes[i], /*TInfo=*/nullptr, 7247 /*BitWidth=*/nullptr, 7248 /*Mutable=*/false, 7249 ICIS_NoInit); 7250 Field->setAccess(AS_public); 7251 VaListTagDecl->addDecl(Field); 7252 } 7253 VaListTagDecl->completeDefinition(); 7254 Context->VaListTagDecl = VaListTagDecl; 7255 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 7256 7257 // } __va_list_tag; 7258 TypedefDecl *VaListTagTypedefDecl = 7259 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 7260 7261 QualType VaListTagTypedefType = 7262 Context->getTypedefType(VaListTagTypedefDecl); 7263 7264 // typedef __va_list_tag __builtin_va_list[1]; 7265 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 7266 QualType VaListTagArrayType 7267 = Context->getConstantArrayType(VaListTagTypedefType, 7268 Size, ArrayType::Normal, 0); 7269 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 7270 } 7271 7272 static TypedefDecl * 7273 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 7274 // struct __va_list_tag { 7275 RecordDecl *VaListTagDecl; 7276 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 7277 VaListTagDecl->startDefinition(); 7278 7279 const size_t NumFields = 4; 7280 QualType FieldTypes[NumFields]; 7281 const char *FieldNames[NumFields]; 7282 7283 // unsigned gp_offset; 7284 FieldTypes[0] = Context->UnsignedIntTy; 7285 FieldNames[0] = "gp_offset"; 7286 7287 // unsigned fp_offset; 7288 FieldTypes[1] = Context->UnsignedIntTy; 7289 FieldNames[1] = "fp_offset"; 7290 7291 // void* overflow_arg_area; 7292 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 7293 FieldNames[2] = "overflow_arg_area"; 7294 7295 // void* reg_save_area; 7296 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 7297 FieldNames[3] = "reg_save_area"; 7298 7299 // Create fields 7300 for (unsigned i = 0; i < NumFields; ++i) { 7301 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 7302 VaListTagDecl, 7303 SourceLocation(), 7304 SourceLocation(), 7305 &Context->Idents.get(FieldNames[i]), 7306 FieldTypes[i], /*TInfo=*/nullptr, 7307 /*BitWidth=*/nullptr, 7308 /*Mutable=*/false, 7309 ICIS_NoInit); 7310 Field->setAccess(AS_public); 7311 VaListTagDecl->addDecl(Field); 7312 } 7313 VaListTagDecl->completeDefinition(); 7314 Context->VaListTagDecl = VaListTagDecl; 7315 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 7316 7317 // }; 7318 7319 // typedef struct __va_list_tag __builtin_va_list[1]; 7320 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 7321 QualType VaListTagArrayType = 7322 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0); 7323 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 7324 } 7325 7326 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 7327 // typedef int __builtin_va_list[4]; 7328 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 7329 QualType IntArrayType = 7330 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0); 7331 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); 7332 } 7333 7334 static TypedefDecl * 7335 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { 7336 // struct __va_list 7337 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); 7338 if (Context->getLangOpts().CPlusPlus) { 7339 // namespace std { struct __va_list { 7340 NamespaceDecl *NS; 7341 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 7342 Context->getTranslationUnitDecl(), 7343 /*Inline*/false, SourceLocation(), 7344 SourceLocation(), &Context->Idents.get("std"), 7345 /*PrevDecl*/ nullptr); 7346 NS->setImplicit(); 7347 VaListDecl->setDeclContext(NS); 7348 } 7349 7350 VaListDecl->startDefinition(); 7351 7352 // void * __ap; 7353 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 7354 VaListDecl, 7355 SourceLocation(), 7356 SourceLocation(), 7357 &Context->Idents.get("__ap"), 7358 Context->getPointerType(Context->VoidTy), 7359 /*TInfo=*/nullptr, 7360 /*BitWidth=*/nullptr, 7361 /*Mutable=*/false, 7362 ICIS_NoInit); 7363 Field->setAccess(AS_public); 7364 VaListDecl->addDecl(Field); 7365 7366 // }; 7367 VaListDecl->completeDefinition(); 7368 Context->VaListTagDecl = VaListDecl; 7369 7370 // typedef struct __va_list __builtin_va_list; 7371 QualType T = Context->getRecordType(VaListDecl); 7372 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 7373 } 7374 7375 static TypedefDecl * 7376 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { 7377 // struct __va_list_tag { 7378 RecordDecl *VaListTagDecl; 7379 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 7380 VaListTagDecl->startDefinition(); 7381 7382 const size_t NumFields = 4; 7383 QualType FieldTypes[NumFields]; 7384 const char *FieldNames[NumFields]; 7385 7386 // long __gpr; 7387 FieldTypes[0] = Context->LongTy; 7388 FieldNames[0] = "__gpr"; 7389 7390 // long __fpr; 7391 FieldTypes[1] = Context->LongTy; 7392 FieldNames[1] = "__fpr"; 7393 7394 // void *__overflow_arg_area; 7395 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 7396 FieldNames[2] = "__overflow_arg_area"; 7397 7398 // void *__reg_save_area; 7399 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 7400 FieldNames[3] = "__reg_save_area"; 7401 7402 // Create fields 7403 for (unsigned i = 0; i < NumFields; ++i) { 7404 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 7405 VaListTagDecl, 7406 SourceLocation(), 7407 SourceLocation(), 7408 &Context->Idents.get(FieldNames[i]), 7409 FieldTypes[i], /*TInfo=*/nullptr, 7410 /*BitWidth=*/nullptr, 7411 /*Mutable=*/false, 7412 ICIS_NoInit); 7413 Field->setAccess(AS_public); 7414 VaListTagDecl->addDecl(Field); 7415 } 7416 VaListTagDecl->completeDefinition(); 7417 Context->VaListTagDecl = VaListTagDecl; 7418 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 7419 7420 // }; 7421 7422 // typedef __va_list_tag __builtin_va_list[1]; 7423 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 7424 QualType VaListTagArrayType = 7425 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0); 7426 7427 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 7428 } 7429 7430 static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 7431 TargetInfo::BuiltinVaListKind Kind) { 7432 switch (Kind) { 7433 case TargetInfo::CharPtrBuiltinVaList: 7434 return CreateCharPtrBuiltinVaListDecl(Context); 7435 case TargetInfo::VoidPtrBuiltinVaList: 7436 return CreateVoidPtrBuiltinVaListDecl(Context); 7437 case TargetInfo::AArch64ABIBuiltinVaList: 7438 return CreateAArch64ABIBuiltinVaListDecl(Context); 7439 case TargetInfo::PowerABIBuiltinVaList: 7440 return CreatePowerABIBuiltinVaListDecl(Context); 7441 case TargetInfo::X86_64ABIBuiltinVaList: 7442 return CreateX86_64ABIBuiltinVaListDecl(Context); 7443 case TargetInfo::PNaClABIBuiltinVaList: 7444 return CreatePNaClABIBuiltinVaListDecl(Context); 7445 case TargetInfo::AAPCSABIBuiltinVaList: 7446 return CreateAAPCSABIBuiltinVaListDecl(Context); 7447 case TargetInfo::SystemZBuiltinVaList: 7448 return CreateSystemZBuiltinVaListDecl(Context); 7449 } 7450 7451 llvm_unreachable("Unhandled __builtin_va_list type kind"); 7452 } 7453 7454 TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 7455 if (!BuiltinVaListDecl) { 7456 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 7457 assert(BuiltinVaListDecl->isImplicit()); 7458 } 7459 7460 return BuiltinVaListDecl; 7461 } 7462 7463 Decl *ASTContext::getVaListTagDecl() const { 7464 // Force the creation of VaListTagDecl by building the __builtin_va_list 7465 // declaration. 7466 if (!VaListTagDecl) 7467 (void)getBuiltinVaListDecl(); 7468 7469 return VaListTagDecl; 7470 } 7471 7472 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const { 7473 if (!BuiltinMSVaListDecl) 7474 BuiltinMSVaListDecl = CreateMSVaListDecl(this); 7475 7476 return BuiltinMSVaListDecl; 7477 } 7478 7479 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const { 7480 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID()); 7481 } 7482 7483 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 7484 assert(ObjCConstantStringType.isNull() && 7485 "'NSConstantString' type already set!"); 7486 7487 ObjCConstantStringType = getObjCInterfaceType(Decl); 7488 } 7489 7490 /// Retrieve the template name that corresponds to a non-empty 7491 /// lookup. 7492 TemplateName 7493 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 7494 UnresolvedSetIterator End) const { 7495 unsigned size = End - Begin; 7496 assert(size > 1 && "set is not overloaded!"); 7497 7498 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 7499 size * sizeof(FunctionTemplateDecl*)); 7500 auto *OT = new (memory) OverloadedTemplateStorage(size); 7501 7502 NamedDecl **Storage = OT->getStorage(); 7503 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 7504 NamedDecl *D = *I; 7505 assert(isa<FunctionTemplateDecl>(D) || 7506 isa<UnresolvedUsingValueDecl>(D) || 7507 (isa<UsingShadowDecl>(D) && 7508 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 7509 *Storage++ = D; 7510 } 7511 7512 return TemplateName(OT); 7513 } 7514 7515 /// Retrieve the template name that represents a qualified 7516 /// template name such as \c std::vector. 7517 TemplateName 7518 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 7519 bool TemplateKeyword, 7520 TemplateDecl *Template) const { 7521 assert(NNS && "Missing nested-name-specifier in qualified template name"); 7522 7523 // FIXME: Canonicalization? 7524 llvm::FoldingSetNodeID ID; 7525 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 7526 7527 void *InsertPos = nullptr; 7528 QualifiedTemplateName *QTN = 7529 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 7530 if (!QTN) { 7531 QTN = new (*this, alignof(QualifiedTemplateName)) 7532 QualifiedTemplateName(NNS, TemplateKeyword, Template); 7533 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 7534 } 7535 7536 return TemplateName(QTN); 7537 } 7538 7539 /// Retrieve the template name that represents a dependent 7540 /// template name such as \c MetaFun::template apply. 7541 TemplateName 7542 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 7543 const IdentifierInfo *Name) const { 7544 assert((!NNS || NNS->isDependent()) && 7545 "Nested name specifier must be dependent"); 7546 7547 llvm::FoldingSetNodeID ID; 7548 DependentTemplateName::Profile(ID, NNS, Name); 7549 7550 void *InsertPos = nullptr; 7551 DependentTemplateName *QTN = 7552 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 7553 7554 if (QTN) 7555 return TemplateName(QTN); 7556 7557 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 7558 if (CanonNNS == NNS) { 7559 QTN = new (*this, alignof(DependentTemplateName)) 7560 DependentTemplateName(NNS, Name); 7561 } else { 7562 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 7563 QTN = new (*this, alignof(DependentTemplateName)) 7564 DependentTemplateName(NNS, Name, Canon); 7565 DependentTemplateName *CheckQTN = 7566 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 7567 assert(!CheckQTN && "Dependent type name canonicalization broken"); 7568 (void)CheckQTN; 7569 } 7570 7571 DependentTemplateNames.InsertNode(QTN, InsertPos); 7572 return TemplateName(QTN); 7573 } 7574 7575 /// Retrieve the template name that represents a dependent 7576 /// template name such as \c MetaFun::template operator+. 7577 TemplateName 7578 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 7579 OverloadedOperatorKind Operator) const { 7580 assert((!NNS || NNS->isDependent()) && 7581 "Nested name specifier must be dependent"); 7582 7583 llvm::FoldingSetNodeID ID; 7584 DependentTemplateName::Profile(ID, NNS, Operator); 7585 7586 void *InsertPos = nullptr; 7587 DependentTemplateName *QTN 7588 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 7589 7590 if (QTN) 7591 return TemplateName(QTN); 7592 7593 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 7594 if (CanonNNS == NNS) { 7595 QTN = new (*this, alignof(DependentTemplateName)) 7596 DependentTemplateName(NNS, Operator); 7597 } else { 7598 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 7599 QTN = new (*this, alignof(DependentTemplateName)) 7600 DependentTemplateName(NNS, Operator, Canon); 7601 7602 DependentTemplateName *CheckQTN 7603 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 7604 assert(!CheckQTN && "Dependent template name canonicalization broken"); 7605 (void)CheckQTN; 7606 } 7607 7608 DependentTemplateNames.InsertNode(QTN, InsertPos); 7609 return TemplateName(QTN); 7610 } 7611 7612 TemplateName 7613 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 7614 TemplateName replacement) const { 7615 llvm::FoldingSetNodeID ID; 7616 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 7617 7618 void *insertPos = nullptr; 7619 SubstTemplateTemplateParmStorage *subst 7620 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 7621 7622 if (!subst) { 7623 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 7624 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 7625 } 7626 7627 return TemplateName(subst); 7628 } 7629 7630 TemplateName 7631 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 7632 const TemplateArgument &ArgPack) const { 7633 auto &Self = const_cast<ASTContext &>(*this); 7634 llvm::FoldingSetNodeID ID; 7635 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 7636 7637 void *InsertPos = nullptr; 7638 SubstTemplateTemplateParmPackStorage *Subst 7639 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 7640 7641 if (!Subst) { 7642 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 7643 ArgPack.pack_size(), 7644 ArgPack.pack_begin()); 7645 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 7646 } 7647 7648 return TemplateName(Subst); 7649 } 7650 7651 /// getFromTargetType - Given one of the integer types provided by 7652 /// TargetInfo, produce the corresponding type. The unsigned @p Type 7653 /// is actually a value of type @c TargetInfo::IntType. 7654 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 7655 switch (Type) { 7656 case TargetInfo::NoInt: return {}; 7657 case TargetInfo::SignedChar: return SignedCharTy; 7658 case TargetInfo::UnsignedChar: return UnsignedCharTy; 7659 case TargetInfo::SignedShort: return ShortTy; 7660 case TargetInfo::UnsignedShort: return UnsignedShortTy; 7661 case TargetInfo::SignedInt: return IntTy; 7662 case TargetInfo::UnsignedInt: return UnsignedIntTy; 7663 case TargetInfo::SignedLong: return LongTy; 7664 case TargetInfo::UnsignedLong: return UnsignedLongTy; 7665 case TargetInfo::SignedLongLong: return LongLongTy; 7666 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 7667 } 7668 7669 llvm_unreachable("Unhandled TargetInfo::IntType value"); 7670 } 7671 7672 //===----------------------------------------------------------------------===// 7673 // Type Predicates. 7674 //===----------------------------------------------------------------------===// 7675 7676 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 7677 /// garbage collection attribute. 7678 /// 7679 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 7680 if (getLangOpts().getGC() == LangOptions::NonGC) 7681 return Qualifiers::GCNone; 7682 7683 assert(getLangOpts().ObjC1); 7684 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 7685 7686 // Default behaviour under objective-C's gc is for ObjC pointers 7687 // (or pointers to them) be treated as though they were declared 7688 // as __strong. 7689 if (GCAttrs == Qualifiers::GCNone) { 7690 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 7691 return Qualifiers::Strong; 7692 else if (Ty->isPointerType()) 7693 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType()); 7694 } else { 7695 // It's not valid to set GC attributes on anything that isn't a 7696 // pointer. 7697 #ifndef NDEBUG 7698 QualType CT = Ty->getCanonicalTypeInternal(); 7699 while (const auto *AT = dyn_cast<ArrayType>(CT)) 7700 CT = AT->getElementType(); 7701 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 7702 #endif 7703 } 7704 return GCAttrs; 7705 } 7706 7707 //===----------------------------------------------------------------------===// 7708 // Type Compatibility Testing 7709 //===----------------------------------------------------------------------===// 7710 7711 /// areCompatVectorTypes - Return true if the two specified vector types are 7712 /// compatible. 7713 static bool areCompatVectorTypes(const VectorType *LHS, 7714 const VectorType *RHS) { 7715 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 7716 return LHS->getElementType() == RHS->getElementType() && 7717 LHS->getNumElements() == RHS->getNumElements(); 7718 } 7719 7720 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 7721 QualType SecondVec) { 7722 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 7723 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 7724 7725 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 7726 return true; 7727 7728 // Treat Neon vector types and most AltiVec vector types as if they are the 7729 // equivalent GCC vector types. 7730 const auto *First = FirstVec->getAs<VectorType>(); 7731 const auto *Second = SecondVec->getAs<VectorType>(); 7732 if (First->getNumElements() == Second->getNumElements() && 7733 hasSameType(First->getElementType(), Second->getElementType()) && 7734 First->getVectorKind() != VectorType::AltiVecPixel && 7735 First->getVectorKind() != VectorType::AltiVecBool && 7736 Second->getVectorKind() != VectorType::AltiVecPixel && 7737 Second->getVectorKind() != VectorType::AltiVecBool) 7738 return true; 7739 7740 return false; 7741 } 7742 7743 //===----------------------------------------------------------------------===// 7744 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 7745 //===----------------------------------------------------------------------===// 7746 7747 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 7748 /// inheritance hierarchy of 'rProto'. 7749 bool 7750 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 7751 ObjCProtocolDecl *rProto) const { 7752 if (declaresSameEntity(lProto, rProto)) 7753 return true; 7754 for (auto *PI : rProto->protocols()) 7755 if (ProtocolCompatibleWithProtocol(lProto, PI)) 7756 return true; 7757 return false; 7758 } 7759 7760 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 7761 /// Class<pr1, ...>. 7762 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs, 7763 QualType rhs) { 7764 const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>(); 7765 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 7766 assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible"); 7767 7768 for (auto *lhsProto : lhsQID->quals()) { 7769 bool match = false; 7770 for (auto *rhsProto : rhsOPT->quals()) { 7771 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 7772 match = true; 7773 break; 7774 } 7775 } 7776 if (!match) 7777 return false; 7778 } 7779 return true; 7780 } 7781 7782 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 7783 /// ObjCQualifiedIDType. 7784 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, 7785 bool compare) { 7786 // Allow id<P..> and an 'id' or void* type in all cases. 7787 if (lhs->isVoidPointerType() || 7788 lhs->isObjCIdType() || lhs->isObjCClassType()) 7789 return true; 7790 else if (rhs->isVoidPointerType() || 7791 rhs->isObjCIdType() || rhs->isObjCClassType()) 7792 return true; 7793 7794 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) { 7795 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 7796 7797 if (!rhsOPT) return false; 7798 7799 if (rhsOPT->qual_empty()) { 7800 // If the RHS is a unqualified interface pointer "NSString*", 7801 // make sure we check the class hierarchy. 7802 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 7803 for (auto *I : lhsQID->quals()) { 7804 // when comparing an id<P> on lhs with a static type on rhs, 7805 // see if static class implements all of id's protocols, directly or 7806 // through its super class and categories. 7807 if (!rhsID->ClassImplementsProtocol(I, true)) 7808 return false; 7809 } 7810 } 7811 // If there are no qualifiers and no interface, we have an 'id'. 7812 return true; 7813 } 7814 // Both the right and left sides have qualifiers. 7815 for (auto *lhsProto : lhsQID->quals()) { 7816 bool match = false; 7817 7818 // when comparing an id<P> on lhs with a static type on rhs, 7819 // see if static class implements all of id's protocols, directly or 7820 // through its super class and categories. 7821 for (auto *rhsProto : rhsOPT->quals()) { 7822 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 7823 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 7824 match = true; 7825 break; 7826 } 7827 } 7828 // If the RHS is a qualified interface pointer "NSString<P>*", 7829 // make sure we check the class hierarchy. 7830 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 7831 for (auto *I : lhsQID->quals()) { 7832 // when comparing an id<P> on lhs with a static type on rhs, 7833 // see if static class implements all of id's protocols, directly or 7834 // through its super class and categories. 7835 if (rhsID->ClassImplementsProtocol(I, true)) { 7836 match = true; 7837 break; 7838 } 7839 } 7840 } 7841 if (!match) 7842 return false; 7843 } 7844 7845 return true; 7846 } 7847 7848 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType(); 7849 assert(rhsQID && "One of the LHS/RHS should be id<x>"); 7850 7851 if (const ObjCObjectPointerType *lhsOPT = 7852 lhs->getAsObjCInterfacePointerType()) { 7853 // If both the right and left sides have qualifiers. 7854 for (auto *lhsProto : lhsOPT->quals()) { 7855 bool match = false; 7856 7857 // when comparing an id<P> on rhs with a static type on lhs, 7858 // see if static class implements all of id's protocols, directly or 7859 // through its super class and categories. 7860 // First, lhs protocols in the qualifier list must be found, direct 7861 // or indirect in rhs's qualifier list or it is a mismatch. 7862 for (auto *rhsProto : rhsQID->quals()) { 7863 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 7864 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 7865 match = true; 7866 break; 7867 } 7868 } 7869 if (!match) 7870 return false; 7871 } 7872 7873 // Static class's protocols, or its super class or category protocols 7874 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 7875 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) { 7876 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 7877 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 7878 // This is rather dubious but matches gcc's behavior. If lhs has 7879 // no type qualifier and its class has no static protocol(s) 7880 // assume that it is mismatch. 7881 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty()) 7882 return false; 7883 for (auto *lhsProto : LHSInheritedProtocols) { 7884 bool match = false; 7885 for (auto *rhsProto : rhsQID->quals()) { 7886 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 7887 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 7888 match = true; 7889 break; 7890 } 7891 } 7892 if (!match) 7893 return false; 7894 } 7895 } 7896 return true; 7897 } 7898 return false; 7899 } 7900 7901 /// canAssignObjCInterfaces - Return true if the two interface types are 7902 /// compatible for assignment from RHS to LHS. This handles validation of any 7903 /// protocol qualifiers on the LHS or RHS. 7904 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 7905 const ObjCObjectPointerType *RHSOPT) { 7906 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 7907 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 7908 7909 // If either type represents the built-in 'id' or 'Class' types, return true. 7910 if (LHS->isObjCUnqualifiedIdOrClass() || 7911 RHS->isObjCUnqualifiedIdOrClass()) 7912 return true; 7913 7914 // Function object that propagates a successful result or handles 7915 // __kindof types. 7916 auto finish = [&](bool succeeded) -> bool { 7917 if (succeeded) 7918 return true; 7919 7920 if (!RHS->isKindOfType()) 7921 return false; 7922 7923 // Strip off __kindof and protocol qualifiers, then check whether 7924 // we can assign the other way. 7925 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this), 7926 LHSOPT->stripObjCKindOfTypeAndQuals(*this)); 7927 }; 7928 7929 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) { 7930 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 7931 QualType(RHSOPT,0), 7932 false)); 7933 } 7934 7935 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { 7936 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0), 7937 QualType(RHSOPT,0))); 7938 } 7939 7940 // If we have 2 user-defined types, fall into that path. 7941 if (LHS->getInterface() && RHS->getInterface()) { 7942 return finish(canAssignObjCInterfaces(LHS, RHS)); 7943 } 7944 7945 return false; 7946 } 7947 7948 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 7949 /// for providing type-safety for objective-c pointers used to pass/return 7950 /// arguments in block literals. When passed as arguments, passing 'A*' where 7951 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 7952 /// not OK. For the return type, the opposite is not OK. 7953 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 7954 const ObjCObjectPointerType *LHSOPT, 7955 const ObjCObjectPointerType *RHSOPT, 7956 bool BlockReturnType) { 7957 7958 // Function object that propagates a successful result or handles 7959 // __kindof types. 7960 auto finish = [&](bool succeeded) -> bool { 7961 if (succeeded) 7962 return true; 7963 7964 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT; 7965 if (!Expected->isKindOfType()) 7966 return false; 7967 7968 // Strip off __kindof and protocol qualifiers, then check whether 7969 // we can assign the other way. 7970 return canAssignObjCInterfacesInBlockPointer( 7971 RHSOPT->stripObjCKindOfTypeAndQuals(*this), 7972 LHSOPT->stripObjCKindOfTypeAndQuals(*this), 7973 BlockReturnType); 7974 }; 7975 7976 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 7977 return true; 7978 7979 if (LHSOPT->isObjCBuiltinType()) { 7980 return finish(RHSOPT->isObjCBuiltinType() || 7981 RHSOPT->isObjCQualifiedIdType()); 7982 } 7983 7984 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) 7985 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 7986 QualType(RHSOPT,0), 7987 false)); 7988 7989 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 7990 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 7991 if (LHS && RHS) { // We have 2 user-defined types. 7992 if (LHS != RHS) { 7993 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 7994 return finish(BlockReturnType); 7995 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 7996 return finish(!BlockReturnType); 7997 } 7998 else 7999 return true; 8000 } 8001 return false; 8002 } 8003 8004 /// Comparison routine for Objective-C protocols to be used with 8005 /// llvm::array_pod_sort. 8006 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, 8007 ObjCProtocolDecl * const *rhs) { 8008 return (*lhs)->getName().compare((*rhs)->getName()); 8009 } 8010 8011 /// getIntersectionOfProtocols - This routine finds the intersection of set 8012 /// of protocols inherited from two distinct objective-c pointer objects with 8013 /// the given common base. 8014 /// It is used to build composite qualifier list of the composite type of 8015 /// the conditional expression involving two objective-c pointer objects. 8016 static 8017 void getIntersectionOfProtocols(ASTContext &Context, 8018 const ObjCInterfaceDecl *CommonBase, 8019 const ObjCObjectPointerType *LHSOPT, 8020 const ObjCObjectPointerType *RHSOPT, 8021 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { 8022 8023 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 8024 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 8025 assert(LHS->getInterface() && "LHS must have an interface base"); 8026 assert(RHS->getInterface() && "RHS must have an interface base"); 8027 8028 // Add all of the protocols for the LHS. 8029 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet; 8030 8031 // Start with the protocol qualifiers. 8032 for (auto proto : LHS->quals()) { 8033 Context.CollectInheritedProtocols(proto, LHSProtocolSet); 8034 } 8035 8036 // Also add the protocols associated with the LHS interface. 8037 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet); 8038 8039 // Add all of the protocls for the RHS. 8040 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet; 8041 8042 // Start with the protocol qualifiers. 8043 for (auto proto : RHS->quals()) { 8044 Context.CollectInheritedProtocols(proto, RHSProtocolSet); 8045 } 8046 8047 // Also add the protocols associated with the RHS interface. 8048 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet); 8049 8050 // Compute the intersection of the collected protocol sets. 8051 for (auto proto : LHSProtocolSet) { 8052 if (RHSProtocolSet.count(proto)) 8053 IntersectionSet.push_back(proto); 8054 } 8055 8056 // Compute the set of protocols that is implied by either the common type or 8057 // the protocols within the intersection. 8058 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols; 8059 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols); 8060 8061 // Remove any implied protocols from the list of inherited protocols. 8062 if (!ImpliedProtocols.empty()) { 8063 IntersectionSet.erase( 8064 std::remove_if(IntersectionSet.begin(), 8065 IntersectionSet.end(), 8066 [&](ObjCProtocolDecl *proto) -> bool { 8067 return ImpliedProtocols.count(proto) > 0; 8068 }), 8069 IntersectionSet.end()); 8070 } 8071 8072 // Sort the remaining protocols by name. 8073 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(), 8074 compareObjCProtocolsByName); 8075 } 8076 8077 /// Determine whether the first type is a subtype of the second. 8078 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, 8079 QualType rhs) { 8080 // Common case: two object pointers. 8081 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>(); 8082 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 8083 if (lhsOPT && rhsOPT) 8084 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT); 8085 8086 // Two block pointers. 8087 const auto *lhsBlock = lhs->getAs<BlockPointerType>(); 8088 const auto *rhsBlock = rhs->getAs<BlockPointerType>(); 8089 if (lhsBlock && rhsBlock) 8090 return ctx.typesAreBlockPointerCompatible(lhs, rhs); 8091 8092 // If either is an unqualified 'id' and the other is a block, it's 8093 // acceptable. 8094 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) || 8095 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock)) 8096 return true; 8097 8098 return false; 8099 } 8100 8101 // Check that the given Objective-C type argument lists are equivalent. 8102 static bool sameObjCTypeArgs(ASTContext &ctx, 8103 const ObjCInterfaceDecl *iface, 8104 ArrayRef<QualType> lhsArgs, 8105 ArrayRef<QualType> rhsArgs, 8106 bool stripKindOf) { 8107 if (lhsArgs.size() != rhsArgs.size()) 8108 return false; 8109 8110 ObjCTypeParamList *typeParams = iface->getTypeParamList(); 8111 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) { 8112 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i])) 8113 continue; 8114 8115 switch (typeParams->begin()[i]->getVariance()) { 8116 case ObjCTypeParamVariance::Invariant: 8117 if (!stripKindOf || 8118 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx), 8119 rhsArgs[i].stripObjCKindOfType(ctx))) { 8120 return false; 8121 } 8122 break; 8123 8124 case ObjCTypeParamVariance::Covariant: 8125 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i])) 8126 return false; 8127 break; 8128 8129 case ObjCTypeParamVariance::Contravariant: 8130 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i])) 8131 return false; 8132 break; 8133 } 8134 } 8135 8136 return true; 8137 } 8138 8139 QualType ASTContext::areCommonBaseCompatible( 8140 const ObjCObjectPointerType *Lptr, 8141 const ObjCObjectPointerType *Rptr) { 8142 const ObjCObjectType *LHS = Lptr->getObjectType(); 8143 const ObjCObjectType *RHS = Rptr->getObjectType(); 8144 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 8145 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 8146 8147 if (!LDecl || !RDecl) 8148 return {}; 8149 8150 // When either LHS or RHS is a kindof type, we should return a kindof type. 8151 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return 8152 // kindof(A). 8153 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType(); 8154 8155 // Follow the left-hand side up the class hierarchy until we either hit a 8156 // root or find the RHS. Record the ancestors in case we don't find it. 8157 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4> 8158 LHSAncestors; 8159 while (true) { 8160 // Record this ancestor. We'll need this if the common type isn't in the 8161 // path from the LHS to the root. 8162 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS; 8163 8164 if (declaresSameEntity(LHS->getInterface(), RDecl)) { 8165 // Get the type arguments. 8166 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten(); 8167 bool anyChanges = false; 8168 if (LHS->isSpecialized() && RHS->isSpecialized()) { 8169 // Both have type arguments, compare them. 8170 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 8171 LHS->getTypeArgs(), RHS->getTypeArgs(), 8172 /*stripKindOf=*/true)) 8173 return {}; 8174 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 8175 // If only one has type arguments, the result will not have type 8176 // arguments. 8177 LHSTypeArgs = {}; 8178 anyChanges = true; 8179 } 8180 8181 // Compute the intersection of protocols. 8182 SmallVector<ObjCProtocolDecl *, 8> Protocols; 8183 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr, 8184 Protocols); 8185 if (!Protocols.empty()) 8186 anyChanges = true; 8187 8188 // If anything in the LHS will have changed, build a new result type. 8189 // If we need to return a kindof type but LHS is not a kindof type, we 8190 // build a new result type. 8191 if (anyChanges || LHS->isKindOfType() != anyKindOf) { 8192 QualType Result = getObjCInterfaceType(LHS->getInterface()); 8193 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols, 8194 anyKindOf || LHS->isKindOfType()); 8195 return getObjCObjectPointerType(Result); 8196 } 8197 8198 return getObjCObjectPointerType(QualType(LHS, 0)); 8199 } 8200 8201 // Find the superclass. 8202 QualType LHSSuperType = LHS->getSuperClassType(); 8203 if (LHSSuperType.isNull()) 8204 break; 8205 8206 LHS = LHSSuperType->castAs<ObjCObjectType>(); 8207 } 8208 8209 // We didn't find anything by following the LHS to its root; now check 8210 // the RHS against the cached set of ancestors. 8211 while (true) { 8212 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl()); 8213 if (KnownLHS != LHSAncestors.end()) { 8214 LHS = KnownLHS->second; 8215 8216 // Get the type arguments. 8217 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten(); 8218 bool anyChanges = false; 8219 if (LHS->isSpecialized() && RHS->isSpecialized()) { 8220 // Both have type arguments, compare them. 8221 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 8222 LHS->getTypeArgs(), RHS->getTypeArgs(), 8223 /*stripKindOf=*/true)) 8224 return {}; 8225 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 8226 // If only one has type arguments, the result will not have type 8227 // arguments. 8228 RHSTypeArgs = {}; 8229 anyChanges = true; 8230 } 8231 8232 // Compute the intersection of protocols. 8233 SmallVector<ObjCProtocolDecl *, 8> Protocols; 8234 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr, 8235 Protocols); 8236 if (!Protocols.empty()) 8237 anyChanges = true; 8238 8239 // If we need to return a kindof type but RHS is not a kindof type, we 8240 // build a new result type. 8241 if (anyChanges || RHS->isKindOfType() != anyKindOf) { 8242 QualType Result = getObjCInterfaceType(RHS->getInterface()); 8243 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols, 8244 anyKindOf || RHS->isKindOfType()); 8245 return getObjCObjectPointerType(Result); 8246 } 8247 8248 return getObjCObjectPointerType(QualType(RHS, 0)); 8249 } 8250 8251 // Find the superclass of the RHS. 8252 QualType RHSSuperType = RHS->getSuperClassType(); 8253 if (RHSSuperType.isNull()) 8254 break; 8255 8256 RHS = RHSSuperType->castAs<ObjCObjectType>(); 8257 } 8258 8259 return {}; 8260 } 8261 8262 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 8263 const ObjCObjectType *RHS) { 8264 assert(LHS->getInterface() && "LHS is not an interface type"); 8265 assert(RHS->getInterface() && "RHS is not an interface type"); 8266 8267 // Verify that the base decls are compatible: the RHS must be a subclass of 8268 // the LHS. 8269 ObjCInterfaceDecl *LHSInterface = LHS->getInterface(); 8270 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface()); 8271 if (!IsSuperClass) 8272 return false; 8273 8274 // If the LHS has protocol qualifiers, determine whether all of them are 8275 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the 8276 // LHS). 8277 if (LHS->getNumProtocols() > 0) { 8278 // OK if conversion of LHS to SuperClass results in narrowing of types 8279 // ; i.e., SuperClass may implement at least one of the protocols 8280 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 8281 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 8282 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 8283 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 8284 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's 8285 // qualifiers. 8286 for (auto *RHSPI : RHS->quals()) 8287 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols); 8288 // If there is no protocols associated with RHS, it is not a match. 8289 if (SuperClassInheritedProtocols.empty()) 8290 return false; 8291 8292 for (const auto *LHSProto : LHS->quals()) { 8293 bool SuperImplementsProtocol = false; 8294 for (auto *SuperClassProto : SuperClassInheritedProtocols) 8295 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 8296 SuperImplementsProtocol = true; 8297 break; 8298 } 8299 if (!SuperImplementsProtocol) 8300 return false; 8301 } 8302 } 8303 8304 // If the LHS is specialized, we may need to check type arguments. 8305 if (LHS->isSpecialized()) { 8306 // Follow the superclass chain until we've matched the LHS class in the 8307 // hierarchy. This substitutes type arguments through. 8308 const ObjCObjectType *RHSSuper = RHS; 8309 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface)) 8310 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>(); 8311 8312 // If the RHS is specializd, compare type arguments. 8313 if (RHSSuper->isSpecialized() && 8314 !sameObjCTypeArgs(*this, LHS->getInterface(), 8315 LHS->getTypeArgs(), RHSSuper->getTypeArgs(), 8316 /*stripKindOf=*/true)) { 8317 return false; 8318 } 8319 } 8320 8321 return true; 8322 } 8323 8324 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 8325 // get the "pointed to" types 8326 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 8327 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 8328 8329 if (!LHSOPT || !RHSOPT) 8330 return false; 8331 8332 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 8333 canAssignObjCInterfaces(RHSOPT, LHSOPT); 8334 } 8335 8336 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 8337 return canAssignObjCInterfaces( 8338 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(), 8339 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>()); 8340 } 8341 8342 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 8343 /// both shall have the identically qualified version of a compatible type. 8344 /// C99 6.2.7p1: Two types have compatible types if their types are the 8345 /// same. See 6.7.[2,3,5] for additional rules. 8346 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 8347 bool CompareUnqualified) { 8348 if (getLangOpts().CPlusPlus) 8349 return hasSameType(LHS, RHS); 8350 8351 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 8352 } 8353 8354 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 8355 return typesAreCompatible(LHS, RHS); 8356 } 8357 8358 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 8359 return !mergeTypes(LHS, RHS, true).isNull(); 8360 } 8361 8362 /// mergeTransparentUnionType - if T is a transparent union type and a member 8363 /// of T is compatible with SubType, return the merged type, else return 8364 /// QualType() 8365 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 8366 bool OfBlockPointer, 8367 bool Unqualified) { 8368 if (const RecordType *UT = T->getAsUnionType()) { 8369 RecordDecl *UD = UT->getDecl(); 8370 if (UD->hasAttr<TransparentUnionAttr>()) { 8371 for (const auto *I : UD->fields()) { 8372 QualType ET = I->getType().getUnqualifiedType(); 8373 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 8374 if (!MT.isNull()) 8375 return MT; 8376 } 8377 } 8378 } 8379 8380 return {}; 8381 } 8382 8383 /// mergeFunctionParameterTypes - merge two types which appear as function 8384 /// parameter types 8385 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 8386 bool OfBlockPointer, 8387 bool Unqualified) { 8388 // GNU extension: two types are compatible if they appear as a function 8389 // argument, one of the types is a transparent union type and the other 8390 // type is compatible with a union member 8391 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 8392 Unqualified); 8393 if (!lmerge.isNull()) 8394 return lmerge; 8395 8396 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 8397 Unqualified); 8398 if (!rmerge.isNull()) 8399 return rmerge; 8400 8401 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 8402 } 8403 8404 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 8405 bool OfBlockPointer, 8406 bool Unqualified) { 8407 const auto *lbase = lhs->getAs<FunctionType>(); 8408 const auto *rbase = rhs->getAs<FunctionType>(); 8409 const auto *lproto = dyn_cast<FunctionProtoType>(lbase); 8410 const auto *rproto = dyn_cast<FunctionProtoType>(rbase); 8411 bool allLTypes = true; 8412 bool allRTypes = true; 8413 8414 // Check return type 8415 QualType retType; 8416 if (OfBlockPointer) { 8417 QualType RHS = rbase->getReturnType(); 8418 QualType LHS = lbase->getReturnType(); 8419 bool UnqualifiedResult = Unqualified; 8420 if (!UnqualifiedResult) 8421 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 8422 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 8423 } 8424 else 8425 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 8426 Unqualified); 8427 if (retType.isNull()) 8428 return {}; 8429 8430 if (Unqualified) 8431 retType = retType.getUnqualifiedType(); 8432 8433 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 8434 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 8435 if (Unqualified) { 8436 LRetType = LRetType.getUnqualifiedType(); 8437 RRetType = RRetType.getUnqualifiedType(); 8438 } 8439 8440 if (getCanonicalType(retType) != LRetType) 8441 allLTypes = false; 8442 if (getCanonicalType(retType) != RRetType) 8443 allRTypes = false; 8444 8445 // FIXME: double check this 8446 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 8447 // rbase->getRegParmAttr() != 0 && 8448 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 8449 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 8450 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 8451 8452 // Compatible functions must have compatible calling conventions 8453 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 8454 return {}; 8455 8456 // Regparm is part of the calling convention. 8457 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 8458 return {}; 8459 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 8460 return {}; 8461 8462 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 8463 return {}; 8464 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs()) 8465 return {}; 8466 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck()) 8467 return {}; 8468 8469 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 8470 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 8471 8472 if (lbaseInfo.getNoReturn() != NoReturn) 8473 allLTypes = false; 8474 if (rbaseInfo.getNoReturn() != NoReturn) 8475 allRTypes = false; 8476 8477 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 8478 8479 if (lproto && rproto) { // two C99 style function prototypes 8480 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() && 8481 "C++ shouldn't be here"); 8482 // Compatible functions must have the same number of parameters 8483 if (lproto->getNumParams() != rproto->getNumParams()) 8484 return {}; 8485 8486 // Variadic and non-variadic functions aren't compatible 8487 if (lproto->isVariadic() != rproto->isVariadic()) 8488 return {}; 8489 8490 if (lproto->getTypeQuals() != rproto->getTypeQuals()) 8491 return {}; 8492 8493 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos; 8494 bool canUseLeft, canUseRight; 8495 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight, 8496 newParamInfos)) 8497 return {}; 8498 8499 if (!canUseLeft) 8500 allLTypes = false; 8501 if (!canUseRight) 8502 allRTypes = false; 8503 8504 // Check parameter type compatibility 8505 SmallVector<QualType, 10> types; 8506 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 8507 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 8508 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 8509 QualType paramType = mergeFunctionParameterTypes( 8510 lParamType, rParamType, OfBlockPointer, Unqualified); 8511 if (paramType.isNull()) 8512 return {}; 8513 8514 if (Unqualified) 8515 paramType = paramType.getUnqualifiedType(); 8516 8517 types.push_back(paramType); 8518 if (Unqualified) { 8519 lParamType = lParamType.getUnqualifiedType(); 8520 rParamType = rParamType.getUnqualifiedType(); 8521 } 8522 8523 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 8524 allLTypes = false; 8525 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 8526 allRTypes = false; 8527 } 8528 8529 if (allLTypes) return lhs; 8530 if (allRTypes) return rhs; 8531 8532 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 8533 EPI.ExtInfo = einfo; 8534 EPI.ExtParameterInfos = 8535 newParamInfos.empty() ? nullptr : newParamInfos.data(); 8536 return getFunctionType(retType, types, EPI); 8537 } 8538 8539 if (lproto) allRTypes = false; 8540 if (rproto) allLTypes = false; 8541 8542 const FunctionProtoType *proto = lproto ? lproto : rproto; 8543 if (proto) { 8544 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here"); 8545 if (proto->isVariadic()) 8546 return {}; 8547 // Check that the types are compatible with the types that 8548 // would result from default argument promotions (C99 6.7.5.3p15). 8549 // The only types actually affected are promotable integer 8550 // types and floats, which would be passed as a different 8551 // type depending on whether the prototype is visible. 8552 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 8553 QualType paramTy = proto->getParamType(i); 8554 8555 // Look at the converted type of enum types, since that is the type used 8556 // to pass enum values. 8557 if (const auto *Enum = paramTy->getAs<EnumType>()) { 8558 paramTy = Enum->getDecl()->getIntegerType(); 8559 if (paramTy.isNull()) 8560 return {}; 8561 } 8562 8563 if (paramTy->isPromotableIntegerType() || 8564 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 8565 return {}; 8566 } 8567 8568 if (allLTypes) return lhs; 8569 if (allRTypes) return rhs; 8570 8571 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 8572 EPI.ExtInfo = einfo; 8573 return getFunctionType(retType, proto->getParamTypes(), EPI); 8574 } 8575 8576 if (allLTypes) return lhs; 8577 if (allRTypes) return rhs; 8578 return getFunctionNoProtoType(retType, einfo); 8579 } 8580 8581 /// Given that we have an enum type and a non-enum type, try to merge them. 8582 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 8583 QualType other, bool isBlockReturnType) { 8584 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 8585 // a signed integer type, or an unsigned integer type. 8586 // Compatibility is based on the underlying type, not the promotion 8587 // type. 8588 QualType underlyingType = ET->getDecl()->getIntegerType(); 8589 if (underlyingType.isNull()) 8590 return {}; 8591 if (Context.hasSameType(underlyingType, other)) 8592 return other; 8593 8594 // In block return types, we're more permissive and accept any 8595 // integral type of the same size. 8596 if (isBlockReturnType && other->isIntegerType() && 8597 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 8598 return other; 8599 8600 return {}; 8601 } 8602 8603 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 8604 bool OfBlockPointer, 8605 bool Unqualified, bool BlockReturnType) { 8606 // C++ [expr]: If an expression initially has the type "reference to T", the 8607 // type is adjusted to "T" prior to any further analysis, the expression 8608 // designates the object or function denoted by the reference, and the 8609 // expression is an lvalue unless the reference is an rvalue reference and 8610 // the expression is a function call (possibly inside parentheses). 8611 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?"); 8612 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?"); 8613 8614 if (Unqualified) { 8615 LHS = LHS.getUnqualifiedType(); 8616 RHS = RHS.getUnqualifiedType(); 8617 } 8618 8619 QualType LHSCan = getCanonicalType(LHS), 8620 RHSCan = getCanonicalType(RHS); 8621 8622 // If two types are identical, they are compatible. 8623 if (LHSCan == RHSCan) 8624 return LHS; 8625 8626 // If the qualifiers are different, the types aren't compatible... mostly. 8627 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 8628 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 8629 if (LQuals != RQuals) { 8630 // If any of these qualifiers are different, we have a type 8631 // mismatch. 8632 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 8633 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 8634 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() || 8635 LQuals.hasUnaligned() != RQuals.hasUnaligned()) 8636 return {}; 8637 8638 // Exactly one GC qualifier difference is allowed: __strong is 8639 // okay if the other type has no GC qualifier but is an Objective 8640 // C object pointer (i.e. implicitly strong by default). We fix 8641 // this by pretending that the unqualified type was actually 8642 // qualified __strong. 8643 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 8644 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 8645 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 8646 8647 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 8648 return {}; 8649 8650 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 8651 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 8652 } 8653 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 8654 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 8655 } 8656 return {}; 8657 } 8658 8659 // Okay, qualifiers are equal. 8660 8661 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 8662 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 8663 8664 // We want to consider the two function types to be the same for these 8665 // comparisons, just force one to the other. 8666 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 8667 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 8668 8669 // Same as above for arrays 8670 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 8671 LHSClass = Type::ConstantArray; 8672 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 8673 RHSClass = Type::ConstantArray; 8674 8675 // ObjCInterfaces are just specialized ObjCObjects. 8676 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 8677 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 8678 8679 // Canonicalize ExtVector -> Vector. 8680 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 8681 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 8682 8683 // If the canonical type classes don't match. 8684 if (LHSClass != RHSClass) { 8685 // Note that we only have special rules for turning block enum 8686 // returns into block int returns, not vice-versa. 8687 if (const auto *ETy = LHS->getAs<EnumType>()) { 8688 return mergeEnumWithInteger(*this, ETy, RHS, false); 8689 } 8690 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 8691 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 8692 } 8693 // allow block pointer type to match an 'id' type. 8694 if (OfBlockPointer && !BlockReturnType) { 8695 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 8696 return LHS; 8697 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 8698 return RHS; 8699 } 8700 8701 return {}; 8702 } 8703 8704 // The canonical type classes match. 8705 switch (LHSClass) { 8706 #define TYPE(Class, Base) 8707 #define ABSTRACT_TYPE(Class, Base) 8708 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 8709 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 8710 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 8711 #include "clang/AST/TypeNodes.def" 8712 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 8713 8714 case Type::Auto: 8715 case Type::DeducedTemplateSpecialization: 8716 case Type::LValueReference: 8717 case Type::RValueReference: 8718 case Type::MemberPointer: 8719 llvm_unreachable("C++ should never be in mergeTypes"); 8720 8721 case Type::ObjCInterface: 8722 case Type::IncompleteArray: 8723 case Type::VariableArray: 8724 case Type::FunctionProto: 8725 case Type::ExtVector: 8726 llvm_unreachable("Types are eliminated above"); 8727 8728 case Type::Pointer: 8729 { 8730 // Merge two pointer types, while trying to preserve typedef info 8731 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType(); 8732 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType(); 8733 if (Unqualified) { 8734 LHSPointee = LHSPointee.getUnqualifiedType(); 8735 RHSPointee = RHSPointee.getUnqualifiedType(); 8736 } 8737 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 8738 Unqualified); 8739 if (ResultType.isNull()) 8740 return {}; 8741 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 8742 return LHS; 8743 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 8744 return RHS; 8745 return getPointerType(ResultType); 8746 } 8747 case Type::BlockPointer: 8748 { 8749 // Merge two block pointer types, while trying to preserve typedef info 8750 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType(); 8751 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType(); 8752 if (Unqualified) { 8753 LHSPointee = LHSPointee.getUnqualifiedType(); 8754 RHSPointee = RHSPointee.getUnqualifiedType(); 8755 } 8756 if (getLangOpts().OpenCL) { 8757 Qualifiers LHSPteeQual = LHSPointee.getQualifiers(); 8758 Qualifiers RHSPteeQual = RHSPointee.getQualifiers(); 8759 // Blocks can't be an expression in a ternary operator (OpenCL v2.0 8760 // 6.12.5) thus the following check is asymmetric. 8761 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual)) 8762 return {}; 8763 LHSPteeQual.removeAddressSpace(); 8764 RHSPteeQual.removeAddressSpace(); 8765 LHSPointee = 8766 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue()); 8767 RHSPointee = 8768 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue()); 8769 } 8770 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 8771 Unqualified); 8772 if (ResultType.isNull()) 8773 return {}; 8774 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 8775 return LHS; 8776 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 8777 return RHS; 8778 return getBlockPointerType(ResultType); 8779 } 8780 case Type::Atomic: 8781 { 8782 // Merge two pointer types, while trying to preserve typedef info 8783 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType(); 8784 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType(); 8785 if (Unqualified) { 8786 LHSValue = LHSValue.getUnqualifiedType(); 8787 RHSValue = RHSValue.getUnqualifiedType(); 8788 } 8789 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 8790 Unqualified); 8791 if (ResultType.isNull()) 8792 return {}; 8793 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 8794 return LHS; 8795 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 8796 return RHS; 8797 return getAtomicType(ResultType); 8798 } 8799 case Type::ConstantArray: 8800 { 8801 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 8802 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 8803 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 8804 return {}; 8805 8806 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 8807 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 8808 if (Unqualified) { 8809 LHSElem = LHSElem.getUnqualifiedType(); 8810 RHSElem = RHSElem.getUnqualifiedType(); 8811 } 8812 8813 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 8814 if (ResultType.isNull()) 8815 return {}; 8816 8817 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 8818 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 8819 8820 // If either side is a variable array, and both are complete, check whether 8821 // the current dimension is definite. 8822 if (LVAT || RVAT) { 8823 auto SizeFetch = [this](const VariableArrayType* VAT, 8824 const ConstantArrayType* CAT) 8825 -> std::pair<bool,llvm::APInt> { 8826 if (VAT) { 8827 llvm::APSInt TheInt; 8828 Expr *E = VAT->getSizeExpr(); 8829 if (E && E->isIntegerConstantExpr(TheInt, *this)) 8830 return std::make_pair(true, TheInt); 8831 else 8832 return std::make_pair(false, TheInt); 8833 } else if (CAT) { 8834 return std::make_pair(true, CAT->getSize()); 8835 } else { 8836 return std::make_pair(false, llvm::APInt()); 8837 } 8838 }; 8839 8840 bool HaveLSize, HaveRSize; 8841 llvm::APInt LSize, RSize; 8842 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT); 8843 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT); 8844 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize)) 8845 return {}; // Definite, but unequal, array dimension 8846 } 8847 8848 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 8849 return LHS; 8850 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 8851 return RHS; 8852 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), 8853 ArrayType::ArraySizeModifier(), 0); 8854 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), 8855 ArrayType::ArraySizeModifier(), 0); 8856 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 8857 return LHS; 8858 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 8859 return RHS; 8860 if (LVAT) { 8861 // FIXME: This isn't correct! But tricky to implement because 8862 // the array's size has to be the size of LHS, but the type 8863 // has to be different. 8864 return LHS; 8865 } 8866 if (RVAT) { 8867 // FIXME: This isn't correct! But tricky to implement because 8868 // the array's size has to be the size of RHS, but the type 8869 // has to be different. 8870 return RHS; 8871 } 8872 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 8873 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 8874 return getIncompleteArrayType(ResultType, 8875 ArrayType::ArraySizeModifier(), 0); 8876 } 8877 case Type::FunctionNoProto: 8878 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 8879 case Type::Record: 8880 case Type::Enum: 8881 return {}; 8882 case Type::Builtin: 8883 // Only exactly equal builtin types are compatible, which is tested above. 8884 return {}; 8885 case Type::Complex: 8886 // Distinct complex types are incompatible. 8887 return {}; 8888 case Type::Vector: 8889 // FIXME: The merged type should be an ExtVector! 8890 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(), 8891 RHSCan->getAs<VectorType>())) 8892 return LHS; 8893 return {}; 8894 case Type::ObjCObject: { 8895 // Check if the types are assignment compatible. 8896 // FIXME: This should be type compatibility, e.g. whether 8897 // "LHS x; RHS x;" at global scope is legal. 8898 const auto *LHSIface = LHS->getAs<ObjCObjectType>(); 8899 const auto *RHSIface = RHS->getAs<ObjCObjectType>(); 8900 if (canAssignObjCInterfaces(LHSIface, RHSIface)) 8901 return LHS; 8902 8903 return {}; 8904 } 8905 case Type::ObjCObjectPointer: 8906 if (OfBlockPointer) { 8907 if (canAssignObjCInterfacesInBlockPointer( 8908 LHS->getAs<ObjCObjectPointerType>(), 8909 RHS->getAs<ObjCObjectPointerType>(), 8910 BlockReturnType)) 8911 return LHS; 8912 return {}; 8913 } 8914 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(), 8915 RHS->getAs<ObjCObjectPointerType>())) 8916 return LHS; 8917 8918 return {}; 8919 case Type::Pipe: 8920 assert(LHS != RHS && 8921 "Equivalent pipe types should have already been handled!"); 8922 return {}; 8923 } 8924 8925 llvm_unreachable("Invalid Type::Class!"); 8926 } 8927 8928 bool ASTContext::mergeExtParameterInfo( 8929 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, 8930 bool &CanUseFirst, bool &CanUseSecond, 8931 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) { 8932 assert(NewParamInfos.empty() && "param info list not empty"); 8933 CanUseFirst = CanUseSecond = true; 8934 bool FirstHasInfo = FirstFnType->hasExtParameterInfos(); 8935 bool SecondHasInfo = SecondFnType->hasExtParameterInfos(); 8936 8937 // Fast path: if the first type doesn't have ext parameter infos, 8938 // we match if and only if the second type also doesn't have them. 8939 if (!FirstHasInfo && !SecondHasInfo) 8940 return true; 8941 8942 bool NeedParamInfo = false; 8943 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size() 8944 : SecondFnType->getExtParameterInfos().size(); 8945 8946 for (size_t I = 0; I < E; ++I) { 8947 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam; 8948 if (FirstHasInfo) 8949 FirstParam = FirstFnType->getExtParameterInfo(I); 8950 if (SecondHasInfo) 8951 SecondParam = SecondFnType->getExtParameterInfo(I); 8952 8953 // Cannot merge unless everything except the noescape flag matches. 8954 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false)) 8955 return false; 8956 8957 bool FirstNoEscape = FirstParam.isNoEscape(); 8958 bool SecondNoEscape = SecondParam.isNoEscape(); 8959 bool IsNoEscape = FirstNoEscape && SecondNoEscape; 8960 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape)); 8961 if (NewParamInfos.back().getOpaqueValue()) 8962 NeedParamInfo = true; 8963 if (FirstNoEscape != IsNoEscape) 8964 CanUseFirst = false; 8965 if (SecondNoEscape != IsNoEscape) 8966 CanUseSecond = false; 8967 } 8968 8969 if (!NeedParamInfo) 8970 NewParamInfos.clear(); 8971 8972 return true; 8973 } 8974 8975 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) { 8976 ObjCLayouts[CD] = nullptr; 8977 } 8978 8979 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 8980 /// 'RHS' attributes and returns the merged version; including for function 8981 /// return types. 8982 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 8983 QualType LHSCan = getCanonicalType(LHS), 8984 RHSCan = getCanonicalType(RHS); 8985 // If two types are identical, they are compatible. 8986 if (LHSCan == RHSCan) 8987 return LHS; 8988 if (RHSCan->isFunctionType()) { 8989 if (!LHSCan->isFunctionType()) 8990 return {}; 8991 QualType OldReturnType = 8992 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 8993 QualType NewReturnType = 8994 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 8995 QualType ResReturnType = 8996 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 8997 if (ResReturnType.isNull()) 8998 return {}; 8999 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 9000 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 9001 // In either case, use OldReturnType to build the new function type. 9002 const auto *F = LHS->getAs<FunctionType>(); 9003 if (const auto *FPT = cast<FunctionProtoType>(F)) { 9004 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9005 EPI.ExtInfo = getFunctionExtInfo(LHS); 9006 QualType ResultType = 9007 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 9008 return ResultType; 9009 } 9010 } 9011 return {}; 9012 } 9013 9014 // If the qualifiers are different, the types can still be merged. 9015 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 9016 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 9017 if (LQuals != RQuals) { 9018 // If any of these qualifiers are different, we have a type mismatch. 9019 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 9020 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 9021 return {}; 9022 9023 // Exactly one GC qualifier difference is allowed: __strong is 9024 // okay if the other type has no GC qualifier but is an Objective 9025 // C object pointer (i.e. implicitly strong by default). We fix 9026 // this by pretending that the unqualified type was actually 9027 // qualified __strong. 9028 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 9029 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 9030 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 9031 9032 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 9033 return {}; 9034 9035 if (GC_L == Qualifiers::Strong) 9036 return LHS; 9037 if (GC_R == Qualifiers::Strong) 9038 return RHS; 9039 return {}; 9040 } 9041 9042 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 9043 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 9044 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 9045 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 9046 if (ResQT == LHSBaseQT) 9047 return LHS; 9048 if (ResQT == RHSBaseQT) 9049 return RHS; 9050 } 9051 return {}; 9052 } 9053 9054 //===----------------------------------------------------------------------===// 9055 // Integer Predicates 9056 //===----------------------------------------------------------------------===// 9057 9058 unsigned ASTContext::getIntWidth(QualType T) const { 9059 if (const auto *ET = T->getAs<EnumType>()) 9060 T = ET->getDecl()->getIntegerType(); 9061 if (T->isBooleanType()) 9062 return 1; 9063 // For builtin types, just use the standard type sizing method 9064 return (unsigned)getTypeSize(T); 9065 } 9066 9067 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 9068 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) && 9069 "Unexpected type"); 9070 9071 // Turn <4 x signed int> -> <4 x unsigned int> 9072 if (const auto *VTy = T->getAs<VectorType>()) 9073 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 9074 VTy->getNumElements(), VTy->getVectorKind()); 9075 9076 // For enums, we return the unsigned version of the base type. 9077 if (const auto *ETy = T->getAs<EnumType>()) 9078 T = ETy->getDecl()->getIntegerType(); 9079 9080 const auto *BTy = T->getAs<BuiltinType>(); 9081 assert(BTy && "Unexpected signed integer or fixed point type"); 9082 switch (BTy->getKind()) { 9083 case BuiltinType::Char_S: 9084 case BuiltinType::SChar: 9085 return UnsignedCharTy; 9086 case BuiltinType::Short: 9087 return UnsignedShortTy; 9088 case BuiltinType::Int: 9089 return UnsignedIntTy; 9090 case BuiltinType::Long: 9091 return UnsignedLongTy; 9092 case BuiltinType::LongLong: 9093 return UnsignedLongLongTy; 9094 case BuiltinType::Int128: 9095 return UnsignedInt128Ty; 9096 9097 case BuiltinType::ShortAccum: 9098 return UnsignedShortAccumTy; 9099 case BuiltinType::Accum: 9100 return UnsignedAccumTy; 9101 case BuiltinType::LongAccum: 9102 return UnsignedLongAccumTy; 9103 case BuiltinType::SatShortAccum: 9104 return SatUnsignedShortAccumTy; 9105 case BuiltinType::SatAccum: 9106 return SatUnsignedAccumTy; 9107 case BuiltinType::SatLongAccum: 9108 return SatUnsignedLongAccumTy; 9109 case BuiltinType::ShortFract: 9110 return UnsignedShortFractTy; 9111 case BuiltinType::Fract: 9112 return UnsignedFractTy; 9113 case BuiltinType::LongFract: 9114 return UnsignedLongFractTy; 9115 case BuiltinType::SatShortFract: 9116 return SatUnsignedShortFractTy; 9117 case BuiltinType::SatFract: 9118 return SatUnsignedFractTy; 9119 case BuiltinType::SatLongFract: 9120 return SatUnsignedLongFractTy; 9121 default: 9122 llvm_unreachable("Unexpected signed integer or fixed point type"); 9123 } 9124 } 9125 9126 ASTMutationListener::~ASTMutationListener() = default; 9127 9128 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 9129 QualType ReturnType) {} 9130 9131 //===----------------------------------------------------------------------===// 9132 // Builtin Type Computation 9133 //===----------------------------------------------------------------------===// 9134 9135 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 9136 /// pointer over the consumed characters. This returns the resultant type. If 9137 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic 9138 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 9139 /// a vector of "i*". 9140 /// 9141 /// RequiresICE is filled in on return to indicate whether the value is required 9142 /// to be an Integer Constant Expression. 9143 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 9144 ASTContext::GetBuiltinTypeError &Error, 9145 bool &RequiresICE, 9146 bool AllowTypeModifiers) { 9147 // Modifiers. 9148 int HowLong = 0; 9149 bool Signed = false, Unsigned = false; 9150 RequiresICE = false; 9151 9152 // Read the prefixed modifiers first. 9153 bool Done = false; 9154 #ifndef NDEBUG 9155 bool IsSpecialLong = false; 9156 #endif 9157 while (!Done) { 9158 switch (*Str++) { 9159 default: Done = true; --Str; break; 9160 case 'I': 9161 RequiresICE = true; 9162 break; 9163 case 'S': 9164 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 9165 assert(!Signed && "Can't use 'S' modifier multiple times!"); 9166 Signed = true; 9167 break; 9168 case 'U': 9169 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 9170 assert(!Unsigned && "Can't use 'U' modifier multiple times!"); 9171 Unsigned = true; 9172 break; 9173 case 'L': 9174 assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers"); 9175 assert(HowLong <= 2 && "Can't have LLLL modifier"); 9176 ++HowLong; 9177 break; 9178 case 'N': 9179 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise. 9180 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!"); 9181 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!"); 9182 #ifndef NDEBUG 9183 IsSpecialLong = true; 9184 #endif 9185 if (Context.getTargetInfo().getLongWidth() == 32) 9186 ++HowLong; 9187 break; 9188 case 'W': 9189 // This modifier represents int64 type. 9190 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!"); 9191 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 9192 #ifndef NDEBUG 9193 IsSpecialLong = true; 9194 #endif 9195 switch (Context.getTargetInfo().getInt64Type()) { 9196 default: 9197 llvm_unreachable("Unexpected integer type"); 9198 case TargetInfo::SignedLong: 9199 HowLong = 1; 9200 break; 9201 case TargetInfo::SignedLongLong: 9202 HowLong = 2; 9203 break; 9204 } 9205 break; 9206 } 9207 } 9208 9209 QualType Type; 9210 9211 // Read the base type. 9212 switch (*Str++) { 9213 default: llvm_unreachable("Unknown builtin type letter!"); 9214 case 'v': 9215 assert(HowLong == 0 && !Signed && !Unsigned && 9216 "Bad modifiers used with 'v'!"); 9217 Type = Context.VoidTy; 9218 break; 9219 case 'h': 9220 assert(HowLong == 0 && !Signed && !Unsigned && 9221 "Bad modifiers used with 'h'!"); 9222 Type = Context.HalfTy; 9223 break; 9224 case 'f': 9225 assert(HowLong == 0 && !Signed && !Unsigned && 9226 "Bad modifiers used with 'f'!"); 9227 Type = Context.FloatTy; 9228 break; 9229 case 'd': 9230 assert(HowLong < 3 && !Signed && !Unsigned && 9231 "Bad modifiers used with 'd'!"); 9232 if (HowLong == 1) 9233 Type = Context.LongDoubleTy; 9234 else if (HowLong == 2) 9235 Type = Context.Float128Ty; 9236 else 9237 Type = Context.DoubleTy; 9238 break; 9239 case 's': 9240 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 9241 if (Unsigned) 9242 Type = Context.UnsignedShortTy; 9243 else 9244 Type = Context.ShortTy; 9245 break; 9246 case 'i': 9247 if (HowLong == 3) 9248 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 9249 else if (HowLong == 2) 9250 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 9251 else if (HowLong == 1) 9252 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 9253 else 9254 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 9255 break; 9256 case 'c': 9257 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 9258 if (Signed) 9259 Type = Context.SignedCharTy; 9260 else if (Unsigned) 9261 Type = Context.UnsignedCharTy; 9262 else 9263 Type = Context.CharTy; 9264 break; 9265 case 'b': // boolean 9266 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 9267 Type = Context.BoolTy; 9268 break; 9269 case 'z': // size_t. 9270 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 9271 Type = Context.getSizeType(); 9272 break; 9273 case 'w': // wchar_t. 9274 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!"); 9275 Type = Context.getWideCharType(); 9276 break; 9277 case 'F': 9278 Type = Context.getCFConstantStringType(); 9279 break; 9280 case 'G': 9281 Type = Context.getObjCIdType(); 9282 break; 9283 case 'H': 9284 Type = Context.getObjCSelType(); 9285 break; 9286 case 'M': 9287 Type = Context.getObjCSuperType(); 9288 break; 9289 case 'a': 9290 Type = Context.getBuiltinVaListType(); 9291 assert(!Type.isNull() && "builtin va list type not initialized!"); 9292 break; 9293 case 'A': 9294 // This is a "reference" to a va_list; however, what exactly 9295 // this means depends on how va_list is defined. There are two 9296 // different kinds of va_list: ones passed by value, and ones 9297 // passed by reference. An example of a by-value va_list is 9298 // x86, where va_list is a char*. An example of by-ref va_list 9299 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 9300 // we want this argument to be a char*&; for x86-64, we want 9301 // it to be a __va_list_tag*. 9302 Type = Context.getBuiltinVaListType(); 9303 assert(!Type.isNull() && "builtin va list type not initialized!"); 9304 if (Type->isArrayType()) 9305 Type = Context.getArrayDecayedType(Type); 9306 else 9307 Type = Context.getLValueReferenceType(Type); 9308 break; 9309 case 'V': { 9310 char *End; 9311 unsigned NumElements = strtoul(Str, &End, 10); 9312 assert(End != Str && "Missing vector size"); 9313 Str = End; 9314 9315 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 9316 RequiresICE, false); 9317 assert(!RequiresICE && "Can't require vector ICE"); 9318 9319 // TODO: No way to make AltiVec vectors in builtins yet. 9320 Type = Context.getVectorType(ElementType, NumElements, 9321 VectorType::GenericVector); 9322 break; 9323 } 9324 case 'E': { 9325 char *End; 9326 9327 unsigned NumElements = strtoul(Str, &End, 10); 9328 assert(End != Str && "Missing vector size"); 9329 9330 Str = End; 9331 9332 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 9333 false); 9334 Type = Context.getExtVectorType(ElementType, NumElements); 9335 break; 9336 } 9337 case 'X': { 9338 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 9339 false); 9340 assert(!RequiresICE && "Can't require complex ICE"); 9341 Type = Context.getComplexType(ElementType); 9342 break; 9343 } 9344 case 'Y': 9345 Type = Context.getPointerDiffType(); 9346 break; 9347 case 'P': 9348 Type = Context.getFILEType(); 9349 if (Type.isNull()) { 9350 Error = ASTContext::GE_Missing_stdio; 9351 return {}; 9352 } 9353 break; 9354 case 'J': 9355 if (Signed) 9356 Type = Context.getsigjmp_bufType(); 9357 else 9358 Type = Context.getjmp_bufType(); 9359 9360 if (Type.isNull()) { 9361 Error = ASTContext::GE_Missing_setjmp; 9362 return {}; 9363 } 9364 break; 9365 case 'K': 9366 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 9367 Type = Context.getucontext_tType(); 9368 9369 if (Type.isNull()) { 9370 Error = ASTContext::GE_Missing_ucontext; 9371 return {}; 9372 } 9373 break; 9374 case 'p': 9375 Type = Context.getProcessIDType(); 9376 break; 9377 } 9378 9379 // If there are modifiers and if we're allowed to parse them, go for it. 9380 Done = !AllowTypeModifiers; 9381 while (!Done) { 9382 switch (char c = *Str++) { 9383 default: Done = true; --Str; break; 9384 case '*': 9385 case '&': { 9386 // Both pointers and references can have their pointee types 9387 // qualified with an address space. 9388 char *End; 9389 unsigned AddrSpace = strtoul(Str, &End, 10); 9390 if (End != Str) { 9391 // Note AddrSpace == 0 is not the same as an unspecified address space. 9392 Type = Context.getAddrSpaceQualType( 9393 Type, 9394 Context.getLangASForBuiltinAddressSpace(AddrSpace)); 9395 Str = End; 9396 } 9397 if (c == '*') 9398 Type = Context.getPointerType(Type); 9399 else 9400 Type = Context.getLValueReferenceType(Type); 9401 break; 9402 } 9403 // FIXME: There's no way to have a built-in with an rvalue ref arg. 9404 case 'C': 9405 Type = Type.withConst(); 9406 break; 9407 case 'D': 9408 Type = Context.getVolatileType(Type); 9409 break; 9410 case 'R': 9411 Type = Type.withRestrict(); 9412 break; 9413 } 9414 } 9415 9416 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 9417 "Integer constant 'I' type must be an integer"); 9418 9419 return Type; 9420 } 9421 9422 /// GetBuiltinType - Return the type for the specified builtin. 9423 QualType ASTContext::GetBuiltinType(unsigned Id, 9424 GetBuiltinTypeError &Error, 9425 unsigned *IntegerConstantArgs) const { 9426 const char *TypeStr = BuiltinInfo.getTypeString(Id); 9427 9428 SmallVector<QualType, 8> ArgTypes; 9429 9430 bool RequiresICE = false; 9431 Error = GE_None; 9432 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 9433 RequiresICE, true); 9434 if (Error != GE_None) 9435 return {}; 9436 9437 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 9438 9439 while (TypeStr[0] && TypeStr[0] != '.') { 9440 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 9441 if (Error != GE_None) 9442 return {}; 9443 9444 // If this argument is required to be an IntegerConstantExpression and the 9445 // caller cares, fill in the bitmask we return. 9446 if (RequiresICE && IntegerConstantArgs) 9447 *IntegerConstantArgs |= 1 << ArgTypes.size(); 9448 9449 // Do array -> pointer decay. The builtin should use the decayed type. 9450 if (Ty->isArrayType()) 9451 Ty = getArrayDecayedType(Ty); 9452 9453 ArgTypes.push_back(Ty); 9454 } 9455 9456 if (Id == Builtin::BI__GetExceptionInfo) 9457 return {}; 9458 9459 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 9460 "'.' should only occur at end of builtin type list!"); 9461 9462 FunctionType::ExtInfo EI(CC_C); 9463 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 9464 9465 bool Variadic = (TypeStr[0] == '.'); 9466 9467 // We really shouldn't be making a no-proto type here. 9468 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus) 9469 return getFunctionNoProtoType(ResType, EI); 9470 9471 FunctionProtoType::ExtProtoInfo EPI; 9472 EPI.ExtInfo = EI; 9473 EPI.Variadic = Variadic; 9474 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id)) 9475 EPI.ExceptionSpec.Type = 9476 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 9477 9478 return getFunctionType(ResType, ArgTypes, EPI); 9479 } 9480 9481 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 9482 const FunctionDecl *FD) { 9483 if (!FD->isExternallyVisible()) 9484 return GVA_Internal; 9485 9486 // Non-user-provided functions get emitted as weak definitions with every 9487 // use, no matter whether they've been explicitly instantiated etc. 9488 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 9489 if (!MD->isUserProvided()) 9490 return GVA_DiscardableODR; 9491 9492 GVALinkage External; 9493 switch (FD->getTemplateSpecializationKind()) { 9494 case TSK_Undeclared: 9495 case TSK_ExplicitSpecialization: 9496 External = GVA_StrongExternal; 9497 break; 9498 9499 case TSK_ExplicitInstantiationDefinition: 9500 return GVA_StrongODR; 9501 9502 // C++11 [temp.explicit]p10: 9503 // [ Note: The intent is that an inline function that is the subject of 9504 // an explicit instantiation declaration will still be implicitly 9505 // instantiated when used so that the body can be considered for 9506 // inlining, but that no out-of-line copy of the inline function would be 9507 // generated in the translation unit. -- end note ] 9508 case TSK_ExplicitInstantiationDeclaration: 9509 return GVA_AvailableExternally; 9510 9511 case TSK_ImplicitInstantiation: 9512 External = GVA_DiscardableODR; 9513 break; 9514 } 9515 9516 if (!FD->isInlined()) 9517 return External; 9518 9519 if ((!Context.getLangOpts().CPlusPlus && 9520 !Context.getTargetInfo().getCXXABI().isMicrosoft() && 9521 !FD->hasAttr<DLLExportAttr>()) || 9522 FD->hasAttr<GNUInlineAttr>()) { 9523 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 9524 9525 // GNU or C99 inline semantics. Determine whether this symbol should be 9526 // externally visible. 9527 if (FD->isInlineDefinitionExternallyVisible()) 9528 return External; 9529 9530 // C99 inline semantics, where the symbol is not externally visible. 9531 return GVA_AvailableExternally; 9532 } 9533 9534 // Functions specified with extern and inline in -fms-compatibility mode 9535 // forcibly get emitted. While the body of the function cannot be later 9536 // replaced, the function definition cannot be discarded. 9537 if (FD->isMSExternInline()) 9538 return GVA_StrongODR; 9539 9540 return GVA_DiscardableODR; 9541 } 9542 9543 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, 9544 const Decl *D, GVALinkage L) { 9545 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx 9546 // dllexport/dllimport on inline functions. 9547 if (D->hasAttr<DLLImportAttr>()) { 9548 if (L == GVA_DiscardableODR || L == GVA_StrongODR) 9549 return GVA_AvailableExternally; 9550 } else if (D->hasAttr<DLLExportAttr>()) { 9551 if (L == GVA_DiscardableODR) 9552 return GVA_StrongODR; 9553 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice && 9554 D->hasAttr<CUDAGlobalAttr>()) { 9555 // Device-side functions with __global__ attribute must always be 9556 // visible externally so they can be launched from host. 9557 if (L == GVA_DiscardableODR || L == GVA_Internal) 9558 return GVA_StrongODR; 9559 } 9560 return L; 9561 } 9562 9563 /// Adjust the GVALinkage for a declaration based on what an external AST source 9564 /// knows about whether there can be other definitions of this declaration. 9565 static GVALinkage 9566 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, 9567 GVALinkage L) { 9568 ExternalASTSource *Source = Ctx.getExternalSource(); 9569 if (!Source) 9570 return L; 9571 9572 switch (Source->hasExternalDefinitions(D)) { 9573 case ExternalASTSource::EK_Never: 9574 // Other translation units rely on us to provide the definition. 9575 if (L == GVA_DiscardableODR) 9576 return GVA_StrongODR; 9577 break; 9578 9579 case ExternalASTSource::EK_Always: 9580 return GVA_AvailableExternally; 9581 9582 case ExternalASTSource::EK_ReplyHazy: 9583 break; 9584 } 9585 return L; 9586 } 9587 9588 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { 9589 return adjustGVALinkageForExternalDefinitionKind(*this, FD, 9590 adjustGVALinkageForAttributes(*this, FD, 9591 basicGVALinkageForFunction(*this, FD))); 9592 } 9593 9594 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, 9595 const VarDecl *VD) { 9596 if (!VD->isExternallyVisible()) 9597 return GVA_Internal; 9598 9599 if (VD->isStaticLocal()) { 9600 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); 9601 while (LexicalContext && !isa<FunctionDecl>(LexicalContext)) 9602 LexicalContext = LexicalContext->getLexicalParent(); 9603 9604 // ObjC Blocks can create local variables that don't have a FunctionDecl 9605 // LexicalContext. 9606 if (!LexicalContext) 9607 return GVA_DiscardableODR; 9608 9609 // Otherwise, let the static local variable inherit its linkage from the 9610 // nearest enclosing function. 9611 auto StaticLocalLinkage = 9612 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext)); 9613 9614 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must 9615 // be emitted in any object with references to the symbol for the object it 9616 // contains, whether inline or out-of-line." 9617 // Similar behavior is observed with MSVC. An alternative ABI could use 9618 // StrongODR/AvailableExternally to match the function, but none are 9619 // known/supported currently. 9620 if (StaticLocalLinkage == GVA_StrongODR || 9621 StaticLocalLinkage == GVA_AvailableExternally) 9622 return GVA_DiscardableODR; 9623 return StaticLocalLinkage; 9624 } 9625 9626 // MSVC treats in-class initialized static data members as definitions. 9627 // By giving them non-strong linkage, out-of-line definitions won't 9628 // cause link errors. 9629 if (Context.isMSStaticDataMemberInlineDefinition(VD)) 9630 return GVA_DiscardableODR; 9631 9632 // Most non-template variables have strong linkage; inline variables are 9633 // linkonce_odr or (occasionally, for compatibility) weak_odr. 9634 GVALinkage StrongLinkage; 9635 switch (Context.getInlineVariableDefinitionKind(VD)) { 9636 case ASTContext::InlineVariableDefinitionKind::None: 9637 StrongLinkage = GVA_StrongExternal; 9638 break; 9639 case ASTContext::InlineVariableDefinitionKind::Weak: 9640 case ASTContext::InlineVariableDefinitionKind::WeakUnknown: 9641 StrongLinkage = GVA_DiscardableODR; 9642 break; 9643 case ASTContext::InlineVariableDefinitionKind::Strong: 9644 StrongLinkage = GVA_StrongODR; 9645 break; 9646 } 9647 9648 switch (VD->getTemplateSpecializationKind()) { 9649 case TSK_Undeclared: 9650 return StrongLinkage; 9651 9652 case TSK_ExplicitSpecialization: 9653 return Context.getTargetInfo().getCXXABI().isMicrosoft() && 9654 VD->isStaticDataMember() 9655 ? GVA_StrongODR 9656 : StrongLinkage; 9657 9658 case TSK_ExplicitInstantiationDefinition: 9659 return GVA_StrongODR; 9660 9661 case TSK_ExplicitInstantiationDeclaration: 9662 return GVA_AvailableExternally; 9663 9664 case TSK_ImplicitInstantiation: 9665 return GVA_DiscardableODR; 9666 } 9667 9668 llvm_unreachable("Invalid Linkage!"); 9669 } 9670 9671 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 9672 return adjustGVALinkageForExternalDefinitionKind(*this, VD, 9673 adjustGVALinkageForAttributes(*this, VD, 9674 basicGVALinkageForVariable(*this, VD))); 9675 } 9676 9677 bool ASTContext::DeclMustBeEmitted(const Decl *D) { 9678 if (const auto *VD = dyn_cast<VarDecl>(D)) { 9679 if (!VD->isFileVarDecl()) 9680 return false; 9681 // Global named register variables (GNU extension) are never emitted. 9682 if (VD->getStorageClass() == SC_Register) 9683 return false; 9684 if (VD->getDescribedVarTemplate() || 9685 isa<VarTemplatePartialSpecializationDecl>(VD)) 9686 return false; 9687 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 9688 // We never need to emit an uninstantiated function template. 9689 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 9690 return false; 9691 } else if (isa<PragmaCommentDecl>(D)) 9692 return true; 9693 else if (isa<OMPThreadPrivateDecl>(D)) 9694 return true; 9695 else if (isa<PragmaDetectMismatchDecl>(D)) 9696 return true; 9697 else if (isa<OMPThreadPrivateDecl>(D)) 9698 return !D->getDeclContext()->isDependentContext(); 9699 else if (isa<OMPDeclareReductionDecl>(D)) 9700 return !D->getDeclContext()->isDependentContext(); 9701 else if (isa<ImportDecl>(D)) 9702 return true; 9703 else 9704 return false; 9705 9706 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) { 9707 assert(getExternalSource() && "It's from an AST file; must have a source."); 9708 // On Windows, PCH files are built together with an object file. If this 9709 // declaration comes from such a PCH and DeclMustBeEmitted would return 9710 // true, it would have returned true and the decl would have been emitted 9711 // into that object file, so it doesn't need to be emitted here. 9712 // Note that decls are still emitted if they're referenced, as usual; 9713 // DeclMustBeEmitted is used to decide whether a decl must be emitted even 9714 // if it's not referenced. 9715 // 9716 // Explicit template instantiation definitions are tricky. If there was an 9717 // explicit template instantiation decl in the PCH before, it will look like 9718 // the definition comes from there, even if that was just the declaration. 9719 // (Explicit instantiation defs of variable templates always get emitted.) 9720 bool IsExpInstDef = 9721 isa<FunctionDecl>(D) && 9722 cast<FunctionDecl>(D)->getTemplateSpecializationKind() == 9723 TSK_ExplicitInstantiationDefinition; 9724 9725 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef) 9726 return false; 9727 } 9728 9729 // If this is a member of a class template, we do not need to emit it. 9730 if (D->getDeclContext()->isDependentContext()) 9731 return false; 9732 9733 // Weak references don't produce any output by themselves. 9734 if (D->hasAttr<WeakRefAttr>()) 9735 return false; 9736 9737 // Aliases and used decls are required. 9738 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 9739 return true; 9740 9741 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 9742 // Forward declarations aren't required. 9743 if (!FD->doesThisDeclarationHaveABody()) 9744 return FD->doesDeclarationForceExternallyVisibleDefinition(); 9745 9746 // Constructors and destructors are required. 9747 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 9748 return true; 9749 9750 // The key function for a class is required. This rule only comes 9751 // into play when inline functions can be key functions, though. 9752 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 9753 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 9754 const CXXRecordDecl *RD = MD->getParent(); 9755 if (MD->isOutOfLine() && RD->isDynamicClass()) { 9756 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); 9757 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 9758 return true; 9759 } 9760 } 9761 } 9762 9763 GVALinkage Linkage = GetGVALinkageForFunction(FD); 9764 9765 // static, static inline, always_inline, and extern inline functions can 9766 // always be deferred. Normal inline functions can be deferred in C99/C++. 9767 // Implicit template instantiations can also be deferred in C++. 9768 return !isDiscardableGVALinkage(Linkage); 9769 } 9770 9771 const auto *VD = cast<VarDecl>(D); 9772 assert(VD->isFileVarDecl() && "Expected file scoped var"); 9773 9774 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly && 9775 !isMSStaticDataMemberInlineDefinition(VD)) 9776 return false; 9777 9778 // Variables that can be needed in other TUs are required. 9779 auto Linkage = GetGVALinkageForVariable(VD); 9780 if (!isDiscardableGVALinkage(Linkage)) 9781 return true; 9782 9783 // We never need to emit a variable that is available in another TU. 9784 if (Linkage == GVA_AvailableExternally) 9785 return false; 9786 9787 // Variables that have destruction with side-effects are required. 9788 if (VD->getType().isDestructedType()) 9789 return true; 9790 9791 // Variables that have initialization with side-effects are required. 9792 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) && 9793 // We can get a value-dependent initializer during error recovery. 9794 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 9795 return true; 9796 9797 // Likewise, variables with tuple-like bindings are required if their 9798 // bindings have side-effects. 9799 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) 9800 for (const auto *BD : DD->bindings()) 9801 if (const auto *BindingVD = BD->getHoldingVar()) 9802 if (DeclMustBeEmitted(BindingVD)) 9803 return true; 9804 9805 // If the decl is marked as `declare target`, it should be emitted. 9806 for (const auto *Decl : D->redecls()) { 9807 if (!Decl->hasAttrs()) 9808 continue; 9809 if (const auto *Attr = Decl->getAttr<OMPDeclareTargetDeclAttr>()) 9810 if (Attr->getMapType() != OMPDeclareTargetDeclAttr::MT_Link) 9811 return true; 9812 } 9813 9814 return false; 9815 } 9816 9817 void ASTContext::forEachMultiversionedFunctionVersion( 9818 const FunctionDecl *FD, 9819 llvm::function_ref<void(const FunctionDecl *)> Pred) const { 9820 assert(FD->isMultiVersion() && "Only valid for multiversioned functions"); 9821 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls; 9822 FD = FD->getCanonicalDecl(); 9823 for (auto *CurDecl : 9824 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) { 9825 FunctionDecl *CurFD = CurDecl->getAsFunction()->getCanonicalDecl(); 9826 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) && 9827 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) { 9828 SeenDecls.insert(CurFD); 9829 Pred(CurFD); 9830 } 9831 } 9832 } 9833 9834 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic, 9835 bool IsCXXMethod) const { 9836 // Pass through to the C++ ABI object 9837 if (IsCXXMethod) 9838 return ABI->getDefaultMethodCallConv(IsVariadic); 9839 9840 switch (LangOpts.getDefaultCallingConv()) { 9841 case LangOptions::DCC_None: 9842 break; 9843 case LangOptions::DCC_CDecl: 9844 return CC_C; 9845 case LangOptions::DCC_FastCall: 9846 if (getTargetInfo().hasFeature("sse2") && !IsVariadic) 9847 return CC_X86FastCall; 9848 break; 9849 case LangOptions::DCC_StdCall: 9850 if (!IsVariadic) 9851 return CC_X86StdCall; 9852 break; 9853 case LangOptions::DCC_VectorCall: 9854 // __vectorcall cannot be applied to variadic functions. 9855 if (!IsVariadic) 9856 return CC_X86VectorCall; 9857 break; 9858 case LangOptions::DCC_RegCall: 9859 // __regcall cannot be applied to variadic functions. 9860 if (!IsVariadic) 9861 return CC_X86RegCall; 9862 break; 9863 } 9864 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown); 9865 } 9866 9867 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 9868 // Pass through to the C++ ABI object 9869 return ABI->isNearlyEmpty(RD); 9870 } 9871 9872 VTableContextBase *ASTContext::getVTableContext() { 9873 if (!VTContext.get()) { 9874 if (Target->getCXXABI().isMicrosoft()) 9875 VTContext.reset(new MicrosoftVTableContext(*this)); 9876 else 9877 VTContext.reset(new ItaniumVTableContext(*this)); 9878 } 9879 return VTContext.get(); 9880 } 9881 9882 MangleContext *ASTContext::createMangleContext() { 9883 switch (Target->getCXXABI().getKind()) { 9884 case TargetCXXABI::GenericAArch64: 9885 case TargetCXXABI::GenericItanium: 9886 case TargetCXXABI::GenericARM: 9887 case TargetCXXABI::GenericMIPS: 9888 case TargetCXXABI::iOS: 9889 case TargetCXXABI::iOS64: 9890 case TargetCXXABI::WebAssembly: 9891 case TargetCXXABI::WatchOS: 9892 return ItaniumMangleContext::create(*this, getDiagnostics()); 9893 case TargetCXXABI::Microsoft: 9894 return MicrosoftMangleContext::create(*this, getDiagnostics()); 9895 } 9896 llvm_unreachable("Unsupported ABI"); 9897 } 9898 9899 CXXABI::~CXXABI() = default; 9900 9901 size_t ASTContext::getSideTableAllocatedMemory() const { 9902 return ASTRecordLayouts.getMemorySize() + 9903 llvm::capacity_in_bytes(ObjCLayouts) + 9904 llvm::capacity_in_bytes(KeyFunctions) + 9905 llvm::capacity_in_bytes(ObjCImpls) + 9906 llvm::capacity_in_bytes(BlockVarCopyInits) + 9907 llvm::capacity_in_bytes(DeclAttrs) + 9908 llvm::capacity_in_bytes(TemplateOrInstantiation) + 9909 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) + 9910 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) + 9911 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) + 9912 llvm::capacity_in_bytes(OverriddenMethods) + 9913 llvm::capacity_in_bytes(Types) + 9914 llvm::capacity_in_bytes(VariableArrayTypes) + 9915 llvm::capacity_in_bytes(ClassScopeSpecializationPattern); 9916 } 9917 9918 /// getIntTypeForBitwidth - 9919 /// sets integer QualTy according to specified details: 9920 /// bitwidth, signed/unsigned. 9921 /// Returns empty type if there is no appropriate target types. 9922 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth, 9923 unsigned Signed) const { 9924 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed); 9925 CanQualType QualTy = getFromTargetType(Ty); 9926 if (!QualTy && DestWidth == 128) 9927 return Signed ? Int128Ty : UnsignedInt128Ty; 9928 return QualTy; 9929 } 9930 9931 /// getRealTypeForBitwidth - 9932 /// sets floating point QualTy according to specified bitwidth. 9933 /// Returns empty type if there is no appropriate target types. 9934 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const { 9935 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth); 9936 switch (Ty) { 9937 case TargetInfo::Float: 9938 return FloatTy; 9939 case TargetInfo::Double: 9940 return DoubleTy; 9941 case TargetInfo::LongDouble: 9942 return LongDoubleTy; 9943 case TargetInfo::Float128: 9944 return Float128Ty; 9945 case TargetInfo::NoFloat: 9946 return {}; 9947 } 9948 9949 llvm_unreachable("Unhandled TargetInfo::RealType value"); 9950 } 9951 9952 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { 9953 if (Number > 1) 9954 MangleNumbers[ND] = Number; 9955 } 9956 9957 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const { 9958 auto I = MangleNumbers.find(ND); 9959 return I != MangleNumbers.end() ? I->second : 1; 9960 } 9961 9962 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { 9963 if (Number > 1) 9964 StaticLocalNumbers[VD] = Number; 9965 } 9966 9967 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { 9968 auto I = StaticLocalNumbers.find(VD); 9969 return I != StaticLocalNumbers.end() ? I->second : 1; 9970 } 9971 9972 MangleNumberingContext & 9973 ASTContext::getManglingNumberContext(const DeclContext *DC) { 9974 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 9975 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC]; 9976 if (!MCtx) 9977 MCtx = createMangleNumberingContext(); 9978 return *MCtx; 9979 } 9980 9981 std::unique_ptr<MangleNumberingContext> 9982 ASTContext::createMangleNumberingContext() const { 9983 return ABI->createMangleNumberingContext(); 9984 } 9985 9986 const CXXConstructorDecl * 9987 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) { 9988 return ABI->getCopyConstructorForExceptionObject( 9989 cast<CXXRecordDecl>(RD->getFirstDecl())); 9990 } 9991 9992 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD, 9993 CXXConstructorDecl *CD) { 9994 return ABI->addCopyConstructorForExceptionObject( 9995 cast<CXXRecordDecl>(RD->getFirstDecl()), 9996 cast<CXXConstructorDecl>(CD->getFirstDecl())); 9997 } 9998 9999 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD, 10000 TypedefNameDecl *DD) { 10001 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD); 10002 } 10003 10004 TypedefNameDecl * 10005 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) { 10006 return ABI->getTypedefNameForUnnamedTagDecl(TD); 10007 } 10008 10009 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD, 10010 DeclaratorDecl *DD) { 10011 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD); 10012 } 10013 10014 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) { 10015 return ABI->getDeclaratorForUnnamedTagDecl(TD); 10016 } 10017 10018 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 10019 ParamIndices[D] = index; 10020 } 10021 10022 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 10023 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 10024 assert(I != ParamIndices.end() && 10025 "ParmIndices lacks entry set by ParmVarDecl"); 10026 return I->second; 10027 } 10028 10029 APValue * 10030 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E, 10031 bool MayCreate) { 10032 assert(E && E->getStorageDuration() == SD_Static && 10033 "don't need to cache the computed value for this temporary"); 10034 if (MayCreate) { 10035 APValue *&MTVI = MaterializedTemporaryValues[E]; 10036 if (!MTVI) 10037 MTVI = new (*this) APValue; 10038 return MTVI; 10039 } 10040 10041 return MaterializedTemporaryValues.lookup(E); 10042 } 10043 10044 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { 10045 const llvm::Triple &T = getTargetInfo().getTriple(); 10046 if (!T.isOSDarwin()) 10047 return false; 10048 10049 if (!(T.isiOS() && T.isOSVersionLT(7)) && 10050 !(T.isMacOSX() && T.isOSVersionLT(10, 9))) 10051 return false; 10052 10053 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 10054 CharUnits sizeChars = getTypeSizeInChars(AtomicTy); 10055 uint64_t Size = sizeChars.getQuantity(); 10056 CharUnits alignChars = getTypeAlignInChars(AtomicTy); 10057 unsigned Align = alignChars.getQuantity(); 10058 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth(); 10059 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); 10060 } 10061 10062 static ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap( 10063 ASTContext::ParentMapPointers::mapped_type U) { 10064 if (const auto *D = U.dyn_cast<const Decl *>()) 10065 return ast_type_traits::DynTypedNode::create(*D); 10066 if (const auto *S = U.dyn_cast<const Stmt *>()) 10067 return ast_type_traits::DynTypedNode::create(*S); 10068 return *U.get<ast_type_traits::DynTypedNode *>(); 10069 } 10070 10071 namespace { 10072 10073 /// Template specializations to abstract away from pointers and TypeLocs. 10074 /// @{ 10075 template <typename T> 10076 ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) { 10077 return ast_type_traits::DynTypedNode::create(*Node); 10078 } 10079 template <> 10080 ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) { 10081 return ast_type_traits::DynTypedNode::create(Node); 10082 } 10083 template <> 10084 ast_type_traits::DynTypedNode 10085 createDynTypedNode(const NestedNameSpecifierLoc &Node) { 10086 return ast_type_traits::DynTypedNode::create(Node); 10087 } 10088 /// @} 10089 10090 /// A \c RecursiveASTVisitor that builds a map from nodes to their 10091 /// parents as defined by the \c RecursiveASTVisitor. 10092 /// 10093 /// Note that the relationship described here is purely in terms of AST 10094 /// traversal - there are other relationships (for example declaration context) 10095 /// in the AST that are better modeled by special matchers. 10096 /// 10097 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes. 10098 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> { 10099 public: 10100 /// Builds and returns the translation unit's parent map. 10101 /// 10102 /// The caller takes ownership of the returned \c ParentMap. 10103 static std::pair<ASTContext::ParentMapPointers *, 10104 ASTContext::ParentMapOtherNodes *> 10105 buildMap(TranslationUnitDecl &TU) { 10106 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers, 10107 new ASTContext::ParentMapOtherNodes); 10108 Visitor.TraverseDecl(&TU); 10109 return std::make_pair(Visitor.Parents, Visitor.OtherParents); 10110 } 10111 10112 private: 10113 friend class RecursiveASTVisitor<ParentMapASTVisitor>; 10114 10115 using VisitorBase = RecursiveASTVisitor<ParentMapASTVisitor>; 10116 10117 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents, 10118 ASTContext::ParentMapOtherNodes *OtherParents) 10119 : Parents(Parents), OtherParents(OtherParents) {} 10120 10121 bool shouldVisitTemplateInstantiations() const { 10122 return true; 10123 } 10124 10125 bool shouldVisitImplicitCode() const { 10126 return true; 10127 } 10128 10129 template <typename T, typename MapNodeTy, typename BaseTraverseFn, 10130 typename MapTy> 10131 bool TraverseNode(T Node, MapNodeTy MapNode, 10132 BaseTraverseFn BaseTraverse, MapTy *Parents) { 10133 if (!Node) 10134 return true; 10135 if (ParentStack.size() > 0) { 10136 // FIXME: Currently we add the same parent multiple times, but only 10137 // when no memoization data is available for the type. 10138 // For example when we visit all subexpressions of template 10139 // instantiations; this is suboptimal, but benign: the only way to 10140 // visit those is with hasAncestor / hasParent, and those do not create 10141 // new matches. 10142 // The plan is to enable DynTypedNode to be storable in a map or hash 10143 // map. The main problem there is to implement hash functions / 10144 // comparison operators for all types that DynTypedNode supports that 10145 // do not have pointer identity. 10146 auto &NodeOrVector = (*Parents)[MapNode]; 10147 if (NodeOrVector.isNull()) { 10148 if (const auto *D = ParentStack.back().get<Decl>()) 10149 NodeOrVector = D; 10150 else if (const auto *S = ParentStack.back().get<Stmt>()) 10151 NodeOrVector = S; 10152 else 10153 NodeOrVector = 10154 new ast_type_traits::DynTypedNode(ParentStack.back()); 10155 } else { 10156 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) { 10157 auto *Vector = new ASTContext::ParentVector( 10158 1, getSingleDynTypedNodeFromParentMap(NodeOrVector)); 10159 delete NodeOrVector 10160 .template dyn_cast<ast_type_traits::DynTypedNode *>(); 10161 NodeOrVector = Vector; 10162 } 10163 10164 auto *Vector = 10165 NodeOrVector.template get<ASTContext::ParentVector *>(); 10166 // Skip duplicates for types that have memoization data. 10167 // We must check that the type has memoization data before calling 10168 // std::find() because DynTypedNode::operator== can't compare all 10169 // types. 10170 bool Found = ParentStack.back().getMemoizationData() && 10171 std::find(Vector->begin(), Vector->end(), 10172 ParentStack.back()) != Vector->end(); 10173 if (!Found) 10174 Vector->push_back(ParentStack.back()); 10175 } 10176 } 10177 ParentStack.push_back(createDynTypedNode(Node)); 10178 bool Result = BaseTraverse(); 10179 ParentStack.pop_back(); 10180 return Result; 10181 } 10182 10183 bool TraverseDecl(Decl *DeclNode) { 10184 return TraverseNode(DeclNode, DeclNode, 10185 [&] { return VisitorBase::TraverseDecl(DeclNode); }, 10186 Parents); 10187 } 10188 10189 bool TraverseStmt(Stmt *StmtNode) { 10190 return TraverseNode(StmtNode, StmtNode, 10191 [&] { return VisitorBase::TraverseStmt(StmtNode); }, 10192 Parents); 10193 } 10194 10195 bool TraverseTypeLoc(TypeLoc TypeLocNode) { 10196 return TraverseNode( 10197 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode), 10198 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); }, 10199 OtherParents); 10200 } 10201 10202 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) { 10203 return TraverseNode( 10204 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode), 10205 [&] { 10206 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); 10207 }, 10208 OtherParents); 10209 } 10210 10211 ASTContext::ParentMapPointers *Parents; 10212 ASTContext::ParentMapOtherNodes *OtherParents; 10213 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack; 10214 }; 10215 10216 } // namespace 10217 10218 template <typename NodeTy, typename MapTy> 10219 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node, 10220 const MapTy &Map) { 10221 auto I = Map.find(Node); 10222 if (I == Map.end()) { 10223 return llvm::ArrayRef<ast_type_traits::DynTypedNode>(); 10224 } 10225 if (const auto *V = 10226 I->second.template dyn_cast<ASTContext::ParentVector *>()) { 10227 return llvm::makeArrayRef(*V); 10228 } 10229 return getSingleDynTypedNodeFromParentMap(I->second); 10230 } 10231 10232 ASTContext::DynTypedNodeList 10233 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) { 10234 if (!PointerParents) { 10235 // We always need to run over the whole translation unit, as 10236 // hasAncestor can escape any subtree. 10237 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()); 10238 PointerParents.reset(Maps.first); 10239 OtherParents.reset(Maps.second); 10240 } 10241 if (Node.getNodeKind().hasPointerIdentity()) 10242 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents); 10243 return getDynNodeFromMap(Node, *OtherParents); 10244 } 10245 10246 bool 10247 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, 10248 const ObjCMethodDecl *MethodImpl) { 10249 // No point trying to match an unavailable/deprecated mothod. 10250 if (MethodDecl->hasAttr<UnavailableAttr>() 10251 || MethodDecl->hasAttr<DeprecatedAttr>()) 10252 return false; 10253 if (MethodDecl->getObjCDeclQualifier() != 10254 MethodImpl->getObjCDeclQualifier()) 10255 return false; 10256 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) 10257 return false; 10258 10259 if (MethodDecl->param_size() != MethodImpl->param_size()) 10260 return false; 10261 10262 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), 10263 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), 10264 EF = MethodDecl->param_end(); 10265 IM != EM && IF != EF; ++IM, ++IF) { 10266 const ParmVarDecl *DeclVar = (*IF); 10267 const ParmVarDecl *ImplVar = (*IM); 10268 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) 10269 return false; 10270 if (!hasSameType(DeclVar->getType(), ImplVar->getType())) 10271 return false; 10272 } 10273 10274 return (MethodDecl->isVariadic() == MethodImpl->isVariadic()); 10275 } 10276 10277 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const { 10278 LangAS AS; 10279 if (QT->getUnqualifiedDesugaredType()->isNullPtrType()) 10280 AS = LangAS::Default; 10281 else 10282 AS = QT->getPointeeType().getAddressSpace(); 10283 10284 return getTargetInfo().getNullPointerValue(AS); 10285 } 10286 10287 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const { 10288 if (isTargetAddressSpace(AS)) 10289 return toTargetAddressSpace(AS); 10290 else 10291 return (*AddrSpaceMap)[(unsigned)AS]; 10292 } 10293 10294 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const { 10295 assert(Ty->isFixedPointType()); 10296 10297 if (Ty->isSaturatedFixedPointType()) return Ty; 10298 10299 const auto &BT = Ty->getAs<BuiltinType>(); 10300 switch (BT->getKind()) { 10301 default: 10302 llvm_unreachable("Not a fixed point type!"); 10303 case BuiltinType::ShortAccum: 10304 return SatShortAccumTy; 10305 case BuiltinType::Accum: 10306 return SatAccumTy; 10307 case BuiltinType::LongAccum: 10308 return SatLongAccumTy; 10309 case BuiltinType::UShortAccum: 10310 return SatUnsignedShortAccumTy; 10311 case BuiltinType::UAccum: 10312 return SatUnsignedAccumTy; 10313 case BuiltinType::ULongAccum: 10314 return SatUnsignedLongAccumTy; 10315 case BuiltinType::ShortFract: 10316 return SatShortFractTy; 10317 case BuiltinType::Fract: 10318 return SatFractTy; 10319 case BuiltinType::LongFract: 10320 return SatLongFractTy; 10321 case BuiltinType::UShortFract: 10322 return SatUnsignedShortFractTy; 10323 case BuiltinType::UFract: 10324 return SatUnsignedFractTy; 10325 case BuiltinType::ULongFract: 10326 return SatUnsignedLongFractTy; 10327 } 10328 } 10329 10330 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const { 10331 if (LangOpts.OpenCL) 10332 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS); 10333 10334 if (LangOpts.CUDA) 10335 return getTargetInfo().getCUDABuiltinAddressSpace(AS); 10336 10337 return getLangASFromTargetAS(AS); 10338 } 10339 10340 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that 10341 // doesn't include ASTContext.h 10342 template 10343 clang::LazyGenerationalUpdatePtr< 10344 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType 10345 clang::LazyGenerationalUpdatePtr< 10346 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( 10347 const clang::ASTContext &Ctx, Decl *Value); 10348 10349 unsigned char ASTContext::getFixedPointScale(QualType Ty) const { 10350 assert(Ty->isFixedPointType()); 10351 10352 const auto *BT = Ty->getAs<BuiltinType>(); 10353 const TargetInfo &Target = getTargetInfo(); 10354 switch (BT->getKind()) { 10355 default: 10356 llvm_unreachable("Not a fixed point type!"); 10357 case BuiltinType::ShortAccum: 10358 case BuiltinType::SatShortAccum: 10359 return Target.getShortAccumScale(); 10360 case BuiltinType::Accum: 10361 case BuiltinType::SatAccum: 10362 return Target.getAccumScale(); 10363 case BuiltinType::LongAccum: 10364 case BuiltinType::SatLongAccum: 10365 return Target.getLongAccumScale(); 10366 case BuiltinType::UShortAccum: 10367 case BuiltinType::SatUShortAccum: 10368 return Target.getUnsignedShortAccumScale(); 10369 case BuiltinType::UAccum: 10370 case BuiltinType::SatUAccum: 10371 return Target.getUnsignedAccumScale(); 10372 case BuiltinType::ULongAccum: 10373 case BuiltinType::SatULongAccum: 10374 return Target.getUnsignedLongAccumScale(); 10375 case BuiltinType::ShortFract: 10376 case BuiltinType::SatShortFract: 10377 return Target.getShortFractScale(); 10378 case BuiltinType::Fract: 10379 case BuiltinType::SatFract: 10380 return Target.getFractScale(); 10381 case BuiltinType::LongFract: 10382 case BuiltinType::SatLongFract: 10383 return Target.getLongFractScale(); 10384 case BuiltinType::UShortFract: 10385 case BuiltinType::SatUShortFract: 10386 return Target.getUnsignedShortFractScale(); 10387 case BuiltinType::UFract: 10388 case BuiltinType::SatUFract: 10389 return Target.getUnsignedFractScale(); 10390 case BuiltinType::ULongFract: 10391 case BuiltinType::SatULongFract: 10392 return Target.getUnsignedLongFractScale(); 10393 } 10394 } 10395 10396 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const { 10397 assert(Ty->isFixedPointType()); 10398 10399 const auto *BT = Ty->getAs<BuiltinType>(); 10400 const TargetInfo &Target = getTargetInfo(); 10401 switch (BT->getKind()) { 10402 default: 10403 llvm_unreachable("Not a fixed point type!"); 10404 case BuiltinType::ShortAccum: 10405 case BuiltinType::SatShortAccum: 10406 return Target.getShortAccumIBits(); 10407 case BuiltinType::Accum: 10408 case BuiltinType::SatAccum: 10409 return Target.getAccumIBits(); 10410 case BuiltinType::LongAccum: 10411 case BuiltinType::SatLongAccum: 10412 return Target.getLongAccumIBits(); 10413 case BuiltinType::UShortAccum: 10414 case BuiltinType::SatUShortAccum: 10415 return Target.getUnsignedShortAccumIBits(); 10416 case BuiltinType::UAccum: 10417 case BuiltinType::SatUAccum: 10418 return Target.getUnsignedAccumIBits(); 10419 case BuiltinType::ULongAccum: 10420 case BuiltinType::SatULongAccum: 10421 return Target.getUnsignedLongAccumIBits(); 10422 case BuiltinType::ShortFract: 10423 case BuiltinType::SatShortFract: 10424 case BuiltinType::Fract: 10425 case BuiltinType::SatFract: 10426 case BuiltinType::LongFract: 10427 case BuiltinType::SatLongFract: 10428 case BuiltinType::UShortFract: 10429 case BuiltinType::SatUShortFract: 10430 case BuiltinType::UFract: 10431 case BuiltinType::SatUFract: 10432 case BuiltinType::ULongFract: 10433 case BuiltinType::SatULongFract: 10434 return 0; 10435 } 10436 } 10437 10438 FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const { 10439 assert(Ty->isFixedPointType()); 10440 bool isSigned = Ty->isSignedFixedPointType(); 10441 return FixedPointSemantics( 10442 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned, 10443 Ty->isSaturatedFixedPointType(), 10444 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding()); 10445 } 10446 10447 APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const { 10448 assert(Ty->isFixedPointType()); 10449 return APFixedPoint::getMax(getFixedPointSemantics(Ty)); 10450 } 10451 10452 APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const { 10453 assert(Ty->isFixedPointType()); 10454 return APFixedPoint::getMin(getFixedPointSemantics(Ty)); 10455 } 10456