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