ASTContext.cpp revision 2a674e8e443b7a3e77957078248fb52b3b1ec321
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 "clang/AST/CharUnits.h" 16#include "clang/AST/DeclCXX.h" 17#include "clang/AST/DeclObjC.h" 18#include "clang/AST/DeclTemplate.h" 19#include "clang/AST/TypeLoc.h" 20#include "clang/AST/Expr.h" 21#include "clang/AST/ExprCXX.h" 22#include "clang/AST/ExternalASTSource.h" 23#include "clang/AST/RecordLayout.h" 24#include "clang/Basic/Builtins.h" 25#include "clang/Basic/SourceManager.h" 26#include "clang/Basic/TargetInfo.h" 27#include "llvm/ADT/SmallString.h" 28#include "llvm/ADT/StringExtras.h" 29#include "llvm/Support/MathExtras.h" 30#include "llvm/Support/raw_ostream.h" 31#include "CXXABI.h" 32 33using namespace clang; 34 35unsigned ASTContext::NumImplicitDefaultConstructors; 36unsigned ASTContext::NumImplicitDefaultConstructorsDeclared; 37unsigned ASTContext::NumImplicitCopyConstructors; 38unsigned ASTContext::NumImplicitCopyConstructorsDeclared; 39unsigned ASTContext::NumImplicitCopyAssignmentOperators; 40unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 41unsigned ASTContext::NumImplicitDestructors; 42unsigned ASTContext::NumImplicitDestructorsDeclared; 43 44enum FloatingRank { 45 FloatRank, DoubleRank, LongDoubleRank 46}; 47 48void 49ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 50 TemplateTemplateParmDecl *Parm) { 51 ID.AddInteger(Parm->getDepth()); 52 ID.AddInteger(Parm->getPosition()); 53 // FIXME: Parameter pack 54 55 TemplateParameterList *Params = Parm->getTemplateParameters(); 56 ID.AddInteger(Params->size()); 57 for (TemplateParameterList::const_iterator P = Params->begin(), 58 PEnd = Params->end(); 59 P != PEnd; ++P) { 60 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 61 ID.AddInteger(0); 62 ID.AddBoolean(TTP->isParameterPack()); 63 continue; 64 } 65 66 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 67 ID.AddInteger(1); 68 // FIXME: Parameter pack 69 ID.AddPointer(NTTP->getType().getAsOpaquePtr()); 70 continue; 71 } 72 73 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); 74 ID.AddInteger(2); 75 Profile(ID, TTP); 76 } 77} 78 79TemplateTemplateParmDecl * 80ASTContext::getCanonicalTemplateTemplateParmDecl( 81 TemplateTemplateParmDecl *TTP) { 82 // Check if we already have a canonical template template parameter. 83 llvm::FoldingSetNodeID ID; 84 CanonicalTemplateTemplateParm::Profile(ID, TTP); 85 void *InsertPos = 0; 86 CanonicalTemplateTemplateParm *Canonical 87 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 88 if (Canonical) 89 return Canonical->getParam(); 90 91 // Build a canonical template parameter list. 92 TemplateParameterList *Params = TTP->getTemplateParameters(); 93 llvm::SmallVector<NamedDecl *, 4> CanonParams; 94 CanonParams.reserve(Params->size()); 95 for (TemplateParameterList::const_iterator P = Params->begin(), 96 PEnd = Params->end(); 97 P != PEnd; ++P) { 98 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) 99 CanonParams.push_back( 100 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(), 101 SourceLocation(), TTP->getDepth(), 102 TTP->getIndex(), 0, false, 103 TTP->isParameterPack())); 104 else if (NonTypeTemplateParmDecl *NTTP 105 = dyn_cast<NonTypeTemplateParmDecl>(*P)) 106 CanonParams.push_back( 107 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 108 SourceLocation(), NTTP->getDepth(), 109 NTTP->getPosition(), 0, 110 getCanonicalType(NTTP->getType()), 111 0)); 112 else 113 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 114 cast<TemplateTemplateParmDecl>(*P))); 115 } 116 117 TemplateTemplateParmDecl *CanonTTP 118 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 119 SourceLocation(), TTP->getDepth(), 120 TTP->getPosition(), 0, 121 TemplateParameterList::Create(*this, SourceLocation(), 122 SourceLocation(), 123 CanonParams.data(), 124 CanonParams.size(), 125 SourceLocation())); 126 127 // Get the new insert position for the node we care about. 128 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 129 assert(Canonical == 0 && "Shouldn't be in the map!"); 130 (void)Canonical; 131 132 // Create the canonical template template parameter entry. 133 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 134 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 135 return CanonTTP; 136} 137 138CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 139 if (!LangOpts.CPlusPlus) return 0; 140 141 switch (T.getCXXABI()) { 142 case CXXABI_ARM: 143 return CreateARMCXXABI(*this); 144 case CXXABI_Itanium: 145 return CreateItaniumCXXABI(*this); 146 case CXXABI_Microsoft: 147 return CreateMicrosoftCXXABI(*this); 148 } 149 return 0; 150} 151 152ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM, 153 const TargetInfo &t, 154 IdentifierTable &idents, SelectorTable &sels, 155 Builtin::Context &builtins, 156 unsigned size_reserve) : 157 TemplateSpecializationTypes(this_()), 158 DependentTemplateSpecializationTypes(this_()), 159 GlobalNestedNameSpecifier(0), IsInt128Installed(false), 160 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0), 161 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0), 162 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0), 163 NullTypeSourceInfo(QualType()), 164 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t), 165 Idents(idents), Selectors(sels), 166 BuiltinInfo(builtins), 167 DeclarationNames(*this), 168 ExternalSource(0), PrintingPolicy(LOpts), 169 LastSDM(0, 0), 170 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) { 171 ObjCIdRedefinitionType = QualType(); 172 ObjCClassRedefinitionType = QualType(); 173 ObjCSelRedefinitionType = QualType(); 174 if (size_reserve > 0) Types.reserve(size_reserve); 175 TUDecl = TranslationUnitDecl::Create(*this); 176 InitBuiltinTypes(); 177} 178 179ASTContext::~ASTContext() { 180 // Release the DenseMaps associated with DeclContext objects. 181 // FIXME: Is this the ideal solution? 182 ReleaseDeclContextMaps(); 183 184 // Call all of the deallocation functions. 185 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I) 186 Deallocations[I].first(Deallocations[I].second); 187 188 // Release all of the memory associated with overridden C++ methods. 189 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator 190 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end(); 191 OM != OMEnd; ++OM) 192 OM->second.Destroy(); 193 194 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 195 // because they can contain DenseMaps. 196 for (llvm::DenseMap<const ObjCContainerDecl*, 197 const ASTRecordLayout*>::iterator 198 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 199 // Increment in loop to prevent using deallocated memory. 200 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 201 R->Destroy(*this); 202 203 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 204 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 205 // Increment in loop to prevent using deallocated memory. 206 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 207 R->Destroy(*this); 208 } 209 210 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 211 AEnd = DeclAttrs.end(); 212 A != AEnd; ++A) 213 A->second->~AttrVec(); 214} 215 216void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) { 217 Deallocations.push_back(std::make_pair(Callback, Data)); 218} 219 220void 221ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) { 222 ExternalSource.reset(Source.take()); 223} 224 225void ASTContext::PrintStats() const { 226 fprintf(stderr, "*** AST Context Stats:\n"); 227 fprintf(stderr, " %d types total.\n", (int)Types.size()); 228 229 unsigned counts[] = { 230#define TYPE(Name, Parent) 0, 231#define ABSTRACT_TYPE(Name, Parent) 232#include "clang/AST/TypeNodes.def" 233 0 // Extra 234 }; 235 236 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 237 Type *T = Types[i]; 238 counts[(unsigned)T->getTypeClass()]++; 239 } 240 241 unsigned Idx = 0; 242 unsigned TotalBytes = 0; 243#define TYPE(Name, Parent) \ 244 if (counts[Idx]) \ 245 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \ 246 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 247 ++Idx; 248#define ABSTRACT_TYPE(Name, Parent) 249#include "clang/AST/TypeNodes.def" 250 251 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes)); 252 253 // Implicit special member functions. 254 fprintf(stderr, " %u/%u implicit default constructors created\n", 255 NumImplicitDefaultConstructorsDeclared, 256 NumImplicitDefaultConstructors); 257 fprintf(stderr, " %u/%u implicit copy constructors created\n", 258 NumImplicitCopyConstructorsDeclared, 259 NumImplicitCopyConstructors); 260 fprintf(stderr, " %u/%u implicit copy assignment operators created\n", 261 NumImplicitCopyAssignmentOperatorsDeclared, 262 NumImplicitCopyAssignmentOperators); 263 fprintf(stderr, " %u/%u implicit destructors created\n", 264 NumImplicitDestructorsDeclared, NumImplicitDestructors); 265 266 if (ExternalSource.get()) { 267 fprintf(stderr, "\n"); 268 ExternalSource->PrintStats(); 269 } 270 271 BumpAlloc.PrintStats(); 272} 273 274 275void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 276 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K); 277 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 278 Types.push_back(Ty); 279} 280 281void ASTContext::InitBuiltinTypes() { 282 assert(VoidTy.isNull() && "Context reinitialized?"); 283 284 // C99 6.2.5p19. 285 InitBuiltinType(VoidTy, BuiltinType::Void); 286 287 // C99 6.2.5p2. 288 InitBuiltinType(BoolTy, BuiltinType::Bool); 289 // C99 6.2.5p3. 290 if (LangOpts.CharIsSigned) 291 InitBuiltinType(CharTy, BuiltinType::Char_S); 292 else 293 InitBuiltinType(CharTy, BuiltinType::Char_U); 294 // C99 6.2.5p4. 295 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 296 InitBuiltinType(ShortTy, BuiltinType::Short); 297 InitBuiltinType(IntTy, BuiltinType::Int); 298 InitBuiltinType(LongTy, BuiltinType::Long); 299 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 300 301 // C99 6.2.5p6. 302 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 303 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 304 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 305 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 306 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 307 308 // C99 6.2.5p10. 309 InitBuiltinType(FloatTy, BuiltinType::Float); 310 InitBuiltinType(DoubleTy, BuiltinType::Double); 311 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 312 313 // GNU extension, 128-bit integers. 314 InitBuiltinType(Int128Ty, BuiltinType::Int128); 315 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 316 317 if (LangOpts.CPlusPlus) // C++ 3.9.1p5 318 InitBuiltinType(WCharTy, BuiltinType::WChar); 319 else // C99 320 WCharTy = getFromTargetType(Target.getWCharType()); 321 322 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 323 InitBuiltinType(Char16Ty, BuiltinType::Char16); 324 else // C99 325 Char16Ty = getFromTargetType(Target.getChar16Type()); 326 327 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 328 InitBuiltinType(Char32Ty, BuiltinType::Char32); 329 else // C99 330 Char32Ty = getFromTargetType(Target.getChar32Type()); 331 332 // Placeholder type for functions. 333 InitBuiltinType(OverloadTy, BuiltinType::Overload); 334 335 // Placeholder type for type-dependent expressions whose type is 336 // completely unknown. No code should ever check a type against 337 // DependentTy and users should never see it; however, it is here to 338 // help diagnose failures to properly check for type-dependent 339 // expressions. 340 InitBuiltinType(DependentTy, BuiltinType::Dependent); 341 342 // Placeholder type for C++0x auto declarations whose real type has 343 // not yet been deduced. 344 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto); 345 346 // C99 6.2.5p11. 347 FloatComplexTy = getComplexType(FloatTy); 348 DoubleComplexTy = getComplexType(DoubleTy); 349 LongDoubleComplexTy = getComplexType(LongDoubleTy); 350 351 BuiltinVaListType = QualType(); 352 353 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope(). 354 ObjCIdTypedefType = QualType(); 355 ObjCClassTypedefType = QualType(); 356 ObjCSelTypedefType = QualType(); 357 358 // Builtin types for 'id', 'Class', and 'SEL'. 359 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 360 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 361 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 362 363 ObjCConstantStringType = QualType(); 364 365 // void * type 366 VoidPtrTy = getPointerType(VoidTy); 367 368 // nullptr type (C++0x 2.14.7) 369 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 370} 371 372Diagnostic &ASTContext::getDiagnostics() const { 373 return SourceMgr.getDiagnostics(); 374} 375 376AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 377 AttrVec *&Result = DeclAttrs[D]; 378 if (!Result) { 379 void *Mem = Allocate(sizeof(AttrVec)); 380 Result = new (Mem) AttrVec; 381 } 382 383 return *Result; 384} 385 386/// \brief Erase the attributes corresponding to the given declaration. 387void ASTContext::eraseDeclAttrs(const Decl *D) { 388 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 389 if (Pos != DeclAttrs.end()) { 390 Pos->second->~AttrVec(); 391 DeclAttrs.erase(Pos); 392 } 393} 394 395 396MemberSpecializationInfo * 397ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 398 assert(Var->isStaticDataMember() && "Not a static data member"); 399 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos 400 = InstantiatedFromStaticDataMember.find(Var); 401 if (Pos == InstantiatedFromStaticDataMember.end()) 402 return 0; 403 404 return Pos->second; 405} 406 407void 408ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 409 TemplateSpecializationKind TSK, 410 SourceLocation PointOfInstantiation) { 411 assert(Inst->isStaticDataMember() && "Not a static data member"); 412 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 413 assert(!InstantiatedFromStaticDataMember[Inst] && 414 "Already noted what static data member was instantiated from"); 415 InstantiatedFromStaticDataMember[Inst] 416 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation); 417} 418 419NamedDecl * 420ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) { 421 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos 422 = InstantiatedFromUsingDecl.find(UUD); 423 if (Pos == InstantiatedFromUsingDecl.end()) 424 return 0; 425 426 return Pos->second; 427} 428 429void 430ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) { 431 assert((isa<UsingDecl>(Pattern) || 432 isa<UnresolvedUsingValueDecl>(Pattern) || 433 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 434 "pattern decl is not a using decl"); 435 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 436 InstantiatedFromUsingDecl[Inst] = Pattern; 437} 438 439UsingShadowDecl * 440ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 441 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 442 = InstantiatedFromUsingShadowDecl.find(Inst); 443 if (Pos == InstantiatedFromUsingShadowDecl.end()) 444 return 0; 445 446 return Pos->second; 447} 448 449void 450ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 451 UsingShadowDecl *Pattern) { 452 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 453 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 454} 455 456FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 457 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 458 = InstantiatedFromUnnamedFieldDecl.find(Field); 459 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 460 return 0; 461 462 return Pos->second; 463} 464 465void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 466 FieldDecl *Tmpl) { 467 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 468 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 469 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 470 "Already noted what unnamed field was instantiated from"); 471 472 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 473} 474 475ASTContext::overridden_cxx_method_iterator 476ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 477 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 478 = OverriddenMethods.find(Method); 479 if (Pos == OverriddenMethods.end()) 480 return 0; 481 482 return Pos->second.begin(); 483} 484 485ASTContext::overridden_cxx_method_iterator 486ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 487 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 488 = OverriddenMethods.find(Method); 489 if (Pos == OverriddenMethods.end()) 490 return 0; 491 492 return Pos->second.end(); 493} 494 495unsigned 496ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 497 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 498 = OverriddenMethods.find(Method); 499 if (Pos == OverriddenMethods.end()) 500 return 0; 501 502 return Pos->second.size(); 503} 504 505void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 506 const CXXMethodDecl *Overridden) { 507 OverriddenMethods[Method].push_back(Overridden); 508} 509 510//===----------------------------------------------------------------------===// 511// Type Sizing and Analysis 512//===----------------------------------------------------------------------===// 513 514/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 515/// scalar floating point type. 516const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 517 const BuiltinType *BT = T->getAs<BuiltinType>(); 518 assert(BT && "Not a floating point type!"); 519 switch (BT->getKind()) { 520 default: assert(0 && "Not a floating point type!"); 521 case BuiltinType::Float: return Target.getFloatFormat(); 522 case BuiltinType::Double: return Target.getDoubleFormat(); 523 case BuiltinType::LongDouble: return Target.getLongDoubleFormat(); 524 } 525} 526 527/// getDeclAlign - Return a conservative estimate of the alignment of the 528/// specified decl. Note that bitfields do not have a valid alignment, so 529/// this method will assert on them. 530/// If @p RefAsPointee, references are treated like their underlying type 531/// (for alignof), else they're treated like pointers (for CodeGen). 532CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) { 533 unsigned Align = Target.getCharWidth(); 534 535 Align = std::max(Align, D->getMaxAlignment()); 536 537 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 538 QualType T = VD->getType(); 539 if (const ReferenceType* RT = T->getAs<ReferenceType>()) { 540 if (RefAsPointee) 541 T = RT->getPointeeType(); 542 else 543 T = getPointerType(RT->getPointeeType()); 544 } 545 if (!T->isIncompleteType() && !T->isFunctionType()) { 546 unsigned MinWidth = Target.getLargeArrayMinWidth(); 547 unsigned ArrayAlign = Target.getLargeArrayAlign(); 548 if (isa<VariableArrayType>(T) && MinWidth != 0) 549 Align = std::max(Align, ArrayAlign); 550 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) { 551 unsigned Size = getTypeSize(CT); 552 if (MinWidth != 0 && MinWidth <= Size) 553 Align = std::max(Align, ArrayAlign); 554 } 555 // Incomplete or function types default to 1. 556 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T)) 557 T = cast<ArrayType>(T)->getElementType(); 558 559 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 560 } 561 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) { 562 // In the case of a field in a packed struct, we want the minimum 563 // of the alignment of the field and the alignment of the struct. 564 Align = std::min(Align, 565 getPreferredTypeAlign(FD->getParent()->getTypeForDecl())); 566 } 567 } 568 569 return CharUnits::fromQuantity(Align / Target.getCharWidth()); 570} 571 572std::pair<CharUnits, CharUnits> 573ASTContext::getTypeInfoInChars(const Type *T) { 574 std::pair<uint64_t, unsigned> Info = getTypeInfo(T); 575 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()), 576 CharUnits::fromQuantity(Info.second / getCharWidth())); 577} 578 579std::pair<CharUnits, CharUnits> 580ASTContext::getTypeInfoInChars(QualType T) { 581 return getTypeInfoInChars(T.getTypePtr()); 582} 583 584/// getTypeSize - Return the size of the specified type, in bits. This method 585/// does not work on incomplete types. 586/// 587/// FIXME: Pointers into different addr spaces could have different sizes and 588/// alignment requirements: getPointerInfo should take an AddrSpace, this 589/// should take a QualType, &c. 590std::pair<uint64_t, unsigned> 591ASTContext::getTypeInfo(const Type *T) { 592 uint64_t Width=0; 593 unsigned Align=8; 594 switch (T->getTypeClass()) { 595#define TYPE(Class, Base) 596#define ABSTRACT_TYPE(Class, Base) 597#define NON_CANONICAL_TYPE(Class, Base) 598#define DEPENDENT_TYPE(Class, Base) case Type::Class: 599#include "clang/AST/TypeNodes.def" 600 assert(false && "Should not see dependent types"); 601 break; 602 603 case Type::FunctionNoProto: 604 case Type::FunctionProto: 605 // GCC extension: alignof(function) = 32 bits 606 Width = 0; 607 Align = 32; 608 break; 609 610 case Type::IncompleteArray: 611 case Type::VariableArray: 612 Width = 0; 613 Align = getTypeAlign(cast<ArrayType>(T)->getElementType()); 614 break; 615 616 case Type::ConstantArray: { 617 const ConstantArrayType *CAT = cast<ConstantArrayType>(T); 618 619 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType()); 620 Width = EltInfo.first*CAT->getSize().getZExtValue(); 621 Align = EltInfo.second; 622 break; 623 } 624 case Type::ExtVector: 625 case Type::Vector: { 626 const VectorType *VT = cast<VectorType>(T); 627 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType()); 628 Width = EltInfo.first*VT->getNumElements(); 629 Align = Width; 630 // If the alignment is not a power of 2, round up to the next power of 2. 631 // This happens for non-power-of-2 length vectors. 632 if (Align & (Align-1)) { 633 Align = llvm::NextPowerOf2(Align); 634 Width = llvm::RoundUpToAlignment(Width, Align); 635 } 636 break; 637 } 638 639 case Type::Builtin: 640 switch (cast<BuiltinType>(T)->getKind()) { 641 default: assert(0 && "Unknown builtin type!"); 642 case BuiltinType::Void: 643 // GCC extension: alignof(void) = 8 bits. 644 Width = 0; 645 Align = 8; 646 break; 647 648 case BuiltinType::Bool: 649 Width = Target.getBoolWidth(); 650 Align = Target.getBoolAlign(); 651 break; 652 case BuiltinType::Char_S: 653 case BuiltinType::Char_U: 654 case BuiltinType::UChar: 655 case BuiltinType::SChar: 656 Width = Target.getCharWidth(); 657 Align = Target.getCharAlign(); 658 break; 659 case BuiltinType::WChar: 660 Width = Target.getWCharWidth(); 661 Align = Target.getWCharAlign(); 662 break; 663 case BuiltinType::Char16: 664 Width = Target.getChar16Width(); 665 Align = Target.getChar16Align(); 666 break; 667 case BuiltinType::Char32: 668 Width = Target.getChar32Width(); 669 Align = Target.getChar32Align(); 670 break; 671 case BuiltinType::UShort: 672 case BuiltinType::Short: 673 Width = Target.getShortWidth(); 674 Align = Target.getShortAlign(); 675 break; 676 case BuiltinType::UInt: 677 case BuiltinType::Int: 678 Width = Target.getIntWidth(); 679 Align = Target.getIntAlign(); 680 break; 681 case BuiltinType::ULong: 682 case BuiltinType::Long: 683 Width = Target.getLongWidth(); 684 Align = Target.getLongAlign(); 685 break; 686 case BuiltinType::ULongLong: 687 case BuiltinType::LongLong: 688 Width = Target.getLongLongWidth(); 689 Align = Target.getLongLongAlign(); 690 break; 691 case BuiltinType::Int128: 692 case BuiltinType::UInt128: 693 Width = 128; 694 Align = 128; // int128_t is 128-bit aligned on all targets. 695 break; 696 case BuiltinType::Float: 697 Width = Target.getFloatWidth(); 698 Align = Target.getFloatAlign(); 699 break; 700 case BuiltinType::Double: 701 Width = Target.getDoubleWidth(); 702 Align = Target.getDoubleAlign(); 703 break; 704 case BuiltinType::LongDouble: 705 Width = Target.getLongDoubleWidth(); 706 Align = Target.getLongDoubleAlign(); 707 break; 708 case BuiltinType::NullPtr: 709 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 710 Align = Target.getPointerAlign(0); // == sizeof(void*) 711 break; 712 case BuiltinType::ObjCId: 713 case BuiltinType::ObjCClass: 714 case BuiltinType::ObjCSel: 715 Width = Target.getPointerWidth(0); 716 Align = Target.getPointerAlign(0); 717 break; 718 } 719 break; 720 case Type::ObjCObjectPointer: 721 Width = Target.getPointerWidth(0); 722 Align = Target.getPointerAlign(0); 723 break; 724 case Type::BlockPointer: { 725 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace(); 726 Width = Target.getPointerWidth(AS); 727 Align = Target.getPointerAlign(AS); 728 break; 729 } 730 case Type::LValueReference: 731 case Type::RValueReference: { 732 // alignof and sizeof should never enter this code path here, so we go 733 // the pointer route. 734 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace(); 735 Width = Target.getPointerWidth(AS); 736 Align = Target.getPointerAlign(AS); 737 break; 738 } 739 case Type::Pointer: { 740 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace(); 741 Width = Target.getPointerWidth(AS); 742 Align = Target.getPointerAlign(AS); 743 break; 744 } 745 case Type::MemberPointer: { 746 const MemberPointerType *MPT = cast<MemberPointerType>(T); 747 std::pair<uint64_t, unsigned> PtrDiffInfo = 748 getTypeInfo(getPointerDiffType()); 749 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT); 750 Align = PtrDiffInfo.second; 751 break; 752 } 753 case Type::Complex: { 754 // Complex types have the same alignment as their elements, but twice the 755 // size. 756 std::pair<uint64_t, unsigned> EltInfo = 757 getTypeInfo(cast<ComplexType>(T)->getElementType()); 758 Width = EltInfo.first*2; 759 Align = EltInfo.second; 760 break; 761 } 762 case Type::ObjCObject: 763 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 764 case Type::ObjCInterface: { 765 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T); 766 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 767 Width = Layout.getSize(); 768 Align = Layout.getAlignment(); 769 break; 770 } 771 case Type::Record: 772 case Type::Enum: { 773 const TagType *TT = cast<TagType>(T); 774 775 if (TT->getDecl()->isInvalidDecl()) { 776 Width = 1; 777 Align = 1; 778 break; 779 } 780 781 if (const EnumType *ET = dyn_cast<EnumType>(TT)) 782 return getTypeInfo(ET->getDecl()->getIntegerType()); 783 784 const RecordType *RT = cast<RecordType>(TT); 785 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl()); 786 Width = Layout.getSize(); 787 Align = Layout.getAlignment(); 788 break; 789 } 790 791 case Type::SubstTemplateTypeParm: 792 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 793 getReplacementType().getTypePtr()); 794 795 case Type::Typedef: { 796 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl(); 797 std::pair<uint64_t, unsigned> Info 798 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 799 Align = std::max(Typedef->getMaxAlignment(), Info.second); 800 Width = Info.first; 801 break; 802 } 803 804 case Type::TypeOfExpr: 805 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType() 806 .getTypePtr()); 807 808 case Type::TypeOf: 809 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr()); 810 811 case Type::Decltype: 812 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType() 813 .getTypePtr()); 814 815 case Type::Elaborated: 816 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 817 818 case Type::TemplateSpecialization: 819 assert(getCanonicalType(T) != T && 820 "Cannot request the size of a dependent type"); 821 // FIXME: this is likely to be wrong once we support template 822 // aliases, since a template alias could refer to a typedef that 823 // has an __aligned__ attribute on it. 824 return getTypeInfo(getCanonicalType(T)); 825 } 826 827 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2"); 828 return std::make_pair(Width, Align); 829} 830 831/// getTypeSizeInChars - Return the size of the specified type, in characters. 832/// This method does not work on incomplete types. 833CharUnits ASTContext::getTypeSizeInChars(QualType T) { 834 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth()); 835} 836CharUnits ASTContext::getTypeSizeInChars(const Type *T) { 837 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth()); 838} 839 840/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 841/// characters. This method does not work on incomplete types. 842CharUnits ASTContext::getTypeAlignInChars(QualType T) { 843 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth()); 844} 845CharUnits ASTContext::getTypeAlignInChars(const Type *T) { 846 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth()); 847} 848 849/// getPreferredTypeAlign - Return the "preferred" alignment of the specified 850/// type for the current target in bits. This can be different than the ABI 851/// alignment in cases where it is beneficial for performance to overalign 852/// a data type. 853unsigned ASTContext::getPreferredTypeAlign(const Type *T) { 854 unsigned ABIAlign = getTypeAlign(T); 855 856 // Double and long long should be naturally aligned if possible. 857 if (const ComplexType* CT = T->getAs<ComplexType>()) 858 T = CT->getElementType().getTypePtr(); 859 if (T->isSpecificBuiltinType(BuiltinType::Double) || 860 T->isSpecificBuiltinType(BuiltinType::LongLong)) 861 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 862 863 return ABIAlign; 864} 865 866/// ShallowCollectObjCIvars - 867/// Collect all ivars, including those synthesized, in the current class. 868/// 869void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI, 870 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 871 // FIXME. This need be removed but there are two many places which 872 // assume const-ness of ObjCInterfaceDecl 873 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 874 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 875 Iv= Iv->getNextIvar()) 876 Ivars.push_back(Iv); 877} 878 879/// DeepCollectObjCIvars - 880/// This routine first collects all declared, but not synthesized, ivars in 881/// super class and then collects all ivars, including those synthesized for 882/// current class. This routine is used for implementation of current class 883/// when all ivars, declared and synthesized are known. 884/// 885void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 886 bool leafClass, 887 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 888 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 889 DeepCollectObjCIvars(SuperClass, false, Ivars); 890 if (!leafClass) { 891 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 892 E = OI->ivar_end(); I != E; ++I) 893 Ivars.push_back(*I); 894 } 895 else 896 ShallowCollectObjCIvars(OI, Ivars); 897} 898 899/// CollectInheritedProtocols - Collect all protocols in current class and 900/// those inherited by it. 901void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 902 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 903 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 904 // We can use protocol_iterator here instead of 905 // all_referenced_protocol_iterator since we are walking all categories. 906 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(), 907 PE = OI->all_referenced_protocol_end(); P != PE; ++P) { 908 ObjCProtocolDecl *Proto = (*P); 909 Protocols.insert(Proto); 910 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 911 PE = Proto->protocol_end(); P != PE; ++P) { 912 Protocols.insert(*P); 913 CollectInheritedProtocols(*P, Protocols); 914 } 915 } 916 917 // Categories of this Interface. 918 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList(); 919 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory()) 920 CollectInheritedProtocols(CDeclChain, Protocols); 921 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 922 while (SD) { 923 CollectInheritedProtocols(SD, Protocols); 924 SD = SD->getSuperClass(); 925 } 926 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 927 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(), 928 PE = OC->protocol_end(); P != PE; ++P) { 929 ObjCProtocolDecl *Proto = (*P); 930 Protocols.insert(Proto); 931 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 932 PE = Proto->protocol_end(); P != PE; ++P) 933 CollectInheritedProtocols(*P, Protocols); 934 } 935 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 936 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(), 937 PE = OP->protocol_end(); P != PE; ++P) { 938 ObjCProtocolDecl *Proto = (*P); 939 Protocols.insert(Proto); 940 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 941 PE = Proto->protocol_end(); P != PE; ++P) 942 CollectInheritedProtocols(*P, Protocols); 943 } 944 } 945} 946 947unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) { 948 unsigned count = 0; 949 // Count ivars declared in class extension. 950 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl; 951 CDecl = CDecl->getNextClassExtension()) 952 count += CDecl->ivar_size(); 953 954 // Count ivar defined in this class's implementation. This 955 // includes synthesized ivars. 956 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 957 count += ImplDecl->ivar_size(); 958 959 return count; 960} 961 962/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists. 963ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 964 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 965 I = ObjCImpls.find(D); 966 if (I != ObjCImpls.end()) 967 return cast<ObjCImplementationDecl>(I->second); 968 return 0; 969} 970/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists. 971ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 972 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 973 I = ObjCImpls.find(D); 974 if (I != ObjCImpls.end()) 975 return cast<ObjCCategoryImplDecl>(I->second); 976 return 0; 977} 978 979/// \brief Set the implementation of ObjCInterfaceDecl. 980void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 981 ObjCImplementationDecl *ImplD) { 982 assert(IFaceD && ImplD && "Passed null params"); 983 ObjCImpls[IFaceD] = ImplD; 984} 985/// \brief Set the implementation of ObjCCategoryDecl. 986void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 987 ObjCCategoryImplDecl *ImplD) { 988 assert(CatD && ImplD && "Passed null params"); 989 ObjCImpls[CatD] = ImplD; 990} 991 992/// \brief Allocate an uninitialized TypeSourceInfo. 993/// 994/// The caller should initialize the memory held by TypeSourceInfo using 995/// the TypeLoc wrappers. 996/// 997/// \param T the type that will be the basis for type source info. This type 998/// should refer to how the declarator was written in source code, not to 999/// what type semantic analysis resolved the declarator to. 1000TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 1001 unsigned DataSize) { 1002 if (!DataSize) 1003 DataSize = TypeLoc::getFullDataSizeForType(T); 1004 else 1005 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 1006 "incorrect data size provided to CreateTypeSourceInfo!"); 1007 1008 TypeSourceInfo *TInfo = 1009 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 1010 new (TInfo) TypeSourceInfo(T); 1011 return TInfo; 1012} 1013 1014TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 1015 SourceLocation L) { 1016 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 1017 DI->getTypeLoc().initialize(L); 1018 return DI; 1019} 1020 1021const ASTRecordLayout & 1022ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) { 1023 return getObjCLayout(D, 0); 1024} 1025 1026const ASTRecordLayout & 1027ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) { 1028 return getObjCLayout(D->getClassInterface(), D); 1029} 1030 1031//===----------------------------------------------------------------------===// 1032// Type creation/memoization methods 1033//===----------------------------------------------------------------------===// 1034 1035QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) { 1036 unsigned Fast = Quals.getFastQualifiers(); 1037 Quals.removeFastQualifiers(); 1038 1039 // Check if we've already instantiated this type. 1040 llvm::FoldingSetNodeID ID; 1041 ExtQuals::Profile(ID, TypeNode, Quals); 1042 void *InsertPos = 0; 1043 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) { 1044 assert(EQ->getQualifiers() == Quals); 1045 QualType T = QualType(EQ, Fast); 1046 return T; 1047 } 1048 1049 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals); 1050 ExtQualNodes.InsertNode(New, InsertPos); 1051 QualType T = QualType(New, Fast); 1052 return T; 1053} 1054 1055QualType ASTContext::getVolatileType(QualType T) { 1056 QualType CanT = getCanonicalType(T); 1057 if (CanT.isVolatileQualified()) return T; 1058 1059 QualifierCollector Quals; 1060 const Type *TypeNode = Quals.strip(T); 1061 Quals.addVolatile(); 1062 1063 return getExtQualType(TypeNode, Quals); 1064} 1065 1066QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) { 1067 QualType CanT = getCanonicalType(T); 1068 if (CanT.getAddressSpace() == AddressSpace) 1069 return T; 1070 1071 // If we are composing extended qualifiers together, merge together 1072 // into one ExtQuals node. 1073 QualifierCollector Quals; 1074 const Type *TypeNode = Quals.strip(T); 1075 1076 // If this type already has an address space specified, it cannot get 1077 // another one. 1078 assert(!Quals.hasAddressSpace() && 1079 "Type cannot be in multiple addr spaces!"); 1080 Quals.addAddressSpace(AddressSpace); 1081 1082 return getExtQualType(TypeNode, Quals); 1083} 1084 1085QualType ASTContext::getObjCGCQualType(QualType T, 1086 Qualifiers::GC GCAttr) { 1087 QualType CanT = getCanonicalType(T); 1088 if (CanT.getObjCGCAttr() == GCAttr) 1089 return T; 1090 1091 if (T->isPointerType()) { 1092 QualType Pointee = T->getAs<PointerType>()->getPointeeType(); 1093 if (Pointee->isAnyPointerType()) { 1094 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 1095 return getPointerType(ResultType); 1096 } 1097 } 1098 1099 // If we are composing extended qualifiers together, merge together 1100 // into one ExtQuals node. 1101 QualifierCollector Quals; 1102 const Type *TypeNode = Quals.strip(T); 1103 1104 // If this type already has an ObjCGC specified, it cannot get 1105 // another one. 1106 assert(!Quals.hasObjCGCAttr() && 1107 "Type cannot have multiple ObjCGCs!"); 1108 Quals.addObjCGCAttr(GCAttr); 1109 1110 return getExtQualType(TypeNode, Quals); 1111} 1112 1113static QualType getExtFunctionType(ASTContext& Context, QualType T, 1114 const FunctionType::ExtInfo &Info) { 1115 QualType ResultType; 1116 if (const PointerType *Pointer = T->getAs<PointerType>()) { 1117 QualType Pointee = Pointer->getPointeeType(); 1118 ResultType = getExtFunctionType(Context, Pointee, Info); 1119 if (ResultType == Pointee) 1120 return T; 1121 1122 ResultType = Context.getPointerType(ResultType); 1123 } else if (const BlockPointerType *BlockPointer 1124 = T->getAs<BlockPointerType>()) { 1125 QualType Pointee = BlockPointer->getPointeeType(); 1126 ResultType = getExtFunctionType(Context, Pointee, Info); 1127 if (ResultType == Pointee) 1128 return T; 1129 1130 ResultType = Context.getBlockPointerType(ResultType); 1131 } else if (const MemberPointerType *MemberPointer 1132 = T->getAs<MemberPointerType>()) { 1133 QualType Pointee = MemberPointer->getPointeeType(); 1134 ResultType = getExtFunctionType(Context, Pointee, Info); 1135 if (ResultType == Pointee) 1136 return T; 1137 1138 ResultType = Context.getMemberPointerType(ResultType, 1139 MemberPointer->getClass()); 1140 } else if (const FunctionType *F = T->getAs<FunctionType>()) { 1141 if (F->getExtInfo() == Info) 1142 return T; 1143 1144 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) { 1145 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(), 1146 Info); 1147 } else { 1148 const FunctionProtoType *FPT = cast<FunctionProtoType>(F); 1149 ResultType 1150 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(), 1151 FPT->getNumArgs(), FPT->isVariadic(), 1152 FPT->getTypeQuals(), 1153 FPT->hasExceptionSpec(), 1154 FPT->hasAnyExceptionSpec(), 1155 FPT->getNumExceptions(), 1156 FPT->exception_begin(), 1157 Info); 1158 } 1159 } else 1160 return T; 1161 1162 return Context.getQualifiedType(ResultType, T.getLocalQualifiers()); 1163} 1164 1165QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) { 1166 FunctionType::ExtInfo Info = getFunctionExtInfo(T); 1167 return getExtFunctionType(*this, T, 1168 Info.withNoReturn(AddNoReturn)); 1169} 1170 1171QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) { 1172 FunctionType::ExtInfo Info = getFunctionExtInfo(T); 1173 return getExtFunctionType(*this, T, 1174 Info.withCallingConv(CallConv)); 1175} 1176 1177QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) { 1178 FunctionType::ExtInfo Info = getFunctionExtInfo(T); 1179 return getExtFunctionType(*this, T, 1180 Info.withRegParm(RegParm)); 1181} 1182 1183/// getComplexType - Return the uniqued reference to the type for a complex 1184/// number with the specified element type. 1185QualType ASTContext::getComplexType(QualType T) { 1186 // Unique pointers, to guarantee there is only one pointer of a particular 1187 // structure. 1188 llvm::FoldingSetNodeID ID; 1189 ComplexType::Profile(ID, T); 1190 1191 void *InsertPos = 0; 1192 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 1193 return QualType(CT, 0); 1194 1195 // If the pointee type isn't canonical, this won't be a canonical type either, 1196 // so fill in the canonical type field. 1197 QualType Canonical; 1198 if (!T.isCanonical()) { 1199 Canonical = getComplexType(getCanonicalType(T)); 1200 1201 // Get the new insert position for the node we care about. 1202 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 1203 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1204 } 1205 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 1206 Types.push_back(New); 1207 ComplexTypes.InsertNode(New, InsertPos); 1208 return QualType(New, 0); 1209} 1210 1211/// getPointerType - Return the uniqued reference to the type for a pointer to 1212/// the specified type. 1213QualType ASTContext::getPointerType(QualType T) { 1214 // Unique pointers, to guarantee there is only one pointer of a particular 1215 // structure. 1216 llvm::FoldingSetNodeID ID; 1217 PointerType::Profile(ID, T); 1218 1219 void *InsertPos = 0; 1220 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1221 return QualType(PT, 0); 1222 1223 // If the pointee type isn't canonical, this won't be a canonical type either, 1224 // so fill in the canonical type field. 1225 QualType Canonical; 1226 if (!T.isCanonical()) { 1227 Canonical = getPointerType(getCanonicalType(T)); 1228 1229 // Get the new insert position for the node we care about. 1230 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1231 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1232 } 1233 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical); 1234 Types.push_back(New); 1235 PointerTypes.InsertNode(New, InsertPos); 1236 return QualType(New, 0); 1237} 1238 1239/// getBlockPointerType - Return the uniqued reference to the type for 1240/// a pointer to the specified block. 1241QualType ASTContext::getBlockPointerType(QualType T) { 1242 assert(T->isFunctionType() && "block of function types only"); 1243 // Unique pointers, to guarantee there is only one block of a particular 1244 // structure. 1245 llvm::FoldingSetNodeID ID; 1246 BlockPointerType::Profile(ID, T); 1247 1248 void *InsertPos = 0; 1249 if (BlockPointerType *PT = 1250 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1251 return QualType(PT, 0); 1252 1253 // If the block pointee type isn't canonical, this won't be a canonical 1254 // type either so fill in the canonical type field. 1255 QualType Canonical; 1256 if (!T.isCanonical()) { 1257 Canonical = getBlockPointerType(getCanonicalType(T)); 1258 1259 // Get the new insert position for the node we care about. 1260 BlockPointerType *NewIP = 1261 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1262 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1263 } 1264 BlockPointerType *New 1265 = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 1266 Types.push_back(New); 1267 BlockPointerTypes.InsertNode(New, InsertPos); 1268 return QualType(New, 0); 1269} 1270 1271/// getLValueReferenceType - Return the uniqued reference to the type for an 1272/// lvalue reference to the specified type. 1273QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) { 1274 // Unique pointers, to guarantee there is only one pointer of a particular 1275 // structure. 1276 llvm::FoldingSetNodeID ID; 1277 ReferenceType::Profile(ID, T, SpelledAsLValue); 1278 1279 void *InsertPos = 0; 1280 if (LValueReferenceType *RT = 1281 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1282 return QualType(RT, 0); 1283 1284 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 1285 1286 // If the referencee type isn't canonical, this won't be a canonical type 1287 // either, so fill in the canonical type field. 1288 QualType Canonical; 1289 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 1290 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 1291 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 1292 1293 // Get the new insert position for the node we care about. 1294 LValueReferenceType *NewIP = 1295 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 1296 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1297 } 1298 1299 LValueReferenceType *New 1300 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 1301 SpelledAsLValue); 1302 Types.push_back(New); 1303 LValueReferenceTypes.InsertNode(New, InsertPos); 1304 1305 return QualType(New, 0); 1306} 1307 1308/// getRValueReferenceType - Return the uniqued reference to the type for an 1309/// rvalue reference to the specified type. 1310QualType ASTContext::getRValueReferenceType(QualType T) { 1311 // Unique pointers, to guarantee there is only one pointer of a particular 1312 // structure. 1313 llvm::FoldingSetNodeID ID; 1314 ReferenceType::Profile(ID, T, false); 1315 1316 void *InsertPos = 0; 1317 if (RValueReferenceType *RT = 1318 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1319 return QualType(RT, 0); 1320 1321 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 1322 1323 // If the referencee type isn't canonical, this won't be a canonical type 1324 // either, so fill in the canonical type field. 1325 QualType Canonical; 1326 if (InnerRef || !T.isCanonical()) { 1327 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 1328 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 1329 1330 // Get the new insert position for the node we care about. 1331 RValueReferenceType *NewIP = 1332 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 1333 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1334 } 1335 1336 RValueReferenceType *New 1337 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 1338 Types.push_back(New); 1339 RValueReferenceTypes.InsertNode(New, InsertPos); 1340 return QualType(New, 0); 1341} 1342 1343/// getMemberPointerType - Return the uniqued reference to the type for a 1344/// member pointer to the specified type, in the specified class. 1345QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) { 1346 // Unique pointers, to guarantee there is only one pointer of a particular 1347 // structure. 1348 llvm::FoldingSetNodeID ID; 1349 MemberPointerType::Profile(ID, T, Cls); 1350 1351 void *InsertPos = 0; 1352 if (MemberPointerType *PT = 1353 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1354 return QualType(PT, 0); 1355 1356 // If the pointee or class type isn't canonical, this won't be a canonical 1357 // type either, so fill in the canonical type field. 1358 QualType Canonical; 1359 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 1360 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 1361 1362 // Get the new insert position for the node we care about. 1363 MemberPointerType *NewIP = 1364 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1365 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1366 } 1367 MemberPointerType *New 1368 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 1369 Types.push_back(New); 1370 MemberPointerTypes.InsertNode(New, InsertPos); 1371 return QualType(New, 0); 1372} 1373 1374/// getConstantArrayType - Return the unique reference to the type for an 1375/// array of the specified element type. 1376QualType ASTContext::getConstantArrayType(QualType EltTy, 1377 const llvm::APInt &ArySizeIn, 1378 ArrayType::ArraySizeModifier ASM, 1379 unsigned EltTypeQuals) { 1380 assert((EltTy->isDependentType() || 1381 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 1382 "Constant array of VLAs is illegal!"); 1383 1384 // Convert the array size into a canonical width matching the pointer size for 1385 // the target. 1386 llvm::APInt ArySize(ArySizeIn); 1387 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace())); 1388 1389 llvm::FoldingSetNodeID ID; 1390 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals); 1391 1392 void *InsertPos = 0; 1393 if (ConstantArrayType *ATP = 1394 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 1395 return QualType(ATP, 0); 1396 1397 // If the element type isn't canonical, this won't be a canonical type either, 1398 // so fill in the canonical type field. 1399 QualType Canonical; 1400 if (!EltTy.isCanonical()) { 1401 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize, 1402 ASM, EltTypeQuals); 1403 // Get the new insert position for the node we care about. 1404 ConstantArrayType *NewIP = 1405 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1406 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1407 } 1408 1409 ConstantArrayType *New = new(*this,TypeAlignment) 1410 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals); 1411 ConstantArrayTypes.InsertNode(New, InsertPos); 1412 Types.push_back(New); 1413 return QualType(New, 0); 1414} 1415 1416/// getIncompleteArrayType - Returns a unique reference to the type for a 1417/// incomplete array of the specified element type. 1418QualType ASTContext::getUnknownSizeVariableArrayType(QualType Ty) { 1419 QualType ElemTy = getBaseElementType(Ty); 1420 DeclarationName Name; 1421 llvm::SmallVector<QualType, 8> ATypes; 1422 QualType ATy = Ty; 1423 while (const ArrayType *AT = getAsArrayType(ATy)) { 1424 ATypes.push_back(ATy); 1425 ATy = AT->getElementType(); 1426 } 1427 for (int i = ATypes.size() - 1; i >= 0; i--) { 1428 if (const VariableArrayType *VAT = getAsVariableArrayType(ATypes[i])) { 1429 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Star, 1430 0, VAT->getBracketsRange()); 1431 } 1432 else if (const ConstantArrayType *CAT = getAsConstantArrayType(ATypes[i])) { 1433 llvm::APSInt ConstVal(CAT->getSize()); 1434 ElemTy = getConstantArrayType(ElemTy, ConstVal, ArrayType::Normal, 0); 1435 } 1436 else if (getAsIncompleteArrayType(ATypes[i])) { 1437 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Normal, 1438 0, SourceRange()); 1439 } 1440 else 1441 assert(false && "DependentArrayType is seen"); 1442 } 1443 return ElemTy; 1444} 1445 1446/// getVariableArrayDecayedType - Returns a vla type where known sizes 1447/// are replaced with [*] 1448QualType ASTContext::getVariableArrayDecayedType(QualType Ty) { 1449 if (Ty->isPointerType()) { 1450 QualType BaseType = Ty->getAs<PointerType>()->getPointeeType(); 1451 if (isa<VariableArrayType>(BaseType)) { 1452 ArrayType *AT = dyn_cast<ArrayType>(BaseType); 1453 VariableArrayType *VAT = cast<VariableArrayType>(AT); 1454 if (VAT->getSizeExpr()) { 1455 Ty = getUnknownSizeVariableArrayType(BaseType); 1456 Ty = getPointerType(Ty); 1457 } 1458 } 1459 } 1460 return Ty; 1461} 1462 1463 1464/// getVariableArrayType - Returns a non-unique reference to the type for a 1465/// variable array of the specified element type. 1466QualType ASTContext::getVariableArrayType(QualType EltTy, 1467 Expr *NumElts, 1468 ArrayType::ArraySizeModifier ASM, 1469 unsigned EltTypeQuals, 1470 SourceRange Brackets) { 1471 // Since we don't unique expressions, it isn't possible to unique VLA's 1472 // that have an expression provided for their size. 1473 QualType CanonType; 1474 1475 if (!EltTy.isCanonical()) { 1476 if (NumElts) 1477 NumElts->Retain(); 1478 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM, 1479 EltTypeQuals, Brackets); 1480 } 1481 1482 VariableArrayType *New = new(*this, TypeAlignment) 1483 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets); 1484 1485 VariableArrayTypes.push_back(New); 1486 Types.push_back(New); 1487 return QualType(New, 0); 1488} 1489 1490/// getDependentSizedArrayType - Returns a non-unique reference to 1491/// the type for a dependently-sized array of the specified element 1492/// type. 1493QualType ASTContext::getDependentSizedArrayType(QualType EltTy, 1494 Expr *NumElts, 1495 ArrayType::ArraySizeModifier ASM, 1496 unsigned EltTypeQuals, 1497 SourceRange Brackets) { 1498 assert((!NumElts || NumElts->isTypeDependent() || 1499 NumElts->isValueDependent()) && 1500 "Size must be type- or value-dependent!"); 1501 1502 void *InsertPos = 0; 1503 DependentSizedArrayType *Canon = 0; 1504 llvm::FoldingSetNodeID ID; 1505 1506 if (NumElts) { 1507 // Dependently-sized array types that do not have a specified 1508 // number of elements will have their sizes deduced from an 1509 // initializer. 1510 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM, 1511 EltTypeQuals, NumElts); 1512 1513 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1514 } 1515 1516 DependentSizedArrayType *New; 1517 if (Canon) { 1518 // We already have a canonical version of this array type; use it as 1519 // the canonical type for a newly-built type. 1520 New = new (*this, TypeAlignment) 1521 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0), 1522 NumElts, ASM, EltTypeQuals, Brackets); 1523 } else { 1524 QualType CanonEltTy = getCanonicalType(EltTy); 1525 if (CanonEltTy == EltTy) { 1526 New = new (*this, TypeAlignment) 1527 DependentSizedArrayType(*this, EltTy, QualType(), 1528 NumElts, ASM, EltTypeQuals, Brackets); 1529 1530 if (NumElts) { 1531 DependentSizedArrayType *CanonCheck 1532 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1533 assert(!CanonCheck && "Dependent-sized canonical array type broken"); 1534 (void)CanonCheck; 1535 DependentSizedArrayTypes.InsertNode(New, InsertPos); 1536 } 1537 } else { 1538 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts, 1539 ASM, EltTypeQuals, 1540 SourceRange()); 1541 New = new (*this, TypeAlignment) 1542 DependentSizedArrayType(*this, EltTy, Canon, 1543 NumElts, ASM, EltTypeQuals, Brackets); 1544 } 1545 } 1546 1547 Types.push_back(New); 1548 return QualType(New, 0); 1549} 1550 1551QualType ASTContext::getIncompleteArrayType(QualType EltTy, 1552 ArrayType::ArraySizeModifier ASM, 1553 unsigned EltTypeQuals) { 1554 llvm::FoldingSetNodeID ID; 1555 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals); 1556 1557 void *InsertPos = 0; 1558 if (IncompleteArrayType *ATP = 1559 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 1560 return QualType(ATP, 0); 1561 1562 // If the element type isn't canonical, this won't be a canonical type 1563 // either, so fill in the canonical type field. 1564 QualType Canonical; 1565 1566 if (!EltTy.isCanonical()) { 1567 Canonical = getIncompleteArrayType(getCanonicalType(EltTy), 1568 ASM, EltTypeQuals); 1569 1570 // Get the new insert position for the node we care about. 1571 IncompleteArrayType *NewIP = 1572 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1573 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1574 } 1575 1576 IncompleteArrayType *New = new (*this, TypeAlignment) 1577 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals); 1578 1579 IncompleteArrayTypes.InsertNode(New, InsertPos); 1580 Types.push_back(New); 1581 return QualType(New, 0); 1582} 1583 1584/// getVectorType - Return the unique reference to a vector type of 1585/// the specified element type and size. VectorType must be a built-in type. 1586QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 1587 VectorType::AltiVecSpecific AltiVecSpec) { 1588 BuiltinType *baseType; 1589 1590 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr()); 1591 assert(baseType != 0 && "getVectorType(): Expecting a built-in type"); 1592 1593 // Check if we've already instantiated a vector of this type. 1594 llvm::FoldingSetNodeID ID; 1595 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec); 1596 1597 void *InsertPos = 0; 1598 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 1599 return QualType(VTP, 0); 1600 1601 // If the element type isn't canonical, this won't be a canonical type either, 1602 // so fill in the canonical type field. 1603 QualType Canonical; 1604 if (!vecType.isCanonical()) { 1605 Canonical = getVectorType(getCanonicalType(vecType), NumElts, 1606 VectorType::NotAltiVec); 1607 1608 // Get the new insert position for the node we care about. 1609 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 1610 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1611 } 1612 VectorType *New = new (*this, TypeAlignment) 1613 VectorType(vecType, NumElts, Canonical, AltiVecSpec); 1614 VectorTypes.InsertNode(New, InsertPos); 1615 Types.push_back(New); 1616 return QualType(New, 0); 1617} 1618 1619/// getExtVectorType - Return the unique reference to an extended vector type of 1620/// the specified element type and size. VectorType must be a built-in type. 1621QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) { 1622 BuiltinType *baseType; 1623 1624 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr()); 1625 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type"); 1626 1627 // Check if we've already instantiated a vector of this type. 1628 llvm::FoldingSetNodeID ID; 1629 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 1630 VectorType::NotAltiVec); 1631 void *InsertPos = 0; 1632 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 1633 return QualType(VTP, 0); 1634 1635 // If the element type isn't canonical, this won't be a canonical type either, 1636 // so fill in the canonical type field. 1637 QualType Canonical; 1638 if (!vecType.isCanonical()) { 1639 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 1640 1641 // Get the new insert position for the node we care about. 1642 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 1643 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1644 } 1645 ExtVectorType *New = new (*this, TypeAlignment) 1646 ExtVectorType(vecType, NumElts, Canonical); 1647 VectorTypes.InsertNode(New, InsertPos); 1648 Types.push_back(New); 1649 return QualType(New, 0); 1650} 1651 1652QualType ASTContext::getDependentSizedExtVectorType(QualType vecType, 1653 Expr *SizeExpr, 1654 SourceLocation AttrLoc) { 1655 llvm::FoldingSetNodeID ID; 1656 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 1657 SizeExpr); 1658 1659 void *InsertPos = 0; 1660 DependentSizedExtVectorType *Canon 1661 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 1662 DependentSizedExtVectorType *New; 1663 if (Canon) { 1664 // We already have a canonical version of this array type; use it as 1665 // the canonical type for a newly-built type. 1666 New = new (*this, TypeAlignment) 1667 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 1668 SizeExpr, AttrLoc); 1669 } else { 1670 QualType CanonVecTy = getCanonicalType(vecType); 1671 if (CanonVecTy == vecType) { 1672 New = new (*this, TypeAlignment) 1673 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 1674 AttrLoc); 1675 1676 DependentSizedExtVectorType *CanonCheck 1677 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 1678 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 1679 (void)CanonCheck; 1680 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 1681 } else { 1682 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 1683 SourceLocation()); 1684 New = new (*this, TypeAlignment) 1685 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc); 1686 } 1687 } 1688 1689 Types.push_back(New); 1690 return QualType(New, 0); 1691} 1692 1693/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 1694/// 1695QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, 1696 const FunctionType::ExtInfo &Info) { 1697 const CallingConv CallConv = Info.getCC(); 1698 // Unique functions, to guarantee there is only one function of a particular 1699 // structure. 1700 llvm::FoldingSetNodeID ID; 1701 FunctionNoProtoType::Profile(ID, ResultTy, Info); 1702 1703 void *InsertPos = 0; 1704 if (FunctionNoProtoType *FT = 1705 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 1706 return QualType(FT, 0); 1707 1708 QualType Canonical; 1709 if (!ResultTy.isCanonical() || 1710 getCanonicalCallConv(CallConv) != CallConv) { 1711 Canonical = 1712 getFunctionNoProtoType(getCanonicalType(ResultTy), 1713 Info.withCallingConv(getCanonicalCallConv(CallConv))); 1714 1715 // Get the new insert position for the node we care about. 1716 FunctionNoProtoType *NewIP = 1717 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 1718 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1719 } 1720 1721 FunctionNoProtoType *New = new (*this, TypeAlignment) 1722 FunctionNoProtoType(ResultTy, Canonical, Info); 1723 Types.push_back(New); 1724 FunctionNoProtoTypes.InsertNode(New, InsertPos); 1725 return QualType(New, 0); 1726} 1727 1728/// getFunctionType - Return a normal function type with a typed argument 1729/// list. isVariadic indicates whether the argument list includes '...'. 1730QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray, 1731 unsigned NumArgs, bool isVariadic, 1732 unsigned TypeQuals, bool hasExceptionSpec, 1733 bool hasAnyExceptionSpec, unsigned NumExs, 1734 const QualType *ExArray, 1735 const FunctionType::ExtInfo &Info) { 1736 const CallingConv CallConv= Info.getCC(); 1737 // Unique functions, to guarantee there is only one function of a particular 1738 // structure. 1739 llvm::FoldingSetNodeID ID; 1740 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic, 1741 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec, 1742 NumExs, ExArray, Info); 1743 1744 void *InsertPos = 0; 1745 if (FunctionProtoType *FTP = 1746 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 1747 return QualType(FTP, 0); 1748 1749 // Determine whether the type being created is already canonical or not. 1750 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical(); 1751 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 1752 if (!ArgArray[i].isCanonicalAsParam()) 1753 isCanonical = false; 1754 1755 // If this type isn't canonical, get the canonical version of it. 1756 // The exception spec is not part of the canonical type. 1757 QualType Canonical; 1758 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) { 1759 llvm::SmallVector<QualType, 16> CanonicalArgs; 1760 CanonicalArgs.reserve(NumArgs); 1761 for (unsigned i = 0; i != NumArgs; ++i) 1762 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 1763 1764 Canonical = getFunctionType(getCanonicalType(ResultTy), 1765 CanonicalArgs.data(), NumArgs, 1766 isVariadic, TypeQuals, false, 1767 false, 0, 0, 1768 Info.withCallingConv(getCanonicalCallConv(CallConv))); 1769 1770 // Get the new insert position for the node we care about. 1771 FunctionProtoType *NewIP = 1772 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 1773 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1774 } 1775 1776 // FunctionProtoType objects are allocated with extra bytes after them 1777 // for two variable size arrays (for parameter and exception types) at the 1778 // end of them. 1779 FunctionProtoType *FTP = 1780 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) + 1781 NumArgs*sizeof(QualType) + 1782 NumExs*sizeof(QualType), TypeAlignment); 1783 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic, 1784 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec, 1785 ExArray, NumExs, Canonical, Info); 1786 Types.push_back(FTP); 1787 FunctionProtoTypes.InsertNode(FTP, InsertPos); 1788 return QualType(FTP, 0); 1789} 1790 1791#ifndef NDEBUG 1792static bool NeedsInjectedClassNameType(const RecordDecl *D) { 1793 if (!isa<CXXRecordDecl>(D)) return false; 1794 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D); 1795 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 1796 return true; 1797 if (RD->getDescribedClassTemplate() && 1798 !isa<ClassTemplateSpecializationDecl>(RD)) 1799 return true; 1800 return false; 1801} 1802#endif 1803 1804/// getInjectedClassNameType - Return the unique reference to the 1805/// injected class name type for the specified templated declaration. 1806QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 1807 QualType TST) { 1808 assert(NeedsInjectedClassNameType(Decl)); 1809 if (Decl->TypeForDecl) { 1810 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 1811 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) { 1812 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 1813 Decl->TypeForDecl = PrevDecl->TypeForDecl; 1814 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 1815 } else { 1816 Decl->TypeForDecl = 1817 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 1818 Types.push_back(Decl->TypeForDecl); 1819 } 1820 return QualType(Decl->TypeForDecl, 0); 1821} 1822 1823/// getTypeDeclType - Return the unique reference to the type for the 1824/// specified type declaration. 1825QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) { 1826 assert(Decl && "Passed null for Decl param"); 1827 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 1828 1829 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl)) 1830 return getTypedefType(Typedef); 1831 1832 assert(!isa<TemplateTypeParmDecl>(Decl) && 1833 "Template type parameter types are always available."); 1834 1835 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) { 1836 assert(!Record->getPreviousDeclaration() && 1837 "struct/union has previous declaration"); 1838 assert(!NeedsInjectedClassNameType(Record)); 1839 return getRecordType(Record); 1840 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) { 1841 assert(!Enum->getPreviousDeclaration() && 1842 "enum has previous declaration"); 1843 return getEnumType(Enum); 1844 } else if (const UnresolvedUsingTypenameDecl *Using = 1845 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 1846 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using); 1847 } else 1848 llvm_unreachable("TypeDecl without a type?"); 1849 1850 Types.push_back(Decl->TypeForDecl); 1851 return QualType(Decl->TypeForDecl, 0); 1852} 1853 1854/// getTypedefType - Return the unique reference to the type for the 1855/// specified typename decl. 1856QualType 1857ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) { 1858 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1859 1860 if (Canonical.isNull()) 1861 Canonical = getCanonicalType(Decl->getUnderlyingType()); 1862 Decl->TypeForDecl = new(*this, TypeAlignment) 1863 TypedefType(Type::Typedef, Decl, Canonical); 1864 Types.push_back(Decl->TypeForDecl); 1865 return QualType(Decl->TypeForDecl, 0); 1866} 1867 1868QualType ASTContext::getRecordType(const RecordDecl *Decl) { 1869 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1870 1871 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration()) 1872 if (PrevDecl->TypeForDecl) 1873 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 1874 1875 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl); 1876 Types.push_back(Decl->TypeForDecl); 1877 return QualType(Decl->TypeForDecl, 0); 1878} 1879 1880QualType ASTContext::getEnumType(const EnumDecl *Decl) { 1881 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1882 1883 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration()) 1884 if (PrevDecl->TypeForDecl) 1885 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 1886 1887 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl); 1888 Types.push_back(Decl->TypeForDecl); 1889 return QualType(Decl->TypeForDecl, 0); 1890} 1891 1892/// \brief Retrieve a substitution-result type. 1893QualType 1894ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 1895 QualType Replacement) { 1896 assert(Replacement.isCanonical() 1897 && "replacement types must always be canonical"); 1898 1899 llvm::FoldingSetNodeID ID; 1900 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 1901 void *InsertPos = 0; 1902 SubstTemplateTypeParmType *SubstParm 1903 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 1904 1905 if (!SubstParm) { 1906 SubstParm = new (*this, TypeAlignment) 1907 SubstTemplateTypeParmType(Parm, Replacement); 1908 Types.push_back(SubstParm); 1909 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 1910 } 1911 1912 return QualType(SubstParm, 0); 1913} 1914 1915/// \brief Retrieve the template type parameter type for a template 1916/// parameter or parameter pack with the given depth, index, and (optionally) 1917/// name. 1918QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 1919 bool ParameterPack, 1920 IdentifierInfo *Name) { 1921 llvm::FoldingSetNodeID ID; 1922 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name); 1923 void *InsertPos = 0; 1924 TemplateTypeParmType *TypeParm 1925 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 1926 1927 if (TypeParm) 1928 return QualType(TypeParm, 0); 1929 1930 if (Name) { 1931 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 1932 TypeParm = new (*this, TypeAlignment) 1933 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon); 1934 1935 TemplateTypeParmType *TypeCheck 1936 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 1937 assert(!TypeCheck && "Template type parameter canonical type broken"); 1938 (void)TypeCheck; 1939 } else 1940 TypeParm = new (*this, TypeAlignment) 1941 TemplateTypeParmType(Depth, Index, ParameterPack); 1942 1943 Types.push_back(TypeParm); 1944 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 1945 1946 return QualType(TypeParm, 0); 1947} 1948 1949TypeSourceInfo * 1950ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 1951 SourceLocation NameLoc, 1952 const TemplateArgumentListInfo &Args, 1953 QualType CanonType) { 1954 QualType TST = getTemplateSpecializationType(Name, Args, CanonType); 1955 1956 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 1957 TemplateSpecializationTypeLoc TL 1958 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc()); 1959 TL.setTemplateNameLoc(NameLoc); 1960 TL.setLAngleLoc(Args.getLAngleLoc()); 1961 TL.setRAngleLoc(Args.getRAngleLoc()); 1962 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 1963 TL.setArgLocInfo(i, Args[i].getLocInfo()); 1964 return DI; 1965} 1966 1967QualType 1968ASTContext::getTemplateSpecializationType(TemplateName Template, 1969 const TemplateArgumentListInfo &Args, 1970 QualType Canon) { 1971 unsigned NumArgs = Args.size(); 1972 1973 llvm::SmallVector<TemplateArgument, 4> ArgVec; 1974 ArgVec.reserve(NumArgs); 1975 for (unsigned i = 0; i != NumArgs; ++i) 1976 ArgVec.push_back(Args[i].getArgument()); 1977 1978 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, 1979 Canon); 1980} 1981 1982QualType 1983ASTContext::getTemplateSpecializationType(TemplateName Template, 1984 const TemplateArgument *Args, 1985 unsigned NumArgs, 1986 QualType Canon) { 1987 if (!Canon.isNull()) 1988 Canon = getCanonicalType(Canon); 1989 else 1990 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs); 1991 1992 // Allocate the (non-canonical) template specialization type, but don't 1993 // try to unique it: these types typically have location information that 1994 // we don't unique and don't want to lose. 1995 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 1996 sizeof(TemplateArgument) * NumArgs), 1997 TypeAlignment); 1998 TemplateSpecializationType *Spec 1999 = new (Mem) TemplateSpecializationType(Template, 2000 Args, NumArgs, 2001 Canon); 2002 2003 Types.push_back(Spec); 2004 return QualType(Spec, 0); 2005} 2006 2007QualType 2008ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template, 2009 const TemplateArgument *Args, 2010 unsigned NumArgs) { 2011 // Build the canonical template specialization type. 2012 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 2013 llvm::SmallVector<TemplateArgument, 4> CanonArgs; 2014 CanonArgs.reserve(NumArgs); 2015 for (unsigned I = 0; I != NumArgs; ++I) 2016 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I])); 2017 2018 // Determine whether this canonical template specialization type already 2019 // exists. 2020 llvm::FoldingSetNodeID ID; 2021 TemplateSpecializationType::Profile(ID, CanonTemplate, 2022 CanonArgs.data(), NumArgs, *this); 2023 2024 void *InsertPos = 0; 2025 TemplateSpecializationType *Spec 2026 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 2027 2028 if (!Spec) { 2029 // Allocate a new canonical template specialization type. 2030 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 2031 sizeof(TemplateArgument) * NumArgs), 2032 TypeAlignment); 2033 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 2034 CanonArgs.data(), NumArgs, 2035 QualType()); 2036 Types.push_back(Spec); 2037 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 2038 } 2039 2040 assert(Spec->isDependentType() && 2041 "Non-dependent template-id type must have a canonical type"); 2042 return QualType(Spec, 0); 2043} 2044 2045QualType 2046ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 2047 NestedNameSpecifier *NNS, 2048 QualType NamedType) { 2049 llvm::FoldingSetNodeID ID; 2050 ElaboratedType::Profile(ID, Keyword, NNS, NamedType); 2051 2052 void *InsertPos = 0; 2053 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 2054 if (T) 2055 return QualType(T, 0); 2056 2057 QualType Canon = NamedType; 2058 if (!Canon.isCanonical()) { 2059 Canon = getCanonicalType(NamedType); 2060 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 2061 assert(!CheckT && "Elaborated canonical type broken"); 2062 (void)CheckT; 2063 } 2064 2065 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon); 2066 Types.push_back(T); 2067 ElaboratedTypes.InsertNode(T, InsertPos); 2068 return QualType(T, 0); 2069} 2070 2071QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 2072 NestedNameSpecifier *NNS, 2073 const IdentifierInfo *Name, 2074 QualType Canon) { 2075 assert(NNS->isDependent() && "nested-name-specifier must be dependent"); 2076 2077 if (Canon.isNull()) { 2078 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 2079 ElaboratedTypeKeyword CanonKeyword = Keyword; 2080 if (Keyword == ETK_None) 2081 CanonKeyword = ETK_Typename; 2082 2083 if (CanonNNS != NNS || CanonKeyword != Keyword) 2084 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name); 2085 } 2086 2087 llvm::FoldingSetNodeID ID; 2088 DependentNameType::Profile(ID, Keyword, NNS, Name); 2089 2090 void *InsertPos = 0; 2091 DependentNameType *T 2092 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 2093 if (T) 2094 return QualType(T, 0); 2095 2096 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon); 2097 Types.push_back(T); 2098 DependentNameTypes.InsertNode(T, InsertPos); 2099 return QualType(T, 0); 2100} 2101 2102QualType 2103ASTContext::getDependentTemplateSpecializationType( 2104 ElaboratedTypeKeyword Keyword, 2105 NestedNameSpecifier *NNS, 2106 const IdentifierInfo *Name, 2107 const TemplateArgumentListInfo &Args) { 2108 // TODO: avoid this copy 2109 llvm::SmallVector<TemplateArgument, 16> ArgCopy; 2110 for (unsigned I = 0, E = Args.size(); I != E; ++I) 2111 ArgCopy.push_back(Args[I].getArgument()); 2112 return getDependentTemplateSpecializationType(Keyword, NNS, Name, 2113 ArgCopy.size(), 2114 ArgCopy.data()); 2115} 2116 2117QualType 2118ASTContext::getDependentTemplateSpecializationType( 2119 ElaboratedTypeKeyword Keyword, 2120 NestedNameSpecifier *NNS, 2121 const IdentifierInfo *Name, 2122 unsigned NumArgs, 2123 const TemplateArgument *Args) { 2124 assert(NNS->isDependent() && "nested-name-specifier must be dependent"); 2125 2126 llvm::FoldingSetNodeID ID; 2127 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 2128 Name, NumArgs, Args); 2129 2130 void *InsertPos = 0; 2131 DependentTemplateSpecializationType *T 2132 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 2133 if (T) 2134 return QualType(T, 0); 2135 2136 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 2137 2138 ElaboratedTypeKeyword CanonKeyword = Keyword; 2139 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 2140 2141 bool AnyNonCanonArgs = false; 2142 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs); 2143 for (unsigned I = 0; I != NumArgs; ++I) { 2144 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]); 2145 if (!CanonArgs[I].structurallyEquals(Args[I])) 2146 AnyNonCanonArgs = true; 2147 } 2148 2149 QualType Canon; 2150 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 2151 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 2152 Name, NumArgs, 2153 CanonArgs.data()); 2154 2155 // Find the insert position again. 2156 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 2157 } 2158 2159 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 2160 sizeof(TemplateArgument) * NumArgs), 2161 TypeAlignment); 2162 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 2163 Name, NumArgs, Args, Canon); 2164 Types.push_back(T); 2165 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 2166 return QualType(T, 0); 2167} 2168 2169/// CmpProtocolNames - Comparison predicate for sorting protocols 2170/// alphabetically. 2171static bool CmpProtocolNames(const ObjCProtocolDecl *LHS, 2172 const ObjCProtocolDecl *RHS) { 2173 return LHS->getDeclName() < RHS->getDeclName(); 2174} 2175 2176static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols, 2177 unsigned NumProtocols) { 2178 if (NumProtocols == 0) return true; 2179 2180 for (unsigned i = 1; i != NumProtocols; ++i) 2181 if (!CmpProtocolNames(Protocols[i-1], Protocols[i])) 2182 return false; 2183 return true; 2184} 2185 2186static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols, 2187 unsigned &NumProtocols) { 2188 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols; 2189 2190 // Sort protocols, keyed by name. 2191 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames); 2192 2193 // Remove duplicates. 2194 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd); 2195 NumProtocols = ProtocolsEnd-Protocols; 2196} 2197 2198QualType ASTContext::getObjCObjectType(QualType BaseType, 2199 ObjCProtocolDecl * const *Protocols, 2200 unsigned NumProtocols) { 2201 // If the base type is an interface and there aren't any protocols 2202 // to add, then the interface type will do just fine. 2203 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType)) 2204 return BaseType; 2205 2206 // Look in the folding set for an existing type. 2207 llvm::FoldingSetNodeID ID; 2208 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols); 2209 void *InsertPos = 0; 2210 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 2211 return QualType(QT, 0); 2212 2213 // Build the canonical type, which has the canonical base type and 2214 // a sorted-and-uniqued list of protocols. 2215 QualType Canonical; 2216 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols); 2217 if (!ProtocolsSorted || !BaseType.isCanonical()) { 2218 if (!ProtocolsSorted) { 2219 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols, 2220 Protocols + NumProtocols); 2221 unsigned UniqueCount = NumProtocols; 2222 2223 SortAndUniqueProtocols(&Sorted[0], UniqueCount); 2224 Canonical = getObjCObjectType(getCanonicalType(BaseType), 2225 &Sorted[0], UniqueCount); 2226 } else { 2227 Canonical = getObjCObjectType(getCanonicalType(BaseType), 2228 Protocols, NumProtocols); 2229 } 2230 2231 // Regenerate InsertPos. 2232 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 2233 } 2234 2235 unsigned Size = sizeof(ObjCObjectTypeImpl); 2236 Size += NumProtocols * sizeof(ObjCProtocolDecl *); 2237 void *Mem = Allocate(Size, TypeAlignment); 2238 ObjCObjectTypeImpl *T = 2239 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols); 2240 2241 Types.push_back(T); 2242 ObjCObjectTypes.InsertNode(T, InsertPos); 2243 return QualType(T, 0); 2244} 2245 2246/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 2247/// the given object type. 2248QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) { 2249 llvm::FoldingSetNodeID ID; 2250 ObjCObjectPointerType::Profile(ID, ObjectT); 2251 2252 void *InsertPos = 0; 2253 if (ObjCObjectPointerType *QT = 2254 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2255 return QualType(QT, 0); 2256 2257 // Find the canonical object type. 2258 QualType Canonical; 2259 if (!ObjectT.isCanonical()) { 2260 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 2261 2262 // Regenerate InsertPos. 2263 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2264 } 2265 2266 // No match. 2267 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 2268 ObjCObjectPointerType *QType = 2269 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 2270 2271 Types.push_back(QType); 2272 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 2273 return QualType(QType, 0); 2274} 2275 2276/// getObjCInterfaceType - Return the unique reference to the type for the 2277/// specified ObjC interface decl. The list of protocols is optional. 2278QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) { 2279 if (Decl->TypeForDecl) 2280 return QualType(Decl->TypeForDecl, 0); 2281 2282 // FIXME: redeclarations? 2283 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 2284 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl); 2285 Decl->TypeForDecl = T; 2286 Types.push_back(T); 2287 return QualType(T, 0); 2288} 2289 2290/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 2291/// TypeOfExprType AST's (since expression's are never shared). For example, 2292/// multiple declarations that refer to "typeof(x)" all contain different 2293/// DeclRefExpr's. This doesn't effect the type checker, since it operates 2294/// on canonical type's (which are always unique). 2295QualType ASTContext::getTypeOfExprType(Expr *tofExpr) { 2296 TypeOfExprType *toe; 2297 if (tofExpr->isTypeDependent()) { 2298 llvm::FoldingSetNodeID ID; 2299 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 2300 2301 void *InsertPos = 0; 2302 DependentTypeOfExprType *Canon 2303 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 2304 if (Canon) { 2305 // We already have a "canonical" version of an identical, dependent 2306 // typeof(expr) type. Use that as our canonical type. 2307 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 2308 QualType((TypeOfExprType*)Canon, 0)); 2309 } 2310 else { 2311 // Build a new, canonical typeof(expr) type. 2312 Canon 2313 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 2314 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 2315 toe = Canon; 2316 } 2317 } else { 2318 QualType Canonical = getCanonicalType(tofExpr->getType()); 2319 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 2320 } 2321 Types.push_back(toe); 2322 return QualType(toe, 0); 2323} 2324 2325/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 2326/// TypeOfType AST's. The only motivation to unique these nodes would be 2327/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 2328/// an issue. This doesn't effect the type checker, since it operates 2329/// on canonical type's (which are always unique). 2330QualType ASTContext::getTypeOfType(QualType tofType) { 2331 QualType Canonical = getCanonicalType(tofType); 2332 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 2333 Types.push_back(tot); 2334 return QualType(tot, 0); 2335} 2336 2337/// getDecltypeForExpr - Given an expr, will return the decltype for that 2338/// expression, according to the rules in C++0x [dcl.type.simple]p4 2339static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) { 2340 if (e->isTypeDependent()) 2341 return Context.DependentTy; 2342 2343 // If e is an id expression or a class member access, decltype(e) is defined 2344 // as the type of the entity named by e. 2345 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) { 2346 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) 2347 return VD->getType(); 2348 } 2349 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) { 2350 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2351 return FD->getType(); 2352 } 2353 // If e is a function call or an invocation of an overloaded operator, 2354 // (parentheses around e are ignored), decltype(e) is defined as the 2355 // return type of that function. 2356 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens())) 2357 return CE->getCallReturnType(); 2358 2359 QualType T = e->getType(); 2360 2361 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is 2362 // defined as T&, otherwise decltype(e) is defined as T. 2363 if (e->isLvalue(Context) == Expr::LV_Valid) 2364 T = Context.getLValueReferenceType(T); 2365 2366 return T; 2367} 2368 2369/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique 2370/// DecltypeType AST's. The only motivation to unique these nodes would be 2371/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be 2372/// an issue. This doesn't effect the type checker, since it operates 2373/// on canonical type's (which are always unique). 2374QualType ASTContext::getDecltypeType(Expr *e) { 2375 DecltypeType *dt; 2376 if (e->isTypeDependent()) { 2377 llvm::FoldingSetNodeID ID; 2378 DependentDecltypeType::Profile(ID, *this, e); 2379 2380 void *InsertPos = 0; 2381 DependentDecltypeType *Canon 2382 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 2383 if (Canon) { 2384 // We already have a "canonical" version of an equivalent, dependent 2385 // decltype type. Use that as our canonical type. 2386 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy, 2387 QualType((DecltypeType*)Canon, 0)); 2388 } 2389 else { 2390 // Build a new, canonical typeof(expr) type. 2391 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 2392 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 2393 dt = Canon; 2394 } 2395 } else { 2396 QualType T = getDecltypeForExpr(e, *this); 2397 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T)); 2398 } 2399 Types.push_back(dt); 2400 return QualType(dt, 0); 2401} 2402 2403/// getTagDeclType - Return the unique reference to the type for the 2404/// specified TagDecl (struct/union/class/enum) decl. 2405QualType ASTContext::getTagDeclType(const TagDecl *Decl) { 2406 assert (Decl); 2407 // FIXME: What is the design on getTagDeclType when it requires casting 2408 // away const? mutable? 2409 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 2410} 2411 2412/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 2413/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 2414/// needs to agree with the definition in <stddef.h>. 2415CanQualType ASTContext::getSizeType() const { 2416 return getFromTargetType(Target.getSizeType()); 2417} 2418 2419/// getSignedWCharType - Return the type of "signed wchar_t". 2420/// Used when in C++, as a GCC extension. 2421QualType ASTContext::getSignedWCharType() const { 2422 // FIXME: derive from "Target" ? 2423 return WCharTy; 2424} 2425 2426/// getUnsignedWCharType - Return the type of "unsigned wchar_t". 2427/// Used when in C++, as a GCC extension. 2428QualType ASTContext::getUnsignedWCharType() const { 2429 // FIXME: derive from "Target" ? 2430 return UnsignedIntTy; 2431} 2432 2433/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?) 2434/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 2435QualType ASTContext::getPointerDiffType() const { 2436 return getFromTargetType(Target.getPtrDiffType(0)); 2437} 2438 2439//===----------------------------------------------------------------------===// 2440// Type Operators 2441//===----------------------------------------------------------------------===// 2442 2443CanQualType ASTContext::getCanonicalParamType(QualType T) { 2444 // Push qualifiers into arrays, and then discard any remaining 2445 // qualifiers. 2446 T = getCanonicalType(T); 2447 T = getVariableArrayDecayedType(T); 2448 const Type *Ty = T.getTypePtr(); 2449 QualType Result; 2450 if (isa<ArrayType>(Ty)) { 2451 Result = getArrayDecayedType(QualType(Ty,0)); 2452 } else if (isa<FunctionType>(Ty)) { 2453 Result = getPointerType(QualType(Ty, 0)); 2454 } else { 2455 Result = QualType(Ty, 0); 2456 } 2457 2458 return CanQualType::CreateUnsafe(Result); 2459} 2460 2461/// getCanonicalType - Return the canonical (structural) type corresponding to 2462/// the specified potentially non-canonical type. The non-canonical version 2463/// of a type may have many "decorated" versions of types. Decorators can 2464/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed 2465/// to be free of any of these, allowing two canonical types to be compared 2466/// for exact equality with a simple pointer comparison. 2467CanQualType ASTContext::getCanonicalType(QualType T) { 2468 QualifierCollector Quals; 2469 const Type *Ptr = Quals.strip(T); 2470 QualType CanType = Ptr->getCanonicalTypeInternal(); 2471 2472 // The canonical internal type will be the canonical type *except* 2473 // that we push type qualifiers down through array types. 2474 2475 // If there are no new qualifiers to push down, stop here. 2476 if (!Quals.hasQualifiers()) 2477 return CanQualType::CreateUnsafe(CanType); 2478 2479 // If the type qualifiers are on an array type, get the canonical 2480 // type of the array with the qualifiers applied to the element 2481 // type. 2482 ArrayType *AT = dyn_cast<ArrayType>(CanType); 2483 if (!AT) 2484 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals)); 2485 2486 // Get the canonical version of the element with the extra qualifiers on it. 2487 // This can recursively sink qualifiers through multiple levels of arrays. 2488 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals); 2489 NewEltTy = getCanonicalType(NewEltTy); 2490 2491 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 2492 return CanQualType::CreateUnsafe( 2493 getConstantArrayType(NewEltTy, CAT->getSize(), 2494 CAT->getSizeModifier(), 2495 CAT->getIndexTypeCVRQualifiers())); 2496 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) 2497 return CanQualType::CreateUnsafe( 2498 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(), 2499 IAT->getIndexTypeCVRQualifiers())); 2500 2501 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT)) 2502 return CanQualType::CreateUnsafe( 2503 getDependentSizedArrayType(NewEltTy, 2504 DSAT->getSizeExpr() ? 2505 DSAT->getSizeExpr()->Retain() : 0, 2506 DSAT->getSizeModifier(), 2507 DSAT->getIndexTypeCVRQualifiers(), 2508 DSAT->getBracketsRange())->getCanonicalTypeInternal()); 2509 2510 VariableArrayType *VAT = cast<VariableArrayType>(AT); 2511 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy, 2512 VAT->getSizeExpr() ? 2513 VAT->getSizeExpr()->Retain() : 0, 2514 VAT->getSizeModifier(), 2515 VAT->getIndexTypeCVRQualifiers(), 2516 VAT->getBracketsRange())); 2517} 2518 2519QualType ASTContext::getUnqualifiedArrayType(QualType T, 2520 Qualifiers &Quals) { 2521 Quals = T.getQualifiers(); 2522 const ArrayType *AT = getAsArrayType(T); 2523 if (!AT) { 2524 return T.getUnqualifiedType(); 2525 } 2526 2527 QualType Elt = AT->getElementType(); 2528 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals); 2529 if (Elt == UnqualElt) 2530 return T; 2531 2532 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { 2533 return getConstantArrayType(UnqualElt, CAT->getSize(), 2534 CAT->getSizeModifier(), 0); 2535 } 2536 2537 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 2538 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0); 2539 } 2540 2541 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) { 2542 return getVariableArrayType(UnqualElt, 2543 VAT->getSizeExpr() ? 2544 VAT->getSizeExpr()->Retain() : 0, 2545 VAT->getSizeModifier(), 2546 VAT->getIndexTypeCVRQualifiers(), 2547 VAT->getBracketsRange()); 2548 } 2549 2550 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT); 2551 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(), 2552 DSAT->getSizeModifier(), 0, 2553 SourceRange()); 2554} 2555 2556/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 2557/// may be similar (C++ 4.4), replaces T1 and T2 with the type that 2558/// they point to and return true. If T1 and T2 aren't pointer types 2559/// or pointer-to-member types, or if they are not similar at this 2560/// level, returns false and leaves T1 and T2 unchanged. Top-level 2561/// qualifiers on T1 and T2 are ignored. This function will typically 2562/// be called in a loop that successively "unwraps" pointer and 2563/// pointer-to-member types to compare them at each level. 2564bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) { 2565 const PointerType *T1PtrType = T1->getAs<PointerType>(), 2566 *T2PtrType = T2->getAs<PointerType>(); 2567 if (T1PtrType && T2PtrType) { 2568 T1 = T1PtrType->getPointeeType(); 2569 T2 = T2PtrType->getPointeeType(); 2570 return true; 2571 } 2572 2573 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 2574 *T2MPType = T2->getAs<MemberPointerType>(); 2575 if (T1MPType && T2MPType && 2576 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 2577 QualType(T2MPType->getClass(), 0))) { 2578 T1 = T1MPType->getPointeeType(); 2579 T2 = T2MPType->getPointeeType(); 2580 return true; 2581 } 2582 2583 if (getLangOptions().ObjC1) { 2584 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(), 2585 *T2OPType = T2->getAs<ObjCObjectPointerType>(); 2586 if (T1OPType && T2OPType) { 2587 T1 = T1OPType->getPointeeType(); 2588 T2 = T2OPType->getPointeeType(); 2589 return true; 2590 } 2591 } 2592 2593 // FIXME: Block pointers, too? 2594 2595 return false; 2596} 2597 2598DeclarationNameInfo ASTContext::getNameForTemplate(TemplateName Name, 2599 SourceLocation NameLoc) { 2600 if (TemplateDecl *TD = Name.getAsTemplateDecl()) 2601 // DNInfo work in progress: CHECKME: what about DNLoc? 2602 return DeclarationNameInfo(TD->getDeclName(), NameLoc); 2603 2604 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) { 2605 DeclarationName DName; 2606 if (DTN->isIdentifier()) { 2607 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 2608 return DeclarationNameInfo(DName, NameLoc); 2609 } else { 2610 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 2611 // DNInfo work in progress: FIXME: source locations? 2612 DeclarationNameLoc DNLoc; 2613 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding(); 2614 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding(); 2615 return DeclarationNameInfo(DName, NameLoc, DNLoc); 2616 } 2617 } 2618 2619 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 2620 assert(Storage); 2621 // DNInfo work in progress: CHECKME: what about DNLoc? 2622 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 2623} 2624 2625TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) { 2626 if (TemplateDecl *Template = Name.getAsTemplateDecl()) { 2627 if (TemplateTemplateParmDecl *TTP 2628 = dyn_cast<TemplateTemplateParmDecl>(Template)) 2629 Template = getCanonicalTemplateTemplateParmDecl(TTP); 2630 2631 // The canonical template name is the canonical template declaration. 2632 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 2633 } 2634 2635 assert(!Name.getAsOverloadedTemplate()); 2636 2637 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 2638 assert(DTN && "Non-dependent template names must refer to template decls."); 2639 return DTN->CanonicalTemplateName; 2640} 2641 2642bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 2643 X = getCanonicalTemplateName(X); 2644 Y = getCanonicalTemplateName(Y); 2645 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 2646} 2647 2648TemplateArgument 2649ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) { 2650 switch (Arg.getKind()) { 2651 case TemplateArgument::Null: 2652 return Arg; 2653 2654 case TemplateArgument::Expression: 2655 return Arg; 2656 2657 case TemplateArgument::Declaration: 2658 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl()); 2659 2660 case TemplateArgument::Template: 2661 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 2662 2663 case TemplateArgument::Integral: 2664 return TemplateArgument(*Arg.getAsIntegral(), 2665 getCanonicalType(Arg.getIntegralType())); 2666 2667 case TemplateArgument::Type: 2668 return TemplateArgument(getCanonicalType(Arg.getAsType())); 2669 2670 case TemplateArgument::Pack: { 2671 // FIXME: Allocate in ASTContext 2672 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()]; 2673 unsigned Idx = 0; 2674 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 2675 AEnd = Arg.pack_end(); 2676 A != AEnd; (void)++A, ++Idx) 2677 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 2678 2679 TemplateArgument Result; 2680 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false); 2681 return Result; 2682 } 2683 } 2684 2685 // Silence GCC warning 2686 assert(false && "Unhandled template argument kind"); 2687 return TemplateArgument(); 2688} 2689 2690NestedNameSpecifier * 2691ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) { 2692 if (!NNS) 2693 return 0; 2694 2695 switch (NNS->getKind()) { 2696 case NestedNameSpecifier::Identifier: 2697 // Canonicalize the prefix but keep the identifier the same. 2698 return NestedNameSpecifier::Create(*this, 2699 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 2700 NNS->getAsIdentifier()); 2701 2702 case NestedNameSpecifier::Namespace: 2703 // A namespace is canonical; build a nested-name-specifier with 2704 // this namespace and no prefix. 2705 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace()); 2706 2707 case NestedNameSpecifier::TypeSpec: 2708 case NestedNameSpecifier::TypeSpecWithTemplate: { 2709 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 2710 return NestedNameSpecifier::Create(*this, 0, 2711 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate, 2712 T.getTypePtr()); 2713 } 2714 2715 case NestedNameSpecifier::Global: 2716 // The global specifier is canonical and unique. 2717 return NNS; 2718 } 2719 2720 // Required to silence a GCC warning 2721 return 0; 2722} 2723 2724 2725const ArrayType *ASTContext::getAsArrayType(QualType T) { 2726 // Handle the non-qualified case efficiently. 2727 if (!T.hasLocalQualifiers()) { 2728 // Handle the common positive case fast. 2729 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 2730 return AT; 2731 } 2732 2733 // Handle the common negative case fast. 2734 QualType CType = T->getCanonicalTypeInternal(); 2735 if (!isa<ArrayType>(CType)) 2736 return 0; 2737 2738 // Apply any qualifiers from the array type to the element type. This 2739 // implements C99 6.7.3p8: "If the specification of an array type includes 2740 // any type qualifiers, the element type is so qualified, not the array type." 2741 2742 // If we get here, we either have type qualifiers on the type, or we have 2743 // sugar such as a typedef in the way. If we have type qualifiers on the type 2744 // we must propagate them down into the element type. 2745 2746 QualifierCollector Qs; 2747 const Type *Ty = Qs.strip(T.getDesugaredType()); 2748 2749 // If we have a simple case, just return now. 2750 const ArrayType *ATy = dyn_cast<ArrayType>(Ty); 2751 if (ATy == 0 || Qs.empty()) 2752 return ATy; 2753 2754 // Otherwise, we have an array and we have qualifiers on it. Push the 2755 // qualifiers into the array element type and return a new array type. 2756 // Get the canonical version of the element with the extra qualifiers on it. 2757 // This can recursively sink qualifiers through multiple levels of arrays. 2758 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs); 2759 2760 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy)) 2761 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 2762 CAT->getSizeModifier(), 2763 CAT->getIndexTypeCVRQualifiers())); 2764 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy)) 2765 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 2766 IAT->getSizeModifier(), 2767 IAT->getIndexTypeCVRQualifiers())); 2768 2769 if (const DependentSizedArrayType *DSAT 2770 = dyn_cast<DependentSizedArrayType>(ATy)) 2771 return cast<ArrayType>( 2772 getDependentSizedArrayType(NewEltTy, 2773 DSAT->getSizeExpr() ? 2774 DSAT->getSizeExpr()->Retain() : 0, 2775 DSAT->getSizeModifier(), 2776 DSAT->getIndexTypeCVRQualifiers(), 2777 DSAT->getBracketsRange())); 2778 2779 const VariableArrayType *VAT = cast<VariableArrayType>(ATy); 2780 return cast<ArrayType>(getVariableArrayType(NewEltTy, 2781 VAT->getSizeExpr() ? 2782 VAT->getSizeExpr()->Retain() : 0, 2783 VAT->getSizeModifier(), 2784 VAT->getIndexTypeCVRQualifiers(), 2785 VAT->getBracketsRange())); 2786} 2787 2788/// getArrayDecayedType - Return the properly qualified result of decaying the 2789/// specified array type to a pointer. This operation is non-trivial when 2790/// handling typedefs etc. The canonical type of "T" must be an array type, 2791/// this returns a pointer to a properly qualified element of the array. 2792/// 2793/// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 2794QualType ASTContext::getArrayDecayedType(QualType Ty) { 2795 // Get the element type with 'getAsArrayType' so that we don't lose any 2796 // typedefs in the element type of the array. This also handles propagation 2797 // of type qualifiers from the array type into the element type if present 2798 // (C99 6.7.3p8). 2799 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 2800 assert(PrettyArrayType && "Not an array type!"); 2801 2802 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 2803 2804 // int x[restrict 4] -> int *restrict 2805 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers()); 2806} 2807 2808QualType ASTContext::getBaseElementType(QualType QT) { 2809 QualifierCollector Qs; 2810 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0))) 2811 QT = AT->getElementType(); 2812 return Qs.apply(QT); 2813} 2814 2815QualType ASTContext::getBaseElementType(const ArrayType *AT) { 2816 QualType ElemTy = AT->getElementType(); 2817 2818 if (const ArrayType *AT = getAsArrayType(ElemTy)) 2819 return getBaseElementType(AT); 2820 2821 return ElemTy; 2822} 2823 2824/// getConstantArrayElementCount - Returns number of constant array elements. 2825uint64_t 2826ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 2827 uint64_t ElementCount = 1; 2828 do { 2829 ElementCount *= CA->getSize().getZExtValue(); 2830 CA = dyn_cast<ConstantArrayType>(CA->getElementType()); 2831 } while (CA); 2832 return ElementCount; 2833} 2834 2835/// getFloatingRank - Return a relative rank for floating point types. 2836/// This routine will assert if passed a built-in type that isn't a float. 2837static FloatingRank getFloatingRank(QualType T) { 2838 if (const ComplexType *CT = T->getAs<ComplexType>()) 2839 return getFloatingRank(CT->getElementType()); 2840 2841 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type"); 2842 switch (T->getAs<BuiltinType>()->getKind()) { 2843 default: assert(0 && "getFloatingRank(): not a floating type"); 2844 case BuiltinType::Float: return FloatRank; 2845 case BuiltinType::Double: return DoubleRank; 2846 case BuiltinType::LongDouble: return LongDoubleRank; 2847 } 2848} 2849 2850/// getFloatingTypeOfSizeWithinDomain - Returns a real floating 2851/// point or a complex type (based on typeDomain/typeSize). 2852/// 'typeDomain' is a real floating point or complex type. 2853/// 'typeSize' is a real floating point or complex type. 2854QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 2855 QualType Domain) const { 2856 FloatingRank EltRank = getFloatingRank(Size); 2857 if (Domain->isComplexType()) { 2858 switch (EltRank) { 2859 default: assert(0 && "getFloatingRank(): illegal value for rank"); 2860 case FloatRank: return FloatComplexTy; 2861 case DoubleRank: return DoubleComplexTy; 2862 case LongDoubleRank: return LongDoubleComplexTy; 2863 } 2864 } 2865 2866 assert(Domain->isRealFloatingType() && "Unknown domain!"); 2867 switch (EltRank) { 2868 default: assert(0 && "getFloatingRank(): illegal value for rank"); 2869 case FloatRank: return FloatTy; 2870 case DoubleRank: return DoubleTy; 2871 case LongDoubleRank: return LongDoubleTy; 2872 } 2873} 2874 2875/// getFloatingTypeOrder - Compare the rank of the two specified floating 2876/// point types, ignoring the domain of the type (i.e. 'double' == 2877/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 2878/// LHS < RHS, return -1. 2879int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) { 2880 FloatingRank LHSR = getFloatingRank(LHS); 2881 FloatingRank RHSR = getFloatingRank(RHS); 2882 2883 if (LHSR == RHSR) 2884 return 0; 2885 if (LHSR > RHSR) 2886 return 1; 2887 return -1; 2888} 2889 2890/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 2891/// routine will assert if passed a built-in type that isn't an integer or enum, 2892/// or if it is not canonicalized. 2893unsigned ASTContext::getIntegerRank(Type *T) { 2894 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 2895 if (EnumType* ET = dyn_cast<EnumType>(T)) 2896 T = ET->getDecl()->getPromotionType().getTypePtr(); 2897 2898 if (T->isSpecificBuiltinType(BuiltinType::WChar)) 2899 T = getFromTargetType(Target.getWCharType()).getTypePtr(); 2900 2901 if (T->isSpecificBuiltinType(BuiltinType::Char16)) 2902 T = getFromTargetType(Target.getChar16Type()).getTypePtr(); 2903 2904 if (T->isSpecificBuiltinType(BuiltinType::Char32)) 2905 T = getFromTargetType(Target.getChar32Type()).getTypePtr(); 2906 2907 switch (cast<BuiltinType>(T)->getKind()) { 2908 default: assert(0 && "getIntegerRank(): not a built-in integer"); 2909 case BuiltinType::Bool: 2910 return 1 + (getIntWidth(BoolTy) << 3); 2911 case BuiltinType::Char_S: 2912 case BuiltinType::Char_U: 2913 case BuiltinType::SChar: 2914 case BuiltinType::UChar: 2915 return 2 + (getIntWidth(CharTy) << 3); 2916 case BuiltinType::Short: 2917 case BuiltinType::UShort: 2918 return 3 + (getIntWidth(ShortTy) << 3); 2919 case BuiltinType::Int: 2920 case BuiltinType::UInt: 2921 return 4 + (getIntWidth(IntTy) << 3); 2922 case BuiltinType::Long: 2923 case BuiltinType::ULong: 2924 return 5 + (getIntWidth(LongTy) << 3); 2925 case BuiltinType::LongLong: 2926 case BuiltinType::ULongLong: 2927 return 6 + (getIntWidth(LongLongTy) << 3); 2928 case BuiltinType::Int128: 2929 case BuiltinType::UInt128: 2930 return 7 + (getIntWidth(Int128Ty) << 3); 2931 } 2932} 2933 2934/// \brief Whether this is a promotable bitfield reference according 2935/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 2936/// 2937/// \returns the type this bit-field will promote to, or NULL if no 2938/// promotion occurs. 2939QualType ASTContext::isPromotableBitField(Expr *E) { 2940 if (E->isTypeDependent() || E->isValueDependent()) 2941 return QualType(); 2942 2943 FieldDecl *Field = E->getBitField(); 2944 if (!Field) 2945 return QualType(); 2946 2947 QualType FT = Field->getType(); 2948 2949 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this); 2950 uint64_t BitWidth = BitWidthAP.getZExtValue(); 2951 uint64_t IntSize = getTypeSize(IntTy); 2952 // GCC extension compatibility: if the bit-field size is less than or equal 2953 // to the size of int, it gets promoted no matter what its type is. 2954 // For instance, unsigned long bf : 4 gets promoted to signed int. 2955 if (BitWidth < IntSize) 2956 return IntTy; 2957 2958 if (BitWidth == IntSize) 2959 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 2960 2961 // Types bigger than int are not subject to promotions, and therefore act 2962 // like the base type. 2963 // FIXME: This doesn't quite match what gcc does, but what gcc does here 2964 // is ridiculous. 2965 return QualType(); 2966} 2967 2968/// getPromotedIntegerType - Returns the type that Promotable will 2969/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 2970/// integer type. 2971QualType ASTContext::getPromotedIntegerType(QualType Promotable) { 2972 assert(!Promotable.isNull()); 2973 assert(Promotable->isPromotableIntegerType()); 2974 if (const EnumType *ET = Promotable->getAs<EnumType>()) 2975 return ET->getDecl()->getPromotionType(); 2976 if (Promotable->isSignedIntegerType()) 2977 return IntTy; 2978 uint64_t PromotableSize = getTypeSize(Promotable); 2979 uint64_t IntSize = getTypeSize(IntTy); 2980 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 2981 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 2982} 2983 2984/// getIntegerTypeOrder - Returns the highest ranked integer type: 2985/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 2986/// LHS < RHS, return -1. 2987int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) { 2988 Type *LHSC = getCanonicalType(LHS).getTypePtr(); 2989 Type *RHSC = getCanonicalType(RHS).getTypePtr(); 2990 if (LHSC == RHSC) return 0; 2991 2992 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 2993 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 2994 2995 unsigned LHSRank = getIntegerRank(LHSC); 2996 unsigned RHSRank = getIntegerRank(RHSC); 2997 2998 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 2999 if (LHSRank == RHSRank) return 0; 3000 return LHSRank > RHSRank ? 1 : -1; 3001 } 3002 3003 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 3004 if (LHSUnsigned) { 3005 // If the unsigned [LHS] type is larger, return it. 3006 if (LHSRank >= RHSRank) 3007 return 1; 3008 3009 // If the signed type can represent all values of the unsigned type, it 3010 // wins. Because we are dealing with 2's complement and types that are 3011 // powers of two larger than each other, this is always safe. 3012 return -1; 3013 } 3014 3015 // If the unsigned [RHS] type is larger, return it. 3016 if (RHSRank >= LHSRank) 3017 return -1; 3018 3019 // If the signed type can represent all values of the unsigned type, it 3020 // wins. Because we are dealing with 2's complement and types that are 3021 // powers of two larger than each other, this is always safe. 3022 return 1; 3023} 3024 3025static RecordDecl * 3026CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC, 3027 SourceLocation L, IdentifierInfo *Id) { 3028 if (Ctx.getLangOptions().CPlusPlus) 3029 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id); 3030 else 3031 return RecordDecl::Create(Ctx, TK, DC, L, Id); 3032} 3033 3034// getCFConstantStringType - Return the type used for constant CFStrings. 3035QualType ASTContext::getCFConstantStringType() { 3036 if (!CFConstantStringTypeDecl) { 3037 CFConstantStringTypeDecl = 3038 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 3039 &Idents.get("NSConstantString")); 3040 CFConstantStringTypeDecl->startDefinition(); 3041 3042 QualType FieldTypes[4]; 3043 3044 // const int *isa; 3045 FieldTypes[0] = getPointerType(IntTy.withConst()); 3046 // int flags; 3047 FieldTypes[1] = IntTy; 3048 // const char *str; 3049 FieldTypes[2] = getPointerType(CharTy.withConst()); 3050 // long length; 3051 FieldTypes[3] = LongTy; 3052 3053 // Create fields 3054 for (unsigned i = 0; i < 4; ++i) { 3055 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl, 3056 SourceLocation(), 0, 3057 FieldTypes[i], /*TInfo=*/0, 3058 /*BitWidth=*/0, 3059 /*Mutable=*/false); 3060 Field->setAccess(AS_public); 3061 CFConstantStringTypeDecl->addDecl(Field); 3062 } 3063 3064 CFConstantStringTypeDecl->completeDefinition(); 3065 } 3066 3067 return getTagDeclType(CFConstantStringTypeDecl); 3068} 3069 3070void ASTContext::setCFConstantStringType(QualType T) { 3071 const RecordType *Rec = T->getAs<RecordType>(); 3072 assert(Rec && "Invalid CFConstantStringType"); 3073 CFConstantStringTypeDecl = Rec->getDecl(); 3074} 3075 3076// getNSConstantStringType - Return the type used for constant NSStrings. 3077QualType ASTContext::getNSConstantStringType() { 3078 if (!NSConstantStringTypeDecl) { 3079 NSConstantStringTypeDecl = 3080 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 3081 &Idents.get("__builtin_NSString")); 3082 NSConstantStringTypeDecl->startDefinition(); 3083 3084 QualType FieldTypes[3]; 3085 3086 // const int *isa; 3087 FieldTypes[0] = getPointerType(IntTy.withConst()); 3088 // const char *str; 3089 FieldTypes[1] = getPointerType(CharTy.withConst()); 3090 // unsigned int length; 3091 FieldTypes[2] = UnsignedIntTy; 3092 3093 // Create fields 3094 for (unsigned i = 0; i < 3; ++i) { 3095 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl, 3096 SourceLocation(), 0, 3097 FieldTypes[i], /*TInfo=*/0, 3098 /*BitWidth=*/0, 3099 /*Mutable=*/false); 3100 Field->setAccess(AS_public); 3101 NSConstantStringTypeDecl->addDecl(Field); 3102 } 3103 3104 NSConstantStringTypeDecl->completeDefinition(); 3105 } 3106 3107 return getTagDeclType(NSConstantStringTypeDecl); 3108} 3109 3110void ASTContext::setNSConstantStringType(QualType T) { 3111 const RecordType *Rec = T->getAs<RecordType>(); 3112 assert(Rec && "Invalid NSConstantStringType"); 3113 NSConstantStringTypeDecl = Rec->getDecl(); 3114} 3115 3116QualType ASTContext::getObjCFastEnumerationStateType() { 3117 if (!ObjCFastEnumerationStateTypeDecl) { 3118 ObjCFastEnumerationStateTypeDecl = 3119 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 3120 &Idents.get("__objcFastEnumerationState")); 3121 ObjCFastEnumerationStateTypeDecl->startDefinition(); 3122 3123 QualType FieldTypes[] = { 3124 UnsignedLongTy, 3125 getPointerType(ObjCIdTypedefType), 3126 getPointerType(UnsignedLongTy), 3127 getConstantArrayType(UnsignedLongTy, 3128 llvm::APInt(32, 5), ArrayType::Normal, 0) 3129 }; 3130 3131 for (size_t i = 0; i < 4; ++i) { 3132 FieldDecl *Field = FieldDecl::Create(*this, 3133 ObjCFastEnumerationStateTypeDecl, 3134 SourceLocation(), 0, 3135 FieldTypes[i], /*TInfo=*/0, 3136 /*BitWidth=*/0, 3137 /*Mutable=*/false); 3138 Field->setAccess(AS_public); 3139 ObjCFastEnumerationStateTypeDecl->addDecl(Field); 3140 } 3141 if (getLangOptions().CPlusPlus) 3142 if (CXXRecordDecl *CXXRD = 3143 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl)) 3144 CXXRD->setEmpty(false); 3145 3146 ObjCFastEnumerationStateTypeDecl->completeDefinition(); 3147 } 3148 3149 return getTagDeclType(ObjCFastEnumerationStateTypeDecl); 3150} 3151 3152QualType ASTContext::getBlockDescriptorType() { 3153 if (BlockDescriptorType) 3154 return getTagDeclType(BlockDescriptorType); 3155 3156 RecordDecl *T; 3157 // FIXME: Needs the FlagAppleBlock bit. 3158 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 3159 &Idents.get("__block_descriptor")); 3160 T->startDefinition(); 3161 3162 QualType FieldTypes[] = { 3163 UnsignedLongTy, 3164 UnsignedLongTy, 3165 }; 3166 3167 const char *FieldNames[] = { 3168 "reserved", 3169 "Size" 3170 }; 3171 3172 for (size_t i = 0; i < 2; ++i) { 3173 FieldDecl *Field = FieldDecl::Create(*this, 3174 T, 3175 SourceLocation(), 3176 &Idents.get(FieldNames[i]), 3177 FieldTypes[i], /*TInfo=*/0, 3178 /*BitWidth=*/0, 3179 /*Mutable=*/false); 3180 Field->setAccess(AS_public); 3181 T->addDecl(Field); 3182 } 3183 3184 T->completeDefinition(); 3185 3186 BlockDescriptorType = T; 3187 3188 return getTagDeclType(BlockDescriptorType); 3189} 3190 3191void ASTContext::setBlockDescriptorType(QualType T) { 3192 const RecordType *Rec = T->getAs<RecordType>(); 3193 assert(Rec && "Invalid BlockDescriptorType"); 3194 BlockDescriptorType = Rec->getDecl(); 3195} 3196 3197QualType ASTContext::getBlockDescriptorExtendedType() { 3198 if (BlockDescriptorExtendedType) 3199 return getTagDeclType(BlockDescriptorExtendedType); 3200 3201 RecordDecl *T; 3202 // FIXME: Needs the FlagAppleBlock bit. 3203 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 3204 &Idents.get("__block_descriptor_withcopydispose")); 3205 T->startDefinition(); 3206 3207 QualType FieldTypes[] = { 3208 UnsignedLongTy, 3209 UnsignedLongTy, 3210 getPointerType(VoidPtrTy), 3211 getPointerType(VoidPtrTy) 3212 }; 3213 3214 const char *FieldNames[] = { 3215 "reserved", 3216 "Size", 3217 "CopyFuncPtr", 3218 "DestroyFuncPtr" 3219 }; 3220 3221 for (size_t i = 0; i < 4; ++i) { 3222 FieldDecl *Field = FieldDecl::Create(*this, 3223 T, 3224 SourceLocation(), 3225 &Idents.get(FieldNames[i]), 3226 FieldTypes[i], /*TInfo=*/0, 3227 /*BitWidth=*/0, 3228 /*Mutable=*/false); 3229 Field->setAccess(AS_public); 3230 T->addDecl(Field); 3231 } 3232 3233 T->completeDefinition(); 3234 3235 BlockDescriptorExtendedType = T; 3236 3237 return getTagDeclType(BlockDescriptorExtendedType); 3238} 3239 3240void ASTContext::setBlockDescriptorExtendedType(QualType T) { 3241 const RecordType *Rec = T->getAs<RecordType>(); 3242 assert(Rec && "Invalid BlockDescriptorType"); 3243 BlockDescriptorExtendedType = Rec->getDecl(); 3244} 3245 3246bool ASTContext::BlockRequiresCopying(QualType Ty) { 3247 if (Ty->isBlockPointerType()) 3248 return true; 3249 if (isObjCNSObjectType(Ty)) 3250 return true; 3251 if (Ty->isObjCObjectPointerType()) 3252 return true; 3253 return false; 3254} 3255 3256QualType ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) { 3257 // type = struct __Block_byref_1_X { 3258 // void *__isa; 3259 // struct __Block_byref_1_X *__forwarding; 3260 // unsigned int __flags; 3261 // unsigned int __size; 3262 // void *__copy_helper; // as needed 3263 // void *__destroy_help // as needed 3264 // int X; 3265 // } * 3266 3267 bool HasCopyAndDispose = BlockRequiresCopying(Ty); 3268 3269 // FIXME: Move up 3270 llvm::SmallString<36> Name; 3271 llvm::raw_svector_ostream(Name) << "__Block_byref_" << 3272 ++UniqueBlockByRefTypeID << '_' << DeclName; 3273 RecordDecl *T; 3274 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 3275 &Idents.get(Name.str())); 3276 T->startDefinition(); 3277 QualType Int32Ty = IntTy; 3278 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported"); 3279 QualType FieldTypes[] = { 3280 getPointerType(VoidPtrTy), 3281 getPointerType(getTagDeclType(T)), 3282 Int32Ty, 3283 Int32Ty, 3284 getPointerType(VoidPtrTy), 3285 getPointerType(VoidPtrTy), 3286 Ty 3287 }; 3288 3289 llvm::StringRef FieldNames[] = { 3290 "__isa", 3291 "__forwarding", 3292 "__flags", 3293 "__size", 3294 "__copy_helper", 3295 "__destroy_helper", 3296 DeclName, 3297 }; 3298 3299 for (size_t i = 0; i < 7; ++i) { 3300 if (!HasCopyAndDispose && i >=4 && i <= 5) 3301 continue; 3302 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 3303 &Idents.get(FieldNames[i]), 3304 FieldTypes[i], /*TInfo=*/0, 3305 /*BitWidth=*/0, /*Mutable=*/false); 3306 Field->setAccess(AS_public); 3307 T->addDecl(Field); 3308 } 3309 3310 T->completeDefinition(); 3311 3312 return getPointerType(getTagDeclType(T)); 3313} 3314 3315 3316QualType ASTContext::getBlockParmType( 3317 bool BlockHasCopyDispose, 3318 llvm::SmallVectorImpl<const Expr *> &Layout) { 3319 3320 // FIXME: Move up 3321 llvm::SmallString<36> Name; 3322 llvm::raw_svector_ostream(Name) << "__block_literal_" 3323 << ++UniqueBlockParmTypeID; 3324 RecordDecl *T; 3325 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 3326 &Idents.get(Name.str())); 3327 T->startDefinition(); 3328 QualType FieldTypes[] = { 3329 getPointerType(VoidPtrTy), 3330 IntTy, 3331 IntTy, 3332 getPointerType(VoidPtrTy), 3333 (BlockHasCopyDispose ? 3334 getPointerType(getBlockDescriptorExtendedType()) : 3335 getPointerType(getBlockDescriptorType())) 3336 }; 3337 3338 const char *FieldNames[] = { 3339 "__isa", 3340 "__flags", 3341 "__reserved", 3342 "__FuncPtr", 3343 "__descriptor" 3344 }; 3345 3346 for (size_t i = 0; i < 5; ++i) { 3347 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 3348 &Idents.get(FieldNames[i]), 3349 FieldTypes[i], /*TInfo=*/0, 3350 /*BitWidth=*/0, /*Mutable=*/false); 3351 Field->setAccess(AS_public); 3352 T->addDecl(Field); 3353 } 3354 3355 for (unsigned i = 0; i < Layout.size(); ++i) { 3356 const Expr *E = Layout[i]; 3357 3358 QualType FieldType = E->getType(); 3359 IdentifierInfo *FieldName = 0; 3360 if (isa<CXXThisExpr>(E)) { 3361 FieldName = &Idents.get("this"); 3362 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) { 3363 const ValueDecl *D = BDRE->getDecl(); 3364 FieldName = D->getIdentifier(); 3365 if (BDRE->isByRef()) 3366 FieldType = BuildByRefType(D->getName(), FieldType); 3367 } else { 3368 // Padding. 3369 assert(isa<ConstantArrayType>(FieldType) && 3370 isa<DeclRefExpr>(E) && 3371 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() && 3372 "doesn't match characteristics of padding decl"); 3373 } 3374 3375 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 3376 FieldName, FieldType, /*TInfo=*/0, 3377 /*BitWidth=*/0, /*Mutable=*/false); 3378 Field->setAccess(AS_public); 3379 T->addDecl(Field); 3380 } 3381 3382 T->completeDefinition(); 3383 3384 return getPointerType(getTagDeclType(T)); 3385} 3386 3387void ASTContext::setObjCFastEnumerationStateType(QualType T) { 3388 const RecordType *Rec = T->getAs<RecordType>(); 3389 assert(Rec && "Invalid ObjCFAstEnumerationStateType"); 3390 ObjCFastEnumerationStateTypeDecl = Rec->getDecl(); 3391} 3392 3393// This returns true if a type has been typedefed to BOOL: 3394// typedef <type> BOOL; 3395static bool isTypeTypedefedAsBOOL(QualType T) { 3396 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 3397 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 3398 return II->isStr("BOOL"); 3399 3400 return false; 3401} 3402 3403/// getObjCEncodingTypeSize returns size of type for objective-c encoding 3404/// purpose. 3405CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) { 3406 CharUnits sz = getTypeSizeInChars(type); 3407 3408 // Make all integer and enum types at least as large as an int 3409 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 3410 sz = std::max(sz, getTypeSizeInChars(IntTy)); 3411 // Treat arrays as pointers, since that's how they're passed in. 3412 else if (type->isArrayType()) 3413 sz = getTypeSizeInChars(VoidPtrTy); 3414 return sz; 3415} 3416 3417static inline 3418std::string charUnitsToString(const CharUnits &CU) { 3419 return llvm::itostr(CU.getQuantity()); 3420} 3421 3422/// getObjCEncodingForBlockDecl - Return the encoded type for this block 3423/// declaration. 3424void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr, 3425 std::string& S) { 3426 const BlockDecl *Decl = Expr->getBlockDecl(); 3427 QualType BlockTy = 3428 Expr->getType()->getAs<BlockPointerType>()->getPointeeType(); 3429 // Encode result type. 3430 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S); 3431 // Compute size of all parameters. 3432 // Start with computing size of a pointer in number of bytes. 3433 // FIXME: There might(should) be a better way of doing this computation! 3434 SourceLocation Loc; 3435 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 3436 CharUnits ParmOffset = PtrSize; 3437 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), 3438 E = Decl->param_end(); PI != E; ++PI) { 3439 QualType PType = (*PI)->getType(); 3440 CharUnits sz = getObjCEncodingTypeSize(PType); 3441 assert (sz.isPositive() && "BlockExpr - Incomplete param type"); 3442 ParmOffset += sz; 3443 } 3444 // Size of the argument frame 3445 S += charUnitsToString(ParmOffset); 3446 // Block pointer and offset. 3447 S += "@?0"; 3448 ParmOffset = PtrSize; 3449 3450 // Argument types. 3451 ParmOffset = PtrSize; 3452 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E = 3453 Decl->param_end(); PI != E; ++PI) { 3454 ParmVarDecl *PVDecl = *PI; 3455 QualType PType = PVDecl->getOriginalType(); 3456 if (const ArrayType *AT = 3457 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 3458 // Use array's original type only if it has known number of 3459 // elements. 3460 if (!isa<ConstantArrayType>(AT)) 3461 PType = PVDecl->getType(); 3462 } else if (PType->isFunctionType()) 3463 PType = PVDecl->getType(); 3464 getObjCEncodingForType(PType, S); 3465 S += charUnitsToString(ParmOffset); 3466 ParmOffset += getObjCEncodingTypeSize(PType); 3467 } 3468} 3469 3470/// getObjCEncodingForMethodDecl - Return the encoded type for this method 3471/// declaration. 3472void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 3473 std::string& S) { 3474 // FIXME: This is not very efficient. 3475 // Encode type qualifer, 'in', 'inout', etc. for the return type. 3476 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S); 3477 // Encode result type. 3478 getObjCEncodingForType(Decl->getResultType(), S); 3479 // Compute size of all parameters. 3480 // Start with computing size of a pointer in number of bytes. 3481 // FIXME: There might(should) be a better way of doing this computation! 3482 SourceLocation Loc; 3483 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 3484 // The first two arguments (self and _cmd) are pointers; account for 3485 // their size. 3486 CharUnits ParmOffset = 2 * PtrSize; 3487 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(), 3488 E = Decl->sel_param_end(); PI != E; ++PI) { 3489 QualType PType = (*PI)->getType(); 3490 CharUnits sz = getObjCEncodingTypeSize(PType); 3491 assert (sz.isPositive() && 3492 "getObjCEncodingForMethodDecl - Incomplete param type"); 3493 ParmOffset += sz; 3494 } 3495 S += charUnitsToString(ParmOffset); 3496 S += "@0:"; 3497 S += charUnitsToString(PtrSize); 3498 3499 // Argument types. 3500 ParmOffset = 2 * PtrSize; 3501 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(), 3502 E = Decl->sel_param_end(); PI != E; ++PI) { 3503 ParmVarDecl *PVDecl = *PI; 3504 QualType PType = PVDecl->getOriginalType(); 3505 if (const ArrayType *AT = 3506 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 3507 // Use array's original type only if it has known number of 3508 // elements. 3509 if (!isa<ConstantArrayType>(AT)) 3510 PType = PVDecl->getType(); 3511 } else if (PType->isFunctionType()) 3512 PType = PVDecl->getType(); 3513 // Process argument qualifiers for user supplied arguments; such as, 3514 // 'in', 'inout', etc. 3515 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S); 3516 getObjCEncodingForType(PType, S); 3517 S += charUnitsToString(ParmOffset); 3518 ParmOffset += getObjCEncodingTypeSize(PType); 3519 } 3520} 3521 3522/// getObjCEncodingForPropertyDecl - Return the encoded type for this 3523/// property declaration. If non-NULL, Container must be either an 3524/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 3525/// NULL when getting encodings for protocol properties. 3526/// Property attributes are stored as a comma-delimited C string. The simple 3527/// attributes readonly and bycopy are encoded as single characters. The 3528/// parametrized attributes, getter=name, setter=name, and ivar=name, are 3529/// encoded as single characters, followed by an identifier. Property types 3530/// are also encoded as a parametrized attribute. The characters used to encode 3531/// these attributes are defined by the following enumeration: 3532/// @code 3533/// enum PropertyAttributes { 3534/// kPropertyReadOnly = 'R', // property is read-only. 3535/// kPropertyBycopy = 'C', // property is a copy of the value last assigned 3536/// kPropertyByref = '&', // property is a reference to the value last assigned 3537/// kPropertyDynamic = 'D', // property is dynamic 3538/// kPropertyGetter = 'G', // followed by getter selector name 3539/// kPropertySetter = 'S', // followed by setter selector name 3540/// kPropertyInstanceVariable = 'V' // followed by instance variable name 3541/// kPropertyType = 't' // followed by old-style type encoding. 3542/// kPropertyWeak = 'W' // 'weak' property 3543/// kPropertyStrong = 'P' // property GC'able 3544/// kPropertyNonAtomic = 'N' // property non-atomic 3545/// }; 3546/// @endcode 3547void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 3548 const Decl *Container, 3549 std::string& S) { 3550 // Collect information from the property implementation decl(s). 3551 bool Dynamic = false; 3552 ObjCPropertyImplDecl *SynthesizePID = 0; 3553 3554 // FIXME: Duplicated code due to poor abstraction. 3555 if (Container) { 3556 if (const ObjCCategoryImplDecl *CID = 3557 dyn_cast<ObjCCategoryImplDecl>(Container)) { 3558 for (ObjCCategoryImplDecl::propimpl_iterator 3559 i = CID->propimpl_begin(), e = CID->propimpl_end(); 3560 i != e; ++i) { 3561 ObjCPropertyImplDecl *PID = *i; 3562 if (PID->getPropertyDecl() == PD) { 3563 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 3564 Dynamic = true; 3565 } else { 3566 SynthesizePID = PID; 3567 } 3568 } 3569 } 3570 } else { 3571 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container); 3572 for (ObjCCategoryImplDecl::propimpl_iterator 3573 i = OID->propimpl_begin(), e = OID->propimpl_end(); 3574 i != e; ++i) { 3575 ObjCPropertyImplDecl *PID = *i; 3576 if (PID->getPropertyDecl() == PD) { 3577 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 3578 Dynamic = true; 3579 } else { 3580 SynthesizePID = PID; 3581 } 3582 } 3583 } 3584 } 3585 } 3586 3587 // FIXME: This is not very efficient. 3588 S = "T"; 3589 3590 // Encode result type. 3591 // GCC has some special rules regarding encoding of properties which 3592 // closely resembles encoding of ivars. 3593 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0, 3594 true /* outermost type */, 3595 true /* encoding for property */); 3596 3597 if (PD->isReadOnly()) { 3598 S += ",R"; 3599 } else { 3600 switch (PD->getSetterKind()) { 3601 case ObjCPropertyDecl::Assign: break; 3602 case ObjCPropertyDecl::Copy: S += ",C"; break; 3603 case ObjCPropertyDecl::Retain: S += ",&"; break; 3604 } 3605 } 3606 3607 // It really isn't clear at all what this means, since properties 3608 // are "dynamic by default". 3609 if (Dynamic) 3610 S += ",D"; 3611 3612 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 3613 S += ",N"; 3614 3615 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 3616 S += ",G"; 3617 S += PD->getGetterName().getAsString(); 3618 } 3619 3620 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 3621 S += ",S"; 3622 S += PD->getSetterName().getAsString(); 3623 } 3624 3625 if (SynthesizePID) { 3626 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 3627 S += ",V"; 3628 S += OID->getNameAsString(); 3629 } 3630 3631 // FIXME: OBJCGC: weak & strong 3632} 3633 3634/// getLegacyIntegralTypeEncoding - 3635/// Another legacy compatibility encoding: 32-bit longs are encoded as 3636/// 'l' or 'L' , but not always. For typedefs, we need to use 3637/// 'i' or 'I' instead if encoding a struct field, or a pointer! 3638/// 3639void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 3640 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 3641 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) { 3642 if (BT->getKind() == BuiltinType::ULong && 3643 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32)) 3644 PointeeTy = UnsignedIntTy; 3645 else 3646 if (BT->getKind() == BuiltinType::Long && 3647 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32)) 3648 PointeeTy = IntTy; 3649 } 3650 } 3651} 3652 3653void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 3654 const FieldDecl *Field) { 3655 // We follow the behavior of gcc, expanding structures which are 3656 // directly pointed to, and expanding embedded structures. Note that 3657 // these rules are sufficient to prevent recursive encoding of the 3658 // same type. 3659 getObjCEncodingForTypeImpl(T, S, true, true, Field, 3660 true /* outermost type */); 3661} 3662 3663static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) { 3664 switch (T->getAs<BuiltinType>()->getKind()) { 3665 default: assert(0 && "Unhandled builtin type kind"); 3666 case BuiltinType::Void: return 'v'; 3667 case BuiltinType::Bool: return 'B'; 3668 case BuiltinType::Char_U: 3669 case BuiltinType::UChar: return 'C'; 3670 case BuiltinType::UShort: return 'S'; 3671 case BuiltinType::UInt: return 'I'; 3672 case BuiltinType::ULong: 3673 return 3674 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q'; 3675 case BuiltinType::UInt128: return 'T'; 3676 case BuiltinType::ULongLong: return 'Q'; 3677 case BuiltinType::Char_S: 3678 case BuiltinType::SChar: return 'c'; 3679 case BuiltinType::Short: return 's'; 3680 case BuiltinType::WChar: 3681 case BuiltinType::Int: return 'i'; 3682 case BuiltinType::Long: 3683 return 3684 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q'; 3685 case BuiltinType::LongLong: return 'q'; 3686 case BuiltinType::Int128: return 't'; 3687 case BuiltinType::Float: return 'f'; 3688 case BuiltinType::Double: return 'd'; 3689 case BuiltinType::LongDouble: return 'd'; 3690 } 3691} 3692 3693static void EncodeBitField(const ASTContext *Context, std::string& S, 3694 QualType T, const FieldDecl *FD) { 3695 const Expr *E = FD->getBitWidth(); 3696 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl"); 3697 ASTContext *Ctx = const_cast<ASTContext*>(Context); 3698 S += 'b'; 3699 // The NeXT runtime encodes bit fields as b followed by the number of bits. 3700 // The GNU runtime requires more information; bitfields are encoded as b, 3701 // then the offset (in bits) of the first element, then the type of the 3702 // bitfield, then the size in bits. For example, in this structure: 3703 // 3704 // struct 3705 // { 3706 // int integer; 3707 // int flags:2; 3708 // }; 3709 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 3710 // runtime, but b32i2 for the GNU runtime. The reason for this extra 3711 // information is not especially sensible, but we're stuck with it for 3712 // compatibility with GCC, although providing it breaks anything that 3713 // actually uses runtime introspection and wants to work on both runtimes... 3714 if (!Ctx->getLangOptions().NeXTRuntime) { 3715 const RecordDecl *RD = FD->getParent(); 3716 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 3717 // FIXME: This same linear search is also used in ExprConstant - it might 3718 // be better if the FieldDecl stored its offset. We'd be increasing the 3719 // size of the object slightly, but saving some time every time it is used. 3720 unsigned i = 0; 3721 for (RecordDecl::field_iterator Field = RD->field_begin(), 3722 FieldEnd = RD->field_end(); 3723 Field != FieldEnd; (void)++Field, ++i) { 3724 if (*Field == FD) 3725 break; 3726 } 3727 S += llvm::utostr(RL.getFieldOffset(i)); 3728 S += ObjCEncodingForPrimitiveKind(Context, T); 3729 } 3730 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue(); 3731 S += llvm::utostr(N); 3732} 3733 3734// FIXME: Use SmallString for accumulating string. 3735void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 3736 bool ExpandPointedToStructures, 3737 bool ExpandStructures, 3738 const FieldDecl *FD, 3739 bool OutermostType, 3740 bool EncodingProperty) { 3741 if (T->getAs<BuiltinType>()) { 3742 if (FD && FD->isBitField()) 3743 return EncodeBitField(this, S, T, FD); 3744 S += ObjCEncodingForPrimitiveKind(this, T); 3745 return; 3746 } 3747 3748 if (const ComplexType *CT = T->getAs<ComplexType>()) { 3749 S += 'j'; 3750 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false, 3751 false); 3752 return; 3753 } 3754 3755 // encoding for pointer or r3eference types. 3756 QualType PointeeTy; 3757 if (const PointerType *PT = T->getAs<PointerType>()) { 3758 if (PT->isObjCSelType()) { 3759 S += ':'; 3760 return; 3761 } 3762 PointeeTy = PT->getPointeeType(); 3763 } 3764 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 3765 PointeeTy = RT->getPointeeType(); 3766 if (!PointeeTy.isNull()) { 3767 bool isReadOnly = false; 3768 // For historical/compatibility reasons, the read-only qualifier of the 3769 // pointee gets emitted _before_ the '^'. The read-only qualifier of 3770 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 3771 // Also, do not emit the 'r' for anything but the outermost type! 3772 if (isa<TypedefType>(T.getTypePtr())) { 3773 if (OutermostType && T.isConstQualified()) { 3774 isReadOnly = true; 3775 S += 'r'; 3776 } 3777 } else if (OutermostType) { 3778 QualType P = PointeeTy; 3779 while (P->getAs<PointerType>()) 3780 P = P->getAs<PointerType>()->getPointeeType(); 3781 if (P.isConstQualified()) { 3782 isReadOnly = true; 3783 S += 'r'; 3784 } 3785 } 3786 if (isReadOnly) { 3787 // Another legacy compatibility encoding. Some ObjC qualifier and type 3788 // combinations need to be rearranged. 3789 // Rewrite "in const" from "nr" to "rn" 3790 if (llvm::StringRef(S).endswith("nr")) 3791 S.replace(S.end()-2, S.end(), "rn"); 3792 } 3793 3794 if (PointeeTy->isCharType()) { 3795 // char pointer types should be encoded as '*' unless it is a 3796 // type that has been typedef'd to 'BOOL'. 3797 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 3798 S += '*'; 3799 return; 3800 } 3801 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) { 3802 // GCC binary compat: Need to convert "struct objc_class *" to "#". 3803 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 3804 S += '#'; 3805 return; 3806 } 3807 // GCC binary compat: Need to convert "struct objc_object *" to "@". 3808 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 3809 S += '@'; 3810 return; 3811 } 3812 // fall through... 3813 } 3814 S += '^'; 3815 getLegacyIntegralTypeEncoding(PointeeTy); 3816 3817 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures, 3818 NULL); 3819 return; 3820 } 3821 3822 if (const ArrayType *AT = 3823 // Ignore type qualifiers etc. 3824 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) { 3825 if (isa<IncompleteArrayType>(AT)) { 3826 // Incomplete arrays are encoded as a pointer to the array element. 3827 S += '^'; 3828 3829 getObjCEncodingForTypeImpl(AT->getElementType(), S, 3830 false, ExpandStructures, FD); 3831 } else { 3832 S += '['; 3833 3834 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 3835 S += llvm::utostr(CAT->getSize().getZExtValue()); 3836 else { 3837 //Variable length arrays are encoded as a regular array with 0 elements. 3838 assert(isa<VariableArrayType>(AT) && "Unknown array type!"); 3839 S += '0'; 3840 } 3841 3842 getObjCEncodingForTypeImpl(AT->getElementType(), S, 3843 false, ExpandStructures, FD); 3844 S += ']'; 3845 } 3846 return; 3847 } 3848 3849 if (T->getAs<FunctionType>()) { 3850 S += '?'; 3851 return; 3852 } 3853 3854 if (const RecordType *RTy = T->getAs<RecordType>()) { 3855 RecordDecl *RDecl = RTy->getDecl(); 3856 S += RDecl->isUnion() ? '(' : '{'; 3857 // Anonymous structures print as '?' 3858 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 3859 S += II->getName(); 3860 if (ClassTemplateSpecializationDecl *Spec 3861 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 3862 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 3863 std::string TemplateArgsStr 3864 = TemplateSpecializationType::PrintTemplateArgumentList( 3865 TemplateArgs.getFlatArgumentList(), 3866 TemplateArgs.flat_size(), 3867 (*this).PrintingPolicy); 3868 3869 S += TemplateArgsStr; 3870 } 3871 } else { 3872 S += '?'; 3873 } 3874 if (ExpandStructures) { 3875 S += '='; 3876 for (RecordDecl::field_iterator Field = RDecl->field_begin(), 3877 FieldEnd = RDecl->field_end(); 3878 Field != FieldEnd; ++Field) { 3879 if (FD) { 3880 S += '"'; 3881 S += Field->getNameAsString(); 3882 S += '"'; 3883 } 3884 3885 // Special case bit-fields. 3886 if (Field->isBitField()) { 3887 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 3888 (*Field)); 3889 } else { 3890 QualType qt = Field->getType(); 3891 getLegacyIntegralTypeEncoding(qt); 3892 getObjCEncodingForTypeImpl(qt, S, false, true, 3893 FD); 3894 } 3895 } 3896 } 3897 S += RDecl->isUnion() ? ')' : '}'; 3898 return; 3899 } 3900 3901 if (T->isEnumeralType()) { 3902 if (FD && FD->isBitField()) 3903 EncodeBitField(this, S, T, FD); 3904 else 3905 S += 'i'; 3906 return; 3907 } 3908 3909 if (T->isBlockPointerType()) { 3910 S += "@?"; // Unlike a pointer-to-function, which is "^?". 3911 return; 3912 } 3913 3914 // Ignore protocol qualifiers when mangling at this level. 3915 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>()) 3916 T = OT->getBaseType(); 3917 3918 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) { 3919 // @encode(class_name) 3920 ObjCInterfaceDecl *OI = OIT->getDecl(); 3921 S += '{'; 3922 const IdentifierInfo *II = OI->getIdentifier(); 3923 S += II->getName(); 3924 S += '='; 3925 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars; 3926 DeepCollectObjCIvars(OI, true, Ivars); 3927 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 3928 FieldDecl *Field = cast<FieldDecl>(Ivars[i]); 3929 if (Field->isBitField()) 3930 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field); 3931 else 3932 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD); 3933 } 3934 S += '}'; 3935 return; 3936 } 3937 3938 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) { 3939 if (OPT->isObjCIdType()) { 3940 S += '@'; 3941 return; 3942 } 3943 3944 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 3945 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 3946 // Since this is a binary compatibility issue, need to consult with runtime 3947 // folks. Fortunately, this is a *very* obsure construct. 3948 S += '#'; 3949 return; 3950 } 3951 3952 if (OPT->isObjCQualifiedIdType()) { 3953 getObjCEncodingForTypeImpl(getObjCIdType(), S, 3954 ExpandPointedToStructures, 3955 ExpandStructures, FD); 3956 if (FD || EncodingProperty) { 3957 // Note that we do extended encoding of protocol qualifer list 3958 // Only when doing ivar or property encoding. 3959 S += '"'; 3960 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 3961 E = OPT->qual_end(); I != E; ++I) { 3962 S += '<'; 3963 S += (*I)->getNameAsString(); 3964 S += '>'; 3965 } 3966 S += '"'; 3967 } 3968 return; 3969 } 3970 3971 QualType PointeeTy = OPT->getPointeeType(); 3972 if (!EncodingProperty && 3973 isa<TypedefType>(PointeeTy.getTypePtr())) { 3974 // Another historical/compatibility reason. 3975 // We encode the underlying type which comes out as 3976 // {...}; 3977 S += '^'; 3978 getObjCEncodingForTypeImpl(PointeeTy, S, 3979 false, ExpandPointedToStructures, 3980 NULL); 3981 return; 3982 } 3983 3984 S += '@'; 3985 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) { 3986 S += '"'; 3987 S += OPT->getInterfaceDecl()->getIdentifier()->getName(); 3988 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 3989 E = OPT->qual_end(); I != E; ++I) { 3990 S += '<'; 3991 S += (*I)->getNameAsString(); 3992 S += '>'; 3993 } 3994 S += '"'; 3995 } 3996 return; 3997 } 3998 3999 // gcc just blithely ignores member pointers. 4000 // TODO: maybe there should be a mangling for these 4001 if (T->getAs<MemberPointerType>()) 4002 return; 4003 4004 assert(0 && "@encode for type not implemented!"); 4005} 4006 4007void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 4008 std::string& S) const { 4009 if (QT & Decl::OBJC_TQ_In) 4010 S += 'n'; 4011 if (QT & Decl::OBJC_TQ_Inout) 4012 S += 'N'; 4013 if (QT & Decl::OBJC_TQ_Out) 4014 S += 'o'; 4015 if (QT & Decl::OBJC_TQ_Bycopy) 4016 S += 'O'; 4017 if (QT & Decl::OBJC_TQ_Byref) 4018 S += 'R'; 4019 if (QT & Decl::OBJC_TQ_Oneway) 4020 S += 'V'; 4021} 4022 4023void ASTContext::setBuiltinVaListType(QualType T) { 4024 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!"); 4025 4026 BuiltinVaListType = T; 4027} 4028 4029void ASTContext::setObjCIdType(QualType T) { 4030 ObjCIdTypedefType = T; 4031} 4032 4033void ASTContext::setObjCSelType(QualType T) { 4034 ObjCSelTypedefType = T; 4035} 4036 4037void ASTContext::setObjCProtoType(QualType QT) { 4038 ObjCProtoType = QT; 4039} 4040 4041void ASTContext::setObjCClassType(QualType T) { 4042 ObjCClassTypedefType = T; 4043} 4044 4045void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 4046 assert(ObjCConstantStringType.isNull() && 4047 "'NSConstantString' type already set!"); 4048 4049 ObjCConstantStringType = getObjCInterfaceType(Decl); 4050} 4051 4052/// \brief Retrieve the template name that corresponds to a non-empty 4053/// lookup. 4054TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 4055 UnresolvedSetIterator End) { 4056 unsigned size = End - Begin; 4057 assert(size > 1 && "set is not overloaded!"); 4058 4059 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 4060 size * sizeof(FunctionTemplateDecl*)); 4061 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size); 4062 4063 NamedDecl **Storage = OT->getStorage(); 4064 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 4065 NamedDecl *D = *I; 4066 assert(isa<FunctionTemplateDecl>(D) || 4067 (isa<UsingShadowDecl>(D) && 4068 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 4069 *Storage++ = D; 4070 } 4071 4072 return TemplateName(OT); 4073} 4074 4075/// \brief Retrieve the template name that represents a qualified 4076/// template name such as \c std::vector. 4077TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 4078 bool TemplateKeyword, 4079 TemplateDecl *Template) { 4080 // FIXME: Canonicalization? 4081 llvm::FoldingSetNodeID ID; 4082 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 4083 4084 void *InsertPos = 0; 4085 QualifiedTemplateName *QTN = 4086 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 4087 if (!QTN) { 4088 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template); 4089 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 4090 } 4091 4092 return TemplateName(QTN); 4093} 4094 4095/// \brief Retrieve the template name that represents a dependent 4096/// template name such as \c MetaFun::template apply. 4097TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 4098 const IdentifierInfo *Name) { 4099 assert((!NNS || NNS->isDependent()) && 4100 "Nested name specifier must be dependent"); 4101 4102 llvm::FoldingSetNodeID ID; 4103 DependentTemplateName::Profile(ID, NNS, Name); 4104 4105 void *InsertPos = 0; 4106 DependentTemplateName *QTN = 4107 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 4108 4109 if (QTN) 4110 return TemplateName(QTN); 4111 4112 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4113 if (CanonNNS == NNS) { 4114 QTN = new (*this,4) DependentTemplateName(NNS, Name); 4115 } else { 4116 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 4117 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon); 4118 DependentTemplateName *CheckQTN = 4119 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 4120 assert(!CheckQTN && "Dependent type name canonicalization broken"); 4121 (void)CheckQTN; 4122 } 4123 4124 DependentTemplateNames.InsertNode(QTN, InsertPos); 4125 return TemplateName(QTN); 4126} 4127 4128/// \brief Retrieve the template name that represents a dependent 4129/// template name such as \c MetaFun::template operator+. 4130TemplateName 4131ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 4132 OverloadedOperatorKind Operator) { 4133 assert((!NNS || NNS->isDependent()) && 4134 "Nested name specifier must be dependent"); 4135 4136 llvm::FoldingSetNodeID ID; 4137 DependentTemplateName::Profile(ID, NNS, Operator); 4138 4139 void *InsertPos = 0; 4140 DependentTemplateName *QTN 4141 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 4142 4143 if (QTN) 4144 return TemplateName(QTN); 4145 4146 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4147 if (CanonNNS == NNS) { 4148 QTN = new (*this,4) DependentTemplateName(NNS, Operator); 4149 } else { 4150 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 4151 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon); 4152 4153 DependentTemplateName *CheckQTN 4154 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 4155 assert(!CheckQTN && "Dependent template name canonicalization broken"); 4156 (void)CheckQTN; 4157 } 4158 4159 DependentTemplateNames.InsertNode(QTN, InsertPos); 4160 return TemplateName(QTN); 4161} 4162 4163/// getFromTargetType - Given one of the integer types provided by 4164/// TargetInfo, produce the corresponding type. The unsigned @p Type 4165/// is actually a value of type @c TargetInfo::IntType. 4166CanQualType ASTContext::getFromTargetType(unsigned Type) const { 4167 switch (Type) { 4168 case TargetInfo::NoInt: return CanQualType(); 4169 case TargetInfo::SignedShort: return ShortTy; 4170 case TargetInfo::UnsignedShort: return UnsignedShortTy; 4171 case TargetInfo::SignedInt: return IntTy; 4172 case TargetInfo::UnsignedInt: return UnsignedIntTy; 4173 case TargetInfo::SignedLong: return LongTy; 4174 case TargetInfo::UnsignedLong: return UnsignedLongTy; 4175 case TargetInfo::SignedLongLong: return LongLongTy; 4176 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 4177 } 4178 4179 assert(false && "Unhandled TargetInfo::IntType value"); 4180 return CanQualType(); 4181} 4182 4183//===----------------------------------------------------------------------===// 4184// Type Predicates. 4185//===----------------------------------------------------------------------===// 4186 4187/// isObjCNSObjectType - Return true if this is an NSObject object using 4188/// NSObject attribute on a c-style pointer type. 4189/// FIXME - Make it work directly on types. 4190/// FIXME: Move to Type. 4191/// 4192bool ASTContext::isObjCNSObjectType(QualType Ty) const { 4193 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) { 4194 if (TypedefDecl *TD = TDT->getDecl()) 4195 if (TD->getAttr<ObjCNSObjectAttr>()) 4196 return true; 4197 } 4198 return false; 4199} 4200 4201/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 4202/// garbage collection attribute. 4203/// 4204Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const { 4205 Qualifiers::GC GCAttrs = Qualifiers::GCNone; 4206 if (getLangOptions().ObjC1 && 4207 getLangOptions().getGCMode() != LangOptions::NonGC) { 4208 GCAttrs = Ty.getObjCGCAttr(); 4209 // Default behavious under objective-c's gc is for objective-c pointers 4210 // (or pointers to them) be treated as though they were declared 4211 // as __strong. 4212 if (GCAttrs == Qualifiers::GCNone) { 4213 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 4214 GCAttrs = Qualifiers::Strong; 4215 else if (Ty->isPointerType()) 4216 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType()); 4217 } 4218 // Non-pointers have none gc'able attribute regardless of the attribute 4219 // set on them. 4220 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType()) 4221 return Qualifiers::GCNone; 4222 } 4223 return GCAttrs; 4224} 4225 4226//===----------------------------------------------------------------------===// 4227// Type Compatibility Testing 4228//===----------------------------------------------------------------------===// 4229 4230/// areCompatVectorTypes - Return true if the two specified vector types are 4231/// compatible. 4232static bool areCompatVectorTypes(const VectorType *LHS, 4233 const VectorType *RHS) { 4234 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 4235 return LHS->getElementType() == RHS->getElementType() && 4236 LHS->getNumElements() == RHS->getNumElements(); 4237} 4238 4239bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 4240 QualType SecondVec) { 4241 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 4242 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 4243 4244 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 4245 return true; 4246 4247 // AltiVec vectors types are identical to equivalent GCC vector types 4248 const VectorType *First = FirstVec->getAs<VectorType>(); 4249 const VectorType *Second = SecondVec->getAs<VectorType>(); 4250 if ((((First->getAltiVecSpecific() == VectorType::AltiVec) && 4251 (Second->getAltiVecSpecific() == VectorType::NotAltiVec)) || 4252 ((First->getAltiVecSpecific() == VectorType::NotAltiVec) && 4253 (Second->getAltiVecSpecific() == VectorType::AltiVec))) && 4254 hasSameType(First->getElementType(), Second->getElementType()) && 4255 (First->getNumElements() == Second->getNumElements())) 4256 return true; 4257 4258 return false; 4259} 4260 4261//===----------------------------------------------------------------------===// 4262// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 4263//===----------------------------------------------------------------------===// 4264 4265/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 4266/// inheritance hierarchy of 'rProto'. 4267bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 4268 ObjCProtocolDecl *rProto) { 4269 if (lProto == rProto) 4270 return true; 4271 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(), 4272 E = rProto->protocol_end(); PI != E; ++PI) 4273 if (ProtocolCompatibleWithProtocol(lProto, *PI)) 4274 return true; 4275 return false; 4276} 4277 4278/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...> 4279/// return true if lhs's protocols conform to rhs's protocol; false 4280/// otherwise. 4281bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) { 4282 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType()) 4283 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false); 4284 return false; 4285} 4286 4287/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and 4288/// Class<p1, ...>. 4289bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs, 4290 QualType rhs) { 4291 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>(); 4292 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 4293 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible"); 4294 4295 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 4296 E = lhsQID->qual_end(); I != E; ++I) { 4297 bool match = false; 4298 ObjCProtocolDecl *lhsProto = *I; 4299 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(), 4300 E = rhsOPT->qual_end(); J != E; ++J) { 4301 ObjCProtocolDecl *rhsProto = *J; 4302 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 4303 match = true; 4304 break; 4305 } 4306 } 4307 if (!match) 4308 return false; 4309 } 4310 return true; 4311} 4312 4313/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 4314/// ObjCQualifiedIDType. 4315bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, 4316 bool compare) { 4317 // Allow id<P..> and an 'id' or void* type in all cases. 4318 if (lhs->isVoidPointerType() || 4319 lhs->isObjCIdType() || lhs->isObjCClassType()) 4320 return true; 4321 else if (rhs->isVoidPointerType() || 4322 rhs->isObjCIdType() || rhs->isObjCClassType()) 4323 return true; 4324 4325 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) { 4326 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 4327 4328 if (!rhsOPT) return false; 4329 4330 if (rhsOPT->qual_empty()) { 4331 // If the RHS is a unqualified interface pointer "NSString*", 4332 // make sure we check the class hierarchy. 4333 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 4334 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 4335 E = lhsQID->qual_end(); I != E; ++I) { 4336 // when comparing an id<P> on lhs with a static type on rhs, 4337 // see if static class implements all of id's protocols, directly or 4338 // through its super class and categories. 4339 if (!rhsID->ClassImplementsProtocol(*I, true)) 4340 return false; 4341 } 4342 } 4343 // If there are no qualifiers and no interface, we have an 'id'. 4344 return true; 4345 } 4346 // Both the right and left sides have qualifiers. 4347 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 4348 E = lhsQID->qual_end(); I != E; ++I) { 4349 ObjCProtocolDecl *lhsProto = *I; 4350 bool match = false; 4351 4352 // when comparing an id<P> on lhs with a static type on rhs, 4353 // see if static class implements all of id's protocols, directly or 4354 // through its super class and categories. 4355 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(), 4356 E = rhsOPT->qual_end(); J != E; ++J) { 4357 ObjCProtocolDecl *rhsProto = *J; 4358 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 4359 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 4360 match = true; 4361 break; 4362 } 4363 } 4364 // If the RHS is a qualified interface pointer "NSString<P>*", 4365 // make sure we check the class hierarchy. 4366 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 4367 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 4368 E = lhsQID->qual_end(); I != E; ++I) { 4369 // when comparing an id<P> on lhs with a static type on rhs, 4370 // see if static class implements all of id's protocols, directly or 4371 // through its super class and categories. 4372 if (rhsID->ClassImplementsProtocol(*I, true)) { 4373 match = true; 4374 break; 4375 } 4376 } 4377 } 4378 if (!match) 4379 return false; 4380 } 4381 4382 return true; 4383 } 4384 4385 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType(); 4386 assert(rhsQID && "One of the LHS/RHS should be id<x>"); 4387 4388 if (const ObjCObjectPointerType *lhsOPT = 4389 lhs->getAsObjCInterfacePointerType()) { 4390 if (lhsOPT->qual_empty()) { 4391 bool match = false; 4392 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) { 4393 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(), 4394 E = rhsQID->qual_end(); I != E; ++I) { 4395 // when comparing an id<P> on rhs with a static type on lhs, 4396 // static class must implement all of id's protocols directly or 4397 // indirectly through its super class. 4398 if (lhsID->ClassImplementsProtocol(*I, true)) { 4399 match = true; 4400 break; 4401 } 4402 } 4403 if (!match) 4404 return false; 4405 } 4406 return true; 4407 } 4408 // Both the right and left sides have qualifiers. 4409 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(), 4410 E = lhsOPT->qual_end(); I != E; ++I) { 4411 ObjCProtocolDecl *lhsProto = *I; 4412 bool match = false; 4413 4414 // when comparing an id<P> on lhs with a static type on rhs, 4415 // see if static class implements all of id's protocols, directly or 4416 // through its super class and categories. 4417 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(), 4418 E = rhsQID->qual_end(); J != E; ++J) { 4419 ObjCProtocolDecl *rhsProto = *J; 4420 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 4421 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 4422 match = true; 4423 break; 4424 } 4425 } 4426 if (!match) 4427 return false; 4428 } 4429 return true; 4430 } 4431 return false; 4432} 4433 4434/// canAssignObjCInterfaces - Return true if the two interface types are 4435/// compatible for assignment from RHS to LHS. This handles validation of any 4436/// protocol qualifiers on the LHS or RHS. 4437/// 4438bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 4439 const ObjCObjectPointerType *RHSOPT) { 4440 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 4441 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 4442 4443 // If either type represents the built-in 'id' or 'Class' types, return true. 4444 if (LHS->isObjCUnqualifiedIdOrClass() || 4445 RHS->isObjCUnqualifiedIdOrClass()) 4446 return true; 4447 4448 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) 4449 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 4450 QualType(RHSOPT,0), 4451 false); 4452 4453 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) 4454 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0), 4455 QualType(RHSOPT,0)); 4456 4457 // If we have 2 user-defined types, fall into that path. 4458 if (LHS->getInterface() && RHS->getInterface()) 4459 return canAssignObjCInterfaces(LHS, RHS); 4460 4461 return false; 4462} 4463 4464/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 4465/// for providing type-safty for objective-c pointers used to pass/return 4466/// arguments in block literals. When passed as arguments, passing 'A*' where 4467/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 4468/// not OK. For the return type, the opposite is not OK. 4469bool ASTContext::canAssignObjCInterfacesInBlockPointer( 4470 const ObjCObjectPointerType *LHSOPT, 4471 const ObjCObjectPointerType *RHSOPT) { 4472 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 4473 return true; 4474 4475 if (LHSOPT->isObjCBuiltinType()) { 4476 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType(); 4477 } 4478 4479 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) 4480 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 4481 QualType(RHSOPT,0), 4482 false); 4483 4484 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 4485 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 4486 if (LHS && RHS) { // We have 2 user-defined types. 4487 if (LHS != RHS) { 4488 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 4489 return false; 4490 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 4491 return true; 4492 } 4493 else 4494 return true; 4495 } 4496 return false; 4497} 4498 4499/// getIntersectionOfProtocols - This routine finds the intersection of set 4500/// of protocols inherited from two distinct objective-c pointer objects. 4501/// It is used to build composite qualifier list of the composite type of 4502/// the conditional expression involving two objective-c pointer objects. 4503static 4504void getIntersectionOfProtocols(ASTContext &Context, 4505 const ObjCObjectPointerType *LHSOPT, 4506 const ObjCObjectPointerType *RHSOPT, 4507 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) { 4508 4509 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 4510 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 4511 assert(LHS->getInterface() && "LHS must have an interface base"); 4512 assert(RHS->getInterface() && "RHS must have an interface base"); 4513 4514 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet; 4515 unsigned LHSNumProtocols = LHS->getNumProtocols(); 4516 if (LHSNumProtocols > 0) 4517 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end()); 4518 else { 4519 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 4520 Context.CollectInheritedProtocols(LHS->getInterface(), 4521 LHSInheritedProtocols); 4522 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(), 4523 LHSInheritedProtocols.end()); 4524 } 4525 4526 unsigned RHSNumProtocols = RHS->getNumProtocols(); 4527 if (RHSNumProtocols > 0) { 4528 ObjCProtocolDecl **RHSProtocols = 4529 const_cast<ObjCProtocolDecl **>(RHS->qual_begin()); 4530 for (unsigned i = 0; i < RHSNumProtocols; ++i) 4531 if (InheritedProtocolSet.count(RHSProtocols[i])) 4532 IntersectionOfProtocols.push_back(RHSProtocols[i]); 4533 } 4534 else { 4535 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols; 4536 Context.CollectInheritedProtocols(RHS->getInterface(), 4537 RHSInheritedProtocols); 4538 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 4539 RHSInheritedProtocols.begin(), 4540 E = RHSInheritedProtocols.end(); I != E; ++I) 4541 if (InheritedProtocolSet.count((*I))) 4542 IntersectionOfProtocols.push_back((*I)); 4543 } 4544} 4545 4546/// areCommonBaseCompatible - Returns common base class of the two classes if 4547/// one found. Note that this is O'2 algorithm. But it will be called as the 4548/// last type comparison in a ?-exp of ObjC pointer types before a 4549/// warning is issued. So, its invokation is extremely rare. 4550QualType ASTContext::areCommonBaseCompatible( 4551 const ObjCObjectPointerType *Lptr, 4552 const ObjCObjectPointerType *Rptr) { 4553 const ObjCObjectType *LHS = Lptr->getObjectType(); 4554 const ObjCObjectType *RHS = Rptr->getObjectType(); 4555 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 4556 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 4557 if (!LDecl || !RDecl) 4558 return QualType(); 4559 4560 while ((LDecl = LDecl->getSuperClass())) { 4561 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl)); 4562 if (canAssignObjCInterfaces(LHS, RHS)) { 4563 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols; 4564 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols); 4565 4566 QualType Result = QualType(LHS, 0); 4567 if (!Protocols.empty()) 4568 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size()); 4569 Result = getObjCObjectPointerType(Result); 4570 return Result; 4571 } 4572 } 4573 4574 return QualType(); 4575} 4576 4577bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 4578 const ObjCObjectType *RHS) { 4579 assert(LHS->getInterface() && "LHS is not an interface type"); 4580 assert(RHS->getInterface() && "RHS is not an interface type"); 4581 4582 // Verify that the base decls are compatible: the RHS must be a subclass of 4583 // the LHS. 4584 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface())) 4585 return false; 4586 4587 // RHS must have a superset of the protocols in the LHS. If the LHS is not 4588 // protocol qualified at all, then we are good. 4589 if (LHS->getNumProtocols() == 0) 4590 return true; 4591 4592 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it 4593 // isn't a superset. 4594 if (RHS->getNumProtocols() == 0) 4595 return true; // FIXME: should return false! 4596 4597 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(), 4598 LHSPE = LHS->qual_end(); 4599 LHSPI != LHSPE; LHSPI++) { 4600 bool RHSImplementsProtocol = false; 4601 4602 // If the RHS doesn't implement the protocol on the left, the types 4603 // are incompatible. 4604 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(), 4605 RHSPE = RHS->qual_end(); 4606 RHSPI != RHSPE; RHSPI++) { 4607 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) { 4608 RHSImplementsProtocol = true; 4609 break; 4610 } 4611 } 4612 // FIXME: For better diagnostics, consider passing back the protocol name. 4613 if (!RHSImplementsProtocol) 4614 return false; 4615 } 4616 // The RHS implements all protocols listed on the LHS. 4617 return true; 4618} 4619 4620bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 4621 // get the "pointed to" types 4622 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 4623 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 4624 4625 if (!LHSOPT || !RHSOPT) 4626 return false; 4627 4628 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 4629 canAssignObjCInterfaces(RHSOPT, LHSOPT); 4630} 4631 4632bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 4633 return canAssignObjCInterfaces( 4634 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(), 4635 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>()); 4636} 4637 4638/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 4639/// both shall have the identically qualified version of a compatible type. 4640/// C99 6.2.7p1: Two types have compatible types if their types are the 4641/// same. See 6.7.[2,3,5] for additional rules. 4642bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 4643 bool CompareUnqualified) { 4644 if (getLangOptions().CPlusPlus) 4645 return hasSameType(LHS, RHS); 4646 4647 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 4648} 4649 4650bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 4651 return !mergeTypes(LHS, RHS, true).isNull(); 4652} 4653 4654QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 4655 bool OfBlockPointer, 4656 bool Unqualified) { 4657 const FunctionType *lbase = lhs->getAs<FunctionType>(); 4658 const FunctionType *rbase = rhs->getAs<FunctionType>(); 4659 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase); 4660 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase); 4661 bool allLTypes = true; 4662 bool allRTypes = true; 4663 4664 // Check return type 4665 QualType retType; 4666 if (OfBlockPointer) 4667 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true, 4668 Unqualified); 4669 else 4670 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), 4671 false, Unqualified); 4672 if (retType.isNull()) return QualType(); 4673 4674 if (Unqualified) 4675 retType = retType.getUnqualifiedType(); 4676 4677 CanQualType LRetType = getCanonicalType(lbase->getResultType()); 4678 CanQualType RRetType = getCanonicalType(rbase->getResultType()); 4679 if (Unqualified) { 4680 LRetType = LRetType.getUnqualifiedType(); 4681 RRetType = RRetType.getUnqualifiedType(); 4682 } 4683 4684 if (getCanonicalType(retType) != LRetType) 4685 allLTypes = false; 4686 if (getCanonicalType(retType) != RRetType) 4687 allRTypes = false; 4688 // FIXME: double check this 4689 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 4690 // rbase->getRegParmAttr() != 0 && 4691 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 4692 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 4693 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 4694 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() : 4695 lbaseInfo.getRegParm(); 4696 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 4697 if (NoReturn != lbaseInfo.getNoReturn() || 4698 RegParm != lbaseInfo.getRegParm()) 4699 allLTypes = false; 4700 if (NoReturn != rbaseInfo.getNoReturn() || 4701 RegParm != rbaseInfo.getRegParm()) 4702 allRTypes = false; 4703 CallingConv lcc = lbaseInfo.getCC(); 4704 CallingConv rcc = rbaseInfo.getCC(); 4705 // Compatible functions must have compatible calling conventions 4706 if (!isSameCallConv(lcc, rcc)) 4707 return QualType(); 4708 4709 if (lproto && rproto) { // two C99 style function prototypes 4710 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() && 4711 "C++ shouldn't be here"); 4712 unsigned lproto_nargs = lproto->getNumArgs(); 4713 unsigned rproto_nargs = rproto->getNumArgs(); 4714 4715 // Compatible functions must have the same number of arguments 4716 if (lproto_nargs != rproto_nargs) 4717 return QualType(); 4718 4719 // Variadic and non-variadic functions aren't compatible 4720 if (lproto->isVariadic() != rproto->isVariadic()) 4721 return QualType(); 4722 4723 if (lproto->getTypeQuals() != rproto->getTypeQuals()) 4724 return QualType(); 4725 4726 // Check argument compatibility 4727 llvm::SmallVector<QualType, 10> types; 4728 for (unsigned i = 0; i < lproto_nargs; i++) { 4729 QualType largtype = lproto->getArgType(i).getUnqualifiedType(); 4730 QualType rargtype = rproto->getArgType(i).getUnqualifiedType(); 4731 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer, 4732 Unqualified); 4733 if (argtype.isNull()) return QualType(); 4734 4735 if (Unqualified) 4736 argtype = argtype.getUnqualifiedType(); 4737 4738 types.push_back(argtype); 4739 if (Unqualified) { 4740 largtype = largtype.getUnqualifiedType(); 4741 rargtype = rargtype.getUnqualifiedType(); 4742 } 4743 4744 if (getCanonicalType(argtype) != getCanonicalType(largtype)) 4745 allLTypes = false; 4746 if (getCanonicalType(argtype) != getCanonicalType(rargtype)) 4747 allRTypes = false; 4748 } 4749 if (allLTypes) return lhs; 4750 if (allRTypes) return rhs; 4751 return getFunctionType(retType, types.begin(), types.size(), 4752 lproto->isVariadic(), lproto->getTypeQuals(), 4753 false, false, 0, 0, 4754 FunctionType::ExtInfo(NoReturn, RegParm, lcc)); 4755 } 4756 4757 if (lproto) allRTypes = false; 4758 if (rproto) allLTypes = false; 4759 4760 const FunctionProtoType *proto = lproto ? lproto : rproto; 4761 if (proto) { 4762 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here"); 4763 if (proto->isVariadic()) return QualType(); 4764 // Check that the types are compatible with the types that 4765 // would result from default argument promotions (C99 6.7.5.3p15). 4766 // The only types actually affected are promotable integer 4767 // types and floats, which would be passed as a different 4768 // type depending on whether the prototype is visible. 4769 unsigned proto_nargs = proto->getNumArgs(); 4770 for (unsigned i = 0; i < proto_nargs; ++i) { 4771 QualType argTy = proto->getArgType(i); 4772 4773 // Look at the promotion type of enum types, since that is the type used 4774 // to pass enum values. 4775 if (const EnumType *Enum = argTy->getAs<EnumType>()) 4776 argTy = Enum->getDecl()->getPromotionType(); 4777 4778 if (argTy->isPromotableIntegerType() || 4779 getCanonicalType(argTy).getUnqualifiedType() == FloatTy) 4780 return QualType(); 4781 } 4782 4783 if (allLTypes) return lhs; 4784 if (allRTypes) return rhs; 4785 return getFunctionType(retType, proto->arg_type_begin(), 4786 proto->getNumArgs(), proto->isVariadic(), 4787 proto->getTypeQuals(), 4788 false, false, 0, 0, 4789 FunctionType::ExtInfo(NoReturn, RegParm, lcc)); 4790 } 4791 4792 if (allLTypes) return lhs; 4793 if (allRTypes) return rhs; 4794 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc); 4795 return getFunctionNoProtoType(retType, Info); 4796} 4797 4798QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 4799 bool OfBlockPointer, 4800 bool Unqualified) { 4801 // C++ [expr]: If an expression initially has the type "reference to T", the 4802 // type is adjusted to "T" prior to any further analysis, the expression 4803 // designates the object or function denoted by the reference, and the 4804 // expression is an lvalue unless the reference is an rvalue reference and 4805 // the expression is a function call (possibly inside parentheses). 4806 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?"); 4807 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?"); 4808 4809 if (Unqualified) { 4810 LHS = LHS.getUnqualifiedType(); 4811 RHS = RHS.getUnqualifiedType(); 4812 } 4813 4814 QualType LHSCan = getCanonicalType(LHS), 4815 RHSCan = getCanonicalType(RHS); 4816 4817 // If two types are identical, they are compatible. 4818 if (LHSCan == RHSCan) 4819 return LHS; 4820 4821 // If the qualifiers are different, the types aren't compatible... mostly. 4822 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 4823 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 4824 if (LQuals != RQuals) { 4825 // If any of these qualifiers are different, we have a type 4826 // mismatch. 4827 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 4828 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 4829 return QualType(); 4830 4831 // Exactly one GC qualifier difference is allowed: __strong is 4832 // okay if the other type has no GC qualifier but is an Objective 4833 // C object pointer (i.e. implicitly strong by default). We fix 4834 // this by pretending that the unqualified type was actually 4835 // qualified __strong. 4836 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 4837 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 4838 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 4839 4840 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 4841 return QualType(); 4842 4843 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 4844 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 4845 } 4846 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 4847 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 4848 } 4849 return QualType(); 4850 } 4851 4852 // Okay, qualifiers are equal. 4853 4854 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 4855 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 4856 4857 // We want to consider the two function types to be the same for these 4858 // comparisons, just force one to the other. 4859 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 4860 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 4861 4862 // Same as above for arrays 4863 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 4864 LHSClass = Type::ConstantArray; 4865 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 4866 RHSClass = Type::ConstantArray; 4867 4868 // ObjCInterfaces are just specialized ObjCObjects. 4869 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 4870 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 4871 4872 // Canonicalize ExtVector -> Vector. 4873 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 4874 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 4875 4876 // If the canonical type classes don't match. 4877 if (LHSClass != RHSClass) { 4878 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 4879 // a signed integer type, or an unsigned integer type. 4880 // Compatibility is based on the underlying type, not the promotion 4881 // type. 4882 if (const EnumType* ETy = LHS->getAs<EnumType>()) { 4883 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType()) 4884 return RHS; 4885 } 4886 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 4887 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType()) 4888 return LHS; 4889 } 4890 4891 return QualType(); 4892 } 4893 4894 // The canonical type classes match. 4895 switch (LHSClass) { 4896#define TYPE(Class, Base) 4897#define ABSTRACT_TYPE(Class, Base) 4898#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 4899#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 4900#define DEPENDENT_TYPE(Class, Base) case Type::Class: 4901#include "clang/AST/TypeNodes.def" 4902 assert(false && "Non-canonical and dependent types shouldn't get here"); 4903 return QualType(); 4904 4905 case Type::LValueReference: 4906 case Type::RValueReference: 4907 case Type::MemberPointer: 4908 assert(false && "C++ should never be in mergeTypes"); 4909 return QualType(); 4910 4911 case Type::ObjCInterface: 4912 case Type::IncompleteArray: 4913 case Type::VariableArray: 4914 case Type::FunctionProto: 4915 case Type::ExtVector: 4916 assert(false && "Types are eliminated above"); 4917 return QualType(); 4918 4919 case Type::Pointer: 4920 { 4921 // Merge two pointer types, while trying to preserve typedef info 4922 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType(); 4923 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType(); 4924 if (Unqualified) { 4925 LHSPointee = LHSPointee.getUnqualifiedType(); 4926 RHSPointee = RHSPointee.getUnqualifiedType(); 4927 } 4928 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 4929 Unqualified); 4930 if (ResultType.isNull()) return QualType(); 4931 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 4932 return LHS; 4933 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 4934 return RHS; 4935 return getPointerType(ResultType); 4936 } 4937 case Type::BlockPointer: 4938 { 4939 // Merge two block pointer types, while trying to preserve typedef info 4940 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType(); 4941 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType(); 4942 if (Unqualified) { 4943 LHSPointee = LHSPointee.getUnqualifiedType(); 4944 RHSPointee = RHSPointee.getUnqualifiedType(); 4945 } 4946 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 4947 Unqualified); 4948 if (ResultType.isNull()) return QualType(); 4949 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 4950 return LHS; 4951 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 4952 return RHS; 4953 return getBlockPointerType(ResultType); 4954 } 4955 case Type::ConstantArray: 4956 { 4957 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 4958 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 4959 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 4960 return QualType(); 4961 4962 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 4963 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 4964 if (Unqualified) { 4965 LHSElem = LHSElem.getUnqualifiedType(); 4966 RHSElem = RHSElem.getUnqualifiedType(); 4967 } 4968 4969 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 4970 if (ResultType.isNull()) return QualType(); 4971 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 4972 return LHS; 4973 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 4974 return RHS; 4975 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), 4976 ArrayType::ArraySizeModifier(), 0); 4977 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), 4978 ArrayType::ArraySizeModifier(), 0); 4979 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 4980 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 4981 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 4982 return LHS; 4983 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 4984 return RHS; 4985 if (LVAT) { 4986 // FIXME: This isn't correct! But tricky to implement because 4987 // the array's size has to be the size of LHS, but the type 4988 // has to be different. 4989 return LHS; 4990 } 4991 if (RVAT) { 4992 // FIXME: This isn't correct! But tricky to implement because 4993 // the array's size has to be the size of RHS, but the type 4994 // has to be different. 4995 return RHS; 4996 } 4997 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 4998 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 4999 return getIncompleteArrayType(ResultType, 5000 ArrayType::ArraySizeModifier(), 0); 5001 } 5002 case Type::FunctionNoProto: 5003 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 5004 case Type::Record: 5005 case Type::Enum: 5006 return QualType(); 5007 case Type::Builtin: 5008 // Only exactly equal builtin types are compatible, which is tested above. 5009 return QualType(); 5010 case Type::Complex: 5011 // Distinct complex types are incompatible. 5012 return QualType(); 5013 case Type::Vector: 5014 // FIXME: The merged type should be an ExtVector! 5015 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(), 5016 RHSCan->getAs<VectorType>())) 5017 return LHS; 5018 return QualType(); 5019 case Type::ObjCObject: { 5020 // Check if the types are assignment compatible. 5021 // FIXME: This should be type compatibility, e.g. whether 5022 // "LHS x; RHS x;" at global scope is legal. 5023 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>(); 5024 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>(); 5025 if (canAssignObjCInterfaces(LHSIface, RHSIface)) 5026 return LHS; 5027 5028 return QualType(); 5029 } 5030 case Type::ObjCObjectPointer: { 5031 if (OfBlockPointer) { 5032 if (canAssignObjCInterfacesInBlockPointer( 5033 LHS->getAs<ObjCObjectPointerType>(), 5034 RHS->getAs<ObjCObjectPointerType>())) 5035 return LHS; 5036 return QualType(); 5037 } 5038 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(), 5039 RHS->getAs<ObjCObjectPointerType>())) 5040 return LHS; 5041 5042 return QualType(); 5043 } 5044 } 5045 5046 return QualType(); 5047} 5048 5049/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 5050/// 'RHS' attributes and returns the merged version; including for function 5051/// return types. 5052QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 5053 QualType LHSCan = getCanonicalType(LHS), 5054 RHSCan = getCanonicalType(RHS); 5055 // If two types are identical, they are compatible. 5056 if (LHSCan == RHSCan) 5057 return LHS; 5058 if (RHSCan->isFunctionType()) { 5059 if (!LHSCan->isFunctionType()) 5060 return QualType(); 5061 QualType OldReturnType = 5062 cast<FunctionType>(RHSCan.getTypePtr())->getResultType(); 5063 QualType NewReturnType = 5064 cast<FunctionType>(LHSCan.getTypePtr())->getResultType(); 5065 QualType ResReturnType = 5066 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 5067 if (ResReturnType.isNull()) 5068 return QualType(); 5069 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 5070 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 5071 // In either case, use OldReturnType to build the new function type. 5072 const FunctionType *F = LHS->getAs<FunctionType>(); 5073 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) { 5074 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS); 5075 QualType ResultType 5076 = getFunctionType(OldReturnType, FPT->arg_type_begin(), 5077 FPT->getNumArgs(), FPT->isVariadic(), 5078 FPT->getTypeQuals(), 5079 FPT->hasExceptionSpec(), 5080 FPT->hasAnyExceptionSpec(), 5081 FPT->getNumExceptions(), 5082 FPT->exception_begin(), 5083 Info); 5084 return ResultType; 5085 } 5086 } 5087 return QualType(); 5088 } 5089 5090 // If the qualifiers are different, the types can still be merged. 5091 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 5092 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 5093 if (LQuals != RQuals) { 5094 // If any of these qualifiers are different, we have a type mismatch. 5095 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 5096 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 5097 return QualType(); 5098 5099 // Exactly one GC qualifier difference is allowed: __strong is 5100 // okay if the other type has no GC qualifier but is an Objective 5101 // C object pointer (i.e. implicitly strong by default). We fix 5102 // this by pretending that the unqualified type was actually 5103 // qualified __strong. 5104 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 5105 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 5106 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 5107 5108 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 5109 return QualType(); 5110 5111 if (GC_L == Qualifiers::Strong) 5112 return LHS; 5113 if (GC_R == Qualifiers::Strong) 5114 return RHS; 5115 return QualType(); 5116 } 5117 5118 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 5119 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 5120 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 5121 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 5122 if (ResQT == LHSBaseQT) 5123 return LHS; 5124 if (ResQT == RHSBaseQT) 5125 return RHS; 5126 } 5127 return QualType(); 5128} 5129 5130//===----------------------------------------------------------------------===// 5131// Integer Predicates 5132//===----------------------------------------------------------------------===// 5133 5134unsigned ASTContext::getIntWidth(QualType T) { 5135 if (T->isBooleanType()) 5136 return 1; 5137 if (EnumType *ET = dyn_cast<EnumType>(T)) 5138 T = ET->getDecl()->getIntegerType(); 5139 // For builtin types, just use the standard type sizing method 5140 return (unsigned)getTypeSize(T); 5141} 5142 5143QualType ASTContext::getCorrespondingUnsignedType(QualType T) { 5144 assert(T->hasSignedIntegerRepresentation() && "Unexpected type"); 5145 5146 // Turn <4 x signed int> -> <4 x unsigned int> 5147 if (const VectorType *VTy = T->getAs<VectorType>()) 5148 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 5149 VTy->getNumElements(), VTy->getAltiVecSpecific()); 5150 5151 // For enums, we return the unsigned version of the base type. 5152 if (const EnumType *ETy = T->getAs<EnumType>()) 5153 T = ETy->getDecl()->getIntegerType(); 5154 5155 const BuiltinType *BTy = T->getAs<BuiltinType>(); 5156 assert(BTy && "Unexpected signed integer type"); 5157 switch (BTy->getKind()) { 5158 case BuiltinType::Char_S: 5159 case BuiltinType::SChar: 5160 return UnsignedCharTy; 5161 case BuiltinType::Short: 5162 return UnsignedShortTy; 5163 case BuiltinType::Int: 5164 return UnsignedIntTy; 5165 case BuiltinType::Long: 5166 return UnsignedLongTy; 5167 case BuiltinType::LongLong: 5168 return UnsignedLongLongTy; 5169 case BuiltinType::Int128: 5170 return UnsignedInt128Ty; 5171 default: 5172 assert(0 && "Unexpected signed integer type"); 5173 return QualType(); 5174 } 5175} 5176 5177ExternalASTSource::~ExternalASTSource() { } 5178 5179void ExternalASTSource::PrintStats() { } 5180 5181 5182//===----------------------------------------------------------------------===// 5183// Builtin Type Computation 5184//===----------------------------------------------------------------------===// 5185 5186/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 5187/// pointer over the consumed characters. This returns the resultant type. 5188static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context, 5189 ASTContext::GetBuiltinTypeError &Error, 5190 bool AllowTypeModifiers = true) { 5191 // Modifiers. 5192 int HowLong = 0; 5193 bool Signed = false, Unsigned = false; 5194 5195 // Read the modifiers first. 5196 bool Done = false; 5197 while (!Done) { 5198 switch (*Str++) { 5199 default: Done = true; --Str; break; 5200 case 'S': 5201 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 5202 assert(!Signed && "Can't use 'S' modifier multiple times!"); 5203 Signed = true; 5204 break; 5205 case 'U': 5206 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 5207 assert(!Unsigned && "Can't use 'S' modifier multiple times!"); 5208 Unsigned = true; 5209 break; 5210 case 'L': 5211 assert(HowLong <= 2 && "Can't have LLLL modifier"); 5212 ++HowLong; 5213 break; 5214 } 5215 } 5216 5217 QualType Type; 5218 5219 // Read the base type. 5220 switch (*Str++) { 5221 default: assert(0 && "Unknown builtin type letter!"); 5222 case 'v': 5223 assert(HowLong == 0 && !Signed && !Unsigned && 5224 "Bad modifiers used with 'v'!"); 5225 Type = Context.VoidTy; 5226 break; 5227 case 'f': 5228 assert(HowLong == 0 && !Signed && !Unsigned && 5229 "Bad modifiers used with 'f'!"); 5230 Type = Context.FloatTy; 5231 break; 5232 case 'd': 5233 assert(HowLong < 2 && !Signed && !Unsigned && 5234 "Bad modifiers used with 'd'!"); 5235 if (HowLong) 5236 Type = Context.LongDoubleTy; 5237 else 5238 Type = Context.DoubleTy; 5239 break; 5240 case 's': 5241 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 5242 if (Unsigned) 5243 Type = Context.UnsignedShortTy; 5244 else 5245 Type = Context.ShortTy; 5246 break; 5247 case 'i': 5248 if (HowLong == 3) 5249 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 5250 else if (HowLong == 2) 5251 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 5252 else if (HowLong == 1) 5253 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 5254 else 5255 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 5256 break; 5257 case 'c': 5258 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 5259 if (Signed) 5260 Type = Context.SignedCharTy; 5261 else if (Unsigned) 5262 Type = Context.UnsignedCharTy; 5263 else 5264 Type = Context.CharTy; 5265 break; 5266 case 'b': // boolean 5267 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 5268 Type = Context.BoolTy; 5269 break; 5270 case 'z': // size_t. 5271 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 5272 Type = Context.getSizeType(); 5273 break; 5274 case 'F': 5275 Type = Context.getCFConstantStringType(); 5276 break; 5277 case 'a': 5278 Type = Context.getBuiltinVaListType(); 5279 assert(!Type.isNull() && "builtin va list type not initialized!"); 5280 break; 5281 case 'A': 5282 // This is a "reference" to a va_list; however, what exactly 5283 // this means depends on how va_list is defined. There are two 5284 // different kinds of va_list: ones passed by value, and ones 5285 // passed by reference. An example of a by-value va_list is 5286 // x86, where va_list is a char*. An example of by-ref va_list 5287 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 5288 // we want this argument to be a char*&; for x86-64, we want 5289 // it to be a __va_list_tag*. 5290 Type = Context.getBuiltinVaListType(); 5291 assert(!Type.isNull() && "builtin va list type not initialized!"); 5292 if (Type->isArrayType()) { 5293 Type = Context.getArrayDecayedType(Type); 5294 } else { 5295 Type = Context.getLValueReferenceType(Type); 5296 } 5297 break; 5298 case 'V': { 5299 char *End; 5300 unsigned NumElements = strtoul(Str, &End, 10); 5301 assert(End != Str && "Missing vector size"); 5302 5303 Str = End; 5304 5305 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false); 5306 // FIXME: Don't know what to do about AltiVec. 5307 Type = Context.getVectorType(ElementType, NumElements, 5308 VectorType::NotAltiVec); 5309 break; 5310 } 5311 case 'X': { 5312 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false); 5313 Type = Context.getComplexType(ElementType); 5314 break; 5315 } 5316 case 'P': 5317 Type = Context.getFILEType(); 5318 if (Type.isNull()) { 5319 Error = ASTContext::GE_Missing_stdio; 5320 return QualType(); 5321 } 5322 break; 5323 case 'J': 5324 if (Signed) 5325 Type = Context.getsigjmp_bufType(); 5326 else 5327 Type = Context.getjmp_bufType(); 5328 5329 if (Type.isNull()) { 5330 Error = ASTContext::GE_Missing_setjmp; 5331 return QualType(); 5332 } 5333 break; 5334 } 5335 5336 if (!AllowTypeModifiers) 5337 return Type; 5338 5339 Done = false; 5340 while (!Done) { 5341 switch (char c = *Str++) { 5342 default: Done = true; --Str; break; 5343 case '*': 5344 case '&': 5345 { 5346 // Both pointers and references can have their pointee types 5347 // qualified with an address space. 5348 char *End; 5349 unsigned AddrSpace = strtoul(Str, &End, 10); 5350 if (End != Str && AddrSpace != 0) { 5351 Type = Context.getAddrSpaceQualType(Type, AddrSpace); 5352 Str = End; 5353 } 5354 } 5355 if (c == '*') 5356 Type = Context.getPointerType(Type); 5357 else 5358 Type = Context.getLValueReferenceType(Type); 5359 break; 5360 // FIXME: There's no way to have a built-in with an rvalue ref arg. 5361 case 'C': 5362 Type = Type.withConst(); 5363 break; 5364 case 'D': 5365 Type = Context.getVolatileType(Type); 5366 break; 5367 } 5368 } 5369 5370 return Type; 5371} 5372 5373/// GetBuiltinType - Return the type for the specified builtin. 5374QualType ASTContext::GetBuiltinType(unsigned id, 5375 GetBuiltinTypeError &Error) { 5376 const char *TypeStr = BuiltinInfo.GetTypeString(id); 5377 5378 llvm::SmallVector<QualType, 8> ArgTypes; 5379 5380 Error = GE_None; 5381 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error); 5382 if (Error != GE_None) 5383 return QualType(); 5384 while (TypeStr[0] && TypeStr[0] != '.') { 5385 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error); 5386 if (Error != GE_None) 5387 return QualType(); 5388 5389 // Do array -> pointer decay. The builtin should use the decayed type. 5390 if (Ty->isArrayType()) 5391 Ty = getArrayDecayedType(Ty); 5392 5393 ArgTypes.push_back(Ty); 5394 } 5395 5396 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 5397 "'.' should only occur at end of builtin type list!"); 5398 5399 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);". 5400 if (ArgTypes.size() == 0 && TypeStr[0] == '.') 5401 return getFunctionNoProtoType(ResType); 5402 5403 // FIXME: Should we create noreturn types? 5404 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), 5405 TypeStr[0] == '.', 0, false, false, 0, 0, 5406 FunctionType::ExtInfo()); 5407} 5408 5409QualType 5410ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) { 5411 // Perform the usual unary conversions. We do this early so that 5412 // integral promotions to "int" can allow us to exit early, in the 5413 // lhs == rhs check. Also, for conversion purposes, we ignore any 5414 // qualifiers. For example, "const float" and "float" are 5415 // equivalent. 5416 if (lhs->isPromotableIntegerType()) 5417 lhs = getPromotedIntegerType(lhs); 5418 else 5419 lhs = lhs.getUnqualifiedType(); 5420 if (rhs->isPromotableIntegerType()) 5421 rhs = getPromotedIntegerType(rhs); 5422 else 5423 rhs = rhs.getUnqualifiedType(); 5424 5425 // If both types are identical, no conversion is needed. 5426 if (lhs == rhs) 5427 return lhs; 5428 5429 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 5430 // The caller can deal with this (e.g. pointer + int). 5431 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 5432 return lhs; 5433 5434 // At this point, we have two different arithmetic types. 5435 5436 // Handle complex types first (C99 6.3.1.8p1). 5437 if (lhs->isComplexType() || rhs->isComplexType()) { 5438 // if we have an integer operand, the result is the complex type. 5439 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { 5440 // convert the rhs to the lhs complex type. 5441 return lhs; 5442 } 5443 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { 5444 // convert the lhs to the rhs complex type. 5445 return rhs; 5446 } 5447 // This handles complex/complex, complex/float, or float/complex. 5448 // When both operands are complex, the shorter operand is converted to the 5449 // type of the longer, and that is the type of the result. This corresponds 5450 // to what is done when combining two real floating-point operands. 5451 // The fun begins when size promotion occur across type domains. 5452 // From H&S 6.3.4: When one operand is complex and the other is a real 5453 // floating-point type, the less precise type is converted, within it's 5454 // real or complex domain, to the precision of the other type. For example, 5455 // when combining a "long double" with a "double _Complex", the 5456 // "double _Complex" is promoted to "long double _Complex". 5457 int result = getFloatingTypeOrder(lhs, rhs); 5458 5459 if (result > 0) { // The left side is bigger, convert rhs. 5460 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs); 5461 } else if (result < 0) { // The right side is bigger, convert lhs. 5462 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs); 5463 } 5464 // At this point, lhs and rhs have the same rank/size. Now, make sure the 5465 // domains match. This is a requirement for our implementation, C99 5466 // does not require this promotion. 5467 if (lhs != rhs) { // Domains don't match, we have complex/float mix. 5468 if (lhs->isRealFloatingType()) { // handle "double, _Complex double". 5469 return rhs; 5470 } else { // handle "_Complex double, double". 5471 return lhs; 5472 } 5473 } 5474 return lhs; // The domain/size match exactly. 5475 } 5476 // Now handle "real" floating types (i.e. float, double, long double). 5477 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) { 5478 // if we have an integer operand, the result is the real floating type. 5479 if (rhs->isIntegerType()) { 5480 // convert rhs to the lhs floating point type. 5481 return lhs; 5482 } 5483 if (rhs->isComplexIntegerType()) { 5484 // convert rhs to the complex floating point type. 5485 return getComplexType(lhs); 5486 } 5487 if (lhs->isIntegerType()) { 5488 // convert lhs to the rhs floating point type. 5489 return rhs; 5490 } 5491 if (lhs->isComplexIntegerType()) { 5492 // convert lhs to the complex floating point type. 5493 return getComplexType(rhs); 5494 } 5495 // We have two real floating types, float/complex combos were handled above. 5496 // Convert the smaller operand to the bigger result. 5497 int result = getFloatingTypeOrder(lhs, rhs); 5498 if (result > 0) // convert the rhs 5499 return lhs; 5500 assert(result < 0 && "illegal float comparison"); 5501 return rhs; // convert the lhs 5502 } 5503 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) { 5504 // Handle GCC complex int extension. 5505 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType(); 5506 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType(); 5507 5508 if (lhsComplexInt && rhsComplexInt) { 5509 if (getIntegerTypeOrder(lhsComplexInt->getElementType(), 5510 rhsComplexInt->getElementType()) >= 0) 5511 return lhs; // convert the rhs 5512 return rhs; 5513 } else if (lhsComplexInt && rhs->isIntegerType()) { 5514 // convert the rhs to the lhs complex type. 5515 return lhs; 5516 } else if (rhsComplexInt && lhs->isIntegerType()) { 5517 // convert the lhs to the rhs complex type. 5518 return rhs; 5519 } 5520 } 5521 // Finally, we have two differing integer types. 5522 // The rules for this case are in C99 6.3.1.8 5523 int compare = getIntegerTypeOrder(lhs, rhs); 5524 bool lhsSigned = lhs->hasSignedIntegerRepresentation(), 5525 rhsSigned = rhs->hasSignedIntegerRepresentation(); 5526 QualType destType; 5527 if (lhsSigned == rhsSigned) { 5528 // Same signedness; use the higher-ranked type 5529 destType = compare >= 0 ? lhs : rhs; 5530 } else if (compare != (lhsSigned ? 1 : -1)) { 5531 // The unsigned type has greater than or equal rank to the 5532 // signed type, so use the unsigned type 5533 destType = lhsSigned ? rhs : lhs; 5534 } else if (getIntWidth(lhs) != getIntWidth(rhs)) { 5535 // The two types are different widths; if we are here, that 5536 // means the signed type is larger than the unsigned type, so 5537 // use the signed type. 5538 destType = lhsSigned ? lhs : rhs; 5539 } else { 5540 // The signed type is higher-ranked than the unsigned type, 5541 // but isn't actually any bigger (like unsigned int and long 5542 // on most 32-bit systems). Use the unsigned type corresponding 5543 // to the signed type. 5544 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs); 5545 } 5546 return destType; 5547} 5548 5549GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) { 5550 GVALinkage External = GVA_StrongExternal; 5551 5552 Linkage L = FD->getLinkage(); 5553 if (L == ExternalLinkage && getLangOptions().CPlusPlus && 5554 FD->getType()->getLinkage() == UniqueExternalLinkage) 5555 L = UniqueExternalLinkage; 5556 5557 switch (L) { 5558 case NoLinkage: 5559 case InternalLinkage: 5560 case UniqueExternalLinkage: 5561 return GVA_Internal; 5562 5563 case ExternalLinkage: 5564 switch (FD->getTemplateSpecializationKind()) { 5565 case TSK_Undeclared: 5566 case TSK_ExplicitSpecialization: 5567 External = GVA_StrongExternal; 5568 break; 5569 5570 case TSK_ExplicitInstantiationDefinition: 5571 return GVA_ExplicitTemplateInstantiation; 5572 5573 case TSK_ExplicitInstantiationDeclaration: 5574 case TSK_ImplicitInstantiation: 5575 External = GVA_TemplateInstantiation; 5576 break; 5577 } 5578 } 5579 5580 if (!FD->isInlined()) 5581 return External; 5582 5583 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) { 5584 // GNU or C99 inline semantics. Determine whether this symbol should be 5585 // externally visible. 5586 if (FD->isInlineDefinitionExternallyVisible()) 5587 return External; 5588 5589 // C99 inline semantics, where the symbol is not externally visible. 5590 return GVA_C99Inline; 5591 } 5592 5593 // C++0x [temp.explicit]p9: 5594 // [ Note: The intent is that an inline function that is the subject of 5595 // an explicit instantiation declaration will still be implicitly 5596 // instantiated when used so that the body can be considered for 5597 // inlining, but that no out-of-line copy of the inline function would be 5598 // generated in the translation unit. -- end note ] 5599 if (FD->getTemplateSpecializationKind() 5600 == TSK_ExplicitInstantiationDeclaration) 5601 return GVA_C99Inline; 5602 5603 return GVA_CXXInline; 5604} 5605 5606GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 5607 // If this is a static data member, compute the kind of template 5608 // specialization. Otherwise, this variable is not part of a 5609 // template. 5610 TemplateSpecializationKind TSK = TSK_Undeclared; 5611 if (VD->isStaticDataMember()) 5612 TSK = VD->getTemplateSpecializationKind(); 5613 5614 Linkage L = VD->getLinkage(); 5615 if (L == ExternalLinkage && getLangOptions().CPlusPlus && 5616 VD->getType()->getLinkage() == UniqueExternalLinkage) 5617 L = UniqueExternalLinkage; 5618 5619 switch (L) { 5620 case NoLinkage: 5621 case InternalLinkage: 5622 case UniqueExternalLinkage: 5623 return GVA_Internal; 5624 5625 case ExternalLinkage: 5626 switch (TSK) { 5627 case TSK_Undeclared: 5628 case TSK_ExplicitSpecialization: 5629 return GVA_StrongExternal; 5630 5631 case TSK_ExplicitInstantiationDeclaration: 5632 llvm_unreachable("Variable should not be instantiated"); 5633 // Fall through to treat this like any other instantiation. 5634 5635 case TSK_ExplicitInstantiationDefinition: 5636 return GVA_ExplicitTemplateInstantiation; 5637 5638 case TSK_ImplicitInstantiation: 5639 return GVA_TemplateInstantiation; 5640 } 5641 } 5642 5643 return GVA_StrongExternal; 5644} 5645 5646bool ASTContext::DeclMustBeEmitted(const Decl *D) { 5647 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 5648 if (!VD->isFileVarDecl()) 5649 return false; 5650 } else if (!isa<FunctionDecl>(D)) 5651 return false; 5652 5653 // Weak references don't produce any output by themselves. 5654 if (D->hasAttr<WeakRefAttr>()) 5655 return false; 5656 5657 // Aliases and used decls are required. 5658 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 5659 return true; 5660 5661 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5662 // Forward declarations aren't required. 5663 if (!FD->isThisDeclarationADefinition()) 5664 return false; 5665 5666 // Constructors and destructors are required. 5667 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 5668 return true; 5669 5670 // The key function for a class is required. 5671 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 5672 const CXXRecordDecl *RD = MD->getParent(); 5673 if (MD->isOutOfLine() && RD->isDynamicClass()) { 5674 const CXXMethodDecl *KeyFunc = getKeyFunction(RD); 5675 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 5676 return true; 5677 } 5678 } 5679 5680 GVALinkage Linkage = GetGVALinkageForFunction(FD); 5681 5682 // static, static inline, always_inline, and extern inline functions can 5683 // always be deferred. Normal inline functions can be deferred in C99/C++. 5684 // Implicit template instantiations can also be deferred in C++. 5685 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline || 5686 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 5687 return false; 5688 return true; 5689 } 5690 5691 const VarDecl *VD = cast<VarDecl>(D); 5692 assert(VD->isFileVarDecl() && "Expected file scoped var"); 5693 5694 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) 5695 return false; 5696 5697 // Structs that have non-trivial constructors or destructors are required. 5698 5699 // FIXME: Handle references. 5700 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) { 5701 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 5702 if (RD->hasDefinition() && 5703 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor())) 5704 return true; 5705 } 5706 } 5707 5708 GVALinkage L = GetGVALinkageForVariable(VD); 5709 if (L == GVA_Internal || L == GVA_TemplateInstantiation) { 5710 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this))) 5711 return false; 5712 } 5713 5714 return true; 5715} 5716 5717CXXABI::~CXXABI() {} 5718