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