Sema.cpp revision 839bff1203adf923e1a75ed2695b8fd824810920
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, bool isLvalue) { 162 QualType ExprTy = Context.getCanonicalType(Expr->getType()); 163 QualType TypeTy = Context.getCanonicalType(Ty); 164 165 if (ExprTy == TypeTy) 166 return; 167 168 if (Expr->getType()->isPointerType() && Ty->isPointerType()) { 169 QualType ExprBaseType = cast<PointerType>(ExprTy)->getPointeeType(); 170 QualType BaseType = cast<PointerType>(TypeTy)->getPointeeType(); 171 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) { 172 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast) 173 << Expr->getSourceRange(); 174 } 175 } 176 177 CheckImplicitConversion(Expr, Ty); 178 179 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) { 180 if (ImpCast->getCastKind() == Kind) { 181 ImpCast->setType(Ty); 182 ImpCast->setLvalueCast(isLvalue); 183 return; 184 } 185 } 186 187 Expr = new (Context) ImplicitCastExpr(Ty, Kind, Expr, isLvalue); 188} 189 190void Sema::DeleteExpr(ExprTy *E) { 191 if (E) static_cast<Expr*>(E)->Destroy(Context); 192} 193void Sema::DeleteStmt(StmtTy *S) { 194 if (S) static_cast<Stmt*>(S)->Destroy(Context); 195} 196 197/// ActOnEndOfTranslationUnit - This is called at the very end of the 198/// translation unit when EOF is reached and all but the top-level scope is 199/// popped. 200void Sema::ActOnEndOfTranslationUnit() { 201 202 // Remove functions that turned out to be used. 203 UnusedStaticFuncs.erase(std::remove_if(UnusedStaticFuncs.begin(), 204 UnusedStaticFuncs.end(), 205 std::mem_fun(&FunctionDecl::isUsed)), 206 UnusedStaticFuncs.end()); 207 208 while (1) { 209 // C++: Perform implicit template instantiations. 210 // 211 // FIXME: When we perform these implicit instantiations, we do not carefully 212 // keep track of the point of instantiation (C++ [temp.point]). This means 213 // that name lookup that occurs within the template instantiation will 214 // always happen at the end of the translation unit, so it will find 215 // some names that should not be found. Although this is common behavior 216 // for C++ compilers, it is technically wrong. In the future, we either need 217 // to be able to filter the results of name lookup or we need to perform 218 // template instantiations earlier. 219 PerformPendingImplicitInstantiations(); 220 221 /// If ProcessPendingClassesWithUnmarkedVirtualMembers ends up marking 222 /// any virtual member functions it might lead to more pending template 223 /// instantiations, which is why we need to loop here. 224 if (!ProcessPendingClassesWithUnmarkedVirtualMembers()) 225 break; 226 } 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 352Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) { 353 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID())); 354 PD.Emit(Builder); 355 356 return Builder; 357} 358 359 360/// \brief Enter a new function scope 361void Sema::PushFunctionScope() { 362 if (FunctionScopes.empty()) { 363 // Use the "top" function scope rather than having to allocate memory for 364 // a new scope. 365 TopFunctionScope.Clear(getDiagnostics().getNumErrors()); 366 FunctionScopes.push_back(&TopFunctionScope); 367 return; 368 } 369 370 FunctionScopes.push_back( 371 new FunctionScopeInfo(getDiagnostics().getNumErrors())); 372} 373 374void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) { 375 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics().getNumErrors(), 376 BlockScope, Block)); 377} 378 379void Sema::PopFunctionOrBlockScope() { 380 if (FunctionScopes.back() != &TopFunctionScope) 381 delete FunctionScopes.back(); 382 else 383 TopFunctionScope.Clear(getDiagnostics().getNumErrors()); 384 385 FunctionScopes.pop_back(); 386} 387 388/// \brief Determine whether any errors occurred within this function/method/ 389/// block. 390bool Sema::hasAnyErrorsInThisFunction() const { 391 unsigned NumErrors = TopFunctionScope.NumErrorsAtStartOfFunction; 392 if (!FunctionScopes.empty()) 393 NumErrors = FunctionScopes.back()->NumErrorsAtStartOfFunction; 394 return NumErrors != getDiagnostics().getNumErrors(); 395} 396 397BlockScopeInfo *Sema::getCurBlock() { 398 if (FunctionScopes.empty()) 399 return 0; 400 401 return dyn_cast<BlockScopeInfo>(FunctionScopes.back()); 402} 403