Sema.cpp revision 207619
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 "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/AST/ASTConsumer.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/ASTDiagnostic.h" 23#include "clang/AST/DeclObjC.h" 24#include "clang/AST/Expr.h" 25#include "clang/Lex/Preprocessor.h" 26#include "clang/Basic/PartialDiagnostic.h" 27#include "clang/Basic/TargetInfo.h" 28using namespace clang; 29 30FunctionScopeInfo::~FunctionScopeInfo() { } 31 32void FunctionScopeInfo::Clear(unsigned NumErrors) { 33 NeedsScopeChecking = false; 34 LabelMap.clear(); 35 SwitchStack.clear(); 36 NumErrorsAtStartOfFunction = NumErrors; 37} 38 39BlockScopeInfo::~BlockScopeInfo() { } 40 41static inline RecordDecl *CreateStructDecl(ASTContext &C, const char *Name) { 42 if (C.getLangOptions().CPlusPlus) 43 return CXXRecordDecl::Create(C, TagDecl::TK_struct, 44 C.getTranslationUnitDecl(), 45 SourceLocation(), &C.Idents.get(Name)); 46 47 return RecordDecl::Create(C, TagDecl::TK_struct, 48 C.getTranslationUnitDecl(), 49 SourceLocation(), &C.Idents.get(Name)); 50} 51 52void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) { 53 TUScope = S; 54 PushDeclContext(S, Context.getTranslationUnitDecl()); 55 56 if (PP.getTargetInfo().getPointerWidth(0) >= 64) { 57 TypeSourceInfo *TInfo; 58 59 // Install [u]int128_t for 64-bit targets. 60 TInfo = Context.getTrivialTypeSourceInfo(Context.Int128Ty); 61 PushOnScopeChains(TypedefDecl::Create(Context, CurContext, 62 SourceLocation(), 63 &Context.Idents.get("__int128_t"), 64 TInfo), TUScope); 65 66 TInfo = Context.getTrivialTypeSourceInfo(Context.UnsignedInt128Ty); 67 PushOnScopeChains(TypedefDecl::Create(Context, CurContext, 68 SourceLocation(), 69 &Context.Idents.get("__uint128_t"), 70 TInfo), TUScope); 71 } 72 73 74 if (!PP.getLangOptions().ObjC1) return; 75 76 // Built-in ObjC types may already be set by PCHReader (hence isNull checks). 77 if (Context.getObjCSelType().isNull()) { 78 // Create the built-in typedef for 'SEL'. 79 QualType SelT = Context.getPointerType(Context.ObjCBuiltinSelTy); 80 TypeSourceInfo *SelInfo = Context.getTrivialTypeSourceInfo(SelT); 81 TypedefDecl *SelTypedef 82 = TypedefDecl::Create(Context, CurContext, SourceLocation(), 83 &Context.Idents.get("SEL"), SelInfo); 84 PushOnScopeChains(SelTypedef, TUScope); 85 Context.setObjCSelType(Context.getTypeDeclType(SelTypedef)); 86 Context.ObjCSelRedefinitionType = Context.getObjCSelType(); 87 } 88 89 // Synthesize "@class Protocol; 90 if (Context.getObjCProtoType().isNull()) { 91 ObjCInterfaceDecl *ProtocolDecl = 92 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(), 93 &Context.Idents.get("Protocol"), 94 SourceLocation(), true); 95 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl)); 96 PushOnScopeChains(ProtocolDecl, TUScope, false); 97 } 98 // Create the built-in typedef for 'id'. 99 if (Context.getObjCIdType().isNull()) { 100 QualType IdT = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy); 101 TypeSourceInfo *IdInfo = Context.getTrivialTypeSourceInfo(IdT); 102 TypedefDecl *IdTypedef 103 = TypedefDecl::Create(Context, CurContext, SourceLocation(), 104 &Context.Idents.get("id"), IdInfo); 105 PushOnScopeChains(IdTypedef, TUScope); 106 Context.setObjCIdType(Context.getTypeDeclType(IdTypedef)); 107 Context.ObjCIdRedefinitionType = Context.getObjCIdType(); 108 } 109 // Create the built-in typedef for 'Class'. 110 if (Context.getObjCClassType().isNull()) { 111 QualType ClassType 112 = Context.getObjCObjectPointerType(Context.ObjCBuiltinClassTy); 113 TypeSourceInfo *ClassInfo = Context.getTrivialTypeSourceInfo(ClassType); 114 TypedefDecl *ClassTypedef 115 = TypedefDecl::Create(Context, CurContext, SourceLocation(), 116 &Context.Idents.get("Class"), ClassInfo); 117 PushOnScopeChains(ClassTypedef, TUScope); 118 Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef)); 119 Context.ObjCClassRedefinitionType = Context.getObjCClassType(); 120 } 121} 122 123Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 124 bool CompleteTranslationUnit, 125 CodeCompleteConsumer *CodeCompleter) 126 : TheTargetAttributesSema(0), 127 LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer), 128 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()), 129 ExternalSource(0), CodeCompleter(CodeCompleter), CurContext(0), 130 PackContext(0), TopFunctionScope(0), ParsingDeclDepth(0), 131 IdResolver(pp.getLangOptions()), StdNamespace(0), StdBadAlloc(0), 132 GlobalNewDeleteDeclared(false), 133 CompleteTranslationUnit(CompleteTranslationUnit), 134 NumSFINAEErrors(0), NonInstantiationEntries(0), 135 CurrentInstantiationScope(0), TyposCorrected(0), 136 AnalysisWarnings(*this) 137{ 138 TUScope = 0; 139 if (getLangOptions().CPlusPlus) 140 FieldCollector.reset(new CXXFieldCollector()); 141 142 // Tell diagnostics how to render things from the AST library. 143 PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument, 144 &Context); 145 146 ExprEvalContexts.push_back( 147 ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0)); 148} 149 150Sema::~Sema() { 151 if (PackContext) FreePackedContext(); 152 delete TheTargetAttributesSema; 153 while (!FunctionScopes.empty()) 154 PopFunctionOrBlockScope(); 155} 156 157/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast. 158/// If there is already an implicit cast, merge into the existing one. 159/// If isLvalue, the result of the cast is an lvalue. 160void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty, 161 CastExpr::CastKind Kind, 162 bool isLvalue, CXXBaseSpecifierArray BasePath) { 163 QualType ExprTy = Context.getCanonicalType(Expr->getType()); 164 QualType TypeTy = Context.getCanonicalType(Ty); 165 166 if (ExprTy == TypeTy) 167 return; 168 169 if (Expr->getType()->isPointerType() && Ty->isPointerType()) { 170 QualType ExprBaseType = cast<PointerType>(ExprTy)->getPointeeType(); 171 QualType BaseType = cast<PointerType>(TypeTy)->getPointeeType(); 172 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) { 173 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast) 174 << Expr->getSourceRange(); 175 } 176 } 177 178 CheckImplicitConversion(Expr, Ty); 179 180 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) { 181 if (ImpCast->getCastKind() == Kind && BasePath.empty()) { 182 ImpCast->setType(Ty); 183 ImpCast->setLvalueCast(isLvalue); 184 return; 185 } 186 } 187 188 Expr = new (Context) ImplicitCastExpr(Ty, Kind, Expr, BasePath, isLvalue); 189} 190 191void Sema::DeleteExpr(ExprTy *E) { 192 if (E) static_cast<Expr*>(E)->Destroy(Context); 193} 194void Sema::DeleteStmt(StmtTy *S) { 195 if (S) static_cast<Stmt*>(S)->Destroy(Context); 196} 197 198/// ActOnEndOfTranslationUnit - This is called at the very end of the 199/// translation unit when EOF is reached and all but the top-level scope is 200/// popped. 201void Sema::ActOnEndOfTranslationUnit() { 202 while (1) { 203 // C++: Perform implicit template instantiations. 204 // 205 // FIXME: When we perform these implicit instantiations, we do not carefully 206 // keep track of the point of instantiation (C++ [temp.point]). This means 207 // that name lookup that occurs within the template instantiation will 208 // always happen at the end of the translation unit, so it will find 209 // some names that should not be found. Although this is common behavior 210 // for C++ compilers, it is technically wrong. In the future, we either need 211 // to be able to filter the results of name lookup or we need to perform 212 // template instantiations earlier. 213 PerformPendingImplicitInstantiations(); 214 215 /// If ProcessPendingClassesWithUnmarkedVirtualMembers ends up marking 216 /// any virtual member functions it might lead to more pending template 217 /// instantiations, which is why we need to loop here. 218 if (!ProcessPendingClassesWithUnmarkedVirtualMembers()) 219 break; 220 } 221 222 // Remove functions that turned out to be used. 223 UnusedStaticFuncs.erase(std::remove_if(UnusedStaticFuncs.begin(), 224 UnusedStaticFuncs.end(), 225 std::mem_fun(&FunctionDecl::isUsed)), 226 UnusedStaticFuncs.end()); 227 228 // Check for #pragma weak identifiers that were never declared 229 // FIXME: This will cause diagnostics to be emitted in a non-determinstic 230 // order! Iterating over a densemap like this is bad. 231 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator 232 I = WeakUndeclaredIdentifiers.begin(), 233 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) { 234 if (I->second.getUsed()) continue; 235 236 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared) 237 << I->first; 238 } 239 240 if (!CompleteTranslationUnit) 241 return; 242 243 // C99 6.9.2p2: 244 // A declaration of an identifier for an object that has file 245 // scope without an initializer, and without a storage-class 246 // specifier or with the storage-class specifier static, 247 // constitutes a tentative definition. If a translation unit 248 // contains one or more tentative definitions for an identifier, 249 // and the translation unit contains no external definition for 250 // that identifier, then the behavior is exactly as if the 251 // translation unit contains a file scope declaration of that 252 // identifier, with the composite type as of the end of the 253 // translation unit, with an initializer equal to 0. 254 llvm::SmallSet<VarDecl *, 32> Seen; 255 for (unsigned i = 0, e = TentativeDefinitions.size(); i != e; ++i) { 256 VarDecl *VD = TentativeDefinitions[i]->getActingDefinition(); 257 258 // If the tentative definition was completed, getActingDefinition() returns 259 // null. If we've already seen this variable before, insert()'s second 260 // return value is false. 261 if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD)) 262 continue; 263 264 if (const IncompleteArrayType *ArrayT 265 = Context.getAsIncompleteArrayType(VD->getType())) { 266 if (RequireCompleteType(VD->getLocation(), 267 ArrayT->getElementType(), 268 diag::err_tentative_def_incomplete_type_arr)) { 269 VD->setInvalidDecl(); 270 continue; 271 } 272 273 // Set the length of the array to 1 (C99 6.9.2p5). 274 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array); 275 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true); 276 QualType T = Context.getConstantArrayType(ArrayT->getElementType(), 277 One, ArrayType::Normal, 0); 278 VD->setType(T); 279 } else if (RequireCompleteType(VD->getLocation(), VD->getType(), 280 diag::err_tentative_def_incomplete_type)) 281 VD->setInvalidDecl(); 282 283 // Notify the consumer that we've completed a tentative definition. 284 if (!VD->isInvalidDecl()) 285 Consumer.CompleteTentativeDefinition(VD); 286 287 } 288 289 // Output warning for unused functions. 290 for (std::vector<FunctionDecl*>::iterator 291 F = UnusedStaticFuncs.begin(), 292 FEnd = UnusedStaticFuncs.end(); 293 F != FEnd; 294 ++F) 295 Diag((*F)->getLocation(), diag::warn_unused_function) << (*F)->getDeclName(); 296 297} 298 299 300//===----------------------------------------------------------------------===// 301// Helper functions. 302//===----------------------------------------------------------------------===// 303 304DeclContext *Sema::getFunctionLevelDeclContext() { 305 DeclContext *DC = CurContext; 306 307 while (isa<BlockDecl>(DC)) 308 DC = DC->getParent(); 309 310 return DC; 311} 312 313/// getCurFunctionDecl - If inside of a function body, this returns a pointer 314/// to the function decl for the function being parsed. If we're currently 315/// in a 'block', this returns the containing context. 316FunctionDecl *Sema::getCurFunctionDecl() { 317 DeclContext *DC = getFunctionLevelDeclContext(); 318 return dyn_cast<FunctionDecl>(DC); 319} 320 321ObjCMethodDecl *Sema::getCurMethodDecl() { 322 DeclContext *DC = getFunctionLevelDeclContext(); 323 return dyn_cast<ObjCMethodDecl>(DC); 324} 325 326NamedDecl *Sema::getCurFunctionOrMethodDecl() { 327 DeclContext *DC = getFunctionLevelDeclContext(); 328 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC)) 329 return cast<NamedDecl>(DC); 330 return 0; 331} 332 333Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() { 334 if (!this->Emit()) 335 return; 336 337 // If this is not a note, and we're in a template instantiation 338 // that is different from the last template instantiation where 339 // we emitted an error, print a template instantiation 340 // backtrace. 341 if (!SemaRef.Diags.isBuiltinNote(DiagID) && 342 !SemaRef.ActiveTemplateInstantiations.empty() && 343 SemaRef.ActiveTemplateInstantiations.back() 344 != SemaRef.LastTemplateInstantiationErrorContext) { 345 SemaRef.PrintInstantiationStack(); 346 SemaRef.LastTemplateInstantiationErrorContext 347 = SemaRef.ActiveTemplateInstantiations.back(); 348 } 349} 350 351Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) { 352 if (isSFINAEContext()) { 353 switch (Diagnostic::getDiagnosticSFINAEResponse(DiagID)) { 354 case Diagnostic::SFINAE_Report: 355 // Fall through; we'll report the diagnostic below. 356 break; 357 358 case Diagnostic::SFINAE_SubstitutionFailure: 359 // Count this failure so that we know that template argument deduction 360 // has failed. 361 ++NumSFINAEErrors; 362 // Fall through 363 364 case Diagnostic::SFINAE_Suppress: 365 // Suppress this diagnostic. 366 Diags.setLastDiagnosticIgnored(); 367 return SemaDiagnosticBuilder(*this); 368 } 369 } 370 371 DiagnosticBuilder DB = Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID); 372 return SemaDiagnosticBuilder(DB, *this, DiagID); 373} 374 375Sema::SemaDiagnosticBuilder 376Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) { 377 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID())); 378 PD.Emit(Builder); 379 380 return Builder; 381} 382 383 384/// \brief Enter a new function scope 385void Sema::PushFunctionScope() { 386 if (FunctionScopes.empty()) { 387 // Use the "top" function scope rather than having to allocate memory for 388 // a new scope. 389 TopFunctionScope.Clear(getDiagnostics().getNumErrors()); 390 FunctionScopes.push_back(&TopFunctionScope); 391 return; 392 } 393 394 FunctionScopes.push_back( 395 new FunctionScopeInfo(getDiagnostics().getNumErrors())); 396} 397 398void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) { 399 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics().getNumErrors(), 400 BlockScope, Block)); 401} 402 403void Sema::PopFunctionOrBlockScope() { 404 if (FunctionScopes.back() != &TopFunctionScope) 405 delete FunctionScopes.back(); 406 else 407 TopFunctionScope.Clear(getDiagnostics().getNumErrors()); 408 409 FunctionScopes.pop_back(); 410} 411 412/// \brief Determine whether any errors occurred within this function/method/ 413/// block. 414bool Sema::hasAnyErrorsInThisFunction() const { 415 unsigned NumErrors = TopFunctionScope.NumErrorsAtStartOfFunction; 416 if (!FunctionScopes.empty()) 417 NumErrors = FunctionScopes.back()->NumErrorsAtStartOfFunction; 418 return NumErrors != getDiagnostics().getNumErrors(); 419} 420 421BlockScopeInfo *Sema::getCurBlock() { 422 if (FunctionScopes.empty()) 423 return 0; 424 425 return dyn_cast<BlockScopeInfo>(FunctionScopes.back()); 426} 427