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