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