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