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