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