Sema.cpp revision 79f414435ef406f9fb3dc7733b93715ac6313425
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 "llvm/ADT/DenseMap.h" 17#include "llvm/ADT/APFloat.h" 18#include "clang/AST/ASTConsumer.h" 19#include "clang/AST/ASTContext.h" 20#include "clang/AST/DeclObjC.h" 21#include "clang/AST/Expr.h" 22#include "clang/Lex/Preprocessor.h" 23#include "clang/Basic/PartialDiagnostic.h" 24#include "clang/Basic/TargetInfo.h" 25using namespace clang; 26 27/// Determines whether we should have an a.k.a. clause when 28/// pretty-printing a type. There are three main criteria: 29/// 30/// 1) Some types provide very minimal sugar that doesn't impede the 31/// user's understanding --- for example, elaborated type 32/// specifiers. If this is all the sugar we see, we don't want an 33/// a.k.a. clause. 34/// 2) Some types are technically sugared but are much more familiar 35/// when seen in their sugared form --- for example, va_list, 36/// vector types, and the magic Objective C types. We don't 37/// want to desugar these, even if we do produce an a.k.a. clause. 38/// 3) Some types may have already been desugared previously in this diagnostic. 39/// if this is the case, doing another "aka" would just be clutter. 40/// 41static bool ShouldAKA(ASTContext &Context, QualType QT, 42 const Diagnostic::ArgumentValue *PrevArgs, 43 unsigned NumPrevArgs, 44 QualType &DesugaredQT) { 45 QualType InputTy = QT; 46 47 bool AKA = false; 48 QualifierCollector Qc; 49 50 while (true) { 51 const Type *Ty = Qc.strip(QT); 52 53 // Don't aka just because we saw an elaborated type... 54 if (isa<ElaboratedType>(Ty)) { 55 QT = cast<ElaboratedType>(Ty)->desugar(); 56 continue; 57 } 58 59 // ...or a qualified name type... 60 if (isa<QualifiedNameType>(Ty)) { 61 QT = cast<QualifiedNameType>(Ty)->desugar(); 62 continue; 63 } 64 65 // ...or a substituted template type parameter. 66 if (isa<SubstTemplateTypeParmType>(Ty)) { 67 QT = cast<SubstTemplateTypeParmType>(Ty)->desugar(); 68 continue; 69 } 70 71 // Don't desugar template specializations. 72 if (isa<TemplateSpecializationType>(Ty)) 73 break; 74 75 // Don't desugar magic Objective-C types. 76 if (QualType(Ty,0) == Context.getObjCIdType() || 77 QualType(Ty,0) == Context.getObjCClassType() || 78 QualType(Ty,0) == Context.getObjCSelType() || 79 QualType(Ty,0) == Context.getObjCProtoType()) 80 break; 81 82 // Don't desugar va_list. 83 if (QualType(Ty,0) == Context.getBuiltinVaListType()) 84 break; 85 86 // Otherwise, do a single-step desugar. 87 QualType Underlying; 88 bool IsSugar = false; 89 switch (Ty->getTypeClass()) { 90#define ABSTRACT_TYPE(Class, Base) 91#define TYPE(Class, Base) \ 92 case Type::Class: { \ 93 const Class##Type *CTy = cast<Class##Type>(Ty); \ 94 if (CTy->isSugared()) { \ 95 IsSugar = true; \ 96 Underlying = CTy->desugar(); \ 97 } \ 98 break; \ 99 } 100#include "clang/AST/TypeNodes.def" 101 } 102 103 // If it wasn't sugared, we're done. 104 if (!IsSugar) 105 break; 106 107 // If the desugared type is a vector type, we don't want to expand 108 // it, it will turn into an attribute mess. People want their "vec4". 109 if (isa<VectorType>(Underlying)) 110 break; 111 112 // Otherwise, we're tearing through something opaque; note that 113 // we'll eventually need an a.k.a. clause and keep going. 114 AKA = true; 115 QT = Underlying; 116 continue; 117 } 118 119 // If we never tore through opaque sugar, don't print aka. 120 if (!AKA) return false; 121 122 // If we did, check to see if we already desugared this type in this 123 // diagnostic. If so, don't do it again. 124 for (unsigned i = 0; i != NumPrevArgs; ++i) { 125 // TODO: Handle ak_declcontext case. 126 if (PrevArgs[i].first == Diagnostic::ak_qualtype) { 127 void *Ptr = (void*)PrevArgs[i].second; 128 QualType PrevTy(QualType::getFromOpaquePtr(Ptr)); 129 if (PrevTy == InputTy) 130 return false; 131 } 132 } 133 134 DesugaredQT = Qc.apply(QT); 135 return true; 136} 137 138/// \brief Convert the given type to a string suitable for printing as part of 139/// a diagnostic. 140/// 141/// \param Context the context in which the type was allocated 142/// \param Ty the type to print 143static std::string 144ConvertTypeToDiagnosticString(ASTContext &Context, QualType Ty, 145 const Diagnostic::ArgumentValue *PrevArgs, 146 unsigned NumPrevArgs) { 147 // FIXME: Playing with std::string is really slow. 148 std::string S = Ty.getAsString(Context.PrintingPolicy); 149 150 // Consider producing an a.k.a. clause if removing all the direct 151 // sugar gives us something "significantly different". 152 153 QualType DesugaredTy; 154 if (ShouldAKA(Context, Ty, PrevArgs, NumPrevArgs, DesugaredTy)) { 155 S = "'"+S+"' (aka '"; 156 S += DesugaredTy.getAsString(Context.PrintingPolicy); 157 S += "')"; 158 return S; 159 } 160 161 S = "'" + S + "'"; 162 return S; 163} 164 165/// ConvertQualTypeToStringFn - This function is used to pretty print the 166/// specified QualType as a string in diagnostics. 167static void ConvertArgToStringFn(Diagnostic::ArgumentKind Kind, intptr_t Val, 168 const char *Modifier, unsigned ModLen, 169 const char *Argument, unsigned ArgLen, 170 const Diagnostic::ArgumentValue *PrevArgs, 171 unsigned NumPrevArgs, 172 llvm::SmallVectorImpl<char> &Output, 173 void *Cookie) { 174 ASTContext &Context = *static_cast<ASTContext*>(Cookie); 175 176 std::string S; 177 bool NeedQuotes = true; 178 179 switch (Kind) { 180 default: assert(0 && "unknown ArgumentKind"); 181 case Diagnostic::ak_qualtype: { 182 assert(ModLen == 0 && ArgLen == 0 && 183 "Invalid modifier for QualType argument"); 184 185 QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val))); 186 S = ConvertTypeToDiagnosticString(Context, Ty, PrevArgs, NumPrevArgs); 187 NeedQuotes = false; 188 break; 189 } 190 case Diagnostic::ak_declarationname: { 191 DeclarationName N = DeclarationName::getFromOpaqueInteger(Val); 192 S = N.getAsString(); 193 194 if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0) 195 S = '+' + S; 196 else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12) && ArgLen==0) 197 S = '-' + S; 198 else 199 assert(ModLen == 0 && ArgLen == 0 && 200 "Invalid modifier for DeclarationName argument"); 201 break; 202 } 203 case Diagnostic::ak_nameddecl: { 204 bool Qualified; 205 if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0) 206 Qualified = true; 207 else { 208 assert(ModLen == 0 && ArgLen == 0 && 209 "Invalid modifier for NamedDecl* argument"); 210 Qualified = false; 211 } 212 reinterpret_cast<NamedDecl*>(Val)-> 213 getNameForDiagnostic(S, Context.PrintingPolicy, Qualified); 214 break; 215 } 216 case Diagnostic::ak_nestednamespec: { 217 llvm::raw_string_ostream OS(S); 218 reinterpret_cast<NestedNameSpecifier*>(Val)->print(OS, 219 Context.PrintingPolicy); 220 NeedQuotes = false; 221 break; 222 } 223 case Diagnostic::ak_declcontext: { 224 DeclContext *DC = reinterpret_cast<DeclContext *> (Val); 225 assert(DC && "Should never have a null declaration context"); 226 227 if (DC->isTranslationUnit()) { 228 // FIXME: Get these strings from some localized place 229 if (Context.getLangOptions().CPlusPlus) 230 S = "the global namespace"; 231 else 232 S = "the global scope"; 233 } else if (TypeDecl *Type = dyn_cast<TypeDecl>(DC)) { 234 S = ConvertTypeToDiagnosticString(Context, Context.getTypeDeclType(Type), 235 PrevArgs, NumPrevArgs); 236 } else { 237 // FIXME: Get these strings from some localized place 238 NamedDecl *ND = cast<NamedDecl>(DC); 239 if (isa<NamespaceDecl>(ND)) 240 S += "namespace "; 241 else if (isa<ObjCMethodDecl>(ND)) 242 S += "method "; 243 else if (isa<FunctionDecl>(ND)) 244 S += "function "; 245 246 S += "'"; 247 ND->getNameForDiagnostic(S, Context.PrintingPolicy, true); 248 S += "'"; 249 } 250 NeedQuotes = false; 251 break; 252 } 253 } 254 255 if (NeedQuotes) 256 Output.push_back('\''); 257 258 Output.append(S.begin(), S.end()); 259 260 if (NeedQuotes) 261 Output.push_back('\''); 262} 263 264 265static inline RecordDecl *CreateStructDecl(ASTContext &C, const char *Name) { 266 if (C.getLangOptions().CPlusPlus) 267 return CXXRecordDecl::Create(C, TagDecl::TK_struct, 268 C.getTranslationUnitDecl(), 269 SourceLocation(), &C.Idents.get(Name)); 270 271 return RecordDecl::Create(C, TagDecl::TK_struct, 272 C.getTranslationUnitDecl(), 273 SourceLocation(), &C.Idents.get(Name)); 274} 275 276void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) { 277 TUScope = S; 278 PushDeclContext(S, Context.getTranslationUnitDecl()); 279 280 if (PP.getTargetInfo().getPointerWidth(0) >= 64) { 281 TypeSourceInfo *TInfo; 282 283 // Install [u]int128_t for 64-bit targets. 284 TInfo = Context.getTrivialTypeSourceInfo(Context.Int128Ty); 285 PushOnScopeChains(TypedefDecl::Create(Context, CurContext, 286 SourceLocation(), 287 &Context.Idents.get("__int128_t"), 288 TInfo), TUScope); 289 290 TInfo = Context.getTrivialTypeSourceInfo(Context.UnsignedInt128Ty); 291 PushOnScopeChains(TypedefDecl::Create(Context, CurContext, 292 SourceLocation(), 293 &Context.Idents.get("__uint128_t"), 294 TInfo), TUScope); 295 } 296 297 298 if (!PP.getLangOptions().ObjC1) return; 299 300 // Built-in ObjC types may already be set by PCHReader (hence isNull checks). 301 if (Context.getObjCSelType().isNull()) { 302 // Create the built-in typedef for 'SEL'. 303 QualType SelT = Context.getPointerType(Context.ObjCBuiltinSelTy); 304 TypeSourceInfo *SelInfo = Context.getTrivialTypeSourceInfo(SelT); 305 TypedefDecl *SelTypedef 306 = TypedefDecl::Create(Context, CurContext, SourceLocation(), 307 &Context.Idents.get("SEL"), SelInfo); 308 PushOnScopeChains(SelTypedef, TUScope); 309 Context.setObjCSelType(Context.getTypeDeclType(SelTypedef)); 310 Context.ObjCSelRedefinitionType = Context.getObjCSelType(); 311 } 312 313 // Synthesize "@class Protocol; 314 if (Context.getObjCProtoType().isNull()) { 315 ObjCInterfaceDecl *ProtocolDecl = 316 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(), 317 &Context.Idents.get("Protocol"), 318 SourceLocation(), true); 319 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl)); 320 PushOnScopeChains(ProtocolDecl, TUScope, false); 321 } 322 // Create the built-in typedef for 'id'. 323 if (Context.getObjCIdType().isNull()) { 324 QualType IdT = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy); 325 TypeSourceInfo *IdInfo = Context.getTrivialTypeSourceInfo(IdT); 326 TypedefDecl *IdTypedef 327 = TypedefDecl::Create(Context, CurContext, SourceLocation(), 328 &Context.Idents.get("id"), IdInfo); 329 PushOnScopeChains(IdTypedef, TUScope); 330 Context.setObjCIdType(Context.getTypeDeclType(IdTypedef)); 331 Context.ObjCIdRedefinitionType = Context.getObjCIdType(); 332 } 333 // Create the built-in typedef for 'Class'. 334 if (Context.getObjCClassType().isNull()) { 335 QualType ClassType 336 = Context.getObjCObjectPointerType(Context.ObjCBuiltinClassTy); 337 TypeSourceInfo *ClassInfo = Context.getTrivialTypeSourceInfo(ClassType); 338 TypedefDecl *ClassTypedef 339 = TypedefDecl::Create(Context, CurContext, SourceLocation(), 340 &Context.Idents.get("Class"), ClassInfo); 341 PushOnScopeChains(ClassTypedef, TUScope); 342 Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef)); 343 Context.ObjCClassRedefinitionType = Context.getObjCClassType(); 344 } 345} 346 347Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 348 bool CompleteTranslationUnit, 349 CodeCompleteConsumer *CodeCompleter) 350 : LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer), 351 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()), 352 ExternalSource(0), CodeCompleter(CodeCompleter), CurContext(0), 353 CurBlock(0), PackContext(0), ParsingDeclDepth(0), 354 IdResolver(pp.getLangOptions()), StdNamespace(0), StdBadAlloc(0), 355 GlobalNewDeleteDeclared(false), 356 CompleteTranslationUnit(CompleteTranslationUnit), 357 NumSFINAEErrors(0), NonInstantiationEntries(0), 358 CurrentInstantiationScope(0) 359{ 360 TUScope = 0; 361 if (getLangOptions().CPlusPlus) 362 FieldCollector.reset(new CXXFieldCollector()); 363 364 // Tell diagnostics how to render things from the AST library. 365 PP.getDiagnostics().SetArgToStringFn(ConvertArgToStringFn, &Context); 366 367 ExprEvalContexts.push_back( 368 ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0)); 369} 370 371/// Retrieves the width and signedness of the given integer type, 372/// or returns false if it is not an integer type. 373/// 374/// \param T must be canonical 375static bool getIntProperties(ASTContext &C, const Type *T, 376 unsigned &BitWidth, bool &Signed) { 377 assert(T->isCanonicalUnqualified()); 378 379 if (const VectorType *VT = dyn_cast<VectorType>(T)) 380 T = VT->getElementType().getTypePtr(); 381 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 382 T = CT->getElementType().getTypePtr(); 383 384 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) { 385 if (!BT->isInteger()) return false; 386 387 BitWidth = C.getIntWidth(QualType(T, 0)); 388 Signed = BT->isSignedInteger(); 389 return true; 390 } 391 392 return false; 393} 394 395/// Checks whether the given value will have the same value if it it 396/// is truncated to the given width, then extended back to the 397/// original width. 398static bool IsSameIntAfterCast(const llvm::APSInt &value, 399 unsigned TargetWidth) { 400 unsigned SourceWidth = value.getBitWidth(); 401 llvm::APSInt truncated = value; 402 truncated.trunc(TargetWidth); 403 truncated.extend(SourceWidth); 404 return (truncated == value); 405} 406 407/// Checks whether the given value will have the same value if it 408/// is truncated to the given width, then extended back to the original 409/// width. 410/// 411/// The value might be a vector or a complex. 412static bool IsSameIntAfterCast(const APValue &value, unsigned TargetWidth) { 413 if (value.isInt()) 414 return IsSameIntAfterCast(value.getInt(), TargetWidth); 415 416 if (value.isVector()) { 417 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 418 if (!IsSameIntAfterCast(value.getVectorElt(i), TargetWidth)) 419 return false; 420 return true; 421 } 422 423 if (value.isComplexInt()) { 424 return IsSameIntAfterCast(value.getComplexIntReal(), TargetWidth) && 425 IsSameIntAfterCast(value.getComplexIntImag(), TargetWidth); 426 } 427 428 // This can happen with lossless casts to intptr_t of "based" lvalues. 429 // Assume it might use arbitrary bits. 430 assert(value.isLValue()); 431 return false; 432} 433 434 435/// Checks whether the given value, which currently has the given 436/// source semantics, has the same value when coerced through the 437/// target semantics. 438static bool IsSameFloatAfterCast(const llvm::APFloat &value, 439 const llvm::fltSemantics &Src, 440 const llvm::fltSemantics &Tgt) { 441 llvm::APFloat truncated = value; 442 443 bool ignored; 444 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 445 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 446 447 return truncated.bitwiseIsEqual(value); 448} 449 450/// Checks whether the given value, which currently has the given 451/// source semantics, has the same value when coerced through the 452/// target semantics. 453/// 454/// The value might be a vector of floats (or a complex number). 455static bool IsSameFloatAfterCast(const APValue &value, 456 const llvm::fltSemantics &Src, 457 const llvm::fltSemantics &Tgt) { 458 if (value.isFloat()) 459 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 460 461 if (value.isVector()) { 462 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 463 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 464 return false; 465 return true; 466 } 467 468 assert(value.isComplexFloat()); 469 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 470 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 471} 472 473/// Determines if it's reasonable for the given expression to be truncated 474/// down to the given integer width. 475/// * Boolean expressions are automatically white-listed. 476/// * Arithmetic operations on implicitly-promoted operands of the 477/// target width or less are okay --- not because the results are 478/// actually guaranteed to fit within the width, but because the 479/// user is effectively pretending that the operations are closed 480/// within the implicitly-promoted type. 481static bool IsExprValueWithinWidth(ASTContext &C, Expr *E, unsigned Width) { 482 E = E->IgnoreParens(); 483 484#ifndef NDEBUG 485 { 486 const Type *ETy = E->getType()->getCanonicalTypeInternal().getTypePtr(); 487 unsigned EWidth; 488 bool ESigned; 489 490 if (!getIntProperties(C, ETy, EWidth, ESigned)) 491 assert(0 && "expression not of integer type"); 492 493 // The caller should never let this happen. 494 assert(EWidth > Width && "called on expr whose type is too small"); 495 } 496#endif 497 498 // Strip implicit casts off. 499 while (isa<ImplicitCastExpr>(E)) { 500 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 501 502 const Type *ETy = E->getType()->getCanonicalTypeInternal().getTypePtr(); 503 504 unsigned EWidth; 505 bool ESigned; 506 if (!getIntProperties(C, ETy, EWidth, ESigned)) 507 return false; 508 509 if (EWidth <= Width) 510 return true; 511 } 512 513 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 514 switch (BO->getOpcode()) { 515 516 // Boolean-valued operations are white-listed. 517 case BinaryOperator::LAnd: 518 case BinaryOperator::LOr: 519 case BinaryOperator::LT: 520 case BinaryOperator::GT: 521 case BinaryOperator::LE: 522 case BinaryOperator::GE: 523 case BinaryOperator::EQ: 524 case BinaryOperator::NE: 525 return true; 526 527 // Operations with opaque sources are black-listed. 528 case BinaryOperator::PtrMemD: 529 case BinaryOperator::PtrMemI: 530 return false; 531 532 // Left shift gets black-listed based on a judgement call. 533 case BinaryOperator::Shl: 534 return false; 535 536 // Various special cases. 537 case BinaryOperator::Shr: 538 return IsExprValueWithinWidth(C, BO->getLHS(), Width); 539 case BinaryOperator::Comma: 540 return IsExprValueWithinWidth(C, BO->getRHS(), Width); 541 case BinaryOperator::Sub: 542 if (BO->getLHS()->getType()->isPointerType()) 543 return false; 544 // fallthrough 545 546 // Any other operator is okay if the operands are 547 // promoted from expressions of appropriate size. 548 default: 549 return IsExprValueWithinWidth(C, BO->getLHS(), Width) && 550 IsExprValueWithinWidth(C, BO->getRHS(), Width); 551 } 552 } 553 554 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 555 switch (UO->getOpcode()) { 556 // Boolean-valued operations are white-listed. 557 case UnaryOperator::LNot: 558 return true; 559 560 // Operations with opaque sources are black-listed. 561 case UnaryOperator::Deref: 562 case UnaryOperator::AddrOf: // should be impossible 563 return false; 564 565 case UnaryOperator::OffsetOf: 566 return false; 567 568 default: 569 return IsExprValueWithinWidth(C, UO->getSubExpr(), Width); 570 } 571 } 572 573 // Don't diagnose if the expression is an integer constant 574 // whose value in the target type is the same as it was 575 // in the original type. 576 Expr::EvalResult result; 577 if (E->Evaluate(result, C)) 578 if (IsSameIntAfterCast(result.Val, Width)) 579 return true; 580 581 return false; 582} 583 584/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 585static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) { 586 S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange(); 587} 588 589/// Implements -Wconversion. 590static void CheckImplicitConversion(Sema &S, Expr *E, QualType T) { 591 // Don't diagnose in unevaluated contexts. 592 if (S.ExprEvalContexts.back().Context == Sema::Unevaluated) 593 return; 594 595 // Don't diagnose for value-dependent expressions. 596 if (E->isValueDependent()) 597 return; 598 599 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 600 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 601 602 // Never diagnose implicit casts to bool. 603 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 604 return; 605 606 // Strip vector types. 607 if (isa<VectorType>(Source)) { 608 if (!isa<VectorType>(Target)) 609 return DiagnoseImpCast(S, E, T, diag::warn_impcast_vector_scalar); 610 611 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 612 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 613 } 614 615 // Strip complex types. 616 if (isa<ComplexType>(Source)) { 617 if (!isa<ComplexType>(Target)) 618 return DiagnoseImpCast(S, E, T, diag::warn_impcast_complex_scalar); 619 620 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 621 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 622 } 623 624 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 625 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 626 627 // If the source is floating point... 628 if (SourceBT && SourceBT->isFloatingPoint()) { 629 // ...and the target is floating point... 630 if (TargetBT && TargetBT->isFloatingPoint()) { 631 // ...then warn if we're dropping FP rank. 632 633 // Builtin FP kinds are ordered by increasing FP rank. 634 if (SourceBT->getKind() > TargetBT->getKind()) { 635 // Don't warn about float constants that are precisely 636 // representable in the target type. 637 Expr::EvalResult result; 638 if (E->Evaluate(result, S.Context)) { 639 // Value might be a float, a float vector, or a float complex. 640 if (IsSameFloatAfterCast(result.Val, 641 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 642 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 643 return; 644 } 645 646 DiagnoseImpCast(S, E, T, diag::warn_impcast_float_precision); 647 } 648 return; 649 } 650 651 // If the target is integral, always warn. 652 if ((TargetBT && TargetBT->isInteger())) 653 // TODO: don't warn for integer values? 654 return DiagnoseImpCast(S, E, T, diag::warn_impcast_float_integer); 655 656 return; 657 } 658 659 unsigned SourceWidth, TargetWidth; 660 bool SourceSigned, TargetSigned; 661 662 if (!getIntProperties(S.Context, Source, SourceWidth, SourceSigned) || 663 !getIntProperties(S.Context, Target, TargetWidth, TargetSigned)) 664 return; 665 666 if (SourceWidth > TargetWidth) { 667 if (IsExprValueWithinWidth(S.Context, E, TargetWidth)) 668 return; 669 670 // People want to build with -Wshorten-64-to-32 and not -Wconversion 671 // and by god we'll let them. 672 if (SourceWidth == 64 && TargetWidth == 32) 673 return DiagnoseImpCast(S, E, T, diag::warn_impcast_integer_64_32); 674 return DiagnoseImpCast(S, E, T, diag::warn_impcast_integer_precision); 675 } 676 677 return; 678} 679 680/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast. 681/// If there is already an implicit cast, merge into the existing one. 682/// If isLvalue, the result of the cast is an lvalue. 683void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty, 684 CastExpr::CastKind Kind, bool isLvalue) { 685 QualType ExprTy = Context.getCanonicalType(Expr->getType()); 686 QualType TypeTy = Context.getCanonicalType(Ty); 687 688 if (ExprTy == TypeTy) 689 return; 690 691 if (Expr->getType()->isPointerType() && Ty->isPointerType()) { 692 QualType ExprBaseType = cast<PointerType>(ExprTy)->getPointeeType(); 693 QualType BaseType = cast<PointerType>(TypeTy)->getPointeeType(); 694 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) { 695 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast) 696 << Expr->getSourceRange(); 697 } 698 } 699 700 CheckImplicitConversion(*this, Expr, Ty); 701 702 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) { 703 if (ImpCast->getCastKind() == Kind) { 704 ImpCast->setType(Ty); 705 ImpCast->setLvalueCast(isLvalue); 706 return; 707 } 708 } 709 710 Expr = new (Context) ImplicitCastExpr(Ty, Kind, Expr, isLvalue); 711} 712 713void Sema::DeleteExpr(ExprTy *E) { 714 if (E) static_cast<Expr*>(E)->Destroy(Context); 715} 716void Sema::DeleteStmt(StmtTy *S) { 717 if (S) static_cast<Stmt*>(S)->Destroy(Context); 718} 719 720/// ActOnEndOfTranslationUnit - This is called at the very end of the 721/// translation unit when EOF is reached and all but the top-level scope is 722/// popped. 723void Sema::ActOnEndOfTranslationUnit() { 724 725 while (1) { 726 // C++: Perform implicit template instantiations. 727 // 728 // FIXME: When we perform these implicit instantiations, we do not carefully 729 // keep track of the point of instantiation (C++ [temp.point]). This means 730 // that name lookup that occurs within the template instantiation will 731 // always happen at the end of the translation unit, so it will find 732 // some names that should not be found. Although this is common behavior 733 // for C++ compilers, it is technically wrong. In the future, we either need 734 // to be able to filter the results of name lookup or we need to perform 735 // template instantiations earlier. 736 PerformPendingImplicitInstantiations(); 737 738 /// If ProcessPendingClassesWithUnmarkedVirtualMembers ends up marking 739 /// any virtual member functions it might lead to more pending template 740 /// instantiations, which is why we need to loop here. 741 if (!ProcessPendingClassesWithUnmarkedVirtualMembers()) 742 break; 743 } 744 745 // Check for #pragma weak identifiers that were never declared 746 // FIXME: This will cause diagnostics to be emitted in a non-determinstic 747 // order! Iterating over a densemap like this is bad. 748 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator 749 I = WeakUndeclaredIdentifiers.begin(), 750 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) { 751 if (I->second.getUsed()) continue; 752 753 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared) 754 << I->first; 755 } 756 757 if (!CompleteTranslationUnit) 758 return; 759 760 // C99 6.9.2p2: 761 // A declaration of an identifier for an object that has file 762 // scope without an initializer, and without a storage-class 763 // specifier or with the storage-class specifier static, 764 // constitutes a tentative definition. If a translation unit 765 // contains one or more tentative definitions for an identifier, 766 // and the translation unit contains no external definition for 767 // that identifier, then the behavior is exactly as if the 768 // translation unit contains a file scope declaration of that 769 // identifier, with the composite type as of the end of the 770 // translation unit, with an initializer equal to 0. 771 for (unsigned i = 0, e = TentativeDefinitionList.size(); i != e; ++i) { 772 VarDecl *VD = TentativeDefinitions.lookup(TentativeDefinitionList[i]); 773 774 // If the tentative definition was completed, it will be in the list, but 775 // not the map. 776 if (VD == 0 || VD->isInvalidDecl() || !VD->isTentativeDefinition(Context)) 777 continue; 778 779 if (const IncompleteArrayType *ArrayT 780 = Context.getAsIncompleteArrayType(VD->getType())) { 781 if (RequireCompleteType(VD->getLocation(), 782 ArrayT->getElementType(), 783 diag::err_tentative_def_incomplete_type_arr)) { 784 VD->setInvalidDecl(); 785 continue; 786 } 787 788 // Set the length of the array to 1 (C99 6.9.2p5). 789 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array); 790 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true); 791 QualType T = Context.getConstantArrayType(ArrayT->getElementType(), 792 One, ArrayType::Normal, 0); 793 VD->setType(T); 794 } else if (RequireCompleteType(VD->getLocation(), VD->getType(), 795 diag::err_tentative_def_incomplete_type)) 796 VD->setInvalidDecl(); 797 798 // Notify the consumer that we've completed a tentative definition. 799 if (!VD->isInvalidDecl()) 800 Consumer.CompleteTentativeDefinition(VD); 801 802 } 803} 804 805 806//===----------------------------------------------------------------------===// 807// Helper functions. 808//===----------------------------------------------------------------------===// 809 810DeclContext *Sema::getFunctionLevelDeclContext() { 811 DeclContext *DC = CurContext; 812 813 while (isa<BlockDecl>(DC)) 814 DC = DC->getParent(); 815 816 return DC; 817} 818 819/// getCurFunctionDecl - If inside of a function body, this returns a pointer 820/// to the function decl for the function being parsed. If we're currently 821/// in a 'block', this returns the containing context. 822FunctionDecl *Sema::getCurFunctionDecl() { 823 DeclContext *DC = getFunctionLevelDeclContext(); 824 return dyn_cast<FunctionDecl>(DC); 825} 826 827ObjCMethodDecl *Sema::getCurMethodDecl() { 828 DeclContext *DC = getFunctionLevelDeclContext(); 829 return dyn_cast<ObjCMethodDecl>(DC); 830} 831 832NamedDecl *Sema::getCurFunctionOrMethodDecl() { 833 DeclContext *DC = getFunctionLevelDeclContext(); 834 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC)) 835 return cast<NamedDecl>(DC); 836 return 0; 837} 838 839Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() { 840 if (!this->Emit()) 841 return; 842 843 // If this is not a note, and we're in a template instantiation 844 // that is different from the last template instantiation where 845 // we emitted an error, print a template instantiation 846 // backtrace. 847 if (!SemaRef.Diags.isBuiltinNote(DiagID) && 848 !SemaRef.ActiveTemplateInstantiations.empty() && 849 SemaRef.ActiveTemplateInstantiations.back() 850 != SemaRef.LastTemplateInstantiationErrorContext) { 851 SemaRef.PrintInstantiationStack(); 852 SemaRef.LastTemplateInstantiationErrorContext 853 = SemaRef.ActiveTemplateInstantiations.back(); 854 } 855} 856 857Sema::SemaDiagnosticBuilder 858Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) { 859 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID())); 860 PD.Emit(Builder); 861 862 return Builder; 863} 864 865void Sema::ActOnComment(SourceRange Comment) { 866 Context.Comments.push_back(Comment); 867} 868 869