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