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