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