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