Expr.cpp revision 7a7ee3033e44b45630981355460ef89efa0bdcc4
1//===--- Expr.cpp - Expression AST Node 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 Expr class and subclasses. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/AST/Expr.h" 15#include "clang/AST/ExprCXX.h" 16#include "clang/AST/APValue.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/DeclObjC.h" 19#include "clang/AST/DeclCXX.h" 20#include "clang/AST/DeclTemplate.h" 21#include "clang/AST/RecordLayout.h" 22#include "clang/AST/StmtVisitor.h" 23#include "clang/Lex/LiteralSupport.h" 24#include "clang/Lex/Lexer.h" 25#include "clang/Sema/SemaDiagnostic.h" 26#include "clang/Basic/Builtins.h" 27#include "clang/Basic/SourceManager.h" 28#include "clang/Basic/TargetInfo.h" 29#include "llvm/Support/ErrorHandling.h" 30#include "llvm/Support/raw_ostream.h" 31#include <algorithm> 32#include <cstring> 33using namespace clang; 34 35/// isKnownToHaveBooleanValue - Return true if this is an integer expression 36/// that is known to return 0 or 1. This happens for _Bool/bool expressions 37/// but also int expressions which are produced by things like comparisons in 38/// C. 39bool Expr::isKnownToHaveBooleanValue() const { 40 const Expr *E = IgnoreParens(); 41 42 // If this value has _Bool type, it is obvious 0/1. 43 if (E->getType()->isBooleanType()) return true; 44 // If this is a non-scalar-integer type, we don't care enough to try. 45 if (!E->getType()->isIntegralOrEnumerationType()) return false; 46 47 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 48 switch (UO->getOpcode()) { 49 case UO_Plus: 50 return UO->getSubExpr()->isKnownToHaveBooleanValue(); 51 default: 52 return false; 53 } 54 } 55 56 // Only look through implicit casts. If the user writes 57 // '(int) (a && b)' treat it as an arbitrary int. 58 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) 59 return CE->getSubExpr()->isKnownToHaveBooleanValue(); 60 61 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 62 switch (BO->getOpcode()) { 63 default: return false; 64 case BO_LT: // Relational operators. 65 case BO_GT: 66 case BO_LE: 67 case BO_GE: 68 case BO_EQ: // Equality operators. 69 case BO_NE: 70 case BO_LAnd: // AND operator. 71 case BO_LOr: // Logical OR operator. 72 return true; 73 74 case BO_And: // Bitwise AND operator. 75 case BO_Xor: // Bitwise XOR operator. 76 case BO_Or: // Bitwise OR operator. 77 // Handle things like (x==2)|(y==12). 78 return BO->getLHS()->isKnownToHaveBooleanValue() && 79 BO->getRHS()->isKnownToHaveBooleanValue(); 80 81 case BO_Comma: 82 case BO_Assign: 83 return BO->getRHS()->isKnownToHaveBooleanValue(); 84 } 85 } 86 87 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) 88 return CO->getTrueExpr()->isKnownToHaveBooleanValue() && 89 CO->getFalseExpr()->isKnownToHaveBooleanValue(); 90 91 return false; 92} 93 94// Amusing macro metaprogramming hack: check whether a class provides 95// a more specific implementation of getExprLoc(). 96namespace { 97 /// This implementation is used when a class provides a custom 98 /// implementation of getExprLoc. 99 template <class E, class T> 100 SourceLocation getExprLocImpl(const Expr *expr, 101 SourceLocation (T::*v)() const) { 102 return static_cast<const E*>(expr)->getExprLoc(); 103 } 104 105 /// This implementation is used when a class doesn't provide 106 /// a custom implementation of getExprLoc. Overload resolution 107 /// should pick it over the implementation above because it's 108 /// more specialized according to function template partial ordering. 109 template <class E> 110 SourceLocation getExprLocImpl(const Expr *expr, 111 SourceLocation (Expr::*v)() const) { 112 return static_cast<const E*>(expr)->getSourceRange().getBegin(); 113 } 114} 115 116SourceLocation Expr::getExprLoc() const { 117 switch (getStmtClass()) { 118 case Stmt::NoStmtClass: llvm_unreachable("statement without class"); 119#define ABSTRACT_STMT(type) 120#define STMT(type, base) \ 121 case Stmt::type##Class: llvm_unreachable(#type " is not an Expr"); break; 122#define EXPR(type, base) \ 123 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc); 124#include "clang/AST/StmtNodes.inc" 125 } 126 llvm_unreachable("unknown statement kind"); 127 return SourceLocation(); 128} 129 130//===----------------------------------------------------------------------===// 131// Primary Expressions. 132//===----------------------------------------------------------------------===// 133 134/// \brief Compute the type-, value-, and instantiation-dependence of a 135/// declaration reference 136/// based on the declaration being referenced. 137static void computeDeclRefDependence(NamedDecl *D, QualType T, 138 bool &TypeDependent, 139 bool &ValueDependent, 140 bool &InstantiationDependent) { 141 TypeDependent = false; 142 ValueDependent = false; 143 InstantiationDependent = false; 144 145 // (TD) C++ [temp.dep.expr]p3: 146 // An id-expression is type-dependent if it contains: 147 // 148 // and 149 // 150 // (VD) C++ [temp.dep.constexpr]p2: 151 // An identifier is value-dependent if it is: 152 153 // (TD) - an identifier that was declared with dependent type 154 // (VD) - a name declared with a dependent type, 155 if (T->isDependentType()) { 156 TypeDependent = true; 157 ValueDependent = true; 158 InstantiationDependent = true; 159 return; 160 } else if (T->isInstantiationDependentType()) { 161 InstantiationDependent = true; 162 } 163 164 // (TD) - a conversion-function-id that specifies a dependent type 165 if (D->getDeclName().getNameKind() 166 == DeclarationName::CXXConversionFunctionName) { 167 QualType T = D->getDeclName().getCXXNameType(); 168 if (T->isDependentType()) { 169 TypeDependent = true; 170 ValueDependent = true; 171 InstantiationDependent = true; 172 return; 173 } 174 175 if (T->isInstantiationDependentType()) 176 InstantiationDependent = true; 177 } 178 179 // (VD) - the name of a non-type template parameter, 180 if (isa<NonTypeTemplateParmDecl>(D)) { 181 ValueDependent = true; 182 InstantiationDependent = true; 183 return; 184 } 185 186 // (VD) - a constant with integral or enumeration type and is 187 // initialized with an expression that is value-dependent. 188 // (VD) - a constant with literal type and is initialized with an 189 // expression that is value-dependent [C++11]. 190 // (VD) - FIXME: Missing from the standard: 191 // - an entity with reference type and is initialized with an 192 // expression that is value-dependent [C++11] 193 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 194 if ((D->getASTContext().getLangOptions().CPlusPlus0x ? 195 Var->getType()->isLiteralType() : 196 Var->getType()->isIntegralOrEnumerationType()) && 197 (Var->getType().getCVRQualifiers() == Qualifiers::Const || 198 Var->getType()->isReferenceType())) { 199 if (const Expr *Init = Var->getAnyInitializer()) 200 if (Init->isValueDependent()) { 201 ValueDependent = true; 202 InstantiationDependent = true; 203 } 204 } 205 206 // (VD) - FIXME: Missing from the standard: 207 // - a member function or a static data member of the current 208 // instantiation 209 if (Var->isStaticDataMember() && 210 Var->getDeclContext()->isDependentContext()) { 211 ValueDependent = true; 212 InstantiationDependent = true; 213 } 214 215 return; 216 } 217 218 // (VD) - FIXME: Missing from the standard: 219 // - a member function or a static data member of the current 220 // instantiation 221 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) { 222 ValueDependent = true; 223 InstantiationDependent = true; 224 } 225} 226 227void DeclRefExpr::computeDependence() { 228 bool TypeDependent = false; 229 bool ValueDependent = false; 230 bool InstantiationDependent = false; 231 computeDeclRefDependence(getDecl(), getType(), TypeDependent, ValueDependent, 232 InstantiationDependent); 233 234 // (TD) C++ [temp.dep.expr]p3: 235 // An id-expression is type-dependent if it contains: 236 // 237 // and 238 // 239 // (VD) C++ [temp.dep.constexpr]p2: 240 // An identifier is value-dependent if it is: 241 if (!TypeDependent && !ValueDependent && 242 hasExplicitTemplateArgs() && 243 TemplateSpecializationType::anyDependentTemplateArguments( 244 getTemplateArgs(), 245 getNumTemplateArgs(), 246 InstantiationDependent)) { 247 TypeDependent = true; 248 ValueDependent = true; 249 InstantiationDependent = true; 250 } 251 252 ExprBits.TypeDependent = TypeDependent; 253 ExprBits.ValueDependent = ValueDependent; 254 ExprBits.InstantiationDependent = InstantiationDependent; 255 256 // Is the declaration a parameter pack? 257 if (getDecl()->isParameterPack()) 258 ExprBits.ContainsUnexpandedParameterPack = true; 259} 260 261DeclRefExpr::DeclRefExpr(NestedNameSpecifierLoc QualifierLoc, 262 ValueDecl *D, const DeclarationNameInfo &NameInfo, 263 NamedDecl *FoundD, 264 const TemplateArgumentListInfo *TemplateArgs, 265 QualType T, ExprValueKind VK) 266 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false), 267 D(D), Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) { 268 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0; 269 if (QualifierLoc) 270 getInternalQualifierLoc() = QualifierLoc; 271 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0; 272 if (FoundD) 273 getInternalFoundDecl() = FoundD; 274 DeclRefExprBits.HasExplicitTemplateArgs = TemplateArgs ? 1 : 0; 275 if (TemplateArgs) { 276 bool Dependent = false; 277 bool InstantiationDependent = false; 278 bool ContainsUnexpandedParameterPack = false; 279 getExplicitTemplateArgs().initializeFrom(*TemplateArgs, Dependent, 280 InstantiationDependent, 281 ContainsUnexpandedParameterPack); 282 if (InstantiationDependent) 283 setInstantiationDependent(true); 284 } 285 DeclRefExprBits.HadMultipleCandidates = 0; 286 287 computeDependence(); 288} 289 290DeclRefExpr *DeclRefExpr::Create(ASTContext &Context, 291 NestedNameSpecifierLoc QualifierLoc, 292 ValueDecl *D, 293 SourceLocation NameLoc, 294 QualType T, 295 ExprValueKind VK, 296 NamedDecl *FoundD, 297 const TemplateArgumentListInfo *TemplateArgs) { 298 return Create(Context, QualifierLoc, D, 299 DeclarationNameInfo(D->getDeclName(), NameLoc), 300 T, VK, FoundD, TemplateArgs); 301} 302 303DeclRefExpr *DeclRefExpr::Create(ASTContext &Context, 304 NestedNameSpecifierLoc QualifierLoc, 305 ValueDecl *D, 306 const DeclarationNameInfo &NameInfo, 307 QualType T, 308 ExprValueKind VK, 309 NamedDecl *FoundD, 310 const TemplateArgumentListInfo *TemplateArgs) { 311 // Filter out cases where the found Decl is the same as the value refenenced. 312 if (D == FoundD) 313 FoundD = 0; 314 315 std::size_t Size = sizeof(DeclRefExpr); 316 if (QualifierLoc != 0) 317 Size += sizeof(NestedNameSpecifierLoc); 318 if (FoundD) 319 Size += sizeof(NamedDecl *); 320 if (TemplateArgs) 321 Size += ASTTemplateArgumentListInfo::sizeFor(*TemplateArgs); 322 323 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>()); 324 return new (Mem) DeclRefExpr(QualifierLoc, D, NameInfo, FoundD, TemplateArgs, 325 T, VK); 326} 327 328DeclRefExpr *DeclRefExpr::CreateEmpty(ASTContext &Context, 329 bool HasQualifier, 330 bool HasFoundDecl, 331 bool HasExplicitTemplateArgs, 332 unsigned NumTemplateArgs) { 333 std::size_t Size = sizeof(DeclRefExpr); 334 if (HasQualifier) 335 Size += sizeof(NestedNameSpecifierLoc); 336 if (HasFoundDecl) 337 Size += sizeof(NamedDecl *); 338 if (HasExplicitTemplateArgs) 339 Size += ASTTemplateArgumentListInfo::sizeFor(NumTemplateArgs); 340 341 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>()); 342 return new (Mem) DeclRefExpr(EmptyShell()); 343} 344 345SourceRange DeclRefExpr::getSourceRange() const { 346 SourceRange R = getNameInfo().getSourceRange(); 347 if (hasQualifier()) 348 R.setBegin(getQualifierLoc().getBeginLoc()); 349 if (hasExplicitTemplateArgs()) 350 R.setEnd(getRAngleLoc()); 351 return R; 352} 353 354// FIXME: Maybe this should use DeclPrinter with a special "print predefined 355// expr" policy instead. 356std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) { 357 ASTContext &Context = CurrentDecl->getASTContext(); 358 359 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) { 360 if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual) 361 return FD->getNameAsString(); 362 363 llvm::SmallString<256> Name; 364 llvm::raw_svector_ostream Out(Name); 365 366 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 367 if (MD->isVirtual() && IT != PrettyFunctionNoVirtual) 368 Out << "virtual "; 369 if (MD->isStatic()) 370 Out << "static "; 371 } 372 373 PrintingPolicy Policy(Context.getLangOptions()); 374 375 std::string Proto = FD->getQualifiedNameAsString(Policy); 376 377 const FunctionType *AFT = FD->getType()->getAs<FunctionType>(); 378 const FunctionProtoType *FT = 0; 379 if (FD->hasWrittenPrototype()) 380 FT = dyn_cast<FunctionProtoType>(AFT); 381 382 Proto += "("; 383 if (FT) { 384 llvm::raw_string_ostream POut(Proto); 385 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 386 if (i) POut << ", "; 387 std::string Param; 388 FD->getParamDecl(i)->getType().getAsStringInternal(Param, Policy); 389 POut << Param; 390 } 391 392 if (FT->isVariadic()) { 393 if (FD->getNumParams()) POut << ", "; 394 POut << "..."; 395 } 396 } 397 Proto += ")"; 398 399 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 400 Qualifiers ThisQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers()); 401 if (ThisQuals.hasConst()) 402 Proto += " const"; 403 if (ThisQuals.hasVolatile()) 404 Proto += " volatile"; 405 } 406 407 if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD)) 408 AFT->getResultType().getAsStringInternal(Proto, Policy); 409 410 Out << Proto; 411 412 Out.flush(); 413 return Name.str().str(); 414 } 415 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) { 416 llvm::SmallString<256> Name; 417 llvm::raw_svector_ostream Out(Name); 418 Out << (MD->isInstanceMethod() ? '-' : '+'); 419 Out << '['; 420 421 // For incorrect code, there might not be an ObjCInterfaceDecl. Do 422 // a null check to avoid a crash. 423 if (const ObjCInterfaceDecl *ID = MD->getClassInterface()) 424 Out << *ID; 425 426 if (const ObjCCategoryImplDecl *CID = 427 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext())) 428 Out << '(' << CID << ')'; 429 430 Out << ' '; 431 Out << MD->getSelector().getAsString(); 432 Out << ']'; 433 434 Out.flush(); 435 return Name.str().str(); 436 } 437 if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) { 438 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string. 439 return "top level"; 440 } 441 return ""; 442} 443 444void APNumericStorage::setIntValue(ASTContext &C, const llvm::APInt &Val) { 445 if (hasAllocation()) 446 C.Deallocate(pVal); 447 448 BitWidth = Val.getBitWidth(); 449 unsigned NumWords = Val.getNumWords(); 450 const uint64_t* Words = Val.getRawData(); 451 if (NumWords > 1) { 452 pVal = new (C) uint64_t[NumWords]; 453 std::copy(Words, Words + NumWords, pVal); 454 } else if (NumWords == 1) 455 VAL = Words[0]; 456 else 457 VAL = 0; 458} 459 460IntegerLiteral * 461IntegerLiteral::Create(ASTContext &C, const llvm::APInt &V, 462 QualType type, SourceLocation l) { 463 return new (C) IntegerLiteral(C, V, type, l); 464} 465 466IntegerLiteral * 467IntegerLiteral::Create(ASTContext &C, EmptyShell Empty) { 468 return new (C) IntegerLiteral(Empty); 469} 470 471FloatingLiteral * 472FloatingLiteral::Create(ASTContext &C, const llvm::APFloat &V, 473 bool isexact, QualType Type, SourceLocation L) { 474 return new (C) FloatingLiteral(C, V, isexact, Type, L); 475} 476 477FloatingLiteral * 478FloatingLiteral::Create(ASTContext &C, EmptyShell Empty) { 479 return new (C) FloatingLiteral(C, Empty); 480} 481 482/// getValueAsApproximateDouble - This returns the value as an inaccurate 483/// double. Note that this may cause loss of precision, but is useful for 484/// debugging dumps, etc. 485double FloatingLiteral::getValueAsApproximateDouble() const { 486 llvm::APFloat V = getValue(); 487 bool ignored; 488 V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven, 489 &ignored); 490 return V.convertToDouble(); 491} 492 493int StringLiteral::mapCharByteWidth(TargetInfo const &target,StringKind k) { 494 int CharByteWidth; 495 switch(k) { 496 case Ascii: 497 case UTF8: 498 CharByteWidth = target.getCharWidth(); 499 break; 500 case Wide: 501 CharByteWidth = target.getWCharWidth(); 502 break; 503 case UTF16: 504 CharByteWidth = target.getChar16Width(); 505 break; 506 case UTF32: 507 CharByteWidth = target.getChar32Width(); 508 } 509 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple"); 510 CharByteWidth /= 8; 511 assert((CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4) 512 && "character byte widths supported are 1, 2, and 4 only"); 513 return CharByteWidth; 514} 515 516StringLiteral *StringLiteral::Create(ASTContext &C, StringRef Str, 517 StringKind Kind, bool Pascal, QualType Ty, 518 const SourceLocation *Loc, 519 unsigned NumStrs) { 520 // Allocate enough space for the StringLiteral plus an array of locations for 521 // any concatenated string tokens. 522 void *Mem = C.Allocate(sizeof(StringLiteral)+ 523 sizeof(SourceLocation)*(NumStrs-1), 524 llvm::alignOf<StringLiteral>()); 525 StringLiteral *SL = new (Mem) StringLiteral(Ty); 526 527 // OPTIMIZE: could allocate this appended to the StringLiteral. 528 SL->setString(C,Str,Kind,Pascal); 529 530 SL->TokLocs[0] = Loc[0]; 531 SL->NumConcatenated = NumStrs; 532 533 if (NumStrs != 1) 534 memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1)); 535 return SL; 536} 537 538StringLiteral *StringLiteral::CreateEmpty(ASTContext &C, unsigned NumStrs) { 539 void *Mem = C.Allocate(sizeof(StringLiteral)+ 540 sizeof(SourceLocation)*(NumStrs-1), 541 llvm::alignOf<StringLiteral>()); 542 StringLiteral *SL = new (Mem) StringLiteral(QualType()); 543 SL->CharByteWidth = 0; 544 SL->Length = 0; 545 SL->NumConcatenated = NumStrs; 546 return SL; 547} 548 549void StringLiteral::setString(ASTContext &C, StringRef Str, 550 StringKind Kind, bool IsPascal) { 551 //FIXME: we assume that the string data comes from a target that uses the same 552 // code unit size and endianess for the type of string. 553 this->Kind = Kind; 554 this->IsPascal = IsPascal; 555 556 CharByteWidth = mapCharByteWidth(C.getTargetInfo(),Kind); 557 assert((Str.size()%CharByteWidth == 0) 558 && "size of data must be multiple of CharByteWidth"); 559 Length = Str.size()/CharByteWidth; 560 561 switch(CharByteWidth) { 562 case 1: { 563 char *AStrData = new (C) char[Length]; 564 std::memcpy(AStrData,Str.data(),Str.size()); 565 StrData.asChar = AStrData; 566 break; 567 } 568 case 2: { 569 uint16_t *AStrData = new (C) uint16_t[Length]; 570 std::memcpy(AStrData,Str.data(),Str.size()); 571 StrData.asUInt16 = AStrData; 572 break; 573 } 574 case 4: { 575 uint32_t *AStrData = new (C) uint32_t[Length]; 576 std::memcpy(AStrData,Str.data(),Str.size()); 577 StrData.asUInt32 = AStrData; 578 break; 579 } 580 default: 581 assert(false && "unsupported CharByteWidth"); 582 } 583} 584 585/// getLocationOfByte - Return a source location that points to the specified 586/// byte of this string literal. 587/// 588/// Strings are amazingly complex. They can be formed from multiple tokens and 589/// can have escape sequences in them in addition to the usual trigraph and 590/// escaped newline business. This routine handles this complexity. 591/// 592SourceLocation StringLiteral:: 593getLocationOfByte(unsigned ByteNo, const SourceManager &SM, 594 const LangOptions &Features, const TargetInfo &Target) const { 595 assert(Kind == StringLiteral::Ascii && "This only works for ASCII strings"); 596 597 // Loop over all of the tokens in this string until we find the one that 598 // contains the byte we're looking for. 599 unsigned TokNo = 0; 600 while (1) { 601 assert(TokNo < getNumConcatenated() && "Invalid byte number!"); 602 SourceLocation StrTokLoc = getStrTokenLoc(TokNo); 603 604 // Get the spelling of the string so that we can get the data that makes up 605 // the string literal, not the identifier for the macro it is potentially 606 // expanded through. 607 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc); 608 609 // Re-lex the token to get its length and original spelling. 610 std::pair<FileID, unsigned> LocInfo =SM.getDecomposedLoc(StrTokSpellingLoc); 611 bool Invalid = false; 612 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 613 if (Invalid) 614 return StrTokSpellingLoc; 615 616 const char *StrData = Buffer.data()+LocInfo.second; 617 618 // Create a langops struct and enable trigraphs. This is sufficient for 619 // relexing tokens. 620 LangOptions LangOpts; 621 LangOpts.Trigraphs = true; 622 623 // Create a lexer starting at the beginning of this token. 624 Lexer TheLexer(StrTokSpellingLoc, Features, Buffer.begin(), StrData, 625 Buffer.end()); 626 Token TheTok; 627 TheLexer.LexFromRawLexer(TheTok); 628 629 // Use the StringLiteralParser to compute the length of the string in bytes. 630 StringLiteralParser SLP(&TheTok, 1, SM, Features, Target); 631 unsigned TokNumBytes = SLP.GetStringLength(); 632 633 // If the byte is in this token, return the location of the byte. 634 if (ByteNo < TokNumBytes || 635 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) { 636 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo); 637 638 // Now that we know the offset of the token in the spelling, use the 639 // preprocessor to get the offset in the original source. 640 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features); 641 } 642 643 // Move to the next string token. 644 ++TokNo; 645 ByteNo -= TokNumBytes; 646 } 647} 648 649 650 651/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 652/// corresponds to, e.g. "sizeof" or "[pre]++". 653const char *UnaryOperator::getOpcodeStr(Opcode Op) { 654 switch (Op) { 655 default: llvm_unreachable("Unknown unary operator"); 656 case UO_PostInc: return "++"; 657 case UO_PostDec: return "--"; 658 case UO_PreInc: return "++"; 659 case UO_PreDec: return "--"; 660 case UO_AddrOf: return "&"; 661 case UO_Deref: return "*"; 662 case UO_Plus: return "+"; 663 case UO_Minus: return "-"; 664 case UO_Not: return "~"; 665 case UO_LNot: return "!"; 666 case UO_Real: return "__real"; 667 case UO_Imag: return "__imag"; 668 case UO_Extension: return "__extension__"; 669 } 670} 671 672UnaryOperatorKind 673UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) { 674 switch (OO) { 675 default: llvm_unreachable("No unary operator for overloaded function"); 676 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc; 677 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec; 678 case OO_Amp: return UO_AddrOf; 679 case OO_Star: return UO_Deref; 680 case OO_Plus: return UO_Plus; 681 case OO_Minus: return UO_Minus; 682 case OO_Tilde: return UO_Not; 683 case OO_Exclaim: return UO_LNot; 684 } 685} 686 687OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) { 688 switch (Opc) { 689 case UO_PostInc: case UO_PreInc: return OO_PlusPlus; 690 case UO_PostDec: case UO_PreDec: return OO_MinusMinus; 691 case UO_AddrOf: return OO_Amp; 692 case UO_Deref: return OO_Star; 693 case UO_Plus: return OO_Plus; 694 case UO_Minus: return OO_Minus; 695 case UO_Not: return OO_Tilde; 696 case UO_LNot: return OO_Exclaim; 697 default: return OO_None; 698 } 699} 700 701 702//===----------------------------------------------------------------------===// 703// Postfix Operators. 704//===----------------------------------------------------------------------===// 705 706CallExpr::CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs, 707 Expr **args, unsigned numargs, QualType t, ExprValueKind VK, 708 SourceLocation rparenloc) 709 : Expr(SC, t, VK, OK_Ordinary, 710 fn->isTypeDependent(), 711 fn->isValueDependent(), 712 fn->isInstantiationDependent(), 713 fn->containsUnexpandedParameterPack()), 714 NumArgs(numargs) { 715 716 SubExprs = new (C) Stmt*[numargs+PREARGS_START+NumPreArgs]; 717 SubExprs[FN] = fn; 718 for (unsigned i = 0; i != numargs; ++i) { 719 if (args[i]->isTypeDependent()) 720 ExprBits.TypeDependent = true; 721 if (args[i]->isValueDependent()) 722 ExprBits.ValueDependent = true; 723 if (args[i]->isInstantiationDependent()) 724 ExprBits.InstantiationDependent = true; 725 if (args[i]->containsUnexpandedParameterPack()) 726 ExprBits.ContainsUnexpandedParameterPack = true; 727 728 SubExprs[i+PREARGS_START+NumPreArgs] = args[i]; 729 } 730 731 CallExprBits.NumPreArgs = NumPreArgs; 732 RParenLoc = rparenloc; 733} 734 735CallExpr::CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, 736 QualType t, ExprValueKind VK, SourceLocation rparenloc) 737 : Expr(CallExprClass, t, VK, OK_Ordinary, 738 fn->isTypeDependent(), 739 fn->isValueDependent(), 740 fn->isInstantiationDependent(), 741 fn->containsUnexpandedParameterPack()), 742 NumArgs(numargs) { 743 744 SubExprs = new (C) Stmt*[numargs+PREARGS_START]; 745 SubExprs[FN] = fn; 746 for (unsigned i = 0; i != numargs; ++i) { 747 if (args[i]->isTypeDependent()) 748 ExprBits.TypeDependent = true; 749 if (args[i]->isValueDependent()) 750 ExprBits.ValueDependent = true; 751 if (args[i]->isInstantiationDependent()) 752 ExprBits.InstantiationDependent = true; 753 if (args[i]->containsUnexpandedParameterPack()) 754 ExprBits.ContainsUnexpandedParameterPack = true; 755 756 SubExprs[i+PREARGS_START] = args[i]; 757 } 758 759 CallExprBits.NumPreArgs = 0; 760 RParenLoc = rparenloc; 761} 762 763CallExpr::CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty) 764 : Expr(SC, Empty), SubExprs(0), NumArgs(0) { 765 // FIXME: Why do we allocate this? 766 SubExprs = new (C) Stmt*[PREARGS_START]; 767 CallExprBits.NumPreArgs = 0; 768} 769 770CallExpr::CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs, 771 EmptyShell Empty) 772 : Expr(SC, Empty), SubExprs(0), NumArgs(0) { 773 // FIXME: Why do we allocate this? 774 SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs]; 775 CallExprBits.NumPreArgs = NumPreArgs; 776} 777 778Decl *CallExpr::getCalleeDecl() { 779 Expr *CEE = getCallee()->IgnoreParenImpCasts(); 780 781 while (SubstNonTypeTemplateParmExpr *NTTP 782 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) { 783 CEE = NTTP->getReplacement()->IgnoreParenCasts(); 784 } 785 786 // If we're calling a dereference, look at the pointer instead. 787 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) { 788 if (BO->isPtrMemOp()) 789 CEE = BO->getRHS()->IgnoreParenCasts(); 790 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) { 791 if (UO->getOpcode() == UO_Deref) 792 CEE = UO->getSubExpr()->IgnoreParenCasts(); 793 } 794 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) 795 return DRE->getDecl(); 796 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE)) 797 return ME->getMemberDecl(); 798 799 return 0; 800} 801 802FunctionDecl *CallExpr::getDirectCallee() { 803 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl()); 804} 805 806/// setNumArgs - This changes the number of arguments present in this call. 807/// Any orphaned expressions are deleted by this, and any new operands are set 808/// to null. 809void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) { 810 // No change, just return. 811 if (NumArgs == getNumArgs()) return; 812 813 // If shrinking # arguments, just delete the extras and forgot them. 814 if (NumArgs < getNumArgs()) { 815 this->NumArgs = NumArgs; 816 return; 817 } 818 819 // Otherwise, we are growing the # arguments. New an bigger argument array. 820 unsigned NumPreArgs = getNumPreArgs(); 821 Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs]; 822 // Copy over args. 823 for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i) 824 NewSubExprs[i] = SubExprs[i]; 825 // Null out new args. 826 for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs; 827 i != NumArgs+PREARGS_START+NumPreArgs; ++i) 828 NewSubExprs[i] = 0; 829 830 if (SubExprs) C.Deallocate(SubExprs); 831 SubExprs = NewSubExprs; 832 this->NumArgs = NumArgs; 833} 834 835/// isBuiltinCall - If this is a call to a builtin, return the builtin ID. If 836/// not, return 0. 837unsigned CallExpr::isBuiltinCall() const { 838 // All simple function calls (e.g. func()) are implicitly cast to pointer to 839 // function. As a result, we try and obtain the DeclRefExpr from the 840 // ImplicitCastExpr. 841 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee()); 842 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()). 843 return 0; 844 845 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()); 846 if (!DRE) 847 return 0; 848 849 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl()); 850 if (!FDecl) 851 return 0; 852 853 if (!FDecl->getIdentifier()) 854 return 0; 855 856 return FDecl->getBuiltinID(); 857} 858 859QualType CallExpr::getCallReturnType() const { 860 QualType CalleeType = getCallee()->getType(); 861 if (const PointerType *FnTypePtr = CalleeType->getAs<PointerType>()) 862 CalleeType = FnTypePtr->getPointeeType(); 863 else if (const BlockPointerType *BPT = CalleeType->getAs<BlockPointerType>()) 864 CalleeType = BPT->getPointeeType(); 865 else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) 866 // This should never be overloaded and so should never return null. 867 CalleeType = Expr::findBoundMemberType(getCallee()); 868 869 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 870 return FnType->getResultType(); 871} 872 873SourceRange CallExpr::getSourceRange() const { 874 if (isa<CXXOperatorCallExpr>(this)) 875 return cast<CXXOperatorCallExpr>(this)->getSourceRange(); 876 877 SourceLocation begin = getCallee()->getLocStart(); 878 if (begin.isInvalid() && getNumArgs() > 0) 879 begin = getArg(0)->getLocStart(); 880 SourceLocation end = getRParenLoc(); 881 if (end.isInvalid() && getNumArgs() > 0) 882 end = getArg(getNumArgs() - 1)->getLocEnd(); 883 return SourceRange(begin, end); 884} 885 886OffsetOfExpr *OffsetOfExpr::Create(ASTContext &C, QualType type, 887 SourceLocation OperatorLoc, 888 TypeSourceInfo *tsi, 889 OffsetOfNode* compsPtr, unsigned numComps, 890 Expr** exprsPtr, unsigned numExprs, 891 SourceLocation RParenLoc) { 892 void *Mem = C.Allocate(sizeof(OffsetOfExpr) + 893 sizeof(OffsetOfNode) * numComps + 894 sizeof(Expr*) * numExprs); 895 896 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, compsPtr, numComps, 897 exprsPtr, numExprs, RParenLoc); 898} 899 900OffsetOfExpr *OffsetOfExpr::CreateEmpty(ASTContext &C, 901 unsigned numComps, unsigned numExprs) { 902 void *Mem = C.Allocate(sizeof(OffsetOfExpr) + 903 sizeof(OffsetOfNode) * numComps + 904 sizeof(Expr*) * numExprs); 905 return new (Mem) OffsetOfExpr(numComps, numExprs); 906} 907 908OffsetOfExpr::OffsetOfExpr(ASTContext &C, QualType type, 909 SourceLocation OperatorLoc, TypeSourceInfo *tsi, 910 OffsetOfNode* compsPtr, unsigned numComps, 911 Expr** exprsPtr, unsigned numExprs, 912 SourceLocation RParenLoc) 913 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary, 914 /*TypeDependent=*/false, 915 /*ValueDependent=*/tsi->getType()->isDependentType(), 916 tsi->getType()->isInstantiationDependentType(), 917 tsi->getType()->containsUnexpandedParameterPack()), 918 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi), 919 NumComps(numComps), NumExprs(numExprs) 920{ 921 for(unsigned i = 0; i < numComps; ++i) { 922 setComponent(i, compsPtr[i]); 923 } 924 925 for(unsigned i = 0; i < numExprs; ++i) { 926 if (exprsPtr[i]->isTypeDependent() || exprsPtr[i]->isValueDependent()) 927 ExprBits.ValueDependent = true; 928 if (exprsPtr[i]->containsUnexpandedParameterPack()) 929 ExprBits.ContainsUnexpandedParameterPack = true; 930 931 setIndexExpr(i, exprsPtr[i]); 932 } 933} 934 935IdentifierInfo *OffsetOfExpr::OffsetOfNode::getFieldName() const { 936 assert(getKind() == Field || getKind() == Identifier); 937 if (getKind() == Field) 938 return getField()->getIdentifier(); 939 940 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask); 941} 942 943MemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow, 944 NestedNameSpecifierLoc QualifierLoc, 945 ValueDecl *memberdecl, 946 DeclAccessPair founddecl, 947 DeclarationNameInfo nameinfo, 948 const TemplateArgumentListInfo *targs, 949 QualType ty, 950 ExprValueKind vk, 951 ExprObjectKind ok) { 952 std::size_t Size = sizeof(MemberExpr); 953 954 bool hasQualOrFound = (QualifierLoc || 955 founddecl.getDecl() != memberdecl || 956 founddecl.getAccess() != memberdecl->getAccess()); 957 if (hasQualOrFound) 958 Size += sizeof(MemberNameQualifier); 959 960 if (targs) 961 Size += ASTTemplateArgumentListInfo::sizeFor(*targs); 962 963 void *Mem = C.Allocate(Size, llvm::alignOf<MemberExpr>()); 964 MemberExpr *E = new (Mem) MemberExpr(base, isarrow, memberdecl, nameinfo, 965 ty, vk, ok); 966 967 if (hasQualOrFound) { 968 // FIXME: Wrong. We should be looking at the member declaration we found. 969 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) { 970 E->setValueDependent(true); 971 E->setTypeDependent(true); 972 E->setInstantiationDependent(true); 973 } 974 else if (QualifierLoc && 975 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent()) 976 E->setInstantiationDependent(true); 977 978 E->HasQualifierOrFoundDecl = true; 979 980 MemberNameQualifier *NQ = E->getMemberQualifier(); 981 NQ->QualifierLoc = QualifierLoc; 982 NQ->FoundDecl = founddecl; 983 } 984 985 if (targs) { 986 bool Dependent = false; 987 bool InstantiationDependent = false; 988 bool ContainsUnexpandedParameterPack = false; 989 E->HasExplicitTemplateArgumentList = true; 990 E->getExplicitTemplateArgs().initializeFrom(*targs, Dependent, 991 InstantiationDependent, 992 ContainsUnexpandedParameterPack); 993 if (InstantiationDependent) 994 E->setInstantiationDependent(true); 995 } 996 997 return E; 998} 999 1000SourceRange MemberExpr::getSourceRange() const { 1001 SourceLocation StartLoc; 1002 if (isImplicitAccess()) { 1003 if (hasQualifier()) 1004 StartLoc = getQualifierLoc().getBeginLoc(); 1005 else 1006 StartLoc = MemberLoc; 1007 } else { 1008 // FIXME: We don't want this to happen. Rather, we should be able to 1009 // detect all kinds of implicit accesses more cleanly. 1010 StartLoc = getBase()->getLocStart(); 1011 if (StartLoc.isInvalid()) 1012 StartLoc = MemberLoc; 1013 } 1014 1015 SourceLocation EndLoc = 1016 HasExplicitTemplateArgumentList? getRAngleLoc() 1017 : getMemberNameInfo().getEndLoc(); 1018 1019 return SourceRange(StartLoc, EndLoc); 1020} 1021 1022void CastExpr::CheckCastConsistency() const { 1023 switch (getCastKind()) { 1024 case CK_DerivedToBase: 1025 case CK_UncheckedDerivedToBase: 1026 case CK_DerivedToBaseMemberPointer: 1027 case CK_BaseToDerived: 1028 case CK_BaseToDerivedMemberPointer: 1029 assert(!path_empty() && "Cast kind should have a base path!"); 1030 break; 1031 1032 case CK_CPointerToObjCPointerCast: 1033 assert(getType()->isObjCObjectPointerType()); 1034 assert(getSubExpr()->getType()->isPointerType()); 1035 goto CheckNoBasePath; 1036 1037 case CK_BlockPointerToObjCPointerCast: 1038 assert(getType()->isObjCObjectPointerType()); 1039 assert(getSubExpr()->getType()->isBlockPointerType()); 1040 goto CheckNoBasePath; 1041 1042 case CK_BitCast: 1043 // Arbitrary casts to C pointer types count as bitcasts. 1044 // Otherwise, we should only have block and ObjC pointer casts 1045 // here if they stay within the type kind. 1046 if (!getType()->isPointerType()) { 1047 assert(getType()->isObjCObjectPointerType() == 1048 getSubExpr()->getType()->isObjCObjectPointerType()); 1049 assert(getType()->isBlockPointerType() == 1050 getSubExpr()->getType()->isBlockPointerType()); 1051 } 1052 goto CheckNoBasePath; 1053 1054 case CK_AnyPointerToBlockPointerCast: 1055 assert(getType()->isBlockPointerType()); 1056 assert(getSubExpr()->getType()->isAnyPointerType() && 1057 !getSubExpr()->getType()->isBlockPointerType()); 1058 goto CheckNoBasePath; 1059 1060 // These should not have an inheritance path. 1061 case CK_Dynamic: 1062 case CK_ToUnion: 1063 case CK_ArrayToPointerDecay: 1064 case CK_FunctionToPointerDecay: 1065 case CK_NullToMemberPointer: 1066 case CK_NullToPointer: 1067 case CK_ConstructorConversion: 1068 case CK_IntegralToPointer: 1069 case CK_PointerToIntegral: 1070 case CK_ToVoid: 1071 case CK_VectorSplat: 1072 case CK_IntegralCast: 1073 case CK_IntegralToFloating: 1074 case CK_FloatingToIntegral: 1075 case CK_FloatingCast: 1076 case CK_ObjCObjectLValueCast: 1077 case CK_FloatingRealToComplex: 1078 case CK_FloatingComplexToReal: 1079 case CK_FloatingComplexCast: 1080 case CK_FloatingComplexToIntegralComplex: 1081 case CK_IntegralRealToComplex: 1082 case CK_IntegralComplexToReal: 1083 case CK_IntegralComplexCast: 1084 case CK_IntegralComplexToFloatingComplex: 1085 case CK_ARCProduceObject: 1086 case CK_ARCConsumeObject: 1087 case CK_ARCReclaimReturnedObject: 1088 case CK_ARCExtendBlockObject: 1089 assert(!getType()->isBooleanType() && "unheralded conversion to bool"); 1090 goto CheckNoBasePath; 1091 1092 case CK_Dependent: 1093 case CK_LValueToRValue: 1094 case CK_NoOp: 1095 case CK_AtomicToNonAtomic: 1096 case CK_NonAtomicToAtomic: 1097 case CK_PointerToBoolean: 1098 case CK_IntegralToBoolean: 1099 case CK_FloatingToBoolean: 1100 case CK_MemberPointerToBoolean: 1101 case CK_FloatingComplexToBoolean: 1102 case CK_IntegralComplexToBoolean: 1103 case CK_LValueBitCast: // -> bool& 1104 case CK_UserDefinedConversion: // operator bool() 1105 CheckNoBasePath: 1106 assert(path_empty() && "Cast kind should not have a base path!"); 1107 break; 1108 } 1109} 1110 1111const char *CastExpr::getCastKindName() const { 1112 switch (getCastKind()) { 1113 case CK_Dependent: 1114 return "Dependent"; 1115 case CK_BitCast: 1116 return "BitCast"; 1117 case CK_LValueBitCast: 1118 return "LValueBitCast"; 1119 case CK_LValueToRValue: 1120 return "LValueToRValue"; 1121 case CK_NoOp: 1122 return "NoOp"; 1123 case CK_BaseToDerived: 1124 return "BaseToDerived"; 1125 case CK_DerivedToBase: 1126 return "DerivedToBase"; 1127 case CK_UncheckedDerivedToBase: 1128 return "UncheckedDerivedToBase"; 1129 case CK_Dynamic: 1130 return "Dynamic"; 1131 case CK_ToUnion: 1132 return "ToUnion"; 1133 case CK_ArrayToPointerDecay: 1134 return "ArrayToPointerDecay"; 1135 case CK_FunctionToPointerDecay: 1136 return "FunctionToPointerDecay"; 1137 case CK_NullToMemberPointer: 1138 return "NullToMemberPointer"; 1139 case CK_NullToPointer: 1140 return "NullToPointer"; 1141 case CK_BaseToDerivedMemberPointer: 1142 return "BaseToDerivedMemberPointer"; 1143 case CK_DerivedToBaseMemberPointer: 1144 return "DerivedToBaseMemberPointer"; 1145 case CK_UserDefinedConversion: 1146 return "UserDefinedConversion"; 1147 case CK_ConstructorConversion: 1148 return "ConstructorConversion"; 1149 case CK_IntegralToPointer: 1150 return "IntegralToPointer"; 1151 case CK_PointerToIntegral: 1152 return "PointerToIntegral"; 1153 case CK_PointerToBoolean: 1154 return "PointerToBoolean"; 1155 case CK_ToVoid: 1156 return "ToVoid"; 1157 case CK_VectorSplat: 1158 return "VectorSplat"; 1159 case CK_IntegralCast: 1160 return "IntegralCast"; 1161 case CK_IntegralToBoolean: 1162 return "IntegralToBoolean"; 1163 case CK_IntegralToFloating: 1164 return "IntegralToFloating"; 1165 case CK_FloatingToIntegral: 1166 return "FloatingToIntegral"; 1167 case CK_FloatingCast: 1168 return "FloatingCast"; 1169 case CK_FloatingToBoolean: 1170 return "FloatingToBoolean"; 1171 case CK_MemberPointerToBoolean: 1172 return "MemberPointerToBoolean"; 1173 case CK_CPointerToObjCPointerCast: 1174 return "CPointerToObjCPointerCast"; 1175 case CK_BlockPointerToObjCPointerCast: 1176 return "BlockPointerToObjCPointerCast"; 1177 case CK_AnyPointerToBlockPointerCast: 1178 return "AnyPointerToBlockPointerCast"; 1179 case CK_ObjCObjectLValueCast: 1180 return "ObjCObjectLValueCast"; 1181 case CK_FloatingRealToComplex: 1182 return "FloatingRealToComplex"; 1183 case CK_FloatingComplexToReal: 1184 return "FloatingComplexToReal"; 1185 case CK_FloatingComplexToBoolean: 1186 return "FloatingComplexToBoolean"; 1187 case CK_FloatingComplexCast: 1188 return "FloatingComplexCast"; 1189 case CK_FloatingComplexToIntegralComplex: 1190 return "FloatingComplexToIntegralComplex"; 1191 case CK_IntegralRealToComplex: 1192 return "IntegralRealToComplex"; 1193 case CK_IntegralComplexToReal: 1194 return "IntegralComplexToReal"; 1195 case CK_IntegralComplexToBoolean: 1196 return "IntegralComplexToBoolean"; 1197 case CK_IntegralComplexCast: 1198 return "IntegralComplexCast"; 1199 case CK_IntegralComplexToFloatingComplex: 1200 return "IntegralComplexToFloatingComplex"; 1201 case CK_ARCConsumeObject: 1202 return "ARCConsumeObject"; 1203 case CK_ARCProduceObject: 1204 return "ARCProduceObject"; 1205 case CK_ARCReclaimReturnedObject: 1206 return "ARCReclaimReturnedObject"; 1207 case CK_ARCExtendBlockObject: 1208 return "ARCCExtendBlockObject"; 1209 case CK_AtomicToNonAtomic: 1210 return "AtomicToNonAtomic"; 1211 case CK_NonAtomicToAtomic: 1212 return "NonAtomicToAtomic"; 1213 } 1214 1215 llvm_unreachable("Unhandled cast kind!"); 1216 return 0; 1217} 1218 1219Expr *CastExpr::getSubExprAsWritten() { 1220 Expr *SubExpr = 0; 1221 CastExpr *E = this; 1222 do { 1223 SubExpr = E->getSubExpr(); 1224 1225 // Skip through reference binding to temporary. 1226 if (MaterializeTemporaryExpr *Materialize 1227 = dyn_cast<MaterializeTemporaryExpr>(SubExpr)) 1228 SubExpr = Materialize->GetTemporaryExpr(); 1229 1230 // Skip any temporary bindings; they're implicit. 1231 if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr)) 1232 SubExpr = Binder->getSubExpr(); 1233 1234 // Conversions by constructor and conversion functions have a 1235 // subexpression describing the call; strip it off. 1236 if (E->getCastKind() == CK_ConstructorConversion) 1237 SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0); 1238 else if (E->getCastKind() == CK_UserDefinedConversion) 1239 SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument(); 1240 1241 // If the subexpression we're left with is an implicit cast, look 1242 // through that, too. 1243 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr))); 1244 1245 return SubExpr; 1246} 1247 1248CXXBaseSpecifier **CastExpr::path_buffer() { 1249 switch (getStmtClass()) { 1250#define ABSTRACT_STMT(x) 1251#define CASTEXPR(Type, Base) \ 1252 case Stmt::Type##Class: \ 1253 return reinterpret_cast<CXXBaseSpecifier**>(static_cast<Type*>(this)+1); 1254#define STMT(Type, Base) 1255#include "clang/AST/StmtNodes.inc" 1256 default: 1257 llvm_unreachable("non-cast expressions not possible here"); 1258 return 0; 1259 } 1260} 1261 1262void CastExpr::setCastPath(const CXXCastPath &Path) { 1263 assert(Path.size() == path_size()); 1264 memcpy(path_buffer(), Path.data(), Path.size() * sizeof(CXXBaseSpecifier*)); 1265} 1266 1267ImplicitCastExpr *ImplicitCastExpr::Create(ASTContext &C, QualType T, 1268 CastKind Kind, Expr *Operand, 1269 const CXXCastPath *BasePath, 1270 ExprValueKind VK) { 1271 unsigned PathSize = (BasePath ? BasePath->size() : 0); 1272 void *Buffer = 1273 C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*)); 1274 ImplicitCastExpr *E = 1275 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK); 1276 if (PathSize) E->setCastPath(*BasePath); 1277 return E; 1278} 1279 1280ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(ASTContext &C, 1281 unsigned PathSize) { 1282 void *Buffer = 1283 C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*)); 1284 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize); 1285} 1286 1287 1288CStyleCastExpr *CStyleCastExpr::Create(ASTContext &C, QualType T, 1289 ExprValueKind VK, CastKind K, Expr *Op, 1290 const CXXCastPath *BasePath, 1291 TypeSourceInfo *WrittenTy, 1292 SourceLocation L, SourceLocation R) { 1293 unsigned PathSize = (BasePath ? BasePath->size() : 0); 1294 void *Buffer = 1295 C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*)); 1296 CStyleCastExpr *E = 1297 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R); 1298 if (PathSize) E->setCastPath(*BasePath); 1299 return E; 1300} 1301 1302CStyleCastExpr *CStyleCastExpr::CreateEmpty(ASTContext &C, unsigned PathSize) { 1303 void *Buffer = 1304 C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*)); 1305 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize); 1306} 1307 1308/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 1309/// corresponds to, e.g. "<<=". 1310const char *BinaryOperator::getOpcodeStr(Opcode Op) { 1311 switch (Op) { 1312 case BO_PtrMemD: return ".*"; 1313 case BO_PtrMemI: return "->*"; 1314 case BO_Mul: return "*"; 1315 case BO_Div: return "/"; 1316 case BO_Rem: return "%"; 1317 case BO_Add: return "+"; 1318 case BO_Sub: return "-"; 1319 case BO_Shl: return "<<"; 1320 case BO_Shr: return ">>"; 1321 case BO_LT: return "<"; 1322 case BO_GT: return ">"; 1323 case BO_LE: return "<="; 1324 case BO_GE: return ">="; 1325 case BO_EQ: return "=="; 1326 case BO_NE: return "!="; 1327 case BO_And: return "&"; 1328 case BO_Xor: return "^"; 1329 case BO_Or: return "|"; 1330 case BO_LAnd: return "&&"; 1331 case BO_LOr: return "||"; 1332 case BO_Assign: return "="; 1333 case BO_MulAssign: return "*="; 1334 case BO_DivAssign: return "/="; 1335 case BO_RemAssign: return "%="; 1336 case BO_AddAssign: return "+="; 1337 case BO_SubAssign: return "-="; 1338 case BO_ShlAssign: return "<<="; 1339 case BO_ShrAssign: return ">>="; 1340 case BO_AndAssign: return "&="; 1341 case BO_XorAssign: return "^="; 1342 case BO_OrAssign: return "|="; 1343 case BO_Comma: return ","; 1344 } 1345 1346 return ""; 1347} 1348 1349BinaryOperatorKind 1350BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) { 1351 switch (OO) { 1352 default: llvm_unreachable("Not an overloadable binary operator"); 1353 case OO_Plus: return BO_Add; 1354 case OO_Minus: return BO_Sub; 1355 case OO_Star: return BO_Mul; 1356 case OO_Slash: return BO_Div; 1357 case OO_Percent: return BO_Rem; 1358 case OO_Caret: return BO_Xor; 1359 case OO_Amp: return BO_And; 1360 case OO_Pipe: return BO_Or; 1361 case OO_Equal: return BO_Assign; 1362 case OO_Less: return BO_LT; 1363 case OO_Greater: return BO_GT; 1364 case OO_PlusEqual: return BO_AddAssign; 1365 case OO_MinusEqual: return BO_SubAssign; 1366 case OO_StarEqual: return BO_MulAssign; 1367 case OO_SlashEqual: return BO_DivAssign; 1368 case OO_PercentEqual: return BO_RemAssign; 1369 case OO_CaretEqual: return BO_XorAssign; 1370 case OO_AmpEqual: return BO_AndAssign; 1371 case OO_PipeEqual: return BO_OrAssign; 1372 case OO_LessLess: return BO_Shl; 1373 case OO_GreaterGreater: return BO_Shr; 1374 case OO_LessLessEqual: return BO_ShlAssign; 1375 case OO_GreaterGreaterEqual: return BO_ShrAssign; 1376 case OO_EqualEqual: return BO_EQ; 1377 case OO_ExclaimEqual: return BO_NE; 1378 case OO_LessEqual: return BO_LE; 1379 case OO_GreaterEqual: return BO_GE; 1380 case OO_AmpAmp: return BO_LAnd; 1381 case OO_PipePipe: return BO_LOr; 1382 case OO_Comma: return BO_Comma; 1383 case OO_ArrowStar: return BO_PtrMemI; 1384 } 1385} 1386 1387OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) { 1388 static const OverloadedOperatorKind OverOps[] = { 1389 /* .* Cannot be overloaded */OO_None, OO_ArrowStar, 1390 OO_Star, OO_Slash, OO_Percent, 1391 OO_Plus, OO_Minus, 1392 OO_LessLess, OO_GreaterGreater, 1393 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual, 1394 OO_EqualEqual, OO_ExclaimEqual, 1395 OO_Amp, 1396 OO_Caret, 1397 OO_Pipe, 1398 OO_AmpAmp, 1399 OO_PipePipe, 1400 OO_Equal, OO_StarEqual, 1401 OO_SlashEqual, OO_PercentEqual, 1402 OO_PlusEqual, OO_MinusEqual, 1403 OO_LessLessEqual, OO_GreaterGreaterEqual, 1404 OO_AmpEqual, OO_CaretEqual, 1405 OO_PipeEqual, 1406 OO_Comma 1407 }; 1408 return OverOps[Opc]; 1409} 1410 1411InitListExpr::InitListExpr(ASTContext &C, SourceLocation lbraceloc, 1412 Expr **initExprs, unsigned numInits, 1413 SourceLocation rbraceloc) 1414 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false, 1415 false, false), 1416 InitExprs(C, numInits), 1417 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0), 1418 HadArrayRangeDesignator(false) 1419{ 1420 for (unsigned I = 0; I != numInits; ++I) { 1421 if (initExprs[I]->isTypeDependent()) 1422 ExprBits.TypeDependent = true; 1423 if (initExprs[I]->isValueDependent()) 1424 ExprBits.ValueDependent = true; 1425 if (initExprs[I]->isInstantiationDependent()) 1426 ExprBits.InstantiationDependent = true; 1427 if (initExprs[I]->containsUnexpandedParameterPack()) 1428 ExprBits.ContainsUnexpandedParameterPack = true; 1429 } 1430 1431 InitExprs.insert(C, InitExprs.end(), initExprs, initExprs+numInits); 1432} 1433 1434void InitListExpr::reserveInits(ASTContext &C, unsigned NumInits) { 1435 if (NumInits > InitExprs.size()) 1436 InitExprs.reserve(C, NumInits); 1437} 1438 1439void InitListExpr::resizeInits(ASTContext &C, unsigned NumInits) { 1440 InitExprs.resize(C, NumInits, 0); 1441} 1442 1443Expr *InitListExpr::updateInit(ASTContext &C, unsigned Init, Expr *expr) { 1444 if (Init >= InitExprs.size()) { 1445 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, 0); 1446 InitExprs.back() = expr; 1447 return 0; 1448 } 1449 1450 Expr *Result = cast_or_null<Expr>(InitExprs[Init]); 1451 InitExprs[Init] = expr; 1452 return Result; 1453} 1454 1455void InitListExpr::setArrayFiller(Expr *filler) { 1456 assert(!hasArrayFiller() && "Filler already set!"); 1457 ArrayFillerOrUnionFieldInit = filler; 1458 // Fill out any "holes" in the array due to designated initializers. 1459 Expr **inits = getInits(); 1460 for (unsigned i = 0, e = getNumInits(); i != e; ++i) 1461 if (inits[i] == 0) 1462 inits[i] = filler; 1463} 1464 1465SourceRange InitListExpr::getSourceRange() const { 1466 if (SyntacticForm) 1467 return SyntacticForm->getSourceRange(); 1468 SourceLocation Beg = LBraceLoc, End = RBraceLoc; 1469 if (Beg.isInvalid()) { 1470 // Find the first non-null initializer. 1471 for (InitExprsTy::const_iterator I = InitExprs.begin(), 1472 E = InitExprs.end(); 1473 I != E; ++I) { 1474 if (Stmt *S = *I) { 1475 Beg = S->getLocStart(); 1476 break; 1477 } 1478 } 1479 } 1480 if (End.isInvalid()) { 1481 // Find the first non-null initializer from the end. 1482 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(), 1483 E = InitExprs.rend(); 1484 I != E; ++I) { 1485 if (Stmt *S = *I) { 1486 End = S->getSourceRange().getEnd(); 1487 break; 1488 } 1489 } 1490 } 1491 return SourceRange(Beg, End); 1492} 1493 1494/// getFunctionType - Return the underlying function type for this block. 1495/// 1496const FunctionType *BlockExpr::getFunctionType() const { 1497 return getType()->getAs<BlockPointerType>()-> 1498 getPointeeType()->getAs<FunctionType>(); 1499} 1500 1501SourceLocation BlockExpr::getCaretLocation() const { 1502 return TheBlock->getCaretLocation(); 1503} 1504const Stmt *BlockExpr::getBody() const { 1505 return TheBlock->getBody(); 1506} 1507Stmt *BlockExpr::getBody() { 1508 return TheBlock->getBody(); 1509} 1510 1511 1512//===----------------------------------------------------------------------===// 1513// Generic Expression Routines 1514//===----------------------------------------------------------------------===// 1515 1516/// isUnusedResultAWarning - Return true if this immediate expression should 1517/// be warned about if the result is unused. If so, fill in Loc and Ranges 1518/// with location to warn on and the source range[s] to report with the 1519/// warning. 1520bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1, 1521 SourceRange &R2, ASTContext &Ctx) const { 1522 // Don't warn if the expr is type dependent. The type could end up 1523 // instantiating to void. 1524 if (isTypeDependent()) 1525 return false; 1526 1527 switch (getStmtClass()) { 1528 default: 1529 if (getType()->isVoidType()) 1530 return false; 1531 Loc = getExprLoc(); 1532 R1 = getSourceRange(); 1533 return true; 1534 case ParenExprClass: 1535 return cast<ParenExpr>(this)->getSubExpr()-> 1536 isUnusedResultAWarning(Loc, R1, R2, Ctx); 1537 case GenericSelectionExprClass: 1538 return cast<GenericSelectionExpr>(this)->getResultExpr()-> 1539 isUnusedResultAWarning(Loc, R1, R2, Ctx); 1540 case UnaryOperatorClass: { 1541 const UnaryOperator *UO = cast<UnaryOperator>(this); 1542 1543 switch (UO->getOpcode()) { 1544 default: break; 1545 case UO_PostInc: 1546 case UO_PostDec: 1547 case UO_PreInc: 1548 case UO_PreDec: // ++/-- 1549 return false; // Not a warning. 1550 case UO_Deref: 1551 // Dereferencing a volatile pointer is a side-effect. 1552 if (Ctx.getCanonicalType(getType()).isVolatileQualified()) 1553 return false; 1554 break; 1555 case UO_Real: 1556 case UO_Imag: 1557 // accessing a piece of a volatile complex is a side-effect. 1558 if (Ctx.getCanonicalType(UO->getSubExpr()->getType()) 1559 .isVolatileQualified()) 1560 return false; 1561 break; 1562 case UO_Extension: 1563 return UO->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx); 1564 } 1565 Loc = UO->getOperatorLoc(); 1566 R1 = UO->getSubExpr()->getSourceRange(); 1567 return true; 1568 } 1569 case BinaryOperatorClass: { 1570 const BinaryOperator *BO = cast<BinaryOperator>(this); 1571 switch (BO->getOpcode()) { 1572 default: 1573 break; 1574 // Consider the RHS of comma for side effects. LHS was checked by 1575 // Sema::CheckCommaOperands. 1576 case BO_Comma: 1577 // ((foo = <blah>), 0) is an idiom for hiding the result (and 1578 // lvalue-ness) of an assignment written in a macro. 1579 if (IntegerLiteral *IE = 1580 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens())) 1581 if (IE->getValue() == 0) 1582 return false; 1583 return BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx); 1584 // Consider '||', '&&' to have side effects if the LHS or RHS does. 1585 case BO_LAnd: 1586 case BO_LOr: 1587 if (!BO->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx) || 1588 !BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx)) 1589 return false; 1590 break; 1591 } 1592 if (BO->isAssignmentOp()) 1593 return false; 1594 Loc = BO->getOperatorLoc(); 1595 R1 = BO->getLHS()->getSourceRange(); 1596 R2 = BO->getRHS()->getSourceRange(); 1597 return true; 1598 } 1599 case CompoundAssignOperatorClass: 1600 case VAArgExprClass: 1601 case AtomicExprClass: 1602 return false; 1603 1604 case ConditionalOperatorClass: { 1605 // If only one of the LHS or RHS is a warning, the operator might 1606 // be being used for control flow. Only warn if both the LHS and 1607 // RHS are warnings. 1608 const ConditionalOperator *Exp = cast<ConditionalOperator>(this); 1609 if (!Exp->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx)) 1610 return false; 1611 if (!Exp->getLHS()) 1612 return true; 1613 return Exp->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx); 1614 } 1615 1616 case MemberExprClass: 1617 // If the base pointer or element is to a volatile pointer/field, accessing 1618 // it is a side effect. 1619 if (Ctx.getCanonicalType(getType()).isVolatileQualified()) 1620 return false; 1621 Loc = cast<MemberExpr>(this)->getMemberLoc(); 1622 R1 = SourceRange(Loc, Loc); 1623 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange(); 1624 return true; 1625 1626 case ArraySubscriptExprClass: 1627 // If the base pointer or element is to a volatile pointer/field, accessing 1628 // it is a side effect. 1629 if (Ctx.getCanonicalType(getType()).isVolatileQualified()) 1630 return false; 1631 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc(); 1632 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange(); 1633 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange(); 1634 return true; 1635 1636 case CXXOperatorCallExprClass: { 1637 // We warn about operator== and operator!= even when user-defined operator 1638 // overloads as there is no reasonable way to define these such that they 1639 // have non-trivial, desirable side-effects. See the -Wunused-comparison 1640 // warning: these operators are commonly typo'ed, and so warning on them 1641 // provides additional value as well. If this list is updated, 1642 // DiagnoseUnusedComparison should be as well. 1643 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this); 1644 if (Op->getOperator() == OO_EqualEqual || 1645 Op->getOperator() == OO_ExclaimEqual) { 1646 Loc = Op->getOperatorLoc(); 1647 R1 = Op->getSourceRange(); 1648 return true; 1649 } 1650 1651 // Fallthrough for generic call handling. 1652 } 1653 case CallExprClass: 1654 case CXXMemberCallExprClass: { 1655 // If this is a direct call, get the callee. 1656 const CallExpr *CE = cast<CallExpr>(this); 1657 if (const Decl *FD = CE->getCalleeDecl()) { 1658 // If the callee has attribute pure, const, or warn_unused_result, warn 1659 // about it. void foo() { strlen("bar"); } should warn. 1660 // 1661 // Note: If new cases are added here, DiagnoseUnusedExprResult should be 1662 // updated to match for QoI. 1663 if (FD->getAttr<WarnUnusedResultAttr>() || 1664 FD->getAttr<PureAttr>() || FD->getAttr<ConstAttr>()) { 1665 Loc = CE->getCallee()->getLocStart(); 1666 R1 = CE->getCallee()->getSourceRange(); 1667 1668 if (unsigned NumArgs = CE->getNumArgs()) 1669 R2 = SourceRange(CE->getArg(0)->getLocStart(), 1670 CE->getArg(NumArgs-1)->getLocEnd()); 1671 return true; 1672 } 1673 } 1674 return false; 1675 } 1676 1677 case CXXTemporaryObjectExprClass: 1678 case CXXConstructExprClass: 1679 return false; 1680 1681 case ObjCMessageExprClass: { 1682 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this); 1683 if (Ctx.getLangOptions().ObjCAutoRefCount && 1684 ME->isInstanceMessage() && 1685 !ME->getType()->isVoidType() && 1686 ME->getSelector().getIdentifierInfoForSlot(0) && 1687 ME->getSelector().getIdentifierInfoForSlot(0) 1688 ->getName().startswith("init")) { 1689 Loc = getExprLoc(); 1690 R1 = ME->getSourceRange(); 1691 return true; 1692 } 1693 1694 const ObjCMethodDecl *MD = ME->getMethodDecl(); 1695 if (MD && MD->getAttr<WarnUnusedResultAttr>()) { 1696 Loc = getExprLoc(); 1697 return true; 1698 } 1699 return false; 1700 } 1701 1702 case ObjCPropertyRefExprClass: 1703 Loc = getExprLoc(); 1704 R1 = getSourceRange(); 1705 return true; 1706 1707 case PseudoObjectExprClass: { 1708 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this); 1709 1710 // Only complain about things that have the form of a getter. 1711 if (isa<UnaryOperator>(PO->getSyntacticForm()) || 1712 isa<BinaryOperator>(PO->getSyntacticForm())) 1713 return false; 1714 1715 Loc = getExprLoc(); 1716 R1 = getSourceRange(); 1717 return true; 1718 } 1719 1720 case StmtExprClass: { 1721 // Statement exprs don't logically have side effects themselves, but are 1722 // sometimes used in macros in ways that give them a type that is unused. 1723 // For example ({ blah; foo(); }) will end up with a type if foo has a type. 1724 // however, if the result of the stmt expr is dead, we don't want to emit a 1725 // warning. 1726 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt(); 1727 if (!CS->body_empty()) { 1728 if (const Expr *E = dyn_cast<Expr>(CS->body_back())) 1729 return E->isUnusedResultAWarning(Loc, R1, R2, Ctx); 1730 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back())) 1731 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt())) 1732 return E->isUnusedResultAWarning(Loc, R1, R2, Ctx); 1733 } 1734 1735 if (getType()->isVoidType()) 1736 return false; 1737 Loc = cast<StmtExpr>(this)->getLParenLoc(); 1738 R1 = getSourceRange(); 1739 return true; 1740 } 1741 case CStyleCastExprClass: 1742 // If this is an explicit cast to void, allow it. People do this when they 1743 // think they know what they're doing :). 1744 if (getType()->isVoidType()) 1745 return false; 1746 Loc = cast<CStyleCastExpr>(this)->getLParenLoc(); 1747 R1 = cast<CStyleCastExpr>(this)->getSubExpr()->getSourceRange(); 1748 return true; 1749 case CXXFunctionalCastExprClass: { 1750 if (getType()->isVoidType()) 1751 return false; 1752 const CastExpr *CE = cast<CastExpr>(this); 1753 1754 // If this is a cast to void or a constructor conversion, check the operand. 1755 // Otherwise, the result of the cast is unused. 1756 if (CE->getCastKind() == CK_ToVoid || 1757 CE->getCastKind() == CK_ConstructorConversion) 1758 return (cast<CastExpr>(this)->getSubExpr() 1759 ->isUnusedResultAWarning(Loc, R1, R2, Ctx)); 1760 Loc = cast<CXXFunctionalCastExpr>(this)->getTypeBeginLoc(); 1761 R1 = cast<CXXFunctionalCastExpr>(this)->getSubExpr()->getSourceRange(); 1762 return true; 1763 } 1764 1765 case ImplicitCastExprClass: 1766 // Check the operand, since implicit casts are inserted by Sema 1767 return (cast<ImplicitCastExpr>(this) 1768 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx)); 1769 1770 case CXXDefaultArgExprClass: 1771 return (cast<CXXDefaultArgExpr>(this) 1772 ->getExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx)); 1773 1774 case CXXNewExprClass: 1775 // FIXME: In theory, there might be new expressions that don't have side 1776 // effects (e.g. a placement new with an uninitialized POD). 1777 case CXXDeleteExprClass: 1778 return false; 1779 case CXXBindTemporaryExprClass: 1780 return (cast<CXXBindTemporaryExpr>(this) 1781 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx)); 1782 case ExprWithCleanupsClass: 1783 return (cast<ExprWithCleanups>(this) 1784 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx)); 1785 } 1786} 1787 1788/// isOBJCGCCandidate - Check if an expression is objc gc'able. 1789/// returns true, if it is; false otherwise. 1790bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const { 1791 const Expr *E = IgnoreParens(); 1792 switch (E->getStmtClass()) { 1793 default: 1794 return false; 1795 case ObjCIvarRefExprClass: 1796 return true; 1797 case Expr::UnaryOperatorClass: 1798 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx); 1799 case ImplicitCastExprClass: 1800 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx); 1801 case MaterializeTemporaryExprClass: 1802 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr() 1803 ->isOBJCGCCandidate(Ctx); 1804 case CStyleCastExprClass: 1805 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx); 1806 case BlockDeclRefExprClass: 1807 case DeclRefExprClass: { 1808 1809 const Decl *D; 1810 if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) 1811 D = BDRE->getDecl(); 1812 else 1813 D = cast<DeclRefExpr>(E)->getDecl(); 1814 1815 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1816 if (VD->hasGlobalStorage()) 1817 return true; 1818 QualType T = VD->getType(); 1819 // dereferencing to a pointer is always a gc'able candidate, 1820 // unless it is __weak. 1821 return T->isPointerType() && 1822 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak); 1823 } 1824 return false; 1825 } 1826 case MemberExprClass: { 1827 const MemberExpr *M = cast<MemberExpr>(E); 1828 return M->getBase()->isOBJCGCCandidate(Ctx); 1829 } 1830 case ArraySubscriptExprClass: 1831 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx); 1832 } 1833} 1834 1835bool Expr::isBoundMemberFunction(ASTContext &Ctx) const { 1836 if (isTypeDependent()) 1837 return false; 1838 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction; 1839} 1840 1841QualType Expr::findBoundMemberType(const Expr *expr) { 1842 assert(expr->hasPlaceholderType(BuiltinType::BoundMember)); 1843 1844 // Bound member expressions are always one of these possibilities: 1845 // x->m x.m x->*y x.*y 1846 // (possibly parenthesized) 1847 1848 expr = expr->IgnoreParens(); 1849 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) { 1850 assert(isa<CXXMethodDecl>(mem->getMemberDecl())); 1851 return mem->getMemberDecl()->getType(); 1852 } 1853 1854 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) { 1855 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>() 1856 ->getPointeeType(); 1857 assert(type->isFunctionType()); 1858 return type; 1859 } 1860 1861 assert(isa<UnresolvedMemberExpr>(expr)); 1862 return QualType(); 1863} 1864 1865static Expr::CanThrowResult MergeCanThrow(Expr::CanThrowResult CT1, 1866 Expr::CanThrowResult CT2) { 1867 // CanThrowResult constants are ordered so that the maximum is the correct 1868 // merge result. 1869 return CT1 > CT2 ? CT1 : CT2; 1870} 1871 1872static Expr::CanThrowResult CanSubExprsThrow(ASTContext &C, const Expr *CE) { 1873 Expr *E = const_cast<Expr*>(CE); 1874 Expr::CanThrowResult R = Expr::CT_Cannot; 1875 for (Expr::child_range I = E->children(); I && R != Expr::CT_Can; ++I) { 1876 R = MergeCanThrow(R, cast<Expr>(*I)->CanThrow(C)); 1877 } 1878 return R; 1879} 1880 1881static Expr::CanThrowResult CanCalleeThrow(ASTContext &Ctx, const Expr *E, 1882 const Decl *D, 1883 bool NullThrows = true) { 1884 if (!D) 1885 return NullThrows ? Expr::CT_Can : Expr::CT_Cannot; 1886 1887 // See if we can get a function type from the decl somehow. 1888 const ValueDecl *VD = dyn_cast<ValueDecl>(D); 1889 if (!VD) // If we have no clue what we're calling, assume the worst. 1890 return Expr::CT_Can; 1891 1892 // As an extension, we assume that __attribute__((nothrow)) functions don't 1893 // throw. 1894 if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>()) 1895 return Expr::CT_Cannot; 1896 1897 QualType T = VD->getType(); 1898 const FunctionProtoType *FT; 1899 if ((FT = T->getAs<FunctionProtoType>())) { 1900 } else if (const PointerType *PT = T->getAs<PointerType>()) 1901 FT = PT->getPointeeType()->getAs<FunctionProtoType>(); 1902 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 1903 FT = RT->getPointeeType()->getAs<FunctionProtoType>(); 1904 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>()) 1905 FT = MT->getPointeeType()->getAs<FunctionProtoType>(); 1906 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) 1907 FT = BT->getPointeeType()->getAs<FunctionProtoType>(); 1908 1909 if (!FT) 1910 return Expr::CT_Can; 1911 1912 if (FT->getExceptionSpecType() == EST_Delayed) { 1913 assert(isa<CXXConstructorDecl>(D) && 1914 "only constructor exception specs can be unknown"); 1915 Ctx.getDiagnostics().Report(E->getLocStart(), 1916 diag::err_exception_spec_unknown) 1917 << E->getSourceRange(); 1918 return Expr::CT_Can; 1919 } 1920 1921 return FT->isNothrow(Ctx) ? Expr::CT_Cannot : Expr::CT_Can; 1922} 1923 1924static Expr::CanThrowResult CanDynamicCastThrow(const CXXDynamicCastExpr *DC) { 1925 if (DC->isTypeDependent()) 1926 return Expr::CT_Dependent; 1927 1928 if (!DC->getTypeAsWritten()->isReferenceType()) 1929 return Expr::CT_Cannot; 1930 1931 if (DC->getSubExpr()->isTypeDependent()) 1932 return Expr::CT_Dependent; 1933 1934 return DC->getCastKind() == clang::CK_Dynamic? Expr::CT_Can : Expr::CT_Cannot; 1935} 1936 1937static Expr::CanThrowResult CanTypeidThrow(ASTContext &C, 1938 const CXXTypeidExpr *DC) { 1939 if (DC->isTypeOperand()) 1940 return Expr::CT_Cannot; 1941 1942 Expr *Op = DC->getExprOperand(); 1943 if (Op->isTypeDependent()) 1944 return Expr::CT_Dependent; 1945 1946 const RecordType *RT = Op->getType()->getAs<RecordType>(); 1947 if (!RT) 1948 return Expr::CT_Cannot; 1949 1950 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic()) 1951 return Expr::CT_Cannot; 1952 1953 if (Op->Classify(C).isPRValue()) 1954 return Expr::CT_Cannot; 1955 1956 return Expr::CT_Can; 1957} 1958 1959Expr::CanThrowResult Expr::CanThrow(ASTContext &C) const { 1960 // C++ [expr.unary.noexcept]p3: 1961 // [Can throw] if in a potentially-evaluated context the expression would 1962 // contain: 1963 switch (getStmtClass()) { 1964 case CXXThrowExprClass: 1965 // - a potentially evaluated throw-expression 1966 return CT_Can; 1967 1968 case CXXDynamicCastExprClass: { 1969 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v), 1970 // where T is a reference type, that requires a run-time check 1971 CanThrowResult CT = CanDynamicCastThrow(cast<CXXDynamicCastExpr>(this)); 1972 if (CT == CT_Can) 1973 return CT; 1974 return MergeCanThrow(CT, CanSubExprsThrow(C, this)); 1975 } 1976 1977 case CXXTypeidExprClass: 1978 // - a potentially evaluated typeid expression applied to a glvalue 1979 // expression whose type is a polymorphic class type 1980 return CanTypeidThrow(C, cast<CXXTypeidExpr>(this)); 1981 1982 // - a potentially evaluated call to a function, member function, function 1983 // pointer, or member function pointer that does not have a non-throwing 1984 // exception-specification 1985 case CallExprClass: 1986 case CXXOperatorCallExprClass: 1987 case CXXMemberCallExprClass: { 1988 const CallExpr *CE = cast<CallExpr>(this); 1989 CanThrowResult CT; 1990 if (isTypeDependent()) 1991 CT = CT_Dependent; 1992 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) 1993 CT = CT_Cannot; 1994 else 1995 CT = CanCalleeThrow(C, this, CE->getCalleeDecl()); 1996 if (CT == CT_Can) 1997 return CT; 1998 return MergeCanThrow(CT, CanSubExprsThrow(C, this)); 1999 } 2000 2001 case CXXConstructExprClass: 2002 case CXXTemporaryObjectExprClass: { 2003 CanThrowResult CT = CanCalleeThrow(C, this, 2004 cast<CXXConstructExpr>(this)->getConstructor()); 2005 if (CT == CT_Can) 2006 return CT; 2007 return MergeCanThrow(CT, CanSubExprsThrow(C, this)); 2008 } 2009 2010 case CXXNewExprClass: { 2011 CanThrowResult CT; 2012 if (isTypeDependent()) 2013 CT = CT_Dependent; 2014 else 2015 CT = MergeCanThrow( 2016 CanCalleeThrow(C, this, cast<CXXNewExpr>(this)->getOperatorNew()), 2017 CanCalleeThrow(C, this, cast<CXXNewExpr>(this)->getConstructor(), 2018 /*NullThrows*/false)); 2019 if (CT == CT_Can) 2020 return CT; 2021 return MergeCanThrow(CT, CanSubExprsThrow(C, this)); 2022 } 2023 2024 case CXXDeleteExprClass: { 2025 CanThrowResult CT; 2026 QualType DTy = cast<CXXDeleteExpr>(this)->getDestroyedType(); 2027 if (DTy.isNull() || DTy->isDependentType()) { 2028 CT = CT_Dependent; 2029 } else { 2030 CT = CanCalleeThrow(C, this, 2031 cast<CXXDeleteExpr>(this)->getOperatorDelete()); 2032 if (const RecordType *RT = DTy->getAs<RecordType>()) { 2033 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2034 CT = MergeCanThrow(CT, CanCalleeThrow(C, this, RD->getDestructor())); 2035 } 2036 if (CT == CT_Can) 2037 return CT; 2038 } 2039 return MergeCanThrow(CT, CanSubExprsThrow(C, this)); 2040 } 2041 2042 case CXXBindTemporaryExprClass: { 2043 // The bound temporary has to be destroyed again, which might throw. 2044 CanThrowResult CT = CanCalleeThrow(C, this, 2045 cast<CXXBindTemporaryExpr>(this)->getTemporary()->getDestructor()); 2046 if (CT == CT_Can) 2047 return CT; 2048 return MergeCanThrow(CT, CanSubExprsThrow(C, this)); 2049 } 2050 2051 // ObjC message sends are like function calls, but never have exception 2052 // specs. 2053 case ObjCMessageExprClass: 2054 case ObjCPropertyRefExprClass: 2055 return CT_Can; 2056 2057 // Many other things have subexpressions, so we have to test those. 2058 // Some are simple: 2059 case ParenExprClass: 2060 case MemberExprClass: 2061 case CXXReinterpretCastExprClass: 2062 case CXXConstCastExprClass: 2063 case ConditionalOperatorClass: 2064 case CompoundLiteralExprClass: 2065 case ExtVectorElementExprClass: 2066 case InitListExprClass: 2067 case DesignatedInitExprClass: 2068 case ParenListExprClass: 2069 case VAArgExprClass: 2070 case CXXDefaultArgExprClass: 2071 case ExprWithCleanupsClass: 2072 case ObjCIvarRefExprClass: 2073 case ObjCIsaExprClass: 2074 case ShuffleVectorExprClass: 2075 return CanSubExprsThrow(C, this); 2076 2077 // Some might be dependent for other reasons. 2078 case UnaryOperatorClass: 2079 case ArraySubscriptExprClass: 2080 case ImplicitCastExprClass: 2081 case CStyleCastExprClass: 2082 case CXXStaticCastExprClass: 2083 case CXXFunctionalCastExprClass: 2084 case BinaryOperatorClass: 2085 case CompoundAssignOperatorClass: 2086 case MaterializeTemporaryExprClass: { 2087 CanThrowResult CT = isTypeDependent() ? CT_Dependent : CT_Cannot; 2088 return MergeCanThrow(CT, CanSubExprsThrow(C, this)); 2089 } 2090 2091 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms. 2092 case StmtExprClass: 2093 return CT_Can; 2094 2095 case ChooseExprClass: 2096 if (isTypeDependent() || isValueDependent()) 2097 return CT_Dependent; 2098 return cast<ChooseExpr>(this)->getChosenSubExpr(C)->CanThrow(C); 2099 2100 case GenericSelectionExprClass: 2101 if (cast<GenericSelectionExpr>(this)->isResultDependent()) 2102 return CT_Dependent; 2103 return cast<GenericSelectionExpr>(this)->getResultExpr()->CanThrow(C); 2104 2105 // Some expressions are always dependent. 2106 case DependentScopeDeclRefExprClass: 2107 case CXXUnresolvedConstructExprClass: 2108 case CXXDependentScopeMemberExprClass: 2109 return CT_Dependent; 2110 2111 default: 2112 // All other expressions don't have subexpressions, or else they are 2113 // unevaluated. 2114 return CT_Cannot; 2115 } 2116} 2117 2118Expr* Expr::IgnoreParens() { 2119 Expr* E = this; 2120 while (true) { 2121 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) { 2122 E = P->getSubExpr(); 2123 continue; 2124 } 2125 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) { 2126 if (P->getOpcode() == UO_Extension) { 2127 E = P->getSubExpr(); 2128 continue; 2129 } 2130 } 2131 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) { 2132 if (!P->isResultDependent()) { 2133 E = P->getResultExpr(); 2134 continue; 2135 } 2136 } 2137 return E; 2138 } 2139} 2140 2141/// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr 2142/// or CastExprs or ImplicitCastExprs, returning their operand. 2143Expr *Expr::IgnoreParenCasts() { 2144 Expr *E = this; 2145 while (true) { 2146 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) { 2147 E = P->getSubExpr(); 2148 continue; 2149 } 2150 if (CastExpr *P = dyn_cast<CastExpr>(E)) { 2151 E = P->getSubExpr(); 2152 continue; 2153 } 2154 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) { 2155 if (P->getOpcode() == UO_Extension) { 2156 E = P->getSubExpr(); 2157 continue; 2158 } 2159 } 2160 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) { 2161 if (!P->isResultDependent()) { 2162 E = P->getResultExpr(); 2163 continue; 2164 } 2165 } 2166 if (MaterializeTemporaryExpr *Materialize 2167 = dyn_cast<MaterializeTemporaryExpr>(E)) { 2168 E = Materialize->GetTemporaryExpr(); 2169 continue; 2170 } 2171 if (SubstNonTypeTemplateParmExpr *NTTP 2172 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) { 2173 E = NTTP->getReplacement(); 2174 continue; 2175 } 2176 return E; 2177 } 2178} 2179 2180/// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue 2181/// casts. This is intended purely as a temporary workaround for code 2182/// that hasn't yet been rewritten to do the right thing about those 2183/// casts, and may disappear along with the last internal use. 2184Expr *Expr::IgnoreParenLValueCasts() { 2185 Expr *E = this; 2186 while (true) { 2187 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) { 2188 E = P->getSubExpr(); 2189 continue; 2190 } else if (CastExpr *P = dyn_cast<CastExpr>(E)) { 2191 if (P->getCastKind() == CK_LValueToRValue) { 2192 E = P->getSubExpr(); 2193 continue; 2194 } 2195 } else if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) { 2196 if (P->getOpcode() == UO_Extension) { 2197 E = P->getSubExpr(); 2198 continue; 2199 } 2200 } else if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) { 2201 if (!P->isResultDependent()) { 2202 E = P->getResultExpr(); 2203 continue; 2204 } 2205 } else if (MaterializeTemporaryExpr *Materialize 2206 = dyn_cast<MaterializeTemporaryExpr>(E)) { 2207 E = Materialize->GetTemporaryExpr(); 2208 continue; 2209 } else if (SubstNonTypeTemplateParmExpr *NTTP 2210 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) { 2211 E = NTTP->getReplacement(); 2212 continue; 2213 } 2214 break; 2215 } 2216 return E; 2217} 2218 2219Expr *Expr::IgnoreParenImpCasts() { 2220 Expr *E = this; 2221 while (true) { 2222 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) { 2223 E = P->getSubExpr(); 2224 continue; 2225 } 2226 if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) { 2227 E = P->getSubExpr(); 2228 continue; 2229 } 2230 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) { 2231 if (P->getOpcode() == UO_Extension) { 2232 E = P->getSubExpr(); 2233 continue; 2234 } 2235 } 2236 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) { 2237 if (!P->isResultDependent()) { 2238 E = P->getResultExpr(); 2239 continue; 2240 } 2241 } 2242 if (MaterializeTemporaryExpr *Materialize 2243 = dyn_cast<MaterializeTemporaryExpr>(E)) { 2244 E = Materialize->GetTemporaryExpr(); 2245 continue; 2246 } 2247 if (SubstNonTypeTemplateParmExpr *NTTP 2248 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) { 2249 E = NTTP->getReplacement(); 2250 continue; 2251 } 2252 return E; 2253 } 2254} 2255 2256Expr *Expr::IgnoreConversionOperator() { 2257 if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) { 2258 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl())) 2259 return MCE->getImplicitObjectArgument(); 2260 } 2261 return this; 2262} 2263 2264/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the 2265/// value (including ptr->int casts of the same size). Strip off any 2266/// ParenExpr or CastExprs, returning their operand. 2267Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) { 2268 Expr *E = this; 2269 while (true) { 2270 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) { 2271 E = P->getSubExpr(); 2272 continue; 2273 } 2274 2275 if (CastExpr *P = dyn_cast<CastExpr>(E)) { 2276 // We ignore integer <-> casts that are of the same width, ptr<->ptr and 2277 // ptr<->int casts of the same width. We also ignore all identity casts. 2278 Expr *SE = P->getSubExpr(); 2279 2280 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) { 2281 E = SE; 2282 continue; 2283 } 2284 2285 if ((E->getType()->isPointerType() || 2286 E->getType()->isIntegralType(Ctx)) && 2287 (SE->getType()->isPointerType() || 2288 SE->getType()->isIntegralType(Ctx)) && 2289 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) { 2290 E = SE; 2291 continue; 2292 } 2293 } 2294 2295 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) { 2296 if (P->getOpcode() == UO_Extension) { 2297 E = P->getSubExpr(); 2298 continue; 2299 } 2300 } 2301 2302 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) { 2303 if (!P->isResultDependent()) { 2304 E = P->getResultExpr(); 2305 continue; 2306 } 2307 } 2308 2309 if (SubstNonTypeTemplateParmExpr *NTTP 2310 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) { 2311 E = NTTP->getReplacement(); 2312 continue; 2313 } 2314 2315 return E; 2316 } 2317} 2318 2319bool Expr::isDefaultArgument() const { 2320 const Expr *E = this; 2321 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E)) 2322 E = M->GetTemporaryExpr(); 2323 2324 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 2325 E = ICE->getSubExprAsWritten(); 2326 2327 return isa<CXXDefaultArgExpr>(E); 2328} 2329 2330/// \brief Skip over any no-op casts and any temporary-binding 2331/// expressions. 2332static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) { 2333 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E)) 2334 E = M->GetTemporaryExpr(); 2335 2336 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 2337 if (ICE->getCastKind() == CK_NoOp) 2338 E = ICE->getSubExpr(); 2339 else 2340 break; 2341 } 2342 2343 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E)) 2344 E = BE->getSubExpr(); 2345 2346 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 2347 if (ICE->getCastKind() == CK_NoOp) 2348 E = ICE->getSubExpr(); 2349 else 2350 break; 2351 } 2352 2353 return E->IgnoreParens(); 2354} 2355 2356/// isTemporaryObject - Determines if this expression produces a 2357/// temporary of the given class type. 2358bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const { 2359 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy))) 2360 return false; 2361 2362 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this); 2363 2364 // Temporaries are by definition pr-values of class type. 2365 if (!E->Classify(C).isPRValue()) { 2366 // In this context, property reference is a message call and is pr-value. 2367 if (!isa<ObjCPropertyRefExpr>(E)) 2368 return false; 2369 } 2370 2371 // Black-list a few cases which yield pr-values of class type that don't 2372 // refer to temporaries of that type: 2373 2374 // - implicit derived-to-base conversions 2375 if (isa<ImplicitCastExpr>(E)) { 2376 switch (cast<ImplicitCastExpr>(E)->getCastKind()) { 2377 case CK_DerivedToBase: 2378 case CK_UncheckedDerivedToBase: 2379 return false; 2380 default: 2381 break; 2382 } 2383 } 2384 2385 // - member expressions (all) 2386 if (isa<MemberExpr>(E)) 2387 return false; 2388 2389 // - opaque values (all) 2390 if (isa<OpaqueValueExpr>(E)) 2391 return false; 2392 2393 return true; 2394} 2395 2396bool Expr::isImplicitCXXThis() const { 2397 const Expr *E = this; 2398 2399 // Strip away parentheses and casts we don't care about. 2400 while (true) { 2401 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) { 2402 E = Paren->getSubExpr(); 2403 continue; 2404 } 2405 2406 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 2407 if (ICE->getCastKind() == CK_NoOp || 2408 ICE->getCastKind() == CK_LValueToRValue || 2409 ICE->getCastKind() == CK_DerivedToBase || 2410 ICE->getCastKind() == CK_UncheckedDerivedToBase) { 2411 E = ICE->getSubExpr(); 2412 continue; 2413 } 2414 } 2415 2416 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) { 2417 if (UnOp->getOpcode() == UO_Extension) { 2418 E = UnOp->getSubExpr(); 2419 continue; 2420 } 2421 } 2422 2423 if (const MaterializeTemporaryExpr *M 2424 = dyn_cast<MaterializeTemporaryExpr>(E)) { 2425 E = M->GetTemporaryExpr(); 2426 continue; 2427 } 2428 2429 break; 2430 } 2431 2432 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E)) 2433 return This->isImplicit(); 2434 2435 return false; 2436} 2437 2438/// hasAnyTypeDependentArguments - Determines if any of the expressions 2439/// in Exprs is type-dependent. 2440bool Expr::hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs) { 2441 for (unsigned I = 0; I < NumExprs; ++I) 2442 if (Exprs[I]->isTypeDependent()) 2443 return true; 2444 2445 return false; 2446} 2447 2448/// hasAnyValueDependentArguments - Determines if any of the expressions 2449/// in Exprs is value-dependent. 2450bool Expr::hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs) { 2451 for (unsigned I = 0; I < NumExprs; ++I) 2452 if (Exprs[I]->isValueDependent()) 2453 return true; 2454 2455 return false; 2456} 2457 2458bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef) const { 2459 // This function is attempting whether an expression is an initializer 2460 // which can be evaluated at compile-time. isEvaluatable handles most 2461 // of the cases, but it can't deal with some initializer-specific 2462 // expressions, and it can't deal with aggregates; we deal with those here, 2463 // and fall back to isEvaluatable for the other cases. 2464 2465 // If we ever capture reference-binding directly in the AST, we can 2466 // kill the second parameter. 2467 2468 if (IsForRef) { 2469 EvalResult Result; 2470 return EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects; 2471 } 2472 2473 switch (getStmtClass()) { 2474 default: break; 2475 case IntegerLiteralClass: 2476 case FloatingLiteralClass: 2477 case StringLiteralClass: 2478 case ObjCStringLiteralClass: 2479 case ObjCEncodeExprClass: 2480 return true; 2481 case CXXTemporaryObjectExprClass: 2482 case CXXConstructExprClass: { 2483 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this); 2484 2485 // Only if it's 2486 if (CE->getConstructor()->isTrivial()) { 2487 // 1) an application of the trivial default constructor or 2488 if (!CE->getNumArgs()) return true; 2489 2490 // 2) an elidable trivial copy construction of an operand which is 2491 // itself a constant initializer. Note that we consider the 2492 // operand on its own, *not* as a reference binding. 2493 if (CE->isElidable() && 2494 CE->getArg(0)->isConstantInitializer(Ctx, false)) 2495 return true; 2496 } 2497 2498 // 3) a foldable constexpr constructor. 2499 break; 2500 } 2501 case CompoundLiteralExprClass: { 2502 // This handles gcc's extension that allows global initializers like 2503 // "struct x {int x;} x = (struct x) {};". 2504 // FIXME: This accepts other cases it shouldn't! 2505 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer(); 2506 return Exp->isConstantInitializer(Ctx, false); 2507 } 2508 case InitListExprClass: { 2509 // FIXME: This doesn't deal with fields with reference types correctly. 2510 // FIXME: This incorrectly allows pointers cast to integers to be assigned 2511 // to bitfields. 2512 const InitListExpr *Exp = cast<InitListExpr>(this); 2513 unsigned numInits = Exp->getNumInits(); 2514 for (unsigned i = 0; i < numInits; i++) { 2515 if (!Exp->getInit(i)->isConstantInitializer(Ctx, false)) 2516 return false; 2517 } 2518 return true; 2519 } 2520 case ImplicitValueInitExprClass: 2521 return true; 2522 case ParenExprClass: 2523 return cast<ParenExpr>(this)->getSubExpr() 2524 ->isConstantInitializer(Ctx, IsForRef); 2525 case GenericSelectionExprClass: 2526 if (cast<GenericSelectionExpr>(this)->isResultDependent()) 2527 return false; 2528 return cast<GenericSelectionExpr>(this)->getResultExpr() 2529 ->isConstantInitializer(Ctx, IsForRef); 2530 case ChooseExprClass: 2531 return cast<ChooseExpr>(this)->getChosenSubExpr(Ctx) 2532 ->isConstantInitializer(Ctx, IsForRef); 2533 case UnaryOperatorClass: { 2534 const UnaryOperator* Exp = cast<UnaryOperator>(this); 2535 if (Exp->getOpcode() == UO_Extension) 2536 return Exp->getSubExpr()->isConstantInitializer(Ctx, false); 2537 break; 2538 } 2539 case CXXFunctionalCastExprClass: 2540 case CXXStaticCastExprClass: 2541 case ImplicitCastExprClass: 2542 case CStyleCastExprClass: { 2543 const CastExpr *CE = cast<CastExpr>(this); 2544 2545 // If we're promoting an integer to an _Atomic type then this is constant 2546 // if the integer is constant. We also need to check the converse in case 2547 // someone does something like: 2548 // 2549 // int a = (_Atomic(int))42; 2550 // 2551 // I doubt anyone would write code like this directly, but it's quite 2552 // possible as the result of macro expansions. 2553 if (CE->getCastKind() == CK_NonAtomicToAtomic || 2554 CE->getCastKind() == CK_AtomicToNonAtomic) 2555 return CE->getSubExpr()->isConstantInitializer(Ctx, false); 2556 2557 // Handle bitcasts of vector constants. 2558 if (getType()->isVectorType() && CE->getCastKind() == CK_BitCast) 2559 return CE->getSubExpr()->isConstantInitializer(Ctx, false); 2560 2561 // Handle misc casts we want to ignore. 2562 // FIXME: Is it really safe to ignore all these? 2563 if (CE->getCastKind() == CK_NoOp || 2564 CE->getCastKind() == CK_LValueToRValue || 2565 CE->getCastKind() == CK_ToUnion || 2566 CE->getCastKind() == CK_ConstructorConversion) 2567 return CE->getSubExpr()->isConstantInitializer(Ctx, false); 2568 2569 break; 2570 } 2571 case MaterializeTemporaryExprClass: 2572 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr() 2573 ->isConstantInitializer(Ctx, false); 2574 } 2575 return isEvaluatable(Ctx); 2576} 2577 2578/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null 2579/// pointer constant or not, as well as the specific kind of constant detected. 2580/// Null pointer constants can be integer constant expressions with the 2581/// value zero, casts of zero to void*, nullptr (C++0X), or __null 2582/// (a GNU extension). 2583Expr::NullPointerConstantKind 2584Expr::isNullPointerConstant(ASTContext &Ctx, 2585 NullPointerConstantValueDependence NPC) const { 2586 if (isValueDependent()) { 2587 switch (NPC) { 2588 case NPC_NeverValueDependent: 2589 llvm_unreachable("Unexpected value dependent expression!"); 2590 case NPC_ValueDependentIsNull: 2591 if (isTypeDependent() || getType()->isIntegralType(Ctx)) 2592 return NPCK_ZeroInteger; 2593 else 2594 return NPCK_NotNull; 2595 2596 case NPC_ValueDependentIsNotNull: 2597 return NPCK_NotNull; 2598 } 2599 } 2600 2601 // Strip off a cast to void*, if it exists. Except in C++. 2602 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) { 2603 if (!Ctx.getLangOptions().CPlusPlus) { 2604 // Check that it is a cast to void*. 2605 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) { 2606 QualType Pointee = PT->getPointeeType(); 2607 if (!Pointee.hasQualifiers() && 2608 Pointee->isVoidType() && // to void* 2609 CE->getSubExpr()->getType()->isIntegerType()) // from int. 2610 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC); 2611 } 2612 } 2613 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) { 2614 // Ignore the ImplicitCastExpr type entirely. 2615 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC); 2616 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) { 2617 // Accept ((void*)0) as a null pointer constant, as many other 2618 // implementations do. 2619 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC); 2620 } else if (const GenericSelectionExpr *GE = 2621 dyn_cast<GenericSelectionExpr>(this)) { 2622 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC); 2623 } else if (const CXXDefaultArgExpr *DefaultArg 2624 = dyn_cast<CXXDefaultArgExpr>(this)) { 2625 // See through default argument expressions 2626 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC); 2627 } else if (isa<GNUNullExpr>(this)) { 2628 // The GNU __null extension is always a null pointer constant. 2629 return NPCK_GNUNull; 2630 } else if (const MaterializeTemporaryExpr *M 2631 = dyn_cast<MaterializeTemporaryExpr>(this)) { 2632 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC); 2633 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) { 2634 if (const Expr *Source = OVE->getSourceExpr()) 2635 return Source->isNullPointerConstant(Ctx, NPC); 2636 } 2637 2638 // C++0x nullptr_t is always a null pointer constant. 2639 if (getType()->isNullPtrType()) 2640 return NPCK_CXX0X_nullptr; 2641 2642 if (const RecordType *UT = getType()->getAsUnionType()) 2643 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2644 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){ 2645 const Expr *InitExpr = CLE->getInitializer(); 2646 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr)) 2647 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC); 2648 } 2649 // This expression must be an integer type. 2650 if (!getType()->isIntegerType() || 2651 (Ctx.getLangOptions().CPlusPlus && getType()->isEnumeralType())) 2652 return NPCK_NotNull; 2653 2654 // If we have an integer constant expression, we need to *evaluate* it and 2655 // test for the value 0. 2656 llvm::APSInt Result; 2657 bool IsNull = isIntegerConstantExpr(Result, Ctx) && Result == 0; 2658 2659 return (IsNull ? NPCK_ZeroInteger : NPCK_NotNull); 2660} 2661 2662/// \brief If this expression is an l-value for an Objective C 2663/// property, find the underlying property reference expression. 2664const ObjCPropertyRefExpr *Expr::getObjCProperty() const { 2665 const Expr *E = this; 2666 while (true) { 2667 assert((E->getValueKind() == VK_LValue && 2668 E->getObjectKind() == OK_ObjCProperty) && 2669 "expression is not a property reference"); 2670 E = E->IgnoreParenCasts(); 2671 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2672 if (BO->getOpcode() == BO_Comma) { 2673 E = BO->getRHS(); 2674 continue; 2675 } 2676 } 2677 2678 break; 2679 } 2680 2681 return cast<ObjCPropertyRefExpr>(E); 2682} 2683 2684FieldDecl *Expr::getBitField() { 2685 Expr *E = this->IgnoreParens(); 2686 2687 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 2688 if (ICE->getCastKind() == CK_LValueToRValue || 2689 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp)) 2690 E = ICE->getSubExpr()->IgnoreParens(); 2691 else 2692 break; 2693 } 2694 2695 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E)) 2696 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) 2697 if (Field->isBitField()) 2698 return Field; 2699 2700 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) 2701 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl())) 2702 if (Field->isBitField()) 2703 return Field; 2704 2705 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) { 2706 if (BinOp->isAssignmentOp() && BinOp->getLHS()) 2707 return BinOp->getLHS()->getBitField(); 2708 2709 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS()) 2710 return BinOp->getRHS()->getBitField(); 2711 } 2712 2713 return 0; 2714} 2715 2716bool Expr::refersToVectorElement() const { 2717 const Expr *E = this->IgnoreParens(); 2718 2719 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 2720 if (ICE->getValueKind() != VK_RValue && 2721 ICE->getCastKind() == CK_NoOp) 2722 E = ICE->getSubExpr()->IgnoreParens(); 2723 else 2724 break; 2725 } 2726 2727 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E)) 2728 return ASE->getBase()->getType()->isVectorType(); 2729 2730 if (isa<ExtVectorElementExpr>(E)) 2731 return true; 2732 2733 return false; 2734} 2735 2736/// isArrow - Return true if the base expression is a pointer to vector, 2737/// return false if the base expression is a vector. 2738bool ExtVectorElementExpr::isArrow() const { 2739 return getBase()->getType()->isPointerType(); 2740} 2741 2742unsigned ExtVectorElementExpr::getNumElements() const { 2743 if (const VectorType *VT = getType()->getAs<VectorType>()) 2744 return VT->getNumElements(); 2745 return 1; 2746} 2747 2748/// containsDuplicateElements - Return true if any element access is repeated. 2749bool ExtVectorElementExpr::containsDuplicateElements() const { 2750 // FIXME: Refactor this code to an accessor on the AST node which returns the 2751 // "type" of component access, and share with code below and in Sema. 2752 StringRef Comp = Accessor->getName(); 2753 2754 // Halving swizzles do not contain duplicate elements. 2755 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd") 2756 return false; 2757 2758 // Advance past s-char prefix on hex swizzles. 2759 if (Comp[0] == 's' || Comp[0] == 'S') 2760 Comp = Comp.substr(1); 2761 2762 for (unsigned i = 0, e = Comp.size(); i != e; ++i) 2763 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos) 2764 return true; 2765 2766 return false; 2767} 2768 2769/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray. 2770void ExtVectorElementExpr::getEncodedElementAccess( 2771 SmallVectorImpl<unsigned> &Elts) const { 2772 StringRef Comp = Accessor->getName(); 2773 if (Comp[0] == 's' || Comp[0] == 'S') 2774 Comp = Comp.substr(1); 2775 2776 bool isHi = Comp == "hi"; 2777 bool isLo = Comp == "lo"; 2778 bool isEven = Comp == "even"; 2779 bool isOdd = Comp == "odd"; 2780 2781 for (unsigned i = 0, e = getNumElements(); i != e; ++i) { 2782 uint64_t Index; 2783 2784 if (isHi) 2785 Index = e + i; 2786 else if (isLo) 2787 Index = i; 2788 else if (isEven) 2789 Index = 2 * i; 2790 else if (isOdd) 2791 Index = 2 * i + 1; 2792 else 2793 Index = ExtVectorType::getAccessorIdx(Comp[i]); 2794 2795 Elts.push_back(Index); 2796 } 2797} 2798 2799ObjCMessageExpr::ObjCMessageExpr(QualType T, 2800 ExprValueKind VK, 2801 SourceLocation LBracLoc, 2802 SourceLocation SuperLoc, 2803 bool IsInstanceSuper, 2804 QualType SuperType, 2805 Selector Sel, 2806 ArrayRef<SourceLocation> SelLocs, 2807 SelectorLocationsKind SelLocsK, 2808 ObjCMethodDecl *Method, 2809 ArrayRef<Expr *> Args, 2810 SourceLocation RBracLoc, 2811 bool isImplicit) 2812 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, 2813 /*TypeDependent=*/false, /*ValueDependent=*/false, 2814 /*InstantiationDependent=*/false, 2815 /*ContainsUnexpandedParameterPack=*/false), 2816 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method 2817 : Sel.getAsOpaquePtr())), 2818 Kind(IsInstanceSuper? SuperInstance : SuperClass), 2819 HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit), 2820 SuperLoc(SuperLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc) 2821{ 2822 initArgsAndSelLocs(Args, SelLocs, SelLocsK); 2823 setReceiverPointer(SuperType.getAsOpaquePtr()); 2824} 2825 2826ObjCMessageExpr::ObjCMessageExpr(QualType T, 2827 ExprValueKind VK, 2828 SourceLocation LBracLoc, 2829 TypeSourceInfo *Receiver, 2830 Selector Sel, 2831 ArrayRef<SourceLocation> SelLocs, 2832 SelectorLocationsKind SelLocsK, 2833 ObjCMethodDecl *Method, 2834 ArrayRef<Expr *> Args, 2835 SourceLocation RBracLoc, 2836 bool isImplicit) 2837 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, T->isDependentType(), 2838 T->isDependentType(), T->isInstantiationDependentType(), 2839 T->containsUnexpandedParameterPack()), 2840 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method 2841 : Sel.getAsOpaquePtr())), 2842 Kind(Class), 2843 HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit), 2844 LBracLoc(LBracLoc), RBracLoc(RBracLoc) 2845{ 2846 initArgsAndSelLocs(Args, SelLocs, SelLocsK); 2847 setReceiverPointer(Receiver); 2848} 2849 2850ObjCMessageExpr::ObjCMessageExpr(QualType T, 2851 ExprValueKind VK, 2852 SourceLocation LBracLoc, 2853 Expr *Receiver, 2854 Selector Sel, 2855 ArrayRef<SourceLocation> SelLocs, 2856 SelectorLocationsKind SelLocsK, 2857 ObjCMethodDecl *Method, 2858 ArrayRef<Expr *> Args, 2859 SourceLocation RBracLoc, 2860 bool isImplicit) 2861 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, Receiver->isTypeDependent(), 2862 Receiver->isTypeDependent(), 2863 Receiver->isInstantiationDependent(), 2864 Receiver->containsUnexpandedParameterPack()), 2865 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method 2866 : Sel.getAsOpaquePtr())), 2867 Kind(Instance), 2868 HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit), 2869 LBracLoc(LBracLoc), RBracLoc(RBracLoc) 2870{ 2871 initArgsAndSelLocs(Args, SelLocs, SelLocsK); 2872 setReceiverPointer(Receiver); 2873} 2874 2875void ObjCMessageExpr::initArgsAndSelLocs(ArrayRef<Expr *> Args, 2876 ArrayRef<SourceLocation> SelLocs, 2877 SelectorLocationsKind SelLocsK) { 2878 setNumArgs(Args.size()); 2879 Expr **MyArgs = getArgs(); 2880 for (unsigned I = 0; I != Args.size(); ++I) { 2881 if (Args[I]->isTypeDependent()) 2882 ExprBits.TypeDependent = true; 2883 if (Args[I]->isValueDependent()) 2884 ExprBits.ValueDependent = true; 2885 if (Args[I]->isInstantiationDependent()) 2886 ExprBits.InstantiationDependent = true; 2887 if (Args[I]->containsUnexpandedParameterPack()) 2888 ExprBits.ContainsUnexpandedParameterPack = true; 2889 2890 MyArgs[I] = Args[I]; 2891 } 2892 2893 if (!isImplicit()) { 2894 SelLocsKind = SelLocsK; 2895 if (SelLocsK == SelLoc_NonStandard) 2896 std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs()); 2897 } 2898} 2899 2900ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T, 2901 ExprValueKind VK, 2902 SourceLocation LBracLoc, 2903 SourceLocation SuperLoc, 2904 bool IsInstanceSuper, 2905 QualType SuperType, 2906 Selector Sel, 2907 ArrayRef<SourceLocation> SelLocs, 2908 ObjCMethodDecl *Method, 2909 ArrayRef<Expr *> Args, 2910 SourceLocation RBracLoc, 2911 bool isImplicit) { 2912 assert((!SelLocs.empty() || isImplicit) && 2913 "No selector locs for non-implicit message"); 2914 ObjCMessageExpr *Mem; 2915 SelectorLocationsKind SelLocsK = SelectorLocationsKind(); 2916 if (isImplicit) 2917 Mem = alloc(Context, Args.size(), 0); 2918 else 2919 Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK); 2920 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, SuperLoc, IsInstanceSuper, 2921 SuperType, Sel, SelLocs, SelLocsK, 2922 Method, Args, RBracLoc, isImplicit); 2923} 2924 2925ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T, 2926 ExprValueKind VK, 2927 SourceLocation LBracLoc, 2928 TypeSourceInfo *Receiver, 2929 Selector Sel, 2930 ArrayRef<SourceLocation> SelLocs, 2931 ObjCMethodDecl *Method, 2932 ArrayRef<Expr *> Args, 2933 SourceLocation RBracLoc, 2934 bool isImplicit) { 2935 assert((!SelLocs.empty() || isImplicit) && 2936 "No selector locs for non-implicit message"); 2937 ObjCMessageExpr *Mem; 2938 SelectorLocationsKind SelLocsK = SelectorLocationsKind(); 2939 if (isImplicit) 2940 Mem = alloc(Context, Args.size(), 0); 2941 else 2942 Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK); 2943 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel, 2944 SelLocs, SelLocsK, Method, Args, RBracLoc, 2945 isImplicit); 2946} 2947 2948ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T, 2949 ExprValueKind VK, 2950 SourceLocation LBracLoc, 2951 Expr *Receiver, 2952 Selector Sel, 2953 ArrayRef<SourceLocation> SelLocs, 2954 ObjCMethodDecl *Method, 2955 ArrayRef<Expr *> Args, 2956 SourceLocation RBracLoc, 2957 bool isImplicit) { 2958 assert((!SelLocs.empty() || isImplicit) && 2959 "No selector locs for non-implicit message"); 2960 ObjCMessageExpr *Mem; 2961 SelectorLocationsKind SelLocsK = SelectorLocationsKind(); 2962 if (isImplicit) 2963 Mem = alloc(Context, Args.size(), 0); 2964 else 2965 Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK); 2966 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel, 2967 SelLocs, SelLocsK, Method, Args, RBracLoc, 2968 isImplicit); 2969} 2970 2971ObjCMessageExpr *ObjCMessageExpr::CreateEmpty(ASTContext &Context, 2972 unsigned NumArgs, 2973 unsigned NumStoredSelLocs) { 2974 ObjCMessageExpr *Mem = alloc(Context, NumArgs, NumStoredSelLocs); 2975 return new (Mem) ObjCMessageExpr(EmptyShell(), NumArgs); 2976} 2977 2978ObjCMessageExpr *ObjCMessageExpr::alloc(ASTContext &C, 2979 ArrayRef<Expr *> Args, 2980 SourceLocation RBraceLoc, 2981 ArrayRef<SourceLocation> SelLocs, 2982 Selector Sel, 2983 SelectorLocationsKind &SelLocsK) { 2984 SelLocsK = hasStandardSelectorLocs(Sel, SelLocs, Args, RBraceLoc); 2985 unsigned NumStoredSelLocs = (SelLocsK == SelLoc_NonStandard) ? SelLocs.size() 2986 : 0; 2987 return alloc(C, Args.size(), NumStoredSelLocs); 2988} 2989 2990ObjCMessageExpr *ObjCMessageExpr::alloc(ASTContext &C, 2991 unsigned NumArgs, 2992 unsigned NumStoredSelLocs) { 2993 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) + 2994 NumArgs * sizeof(Expr *) + NumStoredSelLocs * sizeof(SourceLocation); 2995 return (ObjCMessageExpr *)C.Allocate(Size, 2996 llvm::AlignOf<ObjCMessageExpr>::Alignment); 2997} 2998 2999void ObjCMessageExpr::getSelectorLocs( 3000 SmallVectorImpl<SourceLocation> &SelLocs) const { 3001 for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i) 3002 SelLocs.push_back(getSelectorLoc(i)); 3003} 3004 3005SourceRange ObjCMessageExpr::getReceiverRange() const { 3006 switch (getReceiverKind()) { 3007 case Instance: 3008 return getInstanceReceiver()->getSourceRange(); 3009 3010 case Class: 3011 return getClassReceiverTypeInfo()->getTypeLoc().getSourceRange(); 3012 3013 case SuperInstance: 3014 case SuperClass: 3015 return getSuperLoc(); 3016 } 3017 3018 return SourceLocation(); 3019} 3020 3021Selector ObjCMessageExpr::getSelector() const { 3022 if (HasMethod) 3023 return reinterpret_cast<const ObjCMethodDecl *>(SelectorOrMethod) 3024 ->getSelector(); 3025 return Selector(SelectorOrMethod); 3026} 3027 3028ObjCInterfaceDecl *ObjCMessageExpr::getReceiverInterface() const { 3029 switch (getReceiverKind()) { 3030 case Instance: 3031 if (const ObjCObjectPointerType *Ptr 3032 = getInstanceReceiver()->getType()->getAs<ObjCObjectPointerType>()) 3033 return Ptr->getInterfaceDecl(); 3034 break; 3035 3036 case Class: 3037 if (const ObjCObjectType *Ty 3038 = getClassReceiver()->getAs<ObjCObjectType>()) 3039 return Ty->getInterface(); 3040 break; 3041 3042 case SuperInstance: 3043 if (const ObjCObjectPointerType *Ptr 3044 = getSuperType()->getAs<ObjCObjectPointerType>()) 3045 return Ptr->getInterfaceDecl(); 3046 break; 3047 3048 case SuperClass: 3049 if (const ObjCObjectType *Iface 3050 = getSuperType()->getAs<ObjCObjectType>()) 3051 return Iface->getInterface(); 3052 break; 3053 } 3054 3055 return 0; 3056} 3057 3058StringRef ObjCBridgedCastExpr::getBridgeKindName() const { 3059 switch (getBridgeKind()) { 3060 case OBC_Bridge: 3061 return "__bridge"; 3062 case OBC_BridgeTransfer: 3063 return "__bridge_transfer"; 3064 case OBC_BridgeRetained: 3065 return "__bridge_retained"; 3066 } 3067 3068 return "__bridge"; 3069} 3070 3071bool ChooseExpr::isConditionTrue(const ASTContext &C) const { 3072 return getCond()->EvaluateKnownConstInt(C) != 0; 3073} 3074 3075ShuffleVectorExpr::ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr, 3076 QualType Type, SourceLocation BLoc, 3077 SourceLocation RP) 3078 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary, 3079 Type->isDependentType(), Type->isDependentType(), 3080 Type->isInstantiationDependentType(), 3081 Type->containsUnexpandedParameterPack()), 3082 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(nexpr) 3083{ 3084 SubExprs = new (C) Stmt*[nexpr]; 3085 for (unsigned i = 0; i < nexpr; i++) { 3086 if (args[i]->isTypeDependent()) 3087 ExprBits.TypeDependent = true; 3088 if (args[i]->isValueDependent()) 3089 ExprBits.ValueDependent = true; 3090 if (args[i]->isInstantiationDependent()) 3091 ExprBits.InstantiationDependent = true; 3092 if (args[i]->containsUnexpandedParameterPack()) 3093 ExprBits.ContainsUnexpandedParameterPack = true; 3094 3095 SubExprs[i] = args[i]; 3096 } 3097} 3098 3099void ShuffleVectorExpr::setExprs(ASTContext &C, Expr ** Exprs, 3100 unsigned NumExprs) { 3101 if (SubExprs) C.Deallocate(SubExprs); 3102 3103 SubExprs = new (C) Stmt* [NumExprs]; 3104 this->NumExprs = NumExprs; 3105 memcpy(SubExprs, Exprs, sizeof(Expr *) * NumExprs); 3106} 3107 3108GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context, 3109 SourceLocation GenericLoc, Expr *ControllingExpr, 3110 TypeSourceInfo **AssocTypes, Expr **AssocExprs, 3111 unsigned NumAssocs, SourceLocation DefaultLoc, 3112 SourceLocation RParenLoc, 3113 bool ContainsUnexpandedParameterPack, 3114 unsigned ResultIndex) 3115 : Expr(GenericSelectionExprClass, 3116 AssocExprs[ResultIndex]->getType(), 3117 AssocExprs[ResultIndex]->getValueKind(), 3118 AssocExprs[ResultIndex]->getObjectKind(), 3119 AssocExprs[ResultIndex]->isTypeDependent(), 3120 AssocExprs[ResultIndex]->isValueDependent(), 3121 AssocExprs[ResultIndex]->isInstantiationDependent(), 3122 ContainsUnexpandedParameterPack), 3123 AssocTypes(new (Context) TypeSourceInfo*[NumAssocs]), 3124 SubExprs(new (Context) Stmt*[END_EXPR+NumAssocs]), NumAssocs(NumAssocs), 3125 ResultIndex(ResultIndex), GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), 3126 RParenLoc(RParenLoc) { 3127 SubExprs[CONTROLLING] = ControllingExpr; 3128 std::copy(AssocTypes, AssocTypes+NumAssocs, this->AssocTypes); 3129 std::copy(AssocExprs, AssocExprs+NumAssocs, SubExprs+END_EXPR); 3130} 3131 3132GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context, 3133 SourceLocation GenericLoc, Expr *ControllingExpr, 3134 TypeSourceInfo **AssocTypes, Expr **AssocExprs, 3135 unsigned NumAssocs, SourceLocation DefaultLoc, 3136 SourceLocation RParenLoc, 3137 bool ContainsUnexpandedParameterPack) 3138 : Expr(GenericSelectionExprClass, 3139 Context.DependentTy, 3140 VK_RValue, 3141 OK_Ordinary, 3142 /*isTypeDependent=*/true, 3143 /*isValueDependent=*/true, 3144 /*isInstantiationDependent=*/true, 3145 ContainsUnexpandedParameterPack), 3146 AssocTypes(new (Context) TypeSourceInfo*[NumAssocs]), 3147 SubExprs(new (Context) Stmt*[END_EXPR+NumAssocs]), NumAssocs(NumAssocs), 3148 ResultIndex(-1U), GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), 3149 RParenLoc(RParenLoc) { 3150 SubExprs[CONTROLLING] = ControllingExpr; 3151 std::copy(AssocTypes, AssocTypes+NumAssocs, this->AssocTypes); 3152 std::copy(AssocExprs, AssocExprs+NumAssocs, SubExprs+END_EXPR); 3153} 3154 3155//===----------------------------------------------------------------------===// 3156// DesignatedInitExpr 3157//===----------------------------------------------------------------------===// 3158 3159IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const { 3160 assert(Kind == FieldDesignator && "Only valid on a field designator"); 3161 if (Field.NameOrField & 0x01) 3162 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01); 3163 else 3164 return getField()->getIdentifier(); 3165} 3166 3167DesignatedInitExpr::DesignatedInitExpr(ASTContext &C, QualType Ty, 3168 unsigned NumDesignators, 3169 const Designator *Designators, 3170 SourceLocation EqualOrColonLoc, 3171 bool GNUSyntax, 3172 Expr **IndexExprs, 3173 unsigned NumIndexExprs, 3174 Expr *Init) 3175 : Expr(DesignatedInitExprClass, Ty, 3176 Init->getValueKind(), Init->getObjectKind(), 3177 Init->isTypeDependent(), Init->isValueDependent(), 3178 Init->isInstantiationDependent(), 3179 Init->containsUnexpandedParameterPack()), 3180 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax), 3181 NumDesignators(NumDesignators), NumSubExprs(NumIndexExprs + 1) { 3182 this->Designators = new (C) Designator[NumDesignators]; 3183 3184 // Record the initializer itself. 3185 child_range Child = children(); 3186 *Child++ = Init; 3187 3188 // Copy the designators and their subexpressions, computing 3189 // value-dependence along the way. 3190 unsigned IndexIdx = 0; 3191 for (unsigned I = 0; I != NumDesignators; ++I) { 3192 this->Designators[I] = Designators[I]; 3193 3194 if (this->Designators[I].isArrayDesignator()) { 3195 // Compute type- and value-dependence. 3196 Expr *Index = IndexExprs[IndexIdx]; 3197 if (Index->isTypeDependent() || Index->isValueDependent()) 3198 ExprBits.ValueDependent = true; 3199 if (Index->isInstantiationDependent()) 3200 ExprBits.InstantiationDependent = true; 3201 // Propagate unexpanded parameter packs. 3202 if (Index->containsUnexpandedParameterPack()) 3203 ExprBits.ContainsUnexpandedParameterPack = true; 3204 3205 // Copy the index expressions into permanent storage. 3206 *Child++ = IndexExprs[IndexIdx++]; 3207 } else if (this->Designators[I].isArrayRangeDesignator()) { 3208 // Compute type- and value-dependence. 3209 Expr *Start = IndexExprs[IndexIdx]; 3210 Expr *End = IndexExprs[IndexIdx + 1]; 3211 if (Start->isTypeDependent() || Start->isValueDependent() || 3212 End->isTypeDependent() || End->isValueDependent()) { 3213 ExprBits.ValueDependent = true; 3214 ExprBits.InstantiationDependent = true; 3215 } else if (Start->isInstantiationDependent() || 3216 End->isInstantiationDependent()) { 3217 ExprBits.InstantiationDependent = true; 3218 } 3219 3220 // Propagate unexpanded parameter packs. 3221 if (Start->containsUnexpandedParameterPack() || 3222 End->containsUnexpandedParameterPack()) 3223 ExprBits.ContainsUnexpandedParameterPack = true; 3224 3225 // Copy the start/end expressions into permanent storage. 3226 *Child++ = IndexExprs[IndexIdx++]; 3227 *Child++ = IndexExprs[IndexIdx++]; 3228 } 3229 } 3230 3231 assert(IndexIdx == NumIndexExprs && "Wrong number of index expressions"); 3232} 3233 3234DesignatedInitExpr * 3235DesignatedInitExpr::Create(ASTContext &C, Designator *Designators, 3236 unsigned NumDesignators, 3237 Expr **IndexExprs, unsigned NumIndexExprs, 3238 SourceLocation ColonOrEqualLoc, 3239 bool UsesColonSyntax, Expr *Init) { 3240 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) + 3241 sizeof(Stmt *) * (NumIndexExprs + 1), 8); 3242 return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators, 3243 ColonOrEqualLoc, UsesColonSyntax, 3244 IndexExprs, NumIndexExprs, Init); 3245} 3246 3247DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C, 3248 unsigned NumIndexExprs) { 3249 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) + 3250 sizeof(Stmt *) * (NumIndexExprs + 1), 8); 3251 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1); 3252} 3253 3254void DesignatedInitExpr::setDesignators(ASTContext &C, 3255 const Designator *Desigs, 3256 unsigned NumDesigs) { 3257 Designators = new (C) Designator[NumDesigs]; 3258 NumDesignators = NumDesigs; 3259 for (unsigned I = 0; I != NumDesigs; ++I) 3260 Designators[I] = Desigs[I]; 3261} 3262 3263SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const { 3264 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this); 3265 if (size() == 1) 3266 return DIE->getDesignator(0)->getSourceRange(); 3267 return SourceRange(DIE->getDesignator(0)->getStartLocation(), 3268 DIE->getDesignator(size()-1)->getEndLocation()); 3269} 3270 3271SourceRange DesignatedInitExpr::getSourceRange() const { 3272 SourceLocation StartLoc; 3273 Designator &First = 3274 *const_cast<DesignatedInitExpr*>(this)->designators_begin(); 3275 if (First.isFieldDesignator()) { 3276 if (GNUSyntax) 3277 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc); 3278 else 3279 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc); 3280 } else 3281 StartLoc = 3282 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc); 3283 return SourceRange(StartLoc, getInit()->getSourceRange().getEnd()); 3284} 3285 3286Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) { 3287 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator"); 3288 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 3289 Ptr += sizeof(DesignatedInitExpr); 3290 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr)); 3291 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1)); 3292} 3293 3294Expr *DesignatedInitExpr::getArrayRangeStart(const Designator& D) { 3295 assert(D.Kind == Designator::ArrayRangeDesignator && 3296 "Requires array range designator"); 3297 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 3298 Ptr += sizeof(DesignatedInitExpr); 3299 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr)); 3300 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1)); 3301} 3302 3303Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator& D) { 3304 assert(D.Kind == Designator::ArrayRangeDesignator && 3305 "Requires array range designator"); 3306 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 3307 Ptr += sizeof(DesignatedInitExpr); 3308 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr)); 3309 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2)); 3310} 3311 3312/// \brief Replaces the designator at index @p Idx with the series 3313/// of designators in [First, Last). 3314void DesignatedInitExpr::ExpandDesignator(ASTContext &C, unsigned Idx, 3315 const Designator *First, 3316 const Designator *Last) { 3317 unsigned NumNewDesignators = Last - First; 3318 if (NumNewDesignators == 0) { 3319 std::copy_backward(Designators + Idx + 1, 3320 Designators + NumDesignators, 3321 Designators + Idx); 3322 --NumNewDesignators; 3323 return; 3324 } else if (NumNewDesignators == 1) { 3325 Designators[Idx] = *First; 3326 return; 3327 } 3328 3329 Designator *NewDesignators 3330 = new (C) Designator[NumDesignators - 1 + NumNewDesignators]; 3331 std::copy(Designators, Designators + Idx, NewDesignators); 3332 std::copy(First, Last, NewDesignators + Idx); 3333 std::copy(Designators + Idx + 1, Designators + NumDesignators, 3334 NewDesignators + Idx + NumNewDesignators); 3335 Designators = NewDesignators; 3336 NumDesignators = NumDesignators - 1 + NumNewDesignators; 3337} 3338 3339ParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc, 3340 Expr **exprs, unsigned nexprs, 3341 SourceLocation rparenloc, QualType T) 3342 : Expr(ParenListExprClass, T, VK_RValue, OK_Ordinary, 3343 false, false, false, false), 3344 NumExprs(nexprs), LParenLoc(lparenloc), RParenLoc(rparenloc) { 3345 assert(!T.isNull() && "ParenListExpr must have a valid type"); 3346 Exprs = new (C) Stmt*[nexprs]; 3347 for (unsigned i = 0; i != nexprs; ++i) { 3348 if (exprs[i]->isTypeDependent()) 3349 ExprBits.TypeDependent = true; 3350 if (exprs[i]->isValueDependent()) 3351 ExprBits.ValueDependent = true; 3352 if (exprs[i]->isInstantiationDependent()) 3353 ExprBits.InstantiationDependent = true; 3354 if (exprs[i]->containsUnexpandedParameterPack()) 3355 ExprBits.ContainsUnexpandedParameterPack = true; 3356 3357 Exprs[i] = exprs[i]; 3358 } 3359} 3360 3361const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) { 3362 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e)) 3363 e = ewc->getSubExpr(); 3364 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e)) 3365 e = m->GetTemporaryExpr(); 3366 e = cast<CXXConstructExpr>(e)->getArg(0); 3367 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e)) 3368 e = ice->getSubExpr(); 3369 return cast<OpaqueValueExpr>(e); 3370} 3371 3372PseudoObjectExpr *PseudoObjectExpr::Create(ASTContext &Context, EmptyShell sh, 3373 unsigned numSemanticExprs) { 3374 void *buffer = Context.Allocate(sizeof(PseudoObjectExpr) + 3375 (1 + numSemanticExprs) * sizeof(Expr*), 3376 llvm::alignOf<PseudoObjectExpr>()); 3377 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs); 3378} 3379 3380PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs) 3381 : Expr(PseudoObjectExprClass, shell) { 3382 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1; 3383} 3384 3385PseudoObjectExpr *PseudoObjectExpr::Create(ASTContext &C, Expr *syntax, 3386 ArrayRef<Expr*> semantics, 3387 unsigned resultIndex) { 3388 assert(syntax && "no syntactic expression!"); 3389 assert(semantics.size() && "no semantic expressions!"); 3390 3391 QualType type; 3392 ExprValueKind VK; 3393 if (resultIndex == NoResult) { 3394 type = C.VoidTy; 3395 VK = VK_RValue; 3396 } else { 3397 assert(resultIndex < semantics.size()); 3398 type = semantics[resultIndex]->getType(); 3399 VK = semantics[resultIndex]->getValueKind(); 3400 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary); 3401 } 3402 3403 void *buffer = C.Allocate(sizeof(PseudoObjectExpr) + 3404 (1 + semantics.size()) * sizeof(Expr*), 3405 llvm::alignOf<PseudoObjectExpr>()); 3406 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics, 3407 resultIndex); 3408} 3409 3410PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK, 3411 Expr *syntax, ArrayRef<Expr*> semantics, 3412 unsigned resultIndex) 3413 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary, 3414 /*filled in at end of ctor*/ false, false, false, false) { 3415 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1; 3416 PseudoObjectExprBits.ResultIndex = resultIndex + 1; 3417 3418 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) { 3419 Expr *E = (i == 0 ? syntax : semantics[i-1]); 3420 getSubExprsBuffer()[i] = E; 3421 3422 if (E->isTypeDependent()) 3423 ExprBits.TypeDependent = true; 3424 if (E->isValueDependent()) 3425 ExprBits.ValueDependent = true; 3426 if (E->isInstantiationDependent()) 3427 ExprBits.InstantiationDependent = true; 3428 if (E->containsUnexpandedParameterPack()) 3429 ExprBits.ContainsUnexpandedParameterPack = true; 3430 3431 if (isa<OpaqueValueExpr>(E)) 3432 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != 0 && 3433 "opaque-value semantic expressions for pseudo-object " 3434 "operations must have sources"); 3435 } 3436} 3437 3438//===----------------------------------------------------------------------===// 3439// ExprIterator. 3440//===----------------------------------------------------------------------===// 3441 3442Expr* ExprIterator::operator[](size_t idx) { return cast<Expr>(I[idx]); } 3443Expr* ExprIterator::operator*() const { return cast<Expr>(*I); } 3444Expr* ExprIterator::operator->() const { return cast<Expr>(*I); } 3445const Expr* ConstExprIterator::operator[](size_t idx) const { 3446 return cast<Expr>(I[idx]); 3447} 3448const Expr* ConstExprIterator::operator*() const { return cast<Expr>(*I); } 3449const Expr* ConstExprIterator::operator->() const { return cast<Expr>(*I); } 3450 3451//===----------------------------------------------------------------------===// 3452// Child Iterators for iterating over subexpressions/substatements 3453//===----------------------------------------------------------------------===// 3454 3455// UnaryExprOrTypeTraitExpr 3456Stmt::child_range UnaryExprOrTypeTraitExpr::children() { 3457 // If this is of a type and the type is a VLA type (and not a typedef), the 3458 // size expression of the VLA needs to be treated as an executable expression. 3459 // Why isn't this weirdness documented better in StmtIterator? 3460 if (isArgumentType()) { 3461 if (const VariableArrayType* T = dyn_cast<VariableArrayType>( 3462 getArgumentType().getTypePtr())) 3463 return child_range(child_iterator(T), child_iterator()); 3464 return child_range(); 3465 } 3466 return child_range(&Argument.Ex, &Argument.Ex + 1); 3467} 3468 3469// ObjCMessageExpr 3470Stmt::child_range ObjCMessageExpr::children() { 3471 Stmt **begin; 3472 if (getReceiverKind() == Instance) 3473 begin = reinterpret_cast<Stmt **>(this + 1); 3474 else 3475 begin = reinterpret_cast<Stmt **>(getArgs()); 3476 return child_range(begin, 3477 reinterpret_cast<Stmt **>(getArgs() + getNumArgs())); 3478} 3479 3480// Blocks 3481BlockDeclRefExpr::BlockDeclRefExpr(VarDecl *d, QualType t, ExprValueKind VK, 3482 SourceLocation l, bool ByRef, 3483 bool constAdded) 3484 : Expr(BlockDeclRefExprClass, t, VK, OK_Ordinary, false, false, false, 3485 d->isParameterPack()), 3486 D(d), Loc(l), IsByRef(ByRef), ConstQualAdded(constAdded) 3487{ 3488 bool TypeDependent = false; 3489 bool ValueDependent = false; 3490 bool InstantiationDependent = false; 3491 computeDeclRefDependence(D, getType(), TypeDependent, ValueDependent, 3492 InstantiationDependent); 3493 ExprBits.TypeDependent = TypeDependent; 3494 ExprBits.ValueDependent = ValueDependent; 3495 ExprBits.InstantiationDependent = InstantiationDependent; 3496} 3497 3498 3499AtomicExpr::AtomicExpr(SourceLocation BLoc, Expr **args, unsigned nexpr, 3500 QualType t, AtomicOp op, SourceLocation RP) 3501 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary, 3502 false, false, false, false), 3503 NumSubExprs(nexpr), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) 3504{ 3505 for (unsigned i = 0; i < nexpr; i++) { 3506 if (args[i]->isTypeDependent()) 3507 ExprBits.TypeDependent = true; 3508 if (args[i]->isValueDependent()) 3509 ExprBits.ValueDependent = true; 3510 if (args[i]->isInstantiationDependent()) 3511 ExprBits.InstantiationDependent = true; 3512 if (args[i]->containsUnexpandedParameterPack()) 3513 ExprBits.ContainsUnexpandedParameterPack = true; 3514 3515 SubExprs[i] = args[i]; 3516 } 3517} 3518