CGExpr.cpp revision b23a5a0a043b852ad643d366a0bb5b4c5a5c8881
1//===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===// 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 contains code to emit Expr nodes as LLVM code. 11// 12//===----------------------------------------------------------------------===// 13 14#include "CodeGenFunction.h" 15#include "CodeGenModule.h" 16#include "CGCall.h" 17#include "CGCXXABI.h" 18#include "CGDebugInfo.h" 19#include "CGRecordLayout.h" 20#include "CGObjCRuntime.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/DeclObjC.h" 23#include "llvm/Intrinsics.h" 24#include "clang/Frontend/CodeGenOptions.h" 25#include "llvm/Target/TargetData.h" 26using namespace clang; 27using namespace CodeGen; 28 29//===--------------------------------------------------------------------===// 30// Miscellaneous Helper Methods 31//===--------------------------------------------------------------------===// 32 33llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) { 34 unsigned addressSpace = 35 cast<llvm::PointerType>(value->getType())->getAddressSpace(); 36 37 const llvm::PointerType *destType = Int8PtrTy; 38 if (addressSpace) 39 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace); 40 41 if (value->getType() == destType) return value; 42 return Builder.CreateBitCast(value, destType); 43} 44 45/// CreateTempAlloca - This creates a alloca and inserts it into the entry 46/// block. 47llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty, 48 const llvm::Twine &Name) { 49 if (!Builder.isNamePreserving()) 50 return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt); 51 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt); 52} 53 54void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var, 55 llvm::Value *Init) { 56 llvm::StoreInst *Store = new llvm::StoreInst(Init, Var); 57 llvm::BasicBlock *Block = AllocaInsertPt->getParent(); 58 Block->getInstList().insertAfter(&*AllocaInsertPt, Store); 59} 60 61llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty, 62 const llvm::Twine &Name) { 63 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name); 64 // FIXME: Should we prefer the preferred type alignment here? 65 CharUnits Align = getContext().getTypeAlignInChars(Ty); 66 Alloc->setAlignment(Align.getQuantity()); 67 return Alloc; 68} 69 70llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty, 71 const llvm::Twine &Name) { 72 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name); 73 // FIXME: Should we prefer the preferred type alignment here? 74 CharUnits Align = getContext().getTypeAlignInChars(Ty); 75 Alloc->setAlignment(Align.getQuantity()); 76 return Alloc; 77} 78 79/// EvaluateExprAsBool - Perform the usual unary conversions on the specified 80/// expression and compare the result against zero, returning an Int1Ty value. 81llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) { 82 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) { 83 llvm::Value *MemPtr = EmitScalarExpr(E); 84 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT); 85 } 86 87 QualType BoolTy = getContext().BoolTy; 88 if (!E->getType()->isAnyComplexType()) 89 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy); 90 91 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy); 92} 93 94/// EmitIgnoredExpr - Emit code to compute the specified expression, 95/// ignoring the result. 96void CodeGenFunction::EmitIgnoredExpr(const Expr *E) { 97 if (E->isRValue()) 98 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true); 99 100 // Just emit it as an l-value and drop the result. 101 EmitLValue(E); 102} 103 104/// EmitAnyExpr - Emit code to compute the specified expression which 105/// can have any type. The result is returned as an RValue struct. 106/// If this is an aggregate expression, AggSlot indicates where the 107/// result should be returned. 108RValue CodeGenFunction::EmitAnyExpr(const Expr *E, AggValueSlot AggSlot, 109 bool IgnoreResult) { 110 if (!hasAggregateLLVMType(E->getType())) 111 return RValue::get(EmitScalarExpr(E, IgnoreResult)); 112 else if (E->getType()->isAnyComplexType()) 113 return RValue::getComplex(EmitComplexExpr(E, IgnoreResult, IgnoreResult)); 114 115 EmitAggExpr(E, AggSlot, IgnoreResult); 116 return AggSlot.asRValue(); 117} 118 119/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 120/// always be accessible even if no aggregate location is provided. 121RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) { 122 AggValueSlot AggSlot = AggValueSlot::ignored(); 123 124 if (hasAggregateLLVMType(E->getType()) && 125 !E->getType()->isAnyComplexType()) 126 AggSlot = CreateAggTemp(E->getType(), "agg.tmp"); 127 return EmitAnyExpr(E, AggSlot); 128} 129 130/// EmitAnyExprToMem - Evaluate an expression into a given memory 131/// location. 132void CodeGenFunction::EmitAnyExprToMem(const Expr *E, 133 llvm::Value *Location, 134 bool IsLocationVolatile, 135 bool IsInit) { 136 if (E->getType()->isComplexType()) 137 EmitComplexExprIntoAddr(E, Location, IsLocationVolatile); 138 else if (hasAggregateLLVMType(E->getType())) 139 EmitAggExpr(E, AggValueSlot::forAddr(Location, IsLocationVolatile, IsInit)); 140 else { 141 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false)); 142 LValue LV = MakeAddrLValue(Location, E->getType()); 143 EmitStoreThroughLValue(RV, LV, E->getType()); 144 } 145} 146 147namespace { 148/// \brief An adjustment to be made to the temporary created when emitting a 149/// reference binding, which accesses a particular subobject of that temporary. 150 struct SubobjectAdjustment { 151 enum { DerivedToBaseAdjustment, FieldAdjustment } Kind; 152 153 union { 154 struct { 155 const CastExpr *BasePath; 156 const CXXRecordDecl *DerivedClass; 157 } DerivedToBase; 158 159 FieldDecl *Field; 160 }; 161 162 SubobjectAdjustment(const CastExpr *BasePath, 163 const CXXRecordDecl *DerivedClass) 164 : Kind(DerivedToBaseAdjustment) { 165 DerivedToBase.BasePath = BasePath; 166 DerivedToBase.DerivedClass = DerivedClass; 167 } 168 169 SubobjectAdjustment(FieldDecl *Field) 170 : Kind(FieldAdjustment) { 171 this->Field = Field; 172 } 173 }; 174} 175 176static llvm::Value * 177CreateReferenceTemporary(CodeGenFunction& CGF, QualType Type, 178 const NamedDecl *InitializedDecl) { 179 if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) { 180 if (VD->hasGlobalStorage()) { 181 llvm::SmallString<256> Name; 182 llvm::raw_svector_ostream Out(Name); 183 CGF.CGM.getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out); 184 Out.flush(); 185 186 const llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type); 187 188 // Create the reference temporary. 189 llvm::GlobalValue *RefTemp = 190 new llvm::GlobalVariable(CGF.CGM.getModule(), 191 RefTempTy, /*isConstant=*/false, 192 llvm::GlobalValue::InternalLinkage, 193 llvm::Constant::getNullValue(RefTempTy), 194 Name.str()); 195 return RefTemp; 196 } 197 } 198 199 return CGF.CreateMemTemp(Type, "ref.tmp"); 200} 201 202static llvm::Value * 203EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E, 204 llvm::Value *&ReferenceTemporary, 205 const CXXDestructorDecl *&ReferenceTemporaryDtor, 206 const NamedDecl *InitializedDecl) { 207 if (const CXXDefaultArgExpr *DAE = dyn_cast<CXXDefaultArgExpr>(E)) 208 E = DAE->getExpr(); 209 210 if (const ExprWithCleanups *TE = dyn_cast<ExprWithCleanups>(E)) { 211 CodeGenFunction::RunCleanupsScope Scope(CGF); 212 213 return EmitExprForReferenceBinding(CGF, TE->getSubExpr(), 214 ReferenceTemporary, 215 ReferenceTemporaryDtor, 216 InitializedDecl); 217 } 218 219 if (const ObjCPropertyRefExpr *PRE = 220 dyn_cast<ObjCPropertyRefExpr>(E->IgnoreParenImpCasts())) 221 if (PRE->getGetterResultType()->isReferenceType()) 222 E = PRE; 223 224 RValue RV; 225 if (E->isGLValue()) { 226 // Emit the expression as an lvalue. 227 LValue LV = CGF.EmitLValue(E); 228 if (LV.isPropertyRef()) { 229 RV = CGF.EmitLoadOfPropertyRefLValue(LV); 230 return RV.getScalarVal(); 231 } 232 if (LV.isSimple()) 233 return LV.getAddress(); 234 235 // We have to load the lvalue. 236 RV = CGF.EmitLoadOfLValue(LV, E->getType()); 237 } else { 238 QualType ResultTy = E->getType(); 239 240 llvm::SmallVector<SubobjectAdjustment, 2> Adjustments; 241 while (true) { 242 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 243 E = PE->getSubExpr(); 244 continue; 245 } 246 247 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 248 if ((CE->getCastKind() == CK_DerivedToBase || 249 CE->getCastKind() == CK_UncheckedDerivedToBase) && 250 E->getType()->isRecordType()) { 251 E = CE->getSubExpr(); 252 CXXRecordDecl *Derived 253 = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl()); 254 Adjustments.push_back(SubobjectAdjustment(CE, Derived)); 255 continue; 256 } 257 258 if (CE->getCastKind() == CK_NoOp) { 259 E = CE->getSubExpr(); 260 continue; 261 } 262 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 263 if (!ME->isArrow() && ME->getBase()->isRValue()) { 264 assert(ME->getBase()->getType()->isRecordType()); 265 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 266 E = ME->getBase(); 267 Adjustments.push_back(SubobjectAdjustment(Field)); 268 continue; 269 } 270 } 271 } 272 273 if (const OpaqueValueExpr *opaque = dyn_cast<OpaqueValueExpr>(E)) 274 if (opaque->getType()->isRecordType()) 275 return CGF.EmitOpaqueValueLValue(opaque).getAddress(); 276 277 // Nothing changed. 278 break; 279 } 280 281 // Create a reference temporary if necessary. 282 AggValueSlot AggSlot = AggValueSlot::ignored(); 283 if (CGF.hasAggregateLLVMType(E->getType()) && 284 !E->getType()->isAnyComplexType()) { 285 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(), 286 InitializedDecl); 287 AggSlot = AggValueSlot::forAddr(ReferenceTemporary, false, 288 InitializedDecl != 0); 289 } 290 291 RV = CGF.EmitAnyExpr(E, AggSlot); 292 293 if (InitializedDecl) { 294 // Get the destructor for the reference temporary. 295 if (const RecordType *RT = E->getType()->getAs<RecordType>()) { 296 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 297 if (!ClassDecl->hasTrivialDestructor()) 298 ReferenceTemporaryDtor = ClassDecl->getDestructor(); 299 } 300 } 301 302 // Check if need to perform derived-to-base casts and/or field accesses, to 303 // get from the temporary object we created (and, potentially, for which we 304 // extended the lifetime) to the subobject we're binding the reference to. 305 if (!Adjustments.empty()) { 306 llvm::Value *Object = RV.getAggregateAddr(); 307 for (unsigned I = Adjustments.size(); I != 0; --I) { 308 SubobjectAdjustment &Adjustment = Adjustments[I-1]; 309 switch (Adjustment.Kind) { 310 case SubobjectAdjustment::DerivedToBaseAdjustment: 311 Object = 312 CGF.GetAddressOfBaseClass(Object, 313 Adjustment.DerivedToBase.DerivedClass, 314 Adjustment.DerivedToBase.BasePath->path_begin(), 315 Adjustment.DerivedToBase.BasePath->path_end(), 316 /*NullCheckValue=*/false); 317 break; 318 319 case SubobjectAdjustment::FieldAdjustment: { 320 LValue LV = 321 CGF.EmitLValueForField(Object, Adjustment.Field, 0); 322 if (LV.isSimple()) { 323 Object = LV.getAddress(); 324 break; 325 } 326 327 // For non-simple lvalues, we actually have to create a copy of 328 // the object we're binding to. 329 QualType T = Adjustment.Field->getType().getNonReferenceType() 330 .getUnqualifiedType(); 331 Object = CreateReferenceTemporary(CGF, T, InitializedDecl); 332 LValue TempLV = CGF.MakeAddrLValue(Object, 333 Adjustment.Field->getType()); 334 CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV, T), TempLV, T); 335 break; 336 } 337 338 } 339 } 340 341 return Object; 342 } 343 } 344 345 if (RV.isAggregate()) 346 return RV.getAggregateAddr(); 347 348 // Create a temporary variable that we can bind the reference to. 349 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(), 350 InitializedDecl); 351 352 353 unsigned Alignment = 354 CGF.getContext().getTypeAlignInChars(E->getType()).getQuantity(); 355 if (RV.isScalar()) 356 CGF.EmitStoreOfScalar(RV.getScalarVal(), ReferenceTemporary, 357 /*Volatile=*/false, Alignment, E->getType()); 358 else 359 CGF.StoreComplexToAddr(RV.getComplexVal(), ReferenceTemporary, 360 /*Volatile=*/false); 361 return ReferenceTemporary; 362} 363 364RValue 365CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E, 366 const NamedDecl *InitializedDecl) { 367 llvm::Value *ReferenceTemporary = 0; 368 const CXXDestructorDecl *ReferenceTemporaryDtor = 0; 369 llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary, 370 ReferenceTemporaryDtor, 371 InitializedDecl); 372 if (!ReferenceTemporaryDtor) 373 return RValue::get(Value); 374 375 // Make sure to call the destructor for the reference temporary. 376 if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) { 377 if (VD->hasGlobalStorage()) { 378 llvm::Constant *DtorFn = 379 CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete); 380 EmitCXXGlobalDtorRegistration(DtorFn, 381 cast<llvm::Constant>(ReferenceTemporary)); 382 383 return RValue::get(Value); 384 } 385 } 386 387 PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary); 388 389 return RValue::get(Value); 390} 391 392 393/// getAccessedFieldNo - Given an encoded value and a result number, return the 394/// input field number being accessed. 395unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx, 396 const llvm::Constant *Elts) { 397 if (isa<llvm::ConstantAggregateZero>(Elts)) 398 return 0; 399 400 return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue(); 401} 402 403void CodeGenFunction::EmitCheck(llvm::Value *Address, unsigned Size) { 404 if (!CatchUndefined) 405 return; 406 407 // This needs to be to the standard address space. 408 Address = Builder.CreateBitCast(Address, Int8PtrTy); 409 410 const llvm::Type *IntPtrT = IntPtrTy; 411 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, &IntPtrT, 1); 412 413 // In time, people may want to control this and use a 1 here. 414 llvm::Value *Arg = Builder.getFalse(); 415 llvm::Value *C = Builder.CreateCall2(F, Address, Arg); 416 llvm::BasicBlock *Cont = createBasicBlock(); 417 llvm::BasicBlock *Check = createBasicBlock(); 418 llvm::Value *NegativeOne = llvm::ConstantInt::get(IntPtrTy, -1ULL); 419 Builder.CreateCondBr(Builder.CreateICmpEQ(C, NegativeOne), Cont, Check); 420 421 EmitBlock(Check); 422 Builder.CreateCondBr(Builder.CreateICmpUGE(C, 423 llvm::ConstantInt::get(IntPtrTy, Size)), 424 Cont, getTrapBB()); 425 EmitBlock(Cont); 426} 427 428 429CodeGenFunction::ComplexPairTy CodeGenFunction:: 430EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 431 bool isInc, bool isPre) { 432 ComplexPairTy InVal = LoadComplexFromAddr(LV.getAddress(), 433 LV.isVolatileQualified()); 434 435 llvm::Value *NextVal; 436 if (isa<llvm::IntegerType>(InVal.first->getType())) { 437 uint64_t AmountVal = isInc ? 1 : -1; 438 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true); 439 440 // Add the inc/dec to the real part. 441 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec"); 442 } else { 443 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType(); 444 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1); 445 if (!isInc) 446 FVal.changeSign(); 447 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal); 448 449 // Add the inc/dec to the real part. 450 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec"); 451 } 452 453 ComplexPairTy IncVal(NextVal, InVal.second); 454 455 // Store the updated result through the lvalue. 456 StoreComplexToAddr(IncVal, LV.getAddress(), LV.isVolatileQualified()); 457 458 // If this is a postinc, return the value read from memory, otherwise use the 459 // updated value. 460 return isPre ? IncVal : InVal; 461} 462 463 464//===----------------------------------------------------------------------===// 465// LValue Expression Emission 466//===----------------------------------------------------------------------===// 467 468RValue CodeGenFunction::GetUndefRValue(QualType Ty) { 469 if (Ty->isVoidType()) 470 return RValue::get(0); 471 472 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 473 const llvm::Type *EltTy = ConvertType(CTy->getElementType()); 474 llvm::Value *U = llvm::UndefValue::get(EltTy); 475 return RValue::getComplex(std::make_pair(U, U)); 476 } 477 478 // If this is a use of an undefined aggregate type, the aggregate must have an 479 // identifiable address. Just because the contents of the value are undefined 480 // doesn't mean that the address can't be taken and compared. 481 if (hasAggregateLLVMType(Ty)) { 482 llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp"); 483 return RValue::getAggregate(DestPtr); 484 } 485 486 return RValue::get(llvm::UndefValue::get(ConvertType(Ty))); 487} 488 489RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E, 490 const char *Name) { 491 ErrorUnsupported(E, Name); 492 return GetUndefRValue(E->getType()); 493} 494 495LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E, 496 const char *Name) { 497 ErrorUnsupported(E, Name); 498 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType())); 499 return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType()); 500} 501 502LValue CodeGenFunction::EmitCheckedLValue(const Expr *E) { 503 LValue LV = EmitLValue(E); 504 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) 505 EmitCheck(LV.getAddress(), 506 getContext().getTypeSizeInChars(E->getType()).getQuantity()); 507 return LV; 508} 509 510/// EmitLValue - Emit code to compute a designator that specifies the location 511/// of the expression. 512/// 513/// This can return one of two things: a simple address or a bitfield reference. 514/// In either case, the LLVM Value* in the LValue structure is guaranteed to be 515/// an LLVM pointer type. 516/// 517/// If this returns a bitfield reference, nothing about the pointee type of the 518/// LLVM value is known: For example, it may not be a pointer to an integer. 519/// 520/// If this returns a normal address, and if the lvalue's C type is fixed size, 521/// this method guarantees that the returned pointer type will point to an LLVM 522/// type of the same size of the lvalue's type. If the lvalue has a variable 523/// length type, this is not possible. 524/// 525LValue CodeGenFunction::EmitLValue(const Expr *E) { 526 switch (E->getStmtClass()) { 527 default: return EmitUnsupportedLValue(E, "l-value expression"); 528 529 case Expr::ObjCSelectorExprClass: 530 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E)); 531 case Expr::ObjCIsaExprClass: 532 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E)); 533 case Expr::BinaryOperatorClass: 534 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E)); 535 case Expr::CompoundAssignOperatorClass: 536 if (!E->getType()->isAnyComplexType()) 537 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E)); 538 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E)); 539 case Expr::CallExprClass: 540 case Expr::CXXMemberCallExprClass: 541 case Expr::CXXOperatorCallExprClass: 542 return EmitCallExprLValue(cast<CallExpr>(E)); 543 case Expr::VAArgExprClass: 544 return EmitVAArgExprLValue(cast<VAArgExpr>(E)); 545 case Expr::DeclRefExprClass: 546 return EmitDeclRefLValue(cast<DeclRefExpr>(E)); 547 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr()); 548 case Expr::PredefinedExprClass: 549 return EmitPredefinedLValue(cast<PredefinedExpr>(E)); 550 case Expr::StringLiteralClass: 551 return EmitStringLiteralLValue(cast<StringLiteral>(E)); 552 case Expr::ObjCEncodeExprClass: 553 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E)); 554 555 case Expr::BlockDeclRefExprClass: 556 return EmitBlockDeclRefLValue(cast<BlockDeclRefExpr>(E)); 557 558 case Expr::CXXTemporaryObjectExprClass: 559 case Expr::CXXConstructExprClass: 560 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E)); 561 case Expr::CXXBindTemporaryExprClass: 562 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E)); 563 case Expr::ExprWithCleanupsClass: 564 return EmitExprWithCleanupsLValue(cast<ExprWithCleanups>(E)); 565 case Expr::CXXScalarValueInitExprClass: 566 return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E)); 567 case Expr::CXXDefaultArgExprClass: 568 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr()); 569 case Expr::CXXTypeidExprClass: 570 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E)); 571 572 case Expr::ObjCMessageExprClass: 573 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E)); 574 case Expr::ObjCIvarRefExprClass: 575 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E)); 576 case Expr::ObjCPropertyRefExprClass: 577 return EmitObjCPropertyRefLValue(cast<ObjCPropertyRefExpr>(E)); 578 case Expr::StmtExprClass: 579 return EmitStmtExprLValue(cast<StmtExpr>(E)); 580 case Expr::UnaryOperatorClass: 581 return EmitUnaryOpLValue(cast<UnaryOperator>(E)); 582 case Expr::ArraySubscriptExprClass: 583 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E)); 584 case Expr::ExtVectorElementExprClass: 585 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E)); 586 case Expr::MemberExprClass: 587 return EmitMemberExpr(cast<MemberExpr>(E)); 588 case Expr::CompoundLiteralExprClass: 589 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E)); 590 case Expr::ConditionalOperatorClass: 591 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E)); 592 case Expr::BinaryConditionalOperatorClass: 593 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E)); 594 case Expr::ChooseExprClass: 595 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext())); 596 case Expr::OpaqueValueExprClass: 597 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E)); 598 case Expr::ImplicitCastExprClass: 599 case Expr::CStyleCastExprClass: 600 case Expr::CXXFunctionalCastExprClass: 601 case Expr::CXXStaticCastExprClass: 602 case Expr::CXXDynamicCastExprClass: 603 case Expr::CXXReinterpretCastExprClass: 604 case Expr::CXXConstCastExprClass: 605 return EmitCastLValue(cast<CastExpr>(E)); 606 } 607} 608 609llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, 610 unsigned Alignment, QualType Ty, 611 llvm::MDNode *TBAAInfo) { 612 llvm::LoadInst *Load = Builder.CreateLoad(Addr, "tmp"); 613 if (Volatile) 614 Load->setVolatile(true); 615 if (Alignment) 616 Load->setAlignment(Alignment); 617 if (TBAAInfo) 618 CGM.DecorateInstruction(Load, TBAAInfo); 619 620 return EmitFromMemory(Load, Ty); 621} 622 623static bool isBooleanUnderlyingType(QualType Ty) { 624 if (const EnumType *ET = dyn_cast<EnumType>(Ty)) 625 return ET->getDecl()->getIntegerType()->isBooleanType(); 626 return false; 627} 628 629llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) { 630 // Bool has a different representation in memory than in registers. 631 if (Ty->isBooleanType() || isBooleanUnderlyingType(Ty)) { 632 // This should really always be an i1, but sometimes it's already 633 // an i8, and it's awkward to track those cases down. 634 if (Value->getType()->isIntegerTy(1)) 635 return Builder.CreateZExt(Value, Builder.getInt8Ty(), "frombool"); 636 assert(Value->getType()->isIntegerTy(8) && "value rep of bool not i1/i8"); 637 } 638 639 return Value; 640} 641 642llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) { 643 // Bool has a different representation in memory than in registers. 644 if (Ty->isBooleanType() || isBooleanUnderlyingType(Ty)) { 645 assert(Value->getType()->isIntegerTy(8) && "memory rep of bool not i8"); 646 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool"); 647 } 648 649 return Value; 650} 651 652void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, 653 bool Volatile, unsigned Alignment, 654 QualType Ty, 655 llvm::MDNode *TBAAInfo) { 656 Value = EmitToMemory(Value, Ty); 657 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile); 658 if (Alignment) 659 Store->setAlignment(Alignment); 660 if (TBAAInfo) 661 CGM.DecorateInstruction(Store, TBAAInfo); 662} 663 664/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this 665/// method emits the address of the lvalue, then loads the result as an rvalue, 666/// returning the rvalue. 667RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) { 668 if (LV.isObjCWeak()) { 669 // load of a __weak object. 670 llvm::Value *AddrWeakObj = LV.getAddress(); 671 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this, 672 AddrWeakObj)); 673 } 674 675 if (LV.isSimple()) { 676 llvm::Value *Ptr = LV.getAddress(); 677 678 // Functions are l-values that don't require loading. 679 if (ExprType->isFunctionType()) 680 return RValue::get(Ptr); 681 682 // Everything needs a load. 683 return RValue::get(EmitLoadOfScalar(Ptr, LV.isVolatileQualified(), 684 LV.getAlignment(), ExprType, 685 LV.getTBAAInfo())); 686 687 } 688 689 if (LV.isVectorElt()) { 690 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), 691 LV.isVolatileQualified(), "tmp"); 692 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(), 693 "vecext")); 694 } 695 696 // If this is a reference to a subset of the elements of a vector, either 697 // shuffle the input or extract/insert them as appropriate. 698 if (LV.isExtVectorElt()) 699 return EmitLoadOfExtVectorElementLValue(LV, ExprType); 700 701 if (LV.isBitField()) 702 return EmitLoadOfBitfieldLValue(LV, ExprType); 703 704 assert(LV.isPropertyRef() && "Unknown LValue type!"); 705 return EmitLoadOfPropertyRefLValue(LV); 706} 707 708RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV, 709 QualType ExprType) { 710 const CGBitFieldInfo &Info = LV.getBitFieldInfo(); 711 712 // Get the output type. 713 const llvm::Type *ResLTy = ConvertType(ExprType); 714 unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy); 715 716 // Compute the result as an OR of all of the individual component accesses. 717 llvm::Value *Res = 0; 718 for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) { 719 const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i); 720 721 // Get the field pointer. 722 llvm::Value *Ptr = LV.getBitFieldBaseAddr(); 723 724 // Only offset by the field index if used, so that incoming values are not 725 // required to be structures. 726 if (AI.FieldIndex) 727 Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field"); 728 729 // Offset by the byte offset, if used. 730 if (AI.FieldByteOffset) { 731 Ptr = EmitCastToVoidPtr(Ptr); 732 Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset,"bf.field.offs"); 733 } 734 735 // Cast to the access type. 736 const llvm::Type *PTy = llvm::Type::getIntNPtrTy(getLLVMContext(), 737 AI.AccessWidth, 738 CGM.getContext().getTargetAddressSpace(ExprType)); 739 Ptr = Builder.CreateBitCast(Ptr, PTy); 740 741 // Perform the load. 742 llvm::LoadInst *Load = Builder.CreateLoad(Ptr, LV.isVolatileQualified()); 743 if (AI.AccessAlignment) 744 Load->setAlignment(AI.AccessAlignment); 745 746 // Shift out unused low bits and mask out unused high bits. 747 llvm::Value *Val = Load; 748 if (AI.FieldBitStart) 749 Val = Builder.CreateLShr(Load, AI.FieldBitStart); 750 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(AI.AccessWidth, 751 AI.TargetBitWidth), 752 "bf.clear"); 753 754 // Extend or truncate to the target size. 755 if (AI.AccessWidth < ResSizeInBits) 756 Val = Builder.CreateZExt(Val, ResLTy); 757 else if (AI.AccessWidth > ResSizeInBits) 758 Val = Builder.CreateTrunc(Val, ResLTy); 759 760 // Shift into place, and OR into the result. 761 if (AI.TargetBitOffset) 762 Val = Builder.CreateShl(Val, AI.TargetBitOffset); 763 Res = Res ? Builder.CreateOr(Res, Val) : Val; 764 } 765 766 // If the bit-field is signed, perform the sign-extension. 767 // 768 // FIXME: This can easily be folded into the load of the high bits, which 769 // could also eliminate the mask of high bits in some situations. 770 if (Info.isSigned()) { 771 unsigned ExtraBits = ResSizeInBits - Info.getSize(); 772 if (ExtraBits) 773 Res = Builder.CreateAShr(Builder.CreateShl(Res, ExtraBits), 774 ExtraBits, "bf.val.sext"); 775 } 776 777 return RValue::get(Res); 778} 779 780// If this is a reference to a subset of the elements of a vector, create an 781// appropriate shufflevector. 782RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV, 783 QualType ExprType) { 784 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(), 785 LV.isVolatileQualified(), "tmp"); 786 787 const llvm::Constant *Elts = LV.getExtVectorElts(); 788 789 // If the result of the expression is a non-vector type, we must be extracting 790 // a single element. Just codegen as an extractelement. 791 const VectorType *ExprVT = ExprType->getAs<VectorType>(); 792 if (!ExprVT) { 793 unsigned InIdx = getAccessedFieldNo(0, Elts); 794 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx); 795 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp")); 796 } 797 798 // Always use shuffle vector to try to retain the original program structure 799 unsigned NumResultElts = ExprVT->getNumElements(); 800 801 llvm::SmallVector<llvm::Constant*, 4> Mask; 802 for (unsigned i = 0; i != NumResultElts; ++i) { 803 unsigned InIdx = getAccessedFieldNo(i, Elts); 804 Mask.push_back(llvm::ConstantInt::get(Int32Ty, InIdx)); 805 } 806 807 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 808 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()), 809 MaskV, "tmp"); 810 return RValue::get(Vec); 811} 812 813 814 815/// EmitStoreThroughLValue - Store the specified rvalue into the specified 816/// lvalue, where both are guaranteed to the have the same type, and that type 817/// is 'Ty'. 818void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, 819 QualType Ty) { 820 if (!Dst.isSimple()) { 821 if (Dst.isVectorElt()) { 822 // Read/modify/write the vector, inserting the new element. 823 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), 824 Dst.isVolatileQualified(), "tmp"); 825 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(), 826 Dst.getVectorIdx(), "vecins"); 827 Builder.CreateStore(Vec, Dst.getVectorAddr(),Dst.isVolatileQualified()); 828 return; 829 } 830 831 // If this is an update of extended vector elements, insert them as 832 // appropriate. 833 if (Dst.isExtVectorElt()) 834 return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty); 835 836 if (Dst.isBitField()) 837 return EmitStoreThroughBitfieldLValue(Src, Dst, Ty); 838 839 assert(Dst.isPropertyRef() && "Unknown LValue type"); 840 return EmitStoreThroughPropertyRefLValue(Src, Dst); 841 } 842 843 if (Dst.isObjCWeak() && !Dst.isNonGC()) { 844 // load of a __weak object. 845 llvm::Value *LvalueDst = Dst.getAddress(); 846 llvm::Value *src = Src.getScalarVal(); 847 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst); 848 return; 849 } 850 851 if (Dst.isObjCStrong() && !Dst.isNonGC()) { 852 // load of a __strong object. 853 llvm::Value *LvalueDst = Dst.getAddress(); 854 llvm::Value *src = Src.getScalarVal(); 855 if (Dst.isObjCIvar()) { 856 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL"); 857 const llvm::Type *ResultType = ConvertType(getContext().LongTy); 858 llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp()); 859 llvm::Value *dst = RHS; 860 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast"); 861 llvm::Value *LHS = 862 Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast"); 863 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset"); 864 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst, 865 BytesBetween); 866 } else if (Dst.isGlobalObjCRef()) { 867 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst, 868 Dst.isThreadLocalRef()); 869 } 870 else 871 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst); 872 return; 873 } 874 875 assert(Src.isScalar() && "Can't emit an agg store with this method"); 876 EmitStoreOfScalar(Src.getScalarVal(), Dst.getAddress(), 877 Dst.isVolatileQualified(), Dst.getAlignment(), Ty, 878 Dst.getTBAAInfo()); 879} 880 881void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 882 QualType Ty, 883 llvm::Value **Result) { 884 const CGBitFieldInfo &Info = Dst.getBitFieldInfo(); 885 886 // Get the output type. 887 const llvm::Type *ResLTy = ConvertTypeForMem(Ty); 888 unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy); 889 890 // Get the source value, truncated to the width of the bit-field. 891 llvm::Value *SrcVal = Src.getScalarVal(); 892 893 if (Ty->isBooleanType()) 894 SrcVal = Builder.CreateIntCast(SrcVal, ResLTy, /*IsSigned=*/false); 895 896 SrcVal = Builder.CreateAnd(SrcVal, llvm::APInt::getLowBitsSet(ResSizeInBits, 897 Info.getSize()), 898 "bf.value"); 899 900 // Return the new value of the bit-field, if requested. 901 if (Result) { 902 // Cast back to the proper type for result. 903 const llvm::Type *SrcTy = Src.getScalarVal()->getType(); 904 llvm::Value *ReloadVal = Builder.CreateIntCast(SrcVal, SrcTy, false, 905 "bf.reload.val"); 906 907 // Sign extend if necessary. 908 if (Info.isSigned()) { 909 unsigned ExtraBits = ResSizeInBits - Info.getSize(); 910 if (ExtraBits) 911 ReloadVal = Builder.CreateAShr(Builder.CreateShl(ReloadVal, ExtraBits), 912 ExtraBits, "bf.reload.sext"); 913 } 914 915 *Result = ReloadVal; 916 } 917 918 // Iterate over the components, writing each piece to memory. 919 for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) { 920 const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i); 921 922 // Get the field pointer. 923 llvm::Value *Ptr = Dst.getBitFieldBaseAddr(); 924 unsigned addressSpace = 925 cast<llvm::PointerType>(Ptr->getType())->getAddressSpace(); 926 927 // Only offset by the field index if used, so that incoming values are not 928 // required to be structures. 929 if (AI.FieldIndex) 930 Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field"); 931 932 // Offset by the byte offset, if used. 933 if (AI.FieldByteOffset) { 934 Ptr = EmitCastToVoidPtr(Ptr); 935 Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset,"bf.field.offs"); 936 } 937 938 // Cast to the access type. 939 const llvm::Type *AccessLTy = 940 llvm::Type::getIntNTy(getLLVMContext(), AI.AccessWidth); 941 942 const llvm::Type *PTy = AccessLTy->getPointerTo(addressSpace); 943 Ptr = Builder.CreateBitCast(Ptr, PTy); 944 945 // Extract the piece of the bit-field value to write in this access, limited 946 // to the values that are part of this access. 947 llvm::Value *Val = SrcVal; 948 if (AI.TargetBitOffset) 949 Val = Builder.CreateLShr(Val, AI.TargetBitOffset); 950 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(ResSizeInBits, 951 AI.TargetBitWidth)); 952 953 // Extend or truncate to the access size. 954 if (ResSizeInBits < AI.AccessWidth) 955 Val = Builder.CreateZExt(Val, AccessLTy); 956 else if (ResSizeInBits > AI.AccessWidth) 957 Val = Builder.CreateTrunc(Val, AccessLTy); 958 959 // Shift into the position in memory. 960 if (AI.FieldBitStart) 961 Val = Builder.CreateShl(Val, AI.FieldBitStart); 962 963 // If necessary, load and OR in bits that are outside of the bit-field. 964 if (AI.TargetBitWidth != AI.AccessWidth) { 965 llvm::LoadInst *Load = Builder.CreateLoad(Ptr, Dst.isVolatileQualified()); 966 if (AI.AccessAlignment) 967 Load->setAlignment(AI.AccessAlignment); 968 969 // Compute the mask for zeroing the bits that are part of the bit-field. 970 llvm::APInt InvMask = 971 ~llvm::APInt::getBitsSet(AI.AccessWidth, AI.FieldBitStart, 972 AI.FieldBitStart + AI.TargetBitWidth); 973 974 // Apply the mask and OR in to the value to write. 975 Val = Builder.CreateOr(Builder.CreateAnd(Load, InvMask), Val); 976 } 977 978 // Write the value. 979 llvm::StoreInst *Store = Builder.CreateStore(Val, Ptr, 980 Dst.isVolatileQualified()); 981 if (AI.AccessAlignment) 982 Store->setAlignment(AI.AccessAlignment); 983 } 984} 985 986void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src, 987 LValue Dst, 988 QualType Ty) { 989 // This access turns into a read/modify/write of the vector. Load the input 990 // value now. 991 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(), 992 Dst.isVolatileQualified(), "tmp"); 993 const llvm::Constant *Elts = Dst.getExtVectorElts(); 994 995 llvm::Value *SrcVal = Src.getScalarVal(); 996 997 if (const VectorType *VTy = Ty->getAs<VectorType>()) { 998 unsigned NumSrcElts = VTy->getNumElements(); 999 unsigned NumDstElts = 1000 cast<llvm::VectorType>(Vec->getType())->getNumElements(); 1001 if (NumDstElts == NumSrcElts) { 1002 // Use shuffle vector is the src and destination are the same number of 1003 // elements and restore the vector mask since it is on the side it will be 1004 // stored. 1005 llvm::SmallVector<llvm::Constant*, 4> Mask(NumDstElts); 1006 for (unsigned i = 0; i != NumSrcElts; ++i) { 1007 unsigned InIdx = getAccessedFieldNo(i, Elts); 1008 Mask[InIdx] = llvm::ConstantInt::get(Int32Ty, i); 1009 } 1010 1011 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1012 Vec = Builder.CreateShuffleVector(SrcVal, 1013 llvm::UndefValue::get(Vec->getType()), 1014 MaskV, "tmp"); 1015 } else if (NumDstElts > NumSrcElts) { 1016 // Extended the source vector to the same length and then shuffle it 1017 // into the destination. 1018 // FIXME: since we're shuffling with undef, can we just use the indices 1019 // into that? This could be simpler. 1020 llvm::SmallVector<llvm::Constant*, 4> ExtMask; 1021 unsigned i; 1022 for (i = 0; i != NumSrcElts; ++i) 1023 ExtMask.push_back(llvm::ConstantInt::get(Int32Ty, i)); 1024 for (; i != NumDstElts; ++i) 1025 ExtMask.push_back(llvm::UndefValue::get(Int32Ty)); 1026 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask); 1027 llvm::Value *ExtSrcVal = 1028 Builder.CreateShuffleVector(SrcVal, 1029 llvm::UndefValue::get(SrcVal->getType()), 1030 ExtMaskV, "tmp"); 1031 // build identity 1032 llvm::SmallVector<llvm::Constant*, 4> Mask; 1033 for (unsigned i = 0; i != NumDstElts; ++i) 1034 Mask.push_back(llvm::ConstantInt::get(Int32Ty, i)); 1035 1036 // modify when what gets shuffled in 1037 for (unsigned i = 0; i != NumSrcElts; ++i) { 1038 unsigned Idx = getAccessedFieldNo(i, Elts); 1039 Mask[Idx] = llvm::ConstantInt::get(Int32Ty, i+NumDstElts); 1040 } 1041 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1042 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV, "tmp"); 1043 } else { 1044 // We should never shorten the vector 1045 assert(0 && "unexpected shorten vector length"); 1046 } 1047 } else { 1048 // If the Src is a scalar (not a vector) it must be updating one element. 1049 unsigned InIdx = getAccessedFieldNo(0, Elts); 1050 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx); 1051 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp"); 1052 } 1053 1054 Builder.CreateStore(Vec, Dst.getExtVectorAddr(), Dst.isVolatileQualified()); 1055} 1056 1057// setObjCGCLValueClass - sets class of he lvalue for the purpose of 1058// generating write-barries API. It is currently a global, ivar, 1059// or neither. 1060static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E, 1061 LValue &LV) { 1062 if (Ctx.getLangOptions().getGCMode() == LangOptions::NonGC) 1063 return; 1064 1065 if (isa<ObjCIvarRefExpr>(E)) { 1066 LV.setObjCIvar(true); 1067 ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E)); 1068 LV.setBaseIvarExp(Exp->getBase()); 1069 LV.setObjCArray(E->getType()->isArrayType()); 1070 return; 1071 } 1072 1073 if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) { 1074 if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) { 1075 if (VD->hasGlobalStorage()) { 1076 LV.setGlobalObjCRef(true); 1077 LV.setThreadLocalRef(VD->isThreadSpecified()); 1078 } 1079 } 1080 LV.setObjCArray(E->getType()->isArrayType()); 1081 return; 1082 } 1083 1084 if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) { 1085 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV); 1086 return; 1087 } 1088 1089 if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) { 1090 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV); 1091 if (LV.isObjCIvar()) { 1092 // If cast is to a structure pointer, follow gcc's behavior and make it 1093 // a non-ivar write-barrier. 1094 QualType ExpTy = E->getType(); 1095 if (ExpTy->isPointerType()) 1096 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType(); 1097 if (ExpTy->isRecordType()) 1098 LV.setObjCIvar(false); 1099 } 1100 return; 1101 } 1102 if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) { 1103 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV); 1104 return; 1105 } 1106 1107 if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) { 1108 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV); 1109 return; 1110 } 1111 1112 if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) { 1113 setObjCGCLValueClass(Ctx, Exp->getBase(), LV); 1114 if (LV.isObjCIvar() && !LV.isObjCArray()) 1115 // Using array syntax to assigning to what an ivar points to is not 1116 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0; 1117 LV.setObjCIvar(false); 1118 else if (LV.isGlobalObjCRef() && !LV.isObjCArray()) 1119 // Using array syntax to assigning to what global points to is not 1120 // same as assigning to the global itself. {id *G;} G[i] = 0; 1121 LV.setGlobalObjCRef(false); 1122 return; 1123 } 1124 1125 if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) { 1126 setObjCGCLValueClass(Ctx, Exp->getBase(), LV); 1127 // We don't know if member is an 'ivar', but this flag is looked at 1128 // only in the context of LV.isObjCIvar(). 1129 LV.setObjCArray(E->getType()->isArrayType()); 1130 return; 1131 } 1132} 1133 1134static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF, 1135 const Expr *E, const VarDecl *VD) { 1136 assert((VD->hasExternalStorage() || VD->isFileVarDecl()) && 1137 "Var decl must have external storage or be a file var decl!"); 1138 1139 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD); 1140 if (VD->getType()->isReferenceType()) 1141 V = CGF.Builder.CreateLoad(V, "tmp"); 1142 unsigned Alignment = CGF.getContext().getDeclAlign(VD).getQuantity(); 1143 LValue LV = CGF.MakeAddrLValue(V, E->getType(), Alignment); 1144 setObjCGCLValueClass(CGF.getContext(), E, LV); 1145 return LV; 1146} 1147 1148static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, 1149 const Expr *E, const FunctionDecl *FD) { 1150 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD); 1151 if (!FD->hasPrototype()) { 1152 if (const FunctionProtoType *Proto = 1153 FD->getType()->getAs<FunctionProtoType>()) { 1154 // Ugly case: for a K&R-style definition, the type of the definition 1155 // isn't the same as the type of a use. Correct for this with a 1156 // bitcast. 1157 QualType NoProtoType = 1158 CGF.getContext().getFunctionNoProtoType(Proto->getResultType()); 1159 NoProtoType = CGF.getContext().getPointerType(NoProtoType); 1160 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType), "tmp"); 1161 } 1162 } 1163 unsigned Alignment = CGF.getContext().getDeclAlign(FD).getQuantity(); 1164 return CGF.MakeAddrLValue(V, E->getType(), Alignment); 1165} 1166 1167LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) { 1168 const NamedDecl *ND = E->getDecl(); 1169 unsigned Alignment = getContext().getDeclAlign(ND).getQuantity(); 1170 1171 if (ND->hasAttr<WeakRefAttr>()) { 1172 const ValueDecl *VD = cast<ValueDecl>(ND); 1173 llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD); 1174 return MakeAddrLValue(Aliasee, E->getType(), Alignment); 1175 } 1176 1177 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) { 1178 1179 // Check if this is a global variable. 1180 if (VD->hasExternalStorage() || VD->isFileVarDecl()) 1181 return EmitGlobalVarDeclLValue(*this, E, VD); 1182 1183 bool NonGCable = VD->hasLocalStorage() && 1184 !VD->getType()->isReferenceType() && 1185 !VD->hasAttr<BlocksAttr>(); 1186 1187 llvm::Value *V = LocalDeclMap[VD]; 1188 if (!V && VD->isStaticLocal()) 1189 V = CGM.getStaticLocalDeclAddress(VD); 1190 assert(V && "DeclRefExpr not entered in LocalDeclMap?"); 1191 1192 if (VD->hasAttr<BlocksAttr>()) 1193 V = BuildBlockByrefAddress(V, VD); 1194 1195 if (VD->getType()->isReferenceType()) 1196 V = Builder.CreateLoad(V, "tmp"); 1197 1198 LValue LV = MakeAddrLValue(V, E->getType(), Alignment); 1199 if (NonGCable) { 1200 LV.getQuals().removeObjCGCAttr(); 1201 LV.setNonGC(true); 1202 } 1203 setObjCGCLValueClass(getContext(), E, LV); 1204 return LV; 1205 } 1206 1207 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) 1208 return EmitFunctionDeclLValue(*this, E, fn); 1209 1210 assert(false && "Unhandled DeclRefExpr"); 1211 1212 // an invalid LValue, but the assert will 1213 // ensure that this point is never reached. 1214 return LValue(); 1215} 1216 1217LValue CodeGenFunction::EmitBlockDeclRefLValue(const BlockDeclRefExpr *E) { 1218 unsigned Alignment = 1219 getContext().getDeclAlign(E->getDecl()).getQuantity(); 1220 return MakeAddrLValue(GetAddrOfBlockDecl(E), E->getType(), Alignment); 1221} 1222 1223LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) { 1224 // __extension__ doesn't affect lvalue-ness. 1225 if (E->getOpcode() == UO_Extension) 1226 return EmitLValue(E->getSubExpr()); 1227 1228 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType()); 1229 switch (E->getOpcode()) { 1230 default: assert(0 && "Unknown unary operator lvalue!"); 1231 case UO_Deref: { 1232 QualType T = E->getSubExpr()->getType()->getPointeeType(); 1233 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type"); 1234 1235 LValue LV = MakeAddrLValue(EmitScalarExpr(E->getSubExpr()), T); 1236 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace()); 1237 1238 // We should not generate __weak write barrier on indirect reference 1239 // of a pointer to object; as in void foo (__weak id *param); *param = 0; 1240 // But, we continue to generate __strong write barrier on indirect write 1241 // into a pointer to object. 1242 if (getContext().getLangOptions().ObjC1 && 1243 getContext().getLangOptions().getGCMode() != LangOptions::NonGC && 1244 LV.isObjCWeak()) 1245 LV.setNonGC(!E->isOBJCGCCandidate(getContext())); 1246 return LV; 1247 } 1248 case UO_Real: 1249 case UO_Imag: { 1250 LValue LV = EmitLValue(E->getSubExpr()); 1251 assert(LV.isSimple() && "real/imag on non-ordinary l-value"); 1252 llvm::Value *Addr = LV.getAddress(); 1253 1254 // real and imag are valid on scalars. This is a faster way of 1255 // testing that. 1256 if (!cast<llvm::PointerType>(Addr->getType()) 1257 ->getElementType()->isStructTy()) { 1258 assert(E->getSubExpr()->getType()->isArithmeticType()); 1259 return LV; 1260 } 1261 1262 assert(E->getSubExpr()->getType()->isAnyComplexType()); 1263 1264 unsigned Idx = E->getOpcode() == UO_Imag; 1265 return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(), 1266 Idx, "idx"), 1267 ExprTy); 1268 } 1269 case UO_PreInc: 1270 case UO_PreDec: { 1271 LValue LV = EmitLValue(E->getSubExpr()); 1272 bool isInc = E->getOpcode() == UO_PreInc; 1273 1274 if (E->getType()->isAnyComplexType()) 1275 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/); 1276 else 1277 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/); 1278 return LV; 1279 } 1280 } 1281} 1282 1283LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) { 1284 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E), 1285 E->getType()); 1286} 1287 1288LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) { 1289 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E), 1290 E->getType()); 1291} 1292 1293 1294LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) { 1295 switch (E->getIdentType()) { 1296 default: 1297 return EmitUnsupportedLValue(E, "predefined expression"); 1298 1299 case PredefinedExpr::Func: 1300 case PredefinedExpr::Function: 1301 case PredefinedExpr::PrettyFunction: { 1302 unsigned Type = E->getIdentType(); 1303 std::string GlobalVarName; 1304 1305 switch (Type) { 1306 default: assert(0 && "Invalid type"); 1307 case PredefinedExpr::Func: 1308 GlobalVarName = "__func__."; 1309 break; 1310 case PredefinedExpr::Function: 1311 GlobalVarName = "__FUNCTION__."; 1312 break; 1313 case PredefinedExpr::PrettyFunction: 1314 GlobalVarName = "__PRETTY_FUNCTION__."; 1315 break; 1316 } 1317 1318 llvm::StringRef FnName = CurFn->getName(); 1319 if (FnName.startswith("\01")) 1320 FnName = FnName.substr(1); 1321 GlobalVarName += FnName; 1322 1323 const Decl *CurDecl = CurCodeDecl; 1324 if (CurDecl == 0) 1325 CurDecl = getContext().getTranslationUnitDecl(); 1326 1327 std::string FunctionName = 1328 (isa<BlockDecl>(CurDecl) 1329 ? FnName.str() 1330 : PredefinedExpr::ComputeName((PredefinedExpr::IdentType)Type, CurDecl)); 1331 1332 llvm::Constant *C = 1333 CGM.GetAddrOfConstantCString(FunctionName, GlobalVarName.c_str()); 1334 return MakeAddrLValue(C, E->getType()); 1335 } 1336 } 1337} 1338 1339llvm::BasicBlock *CodeGenFunction::getTrapBB() { 1340 const CodeGenOptions &GCO = CGM.getCodeGenOpts(); 1341 1342 // If we are not optimzing, don't collapse all calls to trap in the function 1343 // to the same call, that way, in the debugger they can see which operation 1344 // did in fact fail. If we are optimizing, we collapse all calls to trap down 1345 // to just one per function to save on codesize. 1346 if (GCO.OptimizationLevel && TrapBB) 1347 return TrapBB; 1348 1349 llvm::BasicBlock *Cont = 0; 1350 if (HaveInsertPoint()) { 1351 Cont = createBasicBlock("cont"); 1352 EmitBranch(Cont); 1353 } 1354 TrapBB = createBasicBlock("trap"); 1355 EmitBlock(TrapBB); 1356 1357 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap, 0, 0); 1358 llvm::CallInst *TrapCall = Builder.CreateCall(F); 1359 TrapCall->setDoesNotReturn(); 1360 TrapCall->setDoesNotThrow(); 1361 Builder.CreateUnreachable(); 1362 1363 if (Cont) 1364 EmitBlock(Cont); 1365 return TrapBB; 1366} 1367 1368/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an 1369/// array to pointer, return the array subexpression. 1370static const Expr *isSimpleArrayDecayOperand(const Expr *E) { 1371 // If this isn't just an array->pointer decay, bail out. 1372 const CastExpr *CE = dyn_cast<CastExpr>(E); 1373 if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay) 1374 return 0; 1375 1376 // If this is a decay from variable width array, bail out. 1377 const Expr *SubExpr = CE->getSubExpr(); 1378 if (SubExpr->getType()->isVariableArrayType()) 1379 return 0; 1380 1381 return SubExpr; 1382} 1383 1384LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) { 1385 // The index must always be an integer, which is not an aggregate. Emit it. 1386 llvm::Value *Idx = EmitScalarExpr(E->getIdx()); 1387 QualType IdxTy = E->getIdx()->getType(); 1388 bool IdxSigned = IdxTy->isSignedIntegerType(); 1389 1390 // If the base is a vector type, then we are forming a vector element lvalue 1391 // with this subscript. 1392 if (E->getBase()->getType()->isVectorType()) { 1393 // Emit the vector as an lvalue to get its address. 1394 LValue LHS = EmitLValue(E->getBase()); 1395 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!"); 1396 Idx = Builder.CreateIntCast(Idx, Int32Ty, IdxSigned, "vidx"); 1397 return LValue::MakeVectorElt(LHS.getAddress(), Idx, 1398 E->getBase()->getType().getCVRQualifiers()); 1399 } 1400 1401 // Extend or truncate the index type to 32 or 64-bits. 1402 if (Idx->getType() != IntPtrTy) 1403 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom"); 1404 1405 // FIXME: As llvm implements the object size checking, this can come out. 1406 if (CatchUndefined) { 1407 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E->getBase())){ 1408 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) { 1409 if (ICE->getCastKind() == CK_ArrayToPointerDecay) { 1410 if (const ConstantArrayType *CAT 1411 = getContext().getAsConstantArrayType(DRE->getType())) { 1412 llvm::APInt Size = CAT->getSize(); 1413 llvm::BasicBlock *Cont = createBasicBlock("cont"); 1414 Builder.CreateCondBr(Builder.CreateICmpULE(Idx, 1415 llvm::ConstantInt::get(Idx->getType(), Size)), 1416 Cont, getTrapBB()); 1417 EmitBlock(Cont); 1418 } 1419 } 1420 } 1421 } 1422 } 1423 1424 // We know that the pointer points to a type of the correct size, unless the 1425 // size is a VLA or Objective-C interface. 1426 llvm::Value *Address = 0; 1427 unsigned ArrayAlignment = 0; 1428 if (const VariableArrayType *VAT = 1429 getContext().getAsVariableArrayType(E->getType())) { 1430 llvm::Value *VLASize = GetVLASize(VAT); 1431 1432 Idx = Builder.CreateMul(Idx, VLASize); 1433 1434 // The base must be a pointer, which is not an aggregate. Emit it. 1435 llvm::Value *Base = EmitScalarExpr(E->getBase()); 1436 1437 Address = EmitCastToVoidPtr(Base); 1438 if (getContext().getLangOptions().isSignedOverflowDefined()) 1439 Address = Builder.CreateGEP(Address, Idx, "arrayidx"); 1440 else 1441 Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx"); 1442 Address = Builder.CreateBitCast(Address, Base->getType()); 1443 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){ 1444 // Indexing over an interface, as in "NSString *P; P[4];" 1445 llvm::Value *InterfaceSize = 1446 llvm::ConstantInt::get(Idx->getType(), 1447 getContext().getTypeSizeInChars(OIT).getQuantity()); 1448 1449 Idx = Builder.CreateMul(Idx, InterfaceSize); 1450 1451 // The base must be a pointer, which is not an aggregate. Emit it. 1452 llvm::Value *Base = EmitScalarExpr(E->getBase()); 1453 Address = EmitCastToVoidPtr(Base); 1454 Address = Builder.CreateGEP(Address, Idx, "arrayidx"); 1455 Address = Builder.CreateBitCast(Address, Base->getType()); 1456 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) { 1457 // If this is A[i] where A is an array, the frontend will have decayed the 1458 // base to be a ArrayToPointerDecay implicit cast. While correct, it is 1459 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a 1460 // "gep x, i" here. Emit one "gep A, 0, i". 1461 assert(Array->getType()->isArrayType() && 1462 "Array to pointer decay must have array source type!"); 1463 LValue ArrayLV = EmitLValue(Array); 1464 llvm::Value *ArrayPtr = ArrayLV.getAddress(); 1465 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0); 1466 llvm::Value *Args[] = { Zero, Idx }; 1467 1468 // Propagate the alignment from the array itself to the result. 1469 ArrayAlignment = ArrayLV.getAlignment(); 1470 1471 if (getContext().getLangOptions().isSignedOverflowDefined()) 1472 Address = Builder.CreateGEP(ArrayPtr, Args, Args+2, "arrayidx"); 1473 else 1474 Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, Args+2, "arrayidx"); 1475 } else { 1476 // The base must be a pointer, which is not an aggregate. Emit it. 1477 llvm::Value *Base = EmitScalarExpr(E->getBase()); 1478 if (getContext().getLangOptions().isSignedOverflowDefined()) 1479 Address = Builder.CreateGEP(Base, Idx, "arrayidx"); 1480 else 1481 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx"); 1482 } 1483 1484 QualType T = E->getBase()->getType()->getPointeeType(); 1485 assert(!T.isNull() && 1486 "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type"); 1487 1488 LValue LV = MakeAddrLValue(Address, T, ArrayAlignment); 1489 LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace()); 1490 1491 if (getContext().getLangOptions().ObjC1 && 1492 getContext().getLangOptions().getGCMode() != LangOptions::NonGC) { 1493 LV.setNonGC(!E->isOBJCGCCandidate(getContext())); 1494 setObjCGCLValueClass(getContext(), E, LV); 1495 } 1496 return LV; 1497} 1498 1499static 1500llvm::Constant *GenerateConstantVector(llvm::LLVMContext &VMContext, 1501 llvm::SmallVector<unsigned, 4> &Elts) { 1502 llvm::SmallVector<llvm::Constant*, 4> CElts; 1503 1504 const llvm::Type *Int32Ty = llvm::Type::getInt32Ty(VMContext); 1505 for (unsigned i = 0, e = Elts.size(); i != e; ++i) 1506 CElts.push_back(llvm::ConstantInt::get(Int32Ty, Elts[i])); 1507 1508 return llvm::ConstantVector::get(CElts); 1509} 1510 1511LValue CodeGenFunction:: 1512EmitExtVectorElementExpr(const ExtVectorElementExpr *E) { 1513 // Emit the base vector as an l-value. 1514 LValue Base; 1515 1516 // ExtVectorElementExpr's base can either be a vector or pointer to vector. 1517 if (E->isArrow()) { 1518 // If it is a pointer to a vector, emit the address and form an lvalue with 1519 // it. 1520 llvm::Value *Ptr = EmitScalarExpr(E->getBase()); 1521 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>(); 1522 Base = MakeAddrLValue(Ptr, PT->getPointeeType()); 1523 Base.getQuals().removeObjCGCAttr(); 1524 } else if (E->getBase()->isGLValue()) { 1525 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x), 1526 // emit the base as an lvalue. 1527 assert(E->getBase()->getType()->isVectorType()); 1528 Base = EmitLValue(E->getBase()); 1529 } else { 1530 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such. 1531 assert(E->getBase()->getType()->getAs<VectorType>() && 1532 "Result must be a vector"); 1533 llvm::Value *Vec = EmitScalarExpr(E->getBase()); 1534 1535 // Store the vector to memory (because LValue wants an address). 1536 llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType()); 1537 Builder.CreateStore(Vec, VecMem); 1538 Base = MakeAddrLValue(VecMem, E->getBase()->getType()); 1539 } 1540 1541 // Encode the element access list into a vector of unsigned indices. 1542 llvm::SmallVector<unsigned, 4> Indices; 1543 E->getEncodedElementAccess(Indices); 1544 1545 if (Base.isSimple()) { 1546 llvm::Constant *CV = GenerateConstantVector(getLLVMContext(), Indices); 1547 return LValue::MakeExtVectorElt(Base.getAddress(), CV, 1548 Base.getVRQualifiers()); 1549 } 1550 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!"); 1551 1552 llvm::Constant *BaseElts = Base.getExtVectorElts(); 1553 llvm::SmallVector<llvm::Constant *, 4> CElts; 1554 1555 for (unsigned i = 0, e = Indices.size(); i != e; ++i) { 1556 if (isa<llvm::ConstantAggregateZero>(BaseElts)) 1557 CElts.push_back(llvm::ConstantInt::get(Int32Ty, 0)); 1558 else 1559 CElts.push_back(cast<llvm::Constant>(BaseElts->getOperand(Indices[i]))); 1560 } 1561 llvm::Constant *CV = llvm::ConstantVector::get(CElts); 1562 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, 1563 Base.getVRQualifiers()); 1564} 1565 1566LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) { 1567 bool isNonGC = false; 1568 Expr *BaseExpr = E->getBase(); 1569 llvm::Value *BaseValue = NULL; 1570 Qualifiers BaseQuals; 1571 1572 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 1573 if (E->isArrow()) { 1574 BaseValue = EmitScalarExpr(BaseExpr); 1575 const PointerType *PTy = 1576 BaseExpr->getType()->getAs<PointerType>(); 1577 BaseQuals = PTy->getPointeeType().getQualifiers(); 1578 } else { 1579 LValue BaseLV = EmitLValue(BaseExpr); 1580 if (BaseLV.isNonGC()) 1581 isNonGC = true; 1582 // FIXME: this isn't right for bitfields. 1583 BaseValue = BaseLV.getAddress(); 1584 QualType BaseTy = BaseExpr->getType(); 1585 BaseQuals = BaseTy.getQualifiers(); 1586 } 1587 1588 NamedDecl *ND = E->getMemberDecl(); 1589 if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) { 1590 LValue LV = EmitLValueForField(BaseValue, Field, 1591 BaseQuals.getCVRQualifiers()); 1592 LV.setNonGC(isNonGC); 1593 setObjCGCLValueClass(getContext(), E, LV); 1594 return LV; 1595 } 1596 1597 if (VarDecl *VD = dyn_cast<VarDecl>(ND)) 1598 return EmitGlobalVarDeclLValue(*this, E, VD); 1599 1600 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) 1601 return EmitFunctionDeclLValue(*this, E, FD); 1602 1603 assert(false && "Unhandled member declaration!"); 1604 return LValue(); 1605} 1606 1607LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value *BaseValue, 1608 const FieldDecl *Field, 1609 unsigned CVRQualifiers) { 1610 const CGRecordLayout &RL = 1611 CGM.getTypes().getCGRecordLayout(Field->getParent()); 1612 const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field); 1613 return LValue::MakeBitfield(BaseValue, Info, 1614 Field->getType().getCVRQualifiers()|CVRQualifiers); 1615} 1616 1617/// EmitLValueForAnonRecordField - Given that the field is a member of 1618/// an anonymous struct or union buried inside a record, and given 1619/// that the base value is a pointer to the enclosing record, derive 1620/// an lvalue for the ultimate field. 1621LValue CodeGenFunction::EmitLValueForAnonRecordField(llvm::Value *BaseValue, 1622 const IndirectFieldDecl *Field, 1623 unsigned CVRQualifiers) { 1624 IndirectFieldDecl::chain_iterator I = Field->chain_begin(), 1625 IEnd = Field->chain_end(); 1626 while (true) { 1627 LValue LV = EmitLValueForField(BaseValue, cast<FieldDecl>(*I), CVRQualifiers); 1628 if (++I == IEnd) return LV; 1629 1630 assert(LV.isSimple()); 1631 BaseValue = LV.getAddress(); 1632 CVRQualifiers |= LV.getVRQualifiers(); 1633 } 1634} 1635 1636LValue CodeGenFunction::EmitLValueForField(llvm::Value *baseAddr, 1637 const FieldDecl *field, 1638 unsigned cvr) { 1639 if (field->isBitField()) 1640 return EmitLValueForBitfield(baseAddr, field, cvr); 1641 1642 const RecordDecl *rec = field->getParent(); 1643 QualType type = field->getType(); 1644 1645 bool mayAlias = rec->hasAttr<MayAliasAttr>(); 1646 1647 llvm::Value *addr; 1648 if (rec->isUnion()) { 1649 // For unions, we just cast to the appropriate type. 1650 assert(!type->isReferenceType() && "union has reference member"); 1651 1652 const llvm::Type *llvmType = CGM.getTypes().ConvertTypeForMem(type); 1653 unsigned AS = 1654 cast<llvm::PointerType>(baseAddr->getType())->getAddressSpace(); 1655 addr = Builder.CreateBitCast(baseAddr, llvmType->getPointerTo(AS), 1656 field->getName()); 1657 } else { 1658 // For structs, we GEP to the field that the record layout suggests. 1659 unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field); 1660 addr = Builder.CreateStructGEP(baseAddr, idx, field->getName()); 1661 1662 // If this is a reference field, load the reference right now. 1663 if (const ReferenceType *refType = type->getAs<ReferenceType>()) { 1664 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref"); 1665 if (cvr & Qualifiers::Volatile) load->setVolatile(true); 1666 1667 if (CGM.shouldUseTBAA()) { 1668 llvm::MDNode *tbaa; 1669 if (mayAlias) 1670 tbaa = CGM.getTBAAInfo(getContext().CharTy); 1671 else 1672 tbaa = CGM.getTBAAInfo(type); 1673 CGM.DecorateInstruction(load, tbaa); 1674 } 1675 1676 addr = load; 1677 mayAlias = false; 1678 type = refType->getPointeeType(); 1679 cvr = 0; // qualifiers don't recursively apply to referencee 1680 } 1681 } 1682 1683 unsigned alignment = getContext().getDeclAlign(field).getQuantity(); 1684 LValue LV = MakeAddrLValue(addr, type, alignment); 1685 LV.getQuals().addCVRQualifiers(cvr); 1686 1687 // __weak attribute on a field is ignored. 1688 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak) 1689 LV.getQuals().removeObjCGCAttr(); 1690 1691 // Fields of may_alias structs act like 'char' for TBAA purposes. 1692 // FIXME: this should get propagated down through anonymous structs 1693 // and unions. 1694 if (mayAlias && LV.getTBAAInfo()) 1695 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy)); 1696 1697 return LV; 1698} 1699 1700LValue 1701CodeGenFunction::EmitLValueForFieldInitialization(llvm::Value *BaseValue, 1702 const FieldDecl *Field, 1703 unsigned CVRQualifiers) { 1704 QualType FieldType = Field->getType(); 1705 1706 if (!FieldType->isReferenceType()) 1707 return EmitLValueForField(BaseValue, Field, CVRQualifiers); 1708 1709 const CGRecordLayout &RL = 1710 CGM.getTypes().getCGRecordLayout(Field->getParent()); 1711 unsigned idx = RL.getLLVMFieldNo(Field); 1712 llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp"); 1713 1714 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs"); 1715 1716 unsigned Alignment = getContext().getDeclAlign(Field).getQuantity(); 1717 return MakeAddrLValue(V, FieldType, Alignment); 1718} 1719 1720LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){ 1721 llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral"); 1722 const Expr *InitExpr = E->getInitializer(); 1723 LValue Result = MakeAddrLValue(DeclPtr, E->getType()); 1724 1725 EmitAnyExprToMem(InitExpr, DeclPtr, /*Volatile*/ false, /*Init*/ true); 1726 1727 return Result; 1728} 1729 1730LValue CodeGenFunction:: 1731EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) { 1732 if (!expr->isGLValue()) { 1733 // ?: here should be an aggregate. 1734 assert((hasAggregateLLVMType(expr->getType()) && 1735 !expr->getType()->isAnyComplexType()) && 1736 "Unexpected conditional operator!"); 1737 return EmitAggExprToLValue(expr); 1738 } 1739 1740 const Expr *condExpr = expr->getCond(); 1741 bool CondExprBool; 1742 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) { 1743 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr(); 1744 if (!CondExprBool) std::swap(live, dead); 1745 1746 if (!ContainsLabel(dead)) 1747 return EmitLValue(live); 1748 } 1749 1750 OpaqueValueMapping binding(*this, expr); 1751 1752 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true"); 1753 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false"); 1754 llvm::BasicBlock *contBlock = createBasicBlock("cond.end"); 1755 1756 ConditionalEvaluation eval(*this); 1757 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock); 1758 1759 // Any temporaries created here are conditional. 1760 EmitBlock(lhsBlock); 1761 eval.begin(*this); 1762 LValue lhs = EmitLValue(expr->getTrueExpr()); 1763 eval.end(*this); 1764 1765 if (!lhs.isSimple()) 1766 return EmitUnsupportedLValue(expr, "conditional operator"); 1767 1768 lhsBlock = Builder.GetInsertBlock(); 1769 Builder.CreateBr(contBlock); 1770 1771 // Any temporaries created here are conditional. 1772 EmitBlock(rhsBlock); 1773 eval.begin(*this); 1774 LValue rhs = EmitLValue(expr->getFalseExpr()); 1775 eval.end(*this); 1776 if (!rhs.isSimple()) 1777 return EmitUnsupportedLValue(expr, "conditional operator"); 1778 rhsBlock = Builder.GetInsertBlock(); 1779 1780 EmitBlock(contBlock); 1781 1782 llvm::PHINode *phi = Builder.CreatePHI(lhs.getAddress()->getType(), 2, 1783 "cond-lvalue"); 1784 phi->addIncoming(lhs.getAddress(), lhsBlock); 1785 phi->addIncoming(rhs.getAddress(), rhsBlock); 1786 return MakeAddrLValue(phi, expr->getType()); 1787} 1788 1789/// EmitCastLValue - Casts are never lvalues unless that cast is a dynamic_cast. 1790/// If the cast is a dynamic_cast, we can have the usual lvalue result, 1791/// otherwise if a cast is needed by the code generator in an lvalue context, 1792/// then it must mean that we need the address of an aggregate in order to 1793/// access one of its fields. This can happen for all the reasons that casts 1794/// are permitted with aggregate result, including noop aggregate casts, and 1795/// cast from scalar to union. 1796LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) { 1797 switch (E->getCastKind()) { 1798 case CK_ToVoid: 1799 return EmitUnsupportedLValue(E, "unexpected cast lvalue"); 1800 1801 case CK_Dependent: 1802 llvm_unreachable("dependent cast kind in IR gen!"); 1803 1804 case CK_GetObjCProperty: { 1805 LValue LV = EmitLValue(E->getSubExpr()); 1806 assert(LV.isPropertyRef()); 1807 RValue RV = EmitLoadOfPropertyRefLValue(LV); 1808 1809 // Property is an aggregate r-value. 1810 if (RV.isAggregate()) { 1811 return MakeAddrLValue(RV.getAggregateAddr(), E->getType()); 1812 } 1813 1814 // Implicit property returns an l-value. 1815 assert(RV.isScalar()); 1816 return MakeAddrLValue(RV.getScalarVal(), E->getSubExpr()->getType()); 1817 } 1818 1819 case CK_NoOp: 1820 case CK_LValueToRValue: 1821 if (!E->getSubExpr()->Classify(getContext()).isPRValue() 1822 || E->getType()->isRecordType()) 1823 return EmitLValue(E->getSubExpr()); 1824 // Fall through to synthesize a temporary. 1825 1826 case CK_BitCast: 1827 case CK_ArrayToPointerDecay: 1828 case CK_FunctionToPointerDecay: 1829 case CK_NullToMemberPointer: 1830 case CK_NullToPointer: 1831 case CK_IntegralToPointer: 1832 case CK_PointerToIntegral: 1833 case CK_PointerToBoolean: 1834 case CK_VectorSplat: 1835 case CK_IntegralCast: 1836 case CK_IntegralToBoolean: 1837 case CK_IntegralToFloating: 1838 case CK_FloatingToIntegral: 1839 case CK_FloatingToBoolean: 1840 case CK_FloatingCast: 1841 case CK_FloatingRealToComplex: 1842 case CK_FloatingComplexToReal: 1843 case CK_FloatingComplexToBoolean: 1844 case CK_FloatingComplexCast: 1845 case CK_FloatingComplexToIntegralComplex: 1846 case CK_IntegralRealToComplex: 1847 case CK_IntegralComplexToReal: 1848 case CK_IntegralComplexToBoolean: 1849 case CK_IntegralComplexCast: 1850 case CK_IntegralComplexToFloatingComplex: 1851 case CK_DerivedToBaseMemberPointer: 1852 case CK_BaseToDerivedMemberPointer: 1853 case CK_MemberPointerToBoolean: 1854 case CK_AnyPointerToBlockPointerCast: { 1855 // These casts only produce lvalues when we're binding a reference to a 1856 // temporary realized from a (converted) pure rvalue. Emit the expression 1857 // as a value, copy it into a temporary, and return an lvalue referring to 1858 // that temporary. 1859 llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp"); 1860 EmitAnyExprToMem(E, V, false, false); 1861 return MakeAddrLValue(V, E->getType()); 1862 } 1863 1864 case CK_Dynamic: { 1865 LValue LV = EmitLValue(E->getSubExpr()); 1866 llvm::Value *V = LV.getAddress(); 1867 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E); 1868 return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType()); 1869 } 1870 1871 case CK_ConstructorConversion: 1872 case CK_UserDefinedConversion: 1873 case CK_AnyPointerToObjCPointerCast: 1874 return EmitLValue(E->getSubExpr()); 1875 1876 case CK_UncheckedDerivedToBase: 1877 case CK_DerivedToBase: { 1878 const RecordType *DerivedClassTy = 1879 E->getSubExpr()->getType()->getAs<RecordType>(); 1880 CXXRecordDecl *DerivedClassDecl = 1881 cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 1882 1883 LValue LV = EmitLValue(E->getSubExpr()); 1884 llvm::Value *This = LV.getAddress(); 1885 1886 // Perform the derived-to-base conversion 1887 llvm::Value *Base = 1888 GetAddressOfBaseClass(This, DerivedClassDecl, 1889 E->path_begin(), E->path_end(), 1890 /*NullCheckValue=*/false); 1891 1892 return MakeAddrLValue(Base, E->getType()); 1893 } 1894 case CK_ToUnion: 1895 return EmitAggExprToLValue(E); 1896 case CK_BaseToDerived: { 1897 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>(); 1898 CXXRecordDecl *DerivedClassDecl = 1899 cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 1900 1901 LValue LV = EmitLValue(E->getSubExpr()); 1902 1903 // Perform the base-to-derived conversion 1904 llvm::Value *Derived = 1905 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl, 1906 E->path_begin(), E->path_end(), 1907 /*NullCheckValue=*/false); 1908 1909 return MakeAddrLValue(Derived, E->getType()); 1910 } 1911 case CK_LValueBitCast: { 1912 // This must be a reinterpret_cast (or c-style equivalent). 1913 const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E); 1914 1915 LValue LV = EmitLValue(E->getSubExpr()); 1916 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(), 1917 ConvertType(CE->getTypeAsWritten())); 1918 return MakeAddrLValue(V, E->getType()); 1919 } 1920 case CK_ObjCObjectLValueCast: { 1921 LValue LV = EmitLValue(E->getSubExpr()); 1922 QualType ToType = getContext().getLValueReferenceType(E->getType()); 1923 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(), 1924 ConvertType(ToType)); 1925 return MakeAddrLValue(V, E->getType()); 1926 } 1927 } 1928 1929 llvm_unreachable("Unhandled lvalue cast kind?"); 1930} 1931 1932LValue CodeGenFunction::EmitNullInitializationLValue( 1933 const CXXScalarValueInitExpr *E) { 1934 QualType Ty = E->getType(); 1935 LValue LV = MakeAddrLValue(CreateMemTemp(Ty), Ty); 1936 EmitNullInitialization(LV.getAddress(), Ty); 1937 return LV; 1938} 1939 1940LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) { 1941 assert(e->isGLValue() || e->getType()->isRecordType()); 1942 return getOpaqueLValueMapping(e); 1943} 1944 1945//===--------------------------------------------------------------------===// 1946// Expression Emission 1947//===--------------------------------------------------------------------===// 1948 1949 1950RValue CodeGenFunction::EmitCallExpr(const CallExpr *E, 1951 ReturnValueSlot ReturnValue) { 1952 if (CGDebugInfo *DI = getDebugInfo()) { 1953 DI->setLocation(E->getLocStart()); 1954 DI->UpdateLineDirectiveRegion(Builder); 1955 DI->EmitStopPoint(Builder); 1956 } 1957 1958 // Builtins never have block type. 1959 if (E->getCallee()->getType()->isBlockPointerType()) 1960 return EmitBlockCallExpr(E, ReturnValue); 1961 1962 if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E)) 1963 return EmitCXXMemberCallExpr(CE, ReturnValue); 1964 1965 const Decl *TargetDecl = 0; 1966 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E->getCallee())) { 1967 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) { 1968 TargetDecl = DRE->getDecl(); 1969 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(TargetDecl)) 1970 if (unsigned builtinID = FD->getBuiltinID()) 1971 return EmitBuiltinExpr(FD, builtinID, E); 1972 } 1973 } 1974 1975 if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E)) 1976 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl)) 1977 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue); 1978 1979 if (isa<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) { 1980 // C++ [expr.pseudo]p1: 1981 // The result shall only be used as the operand for the function call 1982 // operator (), and the result of such a call has type void. The only 1983 // effect is the evaluation of the postfix-expression before the dot or 1984 // arrow. 1985 EmitScalarExpr(E->getCallee()); 1986 return RValue::get(0); 1987 } 1988 1989 llvm::Value *Callee = EmitScalarExpr(E->getCallee()); 1990 return EmitCall(E->getCallee()->getType(), Callee, ReturnValue, 1991 E->arg_begin(), E->arg_end(), TargetDecl); 1992} 1993 1994LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) { 1995 // Comma expressions just emit their LHS then their RHS as an l-value. 1996 if (E->getOpcode() == BO_Comma) { 1997 EmitIgnoredExpr(E->getLHS()); 1998 EnsureInsertPoint(); 1999 return EmitLValue(E->getRHS()); 2000 } 2001 2002 if (E->getOpcode() == BO_PtrMemD || 2003 E->getOpcode() == BO_PtrMemI) 2004 return EmitPointerToDataMemberBinaryExpr(E); 2005 2006 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value"); 2007 2008 if (!hasAggregateLLVMType(E->getType())) { 2009 // __block variables need the RHS evaluated first. 2010 RValue RV = EmitAnyExpr(E->getRHS()); 2011 LValue LV = EmitLValue(E->getLHS()); 2012 EmitStoreThroughLValue(RV, LV, E->getType()); 2013 return LV; 2014 } 2015 2016 if (E->getType()->isAnyComplexType()) 2017 return EmitComplexAssignmentLValue(E); 2018 2019 return EmitAggExprToLValue(E); 2020} 2021 2022LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) { 2023 RValue RV = EmitCallExpr(E); 2024 2025 if (!RV.isScalar()) 2026 return MakeAddrLValue(RV.getAggregateAddr(), E->getType()); 2027 2028 assert(E->getCallReturnType()->isReferenceType() && 2029 "Can't have a scalar return unless the return type is a " 2030 "reference type!"); 2031 2032 return MakeAddrLValue(RV.getScalarVal(), E->getType()); 2033} 2034 2035LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) { 2036 // FIXME: This shouldn't require another copy. 2037 return EmitAggExprToLValue(E); 2038} 2039 2040LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) { 2041 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor() 2042 && "binding l-value to type which needs a temporary"); 2043 AggValueSlot Slot = CreateAggTemp(E->getType(), "tmp"); 2044 EmitCXXConstructExpr(E, Slot); 2045 return MakeAddrLValue(Slot.getAddr(), E->getType()); 2046} 2047 2048LValue 2049CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) { 2050 return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType()); 2051} 2052 2053LValue 2054CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) { 2055 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue"); 2056 Slot.setLifetimeExternallyManaged(); 2057 EmitAggExpr(E->getSubExpr(), Slot); 2058 EmitCXXTemporary(E->getTemporary(), Slot.getAddr()); 2059 return MakeAddrLValue(Slot.getAddr(), E->getType()); 2060} 2061 2062LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) { 2063 RValue RV = EmitObjCMessageExpr(E); 2064 2065 if (!RV.isScalar()) 2066 return MakeAddrLValue(RV.getAggregateAddr(), E->getType()); 2067 2068 assert(E->getMethodDecl()->getResultType()->isReferenceType() && 2069 "Can't have a scalar return unless the return type is a " 2070 "reference type!"); 2071 2072 return MakeAddrLValue(RV.getScalarVal(), E->getType()); 2073} 2074 2075LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) { 2076 llvm::Value *V = 2077 CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true); 2078 return MakeAddrLValue(V, E->getType()); 2079} 2080 2081llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface, 2082 const ObjCIvarDecl *Ivar) { 2083 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar); 2084} 2085 2086LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy, 2087 llvm::Value *BaseValue, 2088 const ObjCIvarDecl *Ivar, 2089 unsigned CVRQualifiers) { 2090 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue, 2091 Ivar, CVRQualifiers); 2092} 2093 2094LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) { 2095 // FIXME: A lot of the code below could be shared with EmitMemberExpr. 2096 llvm::Value *BaseValue = 0; 2097 const Expr *BaseExpr = E->getBase(); 2098 Qualifiers BaseQuals; 2099 QualType ObjectTy; 2100 if (E->isArrow()) { 2101 BaseValue = EmitScalarExpr(BaseExpr); 2102 ObjectTy = BaseExpr->getType()->getPointeeType(); 2103 BaseQuals = ObjectTy.getQualifiers(); 2104 } else { 2105 LValue BaseLV = EmitLValue(BaseExpr); 2106 // FIXME: this isn't right for bitfields. 2107 BaseValue = BaseLV.getAddress(); 2108 ObjectTy = BaseExpr->getType(); 2109 BaseQuals = ObjectTy.getQualifiers(); 2110 } 2111 2112 LValue LV = 2113 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(), 2114 BaseQuals.getCVRQualifiers()); 2115 setObjCGCLValueClass(getContext(), E, LV); 2116 return LV; 2117} 2118 2119LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) { 2120 // Can only get l-value for message expression returning aggregate type 2121 RValue RV = EmitAnyExprToTemp(E); 2122 return MakeAddrLValue(RV.getAggregateAddr(), E->getType()); 2123} 2124 2125RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee, 2126 ReturnValueSlot ReturnValue, 2127 CallExpr::const_arg_iterator ArgBeg, 2128 CallExpr::const_arg_iterator ArgEnd, 2129 const Decl *TargetDecl) { 2130 // Get the actual function type. The callee type will always be a pointer to 2131 // function type or a block pointer type. 2132 assert(CalleeType->isFunctionPointerType() && 2133 "Call must have function pointer type!"); 2134 2135 CalleeType = getContext().getCanonicalType(CalleeType); 2136 2137 const FunctionType *FnType 2138 = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType()); 2139 2140 CallArgList Args; 2141 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd); 2142 2143 return EmitCall(CGM.getTypes().getFunctionInfo(Args, FnType), 2144 Callee, ReturnValue, Args, TargetDecl); 2145} 2146 2147LValue CodeGenFunction:: 2148EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) { 2149 llvm::Value *BaseV; 2150 if (E->getOpcode() == BO_PtrMemI) 2151 BaseV = EmitScalarExpr(E->getLHS()); 2152 else 2153 BaseV = EmitLValue(E->getLHS()).getAddress(); 2154 2155 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS()); 2156 2157 const MemberPointerType *MPT 2158 = E->getRHS()->getType()->getAs<MemberPointerType>(); 2159 2160 llvm::Value *AddV = 2161 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, BaseV, OffsetV, MPT); 2162 2163 return MakeAddrLValue(AddV, MPT->getPointeeType()); 2164} 2165