Sema.cpp revision aeb70b12ab1af1ba7e5e48cee3903d1a768bca90
1//===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===// 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 actions class which performs semantic analysis and 11// builds an AST out of a parse stream. 12// 13//===----------------------------------------------------------------------===// 14 15#include "clang/Sema/Sema.h" 16#include "TargetAttributesSema.h" 17#include "llvm/ADT/DenseMap.h" 18#include "llvm/ADT/SmallSet.h" 19#include "llvm/ADT/APFloat.h" 20#include "clang/Sema/CXXFieldCollector.h" 21#include "clang/Sema/ExternalSemaSource.h" 22#include "clang/Sema/Scope.h" 23#include "clang/Sema/ScopeInfo.h" 24#include "clang/Sema/SemaConsumer.h" 25#include "clang/AST/ASTContext.h" 26#include "clang/AST/ASTDiagnostic.h" 27#include "clang/AST/DeclCXX.h" 28#include "clang/AST/DeclObjC.h" 29#include "clang/AST/Expr.h" 30#include "clang/Lex/Preprocessor.h" 31#include "clang/Basic/PartialDiagnostic.h" 32#include "clang/Basic/TargetInfo.h" 33using namespace clang; 34using namespace sema; 35 36FunctionScopeInfo::~FunctionScopeInfo() { } 37 38void FunctionScopeInfo::Clear(unsigned NumErrors) { 39 HasBranchProtectedScope = false; 40 HasBranchIntoScope = false; 41 HasIndirectGoto = false; 42 43 LabelMap.clear(); 44 SwitchStack.clear(); 45 Returns.clear(); 46 NumErrorsAtStartOfFunction = NumErrors; 47} 48 49BlockScopeInfo::~BlockScopeInfo() { } 50 51void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) { 52 TUScope = S; 53 PushDeclContext(S, Context.getTranslationUnitDecl()); 54 55 VAListTagName = PP.getIdentifierInfo("__va_list_tag"); 56 57 if (!Context.isInt128Installed() && // May be set by ASTReader. 58 PP.getTargetInfo().getPointerWidth(0) >= 64) { 59 TypeSourceInfo *TInfo; 60 61 // Install [u]int128_t for 64-bit targets. 62 TInfo = Context.getTrivialTypeSourceInfo(Context.Int128Ty); 63 PushOnScopeChains(TypedefDecl::Create(Context, CurContext, 64 SourceLocation(), 65 &Context.Idents.get("__int128_t"), 66 TInfo), TUScope); 67 68 TInfo = Context.getTrivialTypeSourceInfo(Context.UnsignedInt128Ty); 69 PushOnScopeChains(TypedefDecl::Create(Context, CurContext, 70 SourceLocation(), 71 &Context.Idents.get("__uint128_t"), 72 TInfo), TUScope); 73 Context.setInt128Installed(); 74 } 75 76 77 if (!PP.getLangOptions().ObjC1) return; 78 79 // Built-in ObjC types may already be set by ASTReader (hence isNull checks). 80 if (Context.getObjCSelType().isNull()) { 81 // Create the built-in typedef for 'SEL'. 82 QualType SelT = Context.getPointerType(Context.ObjCBuiltinSelTy); 83 TypeSourceInfo *SelInfo = Context.getTrivialTypeSourceInfo(SelT); 84 TypedefDecl *SelTypedef 85 = TypedefDecl::Create(Context, CurContext, SourceLocation(), 86 &Context.Idents.get("SEL"), SelInfo); 87 PushOnScopeChains(SelTypedef, TUScope); 88 Context.setObjCSelType(Context.getTypeDeclType(SelTypedef)); 89 Context.ObjCSelRedefinitionType = Context.getObjCSelType(); 90 } 91 92 // Synthesize "@class Protocol; 93 if (Context.getObjCProtoType().isNull()) { 94 ObjCInterfaceDecl *ProtocolDecl = 95 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(), 96 &Context.Idents.get("Protocol"), 97 SourceLocation(), true); 98 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl)); 99 PushOnScopeChains(ProtocolDecl, TUScope, false); 100 } 101 // Create the built-in typedef for 'id'. 102 if (Context.getObjCIdType().isNull()) { 103 QualType T = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 0, 0); 104 T = Context.getObjCObjectPointerType(T); 105 TypeSourceInfo *IdInfo = Context.getTrivialTypeSourceInfo(T); 106 TypedefDecl *IdTypedef 107 = TypedefDecl::Create(Context, CurContext, SourceLocation(), 108 &Context.Idents.get("id"), IdInfo); 109 PushOnScopeChains(IdTypedef, TUScope); 110 Context.setObjCIdType(Context.getTypeDeclType(IdTypedef)); 111 Context.ObjCIdRedefinitionType = Context.getObjCIdType(); 112 } 113 // Create the built-in typedef for 'Class'. 114 if (Context.getObjCClassType().isNull()) { 115 QualType T = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 0, 0); 116 T = Context.getObjCObjectPointerType(T); 117 TypeSourceInfo *ClassInfo = Context.getTrivialTypeSourceInfo(T); 118 TypedefDecl *ClassTypedef 119 = TypedefDecl::Create(Context, CurContext, SourceLocation(), 120 &Context.Idents.get("Class"), ClassInfo); 121 PushOnScopeChains(ClassTypedef, TUScope); 122 Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef)); 123 Context.ObjCClassRedefinitionType = Context.getObjCClassType(); 124 } 125} 126 127Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 128 bool CompleteTranslationUnit, 129 CodeCompleteConsumer *CodeCompleter) 130 : TheTargetAttributesSema(0), 131 LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer), 132 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()), 133 ExternalSource(0), CodeCompleter(CodeCompleter), CurContext(0), 134 PackContext(0), VisContext(0), ParsingDeclDepth(0), 135 IdResolver(pp.getLangOptions()), GlobalNewDeleteDeclared(false), 136 CompleteTranslationUnit(CompleteTranslationUnit), 137 NumSFINAEErrors(0), SuppressAccessChecking(false), 138 NonInstantiationEntries(0), CurrentInstantiationScope(0), TyposCorrected(0), 139 AnalysisWarnings(*this) 140{ 141 TUScope = 0; 142 if (getLangOptions().CPlusPlus) 143 FieldCollector.reset(new CXXFieldCollector()); 144 145 // Tell diagnostics how to render things from the AST library. 146 PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument, 147 &Context); 148 149 ExprEvalContexts.push_back( 150 ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0)); 151 152 FunctionScopes.push_back(new FunctionScopeInfo(Diags.getNumErrors())); 153} 154 155void Sema::Initialize() { 156 // Tell the AST consumer about this Sema object. 157 Consumer.Initialize(Context); 158 159 // FIXME: Isn't this redundant with the initialization above? 160 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer)) 161 SC->InitializeSema(*this); 162 163 // Tell the external Sema source about this Sema object. 164 if (ExternalSemaSource *ExternalSema 165 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource())) 166 ExternalSema->InitializeSema(*this); 167} 168 169Sema::~Sema() { 170 if (PackContext) FreePackedContext(); 171 if (VisContext) FreeVisContext(); 172 delete TheTargetAttributesSema; 173 174 // Kill all the active scopes. 175 for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I) 176 delete FunctionScopes[I]; 177 if (FunctionScopes.size() == 1) 178 delete FunctionScopes[0]; 179 180 // Tell the SemaConsumer to forget about us; we're going out of scope. 181 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer)) 182 SC->ForgetSema(); 183 184 // Detach from the external Sema source. 185 if (ExternalSemaSource *ExternalSema 186 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource())) 187 ExternalSema->ForgetSema(); 188} 189 190/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast. 191/// If there is already an implicit cast, merge into the existing one. 192/// The result is of the given category. 193void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty, 194 CastKind Kind, ExprValueKind VK, 195 const CXXCastPath *BasePath) { 196 QualType ExprTy = Context.getCanonicalType(Expr->getType()); 197 QualType TypeTy = Context.getCanonicalType(Ty); 198 199 if (ExprTy == TypeTy) 200 return; 201 202 if (Expr->getType()->isPointerType() && Ty->isPointerType()) { 203 QualType ExprBaseType = cast<PointerType>(ExprTy)->getPointeeType(); 204 QualType BaseType = cast<PointerType>(TypeTy)->getPointeeType(); 205 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) { 206 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast) 207 << Expr->getSourceRange(); 208 } 209 } 210 211 // If this is a derived-to-base cast to a through a virtual base, we 212 // need a vtable. 213 if (Kind == CK_DerivedToBase && 214 BasePathInvolvesVirtualBase(*BasePath)) { 215 QualType T = Expr->getType(); 216 if (const PointerType *Pointer = T->getAs<PointerType>()) 217 T = Pointer->getPointeeType(); 218 if (const RecordType *RecordTy = T->getAs<RecordType>()) 219 MarkVTableUsed(Expr->getLocStart(), 220 cast<CXXRecordDecl>(RecordTy->getDecl())); 221 } 222 223 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) { 224 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) { 225 ImpCast->setType(Ty); 226 ImpCast->setValueKind(VK); 227 return; 228 } 229 } 230 231 Expr = ImplicitCastExpr::Create(Context, Ty, Kind, Expr, BasePath, VK); 232} 233 234ExprValueKind Sema::CastCategory(Expr *E) { 235 Expr::Classification Classification = E->Classify(Context); 236 return Classification.isRValue() ? VK_RValue : 237 (Classification.isLValue() ? VK_LValue : VK_XValue); 238} 239 240void Sema::DeleteExpr(ExprTy *E) { 241} 242void Sema::DeleteStmt(StmtTy *S) { 243} 244 245/// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector. 246static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) { 247 if (D->isUsed()) 248 return true; 249 250 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 251 // UnusedFileScopedDecls stores the first declaration. 252 // The declaration may have become definition so check again. 253 const FunctionDecl *DeclToCheck; 254 if (FD->hasBody(DeclToCheck)) 255 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 256 257 // Later redecls may add new information resulting in not having to warn, 258 // so check again. 259 DeclToCheck = FD->getMostRecentDeclaration(); 260 if (DeclToCheck != FD) 261 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 262 } 263 264 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 265 // UnusedFileScopedDecls stores the first declaration. 266 // The declaration may have become definition so check again. 267 const VarDecl *DeclToCheck = VD->getDefinition(); 268 if (DeclToCheck) 269 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 270 271 // Later redecls may add new information resulting in not having to warn, 272 // so check again. 273 DeclToCheck = VD->getMostRecentDeclaration(); 274 if (DeclToCheck != VD) 275 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 276 } 277 278 return false; 279} 280 281/// ActOnEndOfTranslationUnit - This is called at the very end of the 282/// translation unit when EOF is reached and all but the top-level scope is 283/// popped. 284void Sema::ActOnEndOfTranslationUnit() { 285 // At PCH writing, implicit instantiations and VTable handling info are 286 // stored and performed when the PCH is included. 287 if (CompleteTranslationUnit) 288 while (1) { 289 // C++: Perform implicit template instantiations. 290 // 291 // FIXME: When we perform these implicit instantiations, we do not 292 // carefully keep track of the point of instantiation (C++ [temp.point]). 293 // This means that name lookup that occurs within the template 294 // instantiation will always happen at the end of the translation unit, 295 // so it will find some names that should not be found. Although this is 296 // common behavior for C++ compilers, it is technically wrong. In the 297 // future, we either need to be able to filter the results of name lookup 298 // or we need to perform template instantiations earlier. 299 PerformPendingInstantiations(); 300 301 /// If DefinedUsedVTables ends up marking any virtual member 302 /// functions it might lead to more pending template 303 /// instantiations, which is why we need to loop here. 304 if (!DefineUsedVTables()) 305 break; 306 } 307 308 // Remove file scoped decls that turned out to be used. 309 UnusedFileScopedDecls.erase(std::remove_if(UnusedFileScopedDecls.begin(), 310 UnusedFileScopedDecls.end(), 311 std::bind1st(std::ptr_fun(ShouldRemoveFromUnused), 312 this)), 313 UnusedFileScopedDecls.end()); 314 315 if (!CompleteTranslationUnit) { 316 TUScope = 0; 317 return; 318 } 319 320 // Check for #pragma weak identifiers that were never declared 321 // FIXME: This will cause diagnostics to be emitted in a non-determinstic 322 // order! Iterating over a densemap like this is bad. 323 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator 324 I = WeakUndeclaredIdentifiers.begin(), 325 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) { 326 if (I->second.getUsed()) continue; 327 328 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared) 329 << I->first; 330 } 331 332 // C99 6.9.2p2: 333 // A declaration of an identifier for an object that has file 334 // scope without an initializer, and without a storage-class 335 // specifier or with the storage-class specifier static, 336 // constitutes a tentative definition. If a translation unit 337 // contains one or more tentative definitions for an identifier, 338 // and the translation unit contains no external definition for 339 // that identifier, then the behavior is exactly as if the 340 // translation unit contains a file scope declaration of that 341 // identifier, with the composite type as of the end of the 342 // translation unit, with an initializer equal to 0. 343 llvm::SmallSet<VarDecl *, 32> Seen; 344 for (unsigned i = 0, e = TentativeDefinitions.size(); i != e; ++i) { 345 VarDecl *VD = TentativeDefinitions[i]->getActingDefinition(); 346 347 // If the tentative definition was completed, getActingDefinition() returns 348 // null. If we've already seen this variable before, insert()'s second 349 // return value is false. 350 if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD)) 351 continue; 352 353 if (const IncompleteArrayType *ArrayT 354 = Context.getAsIncompleteArrayType(VD->getType())) { 355 if (RequireCompleteType(VD->getLocation(), 356 ArrayT->getElementType(), 357 diag::err_tentative_def_incomplete_type_arr)) { 358 VD->setInvalidDecl(); 359 continue; 360 } 361 362 // Set the length of the array to 1 (C99 6.9.2p5). 363 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array); 364 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true); 365 QualType T = Context.getConstantArrayType(ArrayT->getElementType(), 366 One, ArrayType::Normal, 0); 367 VD->setType(T); 368 } else if (RequireCompleteType(VD->getLocation(), VD->getType(), 369 diag::err_tentative_def_incomplete_type)) 370 VD->setInvalidDecl(); 371 372 // Notify the consumer that we've completed a tentative definition. 373 if (!VD->isInvalidDecl()) 374 Consumer.CompleteTentativeDefinition(VD); 375 376 } 377 378 // Output warning for unused file scoped decls. 379 for (llvm::SmallVectorImpl<const DeclaratorDecl*>::iterator 380 I = UnusedFileScopedDecls.begin(), 381 E = UnusedFileScopedDecls.end(); I != E; ++I) { 382 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 383 const FunctionDecl *DiagD; 384 if (!FD->hasBody(DiagD)) 385 DiagD = FD; 386 Diag(DiagD->getLocation(), 387 isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function 388 : diag::warn_unused_function) 389 << DiagD->getDeclName(); 390 } else { 391 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition(); 392 if (!DiagD) 393 DiagD = cast<VarDecl>(*I); 394 Diag(DiagD->getLocation(), diag::warn_unused_variable) 395 << DiagD->getDeclName(); 396 } 397 } 398 399 TUScope = 0; 400} 401 402 403//===----------------------------------------------------------------------===// 404// Helper functions. 405//===----------------------------------------------------------------------===// 406 407DeclContext *Sema::getFunctionLevelDeclContext() { 408 DeclContext *DC = CurContext; 409 410 while (isa<BlockDecl>(DC) || isa<EnumDecl>(DC)) 411 DC = DC->getParent(); 412 413 return DC; 414} 415 416/// getCurFunctionDecl - If inside of a function body, this returns a pointer 417/// to the function decl for the function being parsed. If we're currently 418/// in a 'block', this returns the containing context. 419FunctionDecl *Sema::getCurFunctionDecl() { 420 DeclContext *DC = getFunctionLevelDeclContext(); 421 return dyn_cast<FunctionDecl>(DC); 422} 423 424ObjCMethodDecl *Sema::getCurMethodDecl() { 425 DeclContext *DC = getFunctionLevelDeclContext(); 426 return dyn_cast<ObjCMethodDecl>(DC); 427} 428 429NamedDecl *Sema::getCurFunctionOrMethodDecl() { 430 DeclContext *DC = getFunctionLevelDeclContext(); 431 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC)) 432 return cast<NamedDecl>(DC); 433 return 0; 434} 435 436Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() { 437 if (!this->Emit()) 438 return; 439 440 // If this is not a note, and we're in a template instantiation 441 // that is different from the last template instantiation where 442 // we emitted an error, print a template instantiation 443 // backtrace. 444 if (!SemaRef.Diags.isBuiltinNote(DiagID) && 445 !SemaRef.ActiveTemplateInstantiations.empty() && 446 SemaRef.ActiveTemplateInstantiations.back() 447 != SemaRef.LastTemplateInstantiationErrorContext) { 448 SemaRef.PrintInstantiationStack(); 449 SemaRef.LastTemplateInstantiationErrorContext 450 = SemaRef.ActiveTemplateInstantiations.back(); 451 } 452} 453 454Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) { 455 if (isSFINAEContext()) { 456 switch (Diagnostic::getDiagnosticSFINAEResponse(DiagID)) { 457 case Diagnostic::SFINAE_Report: 458 // Fall through; we'll report the diagnostic below. 459 break; 460 461 case Diagnostic::SFINAE_SubstitutionFailure: 462 // Count this failure so that we know that template argument deduction 463 // has failed. 464 ++NumSFINAEErrors; 465 // Fall through 466 467 case Diagnostic::SFINAE_Suppress: 468 // Suppress this diagnostic. 469 Diags.setLastDiagnosticIgnored(); 470 return SemaDiagnosticBuilder(*this); 471 } 472 } 473 474 DiagnosticBuilder DB = Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID); 475 return SemaDiagnosticBuilder(DB, *this, DiagID); 476} 477 478Sema::SemaDiagnosticBuilder 479Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) { 480 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID())); 481 PD.Emit(Builder); 482 483 return Builder; 484} 485 486/// \brief Determines the active Scope associated with the given declaration 487/// context. 488/// 489/// This routine maps a declaration context to the active Scope object that 490/// represents that declaration context in the parser. It is typically used 491/// from "scope-less" code (e.g., template instantiation, lazy creation of 492/// declarations) that injects a name for name-lookup purposes and, therefore, 493/// must update the Scope. 494/// 495/// \returns The scope corresponding to the given declaraion context, or NULL 496/// if no such scope is open. 497Scope *Sema::getScopeForContext(DeclContext *Ctx) { 498 499 if (!Ctx) 500 return 0; 501 502 Ctx = Ctx->getPrimaryContext(); 503 for (Scope *S = getCurScope(); S; S = S->getParent()) { 504 // Ignore scopes that cannot have declarations. This is important for 505 // out-of-line definitions of static class members. 506 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) 507 if (DeclContext *Entity = static_cast<DeclContext *> (S->getEntity())) 508 if (Ctx == Entity->getPrimaryContext()) 509 return S; 510 } 511 512 return 0; 513} 514 515/// \brief Enter a new function scope 516void Sema::PushFunctionScope() { 517 if (FunctionScopes.size() == 1) { 518 // Use the "top" function scope rather than having to allocate 519 // memory for a new scope. 520 FunctionScopes.back()->Clear(getDiagnostics().getNumErrors()); 521 FunctionScopes.push_back(FunctionScopes.back()); 522 return; 523 } 524 525 FunctionScopes.push_back( 526 new FunctionScopeInfo(getDiagnostics().getNumErrors())); 527} 528 529void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) { 530 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics().getNumErrors(), 531 BlockScope, Block)); 532} 533 534void Sema::PopFunctionOrBlockScope() { 535 FunctionScopeInfo *Scope = FunctionScopes.pop_back_val(); 536 assert(!FunctionScopes.empty() && "mismatched push/pop!"); 537 if (FunctionScopes.back() != Scope) 538 delete Scope; 539} 540 541/// \brief Determine whether any errors occurred within this function/method/ 542/// block. 543bool Sema::hasAnyErrorsInThisFunction() const { 544 return getCurFunction()->NumErrorsAtStartOfFunction 545 != getDiagnostics().getNumErrors(); 546} 547 548BlockScopeInfo *Sema::getCurBlock() { 549 if (FunctionScopes.empty()) 550 return 0; 551 552 return dyn_cast<BlockScopeInfo>(FunctionScopes.back()); 553} 554 555// Pin this vtable to this file. 556ExternalSemaSource::~ExternalSemaSource() {} 557