1 //===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the ASTContext interface. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/ASTContext.h" 15 #include "CXXABI.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Comment.h" 20 #include "clang/AST/CommentCommandTraits.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclContextInternals.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclTemplate.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExternalASTSource.h" 28 #include "clang/AST/Mangle.h" 29 #include "clang/AST/MangleNumberingContext.h" 30 #include "clang/AST/RecordLayout.h" 31 #include "clang/AST/RecursiveASTVisitor.h" 32 #include "clang/AST/TypeLoc.h" 33 #include "clang/AST/VTableBuilder.h" 34 #include "clang/Basic/Builtins.h" 35 #include "clang/Basic/SourceManager.h" 36 #include "clang/Basic/TargetInfo.h" 37 #include "llvm/ADT/StringExtras.h" 38 #include "llvm/ADT/Triple.h" 39 #include "llvm/Support/Capacity.h" 40 #include "llvm/Support/MathExtras.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include <map> 43 44 using namespace clang; 45 46 unsigned ASTContext::NumImplicitDefaultConstructors; 47 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared; 48 unsigned ASTContext::NumImplicitCopyConstructors; 49 unsigned ASTContext::NumImplicitCopyConstructorsDeclared; 50 unsigned ASTContext::NumImplicitMoveConstructors; 51 unsigned ASTContext::NumImplicitMoveConstructorsDeclared; 52 unsigned ASTContext::NumImplicitCopyAssignmentOperators; 53 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 54 unsigned ASTContext::NumImplicitMoveAssignmentOperators; 55 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 56 unsigned ASTContext::NumImplicitDestructors; 57 unsigned ASTContext::NumImplicitDestructorsDeclared; 58 59 enum FloatingRank { 60 HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank 61 }; 62 63 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const { 64 if (!CommentsLoaded && ExternalSource) { 65 ExternalSource->ReadComments(); 66 67 #ifndef NDEBUG 68 ArrayRef<RawComment *> RawComments = Comments.getComments(); 69 assert(std::is_sorted(RawComments.begin(), RawComments.end(), 70 BeforeThanCompare<RawComment>(SourceMgr))); 71 #endif 72 73 CommentsLoaded = true; 74 } 75 76 assert(D); 77 78 // User can not attach documentation to implicit declarations. 79 if (D->isImplicit()) 80 return nullptr; 81 82 // User can not attach documentation to implicit instantiations. 83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 85 return nullptr; 86 } 87 88 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 89 if (VD->isStaticDataMember() && 90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 91 return nullptr; 92 } 93 94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) { 95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 96 return nullptr; 97 } 98 99 if (const ClassTemplateSpecializationDecl *CTSD = 100 dyn_cast<ClassTemplateSpecializationDecl>(D)) { 101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind(); 102 if (TSK == TSK_ImplicitInstantiation || 103 TSK == TSK_Undeclared) 104 return nullptr; 105 } 106 107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 109 return nullptr; 110 } 111 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) { 112 // When tag declaration (but not definition!) is part of the 113 // decl-specifier-seq of some other declaration, it doesn't get comment 114 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition()) 115 return nullptr; 116 } 117 // TODO: handle comments for function parameters properly. 118 if (isa<ParmVarDecl>(D)) 119 return nullptr; 120 121 // TODO: we could look up template parameter documentation in the template 122 // documentation. 123 if (isa<TemplateTypeParmDecl>(D) || 124 isa<NonTypeTemplateParmDecl>(D) || 125 isa<TemplateTemplateParmDecl>(D)) 126 return nullptr; 127 128 ArrayRef<RawComment *> RawComments = Comments.getComments(); 129 130 // If there are no comments anywhere, we won't find anything. 131 if (RawComments.empty()) 132 return nullptr; 133 134 // Find declaration location. 135 // For Objective-C declarations we generally don't expect to have multiple 136 // declarators, thus use declaration starting location as the "declaration 137 // location". 138 // For all other declarations multiple declarators are used quite frequently, 139 // so we use the location of the identifier as the "declaration location". 140 SourceLocation DeclLoc; 141 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) || 142 isa<ObjCPropertyDecl>(D) || 143 isa<RedeclarableTemplateDecl>(D) || 144 isa<ClassTemplateSpecializationDecl>(D)) 145 DeclLoc = D->getLocStart(); 146 else { 147 DeclLoc = D->getLocation(); 148 if (DeclLoc.isMacroID()) { 149 if (isa<TypedefDecl>(D)) { 150 // If location of the typedef name is in a macro, it is because being 151 // declared via a macro. Try using declaration's starting location as 152 // the "declaration location". 153 DeclLoc = D->getLocStart(); 154 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) { 155 // If location of the tag decl is inside a macro, but the spelling of 156 // the tag name comes from a macro argument, it looks like a special 157 // macro like NS_ENUM is being used to define the tag decl. In that 158 // case, adjust the source location to the expansion loc so that we can 159 // attach the comment to the tag decl. 160 if (SourceMgr.isMacroArgExpansion(DeclLoc) && 161 TD->isCompleteDefinition()) 162 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc); 163 } 164 } 165 } 166 167 // If the declaration doesn't map directly to a location in a file, we 168 // can't find the comment. 169 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 170 return nullptr; 171 172 // Find the comment that occurs just after this declaration. 173 ArrayRef<RawComment *>::iterator Comment; 174 { 175 // When searching for comments during parsing, the comment we are looking 176 // for is usually among the last two comments we parsed -- check them 177 // first. 178 RawComment CommentAtDeclLoc( 179 SourceMgr, SourceRange(DeclLoc), false, 180 LangOpts.CommentOpts.ParseAllComments); 181 BeforeThanCompare<RawComment> Compare(SourceMgr); 182 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1; 183 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc); 184 if (!Found && RawComments.size() >= 2) { 185 MaybeBeforeDecl--; 186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc); 187 } 188 189 if (Found) { 190 Comment = MaybeBeforeDecl + 1; 191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(), 192 &CommentAtDeclLoc, Compare)); 193 } else { 194 // Slow path. 195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(), 196 &CommentAtDeclLoc, Compare); 197 } 198 } 199 200 // Decompose the location for the declaration and find the beginning of the 201 // file buffer. 202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc); 203 204 // First check whether we have a trailing comment. 205 if (Comment != RawComments.end() && 206 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() && 207 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) || 208 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) { 209 std::pair<FileID, unsigned> CommentBeginDecomp 210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin()); 211 // Check that Doxygen trailing comment comes after the declaration, starts 212 // on the same line and in the same file as the declaration. 213 if (DeclLocDecomp.first == CommentBeginDecomp.first && 214 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) 215 == SourceMgr.getLineNumber(CommentBeginDecomp.first, 216 CommentBeginDecomp.second)) { 217 return *Comment; 218 } 219 } 220 221 // The comment just after the declaration was not a trailing comment. 222 // Let's look at the previous comment. 223 if (Comment == RawComments.begin()) 224 return nullptr; 225 --Comment; 226 227 // Check that we actually have a non-member Doxygen comment. 228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment()) 229 return nullptr; 230 231 // Decompose the end of the comment. 232 std::pair<FileID, unsigned> CommentEndDecomp 233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd()); 234 235 // If the comment and the declaration aren't in the same file, then they 236 // aren't related. 237 if (DeclLocDecomp.first != CommentEndDecomp.first) 238 return nullptr; 239 240 // Get the corresponding buffer. 241 bool Invalid = false; 242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first, 243 &Invalid).data(); 244 if (Invalid) 245 return nullptr; 246 247 // Extract text between the comment and declaration. 248 StringRef Text(Buffer + CommentEndDecomp.second, 249 DeclLocDecomp.second - CommentEndDecomp.second); 250 251 // There should be no other declarations or preprocessor directives between 252 // comment and declaration. 253 if (Text.find_first_of(";{}#@") != StringRef::npos) 254 return nullptr; 255 256 return *Comment; 257 } 258 259 namespace { 260 /// If we have a 'templated' declaration for a template, adjust 'D' to 261 /// refer to the actual template. 262 /// If we have an implicit instantiation, adjust 'D' to refer to template. 263 const Decl *adjustDeclToTemplate(const Decl *D) { 264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 265 // Is this function declaration part of a function template? 266 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 267 return FTD; 268 269 // Nothing to do if function is not an implicit instantiation. 270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) 271 return D; 272 273 // Function is an implicit instantiation of a function template? 274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate()) 275 return FTD; 276 277 // Function is instantiated from a member definition of a class template? 278 if (const FunctionDecl *MemberDecl = 279 FD->getInstantiatedFromMemberFunction()) 280 return MemberDecl; 281 282 return D; 283 } 284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 285 // Static data member is instantiated from a member definition of a class 286 // template? 287 if (VD->isStaticDataMember()) 288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember()) 289 return MemberDecl; 290 291 return D; 292 } 293 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) { 294 // Is this class declaration part of a class template? 295 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate()) 296 return CTD; 297 298 // Class is an implicit instantiation of a class template or partial 299 // specialization? 300 if (const ClassTemplateSpecializationDecl *CTSD = 301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) { 302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation) 303 return D; 304 llvm::PointerUnion<ClassTemplateDecl *, 305 ClassTemplatePartialSpecializationDecl *> 306 PU = CTSD->getSpecializedTemplateOrPartial(); 307 return PU.is<ClassTemplateDecl*>() ? 308 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) : 309 static_cast<const Decl*>( 310 PU.get<ClassTemplatePartialSpecializationDecl *>()); 311 } 312 313 // Class is instantiated from a member definition of a class template? 314 if (const MemberSpecializationInfo *Info = 315 CRD->getMemberSpecializationInfo()) 316 return Info->getInstantiatedFrom(); 317 318 return D; 319 } 320 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 321 // Enum is instantiated from a member definition of a class template? 322 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum()) 323 return MemberDecl; 324 325 return D; 326 } 327 // FIXME: Adjust alias templates? 328 return D; 329 } 330 } // anonymous namespace 331 332 const RawComment *ASTContext::getRawCommentForAnyRedecl( 333 const Decl *D, 334 const Decl **OriginalDecl) const { 335 D = adjustDeclToTemplate(D); 336 337 // Check whether we have cached a comment for this declaration already. 338 { 339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos = 340 RedeclComments.find(D); 341 if (Pos != RedeclComments.end()) { 342 const RawCommentAndCacheFlags &Raw = Pos->second; 343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) { 344 if (OriginalDecl) 345 *OriginalDecl = Raw.getOriginalDecl(); 346 return Raw.getRaw(); 347 } 348 } 349 } 350 351 // Search for comments attached to declarations in the redeclaration chain. 352 const RawComment *RC = nullptr; 353 const Decl *OriginalDeclForRC = nullptr; 354 for (auto I : D->redecls()) { 355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos = 356 RedeclComments.find(I); 357 if (Pos != RedeclComments.end()) { 358 const RawCommentAndCacheFlags &Raw = Pos->second; 359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) { 360 RC = Raw.getRaw(); 361 OriginalDeclForRC = Raw.getOriginalDecl(); 362 break; 363 } 364 } else { 365 RC = getRawCommentForDeclNoCache(I); 366 OriginalDeclForRC = I; 367 RawCommentAndCacheFlags Raw; 368 if (RC) { 369 // Call order swapped to work around ICE in VS2015 RTM (Release Win32) 370 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530 371 Raw.setKind(RawCommentAndCacheFlags::FromDecl); 372 Raw.setRaw(RC); 373 } else 374 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl); 375 Raw.setOriginalDecl(I); 376 RedeclComments[I] = Raw; 377 if (RC) 378 break; 379 } 380 } 381 382 // If we found a comment, it should be a documentation comment. 383 assert(!RC || RC->isDocumentation()); 384 385 if (OriginalDecl) 386 *OriginalDecl = OriginalDeclForRC; 387 388 // Update cache for every declaration in the redeclaration chain. 389 RawCommentAndCacheFlags Raw; 390 Raw.setRaw(RC); 391 Raw.setKind(RawCommentAndCacheFlags::FromRedecl); 392 Raw.setOriginalDecl(OriginalDeclForRC); 393 394 for (auto I : D->redecls()) { 395 RawCommentAndCacheFlags &R = RedeclComments[I]; 396 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl) 397 R = Raw; 398 } 399 400 return RC; 401 } 402 403 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, 404 SmallVectorImpl<const NamedDecl *> &Redeclared) { 405 const DeclContext *DC = ObjCMethod->getDeclContext(); 406 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) { 407 const ObjCInterfaceDecl *ID = IMD->getClassInterface(); 408 if (!ID) 409 return; 410 // Add redeclared method here. 411 for (const auto *Ext : ID->known_extensions()) { 412 if (ObjCMethodDecl *RedeclaredMethod = 413 Ext->getMethod(ObjCMethod->getSelector(), 414 ObjCMethod->isInstanceMethod())) 415 Redeclared.push_back(RedeclaredMethod); 416 } 417 } 418 } 419 420 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC, 421 const Decl *D) const { 422 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo; 423 ThisDeclInfo->CommentDecl = D; 424 ThisDeclInfo->IsFilled = false; 425 ThisDeclInfo->fill(); 426 ThisDeclInfo->CommentDecl = FC->getDecl(); 427 if (!ThisDeclInfo->TemplateParameters) 428 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters; 429 comments::FullComment *CFC = 430 new (*this) comments::FullComment(FC->getBlocks(), 431 ThisDeclInfo); 432 return CFC; 433 } 434 435 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const { 436 const RawComment *RC = getRawCommentForDeclNoCache(D); 437 return RC ? RC->parse(*this, nullptr, D) : nullptr; 438 } 439 440 comments::FullComment *ASTContext::getCommentForDecl( 441 const Decl *D, 442 const Preprocessor *PP) const { 443 if (D->isInvalidDecl()) 444 return nullptr; 445 D = adjustDeclToTemplate(D); 446 447 const Decl *Canonical = D->getCanonicalDecl(); 448 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos = 449 ParsedComments.find(Canonical); 450 451 if (Pos != ParsedComments.end()) { 452 if (Canonical != D) { 453 comments::FullComment *FC = Pos->second; 454 comments::FullComment *CFC = cloneFullComment(FC, D); 455 return CFC; 456 } 457 return Pos->second; 458 } 459 460 const Decl *OriginalDecl; 461 462 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl); 463 if (!RC) { 464 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) { 465 SmallVector<const NamedDecl*, 8> Overridden; 466 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D); 467 if (OMD && OMD->isPropertyAccessor()) 468 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) 469 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP)) 470 return cloneFullComment(FC, D); 471 if (OMD) 472 addRedeclaredMethods(OMD, Overridden); 473 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden); 474 for (unsigned i = 0, e = Overridden.size(); i < e; i++) 475 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) 476 return cloneFullComment(FC, D); 477 } 478 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 479 // Attach any tag type's documentation to its typedef if latter 480 // does not have one of its own. 481 QualType QT = TD->getUnderlyingType(); 482 if (const TagType *TT = QT->getAs<TagType>()) 483 if (const Decl *TD = TT->getDecl()) 484 if (comments::FullComment *FC = getCommentForDecl(TD, PP)) 485 return cloneFullComment(FC, D); 486 } 487 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) { 488 while (IC->getSuperClass()) { 489 IC = IC->getSuperClass(); 490 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 491 return cloneFullComment(FC, D); 492 } 493 } 494 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) { 495 if (const ObjCInterfaceDecl *IC = CD->getClassInterface()) 496 if (comments::FullComment *FC = getCommentForDecl(IC, PP)) 497 return cloneFullComment(FC, D); 498 } 499 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 500 if (!(RD = RD->getDefinition())) 501 return nullptr; 502 // Check non-virtual bases. 503 for (const auto &I : RD->bases()) { 504 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public)) 505 continue; 506 QualType Ty = I.getType(); 507 if (Ty.isNull()) 508 continue; 509 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) { 510 if (!(NonVirtualBase= NonVirtualBase->getDefinition())) 511 continue; 512 513 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP)) 514 return cloneFullComment(FC, D); 515 } 516 } 517 // Check virtual bases. 518 for (const auto &I : RD->vbases()) { 519 if (I.getAccessSpecifier() != AS_public) 520 continue; 521 QualType Ty = I.getType(); 522 if (Ty.isNull()) 523 continue; 524 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) { 525 if (!(VirtualBase= VirtualBase->getDefinition())) 526 continue; 527 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP)) 528 return cloneFullComment(FC, D); 529 } 530 } 531 } 532 return nullptr; 533 } 534 535 // If the RawComment was attached to other redeclaration of this Decl, we 536 // should parse the comment in context of that other Decl. This is important 537 // because comments can contain references to parameter names which can be 538 // different across redeclarations. 539 if (D != OriginalDecl) 540 return getCommentForDecl(OriginalDecl, PP); 541 542 comments::FullComment *FC = RC->parse(*this, PP, D); 543 ParsedComments[Canonical] = FC; 544 return FC; 545 } 546 547 void 548 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 549 TemplateTemplateParmDecl *Parm) { 550 ID.AddInteger(Parm->getDepth()); 551 ID.AddInteger(Parm->getPosition()); 552 ID.AddBoolean(Parm->isParameterPack()); 553 554 TemplateParameterList *Params = Parm->getTemplateParameters(); 555 ID.AddInteger(Params->size()); 556 for (TemplateParameterList::const_iterator P = Params->begin(), 557 PEnd = Params->end(); 558 P != PEnd; ++P) { 559 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 560 ID.AddInteger(0); 561 ID.AddBoolean(TTP->isParameterPack()); 562 continue; 563 } 564 565 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 566 ID.AddInteger(1); 567 ID.AddBoolean(NTTP->isParameterPack()); 568 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr()); 569 if (NTTP->isExpandedParameterPack()) { 570 ID.AddBoolean(true); 571 ID.AddInteger(NTTP->getNumExpansionTypes()); 572 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 573 QualType T = NTTP->getExpansionType(I); 574 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); 575 } 576 } else 577 ID.AddBoolean(false); 578 continue; 579 } 580 581 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); 582 ID.AddInteger(2); 583 Profile(ID, TTP); 584 } 585 } 586 587 TemplateTemplateParmDecl * 588 ASTContext::getCanonicalTemplateTemplateParmDecl( 589 TemplateTemplateParmDecl *TTP) const { 590 // Check if we already have a canonical template template parameter. 591 llvm::FoldingSetNodeID ID; 592 CanonicalTemplateTemplateParm::Profile(ID, TTP); 593 void *InsertPos = nullptr; 594 CanonicalTemplateTemplateParm *Canonical 595 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 596 if (Canonical) 597 return Canonical->getParam(); 598 599 // Build a canonical template parameter list. 600 TemplateParameterList *Params = TTP->getTemplateParameters(); 601 SmallVector<NamedDecl *, 4> CanonParams; 602 CanonParams.reserve(Params->size()); 603 for (TemplateParameterList::const_iterator P = Params->begin(), 604 PEnd = Params->end(); 605 P != PEnd; ++P) { 606 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) 607 CanonParams.push_back( 608 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(), 609 SourceLocation(), 610 SourceLocation(), 611 TTP->getDepth(), 612 TTP->getIndex(), nullptr, false, 613 TTP->isParameterPack())); 614 else if (NonTypeTemplateParmDecl *NTTP 615 = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 616 QualType T = getCanonicalType(NTTP->getType()); 617 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 618 NonTypeTemplateParmDecl *Param; 619 if (NTTP->isExpandedParameterPack()) { 620 SmallVector<QualType, 2> ExpandedTypes; 621 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; 622 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 623 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); 624 ExpandedTInfos.push_back( 625 getTrivialTypeSourceInfo(ExpandedTypes.back())); 626 } 627 628 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 629 SourceLocation(), 630 SourceLocation(), 631 NTTP->getDepth(), 632 NTTP->getPosition(), nullptr, 633 T, 634 TInfo, 635 ExpandedTypes, 636 ExpandedTInfos); 637 } else { 638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 639 SourceLocation(), 640 SourceLocation(), 641 NTTP->getDepth(), 642 NTTP->getPosition(), nullptr, 643 T, 644 NTTP->isParameterPack(), 645 TInfo); 646 } 647 CanonParams.push_back(Param); 648 649 } else 650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 651 cast<TemplateTemplateParmDecl>(*P))); 652 } 653 654 assert(!TTP->getRequiresClause() && 655 "Unexpected requires-clause on template template-parameter"); 656 Expr *const CanonRequiresClause = nullptr; 657 658 TemplateTemplateParmDecl *CanonTTP 659 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 660 SourceLocation(), TTP->getDepth(), 661 TTP->getPosition(), 662 TTP->isParameterPack(), 663 nullptr, 664 TemplateParameterList::Create(*this, SourceLocation(), 665 SourceLocation(), 666 CanonParams, 667 SourceLocation(), 668 CanonRequiresClause)); 669 670 // Get the new insert position for the node we care about. 671 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 672 assert(!Canonical && "Shouldn't be in the map!"); 673 (void)Canonical; 674 675 // Create the canonical template template parameter entry. 676 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 677 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 678 return CanonTTP; 679 } 680 681 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 682 if (!LangOpts.CPlusPlus) return nullptr; 683 684 switch (T.getCXXABI().getKind()) { 685 case TargetCXXABI::GenericARM: // Same as Itanium at this level 686 case TargetCXXABI::iOS: 687 case TargetCXXABI::iOS64: 688 case TargetCXXABI::WatchOS: 689 case TargetCXXABI::GenericAArch64: 690 case TargetCXXABI::GenericMIPS: 691 case TargetCXXABI::GenericItanium: 692 case TargetCXXABI::WebAssembly: 693 return CreateItaniumCXXABI(*this); 694 case TargetCXXABI::Microsoft: 695 return CreateMicrosoftCXXABI(*this); 696 } 697 llvm_unreachable("Invalid CXXABI type!"); 698 } 699 700 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T, 701 const LangOptions &LOpts) { 702 if (LOpts.FakeAddressSpaceMap) { 703 // The fake address space map must have a distinct entry for each 704 // language-specific address space. 705 static const unsigned FakeAddrSpaceMap[] = { 706 0, // Default 707 1, // opencl_global 708 3, // opencl_local 709 2, // opencl_constant 710 4, // opencl_generic 711 5, // cuda_device 712 6, // cuda_constant 713 7 // cuda_shared 714 }; 715 return &FakeAddrSpaceMap; 716 } else { 717 return &T.getAddressSpaceMap(); 718 } 719 } 720 721 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, 722 const LangOptions &LangOpts) { 723 switch (LangOpts.getAddressSpaceMapMangling()) { 724 case LangOptions::ASMM_Target: 725 return TI.useAddressSpaceMapMangling(); 726 case LangOptions::ASMM_On: 727 return true; 728 case LangOptions::ASMM_Off: 729 return false; 730 } 731 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything."); 732 } 733 734 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM, 735 IdentifierTable &idents, SelectorTable &sels, 736 Builtin::Context &builtins) 737 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()), 738 DependentTemplateSpecializationTypes(this_()), 739 SubstTemplateTemplateParmPacks(this_()), 740 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr), 741 UInt128Decl(nullptr), BuiltinVaListDecl(nullptr), 742 BuiltinMSVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), 743 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr), 744 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr), 745 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr), 746 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr), 747 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr), 748 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(), 749 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr), 750 TypePackElementDecl(nullptr), SourceMgr(SM), LangOpts(LOpts), 751 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)), 752 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles, 753 LangOpts.XRayNeverInstrumentFiles, SM)), 754 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr), 755 PrintingPolicy(LOpts), Idents(idents), Selectors(sels), 756 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr), 757 Listener(nullptr), Comments(SM), CommentsLoaded(false), 758 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) { 759 TUDecl = TranslationUnitDecl::Create(*this); 760 } 761 762 ASTContext::~ASTContext() { 763 ReleaseParentMapEntries(); 764 765 // Release the DenseMaps associated with DeclContext objects. 766 // FIXME: Is this the ideal solution? 767 ReleaseDeclContextMaps(); 768 769 // Call all of the deallocation functions on all of their targets. 770 for (auto &Pair : Deallocations) 771 (Pair.first)(Pair.second); 772 773 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 774 // because they can contain DenseMaps. 775 for (llvm::DenseMap<const ObjCContainerDecl*, 776 const ASTRecordLayout*>::iterator 777 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 778 // Increment in loop to prevent using deallocated memory. 779 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 780 R->Destroy(*this); 781 782 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 783 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 784 // Increment in loop to prevent using deallocated memory. 785 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 786 R->Destroy(*this); 787 } 788 789 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 790 AEnd = DeclAttrs.end(); 791 A != AEnd; ++A) 792 A->second->~AttrVec(); 793 794 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair : 795 MaterializedTemporaryValues) 796 MTVPair.second->~APValue(); 797 798 for (const auto &Value : ModuleInitializers) 799 Value.second->~PerModuleInitializers(); 800 } 801 802 void ASTContext::ReleaseParentMapEntries() { 803 if (!PointerParents) return; 804 for (const auto &Entry : *PointerParents) { 805 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) { 806 delete Entry.second.get<ast_type_traits::DynTypedNode *>(); 807 } else if (Entry.second.is<ParentVector *>()) { 808 delete Entry.second.get<ParentVector *>(); 809 } 810 } 811 for (const auto &Entry : *OtherParents) { 812 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) { 813 delete Entry.second.get<ast_type_traits::DynTypedNode *>(); 814 } else if (Entry.second.is<ParentVector *>()) { 815 delete Entry.second.get<ParentVector *>(); 816 } 817 } 818 } 819 820 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) { 821 Deallocations.push_back({Callback, Data}); 822 } 823 824 void 825 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) { 826 ExternalSource = std::move(Source); 827 } 828 829 void ASTContext::PrintStats() const { 830 llvm::errs() << "\n*** AST Context Stats:\n"; 831 llvm::errs() << " " << Types.size() << " types total.\n"; 832 833 unsigned counts[] = { 834 #define TYPE(Name, Parent) 0, 835 #define ABSTRACT_TYPE(Name, Parent) 836 #include "clang/AST/TypeNodes.def" 837 0 // Extra 838 }; 839 840 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 841 Type *T = Types[i]; 842 counts[(unsigned)T->getTypeClass()]++; 843 } 844 845 unsigned Idx = 0; 846 unsigned TotalBytes = 0; 847 #define TYPE(Name, Parent) \ 848 if (counts[Idx]) \ 849 llvm::errs() << " " << counts[Idx] << " " << #Name \ 850 << " types\n"; \ 851 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 852 ++Idx; 853 #define ABSTRACT_TYPE(Name, Parent) 854 #include "clang/AST/TypeNodes.def" 855 856 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 857 858 // Implicit special member functions. 859 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 860 << NumImplicitDefaultConstructors 861 << " implicit default constructors created\n"; 862 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 863 << NumImplicitCopyConstructors 864 << " implicit copy constructors created\n"; 865 if (getLangOpts().CPlusPlus) 866 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 867 << NumImplicitMoveConstructors 868 << " implicit move constructors created\n"; 869 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 870 << NumImplicitCopyAssignmentOperators 871 << " implicit copy assignment operators created\n"; 872 if (getLangOpts().CPlusPlus) 873 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 874 << NumImplicitMoveAssignmentOperators 875 << " implicit move assignment operators created\n"; 876 llvm::errs() << NumImplicitDestructorsDeclared << "/" 877 << NumImplicitDestructors 878 << " implicit destructors created\n"; 879 880 if (ExternalSource) { 881 llvm::errs() << "\n"; 882 ExternalSource->PrintStats(); 883 } 884 885 BumpAlloc.PrintStats(); 886 } 887 888 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M, 889 bool NotifyListeners) { 890 if (NotifyListeners) 891 if (auto *Listener = getASTMutationListener()) 892 Listener->RedefinedHiddenDefinition(ND, M); 893 894 if (getLangOpts().ModulesLocalVisibility) 895 MergedDefModules[ND].push_back(M); 896 else 897 ND->setVisibleDespiteOwningModule(); 898 } 899 900 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) { 901 auto It = MergedDefModules.find(ND); 902 if (It == MergedDefModules.end()) 903 return; 904 905 auto &Merged = It->second; 906 llvm::DenseSet<Module*> Found; 907 for (Module *&M : Merged) 908 if (!Found.insert(M).second) 909 M = nullptr; 910 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end()); 911 } 912 913 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) { 914 if (LazyInitializers.empty()) 915 return; 916 917 auto *Source = Ctx.getExternalSource(); 918 assert(Source && "lazy initializers but no external source"); 919 920 auto LazyInits = std::move(LazyInitializers); 921 LazyInitializers.clear(); 922 923 for (auto ID : LazyInits) 924 Initializers.push_back(Source->GetExternalDecl(ID)); 925 926 assert(LazyInitializers.empty() && 927 "GetExternalDecl for lazy module initializer added more inits"); 928 } 929 930 void ASTContext::addModuleInitializer(Module *M, Decl *D) { 931 // One special case: if we add a module initializer that imports another 932 // module, and that module's only initializer is an ImportDecl, simplify. 933 if (auto *ID = dyn_cast<ImportDecl>(D)) { 934 auto It = ModuleInitializers.find(ID->getImportedModule()); 935 936 // Maybe the ImportDecl does nothing at all. (Common case.) 937 if (It == ModuleInitializers.end()) 938 return; 939 940 // Maybe the ImportDecl only imports another ImportDecl. 941 auto &Imported = *It->second; 942 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) { 943 Imported.resolve(*this); 944 auto *OnlyDecl = Imported.Initializers.front(); 945 if (isa<ImportDecl>(OnlyDecl)) 946 D = OnlyDecl; 947 } 948 } 949 950 auto *&Inits = ModuleInitializers[M]; 951 if (!Inits) 952 Inits = new (*this) PerModuleInitializers; 953 Inits->Initializers.push_back(D); 954 } 955 956 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) { 957 auto *&Inits = ModuleInitializers[M]; 958 if (!Inits) 959 Inits = new (*this) PerModuleInitializers; 960 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(), 961 IDs.begin(), IDs.end()); 962 } 963 964 ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) { 965 auto It = ModuleInitializers.find(M); 966 if (It == ModuleInitializers.end()) 967 return None; 968 969 auto *Inits = It->second; 970 Inits->resolve(*this); 971 return Inits->Initializers; 972 } 973 974 ExternCContextDecl *ASTContext::getExternCContextDecl() const { 975 if (!ExternCContext) 976 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl()); 977 978 return ExternCContext; 979 } 980 981 BuiltinTemplateDecl * 982 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, 983 const IdentifierInfo *II) const { 984 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK); 985 BuiltinTemplate->setImplicit(); 986 TUDecl->addDecl(BuiltinTemplate); 987 988 return BuiltinTemplate; 989 } 990 991 BuiltinTemplateDecl * 992 ASTContext::getMakeIntegerSeqDecl() const { 993 if (!MakeIntegerSeqDecl) 994 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq, 995 getMakeIntegerSeqName()); 996 return MakeIntegerSeqDecl; 997 } 998 999 BuiltinTemplateDecl * 1000 ASTContext::getTypePackElementDecl() const { 1001 if (!TypePackElementDecl) 1002 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element, 1003 getTypePackElementName()); 1004 return TypePackElementDecl; 1005 } 1006 1007 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name, 1008 RecordDecl::TagKind TK) const { 1009 SourceLocation Loc; 1010 RecordDecl *NewDecl; 1011 if (getLangOpts().CPlusPlus) 1012 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, 1013 Loc, &Idents.get(Name)); 1014 else 1015 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc, 1016 &Idents.get(Name)); 1017 NewDecl->setImplicit(); 1018 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit( 1019 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default)); 1020 return NewDecl; 1021 } 1022 1023 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T, 1024 StringRef Name) const { 1025 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 1026 TypedefDecl *NewDecl = TypedefDecl::Create( 1027 const_cast<ASTContext &>(*this), getTranslationUnitDecl(), 1028 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo); 1029 NewDecl->setImplicit(); 1030 return NewDecl; 1031 } 1032 1033 TypedefDecl *ASTContext::getInt128Decl() const { 1034 if (!Int128Decl) 1035 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t"); 1036 return Int128Decl; 1037 } 1038 1039 TypedefDecl *ASTContext::getUInt128Decl() const { 1040 if (!UInt128Decl) 1041 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t"); 1042 return UInt128Decl; 1043 } 1044 1045 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 1046 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K); 1047 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 1048 Types.push_back(Ty); 1049 } 1050 1051 void ASTContext::InitBuiltinTypes(const TargetInfo &Target, 1052 const TargetInfo *AuxTarget) { 1053 assert((!this->Target || this->Target == &Target) && 1054 "Incorrect target reinitialization"); 1055 assert(VoidTy.isNull() && "Context reinitialized?"); 1056 1057 this->Target = &Target; 1058 this->AuxTarget = AuxTarget; 1059 1060 ABI.reset(createCXXABI(Target)); 1061 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 1062 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); 1063 1064 // C99 6.2.5p19. 1065 InitBuiltinType(VoidTy, BuiltinType::Void); 1066 1067 // C99 6.2.5p2. 1068 InitBuiltinType(BoolTy, BuiltinType::Bool); 1069 // C99 6.2.5p3. 1070 if (LangOpts.CharIsSigned) 1071 InitBuiltinType(CharTy, BuiltinType::Char_S); 1072 else 1073 InitBuiltinType(CharTy, BuiltinType::Char_U); 1074 // C99 6.2.5p4. 1075 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 1076 InitBuiltinType(ShortTy, BuiltinType::Short); 1077 InitBuiltinType(IntTy, BuiltinType::Int); 1078 InitBuiltinType(LongTy, BuiltinType::Long); 1079 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 1080 1081 // C99 6.2.5p6. 1082 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 1083 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 1084 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 1085 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 1086 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 1087 1088 // C99 6.2.5p10. 1089 InitBuiltinType(FloatTy, BuiltinType::Float); 1090 InitBuiltinType(DoubleTy, BuiltinType::Double); 1091 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 1092 1093 // GNU extension, __float128 for IEEE quadruple precision 1094 InitBuiltinType(Float128Ty, BuiltinType::Float128); 1095 1096 // GNU extension, 128-bit integers. 1097 InitBuiltinType(Int128Ty, BuiltinType::Int128); 1098 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 1099 1100 // C++ 3.9.1p5 1101 if (TargetInfo::isTypeSigned(Target.getWCharType())) 1102 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 1103 else // -fshort-wchar makes wchar_t be unsigned. 1104 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 1105 if (LangOpts.CPlusPlus && LangOpts.WChar) 1106 WideCharTy = WCharTy; 1107 else { 1108 // C99 (or C++ using -fno-wchar). 1109 WideCharTy = getFromTargetType(Target.getWCharType()); 1110 } 1111 1112 WIntTy = getFromTargetType(Target.getWIntType()); 1113 1114 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1115 InitBuiltinType(Char16Ty, BuiltinType::Char16); 1116 else // C99 1117 Char16Ty = getFromTargetType(Target.getChar16Type()); 1118 1119 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 1120 InitBuiltinType(Char32Ty, BuiltinType::Char32); 1121 else // C99 1122 Char32Ty = getFromTargetType(Target.getChar32Type()); 1123 1124 // Placeholder type for type-dependent expressions whose type is 1125 // completely unknown. No code should ever check a type against 1126 // DependentTy and users should never see it; however, it is here to 1127 // help diagnose failures to properly check for type-dependent 1128 // expressions. 1129 InitBuiltinType(DependentTy, BuiltinType::Dependent); 1130 1131 // Placeholder type for functions. 1132 InitBuiltinType(OverloadTy, BuiltinType::Overload); 1133 1134 // Placeholder type for bound members. 1135 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 1136 1137 // Placeholder type for pseudo-objects. 1138 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 1139 1140 // "any" type; useful for debugger-like clients. 1141 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 1142 1143 // Placeholder type for unbridged ARC casts. 1144 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 1145 1146 // Placeholder type for builtin functions. 1147 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); 1148 1149 // Placeholder type for OMP array sections. 1150 if (LangOpts.OpenMP) 1151 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection); 1152 1153 // C99 6.2.5p11. 1154 FloatComplexTy = getComplexType(FloatTy); 1155 DoubleComplexTy = getComplexType(DoubleTy); 1156 LongDoubleComplexTy = getComplexType(LongDoubleTy); 1157 Float128ComplexTy = getComplexType(Float128Ty); 1158 1159 // Builtin types for 'id', 'Class', and 'SEL'. 1160 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 1161 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 1162 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 1163 1164 if (LangOpts.OpenCL) { 1165 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1166 InitBuiltinType(SingletonId, BuiltinType::Id); 1167 #include "clang/Basic/OpenCLImageTypes.def" 1168 1169 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); 1170 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent); 1171 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent); 1172 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue); 1173 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID); 1174 } 1175 1176 // Builtin type for __objc_yes and __objc_no 1177 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 1178 SignedCharTy : BoolTy); 1179 1180 ObjCConstantStringType = QualType(); 1181 1182 ObjCSuperType = QualType(); 1183 1184 // void * type 1185 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 SubstTemplateTypeParmPackTypes.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 /// Return the unique signed counterpart of the integer type 4529 /// corresponding to size_t. 4530 CanQualType ASTContext::getSignedSizeType() const { 4531 return getFromTargetType(Target->getSignedSizeType()); 4532 } 4533 4534 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 4535 CanQualType ASTContext::getIntMaxType() const { 4536 return getFromTargetType(Target->getIntMaxType()); 4537 } 4538 4539 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 4540 CanQualType ASTContext::getUIntMaxType() const { 4541 return getFromTargetType(Target->getUIntMaxType()); 4542 } 4543 4544 /// getSignedWCharType - Return the type of "signed wchar_t". 4545 /// Used when in C++, as a GCC extension. 4546 QualType ASTContext::getSignedWCharType() const { 4547 // FIXME: derive from "Target" ? 4548 return WCharTy; 4549 } 4550 4551 /// getUnsignedWCharType - Return the type of "unsigned wchar_t". 4552 /// Used when in C++, as a GCC extension. 4553 QualType ASTContext::getUnsignedWCharType() const { 4554 // FIXME: derive from "Target" ? 4555 return UnsignedIntTy; 4556 } 4557 4558 QualType ASTContext::getIntPtrType() const { 4559 return getFromTargetType(Target->getIntPtrType()); 4560 } 4561 4562 QualType ASTContext::getUIntPtrType() const { 4563 return getCorrespondingUnsignedType(getIntPtrType()); 4564 } 4565 4566 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 4567 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 4568 QualType ASTContext::getPointerDiffType() const { 4569 return getFromTargetType(Target->getPtrDiffType(0)); 4570 } 4571 4572 /// \brief Return the unique type for "pid_t" defined in 4573 /// <sys/types.h>. We need this to compute the correct type for vfork(). 4574 QualType ASTContext::getProcessIDType() const { 4575 return getFromTargetType(Target->getProcessIDType()); 4576 } 4577 4578 //===----------------------------------------------------------------------===// 4579 // Type Operators 4580 //===----------------------------------------------------------------------===// 4581 4582 CanQualType ASTContext::getCanonicalParamType(QualType T) const { 4583 // Push qualifiers into arrays, and then discard any remaining 4584 // qualifiers. 4585 T = getCanonicalType(T); 4586 T = getVariableArrayDecayedType(T); 4587 const Type *Ty = T.getTypePtr(); 4588 QualType Result; 4589 if (isa<ArrayType>(Ty)) { 4590 Result = getArrayDecayedType(QualType(Ty,0)); 4591 } else if (isa<FunctionType>(Ty)) { 4592 Result = getPointerType(QualType(Ty, 0)); 4593 } else { 4594 Result = QualType(Ty, 0); 4595 } 4596 4597 return CanQualType::CreateUnsafe(Result); 4598 } 4599 4600 QualType ASTContext::getUnqualifiedArrayType(QualType type, 4601 Qualifiers &quals) { 4602 SplitQualType splitType = type.getSplitUnqualifiedType(); 4603 4604 // FIXME: getSplitUnqualifiedType() actually walks all the way to 4605 // the unqualified desugared type and then drops it on the floor. 4606 // We then have to strip that sugar back off with 4607 // getUnqualifiedDesugaredType(), which is silly. 4608 const ArrayType *AT = 4609 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 4610 4611 // If we don't have an array, just use the results in splitType. 4612 if (!AT) { 4613 quals = splitType.Quals; 4614 return QualType(splitType.Ty, 0); 4615 } 4616 4617 // Otherwise, recurse on the array's element type. 4618 QualType elementType = AT->getElementType(); 4619 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 4620 4621 // If that didn't change the element type, AT has no qualifiers, so we 4622 // can just use the results in splitType. 4623 if (elementType == unqualElementType) { 4624 assert(quals.empty()); // from the recursive call 4625 quals = splitType.Quals; 4626 return QualType(splitType.Ty, 0); 4627 } 4628 4629 // Otherwise, add in the qualifiers from the outermost type, then 4630 // build the type back up. 4631 quals.addConsistentQualifiers(splitType.Quals); 4632 4633 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { 4634 return getConstantArrayType(unqualElementType, CAT->getSize(), 4635 CAT->getSizeModifier(), 0); 4636 } 4637 4638 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 4639 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 4640 } 4641 4642 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) { 4643 return getVariableArrayType(unqualElementType, 4644 VAT->getSizeExpr(), 4645 VAT->getSizeModifier(), 4646 VAT->getIndexTypeCVRQualifiers(), 4647 VAT->getBracketsRange()); 4648 } 4649 4650 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT); 4651 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 4652 DSAT->getSizeModifier(), 0, 4653 SourceRange()); 4654 } 4655 4656 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 4657 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that 4658 /// they point to and return true. If T1 and T2 aren't pointer types 4659 /// or pointer-to-member types, or if they are not similar at this 4660 /// level, returns false and leaves T1 and T2 unchanged. Top-level 4661 /// qualifiers on T1 and T2 are ignored. This function will typically 4662 /// be called in a loop that successively "unwraps" pointer and 4663 /// pointer-to-member types to compare them at each level. 4664 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) { 4665 const PointerType *T1PtrType = T1->getAs<PointerType>(), 4666 *T2PtrType = T2->getAs<PointerType>(); 4667 if (T1PtrType && T2PtrType) { 4668 T1 = T1PtrType->getPointeeType(); 4669 T2 = T2PtrType->getPointeeType(); 4670 return true; 4671 } 4672 4673 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 4674 *T2MPType = T2->getAs<MemberPointerType>(); 4675 if (T1MPType && T2MPType && 4676 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 4677 QualType(T2MPType->getClass(), 0))) { 4678 T1 = T1MPType->getPointeeType(); 4679 T2 = T2MPType->getPointeeType(); 4680 return true; 4681 } 4682 4683 if (getLangOpts().ObjC1) { 4684 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(), 4685 *T2OPType = T2->getAs<ObjCObjectPointerType>(); 4686 if (T1OPType && T2OPType) { 4687 T1 = T1OPType->getPointeeType(); 4688 T2 = T2OPType->getPointeeType(); 4689 return true; 4690 } 4691 } 4692 4693 // FIXME: Block pointers, too? 4694 4695 return false; 4696 } 4697 4698 DeclarationNameInfo 4699 ASTContext::getNameForTemplate(TemplateName Name, 4700 SourceLocation NameLoc) const { 4701 switch (Name.getKind()) { 4702 case TemplateName::QualifiedTemplate: 4703 case TemplateName::Template: 4704 // DNInfo work in progress: CHECKME: what about DNLoc? 4705 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 4706 NameLoc); 4707 4708 case TemplateName::OverloadedTemplate: { 4709 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 4710 // DNInfo work in progress: CHECKME: what about DNLoc? 4711 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 4712 } 4713 4714 case TemplateName::DependentTemplate: { 4715 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 4716 DeclarationName DName; 4717 if (DTN->isIdentifier()) { 4718 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 4719 return DeclarationNameInfo(DName, NameLoc); 4720 } else { 4721 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 4722 // DNInfo work in progress: FIXME: source locations? 4723 DeclarationNameLoc DNLoc; 4724 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding(); 4725 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding(); 4726 return DeclarationNameInfo(DName, NameLoc, DNLoc); 4727 } 4728 } 4729 4730 case TemplateName::SubstTemplateTemplateParm: { 4731 SubstTemplateTemplateParmStorage *subst 4732 = Name.getAsSubstTemplateTemplateParm(); 4733 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 4734 NameLoc); 4735 } 4736 4737 case TemplateName::SubstTemplateTemplateParmPack: { 4738 SubstTemplateTemplateParmPackStorage *subst 4739 = Name.getAsSubstTemplateTemplateParmPack(); 4740 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 4741 NameLoc); 4742 } 4743 } 4744 4745 llvm_unreachable("bad template name kind!"); 4746 } 4747 4748 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { 4749 switch (Name.getKind()) { 4750 case TemplateName::QualifiedTemplate: 4751 case TemplateName::Template: { 4752 TemplateDecl *Template = Name.getAsTemplateDecl(); 4753 if (TemplateTemplateParmDecl *TTP 4754 = dyn_cast<TemplateTemplateParmDecl>(Template)) 4755 Template = getCanonicalTemplateTemplateParmDecl(TTP); 4756 4757 // The canonical template name is the canonical template declaration. 4758 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 4759 } 4760 4761 case TemplateName::OverloadedTemplate: 4762 llvm_unreachable("cannot canonicalize overloaded template"); 4763 4764 case TemplateName::DependentTemplate: { 4765 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 4766 assert(DTN && "Non-dependent template names must refer to template decls."); 4767 return DTN->CanonicalTemplateName; 4768 } 4769 4770 case TemplateName::SubstTemplateTemplateParm: { 4771 SubstTemplateTemplateParmStorage *subst 4772 = Name.getAsSubstTemplateTemplateParm(); 4773 return getCanonicalTemplateName(subst->getReplacement()); 4774 } 4775 4776 case TemplateName::SubstTemplateTemplateParmPack: { 4777 SubstTemplateTemplateParmPackStorage *subst 4778 = Name.getAsSubstTemplateTemplateParmPack(); 4779 TemplateTemplateParmDecl *canonParameter 4780 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 4781 TemplateArgument canonArgPack 4782 = getCanonicalTemplateArgument(subst->getArgumentPack()); 4783 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 4784 } 4785 } 4786 4787 llvm_unreachable("bad template name!"); 4788 } 4789 4790 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 4791 X = getCanonicalTemplateName(X); 4792 Y = getCanonicalTemplateName(Y); 4793 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 4794 } 4795 4796 TemplateArgument 4797 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 4798 switch (Arg.getKind()) { 4799 case TemplateArgument::Null: 4800 return Arg; 4801 4802 case TemplateArgument::Expression: 4803 return Arg; 4804 4805 case TemplateArgument::Declaration: { 4806 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); 4807 return TemplateArgument(D, Arg.getParamTypeForDecl()); 4808 } 4809 4810 case TemplateArgument::NullPtr: 4811 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), 4812 /*isNullPtr*/true); 4813 4814 case TemplateArgument::Template: 4815 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 4816 4817 case TemplateArgument::TemplateExpansion: 4818 return TemplateArgument(getCanonicalTemplateName( 4819 Arg.getAsTemplateOrTemplatePattern()), 4820 Arg.getNumTemplateExpansions()); 4821 4822 case TemplateArgument::Integral: 4823 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 4824 4825 case TemplateArgument::Type: 4826 return TemplateArgument(getCanonicalType(Arg.getAsType())); 4827 4828 case TemplateArgument::Pack: { 4829 if (Arg.pack_size() == 0) 4830 return Arg; 4831 4832 TemplateArgument *CanonArgs 4833 = new (*this) TemplateArgument[Arg.pack_size()]; 4834 unsigned Idx = 0; 4835 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 4836 AEnd = Arg.pack_end(); 4837 A != AEnd; (void)++A, ++Idx) 4838 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 4839 4840 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size())); 4841 } 4842 } 4843 4844 // Silence GCC warning 4845 llvm_unreachable("Unhandled template argument kind"); 4846 } 4847 4848 NestedNameSpecifier * 4849 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 4850 if (!NNS) 4851 return nullptr; 4852 4853 switch (NNS->getKind()) { 4854 case NestedNameSpecifier::Identifier: 4855 // Canonicalize the prefix but keep the identifier the same. 4856 return NestedNameSpecifier::Create(*this, 4857 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 4858 NNS->getAsIdentifier()); 4859 4860 case NestedNameSpecifier::Namespace: 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->getAsNamespace()->getOriginalNamespace()); 4865 4866 case NestedNameSpecifier::NamespaceAlias: 4867 // A namespace is canonical; build a nested-name-specifier with 4868 // this namespace and no prefix. 4869 return NestedNameSpecifier::Create(*this, nullptr, 4870 NNS->getAsNamespaceAlias()->getNamespace() 4871 ->getOriginalNamespace()); 4872 4873 case NestedNameSpecifier::TypeSpec: 4874 case NestedNameSpecifier::TypeSpecWithTemplate: { 4875 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 4876 4877 // If we have some kind of dependent-named type (e.g., "typename T::type"), 4878 // break it apart into its prefix and identifier, then reconsititute those 4879 // as the canonical nested-name-specifier. This is required to canonicalize 4880 // a dependent nested-name-specifier involving typedefs of dependent-name 4881 // types, e.g., 4882 // typedef typename T::type T1; 4883 // typedef typename T1::type T2; 4884 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) 4885 return NestedNameSpecifier::Create(*this, DNT->getQualifier(), 4886 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 4887 4888 // Otherwise, just canonicalize the type, and force it to be a TypeSpec. 4889 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the 4890 // first place? 4891 return NestedNameSpecifier::Create(*this, nullptr, false, 4892 const_cast<Type *>(T.getTypePtr())); 4893 } 4894 4895 case NestedNameSpecifier::Global: 4896 case NestedNameSpecifier::Super: 4897 // The global specifier and __super specifer are canonical and unique. 4898 return NNS; 4899 } 4900 4901 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 4902 } 4903 4904 const ArrayType *ASTContext::getAsArrayType(QualType T) const { 4905 // Handle the non-qualified case efficiently. 4906 if (!T.hasLocalQualifiers()) { 4907 // Handle the common positive case fast. 4908 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 4909 return AT; 4910 } 4911 4912 // Handle the common negative case fast. 4913 if (!isa<ArrayType>(T.getCanonicalType())) 4914 return nullptr; 4915 4916 // Apply any qualifiers from the array type to the element type. This 4917 // implements C99 6.7.3p8: "If the specification of an array type includes 4918 // any type qualifiers, the element type is so qualified, not the array type." 4919 4920 // If we get here, we either have type qualifiers on the type, or we have 4921 // sugar such as a typedef in the way. If we have type qualifiers on the type 4922 // we must propagate them down into the element type. 4923 4924 SplitQualType split = T.getSplitDesugaredType(); 4925 Qualifiers qs = split.Quals; 4926 4927 // If we have a simple case, just return now. 4928 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty); 4929 if (!ATy || qs.empty()) 4930 return ATy; 4931 4932 // Otherwise, we have an array and we have qualifiers on it. Push the 4933 // qualifiers into the array element type and return a new array type. 4934 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 4935 4936 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy)) 4937 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 4938 CAT->getSizeModifier(), 4939 CAT->getIndexTypeCVRQualifiers())); 4940 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy)) 4941 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 4942 IAT->getSizeModifier(), 4943 IAT->getIndexTypeCVRQualifiers())); 4944 4945 if (const DependentSizedArrayType *DSAT 4946 = dyn_cast<DependentSizedArrayType>(ATy)) 4947 return cast<ArrayType>( 4948 getDependentSizedArrayType(NewEltTy, 4949 DSAT->getSizeExpr(), 4950 DSAT->getSizeModifier(), 4951 DSAT->getIndexTypeCVRQualifiers(), 4952 DSAT->getBracketsRange())); 4953 4954 const VariableArrayType *VAT = cast<VariableArrayType>(ATy); 4955 return cast<ArrayType>(getVariableArrayType(NewEltTy, 4956 VAT->getSizeExpr(), 4957 VAT->getSizeModifier(), 4958 VAT->getIndexTypeCVRQualifiers(), 4959 VAT->getBracketsRange())); 4960 } 4961 4962 QualType ASTContext::getAdjustedParameterType(QualType T) const { 4963 if (T->isArrayType() || T->isFunctionType()) 4964 return getDecayedType(T); 4965 return T; 4966 } 4967 4968 QualType ASTContext::getSignatureParameterType(QualType T) const { 4969 T = getVariableArrayDecayedType(T); 4970 T = getAdjustedParameterType(T); 4971 return T.getUnqualifiedType(); 4972 } 4973 4974 QualType ASTContext::getExceptionObjectType(QualType T) const { 4975 // C++ [except.throw]p3: 4976 // A throw-expression initializes a temporary object, called the exception 4977 // object, the type of which is determined by removing any top-level 4978 // cv-qualifiers from the static type of the operand of throw and adjusting 4979 // the type from "array of T" or "function returning T" to "pointer to T" 4980 // or "pointer to function returning T", [...] 4981 T = getVariableArrayDecayedType(T); 4982 if (T->isArrayType() || T->isFunctionType()) 4983 T = getDecayedType(T); 4984 return T.getUnqualifiedType(); 4985 } 4986 4987 /// getArrayDecayedType - Return the properly qualified result of decaying the 4988 /// specified array type to a pointer. This operation is non-trivial when 4989 /// handling typedefs etc. The canonical type of "T" must be an array type, 4990 /// this returns a pointer to a properly qualified element of the array. 4991 /// 4992 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 4993 QualType ASTContext::getArrayDecayedType(QualType Ty) const { 4994 // Get the element type with 'getAsArrayType' so that we don't lose any 4995 // typedefs in the element type of the array. This also handles propagation 4996 // of type qualifiers from the array type into the element type if present 4997 // (C99 6.7.3p8). 4998 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 4999 assert(PrettyArrayType && "Not an array type!"); 5000 5001 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 5002 5003 // int x[restrict 4] -> int *restrict 5004 QualType Result = getQualifiedType(PtrTy, 5005 PrettyArrayType->getIndexTypeQualifiers()); 5006 5007 // int x[_Nullable] -> int * _Nullable 5008 if (auto Nullability = Ty->getNullability(*this)) { 5009 Result = const_cast<ASTContext *>(this)->getAttributedType( 5010 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result); 5011 } 5012 return Result; 5013 } 5014 5015 QualType ASTContext::getBaseElementType(const ArrayType *array) const { 5016 return getBaseElementType(array->getElementType()); 5017 } 5018 5019 QualType ASTContext::getBaseElementType(QualType type) const { 5020 Qualifiers qs; 5021 while (true) { 5022 SplitQualType split = type.getSplitDesugaredType(); 5023 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 5024 if (!array) break; 5025 5026 type = array->getElementType(); 5027 qs.addConsistentQualifiers(split.Quals); 5028 } 5029 5030 return getQualifiedType(type, qs); 5031 } 5032 5033 /// getConstantArrayElementCount - Returns number of constant array elements. 5034 uint64_t 5035 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 5036 uint64_t ElementCount = 1; 5037 do { 5038 ElementCount *= CA->getSize().getZExtValue(); 5039 CA = dyn_cast_or_null<ConstantArrayType>( 5040 CA->getElementType()->getAsArrayTypeUnsafe()); 5041 } while (CA); 5042 return ElementCount; 5043 } 5044 5045 /// getFloatingRank - Return a relative rank for floating point types. 5046 /// This routine will assert if passed a built-in type that isn't a float. 5047 static FloatingRank getFloatingRank(QualType T) { 5048 if (const ComplexType *CT = T->getAs<ComplexType>()) 5049 return getFloatingRank(CT->getElementType()); 5050 5051 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type"); 5052 switch (T->getAs<BuiltinType>()->getKind()) { 5053 default: llvm_unreachable("getFloatingRank(): not a floating type"); 5054 case BuiltinType::Half: return HalfRank; 5055 case BuiltinType::Float: return FloatRank; 5056 case BuiltinType::Double: return DoubleRank; 5057 case BuiltinType::LongDouble: return LongDoubleRank; 5058 case BuiltinType::Float128: return Float128Rank; 5059 } 5060 } 5061 5062 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating 5063 /// point or a complex type (based on typeDomain/typeSize). 5064 /// 'typeDomain' is a real floating point or complex type. 5065 /// 'typeSize' is a real floating point or complex type. 5066 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 5067 QualType Domain) const { 5068 FloatingRank EltRank = getFloatingRank(Size); 5069 if (Domain->isComplexType()) { 5070 switch (EltRank) { 5071 case HalfRank: llvm_unreachable("Complex half is not supported"); 5072 case FloatRank: return FloatComplexTy; 5073 case DoubleRank: return DoubleComplexTy; 5074 case LongDoubleRank: return LongDoubleComplexTy; 5075 case Float128Rank: return Float128ComplexTy; 5076 } 5077 } 5078 5079 assert(Domain->isRealFloatingType() && "Unknown domain!"); 5080 switch (EltRank) { 5081 case HalfRank: return HalfTy; 5082 case FloatRank: return FloatTy; 5083 case DoubleRank: return DoubleTy; 5084 case LongDoubleRank: return LongDoubleTy; 5085 case Float128Rank: return Float128Ty; 5086 } 5087 llvm_unreachable("getFloatingRank(): illegal value for rank"); 5088 } 5089 5090 /// getFloatingTypeOrder - Compare the rank of the two specified floating 5091 /// point types, ignoring the domain of the type (i.e. 'double' == 5092 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 5093 /// LHS < RHS, return -1. 5094 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 5095 FloatingRank LHSR = getFloatingRank(LHS); 5096 FloatingRank RHSR = getFloatingRank(RHS); 5097 5098 if (LHSR == RHSR) 5099 return 0; 5100 if (LHSR > RHSR) 5101 return 1; 5102 return -1; 5103 } 5104 5105 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 5106 /// routine will assert if passed a built-in type that isn't an integer or enum, 5107 /// or if it is not canonicalized. 5108 unsigned ASTContext::getIntegerRank(const Type *T) const { 5109 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 5110 5111 switch (cast<BuiltinType>(T)->getKind()) { 5112 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 5113 case BuiltinType::Bool: 5114 return 1 + (getIntWidth(BoolTy) << 3); 5115 case BuiltinType::Char_S: 5116 case BuiltinType::Char_U: 5117 case BuiltinType::SChar: 5118 case BuiltinType::UChar: 5119 return 2 + (getIntWidth(CharTy) << 3); 5120 case BuiltinType::Short: 5121 case BuiltinType::UShort: 5122 return 3 + (getIntWidth(ShortTy) << 3); 5123 case BuiltinType::Int: 5124 case BuiltinType::UInt: 5125 return 4 + (getIntWidth(IntTy) << 3); 5126 case BuiltinType::Long: 5127 case BuiltinType::ULong: 5128 return 5 + (getIntWidth(LongTy) << 3); 5129 case BuiltinType::LongLong: 5130 case BuiltinType::ULongLong: 5131 return 6 + (getIntWidth(LongLongTy) << 3); 5132 case BuiltinType::Int128: 5133 case BuiltinType::UInt128: 5134 return 7 + (getIntWidth(Int128Ty) << 3); 5135 } 5136 } 5137 5138 /// \brief Whether this is a promotable bitfield reference according 5139 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 5140 /// 5141 /// \returns the type this bit-field will promote to, or NULL if no 5142 /// promotion occurs. 5143 QualType ASTContext::isPromotableBitField(Expr *E) const { 5144 if (E->isTypeDependent() || E->isValueDependent()) 5145 return QualType(); 5146 5147 // FIXME: We should not do this unless E->refersToBitField() is true. This 5148 // matters in C where getSourceBitField() will find bit-fields for various 5149 // cases where the source expression is not a bit-field designator. 5150 5151 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? 5152 if (!Field) 5153 return QualType(); 5154 5155 QualType FT = Field->getType(); 5156 5157 uint64_t BitWidth = Field->getBitWidthValue(*this); 5158 uint64_t IntSize = getTypeSize(IntTy); 5159 // C++ [conv.prom]p5: 5160 // A prvalue for an integral bit-field can be converted to a prvalue of type 5161 // int if int can represent all the values of the bit-field; otherwise, it 5162 // can be converted to unsigned int if unsigned int can represent all the 5163 // values of the bit-field. If the bit-field is larger yet, no integral 5164 // promotion applies to it. 5165 // C11 6.3.1.1/2: 5166 // [For a bit-field of type _Bool, int, signed int, or unsigned int:] 5167 // If an int can represent all values of the original type (as restricted by 5168 // the width, for a bit-field), the value is converted to an int; otherwise, 5169 // it is converted to an unsigned int. 5170 // 5171 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int. 5172 // We perform that promotion here to match GCC and C++. 5173 if (BitWidth < IntSize) 5174 return IntTy; 5175 5176 if (BitWidth == IntSize) 5177 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 5178 5179 // Types bigger than int are not subject to promotions, and therefore act 5180 // like the base type. GCC has some weird bugs in this area that we 5181 // deliberately do not follow (GCC follows a pre-standard resolution to 5182 // C's DR315 which treats bit-width as being part of the type, and this leaks 5183 // into their semantics in some cases). 5184 return QualType(); 5185 } 5186 5187 /// getPromotedIntegerType - Returns the type that Promotable will 5188 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 5189 /// integer type. 5190 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 5191 assert(!Promotable.isNull()); 5192 assert(Promotable->isPromotableIntegerType()); 5193 if (const EnumType *ET = Promotable->getAs<EnumType>()) 5194 return ET->getDecl()->getPromotionType(); 5195 5196 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) { 5197 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 5198 // (3.9.1) can be converted to a prvalue of the first of the following 5199 // types that can represent all the values of its underlying type: 5200 // int, unsigned int, long int, unsigned long int, long long int, or 5201 // unsigned long long int [...] 5202 // FIXME: Is there some better way to compute this? 5203 if (BT->getKind() == BuiltinType::WChar_S || 5204 BT->getKind() == BuiltinType::WChar_U || 5205 BT->getKind() == BuiltinType::Char16 || 5206 BT->getKind() == BuiltinType::Char32) { 5207 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 5208 uint64_t FromSize = getTypeSize(BT); 5209 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 5210 LongLongTy, UnsignedLongLongTy }; 5211 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 5212 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 5213 if (FromSize < ToSize || 5214 (FromSize == ToSize && 5215 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 5216 return PromoteTypes[Idx]; 5217 } 5218 llvm_unreachable("char type should fit into long long"); 5219 } 5220 } 5221 5222 // At this point, we should have a signed or unsigned integer type. 5223 if (Promotable->isSignedIntegerType()) 5224 return IntTy; 5225 uint64_t PromotableSize = getIntWidth(Promotable); 5226 uint64_t IntSize = getIntWidth(IntTy); 5227 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 5228 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 5229 } 5230 5231 /// \brief Recurses in pointer/array types until it finds an objc retainable 5232 /// type and returns its ownership. 5233 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 5234 while (!T.isNull()) { 5235 if (T.getObjCLifetime() != Qualifiers::OCL_None) 5236 return T.getObjCLifetime(); 5237 if (T->isArrayType()) 5238 T = getBaseElementType(T); 5239 else if (const PointerType *PT = T->getAs<PointerType>()) 5240 T = PT->getPointeeType(); 5241 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 5242 T = RT->getPointeeType(); 5243 else 5244 break; 5245 } 5246 5247 return Qualifiers::OCL_None; 5248 } 5249 5250 static const Type *getIntegerTypeForEnum(const EnumType *ET) { 5251 // Incomplete enum types are not treated as integer types. 5252 // FIXME: In C++, enum types are never integer types. 5253 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 5254 return ET->getDecl()->getIntegerType().getTypePtr(); 5255 return nullptr; 5256 } 5257 5258 /// getIntegerTypeOrder - Returns the highest ranked integer type: 5259 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 5260 /// LHS < RHS, return -1. 5261 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 5262 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 5263 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 5264 5265 // Unwrap enums to their underlying type. 5266 if (const EnumType *ET = dyn_cast<EnumType>(LHSC)) 5267 LHSC = getIntegerTypeForEnum(ET); 5268 if (const EnumType *ET = dyn_cast<EnumType>(RHSC)) 5269 RHSC = getIntegerTypeForEnum(ET); 5270 5271 if (LHSC == RHSC) return 0; 5272 5273 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 5274 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 5275 5276 unsigned LHSRank = getIntegerRank(LHSC); 5277 unsigned RHSRank = getIntegerRank(RHSC); 5278 5279 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 5280 if (LHSRank == RHSRank) return 0; 5281 return LHSRank > RHSRank ? 1 : -1; 5282 } 5283 5284 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 5285 if (LHSUnsigned) { 5286 // If the unsigned [LHS] type is larger, return it. 5287 if (LHSRank >= RHSRank) 5288 return 1; 5289 5290 // If the signed type can represent all values of the unsigned type, it 5291 // wins. Because we are dealing with 2's complement and types that are 5292 // powers of two larger than each other, this is always safe. 5293 return -1; 5294 } 5295 5296 // If the unsigned [RHS] type is larger, return it. 5297 if (RHSRank >= LHSRank) 5298 return -1; 5299 5300 // If the signed type can represent all values of the unsigned type, it 5301 // wins. Because we are dealing with 2's complement and types that are 5302 // powers of two larger than each other, this is always safe. 5303 return 1; 5304 } 5305 5306 TypedefDecl *ASTContext::getCFConstantStringDecl() const { 5307 if (!CFConstantStringTypeDecl) { 5308 assert(!CFConstantStringTagDecl && 5309 "tag and typedef should be initialized together"); 5310 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag"); 5311 CFConstantStringTagDecl->startDefinition(); 5312 5313 QualType FieldTypes[4]; 5314 const char *FieldNames[4]; 5315 5316 // const int *isa; 5317 FieldTypes[0] = getPointerType(IntTy.withConst()); 5318 FieldNames[0] = "isa"; 5319 // int flags; 5320 FieldTypes[1] = IntTy; 5321 FieldNames[1] = "flags"; 5322 // const char *str; 5323 FieldTypes[2] = getPointerType(CharTy.withConst()); 5324 FieldNames[2] = "str"; 5325 // long length; 5326 FieldTypes[3] = LongTy; 5327 FieldNames[3] = "length"; 5328 5329 // Create fields 5330 for (unsigned i = 0; i < 4; ++i) { 5331 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl, 5332 SourceLocation(), 5333 SourceLocation(), 5334 &Idents.get(FieldNames[i]), 5335 FieldTypes[i], /*TInfo=*/nullptr, 5336 /*BitWidth=*/nullptr, 5337 /*Mutable=*/false, 5338 ICIS_NoInit); 5339 Field->setAccess(AS_public); 5340 CFConstantStringTagDecl->addDecl(Field); 5341 } 5342 5343 CFConstantStringTagDecl->completeDefinition(); 5344 // This type is designed to be compatible with NSConstantString, but cannot 5345 // use the same name, since NSConstantString is an interface. 5346 auto tagType = getTagDeclType(CFConstantStringTagDecl); 5347 CFConstantStringTypeDecl = 5348 buildImplicitTypedef(tagType, "__NSConstantString"); 5349 } 5350 5351 return CFConstantStringTypeDecl; 5352 } 5353 5354 RecordDecl *ASTContext::getCFConstantStringTagDecl() const { 5355 if (!CFConstantStringTagDecl) 5356 getCFConstantStringDecl(); // Build the tag and the typedef. 5357 return CFConstantStringTagDecl; 5358 } 5359 5360 // getCFConstantStringType - Return the type used for constant CFStrings. 5361 QualType ASTContext::getCFConstantStringType() const { 5362 return getTypedefType(getCFConstantStringDecl()); 5363 } 5364 5365 QualType ASTContext::getObjCSuperType() const { 5366 if (ObjCSuperType.isNull()) { 5367 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super"); 5368 TUDecl->addDecl(ObjCSuperTypeDecl); 5369 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); 5370 } 5371 return ObjCSuperType; 5372 } 5373 5374 void ASTContext::setCFConstantStringType(QualType T) { 5375 const TypedefType *TD = T->getAs<TypedefType>(); 5376 assert(TD && "Invalid CFConstantStringType"); 5377 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl()); 5378 auto TagType = 5379 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>(); 5380 assert(TagType && "Invalid CFConstantStringType"); 5381 CFConstantStringTagDecl = TagType->getDecl(); 5382 } 5383 5384 QualType ASTContext::getBlockDescriptorType() const { 5385 if (BlockDescriptorType) 5386 return getTagDeclType(BlockDescriptorType); 5387 5388 RecordDecl *RD; 5389 // FIXME: Needs the FlagAppleBlock bit. 5390 RD = buildImplicitRecord("__block_descriptor"); 5391 RD->startDefinition(); 5392 5393 QualType FieldTypes[] = { 5394 UnsignedLongTy, 5395 UnsignedLongTy, 5396 }; 5397 5398 static const char *const FieldNames[] = { 5399 "reserved", 5400 "Size" 5401 }; 5402 5403 for (size_t i = 0; i < 2; ++i) { 5404 FieldDecl *Field = FieldDecl::Create( 5405 *this, RD, SourceLocation(), SourceLocation(), 5406 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 5407 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 5408 Field->setAccess(AS_public); 5409 RD->addDecl(Field); 5410 } 5411 5412 RD->completeDefinition(); 5413 5414 BlockDescriptorType = RD; 5415 5416 return getTagDeclType(BlockDescriptorType); 5417 } 5418 5419 QualType ASTContext::getBlockDescriptorExtendedType() const { 5420 if (BlockDescriptorExtendedType) 5421 return getTagDeclType(BlockDescriptorExtendedType); 5422 5423 RecordDecl *RD; 5424 // FIXME: Needs the FlagAppleBlock bit. 5425 RD = buildImplicitRecord("__block_descriptor_withcopydispose"); 5426 RD->startDefinition(); 5427 5428 QualType FieldTypes[] = { 5429 UnsignedLongTy, 5430 UnsignedLongTy, 5431 getPointerType(VoidPtrTy), 5432 getPointerType(VoidPtrTy) 5433 }; 5434 5435 static const char *const FieldNames[] = { 5436 "reserved", 5437 "Size", 5438 "CopyFuncPtr", 5439 "DestroyFuncPtr" 5440 }; 5441 5442 for (size_t i = 0; i < 4; ++i) { 5443 FieldDecl *Field = FieldDecl::Create( 5444 *this, RD, SourceLocation(), SourceLocation(), 5445 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 5446 /*BitWidth=*/nullptr, 5447 /*Mutable=*/false, ICIS_NoInit); 5448 Field->setAccess(AS_public); 5449 RD->addDecl(Field); 5450 } 5451 5452 RD->completeDefinition(); 5453 5454 BlockDescriptorExtendedType = RD; 5455 return getTagDeclType(BlockDescriptorExtendedType); 5456 } 5457 5458 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" 5459 /// requires copy/dispose. Note that this must match the logic 5460 /// in buildByrefHelpers. 5461 bool ASTContext::BlockRequiresCopying(QualType Ty, 5462 const VarDecl *D) { 5463 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { 5464 const Expr *copyExpr = getBlockVarCopyInits(D); 5465 if (!copyExpr && record->hasTrivialDestructor()) return false; 5466 5467 return true; 5468 } 5469 5470 if (!Ty->isObjCRetainableType()) return false; 5471 5472 Qualifiers qs = Ty.getQualifiers(); 5473 5474 // If we have lifetime, that dominates. 5475 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { 5476 switch (lifetime) { 5477 case Qualifiers::OCL_None: llvm_unreachable("impossible"); 5478 5479 // These are just bits as far as the runtime is concerned. 5480 case Qualifiers::OCL_ExplicitNone: 5481 case Qualifiers::OCL_Autoreleasing: 5482 return false; 5483 5484 // Tell the runtime that this is ARC __weak, called by the 5485 // byref routines. 5486 case Qualifiers::OCL_Weak: 5487 // ARC __strong __block variables need to be retained. 5488 case Qualifiers::OCL_Strong: 5489 return true; 5490 } 5491 llvm_unreachable("fell out of lifetime switch!"); 5492 } 5493 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || 5494 Ty->isObjCObjectPointerType()); 5495 } 5496 5497 bool ASTContext::getByrefLifetime(QualType Ty, 5498 Qualifiers::ObjCLifetime &LifeTime, 5499 bool &HasByrefExtendedLayout) const { 5500 5501 if (!getLangOpts().ObjC1 || 5502 getLangOpts().getGC() != LangOptions::NonGC) 5503 return false; 5504 5505 HasByrefExtendedLayout = false; 5506 if (Ty->isRecordType()) { 5507 HasByrefExtendedLayout = true; 5508 LifeTime = Qualifiers::OCL_None; 5509 } else if ((LifeTime = Ty.getObjCLifetime())) { 5510 // Honor the ARC qualifiers. 5511 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) { 5512 // The MRR rule. 5513 LifeTime = Qualifiers::OCL_ExplicitNone; 5514 } else { 5515 LifeTime = Qualifiers::OCL_None; 5516 } 5517 return true; 5518 } 5519 5520 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 5521 if (!ObjCInstanceTypeDecl) 5522 ObjCInstanceTypeDecl = 5523 buildImplicitTypedef(getObjCIdType(), "instancetype"); 5524 return ObjCInstanceTypeDecl; 5525 } 5526 5527 // This returns true if a type has been typedefed to BOOL: 5528 // typedef <type> BOOL; 5529 static bool isTypeTypedefedAsBOOL(QualType T) { 5530 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 5531 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 5532 return II->isStr("BOOL"); 5533 5534 return false; 5535 } 5536 5537 /// getObjCEncodingTypeSize returns size of type for objective-c encoding 5538 /// purpose. 5539 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 5540 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 5541 return CharUnits::Zero(); 5542 5543 CharUnits sz = getTypeSizeInChars(type); 5544 5545 // Make all integer and enum types at least as large as an int 5546 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 5547 sz = std::max(sz, getTypeSizeInChars(IntTy)); 5548 // Treat arrays as pointers, since that's how they're passed in. 5549 else if (type->isArrayType()) 5550 sz = getTypeSizeInChars(VoidPtrTy); 5551 return sz; 5552 } 5553 5554 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { 5555 return getTargetInfo().getCXXABI().isMicrosoft() && 5556 VD->isStaticDataMember() && 5557 VD->getType()->isIntegralOrEnumerationType() && 5558 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit(); 5559 } 5560 5561 ASTContext::InlineVariableDefinitionKind 5562 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const { 5563 if (!VD->isInline()) 5564 return InlineVariableDefinitionKind::None; 5565 5566 // In almost all cases, it's a weak definition. 5567 auto *First = VD->getFirstDecl(); 5568 if (!First->isConstexpr() || First->isInlineSpecified() || 5569 !VD->isStaticDataMember()) 5570 return InlineVariableDefinitionKind::Weak; 5571 5572 // If there's a file-context declaration in this translation unit, it's a 5573 // non-discardable definition. 5574 for (auto *D : VD->redecls()) 5575 if (D->getLexicalDeclContext()->isFileContext()) 5576 return InlineVariableDefinitionKind::Strong; 5577 5578 // If we've not seen one yet, we don't know. 5579 return InlineVariableDefinitionKind::WeakUnknown; 5580 } 5581 5582 static inline 5583 std::string charUnitsToString(const CharUnits &CU) { 5584 return llvm::itostr(CU.getQuantity()); 5585 } 5586 5587 /// getObjCEncodingForBlock - Return the encoded type for this block 5588 /// declaration. 5589 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 5590 std::string S; 5591 5592 const BlockDecl *Decl = Expr->getBlockDecl(); 5593 QualType BlockTy = 5594 Expr->getType()->getAs<BlockPointerType>()->getPointeeType(); 5595 // Encode result type. 5596 if (getLangOpts().EncodeExtendedBlockSig) 5597 getObjCEncodingForMethodParameter( 5598 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S, 5599 true /*Extended*/); 5600 else 5601 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S); 5602 // Compute size of all parameters. 5603 // Start with computing size of a pointer in number of bytes. 5604 // FIXME: There might(should) be a better way of doing this computation! 5605 SourceLocation Loc; 5606 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 5607 CharUnits ParmOffset = PtrSize; 5608 for (auto PI : Decl->parameters()) { 5609 QualType PType = PI->getType(); 5610 CharUnits sz = getObjCEncodingTypeSize(PType); 5611 if (sz.isZero()) 5612 continue; 5613 assert (sz.isPositive() && "BlockExpr - Incomplete param type"); 5614 ParmOffset += sz; 5615 } 5616 // Size of the argument frame 5617 S += charUnitsToString(ParmOffset); 5618 // Block pointer and offset. 5619 S += "@?0"; 5620 5621 // Argument types. 5622 ParmOffset = PtrSize; 5623 for (auto PVDecl : Decl->parameters()) { 5624 QualType PType = PVDecl->getOriginalType(); 5625 if (const ArrayType *AT = 5626 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 5627 // Use array's original type only if it has known number of 5628 // elements. 5629 if (!isa<ConstantArrayType>(AT)) 5630 PType = PVDecl->getType(); 5631 } else if (PType->isFunctionType()) 5632 PType = PVDecl->getType(); 5633 if (getLangOpts().EncodeExtendedBlockSig) 5634 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, 5635 S, true /*Extended*/); 5636 else 5637 getObjCEncodingForType(PType, S); 5638 S += charUnitsToString(ParmOffset); 5639 ParmOffset += getObjCEncodingTypeSize(PType); 5640 } 5641 5642 return S; 5643 } 5644 5645 std::string 5646 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { 5647 std::string S; 5648 // Encode result type. 5649 getObjCEncodingForType(Decl->getReturnType(), S); 5650 CharUnits ParmOffset; 5651 // Compute size of all parameters. 5652 for (auto PI : Decl->parameters()) { 5653 QualType PType = PI->getType(); 5654 CharUnits sz = getObjCEncodingTypeSize(PType); 5655 if (sz.isZero()) 5656 continue; 5657 5658 assert(sz.isPositive() && 5659 "getObjCEncodingForFunctionDecl - Incomplete param type"); 5660 ParmOffset += sz; 5661 } 5662 S += charUnitsToString(ParmOffset); 5663 ParmOffset = CharUnits::Zero(); 5664 5665 // Argument types. 5666 for (auto PVDecl : Decl->parameters()) { 5667 QualType PType = PVDecl->getOriginalType(); 5668 if (const ArrayType *AT = 5669 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 5670 // Use array's original type only if it has known number of 5671 // elements. 5672 if (!isa<ConstantArrayType>(AT)) 5673 PType = PVDecl->getType(); 5674 } else if (PType->isFunctionType()) 5675 PType = PVDecl->getType(); 5676 getObjCEncodingForType(PType, S); 5677 S += charUnitsToString(ParmOffset); 5678 ParmOffset += getObjCEncodingTypeSize(PType); 5679 } 5680 5681 return S; 5682 } 5683 5684 /// getObjCEncodingForMethodParameter - Return the encoded type for a single 5685 /// method parameter or return type. If Extended, include class names and 5686 /// block object types. 5687 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 5688 QualType T, std::string& S, 5689 bool Extended) const { 5690 // Encode type qualifer, 'in', 'inout', etc. for the parameter. 5691 getObjCEncodingForTypeQualifier(QT, S); 5692 // Encode parameter type. 5693 getObjCEncodingForTypeImpl(T, S, true, true, nullptr, 5694 true /*OutermostType*/, 5695 false /*EncodingProperty*/, 5696 false /*StructField*/, 5697 Extended /*EncodeBlockParameters*/, 5698 Extended /*EncodeClassNames*/); 5699 } 5700 5701 /// getObjCEncodingForMethodDecl - Return the encoded type for this method 5702 /// declaration. 5703 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 5704 bool Extended) const { 5705 // FIXME: This is not very efficient. 5706 // Encode return type. 5707 std::string S; 5708 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 5709 Decl->getReturnType(), S, Extended); 5710 // Compute size of all parameters. 5711 // Start with computing size of a pointer in number of bytes. 5712 // FIXME: There might(should) be a better way of doing this computation! 5713 SourceLocation Loc; 5714 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 5715 // The first two arguments (self and _cmd) are pointers; account for 5716 // their size. 5717 CharUnits ParmOffset = 2 * PtrSize; 5718 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 5719 E = Decl->sel_param_end(); PI != E; ++PI) { 5720 QualType PType = (*PI)->getType(); 5721 CharUnits sz = getObjCEncodingTypeSize(PType); 5722 if (sz.isZero()) 5723 continue; 5724 5725 assert (sz.isPositive() && 5726 "getObjCEncodingForMethodDecl - Incomplete param type"); 5727 ParmOffset += sz; 5728 } 5729 S += charUnitsToString(ParmOffset); 5730 S += "@0:"; 5731 S += charUnitsToString(PtrSize); 5732 5733 // Argument types. 5734 ParmOffset = 2 * PtrSize; 5735 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 5736 E = Decl->sel_param_end(); PI != E; ++PI) { 5737 const ParmVarDecl *PVDecl = *PI; 5738 QualType PType = PVDecl->getOriginalType(); 5739 if (const ArrayType *AT = 5740 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 5741 // Use array's original type only if it has known number of 5742 // elements. 5743 if (!isa<ConstantArrayType>(AT)) 5744 PType = PVDecl->getType(); 5745 } else if (PType->isFunctionType()) 5746 PType = PVDecl->getType(); 5747 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 5748 PType, S, Extended); 5749 S += charUnitsToString(ParmOffset); 5750 ParmOffset += getObjCEncodingTypeSize(PType); 5751 } 5752 5753 return S; 5754 } 5755 5756 ObjCPropertyImplDecl * 5757 ASTContext::getObjCPropertyImplDeclForPropertyDecl( 5758 const ObjCPropertyDecl *PD, 5759 const Decl *Container) const { 5760 if (!Container) 5761 return nullptr; 5762 if (const ObjCCategoryImplDecl *CID = 5763 dyn_cast<ObjCCategoryImplDecl>(Container)) { 5764 for (auto *PID : CID->property_impls()) 5765 if (PID->getPropertyDecl() == PD) 5766 return PID; 5767 } else { 5768 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container); 5769 for (auto *PID : OID->property_impls()) 5770 if (PID->getPropertyDecl() == PD) 5771 return PID; 5772 } 5773 return nullptr; 5774 } 5775 5776 /// getObjCEncodingForPropertyDecl - Return the encoded type for this 5777 /// property declaration. If non-NULL, Container must be either an 5778 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 5779 /// NULL when getting encodings for protocol properties. 5780 /// Property attributes are stored as a comma-delimited C string. The simple 5781 /// attributes readonly and bycopy are encoded as single characters. The 5782 /// parametrized attributes, getter=name, setter=name, and ivar=name, are 5783 /// encoded as single characters, followed by an identifier. Property types 5784 /// are also encoded as a parametrized attribute. The characters used to encode 5785 /// these attributes are defined by the following enumeration: 5786 /// @code 5787 /// enum PropertyAttributes { 5788 /// kPropertyReadOnly = 'R', // property is read-only. 5789 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned 5790 /// kPropertyByref = '&', // property is a reference to the value last assigned 5791 /// kPropertyDynamic = 'D', // property is dynamic 5792 /// kPropertyGetter = 'G', // followed by getter selector name 5793 /// kPropertySetter = 'S', // followed by setter selector name 5794 /// kPropertyInstanceVariable = 'V' // followed by instance variable name 5795 /// kPropertyType = 'T' // followed by old-style type encoding. 5796 /// kPropertyWeak = 'W' // 'weak' property 5797 /// kPropertyStrong = 'P' // property GC'able 5798 /// kPropertyNonAtomic = 'N' // property non-atomic 5799 /// }; 5800 /// @endcode 5801 std::string 5802 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 5803 const Decl *Container) const { 5804 // Collect information from the property implementation decl(s). 5805 bool Dynamic = false; 5806 ObjCPropertyImplDecl *SynthesizePID = nullptr; 5807 5808 if (ObjCPropertyImplDecl *PropertyImpDecl = 5809 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { 5810 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 5811 Dynamic = true; 5812 else 5813 SynthesizePID = PropertyImpDecl; 5814 } 5815 5816 // FIXME: This is not very efficient. 5817 std::string S = "T"; 5818 5819 // Encode result type. 5820 // GCC has some special rules regarding encoding of properties which 5821 // closely resembles encoding of ivars. 5822 getObjCEncodingForPropertyType(PD->getType(), S); 5823 5824 if (PD->isReadOnly()) { 5825 S += ",R"; 5826 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) 5827 S += ",C"; 5828 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) 5829 S += ",&"; 5830 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak) 5831 S += ",W"; 5832 } else { 5833 switch (PD->getSetterKind()) { 5834 case ObjCPropertyDecl::Assign: break; 5835 case ObjCPropertyDecl::Copy: S += ",C"; break; 5836 case ObjCPropertyDecl::Retain: S += ",&"; break; 5837 case ObjCPropertyDecl::Weak: S += ",W"; break; 5838 } 5839 } 5840 5841 // It really isn't clear at all what this means, since properties 5842 // are "dynamic by default". 5843 if (Dynamic) 5844 S += ",D"; 5845 5846 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 5847 S += ",N"; 5848 5849 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 5850 S += ",G"; 5851 S += PD->getGetterName().getAsString(); 5852 } 5853 5854 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 5855 S += ",S"; 5856 S += PD->getSetterName().getAsString(); 5857 } 5858 5859 if (SynthesizePID) { 5860 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 5861 S += ",V"; 5862 S += OID->getNameAsString(); 5863 } 5864 5865 // FIXME: OBJCGC: weak & strong 5866 return S; 5867 } 5868 5869 /// getLegacyIntegralTypeEncoding - 5870 /// Another legacy compatibility encoding: 32-bit longs are encoded as 5871 /// 'l' or 'L' , but not always. For typedefs, we need to use 5872 /// 'i' or 'I' instead if encoding a struct field, or a pointer! 5873 /// 5874 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 5875 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 5876 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) { 5877 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 5878 PointeeTy = UnsignedIntTy; 5879 else 5880 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 5881 PointeeTy = IntTy; 5882 } 5883 } 5884 } 5885 5886 void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 5887 const FieldDecl *Field, 5888 QualType *NotEncodedT) const { 5889 // We follow the behavior of gcc, expanding structures which are 5890 // directly pointed to, and expanding embedded structures. Note that 5891 // these rules are sufficient to prevent recursive encoding of the 5892 // same type. 5893 getObjCEncodingForTypeImpl(T, S, true, true, Field, 5894 true /* outermost type */, false, false, 5895 false, false, false, NotEncodedT); 5896 } 5897 5898 void ASTContext::getObjCEncodingForPropertyType(QualType T, 5899 std::string& S) const { 5900 // Encode result type. 5901 // GCC has some special rules regarding encoding of properties which 5902 // closely resembles encoding of ivars. 5903 getObjCEncodingForTypeImpl(T, S, true, true, nullptr, 5904 true /* outermost type */, 5905 true /* encoding property */); 5906 } 5907 5908 static char getObjCEncodingForPrimitiveKind(const ASTContext *C, 5909 BuiltinType::Kind kind) { 5910 switch (kind) { 5911 case BuiltinType::Void: return 'v'; 5912 case BuiltinType::Bool: return 'B'; 5913 case BuiltinType::Char_U: 5914 case BuiltinType::UChar: return 'C'; 5915 case BuiltinType::Char16: 5916 case BuiltinType::UShort: return 'S'; 5917 case BuiltinType::Char32: 5918 case BuiltinType::UInt: return 'I'; 5919 case BuiltinType::ULong: 5920 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; 5921 case BuiltinType::UInt128: return 'T'; 5922 case BuiltinType::ULongLong: return 'Q'; 5923 case BuiltinType::Char_S: 5924 case BuiltinType::SChar: return 'c'; 5925 case BuiltinType::Short: return 's'; 5926 case BuiltinType::WChar_S: 5927 case BuiltinType::WChar_U: 5928 case BuiltinType::Int: return 'i'; 5929 case BuiltinType::Long: 5930 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; 5931 case BuiltinType::LongLong: return 'q'; 5932 case BuiltinType::Int128: return 't'; 5933 case BuiltinType::Float: return 'f'; 5934 case BuiltinType::Double: return 'd'; 5935 case BuiltinType::LongDouble: return 'D'; 5936 case BuiltinType::NullPtr: return '*'; // like char* 5937 5938 case BuiltinType::Float128: 5939 case BuiltinType::Half: 5940 // FIXME: potentially need @encodes for these! 5941 return ' '; 5942 5943 case BuiltinType::ObjCId: 5944 case BuiltinType::ObjCClass: 5945 case BuiltinType::ObjCSel: 5946 llvm_unreachable("@encoding ObjC primitive type"); 5947 5948 // OpenCL and placeholder types don't need @encodings. 5949 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5950 case BuiltinType::Id: 5951 #include "clang/Basic/OpenCLImageTypes.def" 5952 case BuiltinType::OCLEvent: 5953 case BuiltinType::OCLClkEvent: 5954 case BuiltinType::OCLQueue: 5955 case BuiltinType::OCLReserveID: 5956 case BuiltinType::OCLSampler: 5957 case BuiltinType::Dependent: 5958 #define BUILTIN_TYPE(KIND, ID) 5959 #define PLACEHOLDER_TYPE(KIND, ID) \ 5960 case BuiltinType::KIND: 5961 #include "clang/AST/BuiltinTypes.def" 5962 llvm_unreachable("invalid builtin type for @encode"); 5963 } 5964 llvm_unreachable("invalid BuiltinType::Kind value"); 5965 } 5966 5967 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 5968 EnumDecl *Enum = ET->getDecl(); 5969 5970 // The encoding of an non-fixed enum type is always 'i', regardless of size. 5971 if (!Enum->isFixed()) 5972 return 'i'; 5973 5974 // The encoding of a fixed enum type matches its fixed underlying type. 5975 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>(); 5976 return getObjCEncodingForPrimitiveKind(C, BT->getKind()); 5977 } 5978 5979 static void EncodeBitField(const ASTContext *Ctx, std::string& S, 5980 QualType T, const FieldDecl *FD) { 5981 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 5982 S += 'b'; 5983 // The NeXT runtime encodes bit fields as b followed by the number of bits. 5984 // The GNU runtime requires more information; bitfields are encoded as b, 5985 // then the offset (in bits) of the first element, then the type of the 5986 // bitfield, then the size in bits. For example, in this structure: 5987 // 5988 // struct 5989 // { 5990 // int integer; 5991 // int flags:2; 5992 // }; 5993 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 5994 // runtime, but b32i2 for the GNU runtime. The reason for this extra 5995 // information is not especially sensible, but we're stuck with it for 5996 // compatibility with GCC, although providing it breaks anything that 5997 // actually uses runtime introspection and wants to work on both runtimes... 5998 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 5999 uint64_t Offset; 6000 6001 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) { 6002 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr, 6003 IVD); 6004 } else { 6005 const RecordDecl *RD = FD->getParent(); 6006 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 6007 Offset = RL.getFieldOffset(FD->getFieldIndex()); 6008 } 6009 6010 S += llvm::utostr(Offset); 6011 6012 if (const EnumType *ET = T->getAs<EnumType>()) 6013 S += ObjCEncodingForEnumType(Ctx, ET); 6014 else { 6015 const BuiltinType *BT = T->castAs<BuiltinType>(); 6016 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind()); 6017 } 6018 } 6019 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 6020 } 6021 6022 // FIXME: Use SmallString for accumulating string. 6023 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 6024 bool ExpandPointedToStructures, 6025 bool ExpandStructures, 6026 const FieldDecl *FD, 6027 bool OutermostType, 6028 bool EncodingProperty, 6029 bool StructField, 6030 bool EncodeBlockParameters, 6031 bool EncodeClassNames, 6032 bool EncodePointerToObjCTypedef, 6033 QualType *NotEncodedT) const { 6034 CanQualType CT = getCanonicalType(T); 6035 switch (CT->getTypeClass()) { 6036 case Type::Builtin: 6037 case Type::Enum: 6038 if (FD && FD->isBitField()) 6039 return EncodeBitField(this, S, T, FD); 6040 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT)) 6041 S += getObjCEncodingForPrimitiveKind(this, BT->getKind()); 6042 else 6043 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); 6044 return; 6045 6046 case Type::Complex: { 6047 const ComplexType *CT = T->castAs<ComplexType>(); 6048 S += 'j'; 6049 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr); 6050 return; 6051 } 6052 6053 case Type::Atomic: { 6054 const AtomicType *AT = T->castAs<AtomicType>(); 6055 S += 'A'; 6056 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr); 6057 return; 6058 } 6059 6060 // encoding for pointer or reference types. 6061 case Type::Pointer: 6062 case Type::LValueReference: 6063 case Type::RValueReference: { 6064 QualType PointeeTy; 6065 if (isa<PointerType>(CT)) { 6066 const PointerType *PT = T->castAs<PointerType>(); 6067 if (PT->isObjCSelType()) { 6068 S += ':'; 6069 return; 6070 } 6071 PointeeTy = PT->getPointeeType(); 6072 } else { 6073 PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); 6074 } 6075 6076 bool isReadOnly = false; 6077 // For historical/compatibility reasons, the read-only qualifier of the 6078 // pointee gets emitted _before_ the '^'. The read-only qualifier of 6079 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 6080 // Also, do not emit the 'r' for anything but the outermost type! 6081 if (isa<TypedefType>(T.getTypePtr())) { 6082 if (OutermostType && T.isConstQualified()) { 6083 isReadOnly = true; 6084 S += 'r'; 6085 } 6086 } else if (OutermostType) { 6087 QualType P = PointeeTy; 6088 while (P->getAs<PointerType>()) 6089 P = P->getAs<PointerType>()->getPointeeType(); 6090 if (P.isConstQualified()) { 6091 isReadOnly = true; 6092 S += 'r'; 6093 } 6094 } 6095 if (isReadOnly) { 6096 // Another legacy compatibility encoding. Some ObjC qualifier and type 6097 // combinations need to be rearranged. 6098 // Rewrite "in const" from "nr" to "rn" 6099 if (StringRef(S).endswith("nr")) 6100 S.replace(S.end()-2, S.end(), "rn"); 6101 } 6102 6103 if (PointeeTy->isCharType()) { 6104 // char pointer types should be encoded as '*' unless it is a 6105 // type that has been typedef'd to 'BOOL'. 6106 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 6107 S += '*'; 6108 return; 6109 } 6110 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) { 6111 // GCC binary compat: Need to convert "struct objc_class *" to "#". 6112 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 6113 S += '#'; 6114 return; 6115 } 6116 // GCC binary compat: Need to convert "struct objc_object *" to "@". 6117 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 6118 S += '@'; 6119 return; 6120 } 6121 // fall through... 6122 } 6123 S += '^'; 6124 getLegacyIntegralTypeEncoding(PointeeTy); 6125 6126 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures, 6127 nullptr, false, false, false, false, false, false, 6128 NotEncodedT); 6129 return; 6130 } 6131 6132 case Type::ConstantArray: 6133 case Type::IncompleteArray: 6134 case Type::VariableArray: { 6135 const ArrayType *AT = cast<ArrayType>(CT); 6136 6137 if (isa<IncompleteArrayType>(AT) && !StructField) { 6138 // Incomplete arrays are encoded as a pointer to the array element. 6139 S += '^'; 6140 6141 getObjCEncodingForTypeImpl(AT->getElementType(), S, 6142 false, ExpandStructures, FD); 6143 } else { 6144 S += '['; 6145 6146 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 6147 S += llvm::utostr(CAT->getSize().getZExtValue()); 6148 else { 6149 //Variable length arrays are encoded as a regular array with 0 elements. 6150 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 6151 "Unknown array type!"); 6152 S += '0'; 6153 } 6154 6155 getObjCEncodingForTypeImpl(AT->getElementType(), S, 6156 false, ExpandStructures, FD, 6157 false, false, false, false, false, false, 6158 NotEncodedT); 6159 S += ']'; 6160 } 6161 return; 6162 } 6163 6164 case Type::FunctionNoProto: 6165 case Type::FunctionProto: 6166 S += '?'; 6167 return; 6168 6169 case Type::Record: { 6170 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); 6171 S += RDecl->isUnion() ? '(' : '{'; 6172 // Anonymous structures print as '?' 6173 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 6174 S += II->getName(); 6175 if (ClassTemplateSpecializationDecl *Spec 6176 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 6177 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 6178 llvm::raw_string_ostream OS(S); 6179 TemplateSpecializationType::PrintTemplateArgumentList(OS, 6180 TemplateArgs.asArray(), 6181 (*this).getPrintingPolicy()); 6182 } 6183 } else { 6184 S += '?'; 6185 } 6186 if (ExpandStructures) { 6187 S += '='; 6188 if (!RDecl->isUnion()) { 6189 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); 6190 } else { 6191 for (const auto *Field : RDecl->fields()) { 6192 if (FD) { 6193 S += '"'; 6194 S += Field->getNameAsString(); 6195 S += '"'; 6196 } 6197 6198 // Special case bit-fields. 6199 if (Field->isBitField()) { 6200 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 6201 Field); 6202 } else { 6203 QualType qt = Field->getType(); 6204 getLegacyIntegralTypeEncoding(qt); 6205 getObjCEncodingForTypeImpl(qt, S, false, true, 6206 FD, /*OutermostType*/false, 6207 /*EncodingProperty*/false, 6208 /*StructField*/true, 6209 false, false, false, NotEncodedT); 6210 } 6211 } 6212 } 6213 } 6214 S += RDecl->isUnion() ? ')' : '}'; 6215 return; 6216 } 6217 6218 case Type::BlockPointer: { 6219 const BlockPointerType *BT = T->castAs<BlockPointerType>(); 6220 S += "@?"; // Unlike a pointer-to-function, which is "^?". 6221 if (EncodeBlockParameters) { 6222 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>(); 6223 6224 S += '<'; 6225 // Block return type 6226 getObjCEncodingForTypeImpl( 6227 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures, 6228 FD, false /* OutermostType */, EncodingProperty, 6229 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false, 6230 NotEncodedT); 6231 // Block self 6232 S += "@?"; 6233 // Block parameters 6234 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) { 6235 for (const auto &I : FPT->param_types()) 6236 getObjCEncodingForTypeImpl( 6237 I, S, ExpandPointedToStructures, ExpandStructures, FD, 6238 false /* OutermostType */, EncodingProperty, 6239 false /* StructField */, EncodeBlockParameters, EncodeClassNames, 6240 false, NotEncodedT); 6241 } 6242 S += '>'; 6243 } 6244 return; 6245 } 6246 6247 case Type::ObjCObject: { 6248 // hack to match legacy encoding of *id and *Class 6249 QualType Ty = getObjCObjectPointerType(CT); 6250 if (Ty->isObjCIdType()) { 6251 S += "{objc_object=}"; 6252 return; 6253 } 6254 else if (Ty->isObjCClassType()) { 6255 S += "{objc_class=}"; 6256 return; 6257 } 6258 // TODO: Double check to make sure this intentially falls through. 6259 LLVM_FALLTHROUGH; 6260 } 6261 6262 case Type::ObjCInterface: { 6263 // Ignore protocol qualifiers when mangling at this level. 6264 // @encode(class_name) 6265 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface(); 6266 S += '{'; 6267 S += OI->getObjCRuntimeNameAsString(); 6268 if (ExpandStructures) { 6269 S += '='; 6270 SmallVector<const ObjCIvarDecl*, 32> Ivars; 6271 DeepCollectObjCIvars(OI, true, Ivars); 6272 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 6273 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]); 6274 if (Field->isBitField()) 6275 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field); 6276 else 6277 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD, 6278 false, false, false, false, false, 6279 EncodePointerToObjCTypedef, 6280 NotEncodedT); 6281 } 6282 } 6283 S += '}'; 6284 return; 6285 } 6286 6287 case Type::ObjCObjectPointer: { 6288 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>(); 6289 if (OPT->isObjCIdType()) { 6290 S += '@'; 6291 return; 6292 } 6293 6294 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 6295 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 6296 // Since this is a binary compatibility issue, need to consult with runtime 6297 // folks. Fortunately, this is a *very* obsure construct. 6298 S += '#'; 6299 return; 6300 } 6301 6302 if (OPT->isObjCQualifiedIdType()) { 6303 getObjCEncodingForTypeImpl(getObjCIdType(), S, 6304 ExpandPointedToStructures, 6305 ExpandStructures, FD); 6306 if (FD || EncodingProperty || EncodeClassNames) { 6307 // Note that we do extended encoding of protocol qualifer list 6308 // Only when doing ivar or property encoding. 6309 S += '"'; 6310 for (const auto *I : OPT->quals()) { 6311 S += '<'; 6312 S += I->getObjCRuntimeNameAsString(); 6313 S += '>'; 6314 } 6315 S += '"'; 6316 } 6317 return; 6318 } 6319 6320 QualType PointeeTy = OPT->getPointeeType(); 6321 if (!EncodingProperty && 6322 isa<TypedefType>(PointeeTy.getTypePtr()) && 6323 !EncodePointerToObjCTypedef) { 6324 // Another historical/compatibility reason. 6325 // We encode the underlying type which comes out as 6326 // {...}; 6327 S += '^'; 6328 if (FD && OPT->getInterfaceDecl()) { 6329 // Prevent recursive encoding of fields in some rare cases. 6330 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl(); 6331 SmallVector<const ObjCIvarDecl*, 32> Ivars; 6332 DeepCollectObjCIvars(OI, true, Ivars); 6333 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 6334 if (cast<FieldDecl>(Ivars[i]) == FD) { 6335 S += '{'; 6336 S += OI->getObjCRuntimeNameAsString(); 6337 S += '}'; 6338 return; 6339 } 6340 } 6341 } 6342 getObjCEncodingForTypeImpl(PointeeTy, S, 6343 false, ExpandPointedToStructures, 6344 nullptr, 6345 false, false, false, false, false, 6346 /*EncodePointerToObjCTypedef*/true); 6347 return; 6348 } 6349 6350 S += '@'; 6351 if (OPT->getInterfaceDecl() && 6352 (FD || EncodingProperty || EncodeClassNames)) { 6353 S += '"'; 6354 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString(); 6355 for (const auto *I : OPT->quals()) { 6356 S += '<'; 6357 S += I->getObjCRuntimeNameAsString(); 6358 S += '>'; 6359 } 6360 S += '"'; 6361 } 6362 return; 6363 } 6364 6365 // gcc just blithely ignores member pointers. 6366 // FIXME: we shoul do better than that. 'M' is available. 6367 case Type::MemberPointer: 6368 // This matches gcc's encoding, even though technically it is insufficient. 6369 //FIXME. We should do a better job than gcc. 6370 case Type::Vector: 6371 case Type::ExtVector: 6372 // Until we have a coherent encoding of these three types, issue warning. 6373 { if (NotEncodedT) 6374 *NotEncodedT = T; 6375 return; 6376 } 6377 6378 // We could see an undeduced auto type here during error recovery. 6379 // Just ignore it. 6380 case Type::Auto: 6381 case Type::DeducedTemplateSpecialization: 6382 return; 6383 6384 case Type::Pipe: 6385 #define ABSTRACT_TYPE(KIND, BASE) 6386 #define TYPE(KIND, BASE) 6387 #define DEPENDENT_TYPE(KIND, BASE) \ 6388 case Type::KIND: 6389 #define NON_CANONICAL_TYPE(KIND, BASE) \ 6390 case Type::KIND: 6391 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ 6392 case Type::KIND: 6393 #include "clang/AST/TypeNodes.def" 6394 llvm_unreachable("@encode for dependent type!"); 6395 } 6396 llvm_unreachable("bad type kind!"); 6397 } 6398 6399 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 6400 std::string &S, 6401 const FieldDecl *FD, 6402 bool includeVBases, 6403 QualType *NotEncodedT) const { 6404 assert(RDecl && "Expected non-null RecordDecl"); 6405 assert(!RDecl->isUnion() && "Should not be called for unions"); 6406 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl()) 6407 return; 6408 6409 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 6410 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 6411 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 6412 6413 if (CXXRec) { 6414 for (const auto &BI : CXXRec->bases()) { 6415 if (!BI.isVirtual()) { 6416 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 6417 if (base->isEmpty()) 6418 continue; 6419 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 6420 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 6421 std::make_pair(offs, base)); 6422 } 6423 } 6424 } 6425 6426 unsigned i = 0; 6427 for (auto *Field : RDecl->fields()) { 6428 uint64_t offs = layout.getFieldOffset(i); 6429 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 6430 std::make_pair(offs, Field)); 6431 ++i; 6432 } 6433 6434 if (CXXRec && includeVBases) { 6435 for (const auto &BI : CXXRec->vbases()) { 6436 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 6437 if (base->isEmpty()) 6438 continue; 6439 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 6440 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && 6441 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 6442 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 6443 std::make_pair(offs, base)); 6444 } 6445 } 6446 6447 CharUnits size; 6448 if (CXXRec) { 6449 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 6450 } else { 6451 size = layout.getSize(); 6452 } 6453 6454 #ifndef NDEBUG 6455 uint64_t CurOffs = 0; 6456 #endif 6457 std::multimap<uint64_t, NamedDecl *>::iterator 6458 CurLayObj = FieldOrBaseOffsets.begin(); 6459 6460 if (CXXRec && CXXRec->isDynamicClass() && 6461 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 6462 if (FD) { 6463 S += "\"_vptr$"; 6464 std::string recname = CXXRec->getNameAsString(); 6465 if (recname.empty()) recname = "?"; 6466 S += recname; 6467 S += '"'; 6468 } 6469 S += "^^?"; 6470 #ifndef NDEBUG 6471 CurOffs += getTypeSize(VoidPtrTy); 6472 #endif 6473 } 6474 6475 if (!RDecl->hasFlexibleArrayMember()) { 6476 // Mark the end of the structure. 6477 uint64_t offs = toBits(size); 6478 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 6479 std::make_pair(offs, nullptr)); 6480 } 6481 6482 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 6483 #ifndef NDEBUG 6484 assert(CurOffs <= CurLayObj->first); 6485 if (CurOffs < CurLayObj->first) { 6486 uint64_t padding = CurLayObj->first - CurOffs; 6487 // FIXME: There doesn't seem to be a way to indicate in the encoding that 6488 // packing/alignment of members is different that normal, in which case 6489 // the encoding will be out-of-sync with the real layout. 6490 // If the runtime switches to just consider the size of types without 6491 // taking into account alignment, we could make padding explicit in the 6492 // encoding (e.g. using arrays of chars). The encoding strings would be 6493 // longer then though. 6494 CurOffs += padding; 6495 } 6496 #endif 6497 6498 NamedDecl *dcl = CurLayObj->second; 6499 if (!dcl) 6500 break; // reached end of structure. 6501 6502 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) { 6503 // We expand the bases without their virtual bases since those are going 6504 // in the initial structure. Note that this differs from gcc which 6505 // expands virtual bases each time one is encountered in the hierarchy, 6506 // making the encoding type bigger than it really is. 6507 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, 6508 NotEncodedT); 6509 assert(!base->isEmpty()); 6510 #ifndef NDEBUG 6511 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 6512 #endif 6513 } else { 6514 FieldDecl *field = cast<FieldDecl>(dcl); 6515 if (FD) { 6516 S += '"'; 6517 S += field->getNameAsString(); 6518 S += '"'; 6519 } 6520 6521 if (field->isBitField()) { 6522 EncodeBitField(this, S, field->getType(), field); 6523 #ifndef NDEBUG 6524 CurOffs += field->getBitWidthValue(*this); 6525 #endif 6526 } else { 6527 QualType qt = field->getType(); 6528 getLegacyIntegralTypeEncoding(qt); 6529 getObjCEncodingForTypeImpl(qt, S, false, true, FD, 6530 /*OutermostType*/false, 6531 /*EncodingProperty*/false, 6532 /*StructField*/true, 6533 false, false, false, NotEncodedT); 6534 #ifndef NDEBUG 6535 CurOffs += getTypeSize(field->getType()); 6536 #endif 6537 } 6538 } 6539 } 6540 } 6541 6542 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 6543 std::string& S) const { 6544 if (QT & Decl::OBJC_TQ_In) 6545 S += 'n'; 6546 if (QT & Decl::OBJC_TQ_Inout) 6547 S += 'N'; 6548 if (QT & Decl::OBJC_TQ_Out) 6549 S += 'o'; 6550 if (QT & Decl::OBJC_TQ_Bycopy) 6551 S += 'O'; 6552 if (QT & Decl::OBJC_TQ_Byref) 6553 S += 'R'; 6554 if (QT & Decl::OBJC_TQ_Oneway) 6555 S += 'V'; 6556 } 6557 6558 TypedefDecl *ASTContext::getObjCIdDecl() const { 6559 if (!ObjCIdDecl) { 6560 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { }); 6561 T = getObjCObjectPointerType(T); 6562 ObjCIdDecl = buildImplicitTypedef(T, "id"); 6563 } 6564 return ObjCIdDecl; 6565 } 6566 6567 TypedefDecl *ASTContext::getObjCSelDecl() const { 6568 if (!ObjCSelDecl) { 6569 QualType T = getPointerType(ObjCBuiltinSelTy); 6570 ObjCSelDecl = buildImplicitTypedef(T, "SEL"); 6571 } 6572 return ObjCSelDecl; 6573 } 6574 6575 TypedefDecl *ASTContext::getObjCClassDecl() const { 6576 if (!ObjCClassDecl) { 6577 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { }); 6578 T = getObjCObjectPointerType(T); 6579 ObjCClassDecl = buildImplicitTypedef(T, "Class"); 6580 } 6581 return ObjCClassDecl; 6582 } 6583 6584 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 6585 if (!ObjCProtocolClassDecl) { 6586 ObjCProtocolClassDecl 6587 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 6588 SourceLocation(), 6589 &Idents.get("Protocol"), 6590 /*typeParamList=*/nullptr, 6591 /*PrevDecl=*/nullptr, 6592 SourceLocation(), true); 6593 } 6594 6595 return ObjCProtocolClassDecl; 6596 } 6597 6598 //===----------------------------------------------------------------------===// 6599 // __builtin_va_list Construction Functions 6600 //===----------------------------------------------------------------------===// 6601 6602 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context, 6603 StringRef Name) { 6604 // typedef char* __builtin[_ms]_va_list; 6605 QualType T = Context->getPointerType(Context->CharTy); 6606 return Context->buildImplicitTypedef(T, Name); 6607 } 6608 6609 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) { 6610 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list"); 6611 } 6612 6613 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 6614 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list"); 6615 } 6616 6617 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 6618 // typedef void* __builtin_va_list; 6619 QualType T = Context->getPointerType(Context->VoidTy); 6620 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 6621 } 6622 6623 static TypedefDecl * 6624 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { 6625 // struct __va_list 6626 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); 6627 if (Context->getLangOpts().CPlusPlus) { 6628 // namespace std { struct __va_list { 6629 NamespaceDecl *NS; 6630 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 6631 Context->getTranslationUnitDecl(), 6632 /*Inline*/ false, SourceLocation(), 6633 SourceLocation(), &Context->Idents.get("std"), 6634 /*PrevDecl*/ nullptr); 6635 NS->setImplicit(); 6636 VaListTagDecl->setDeclContext(NS); 6637 } 6638 6639 VaListTagDecl->startDefinition(); 6640 6641 const size_t NumFields = 5; 6642 QualType FieldTypes[NumFields]; 6643 const char *FieldNames[NumFields]; 6644 6645 // void *__stack; 6646 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 6647 FieldNames[0] = "__stack"; 6648 6649 // void *__gr_top; 6650 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 6651 FieldNames[1] = "__gr_top"; 6652 6653 // void *__vr_top; 6654 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 6655 FieldNames[2] = "__vr_top"; 6656 6657 // int __gr_offs; 6658 FieldTypes[3] = Context->IntTy; 6659 FieldNames[3] = "__gr_offs"; 6660 6661 // int __vr_offs; 6662 FieldTypes[4] = Context->IntTy; 6663 FieldNames[4] = "__vr_offs"; 6664 6665 // Create fields 6666 for (unsigned i = 0; i < NumFields; ++i) { 6667 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 6668 VaListTagDecl, 6669 SourceLocation(), 6670 SourceLocation(), 6671 &Context->Idents.get(FieldNames[i]), 6672 FieldTypes[i], /*TInfo=*/nullptr, 6673 /*BitWidth=*/nullptr, 6674 /*Mutable=*/false, 6675 ICIS_NoInit); 6676 Field->setAccess(AS_public); 6677 VaListTagDecl->addDecl(Field); 6678 } 6679 VaListTagDecl->completeDefinition(); 6680 Context->VaListTagDecl = VaListTagDecl; 6681 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 6682 6683 // } __builtin_va_list; 6684 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 6685 } 6686 6687 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 6688 // typedef struct __va_list_tag { 6689 RecordDecl *VaListTagDecl; 6690 6691 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 6692 VaListTagDecl->startDefinition(); 6693 6694 const size_t NumFields = 5; 6695 QualType FieldTypes[NumFields]; 6696 const char *FieldNames[NumFields]; 6697 6698 // unsigned char gpr; 6699 FieldTypes[0] = Context->UnsignedCharTy; 6700 FieldNames[0] = "gpr"; 6701 6702 // unsigned char fpr; 6703 FieldTypes[1] = Context->UnsignedCharTy; 6704 FieldNames[1] = "fpr"; 6705 6706 // unsigned short reserved; 6707 FieldTypes[2] = Context->UnsignedShortTy; 6708 FieldNames[2] = "reserved"; 6709 6710 // void* overflow_arg_area; 6711 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 6712 FieldNames[3] = "overflow_arg_area"; 6713 6714 // void* reg_save_area; 6715 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 6716 FieldNames[4] = "reg_save_area"; 6717 6718 // Create fields 6719 for (unsigned i = 0; i < NumFields; ++i) { 6720 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 6721 SourceLocation(), 6722 SourceLocation(), 6723 &Context->Idents.get(FieldNames[i]), 6724 FieldTypes[i], /*TInfo=*/nullptr, 6725 /*BitWidth=*/nullptr, 6726 /*Mutable=*/false, 6727 ICIS_NoInit); 6728 Field->setAccess(AS_public); 6729 VaListTagDecl->addDecl(Field); 6730 } 6731 VaListTagDecl->completeDefinition(); 6732 Context->VaListTagDecl = VaListTagDecl; 6733 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 6734 6735 // } __va_list_tag; 6736 TypedefDecl *VaListTagTypedefDecl = 6737 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 6738 6739 QualType VaListTagTypedefType = 6740 Context->getTypedefType(VaListTagTypedefDecl); 6741 6742 // typedef __va_list_tag __builtin_va_list[1]; 6743 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 6744 QualType VaListTagArrayType 6745 = Context->getConstantArrayType(VaListTagTypedefType, 6746 Size, ArrayType::Normal, 0); 6747 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 6748 } 6749 6750 static TypedefDecl * 6751 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 6752 // struct __va_list_tag { 6753 RecordDecl *VaListTagDecl; 6754 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 6755 VaListTagDecl->startDefinition(); 6756 6757 const size_t NumFields = 4; 6758 QualType FieldTypes[NumFields]; 6759 const char *FieldNames[NumFields]; 6760 6761 // unsigned gp_offset; 6762 FieldTypes[0] = Context->UnsignedIntTy; 6763 FieldNames[0] = "gp_offset"; 6764 6765 // unsigned fp_offset; 6766 FieldTypes[1] = Context->UnsignedIntTy; 6767 FieldNames[1] = "fp_offset"; 6768 6769 // void* overflow_arg_area; 6770 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 6771 FieldNames[2] = "overflow_arg_area"; 6772 6773 // void* reg_save_area; 6774 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 6775 FieldNames[3] = "reg_save_area"; 6776 6777 // Create fields 6778 for (unsigned i = 0; i < NumFields; ++i) { 6779 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 6780 VaListTagDecl, 6781 SourceLocation(), 6782 SourceLocation(), 6783 &Context->Idents.get(FieldNames[i]), 6784 FieldTypes[i], /*TInfo=*/nullptr, 6785 /*BitWidth=*/nullptr, 6786 /*Mutable=*/false, 6787 ICIS_NoInit); 6788 Field->setAccess(AS_public); 6789 VaListTagDecl->addDecl(Field); 6790 } 6791 VaListTagDecl->completeDefinition(); 6792 Context->VaListTagDecl = VaListTagDecl; 6793 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 6794 6795 // }; 6796 6797 // typedef struct __va_list_tag __builtin_va_list[1]; 6798 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 6799 QualType VaListTagArrayType = 6800 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0); 6801 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 6802 } 6803 6804 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 6805 // typedef int __builtin_va_list[4]; 6806 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 6807 QualType IntArrayType = 6808 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0); 6809 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); 6810 } 6811 6812 static TypedefDecl * 6813 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { 6814 // struct __va_list 6815 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); 6816 if (Context->getLangOpts().CPlusPlus) { 6817 // namespace std { struct __va_list { 6818 NamespaceDecl *NS; 6819 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 6820 Context->getTranslationUnitDecl(), 6821 /*Inline*/false, SourceLocation(), 6822 SourceLocation(), &Context->Idents.get("std"), 6823 /*PrevDecl*/ nullptr); 6824 NS->setImplicit(); 6825 VaListDecl->setDeclContext(NS); 6826 } 6827 6828 VaListDecl->startDefinition(); 6829 6830 // void * __ap; 6831 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 6832 VaListDecl, 6833 SourceLocation(), 6834 SourceLocation(), 6835 &Context->Idents.get("__ap"), 6836 Context->getPointerType(Context->VoidTy), 6837 /*TInfo=*/nullptr, 6838 /*BitWidth=*/nullptr, 6839 /*Mutable=*/false, 6840 ICIS_NoInit); 6841 Field->setAccess(AS_public); 6842 VaListDecl->addDecl(Field); 6843 6844 // }; 6845 VaListDecl->completeDefinition(); 6846 Context->VaListTagDecl = VaListDecl; 6847 6848 // typedef struct __va_list __builtin_va_list; 6849 QualType T = Context->getRecordType(VaListDecl); 6850 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 6851 } 6852 6853 static TypedefDecl * 6854 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { 6855 // struct __va_list_tag { 6856 RecordDecl *VaListTagDecl; 6857 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 6858 VaListTagDecl->startDefinition(); 6859 6860 const size_t NumFields = 4; 6861 QualType FieldTypes[NumFields]; 6862 const char *FieldNames[NumFields]; 6863 6864 // long __gpr; 6865 FieldTypes[0] = Context->LongTy; 6866 FieldNames[0] = "__gpr"; 6867 6868 // long __fpr; 6869 FieldTypes[1] = Context->LongTy; 6870 FieldNames[1] = "__fpr"; 6871 6872 // void *__overflow_arg_area; 6873 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 6874 FieldNames[2] = "__overflow_arg_area"; 6875 6876 // void *__reg_save_area; 6877 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 6878 FieldNames[3] = "__reg_save_area"; 6879 6880 // Create fields 6881 for (unsigned i = 0; i < NumFields; ++i) { 6882 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 6883 VaListTagDecl, 6884 SourceLocation(), 6885 SourceLocation(), 6886 &Context->Idents.get(FieldNames[i]), 6887 FieldTypes[i], /*TInfo=*/nullptr, 6888 /*BitWidth=*/nullptr, 6889 /*Mutable=*/false, 6890 ICIS_NoInit); 6891 Field->setAccess(AS_public); 6892 VaListTagDecl->addDecl(Field); 6893 } 6894 VaListTagDecl->completeDefinition(); 6895 Context->VaListTagDecl = VaListTagDecl; 6896 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 6897 6898 // }; 6899 6900 // typedef __va_list_tag __builtin_va_list[1]; 6901 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 6902 QualType VaListTagArrayType = 6903 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0); 6904 6905 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 6906 } 6907 6908 static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 6909 TargetInfo::BuiltinVaListKind Kind) { 6910 switch (Kind) { 6911 case TargetInfo::CharPtrBuiltinVaList: 6912 return CreateCharPtrBuiltinVaListDecl(Context); 6913 case TargetInfo::VoidPtrBuiltinVaList: 6914 return CreateVoidPtrBuiltinVaListDecl(Context); 6915 case TargetInfo::AArch64ABIBuiltinVaList: 6916 return CreateAArch64ABIBuiltinVaListDecl(Context); 6917 case TargetInfo::PowerABIBuiltinVaList: 6918 return CreatePowerABIBuiltinVaListDecl(Context); 6919 case TargetInfo::X86_64ABIBuiltinVaList: 6920 return CreateX86_64ABIBuiltinVaListDecl(Context); 6921 case TargetInfo::PNaClABIBuiltinVaList: 6922 return CreatePNaClABIBuiltinVaListDecl(Context); 6923 case TargetInfo::AAPCSABIBuiltinVaList: 6924 return CreateAAPCSABIBuiltinVaListDecl(Context); 6925 case TargetInfo::SystemZBuiltinVaList: 6926 return CreateSystemZBuiltinVaListDecl(Context); 6927 } 6928 6929 llvm_unreachable("Unhandled __builtin_va_list type kind"); 6930 } 6931 6932 TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 6933 if (!BuiltinVaListDecl) { 6934 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 6935 assert(BuiltinVaListDecl->isImplicit()); 6936 } 6937 6938 return BuiltinVaListDecl; 6939 } 6940 6941 Decl *ASTContext::getVaListTagDecl() const { 6942 // Force the creation of VaListTagDecl by building the __builtin_va_list 6943 // declaration. 6944 if (!VaListTagDecl) 6945 (void)getBuiltinVaListDecl(); 6946 6947 return VaListTagDecl; 6948 } 6949 6950 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const { 6951 if (!BuiltinMSVaListDecl) 6952 BuiltinMSVaListDecl = CreateMSVaListDecl(this); 6953 6954 return BuiltinMSVaListDecl; 6955 } 6956 6957 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 6958 assert(ObjCConstantStringType.isNull() && 6959 "'NSConstantString' type already set!"); 6960 6961 ObjCConstantStringType = getObjCInterfaceType(Decl); 6962 } 6963 6964 /// \brief Retrieve the template name that corresponds to a non-empty 6965 /// lookup. 6966 TemplateName 6967 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 6968 UnresolvedSetIterator End) const { 6969 unsigned size = End - Begin; 6970 assert(size > 1 && "set is not overloaded!"); 6971 6972 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 6973 size * sizeof(FunctionTemplateDecl*)); 6974 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size); 6975 6976 NamedDecl **Storage = OT->getStorage(); 6977 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 6978 NamedDecl *D = *I; 6979 assert(isa<FunctionTemplateDecl>(D) || 6980 (isa<UsingShadowDecl>(D) && 6981 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 6982 *Storage++ = D; 6983 } 6984 6985 return TemplateName(OT); 6986 } 6987 6988 /// \brief Retrieve the template name that represents a qualified 6989 /// template name such as \c std::vector. 6990 TemplateName 6991 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 6992 bool TemplateKeyword, 6993 TemplateDecl *Template) const { 6994 assert(NNS && "Missing nested-name-specifier in qualified template name"); 6995 6996 // FIXME: Canonicalization? 6997 llvm::FoldingSetNodeID ID; 6998 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 6999 7000 void *InsertPos = nullptr; 7001 QualifiedTemplateName *QTN = 7002 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 7003 if (!QTN) { 7004 QTN = new (*this, alignof(QualifiedTemplateName)) 7005 QualifiedTemplateName(NNS, TemplateKeyword, Template); 7006 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 7007 } 7008 7009 return TemplateName(QTN); 7010 } 7011 7012 /// \brief Retrieve the template name that represents a dependent 7013 /// template name such as \c MetaFun::template apply. 7014 TemplateName 7015 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 7016 const IdentifierInfo *Name) const { 7017 assert((!NNS || NNS->isDependent()) && 7018 "Nested name specifier must be dependent"); 7019 7020 llvm::FoldingSetNodeID ID; 7021 DependentTemplateName::Profile(ID, NNS, Name); 7022 7023 void *InsertPos = nullptr; 7024 DependentTemplateName *QTN = 7025 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 7026 7027 if (QTN) 7028 return TemplateName(QTN); 7029 7030 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 7031 if (CanonNNS == NNS) { 7032 QTN = new (*this, alignof(DependentTemplateName)) 7033 DependentTemplateName(NNS, Name); 7034 } else { 7035 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 7036 QTN = new (*this, alignof(DependentTemplateName)) 7037 DependentTemplateName(NNS, Name, Canon); 7038 DependentTemplateName *CheckQTN = 7039 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 7040 assert(!CheckQTN && "Dependent type name canonicalization broken"); 7041 (void)CheckQTN; 7042 } 7043 7044 DependentTemplateNames.InsertNode(QTN, InsertPos); 7045 return TemplateName(QTN); 7046 } 7047 7048 /// \brief Retrieve the template name that represents a dependent 7049 /// template name such as \c MetaFun::template operator+. 7050 TemplateName 7051 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 7052 OverloadedOperatorKind Operator) const { 7053 assert((!NNS || NNS->isDependent()) && 7054 "Nested name specifier must be dependent"); 7055 7056 llvm::FoldingSetNodeID ID; 7057 DependentTemplateName::Profile(ID, NNS, Operator); 7058 7059 void *InsertPos = nullptr; 7060 DependentTemplateName *QTN 7061 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 7062 7063 if (QTN) 7064 return TemplateName(QTN); 7065 7066 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 7067 if (CanonNNS == NNS) { 7068 QTN = new (*this, alignof(DependentTemplateName)) 7069 DependentTemplateName(NNS, Operator); 7070 } else { 7071 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 7072 QTN = new (*this, alignof(DependentTemplateName)) 7073 DependentTemplateName(NNS, Operator, Canon); 7074 7075 DependentTemplateName *CheckQTN 7076 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 7077 assert(!CheckQTN && "Dependent template name canonicalization broken"); 7078 (void)CheckQTN; 7079 } 7080 7081 DependentTemplateNames.InsertNode(QTN, InsertPos); 7082 return TemplateName(QTN); 7083 } 7084 7085 TemplateName 7086 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 7087 TemplateName replacement) const { 7088 llvm::FoldingSetNodeID ID; 7089 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 7090 7091 void *insertPos = nullptr; 7092 SubstTemplateTemplateParmStorage *subst 7093 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 7094 7095 if (!subst) { 7096 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 7097 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 7098 } 7099 7100 return TemplateName(subst); 7101 } 7102 7103 TemplateName 7104 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 7105 const TemplateArgument &ArgPack) const { 7106 ASTContext &Self = const_cast<ASTContext &>(*this); 7107 llvm::FoldingSetNodeID ID; 7108 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 7109 7110 void *InsertPos = nullptr; 7111 SubstTemplateTemplateParmPackStorage *Subst 7112 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 7113 7114 if (!Subst) { 7115 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 7116 ArgPack.pack_size(), 7117 ArgPack.pack_begin()); 7118 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 7119 } 7120 7121 return TemplateName(Subst); 7122 } 7123 7124 /// getFromTargetType - Given one of the integer types provided by 7125 /// TargetInfo, produce the corresponding type. The unsigned @p Type 7126 /// is actually a value of type @c TargetInfo::IntType. 7127 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 7128 switch (Type) { 7129 case TargetInfo::NoInt: return CanQualType(); 7130 case TargetInfo::SignedChar: return SignedCharTy; 7131 case TargetInfo::UnsignedChar: return UnsignedCharTy; 7132 case TargetInfo::SignedShort: return ShortTy; 7133 case TargetInfo::UnsignedShort: return UnsignedShortTy; 7134 case TargetInfo::SignedInt: return IntTy; 7135 case TargetInfo::UnsignedInt: return UnsignedIntTy; 7136 case TargetInfo::SignedLong: return LongTy; 7137 case TargetInfo::UnsignedLong: return UnsignedLongTy; 7138 case TargetInfo::SignedLongLong: return LongLongTy; 7139 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 7140 } 7141 7142 llvm_unreachable("Unhandled TargetInfo::IntType value"); 7143 } 7144 7145 //===----------------------------------------------------------------------===// 7146 // Type Predicates. 7147 //===----------------------------------------------------------------------===// 7148 7149 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 7150 /// garbage collection attribute. 7151 /// 7152 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 7153 if (getLangOpts().getGC() == LangOptions::NonGC) 7154 return Qualifiers::GCNone; 7155 7156 assert(getLangOpts().ObjC1); 7157 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 7158 7159 // Default behaviour under objective-C's gc is for ObjC pointers 7160 // (or pointers to them) be treated as though they were declared 7161 // as __strong. 7162 if (GCAttrs == Qualifiers::GCNone) { 7163 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 7164 return Qualifiers::Strong; 7165 else if (Ty->isPointerType()) 7166 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType()); 7167 } else { 7168 // It's not valid to set GC attributes on anything that isn't a 7169 // pointer. 7170 #ifndef NDEBUG 7171 QualType CT = Ty->getCanonicalTypeInternal(); 7172 while (const ArrayType *AT = dyn_cast<ArrayType>(CT)) 7173 CT = AT->getElementType(); 7174 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 7175 #endif 7176 } 7177 return GCAttrs; 7178 } 7179 7180 //===----------------------------------------------------------------------===// 7181 // Type Compatibility Testing 7182 //===----------------------------------------------------------------------===// 7183 7184 /// areCompatVectorTypes - Return true if the two specified vector types are 7185 /// compatible. 7186 static bool areCompatVectorTypes(const VectorType *LHS, 7187 const VectorType *RHS) { 7188 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 7189 return LHS->getElementType() == RHS->getElementType() && 7190 LHS->getNumElements() == RHS->getNumElements(); 7191 } 7192 7193 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 7194 QualType SecondVec) { 7195 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 7196 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 7197 7198 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 7199 return true; 7200 7201 // Treat Neon vector types and most AltiVec vector types as if they are the 7202 // equivalent GCC vector types. 7203 const VectorType *First = FirstVec->getAs<VectorType>(); 7204 const VectorType *Second = SecondVec->getAs<VectorType>(); 7205 if (First->getNumElements() == Second->getNumElements() && 7206 hasSameType(First->getElementType(), Second->getElementType()) && 7207 First->getVectorKind() != VectorType::AltiVecPixel && 7208 First->getVectorKind() != VectorType::AltiVecBool && 7209 Second->getVectorKind() != VectorType::AltiVecPixel && 7210 Second->getVectorKind() != VectorType::AltiVecBool) 7211 return true; 7212 7213 return false; 7214 } 7215 7216 //===----------------------------------------------------------------------===// 7217 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 7218 //===----------------------------------------------------------------------===// 7219 7220 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 7221 /// inheritance hierarchy of 'rProto'. 7222 bool 7223 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 7224 ObjCProtocolDecl *rProto) const { 7225 if (declaresSameEntity(lProto, rProto)) 7226 return true; 7227 for (auto *PI : rProto->protocols()) 7228 if (ProtocolCompatibleWithProtocol(lProto, PI)) 7229 return true; 7230 return false; 7231 } 7232 7233 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 7234 /// Class<pr1, ...>. 7235 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs, 7236 QualType rhs) { 7237 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>(); 7238 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 7239 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible"); 7240 7241 for (auto *lhsProto : lhsQID->quals()) { 7242 bool match = false; 7243 for (auto *rhsProto : rhsOPT->quals()) { 7244 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 7245 match = true; 7246 break; 7247 } 7248 } 7249 if (!match) 7250 return false; 7251 } 7252 return true; 7253 } 7254 7255 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 7256 /// ObjCQualifiedIDType. 7257 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, 7258 bool compare) { 7259 // Allow id<P..> and an 'id' or void* type in all cases. 7260 if (lhs->isVoidPointerType() || 7261 lhs->isObjCIdType() || lhs->isObjCClassType()) 7262 return true; 7263 else if (rhs->isVoidPointerType() || 7264 rhs->isObjCIdType() || rhs->isObjCClassType()) 7265 return true; 7266 7267 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) { 7268 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 7269 7270 if (!rhsOPT) return false; 7271 7272 if (rhsOPT->qual_empty()) { 7273 // If the RHS is a unqualified interface pointer "NSString*", 7274 // make sure we check the class hierarchy. 7275 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 7276 for (auto *I : lhsQID->quals()) { 7277 // when comparing an id<P> on lhs with a static type on rhs, 7278 // see if static class implements all of id's protocols, directly or 7279 // through its super class and categories. 7280 if (!rhsID->ClassImplementsProtocol(I, true)) 7281 return false; 7282 } 7283 } 7284 // If there are no qualifiers and no interface, we have an 'id'. 7285 return true; 7286 } 7287 // Both the right and left sides have qualifiers. 7288 for (auto *lhsProto : lhsQID->quals()) { 7289 bool match = false; 7290 7291 // when comparing an id<P> on lhs with a static type on rhs, 7292 // see if static class implements all of id's protocols, directly or 7293 // through its super class and categories. 7294 for (auto *rhsProto : rhsOPT->quals()) { 7295 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 7296 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 7297 match = true; 7298 break; 7299 } 7300 } 7301 // If the RHS is a qualified interface pointer "NSString<P>*", 7302 // make sure we check the class hierarchy. 7303 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 7304 for (auto *I : lhsQID->quals()) { 7305 // when comparing an id<P> on lhs with a static type on rhs, 7306 // see if static class implements all of id's protocols, directly or 7307 // through its super class and categories. 7308 if (rhsID->ClassImplementsProtocol(I, true)) { 7309 match = true; 7310 break; 7311 } 7312 } 7313 } 7314 if (!match) 7315 return false; 7316 } 7317 7318 return true; 7319 } 7320 7321 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType(); 7322 assert(rhsQID && "One of the LHS/RHS should be id<x>"); 7323 7324 if (const ObjCObjectPointerType *lhsOPT = 7325 lhs->getAsObjCInterfacePointerType()) { 7326 // If both the right and left sides have qualifiers. 7327 for (auto *lhsProto : lhsOPT->quals()) { 7328 bool match = false; 7329 7330 // when comparing an id<P> on rhs with a static type on lhs, 7331 // see if static class implements all of id's protocols, directly or 7332 // through its super class and categories. 7333 // First, lhs protocols in the qualifier list must be found, direct 7334 // or indirect in rhs's qualifier list or it is a mismatch. 7335 for (auto *rhsProto : rhsQID->quals()) { 7336 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 7337 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 7338 match = true; 7339 break; 7340 } 7341 } 7342 if (!match) 7343 return false; 7344 } 7345 7346 // Static class's protocols, or its super class or category protocols 7347 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 7348 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) { 7349 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 7350 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 7351 // This is rather dubious but matches gcc's behavior. If lhs has 7352 // no type qualifier and its class has no static protocol(s) 7353 // assume that it is mismatch. 7354 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty()) 7355 return false; 7356 for (auto *lhsProto : LHSInheritedProtocols) { 7357 bool match = false; 7358 for (auto *rhsProto : rhsQID->quals()) { 7359 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 7360 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 7361 match = true; 7362 break; 7363 } 7364 } 7365 if (!match) 7366 return false; 7367 } 7368 } 7369 return true; 7370 } 7371 return false; 7372 } 7373 7374 /// canAssignObjCInterfaces - Return true if the two interface types are 7375 /// compatible for assignment from RHS to LHS. This handles validation of any 7376 /// protocol qualifiers on the LHS or RHS. 7377 /// 7378 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 7379 const ObjCObjectPointerType *RHSOPT) { 7380 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 7381 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 7382 7383 // If either type represents the built-in 'id' or 'Class' types, return true. 7384 if (LHS->isObjCUnqualifiedIdOrClass() || 7385 RHS->isObjCUnqualifiedIdOrClass()) 7386 return true; 7387 7388 // Function object that propagates a successful result or handles 7389 // __kindof types. 7390 auto finish = [&](bool succeeded) -> bool { 7391 if (succeeded) 7392 return true; 7393 7394 if (!RHS->isKindOfType()) 7395 return false; 7396 7397 // Strip off __kindof and protocol qualifiers, then check whether 7398 // we can assign the other way. 7399 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this), 7400 LHSOPT->stripObjCKindOfTypeAndQuals(*this)); 7401 }; 7402 7403 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) { 7404 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 7405 QualType(RHSOPT,0), 7406 false)); 7407 } 7408 7409 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { 7410 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0), 7411 QualType(RHSOPT,0))); 7412 } 7413 7414 // If we have 2 user-defined types, fall into that path. 7415 if (LHS->getInterface() && RHS->getInterface()) { 7416 return finish(canAssignObjCInterfaces(LHS, RHS)); 7417 } 7418 7419 return false; 7420 } 7421 7422 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 7423 /// for providing type-safety for objective-c pointers used to pass/return 7424 /// arguments in block literals. When passed as arguments, passing 'A*' where 7425 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 7426 /// not OK. For the return type, the opposite is not OK. 7427 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 7428 const ObjCObjectPointerType *LHSOPT, 7429 const ObjCObjectPointerType *RHSOPT, 7430 bool BlockReturnType) { 7431 7432 // Function object that propagates a successful result or handles 7433 // __kindof types. 7434 auto finish = [&](bool succeeded) -> bool { 7435 if (succeeded) 7436 return true; 7437 7438 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT; 7439 if (!Expected->isKindOfType()) 7440 return false; 7441 7442 // Strip off __kindof and protocol qualifiers, then check whether 7443 // we can assign the other way. 7444 return canAssignObjCInterfacesInBlockPointer( 7445 RHSOPT->stripObjCKindOfTypeAndQuals(*this), 7446 LHSOPT->stripObjCKindOfTypeAndQuals(*this), 7447 BlockReturnType); 7448 }; 7449 7450 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 7451 return true; 7452 7453 if (LHSOPT->isObjCBuiltinType()) { 7454 return finish(RHSOPT->isObjCBuiltinType() || 7455 RHSOPT->isObjCQualifiedIdType()); 7456 } 7457 7458 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) 7459 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 7460 QualType(RHSOPT,0), 7461 false)); 7462 7463 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 7464 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 7465 if (LHS && RHS) { // We have 2 user-defined types. 7466 if (LHS != RHS) { 7467 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 7468 return finish(BlockReturnType); 7469 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 7470 return finish(!BlockReturnType); 7471 } 7472 else 7473 return true; 7474 } 7475 return false; 7476 } 7477 7478 /// Comparison routine for Objective-C protocols to be used with 7479 /// llvm::array_pod_sort. 7480 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, 7481 ObjCProtocolDecl * const *rhs) { 7482 return (*lhs)->getName().compare((*rhs)->getName()); 7483 7484 } 7485 7486 /// getIntersectionOfProtocols - This routine finds the intersection of set 7487 /// of protocols inherited from two distinct objective-c pointer objects with 7488 /// the given common base. 7489 /// It is used to build composite qualifier list of the composite type of 7490 /// the conditional expression involving two objective-c pointer objects. 7491 static 7492 void getIntersectionOfProtocols(ASTContext &Context, 7493 const ObjCInterfaceDecl *CommonBase, 7494 const ObjCObjectPointerType *LHSOPT, 7495 const ObjCObjectPointerType *RHSOPT, 7496 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { 7497 7498 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 7499 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 7500 assert(LHS->getInterface() && "LHS must have an interface base"); 7501 assert(RHS->getInterface() && "RHS must have an interface base"); 7502 7503 // Add all of the protocols for the LHS. 7504 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet; 7505 7506 // Start with the protocol qualifiers. 7507 for (auto proto : LHS->quals()) { 7508 Context.CollectInheritedProtocols(proto, LHSProtocolSet); 7509 } 7510 7511 // Also add the protocols associated with the LHS interface. 7512 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet); 7513 7514 // Add all of the protocls for the RHS. 7515 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet; 7516 7517 // Start with the protocol qualifiers. 7518 for (auto proto : RHS->quals()) { 7519 Context.CollectInheritedProtocols(proto, RHSProtocolSet); 7520 } 7521 7522 // Also add the protocols associated with the RHS interface. 7523 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet); 7524 7525 // Compute the intersection of the collected protocol sets. 7526 for (auto proto : LHSProtocolSet) { 7527 if (RHSProtocolSet.count(proto)) 7528 IntersectionSet.push_back(proto); 7529 } 7530 7531 // Compute the set of protocols that is implied by either the common type or 7532 // the protocols within the intersection. 7533 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols; 7534 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols); 7535 7536 // Remove any implied protocols from the list of inherited protocols. 7537 if (!ImpliedProtocols.empty()) { 7538 IntersectionSet.erase( 7539 std::remove_if(IntersectionSet.begin(), 7540 IntersectionSet.end(), 7541 [&](ObjCProtocolDecl *proto) -> bool { 7542 return ImpliedProtocols.count(proto) > 0; 7543 }), 7544 IntersectionSet.end()); 7545 } 7546 7547 // Sort the remaining protocols by name. 7548 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(), 7549 compareObjCProtocolsByName); 7550 } 7551 7552 /// Determine whether the first type is a subtype of the second. 7553 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, 7554 QualType rhs) { 7555 // Common case: two object pointers. 7556 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>(); 7557 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 7558 if (lhsOPT && rhsOPT) 7559 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT); 7560 7561 // Two block pointers. 7562 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>(); 7563 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>(); 7564 if (lhsBlock && rhsBlock) 7565 return ctx.typesAreBlockPointerCompatible(lhs, rhs); 7566 7567 // If either is an unqualified 'id' and the other is a block, it's 7568 // acceptable. 7569 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) || 7570 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock)) 7571 return true; 7572 7573 return false; 7574 } 7575 7576 // Check that the given Objective-C type argument lists are equivalent. 7577 static bool sameObjCTypeArgs(ASTContext &ctx, 7578 const ObjCInterfaceDecl *iface, 7579 ArrayRef<QualType> lhsArgs, 7580 ArrayRef<QualType> rhsArgs, 7581 bool stripKindOf) { 7582 if (lhsArgs.size() != rhsArgs.size()) 7583 return false; 7584 7585 ObjCTypeParamList *typeParams = iface->getTypeParamList(); 7586 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) { 7587 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i])) 7588 continue; 7589 7590 switch (typeParams->begin()[i]->getVariance()) { 7591 case ObjCTypeParamVariance::Invariant: 7592 if (!stripKindOf || 7593 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx), 7594 rhsArgs[i].stripObjCKindOfType(ctx))) { 7595 return false; 7596 } 7597 break; 7598 7599 case ObjCTypeParamVariance::Covariant: 7600 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i])) 7601 return false; 7602 break; 7603 7604 case ObjCTypeParamVariance::Contravariant: 7605 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i])) 7606 return false; 7607 break; 7608 } 7609 } 7610 7611 return true; 7612 } 7613 7614 QualType ASTContext::areCommonBaseCompatible( 7615 const ObjCObjectPointerType *Lptr, 7616 const ObjCObjectPointerType *Rptr) { 7617 const ObjCObjectType *LHS = Lptr->getObjectType(); 7618 const ObjCObjectType *RHS = Rptr->getObjectType(); 7619 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 7620 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 7621 7622 if (!LDecl || !RDecl) 7623 return QualType(); 7624 7625 // When either LHS or RHS is a kindof type, we should return a kindof type. 7626 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return 7627 // kindof(A). 7628 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType(); 7629 7630 // Follow the left-hand side up the class hierarchy until we either hit a 7631 // root or find the RHS. Record the ancestors in case we don't find it. 7632 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4> 7633 LHSAncestors; 7634 while (true) { 7635 // Record this ancestor. We'll need this if the common type isn't in the 7636 // path from the LHS to the root. 7637 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS; 7638 7639 if (declaresSameEntity(LHS->getInterface(), RDecl)) { 7640 // Get the type arguments. 7641 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten(); 7642 bool anyChanges = false; 7643 if (LHS->isSpecialized() && RHS->isSpecialized()) { 7644 // Both have type arguments, compare them. 7645 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 7646 LHS->getTypeArgs(), RHS->getTypeArgs(), 7647 /*stripKindOf=*/true)) 7648 return QualType(); 7649 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 7650 // If only one has type arguments, the result will not have type 7651 // arguments. 7652 LHSTypeArgs = { }; 7653 anyChanges = true; 7654 } 7655 7656 // Compute the intersection of protocols. 7657 SmallVector<ObjCProtocolDecl *, 8> Protocols; 7658 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr, 7659 Protocols); 7660 if (!Protocols.empty()) 7661 anyChanges = true; 7662 7663 // If anything in the LHS will have changed, build a new result type. 7664 // If we need to return a kindof type but LHS is not a kindof type, we 7665 // build a new result type. 7666 if (anyChanges || LHS->isKindOfType() != anyKindOf) { 7667 QualType Result = getObjCInterfaceType(LHS->getInterface()); 7668 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols, 7669 anyKindOf || LHS->isKindOfType()); 7670 return getObjCObjectPointerType(Result); 7671 } 7672 7673 return getObjCObjectPointerType(QualType(LHS, 0)); 7674 } 7675 7676 // Find the superclass. 7677 QualType LHSSuperType = LHS->getSuperClassType(); 7678 if (LHSSuperType.isNull()) 7679 break; 7680 7681 LHS = LHSSuperType->castAs<ObjCObjectType>(); 7682 } 7683 7684 // We didn't find anything by following the LHS to its root; now check 7685 // the RHS against the cached set of ancestors. 7686 while (true) { 7687 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl()); 7688 if (KnownLHS != LHSAncestors.end()) { 7689 LHS = KnownLHS->second; 7690 7691 // Get the type arguments. 7692 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten(); 7693 bool anyChanges = false; 7694 if (LHS->isSpecialized() && RHS->isSpecialized()) { 7695 // Both have type arguments, compare them. 7696 if (!sameObjCTypeArgs(*this, LHS->getInterface(), 7697 LHS->getTypeArgs(), RHS->getTypeArgs(), 7698 /*stripKindOf=*/true)) 7699 return QualType(); 7700 } else if (LHS->isSpecialized() != RHS->isSpecialized()) { 7701 // If only one has type arguments, the result will not have type 7702 // arguments. 7703 RHSTypeArgs = { }; 7704 anyChanges = true; 7705 } 7706 7707 // Compute the intersection of protocols. 7708 SmallVector<ObjCProtocolDecl *, 8> Protocols; 7709 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr, 7710 Protocols); 7711 if (!Protocols.empty()) 7712 anyChanges = true; 7713 7714 // If we need to return a kindof type but RHS is not a kindof type, we 7715 // build a new result type. 7716 if (anyChanges || RHS->isKindOfType() != anyKindOf) { 7717 QualType Result = getObjCInterfaceType(RHS->getInterface()); 7718 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols, 7719 anyKindOf || RHS->isKindOfType()); 7720 return getObjCObjectPointerType(Result); 7721 } 7722 7723 return getObjCObjectPointerType(QualType(RHS, 0)); 7724 } 7725 7726 // Find the superclass of the RHS. 7727 QualType RHSSuperType = RHS->getSuperClassType(); 7728 if (RHSSuperType.isNull()) 7729 break; 7730 7731 RHS = RHSSuperType->castAs<ObjCObjectType>(); 7732 } 7733 7734 return QualType(); 7735 } 7736 7737 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 7738 const ObjCObjectType *RHS) { 7739 assert(LHS->getInterface() && "LHS is not an interface type"); 7740 assert(RHS->getInterface() && "RHS is not an interface type"); 7741 7742 // Verify that the base decls are compatible: the RHS must be a subclass of 7743 // the LHS. 7744 ObjCInterfaceDecl *LHSInterface = LHS->getInterface(); 7745 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface()); 7746 if (!IsSuperClass) 7747 return false; 7748 7749 // If the LHS has protocol qualifiers, determine whether all of them are 7750 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the 7751 // LHS). 7752 if (LHS->getNumProtocols() > 0) { 7753 // OK if conversion of LHS to SuperClass results in narrowing of types 7754 // ; i.e., SuperClass may implement at least one of the protocols 7755 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 7756 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 7757 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 7758 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 7759 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's 7760 // qualifiers. 7761 for (auto *RHSPI : RHS->quals()) 7762 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols); 7763 // If there is no protocols associated with RHS, it is not a match. 7764 if (SuperClassInheritedProtocols.empty()) 7765 return false; 7766 7767 for (const auto *LHSProto : LHS->quals()) { 7768 bool SuperImplementsProtocol = false; 7769 for (auto *SuperClassProto : SuperClassInheritedProtocols) 7770 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 7771 SuperImplementsProtocol = true; 7772 break; 7773 } 7774 if (!SuperImplementsProtocol) 7775 return false; 7776 } 7777 } 7778 7779 // If the LHS is specialized, we may need to check type arguments. 7780 if (LHS->isSpecialized()) { 7781 // Follow the superclass chain until we've matched the LHS class in the 7782 // hierarchy. This substitutes type arguments through. 7783 const ObjCObjectType *RHSSuper = RHS; 7784 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface)) 7785 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>(); 7786 7787 // If the RHS is specializd, compare type arguments. 7788 if (RHSSuper->isSpecialized() && 7789 !sameObjCTypeArgs(*this, LHS->getInterface(), 7790 LHS->getTypeArgs(), RHSSuper->getTypeArgs(), 7791 /*stripKindOf=*/true)) { 7792 return false; 7793 } 7794 } 7795 7796 return true; 7797 } 7798 7799 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 7800 // get the "pointed to" types 7801 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 7802 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 7803 7804 if (!LHSOPT || !RHSOPT) 7805 return false; 7806 7807 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 7808 canAssignObjCInterfaces(RHSOPT, LHSOPT); 7809 } 7810 7811 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 7812 return canAssignObjCInterfaces( 7813 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(), 7814 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>()); 7815 } 7816 7817 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 7818 /// both shall have the identically qualified version of a compatible type. 7819 /// C99 6.2.7p1: Two types have compatible types if their types are the 7820 /// same. See 6.7.[2,3,5] for additional rules. 7821 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 7822 bool CompareUnqualified) { 7823 if (getLangOpts().CPlusPlus) 7824 return hasSameType(LHS, RHS); 7825 7826 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 7827 } 7828 7829 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 7830 return typesAreCompatible(LHS, RHS); 7831 } 7832 7833 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 7834 return !mergeTypes(LHS, RHS, true).isNull(); 7835 } 7836 7837 /// mergeTransparentUnionType - if T is a transparent union type and a member 7838 /// of T is compatible with SubType, return the merged type, else return 7839 /// QualType() 7840 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 7841 bool OfBlockPointer, 7842 bool Unqualified) { 7843 if (const RecordType *UT = T->getAsUnionType()) { 7844 RecordDecl *UD = UT->getDecl(); 7845 if (UD->hasAttr<TransparentUnionAttr>()) { 7846 for (const auto *I : UD->fields()) { 7847 QualType ET = I->getType().getUnqualifiedType(); 7848 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 7849 if (!MT.isNull()) 7850 return MT; 7851 } 7852 } 7853 } 7854 7855 return QualType(); 7856 } 7857 7858 /// mergeFunctionParameterTypes - merge two types which appear as function 7859 /// parameter types 7860 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 7861 bool OfBlockPointer, 7862 bool Unqualified) { 7863 // GNU extension: two types are compatible if they appear as a function 7864 // argument, one of the types is a transparent union type and the other 7865 // type is compatible with a union member 7866 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 7867 Unqualified); 7868 if (!lmerge.isNull()) 7869 return lmerge; 7870 7871 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 7872 Unqualified); 7873 if (!rmerge.isNull()) 7874 return rmerge; 7875 7876 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 7877 } 7878 7879 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 7880 bool OfBlockPointer, 7881 bool Unqualified) { 7882 const FunctionType *lbase = lhs->getAs<FunctionType>(); 7883 const FunctionType *rbase = rhs->getAs<FunctionType>(); 7884 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase); 7885 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase); 7886 bool allLTypes = true; 7887 bool allRTypes = true; 7888 7889 // Check return type 7890 QualType retType; 7891 if (OfBlockPointer) { 7892 QualType RHS = rbase->getReturnType(); 7893 QualType LHS = lbase->getReturnType(); 7894 bool UnqualifiedResult = Unqualified; 7895 if (!UnqualifiedResult) 7896 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 7897 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 7898 } 7899 else 7900 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 7901 Unqualified); 7902 if (retType.isNull()) return QualType(); 7903 7904 if (Unqualified) 7905 retType = retType.getUnqualifiedType(); 7906 7907 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 7908 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 7909 if (Unqualified) { 7910 LRetType = LRetType.getUnqualifiedType(); 7911 RRetType = RRetType.getUnqualifiedType(); 7912 } 7913 7914 if (getCanonicalType(retType) != LRetType) 7915 allLTypes = false; 7916 if (getCanonicalType(retType) != RRetType) 7917 allRTypes = false; 7918 7919 // FIXME: double check this 7920 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 7921 // rbase->getRegParmAttr() != 0 && 7922 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 7923 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 7924 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 7925 7926 // Compatible functions must have compatible calling conventions 7927 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 7928 return QualType(); 7929 7930 // Regparm is part of the calling convention. 7931 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 7932 return QualType(); 7933 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 7934 return QualType(); 7935 7936 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 7937 return QualType(); 7938 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs()) 7939 return QualType(); 7940 7941 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 7942 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 7943 7944 if (lbaseInfo.getNoReturn() != NoReturn) 7945 allLTypes = false; 7946 if (rbaseInfo.getNoReturn() != NoReturn) 7947 allRTypes = false; 7948 7949 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 7950 7951 if (lproto && rproto) { // two C99 style function prototypes 7952 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() && 7953 "C++ shouldn't be here"); 7954 // Compatible functions must have the same number of parameters 7955 if (lproto->getNumParams() != rproto->getNumParams()) 7956 return QualType(); 7957 7958 // Variadic and non-variadic functions aren't compatible 7959 if (lproto->isVariadic() != rproto->isVariadic()) 7960 return QualType(); 7961 7962 if (lproto->getTypeQuals() != rproto->getTypeQuals()) 7963 return QualType(); 7964 7965 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto)) 7966 return QualType(); 7967 7968 // Check parameter type compatibility 7969 SmallVector<QualType, 10> types; 7970 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 7971 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 7972 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 7973 QualType paramType = mergeFunctionParameterTypes( 7974 lParamType, rParamType, OfBlockPointer, Unqualified); 7975 if (paramType.isNull()) 7976 return QualType(); 7977 7978 if (Unqualified) 7979 paramType = paramType.getUnqualifiedType(); 7980 7981 types.push_back(paramType); 7982 if (Unqualified) { 7983 lParamType = lParamType.getUnqualifiedType(); 7984 rParamType = rParamType.getUnqualifiedType(); 7985 } 7986 7987 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 7988 allLTypes = false; 7989 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 7990 allRTypes = false; 7991 } 7992 7993 if (allLTypes) return lhs; 7994 if (allRTypes) return rhs; 7995 7996 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 7997 EPI.ExtInfo = einfo; 7998 return getFunctionType(retType, types, EPI); 7999 } 8000 8001 if (lproto) allRTypes = false; 8002 if (rproto) allLTypes = false; 8003 8004 const FunctionProtoType *proto = lproto ? lproto : rproto; 8005 if (proto) { 8006 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here"); 8007 if (proto->isVariadic()) return QualType(); 8008 // Check that the types are compatible with the types that 8009 // would result from default argument promotions (C99 6.7.5.3p15). 8010 // The only types actually affected are promotable integer 8011 // types and floats, which would be passed as a different 8012 // type depending on whether the prototype is visible. 8013 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 8014 QualType paramTy = proto->getParamType(i); 8015 8016 // Look at the converted type of enum types, since that is the type used 8017 // to pass enum values. 8018 if (const EnumType *Enum = paramTy->getAs<EnumType>()) { 8019 paramTy = Enum->getDecl()->getIntegerType(); 8020 if (paramTy.isNull()) 8021 return QualType(); 8022 } 8023 8024 if (paramTy->isPromotableIntegerType() || 8025 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 8026 return QualType(); 8027 } 8028 8029 if (allLTypes) return lhs; 8030 if (allRTypes) return rhs; 8031 8032 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 8033 EPI.ExtInfo = einfo; 8034 return getFunctionType(retType, proto->getParamTypes(), EPI); 8035 } 8036 8037 if (allLTypes) return lhs; 8038 if (allRTypes) return rhs; 8039 return getFunctionNoProtoType(retType, einfo); 8040 } 8041 8042 /// Given that we have an enum type and a non-enum type, try to merge them. 8043 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 8044 QualType other, bool isBlockReturnType) { 8045 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 8046 // a signed integer type, or an unsigned integer type. 8047 // Compatibility is based on the underlying type, not the promotion 8048 // type. 8049 QualType underlyingType = ET->getDecl()->getIntegerType(); 8050 if (underlyingType.isNull()) return QualType(); 8051 if (Context.hasSameType(underlyingType, other)) 8052 return other; 8053 8054 // In block return types, we're more permissive and accept any 8055 // integral type of the same size. 8056 if (isBlockReturnType && other->isIntegerType() && 8057 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 8058 return other; 8059 8060 return QualType(); 8061 } 8062 8063 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 8064 bool OfBlockPointer, 8065 bool Unqualified, bool BlockReturnType) { 8066 // C++ [expr]: If an expression initially has the type "reference to T", the 8067 // type is adjusted to "T" prior to any further analysis, the expression 8068 // designates the object or function denoted by the reference, and the 8069 // expression is an lvalue unless the reference is an rvalue reference and 8070 // the expression is a function call (possibly inside parentheses). 8071 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?"); 8072 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?"); 8073 8074 if (Unqualified) { 8075 LHS = LHS.getUnqualifiedType(); 8076 RHS = RHS.getUnqualifiedType(); 8077 } 8078 8079 QualType LHSCan = getCanonicalType(LHS), 8080 RHSCan = getCanonicalType(RHS); 8081 8082 // If two types are identical, they are compatible. 8083 if (LHSCan == RHSCan) 8084 return LHS; 8085 8086 // If the qualifiers are different, the types aren't compatible... mostly. 8087 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 8088 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 8089 if (LQuals != RQuals) { 8090 // If any of these qualifiers are different, we have a type 8091 // mismatch. 8092 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 8093 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 8094 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() || 8095 LQuals.hasUnaligned() != RQuals.hasUnaligned()) 8096 return QualType(); 8097 8098 // Exactly one GC qualifier difference is allowed: __strong is 8099 // okay if the other type has no GC qualifier but is an Objective 8100 // C object pointer (i.e. implicitly strong by default). We fix 8101 // this by pretending that the unqualified type was actually 8102 // qualified __strong. 8103 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 8104 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 8105 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 8106 8107 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 8108 return QualType(); 8109 8110 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 8111 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 8112 } 8113 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 8114 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 8115 } 8116 return QualType(); 8117 } 8118 8119 // Okay, qualifiers are equal. 8120 8121 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 8122 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 8123 8124 // We want to consider the two function types to be the same for these 8125 // comparisons, just force one to the other. 8126 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 8127 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 8128 8129 // Same as above for arrays 8130 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 8131 LHSClass = Type::ConstantArray; 8132 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 8133 RHSClass = Type::ConstantArray; 8134 8135 // ObjCInterfaces are just specialized ObjCObjects. 8136 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 8137 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 8138 8139 // Canonicalize ExtVector -> Vector. 8140 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 8141 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 8142 8143 // If the canonical type classes don't match. 8144 if (LHSClass != RHSClass) { 8145 // Note that we only have special rules for turning block enum 8146 // returns into block int returns, not vice-versa. 8147 if (const EnumType* ETy = LHS->getAs<EnumType>()) { 8148 return mergeEnumWithInteger(*this, ETy, RHS, false); 8149 } 8150 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 8151 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 8152 } 8153 // allow block pointer type to match an 'id' type. 8154 if (OfBlockPointer && !BlockReturnType) { 8155 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 8156 return LHS; 8157 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 8158 return RHS; 8159 } 8160 8161 return QualType(); 8162 } 8163 8164 // The canonical type classes match. 8165 switch (LHSClass) { 8166 #define TYPE(Class, Base) 8167 #define ABSTRACT_TYPE(Class, Base) 8168 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 8169 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 8170 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 8171 #include "clang/AST/TypeNodes.def" 8172 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 8173 8174 case Type::Auto: 8175 case Type::DeducedTemplateSpecialization: 8176 case Type::LValueReference: 8177 case Type::RValueReference: 8178 case Type::MemberPointer: 8179 llvm_unreachable("C++ should never be in mergeTypes"); 8180 8181 case Type::ObjCInterface: 8182 case Type::IncompleteArray: 8183 case Type::VariableArray: 8184 case Type::FunctionProto: 8185 case Type::ExtVector: 8186 llvm_unreachable("Types are eliminated above"); 8187 8188 case Type::Pointer: 8189 { 8190 // Merge two pointer types, while trying to preserve typedef info 8191 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType(); 8192 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType(); 8193 if (Unqualified) { 8194 LHSPointee = LHSPointee.getUnqualifiedType(); 8195 RHSPointee = RHSPointee.getUnqualifiedType(); 8196 } 8197 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 8198 Unqualified); 8199 if (ResultType.isNull()) return QualType(); 8200 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 8201 return LHS; 8202 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 8203 return RHS; 8204 return getPointerType(ResultType); 8205 } 8206 case Type::BlockPointer: 8207 { 8208 // Merge two block pointer types, while trying to preserve typedef info 8209 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType(); 8210 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType(); 8211 if (Unqualified) { 8212 LHSPointee = LHSPointee.getUnqualifiedType(); 8213 RHSPointee = RHSPointee.getUnqualifiedType(); 8214 } 8215 if (getLangOpts().OpenCL) { 8216 Qualifiers LHSPteeQual = LHSPointee.getQualifiers(); 8217 Qualifiers RHSPteeQual = RHSPointee.getQualifiers(); 8218 // Blocks can't be an expression in a ternary operator (OpenCL v2.0 8219 // 6.12.5) thus the following check is asymmetric. 8220 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual)) 8221 return QualType(); 8222 LHSPteeQual.removeAddressSpace(); 8223 RHSPteeQual.removeAddressSpace(); 8224 LHSPointee = 8225 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue()); 8226 RHSPointee = 8227 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue()); 8228 } 8229 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 8230 Unqualified); 8231 if (ResultType.isNull()) return QualType(); 8232 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 8233 return LHS; 8234 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 8235 return RHS; 8236 return getBlockPointerType(ResultType); 8237 } 8238 case Type::Atomic: 8239 { 8240 // Merge two pointer types, while trying to preserve typedef info 8241 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType(); 8242 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType(); 8243 if (Unqualified) { 8244 LHSValue = LHSValue.getUnqualifiedType(); 8245 RHSValue = RHSValue.getUnqualifiedType(); 8246 } 8247 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 8248 Unqualified); 8249 if (ResultType.isNull()) return QualType(); 8250 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 8251 return LHS; 8252 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 8253 return RHS; 8254 return getAtomicType(ResultType); 8255 } 8256 case Type::ConstantArray: 8257 { 8258 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 8259 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 8260 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 8261 return QualType(); 8262 8263 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 8264 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 8265 if (Unqualified) { 8266 LHSElem = LHSElem.getUnqualifiedType(); 8267 RHSElem = RHSElem.getUnqualifiedType(); 8268 } 8269 8270 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 8271 if (ResultType.isNull()) return QualType(); 8272 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 8273 return LHS; 8274 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 8275 return RHS; 8276 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), 8277 ArrayType::ArraySizeModifier(), 0); 8278 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), 8279 ArrayType::ArraySizeModifier(), 0); 8280 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 8281 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 8282 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 8283 return LHS; 8284 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 8285 return RHS; 8286 if (LVAT) { 8287 // FIXME: This isn't correct! But tricky to implement because 8288 // the array's size has to be the size of LHS, but the type 8289 // has to be different. 8290 return LHS; 8291 } 8292 if (RVAT) { 8293 // FIXME: This isn't correct! But tricky to implement because 8294 // the array's size has to be the size of RHS, but the type 8295 // has to be different. 8296 return RHS; 8297 } 8298 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 8299 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 8300 return getIncompleteArrayType(ResultType, 8301 ArrayType::ArraySizeModifier(), 0); 8302 } 8303 case Type::FunctionNoProto: 8304 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 8305 case Type::Record: 8306 case Type::Enum: 8307 return QualType(); 8308 case Type::Builtin: 8309 // Only exactly equal builtin types are compatible, which is tested above. 8310 return QualType(); 8311 case Type::Complex: 8312 // Distinct complex types are incompatible. 8313 return QualType(); 8314 case Type::Vector: 8315 // FIXME: The merged type should be an ExtVector! 8316 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(), 8317 RHSCan->getAs<VectorType>())) 8318 return LHS; 8319 return QualType(); 8320 case Type::ObjCObject: { 8321 // Check if the types are assignment compatible. 8322 // FIXME: This should be type compatibility, e.g. whether 8323 // "LHS x; RHS x;" at global scope is legal. 8324 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>(); 8325 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>(); 8326 if (canAssignObjCInterfaces(LHSIface, RHSIface)) 8327 return LHS; 8328 8329 return QualType(); 8330 } 8331 case Type::ObjCObjectPointer: { 8332 if (OfBlockPointer) { 8333 if (canAssignObjCInterfacesInBlockPointer( 8334 LHS->getAs<ObjCObjectPointerType>(), 8335 RHS->getAs<ObjCObjectPointerType>(), 8336 BlockReturnType)) 8337 return LHS; 8338 return QualType(); 8339 } 8340 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(), 8341 RHS->getAs<ObjCObjectPointerType>())) 8342 return LHS; 8343 8344 return QualType(); 8345 } 8346 case Type::Pipe: 8347 { 8348 assert(LHS != RHS && 8349 "Equivalent pipe types should have already been handled!"); 8350 return QualType(); 8351 } 8352 } 8353 8354 llvm_unreachable("Invalid Type::Class!"); 8355 } 8356 8357 bool ASTContext::doFunctionTypesMatchOnExtParameterInfos( 8358 const FunctionProtoType *firstFnType, 8359 const FunctionProtoType *secondFnType) { 8360 // Fast path: if the first type doesn't have ext parameter infos, 8361 // we match if and only if they second type also doesn't have them. 8362 if (!firstFnType->hasExtParameterInfos()) 8363 return !secondFnType->hasExtParameterInfos(); 8364 8365 // Otherwise, we can only match if the second type has them. 8366 if (!secondFnType->hasExtParameterInfos()) 8367 return false; 8368 8369 auto firstEPI = firstFnType->getExtParameterInfos(); 8370 auto secondEPI = secondFnType->getExtParameterInfos(); 8371 assert(firstEPI.size() == secondEPI.size()); 8372 8373 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) { 8374 if (firstEPI[i] != secondEPI[i]) 8375 return false; 8376 } 8377 return true; 8378 } 8379 8380 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) { 8381 ObjCLayouts[CD] = nullptr; 8382 } 8383 8384 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 8385 /// 'RHS' attributes and returns the merged version; including for function 8386 /// return types. 8387 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 8388 QualType LHSCan = getCanonicalType(LHS), 8389 RHSCan = getCanonicalType(RHS); 8390 // If two types are identical, they are compatible. 8391 if (LHSCan == RHSCan) 8392 return LHS; 8393 if (RHSCan->isFunctionType()) { 8394 if (!LHSCan->isFunctionType()) 8395 return QualType(); 8396 QualType OldReturnType = 8397 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 8398 QualType NewReturnType = 8399 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 8400 QualType ResReturnType = 8401 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 8402 if (ResReturnType.isNull()) 8403 return QualType(); 8404 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 8405 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 8406 // In either case, use OldReturnType to build the new function type. 8407 const FunctionType *F = LHS->getAs<FunctionType>(); 8408 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) { 8409 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8410 EPI.ExtInfo = getFunctionExtInfo(LHS); 8411 QualType ResultType = 8412 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 8413 return ResultType; 8414 } 8415 } 8416 return QualType(); 8417 } 8418 8419 // If the qualifiers are different, the types can still be merged. 8420 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 8421 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 8422 if (LQuals != RQuals) { 8423 // If any of these qualifiers are different, we have a type mismatch. 8424 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 8425 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 8426 return QualType(); 8427 8428 // Exactly one GC qualifier difference is allowed: __strong is 8429 // okay if the other type has no GC qualifier but is an Objective 8430 // C object pointer (i.e. implicitly strong by default). We fix 8431 // this by pretending that the unqualified type was actually 8432 // qualified __strong. 8433 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 8434 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 8435 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 8436 8437 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 8438 return QualType(); 8439 8440 if (GC_L == Qualifiers::Strong) 8441 return LHS; 8442 if (GC_R == Qualifiers::Strong) 8443 return RHS; 8444 return QualType(); 8445 } 8446 8447 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 8448 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 8449 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 8450 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 8451 if (ResQT == LHSBaseQT) 8452 return LHS; 8453 if (ResQT == RHSBaseQT) 8454 return RHS; 8455 } 8456 return QualType(); 8457 } 8458 8459 //===----------------------------------------------------------------------===// 8460 // Integer Predicates 8461 //===----------------------------------------------------------------------===// 8462 8463 unsigned ASTContext::getIntWidth(QualType T) const { 8464 if (const EnumType *ET = T->getAs<EnumType>()) 8465 T = ET->getDecl()->getIntegerType(); 8466 if (T->isBooleanType()) 8467 return 1; 8468 // For builtin types, just use the standard type sizing method 8469 return (unsigned)getTypeSize(T); 8470 } 8471 8472 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 8473 assert(T->hasSignedIntegerRepresentation() && "Unexpected type"); 8474 8475 // Turn <4 x signed int> -> <4 x unsigned int> 8476 if (const VectorType *VTy = T->getAs<VectorType>()) 8477 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 8478 VTy->getNumElements(), VTy->getVectorKind()); 8479 8480 // For enums, we return the unsigned version of the base type. 8481 if (const EnumType *ETy = T->getAs<EnumType>()) 8482 T = ETy->getDecl()->getIntegerType(); 8483 8484 const BuiltinType *BTy = T->getAs<BuiltinType>(); 8485 assert(BTy && "Unexpected signed integer type"); 8486 switch (BTy->getKind()) { 8487 case BuiltinType::Char_S: 8488 case BuiltinType::SChar: 8489 return UnsignedCharTy; 8490 case BuiltinType::Short: 8491 return UnsignedShortTy; 8492 case BuiltinType::Int: 8493 return UnsignedIntTy; 8494 case BuiltinType::Long: 8495 return UnsignedLongTy; 8496 case BuiltinType::LongLong: 8497 return UnsignedLongLongTy; 8498 case BuiltinType::Int128: 8499 return UnsignedInt128Ty; 8500 default: 8501 llvm_unreachable("Unexpected signed integer type"); 8502 } 8503 } 8504 8505 ASTMutationListener::~ASTMutationListener() { } 8506 8507 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 8508 QualType ReturnType) {} 8509 8510 //===----------------------------------------------------------------------===// 8511 // Builtin Type Computation 8512 //===----------------------------------------------------------------------===// 8513 8514 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 8515 /// pointer over the consumed characters. This returns the resultant type. If 8516 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic 8517 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 8518 /// a vector of "i*". 8519 /// 8520 /// RequiresICE is filled in on return to indicate whether the value is required 8521 /// to be an Integer Constant Expression. 8522 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 8523 ASTContext::GetBuiltinTypeError &Error, 8524 bool &RequiresICE, 8525 bool AllowTypeModifiers) { 8526 // Modifiers. 8527 int HowLong = 0; 8528 bool Signed = false, Unsigned = false; 8529 RequiresICE = false; 8530 8531 // Read the prefixed modifiers first. 8532 bool Done = false; 8533 #ifndef NDEBUG 8534 bool IsSpecialLong = false; 8535 #endif 8536 while (!Done) { 8537 switch (*Str++) { 8538 default: Done = true; --Str; break; 8539 case 'I': 8540 RequiresICE = true; 8541 break; 8542 case 'S': 8543 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 8544 assert(!Signed && "Can't use 'S' modifier multiple times!"); 8545 Signed = true; 8546 break; 8547 case 'U': 8548 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 8549 assert(!Unsigned && "Can't use 'U' modifier multiple times!"); 8550 Unsigned = true; 8551 break; 8552 case 'L': 8553 assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers"); 8554 assert(HowLong <= 2 && "Can't have LLLL modifier"); 8555 ++HowLong; 8556 break; 8557 case 'N': { 8558 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise. 8559 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!"); 8560 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!"); 8561 #ifndef NDEBUG 8562 IsSpecialLong = true; 8563 #endif 8564 if (Context.getTargetInfo().getLongWidth() == 32) 8565 ++HowLong; 8566 break; 8567 } 8568 case 'W': 8569 // This modifier represents int64 type. 8570 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!"); 8571 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 8572 #ifndef NDEBUG 8573 IsSpecialLong = true; 8574 #endif 8575 switch (Context.getTargetInfo().getInt64Type()) { 8576 default: 8577 llvm_unreachable("Unexpected integer type"); 8578 case TargetInfo::SignedLong: 8579 HowLong = 1; 8580 break; 8581 case TargetInfo::SignedLongLong: 8582 HowLong = 2; 8583 break; 8584 } 8585 break; 8586 } 8587 } 8588 8589 QualType Type; 8590 8591 // Read the base type. 8592 switch (*Str++) { 8593 default: llvm_unreachable("Unknown builtin type letter!"); 8594 case 'v': 8595 assert(HowLong == 0 && !Signed && !Unsigned && 8596 "Bad modifiers used with 'v'!"); 8597 Type = Context.VoidTy; 8598 break; 8599 case 'h': 8600 assert(HowLong == 0 && !Signed && !Unsigned && 8601 "Bad modifiers used with 'h'!"); 8602 Type = Context.HalfTy; 8603 break; 8604 case 'f': 8605 assert(HowLong == 0 && !Signed && !Unsigned && 8606 "Bad modifiers used with 'f'!"); 8607 Type = Context.FloatTy; 8608 break; 8609 case 'd': 8610 assert(HowLong < 2 && !Signed && !Unsigned && 8611 "Bad modifiers used with 'd'!"); 8612 if (HowLong) 8613 Type = Context.LongDoubleTy; 8614 else 8615 Type = Context.DoubleTy; 8616 break; 8617 case 's': 8618 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 8619 if (Unsigned) 8620 Type = Context.UnsignedShortTy; 8621 else 8622 Type = Context.ShortTy; 8623 break; 8624 case 'i': 8625 if (HowLong == 3) 8626 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 8627 else if (HowLong == 2) 8628 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 8629 else if (HowLong == 1) 8630 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 8631 else 8632 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 8633 break; 8634 case 'c': 8635 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 8636 if (Signed) 8637 Type = Context.SignedCharTy; 8638 else if (Unsigned) 8639 Type = Context.UnsignedCharTy; 8640 else 8641 Type = Context.CharTy; 8642 break; 8643 case 'b': // boolean 8644 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 8645 Type = Context.BoolTy; 8646 break; 8647 case 'z': // size_t. 8648 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 8649 Type = Context.getSizeType(); 8650 break; 8651 case 'w': // wchar_t. 8652 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!"); 8653 Type = Context.getWideCharType(); 8654 break; 8655 case 'F': 8656 Type = Context.getCFConstantStringType(); 8657 break; 8658 case 'G': 8659 Type = Context.getObjCIdType(); 8660 break; 8661 case 'H': 8662 Type = Context.getObjCSelType(); 8663 break; 8664 case 'M': 8665 Type = Context.getObjCSuperType(); 8666 break; 8667 case 'a': 8668 Type = Context.getBuiltinVaListType(); 8669 assert(!Type.isNull() && "builtin va list type not initialized!"); 8670 break; 8671 case 'A': 8672 // This is a "reference" to a va_list; however, what exactly 8673 // this means depends on how va_list is defined. There are two 8674 // different kinds of va_list: ones passed by value, and ones 8675 // passed by reference. An example of a by-value va_list is 8676 // x86, where va_list is a char*. An example of by-ref va_list 8677 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 8678 // we want this argument to be a char*&; for x86-64, we want 8679 // it to be a __va_list_tag*. 8680 Type = Context.getBuiltinVaListType(); 8681 assert(!Type.isNull() && "builtin va list type not initialized!"); 8682 if (Type->isArrayType()) 8683 Type = Context.getArrayDecayedType(Type); 8684 else 8685 Type = Context.getLValueReferenceType(Type); 8686 break; 8687 case 'V': { 8688 char *End; 8689 unsigned NumElements = strtoul(Str, &End, 10); 8690 assert(End != Str && "Missing vector size"); 8691 Str = End; 8692 8693 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 8694 RequiresICE, false); 8695 assert(!RequiresICE && "Can't require vector ICE"); 8696 8697 // TODO: No way to make AltiVec vectors in builtins yet. 8698 Type = Context.getVectorType(ElementType, NumElements, 8699 VectorType::GenericVector); 8700 break; 8701 } 8702 case 'E': { 8703 char *End; 8704 8705 unsigned NumElements = strtoul(Str, &End, 10); 8706 assert(End != Str && "Missing vector size"); 8707 8708 Str = End; 8709 8710 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 8711 false); 8712 Type = Context.getExtVectorType(ElementType, NumElements); 8713 break; 8714 } 8715 case 'X': { 8716 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 8717 false); 8718 assert(!RequiresICE && "Can't require complex ICE"); 8719 Type = Context.getComplexType(ElementType); 8720 break; 8721 } 8722 case 'Y' : { 8723 Type = Context.getPointerDiffType(); 8724 break; 8725 } 8726 case 'P': 8727 Type = Context.getFILEType(); 8728 if (Type.isNull()) { 8729 Error = ASTContext::GE_Missing_stdio; 8730 return QualType(); 8731 } 8732 break; 8733 case 'J': 8734 if (Signed) 8735 Type = Context.getsigjmp_bufType(); 8736 else 8737 Type = Context.getjmp_bufType(); 8738 8739 if (Type.isNull()) { 8740 Error = ASTContext::GE_Missing_setjmp; 8741 return QualType(); 8742 } 8743 break; 8744 case 'K': 8745 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 8746 Type = Context.getucontext_tType(); 8747 8748 if (Type.isNull()) { 8749 Error = ASTContext::GE_Missing_ucontext; 8750 return QualType(); 8751 } 8752 break; 8753 case 'p': 8754 Type = Context.getProcessIDType(); 8755 break; 8756 } 8757 8758 // If there are modifiers and if we're allowed to parse them, go for it. 8759 Done = !AllowTypeModifiers; 8760 while (!Done) { 8761 switch (char c = *Str++) { 8762 default: Done = true; --Str; break; 8763 case '*': 8764 case '&': { 8765 // Both pointers and references can have their pointee types 8766 // qualified with an address space. 8767 char *End; 8768 unsigned AddrSpace = strtoul(Str, &End, 10); 8769 if (End != Str && AddrSpace != 0) { 8770 Type = Context.getAddrSpaceQualType( 8771 Type, AddrSpace + LangAS::FirstTargetAddressSpace); 8772 Str = End; 8773 } 8774 if (c == '*') 8775 Type = Context.getPointerType(Type); 8776 else 8777 Type = Context.getLValueReferenceType(Type); 8778 break; 8779 } 8780 // FIXME: There's no way to have a built-in with an rvalue ref arg. 8781 case 'C': 8782 Type = Type.withConst(); 8783 break; 8784 case 'D': 8785 Type = Context.getVolatileType(Type); 8786 break; 8787 case 'R': 8788 Type = Type.withRestrict(); 8789 break; 8790 } 8791 } 8792 8793 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 8794 "Integer constant 'I' type must be an integer"); 8795 8796 return Type; 8797 } 8798 8799 /// GetBuiltinType - Return the type for the specified builtin. 8800 QualType ASTContext::GetBuiltinType(unsigned Id, 8801 GetBuiltinTypeError &Error, 8802 unsigned *IntegerConstantArgs) const { 8803 const char *TypeStr = BuiltinInfo.getTypeString(Id); 8804 8805 SmallVector<QualType, 8> ArgTypes; 8806 8807 bool RequiresICE = false; 8808 Error = GE_None; 8809 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 8810 RequiresICE, true); 8811 if (Error != GE_None) 8812 return QualType(); 8813 8814 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 8815 8816 while (TypeStr[0] && TypeStr[0] != '.') { 8817 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 8818 if (Error != GE_None) 8819 return QualType(); 8820 8821 // If this argument is required to be an IntegerConstantExpression and the 8822 // caller cares, fill in the bitmask we return. 8823 if (RequiresICE && IntegerConstantArgs) 8824 *IntegerConstantArgs |= 1 << ArgTypes.size(); 8825 8826 // Do array -> pointer decay. The builtin should use the decayed type. 8827 if (Ty->isArrayType()) 8828 Ty = getArrayDecayedType(Ty); 8829 8830 ArgTypes.push_back(Ty); 8831 } 8832 8833 if (Id == Builtin::BI__GetExceptionInfo) 8834 return QualType(); 8835 8836 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 8837 "'.' should only occur at end of builtin type list!"); 8838 8839 FunctionType::ExtInfo EI(CC_C); 8840 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 8841 8842 bool Variadic = (TypeStr[0] == '.'); 8843 8844 // We really shouldn't be making a no-proto type here. 8845 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus) 8846 return getFunctionNoProtoType(ResType, EI); 8847 8848 FunctionProtoType::ExtProtoInfo EPI; 8849 EPI.ExtInfo = EI; 8850 EPI.Variadic = Variadic; 8851 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id)) 8852 EPI.ExceptionSpec.Type = 8853 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 8854 8855 return getFunctionType(ResType, ArgTypes, EPI); 8856 } 8857 8858 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 8859 const FunctionDecl *FD) { 8860 if (!FD->isExternallyVisible()) 8861 return GVA_Internal; 8862 8863 GVALinkage External; 8864 switch (FD->getTemplateSpecializationKind()) { 8865 case TSK_Undeclared: 8866 case TSK_ExplicitSpecialization: 8867 External = GVA_StrongExternal; 8868 break; 8869 8870 case TSK_ExplicitInstantiationDefinition: 8871 return GVA_StrongODR; 8872 8873 // C++11 [temp.explicit]p10: 8874 // [ Note: The intent is that an inline function that is the subject of 8875 // an explicit instantiation declaration will still be implicitly 8876 // instantiated when used so that the body can be considered for 8877 // inlining, but that no out-of-line copy of the inline function would be 8878 // generated in the translation unit. -- end note ] 8879 case TSK_ExplicitInstantiationDeclaration: 8880 return GVA_AvailableExternally; 8881 8882 case TSK_ImplicitInstantiation: 8883 External = GVA_DiscardableODR; 8884 break; 8885 } 8886 8887 if (!FD->isInlined()) 8888 return External; 8889 8890 if ((!Context.getLangOpts().CPlusPlus && 8891 !Context.getTargetInfo().getCXXABI().isMicrosoft() && 8892 !FD->hasAttr<DLLExportAttr>()) || 8893 FD->hasAttr<GNUInlineAttr>()) { 8894 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 8895 8896 // GNU or C99 inline semantics. Determine whether this symbol should be 8897 // externally visible. 8898 if (FD->isInlineDefinitionExternallyVisible()) 8899 return External; 8900 8901 // C99 inline semantics, where the symbol is not externally visible. 8902 return GVA_AvailableExternally; 8903 } 8904 8905 // Functions specified with extern and inline in -fms-compatibility mode 8906 // forcibly get emitted. While the body of the function cannot be later 8907 // replaced, the function definition cannot be discarded. 8908 if (FD->isMSExternInline()) 8909 return GVA_StrongODR; 8910 8911 return GVA_DiscardableODR; 8912 } 8913 8914 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, 8915 GVALinkage L, const Decl *D) { 8916 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx 8917 // dllexport/dllimport on inline functions. 8918 if (D->hasAttr<DLLImportAttr>()) { 8919 if (L == GVA_DiscardableODR || L == GVA_StrongODR) 8920 return GVA_AvailableExternally; 8921 } else if (D->hasAttr<DLLExportAttr>()) { 8922 if (L == GVA_DiscardableODR) 8923 return GVA_StrongODR; 8924 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice && 8925 D->hasAttr<CUDAGlobalAttr>()) { 8926 // Device-side functions with __global__ attribute must always be 8927 // visible externally so they can be launched from host. 8928 if (L == GVA_DiscardableODR || L == GVA_Internal) 8929 return GVA_StrongODR; 8930 } 8931 return L; 8932 } 8933 8934 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { 8935 auto L = adjustGVALinkageForAttributes( 8936 *this, basicGVALinkageForFunction(*this, FD), FD); 8937 auto EK = ExternalASTSource::EK_ReplyHazy; 8938 if (auto *Ext = getExternalSource()) 8939 EK = Ext->hasExternalDefinitions(FD); 8940 switch (EK) { 8941 case ExternalASTSource::EK_Never: 8942 if (L == GVA_DiscardableODR) 8943 return GVA_StrongODR; 8944 break; 8945 case ExternalASTSource::EK_Always: 8946 return GVA_AvailableExternally; 8947 case ExternalASTSource::EK_ReplyHazy: 8948 break; 8949 } 8950 return L; 8951 } 8952 8953 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, 8954 const VarDecl *VD) { 8955 if (!VD->isExternallyVisible()) 8956 return GVA_Internal; 8957 8958 if (VD->isStaticLocal()) { 8959 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); 8960 while (LexicalContext && !isa<FunctionDecl>(LexicalContext)) 8961 LexicalContext = LexicalContext->getLexicalParent(); 8962 8963 // ObjC Blocks can create local variables that don't have a FunctionDecl 8964 // LexicalContext. 8965 if (!LexicalContext) 8966 return GVA_DiscardableODR; 8967 8968 // Otherwise, let the static local variable inherit its linkage from the 8969 // nearest enclosing function. 8970 auto StaticLocalLinkage = 8971 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext)); 8972 8973 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must 8974 // be emitted in any object with references to the symbol for the object it 8975 // contains, whether inline or out-of-line." 8976 // Similar behavior is observed with MSVC. An alternative ABI could use 8977 // StrongODR/AvailableExternally to match the function, but none are 8978 // known/supported currently. 8979 if (StaticLocalLinkage == GVA_StrongODR || 8980 StaticLocalLinkage == GVA_AvailableExternally) 8981 return GVA_DiscardableODR; 8982 return StaticLocalLinkage; 8983 } 8984 8985 // MSVC treats in-class initialized static data members as definitions. 8986 // By giving them non-strong linkage, out-of-line definitions won't 8987 // cause link errors. 8988 if (Context.isMSStaticDataMemberInlineDefinition(VD)) 8989 return GVA_DiscardableODR; 8990 8991 // Most non-template variables have strong linkage; inline variables are 8992 // linkonce_odr or (occasionally, for compatibility) weak_odr. 8993 GVALinkage StrongLinkage; 8994 switch (Context.getInlineVariableDefinitionKind(VD)) { 8995 case ASTContext::InlineVariableDefinitionKind::None: 8996 StrongLinkage = GVA_StrongExternal; 8997 break; 8998 case ASTContext::InlineVariableDefinitionKind::Weak: 8999 case ASTContext::InlineVariableDefinitionKind::WeakUnknown: 9000 StrongLinkage = GVA_DiscardableODR; 9001 break; 9002 case ASTContext::InlineVariableDefinitionKind::Strong: 9003 StrongLinkage = GVA_StrongODR; 9004 break; 9005 } 9006 9007 switch (VD->getTemplateSpecializationKind()) { 9008 case TSK_Undeclared: 9009 return StrongLinkage; 9010 9011 case TSK_ExplicitSpecialization: 9012 return Context.getTargetInfo().getCXXABI().isMicrosoft() && 9013 VD->isStaticDataMember() 9014 ? GVA_StrongODR 9015 : StrongLinkage; 9016 9017 case TSK_ExplicitInstantiationDefinition: 9018 return GVA_StrongODR; 9019 9020 case TSK_ExplicitInstantiationDeclaration: 9021 return GVA_AvailableExternally; 9022 9023 case TSK_ImplicitInstantiation: 9024 return GVA_DiscardableODR; 9025 } 9026 9027 llvm_unreachable("Invalid Linkage!"); 9028 } 9029 9030 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 9031 return adjustGVALinkageForAttributes( 9032 *this, basicGVALinkageForVariable(*this, VD), VD); 9033 } 9034 9035 bool ASTContext::DeclMustBeEmitted(const Decl *D) { 9036 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 9037 if (!VD->isFileVarDecl()) 9038 return false; 9039 // Global named register variables (GNU extension) are never emitted. 9040 if (VD->getStorageClass() == SC_Register) 9041 return false; 9042 if (VD->getDescribedVarTemplate() || 9043 isa<VarTemplatePartialSpecializationDecl>(VD)) 9044 return false; 9045 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 9046 // We never need to emit an uninstantiated function template. 9047 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 9048 return false; 9049 } else if (isa<PragmaCommentDecl>(D)) 9050 return true; 9051 else if (isa<OMPThreadPrivateDecl>(D) || 9052 D->hasAttr<OMPDeclareTargetDeclAttr>()) 9053 return true; 9054 else if (isa<PragmaDetectMismatchDecl>(D)) 9055 return true; 9056 else if (isa<OMPThreadPrivateDecl>(D)) 9057 return !D->getDeclContext()->isDependentContext(); 9058 else if (isa<OMPDeclareReductionDecl>(D)) 9059 return !D->getDeclContext()->isDependentContext(); 9060 else if (isa<ImportDecl>(D)) 9061 return true; 9062 else 9063 return false; 9064 9065 // If this is a member of a class template, we do not need to emit it. 9066 if (D->getDeclContext()->isDependentContext()) 9067 return false; 9068 9069 // Weak references don't produce any output by themselves. 9070 if (D->hasAttr<WeakRefAttr>()) 9071 return false; 9072 9073 // Aliases and used decls are required. 9074 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 9075 return true; 9076 9077 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 9078 // Forward declarations aren't required. 9079 if (!FD->doesThisDeclarationHaveABody()) 9080 return FD->doesDeclarationForceExternallyVisibleDefinition(); 9081 9082 // Constructors and destructors are required. 9083 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 9084 return true; 9085 9086 // The key function for a class is required. This rule only comes 9087 // into play when inline functions can be key functions, though. 9088 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 9089 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 9090 const CXXRecordDecl *RD = MD->getParent(); 9091 if (MD->isOutOfLine() && RD->isDynamicClass()) { 9092 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); 9093 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 9094 return true; 9095 } 9096 } 9097 } 9098 9099 GVALinkage Linkage = GetGVALinkageForFunction(FD); 9100 9101 // static, static inline, always_inline, and extern inline functions can 9102 // always be deferred. Normal inline functions can be deferred in C99/C++. 9103 // Implicit template instantiations can also be deferred in C++. 9104 return !isDiscardableGVALinkage(Linkage); 9105 } 9106 9107 const VarDecl *VD = cast<VarDecl>(D); 9108 assert(VD->isFileVarDecl() && "Expected file scoped var"); 9109 9110 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly && 9111 !isMSStaticDataMemberInlineDefinition(VD)) 9112 return false; 9113 9114 // Variables that can be needed in other TUs are required. 9115 if (!isDiscardableGVALinkage(GetGVALinkageForVariable(VD))) 9116 return true; 9117 9118 // Variables that have destruction with side-effects are required. 9119 if (VD->getType().isDestructedType()) 9120 return true; 9121 9122 // Variables that have initialization with side-effects are required. 9123 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) && 9124 // We can get a value-dependent initializer during error recovery. 9125 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 9126 return true; 9127 9128 // Likewise, variables with tuple-like bindings are required if their 9129 // bindings have side-effects. 9130 if (auto *DD = dyn_cast<DecompositionDecl>(VD)) 9131 for (auto *BD : DD->bindings()) 9132 if (auto *BindingVD = BD->getHoldingVar()) 9133 if (DeclMustBeEmitted(BindingVD)) 9134 return true; 9135 9136 return false; 9137 } 9138 9139 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic, 9140 bool IsCXXMethod) const { 9141 // Pass through to the C++ ABI object 9142 if (IsCXXMethod) 9143 return ABI->getDefaultMethodCallConv(IsVariadic); 9144 9145 switch (LangOpts.getDefaultCallingConv()) { 9146 case LangOptions::DCC_None: 9147 break; 9148 case LangOptions::DCC_CDecl: 9149 return CC_C; 9150 case LangOptions::DCC_FastCall: 9151 if (getTargetInfo().hasFeature("sse2")) 9152 return CC_X86FastCall; 9153 break; 9154 case LangOptions::DCC_StdCall: 9155 if (!IsVariadic) 9156 return CC_X86StdCall; 9157 break; 9158 case LangOptions::DCC_VectorCall: 9159 // __vectorcall cannot be applied to variadic functions. 9160 if (!IsVariadic) 9161 return CC_X86VectorCall; 9162 break; 9163 } 9164 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown); 9165 } 9166 9167 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 9168 // Pass through to the C++ ABI object 9169 return ABI->isNearlyEmpty(RD); 9170 } 9171 9172 VTableContextBase *ASTContext::getVTableContext() { 9173 if (!VTContext.get()) { 9174 if (Target->getCXXABI().isMicrosoft()) 9175 VTContext.reset(new MicrosoftVTableContext(*this)); 9176 else 9177 VTContext.reset(new ItaniumVTableContext(*this)); 9178 } 9179 return VTContext.get(); 9180 } 9181 9182 MangleContext *ASTContext::createMangleContext() { 9183 switch (Target->getCXXABI().getKind()) { 9184 case TargetCXXABI::GenericAArch64: 9185 case TargetCXXABI::GenericItanium: 9186 case TargetCXXABI::GenericARM: 9187 case TargetCXXABI::GenericMIPS: 9188 case TargetCXXABI::iOS: 9189 case TargetCXXABI::iOS64: 9190 case TargetCXXABI::WebAssembly: 9191 case TargetCXXABI::WatchOS: 9192 return ItaniumMangleContext::create(*this, getDiagnostics()); 9193 case TargetCXXABI::Microsoft: 9194 return MicrosoftMangleContext::create(*this, getDiagnostics()); 9195 } 9196 llvm_unreachable("Unsupported ABI"); 9197 } 9198 9199 CXXABI::~CXXABI() {} 9200 9201 size_t ASTContext::getSideTableAllocatedMemory() const { 9202 return ASTRecordLayouts.getMemorySize() + 9203 llvm::capacity_in_bytes(ObjCLayouts) + 9204 llvm::capacity_in_bytes(KeyFunctions) + 9205 llvm::capacity_in_bytes(ObjCImpls) + 9206 llvm::capacity_in_bytes(BlockVarCopyInits) + 9207 llvm::capacity_in_bytes(DeclAttrs) + 9208 llvm::capacity_in_bytes(TemplateOrInstantiation) + 9209 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) + 9210 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) + 9211 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) + 9212 llvm::capacity_in_bytes(OverriddenMethods) + 9213 llvm::capacity_in_bytes(Types) + 9214 llvm::capacity_in_bytes(VariableArrayTypes) + 9215 llvm::capacity_in_bytes(ClassScopeSpecializationPattern); 9216 } 9217 9218 /// getIntTypeForBitwidth - 9219 /// sets integer QualTy according to specified details: 9220 /// bitwidth, signed/unsigned. 9221 /// Returns empty type if there is no appropriate target types. 9222 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth, 9223 unsigned Signed) const { 9224 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed); 9225 CanQualType QualTy = getFromTargetType(Ty); 9226 if (!QualTy && DestWidth == 128) 9227 return Signed ? Int128Ty : UnsignedInt128Ty; 9228 return QualTy; 9229 } 9230 9231 /// getRealTypeForBitwidth - 9232 /// sets floating point QualTy according to specified bitwidth. 9233 /// Returns empty type if there is no appropriate target types. 9234 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const { 9235 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth); 9236 switch (Ty) { 9237 case TargetInfo::Float: 9238 return FloatTy; 9239 case TargetInfo::Double: 9240 return DoubleTy; 9241 case TargetInfo::LongDouble: 9242 return LongDoubleTy; 9243 case TargetInfo::Float128: 9244 return Float128Ty; 9245 case TargetInfo::NoFloat: 9246 return QualType(); 9247 } 9248 9249 llvm_unreachable("Unhandled TargetInfo::RealType value"); 9250 } 9251 9252 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { 9253 if (Number > 1) 9254 MangleNumbers[ND] = Number; 9255 } 9256 9257 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const { 9258 auto I = MangleNumbers.find(ND); 9259 return I != MangleNumbers.end() ? I->second : 1; 9260 } 9261 9262 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { 9263 if (Number > 1) 9264 StaticLocalNumbers[VD] = Number; 9265 } 9266 9267 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { 9268 auto I = StaticLocalNumbers.find(VD); 9269 return I != StaticLocalNumbers.end() ? I->second : 1; 9270 } 9271 9272 MangleNumberingContext & 9273 ASTContext::getManglingNumberContext(const DeclContext *DC) { 9274 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. 9275 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC]; 9276 if (!MCtx) 9277 MCtx = createMangleNumberingContext(); 9278 return *MCtx; 9279 } 9280 9281 std::unique_ptr<MangleNumberingContext> 9282 ASTContext::createMangleNumberingContext() const { 9283 return ABI->createMangleNumberingContext(); 9284 } 9285 9286 const CXXConstructorDecl * 9287 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) { 9288 return ABI->getCopyConstructorForExceptionObject( 9289 cast<CXXRecordDecl>(RD->getFirstDecl())); 9290 } 9291 9292 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD, 9293 CXXConstructorDecl *CD) { 9294 return ABI->addCopyConstructorForExceptionObject( 9295 cast<CXXRecordDecl>(RD->getFirstDecl()), 9296 cast<CXXConstructorDecl>(CD->getFirstDecl())); 9297 } 9298 9299 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD, 9300 TypedefNameDecl *DD) { 9301 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD); 9302 } 9303 9304 TypedefNameDecl * 9305 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) { 9306 return ABI->getTypedefNameForUnnamedTagDecl(TD); 9307 } 9308 9309 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD, 9310 DeclaratorDecl *DD) { 9311 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD); 9312 } 9313 9314 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) { 9315 return ABI->getDeclaratorForUnnamedTagDecl(TD); 9316 } 9317 9318 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 9319 ParamIndices[D] = index; 9320 } 9321 9322 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 9323 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 9324 assert(I != ParamIndices.end() && 9325 "ParmIndices lacks entry set by ParmVarDecl"); 9326 return I->second; 9327 } 9328 9329 APValue * 9330 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E, 9331 bool MayCreate) { 9332 assert(E && E->getStorageDuration() == SD_Static && 9333 "don't need to cache the computed value for this temporary"); 9334 if (MayCreate) { 9335 APValue *&MTVI = MaterializedTemporaryValues[E]; 9336 if (!MTVI) 9337 MTVI = new (*this) APValue; 9338 return MTVI; 9339 } 9340 9341 return MaterializedTemporaryValues.lookup(E); 9342 } 9343 9344 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { 9345 const llvm::Triple &T = getTargetInfo().getTriple(); 9346 if (!T.isOSDarwin()) 9347 return false; 9348 9349 if (!(T.isiOS() && T.isOSVersionLT(7)) && 9350 !(T.isMacOSX() && T.isOSVersionLT(10, 9))) 9351 return false; 9352 9353 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 9354 CharUnits sizeChars = getTypeSizeInChars(AtomicTy); 9355 uint64_t Size = sizeChars.getQuantity(); 9356 CharUnits alignChars = getTypeAlignInChars(AtomicTy); 9357 unsigned Align = alignChars.getQuantity(); 9358 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth(); 9359 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); 9360 } 9361 9362 namespace { 9363 9364 ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap( 9365 ASTContext::ParentMapPointers::mapped_type U) { 9366 if (const auto *D = U.dyn_cast<const Decl *>()) 9367 return ast_type_traits::DynTypedNode::create(*D); 9368 if (const auto *S = U.dyn_cast<const Stmt *>()) 9369 return ast_type_traits::DynTypedNode::create(*S); 9370 return *U.get<ast_type_traits::DynTypedNode *>(); 9371 } 9372 9373 /// Template specializations to abstract away from pointers and TypeLocs. 9374 /// @{ 9375 template <typename T> 9376 ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) { 9377 return ast_type_traits::DynTypedNode::create(*Node); 9378 } 9379 template <> 9380 ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) { 9381 return ast_type_traits::DynTypedNode::create(Node); 9382 } 9383 template <> 9384 ast_type_traits::DynTypedNode 9385 createDynTypedNode(const NestedNameSpecifierLoc &Node) { 9386 return ast_type_traits::DynTypedNode::create(Node); 9387 } 9388 /// @} 9389 9390 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their 9391 /// parents as defined by the \c RecursiveASTVisitor. 9392 /// 9393 /// Note that the relationship described here is purely in terms of AST 9394 /// traversal - there are other relationships (for example declaration context) 9395 /// in the AST that are better modeled by special matchers. 9396 /// 9397 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes. 9398 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> { 9399 public: 9400 /// \brief Builds and returns the translation unit's parent map. 9401 /// 9402 /// The caller takes ownership of the returned \c ParentMap. 9403 static std::pair<ASTContext::ParentMapPointers *, 9404 ASTContext::ParentMapOtherNodes *> 9405 buildMap(TranslationUnitDecl &TU) { 9406 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers, 9407 new ASTContext::ParentMapOtherNodes); 9408 Visitor.TraverseDecl(&TU); 9409 return std::make_pair(Visitor.Parents, Visitor.OtherParents); 9410 } 9411 9412 private: 9413 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase; 9414 9415 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents, 9416 ASTContext::ParentMapOtherNodes *OtherParents) 9417 : Parents(Parents), OtherParents(OtherParents) {} 9418 9419 bool shouldVisitTemplateInstantiations() const { 9420 return true; 9421 } 9422 bool shouldVisitImplicitCode() const { 9423 return true; 9424 } 9425 9426 template <typename T, typename MapNodeTy, typename BaseTraverseFn, 9427 typename MapTy> 9428 bool TraverseNode(T Node, MapNodeTy MapNode, 9429 BaseTraverseFn BaseTraverse, MapTy *Parents) { 9430 if (!Node) 9431 return true; 9432 if (ParentStack.size() > 0) { 9433 // FIXME: Currently we add the same parent multiple times, but only 9434 // when no memoization data is available for the type. 9435 // For example when we visit all subexpressions of template 9436 // instantiations; this is suboptimal, but benign: the only way to 9437 // visit those is with hasAncestor / hasParent, and those do not create 9438 // new matches. 9439 // The plan is to enable DynTypedNode to be storable in a map or hash 9440 // map. The main problem there is to implement hash functions / 9441 // comparison operators for all types that DynTypedNode supports that 9442 // do not have pointer identity. 9443 auto &NodeOrVector = (*Parents)[MapNode]; 9444 if (NodeOrVector.isNull()) { 9445 if (const auto *D = ParentStack.back().get<Decl>()) 9446 NodeOrVector = D; 9447 else if (const auto *S = ParentStack.back().get<Stmt>()) 9448 NodeOrVector = S; 9449 else 9450 NodeOrVector = 9451 new ast_type_traits::DynTypedNode(ParentStack.back()); 9452 } else { 9453 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) { 9454 auto *Vector = new ASTContext::ParentVector( 9455 1, getSingleDynTypedNodeFromParentMap(NodeOrVector)); 9456 delete NodeOrVector 9457 .template dyn_cast<ast_type_traits::DynTypedNode *>(); 9458 NodeOrVector = Vector; 9459 } 9460 9461 auto *Vector = 9462 NodeOrVector.template get<ASTContext::ParentVector *>(); 9463 // Skip duplicates for types that have memoization data. 9464 // We must check that the type has memoization data before calling 9465 // std::find() because DynTypedNode::operator== can't compare all 9466 // types. 9467 bool Found = ParentStack.back().getMemoizationData() && 9468 std::find(Vector->begin(), Vector->end(), 9469 ParentStack.back()) != Vector->end(); 9470 if (!Found) 9471 Vector->push_back(ParentStack.back()); 9472 } 9473 } 9474 ParentStack.push_back(createDynTypedNode(Node)); 9475 bool Result = BaseTraverse(); 9476 ParentStack.pop_back(); 9477 return Result; 9478 } 9479 9480 bool TraverseDecl(Decl *DeclNode) { 9481 return TraverseNode(DeclNode, DeclNode, 9482 [&] { return VisitorBase::TraverseDecl(DeclNode); }, 9483 Parents); 9484 } 9485 9486 bool TraverseStmt(Stmt *StmtNode) { 9487 return TraverseNode(StmtNode, StmtNode, 9488 [&] { return VisitorBase::TraverseStmt(StmtNode); }, 9489 Parents); 9490 } 9491 9492 bool TraverseTypeLoc(TypeLoc TypeLocNode) { 9493 return TraverseNode( 9494 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode), 9495 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); }, 9496 OtherParents); 9497 } 9498 9499 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) { 9500 return TraverseNode( 9501 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode), 9502 [&] { 9503 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); 9504 }, 9505 OtherParents); 9506 } 9507 9508 ASTContext::ParentMapPointers *Parents; 9509 ASTContext::ParentMapOtherNodes *OtherParents; 9510 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack; 9511 9512 friend class RecursiveASTVisitor<ParentMapASTVisitor>; 9513 }; 9514 9515 } // anonymous namespace 9516 9517 template <typename NodeTy, typename MapTy> 9518 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node, 9519 const MapTy &Map) { 9520 auto I = Map.find(Node); 9521 if (I == Map.end()) { 9522 return llvm::ArrayRef<ast_type_traits::DynTypedNode>(); 9523 } 9524 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) { 9525 return llvm::makeArrayRef(*V); 9526 } 9527 return getSingleDynTypedNodeFromParentMap(I->second); 9528 } 9529 9530 ASTContext::DynTypedNodeList 9531 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) { 9532 if (!PointerParents) { 9533 // We always need to run over the whole translation unit, as 9534 // hasAncestor can escape any subtree. 9535 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()); 9536 PointerParents.reset(Maps.first); 9537 OtherParents.reset(Maps.second); 9538 } 9539 if (Node.getNodeKind().hasPointerIdentity()) 9540 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents); 9541 return getDynNodeFromMap(Node, *OtherParents); 9542 } 9543 9544 bool 9545 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, 9546 const ObjCMethodDecl *MethodImpl) { 9547 // No point trying to match an unavailable/deprecated mothod. 9548 if (MethodDecl->hasAttr<UnavailableAttr>() 9549 || MethodDecl->hasAttr<DeprecatedAttr>()) 9550 return false; 9551 if (MethodDecl->getObjCDeclQualifier() != 9552 MethodImpl->getObjCDeclQualifier()) 9553 return false; 9554 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) 9555 return false; 9556 9557 if (MethodDecl->param_size() != MethodImpl->param_size()) 9558 return false; 9559 9560 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), 9561 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), 9562 EF = MethodDecl->param_end(); 9563 IM != EM && IF != EF; ++IM, ++IF) { 9564 const ParmVarDecl *DeclVar = (*IF); 9565 const ParmVarDecl *ImplVar = (*IM); 9566 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) 9567 return false; 9568 if (!hasSameType(DeclVar->getType(), ImplVar->getType())) 9569 return false; 9570 } 9571 return (MethodDecl->isVariadic() == MethodImpl->isVariadic()); 9572 9573 } 9574 9575 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const { 9576 unsigned AS; 9577 if (QT->getUnqualifiedDesugaredType()->isNullPtrType()) 9578 AS = 0; 9579 else 9580 AS = QT->getPointeeType().getAddressSpace(); 9581 9582 return getTargetInfo().getNullPointerValue(AS); 9583 } 9584 9585 unsigned ASTContext::getTargetAddressSpace(unsigned AS) const { 9586 if (AS >= LangAS::FirstTargetAddressSpace) 9587 return AS - LangAS::FirstTargetAddressSpace; 9588 else 9589 return (*AddrSpaceMap)[AS]; 9590 } 9591 9592 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that 9593 // doesn't include ASTContext.h 9594 template 9595 clang::LazyGenerationalUpdatePtr< 9596 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType 9597 clang::LazyGenerationalUpdatePtr< 9598 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( 9599 const clang::ASTContext &Ctx, Decl *Value); 9600