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 "CGObjCRuntime.h" 18 #include "clang/AST/ASTContext.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "llvm/Target/TargetData.h" 21 using namespace clang; 22 using namespace CodeGen; 23 24 //===--------------------------------------------------------------------===// 25 // Miscellaneous Helper Methods 26 //===--------------------------------------------------------------------===// 27 28 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 29 /// block. 30 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty, 31 const char *Name) { 32 if (!Builder.isNamePreserving()) 33 Name = ""; 34 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt); 35 } 36 37 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 38 /// expression and compare the result against zero, returning an Int1Ty value. 39 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) { 40 QualType BoolTy = getContext().BoolTy; 41 if (!E->getType()->isAnyComplexType()) 42 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy); 43 44 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy); 45 } 46 47 /// EmitAnyExpr - Emit code to compute the specified expression which can have 48 /// any type. The result is returned as an RValue struct. If this is an 49 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where the 50 /// result should be returned. 51 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, llvm::Value *AggLoc, 52 bool IsAggLocVolatile, bool IgnoreResult, 53 bool IsInitializer) { 54 if (!hasAggregateLLVMType(E->getType())) 55 return RValue::get(EmitScalarExpr(E, IgnoreResult)); 56 else if (E->getType()->isAnyComplexType()) 57 return RValue::getComplex(EmitComplexExpr(E, false, false, 58 IgnoreResult, IgnoreResult)); 59 60 EmitAggExpr(E, AggLoc, IsAggLocVolatile, IgnoreResult, IsInitializer); 61 return RValue::getAggregate(AggLoc, IsAggLocVolatile); 62 } 63 64 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 65 /// always be accessible even if no aggregate location is provided. 66 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E, 67 bool IsAggLocVolatile, 68 bool IsInitializer) { 69 llvm::Value *AggLoc = 0; 70 71 if (hasAggregateLLVMType(E->getType()) && 72 !E->getType()->isAnyComplexType()) 73 AggLoc = CreateTempAlloca(ConvertType(E->getType()), "agg.tmp"); 74 return EmitAnyExpr(E, AggLoc, IsAggLocVolatile, /*IgnoreResult=*/false, 75 IsInitializer); 76 } 77 78 RValue CodeGenFunction::EmitReferenceBindingToExpr(const Expr* E, 79 QualType DestType, 80 bool IsInitializer) { 81 RValue Val; 82 if (E->isLvalue(getContext()) == Expr::LV_Valid) { 83 // Emit the expr as an lvalue. 84 LValue LV = EmitLValue(E); 85 if (LV.isSimple()) 86 return RValue::get(LV.getAddress()); 87 Val = EmitLoadOfLValue(LV, E->getType()); 88 } else { 89 // FIXME: Initializers don't work with casts yet. For example 90 // const A& a = B(); 91 // if B inherits from A. 92 Val = EmitAnyExprToTemp(E, /*IsAggLocVolatile=*/false, 93 IsInitializer); 94 95 if (IsInitializer) { 96 // We might have to destroy the temporary variable. 97 if (const RecordType *RT = E->getType()->getAs<RecordType>()) { 98 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 99 if (!ClassDecl->hasTrivialDestructor()) { 100 const CXXDestructorDecl *Dtor = 101 ClassDecl->getDestructor(getContext()); 102 103 CleanupScope scope(*this); 104 EmitCXXDestructorCall(Dtor, Dtor_Complete, Val.getAggregateAddr()); 105 } 106 } 107 } 108 } 109 } 110 111 if (Val.isAggregate()) { 112 Val = RValue::get(Val.getAggregateAddr()); 113 } else { 114 // Create a temporary variable that we can bind the reference to. 115 llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(E->getType()), 116 "reftmp"); 117 if (Val.isScalar()) 118 EmitStoreOfScalar(Val.getScalarVal(), Temp, false, E->getType()); 119 else 120 StoreComplexToAddr(Val.getComplexVal(), Temp, false); 121 Val = RValue::get(Temp); 122 } 123 124 return Val; 125 } 126 127 128 /// getAccessedFieldNo - Given an encoded value and a result number, return the 129 /// input field number being accessed. 130 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx, 131 const llvm::Constant *Elts) { 132 if (isa<llvm::ConstantAggregateZero>(Elts)) 133 return 0; 134 135 return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue(); 136 } 137 138 139 //===----------------------------------------------------------------------===// 140 // LValue Expression Emission 141 //===----------------------------------------------------------------------===// 142 143 RValue CodeGenFunction::GetUndefRValue(QualType Ty) { 144 if (Ty->isVoidType()) { 145 return RValue::get(0); 146 } else if (const ComplexType *CTy = Ty->getAsComplexType()) { 147 const llvm::Type *EltTy = ConvertType(CTy->getElementType()); 148 llvm::Value *U = llvm::UndefValue::get(EltTy); 149 return RValue::getComplex(std::make_pair(U, U)); 150 } else if (hasAggregateLLVMType(Ty)) { 151 const llvm::Type *LTy = llvm::PointerType::getUnqual(ConvertType(Ty)); 152 return RValue::getAggregate(llvm::UndefValue::get(LTy)); 153 } else { 154 return RValue::get(llvm::UndefValue::get(ConvertType(Ty))); 155 } 156 } 157 158 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E, 159 const char *Name) { 160 ErrorUnsupported(E, Name); 161 return GetUndefRValue(E->getType()); 162 } 163 164 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E, 165 const char *Name) { 166 ErrorUnsupported(E, Name); 167 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType())); 168 return LValue::MakeAddr(llvm::UndefValue::get(Ty), 169 E->getType().getCVRQualifiers(), 170 getContext().getObjCGCAttrKind(E->getType()), 171 E->getType().getAddressSpace()); 172 } 173 174 /// EmitLValue - Emit code to compute a designator that specifies the location 175 /// of the expression. 176 /// 177 /// This can return one of two things: a simple address or a bitfield reference. 178 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be 179 /// an LLVM pointer type. 180 /// 181 /// If this returns a bitfield reference, nothing about the pointee type of the 182 /// LLVM value is known: For example, it may not be a pointer to an integer. 183 /// 184 /// If this returns a normal address, and if the lvalue's C type is fixed size, 185 /// this method guarantees that the returned pointer type will point to an LLVM 186 /// type of the same size of the lvalue's type. If the lvalue has a variable 187 /// length type, this is not possible. 188 /// 189 LValue CodeGenFunction::EmitLValue(const Expr *E) { 190 switch (E->getStmtClass()) { 191 default: return EmitUnsupportedLValue(E, "l-value expression"); 192 193 case Expr::BinaryOperatorClass: 194 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E)); 195 case Expr::CallExprClass: 196 case Expr::CXXMemberCallExprClass: 197 case Expr::CXXOperatorCallExprClass: 198 return EmitCallExprLValue(cast<CallExpr>(E)); 199 case Expr::VAArgExprClass: 200 return EmitVAArgExprLValue(cast<VAArgExpr>(E)); 201 case Expr::DeclRefExprClass: 202 case Expr::QualifiedDeclRefExprClass: 203 return EmitDeclRefLValue(cast<DeclRefExpr>(E)); 204 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr()); 205 case Expr::PredefinedExprClass: 206 return EmitPredefinedLValue(cast<PredefinedExpr>(E)); 207 case Expr::StringLiteralClass: 208 return EmitStringLiteralLValue(cast<StringLiteral>(E)); 209 case Expr::ObjCEncodeExprClass: 210 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E)); 211 212 case Expr::BlockDeclRefExprClass: 213 return EmitBlockDeclRefLValue(cast<BlockDeclRefExpr>(E)); 214 215 case Expr::CXXConditionDeclExprClass: 216 return EmitCXXConditionDeclLValue(cast<CXXConditionDeclExpr>(E)); 217 case Expr::CXXTemporaryObjectExprClass: 218 case Expr::CXXConstructExprClass: 219 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E)); 220 case Expr::CXXBindTemporaryExprClass: 221 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E)); 222 223 case Expr::ObjCMessageExprClass: 224 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E)); 225 case Expr::ObjCIvarRefExprClass: 226 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E)); 227 case Expr::ObjCPropertyRefExprClass: 228 return EmitObjCPropertyRefLValue(cast<ObjCPropertyRefExpr>(E)); 229 case Expr::ObjCImplicitSetterGetterRefExprClass: 230 return EmitObjCKVCRefLValue(cast<ObjCImplicitSetterGetterRefExpr>(E)); 231 case Expr::ObjCSuperExprClass: 232 return EmitObjCSuperExprLValue(cast<ObjCSuperExpr>(E)); 233 234 case Expr::StmtExprClass: 235 return EmitStmtExprLValue(cast<StmtExpr>(E)); 236 case Expr::UnaryOperatorClass: 237 return EmitUnaryOpLValue(cast<UnaryOperator>(E)); 238 case Expr::ArraySubscriptExprClass: 239 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E)); 240 case Expr::ExtVectorElementExprClass: 241 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E)); 242 case Expr::MemberExprClass: 243 return EmitMemberExpr(cast<MemberExpr>(E)); 244 case Expr::CompoundLiteralExprClass: 245 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E)); 246 case Expr::ConditionalOperatorClass: 247 return EmitConditionalOperator(cast<ConditionalOperator>(E)); 248 case Expr::ChooseExprClass: 249 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext())); 250 case Expr::ImplicitCastExprClass: 251 case Expr::CStyleCastExprClass: 252 case Expr::CXXFunctionalCastExprClass: 253 case Expr::CXXStaticCastExprClass: 254 case Expr::CXXDynamicCastExprClass: 255 case Expr::CXXReinterpretCastExprClass: 256 case Expr::CXXConstCastExprClass: 257 return EmitCastLValue(cast<CastExpr>(E)); 258 } 259 } 260 261 llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, 262 QualType Ty) { 263 llvm::Value *V = Builder.CreateLoad(Addr, Volatile, "tmp"); 264 265 // Bool can have different representation in memory than in registers. 266 if (Ty->isBooleanType()) 267 if (V->getType() != llvm::Type::getInt1Ty(VMContext)) 268 V = Builder.CreateTrunc(V, llvm::Type::getInt1Ty(VMContext), "tobool"); 269 270 return V; 271 } 272 273 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, 274 bool Volatile, QualType Ty) { 275 276 if (Ty->isBooleanType()) { 277 // Bool can have different representation in memory than in registers. 278 const llvm::Type *SrcTy = Value->getType(); 279 const llvm::PointerType *DstPtr = cast<llvm::PointerType>(Addr->getType()); 280 if (DstPtr->getElementType() != SrcTy) { 281 const llvm::Type *MemTy = 282 llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace()); 283 Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp"); 284 } 285 } 286 Builder.CreateStore(Value, Addr, Volatile); 287 } 288 289 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this 290 /// method emits the address of the lvalue, then loads the result as an rvalue, 291 /// returning the rvalue. 292 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) { 293 if (LV.isObjCWeak()) { 294 // load of a __weak object. 295 llvm::Value *AddrWeakObj = LV.getAddress(); 296 llvm::Value *read_weak = CGM.getObjCRuntime().EmitObjCWeakRead(*this, 297 AddrWeakObj); 298 return RValue::get(read_weak); 299 } 300 301 if (LV.isSimple()) { 302 llvm::Value *Ptr = LV.getAddress(); 303 const llvm::Type *EltTy = 304 cast<llvm::PointerType>(Ptr->getType())->getElementType(); 305 306 // Simple scalar l-value. 307 if (EltTy->isSingleValueType()) 308 return RValue::get(EmitLoadOfScalar(Ptr, LV.isVolatileQualified(), 309 ExprType)); 310 311 assert(ExprType->isFunctionType() && "Unknown scalar value"); 312 return RValue::get(Ptr); 313 } 314 315 if (LV.isVectorElt()) { 316 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), 317 LV.isVolatileQualified(), "tmp"); 318 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(), 319 "vecext")); 320 } 321 322 // If this is a reference to a subset of the elements of a vector, either 323 // shuffle the input or extract/insert them as appropriate. 324 if (LV.isExtVectorElt()) 325 return EmitLoadOfExtVectorElementLValue(LV, ExprType); 326 327 if (LV.isBitfield()) 328 return EmitLoadOfBitfieldLValue(LV, ExprType); 329 330 if (LV.isPropertyRef()) 331 return EmitLoadOfPropertyRefLValue(LV, ExprType); 332 333 assert(LV.isKVCRef() && "Unknown LValue type!"); 334 return EmitLoadOfKVCRefLValue(LV, ExprType); 335 } 336 337 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV, 338 QualType ExprType) { 339 unsigned StartBit = LV.getBitfieldStartBit(); 340 unsigned BitfieldSize = LV.getBitfieldSize(); 341 llvm::Value *Ptr = LV.getBitfieldAddr(); 342 343 const llvm::Type *EltTy = 344 cast<llvm::PointerType>(Ptr->getType())->getElementType(); 345 unsigned EltTySize = CGM.getTargetData().getTypeSizeInBits(EltTy); 346 347 // In some cases the bitfield may straddle two memory locations. Currently we 348 // load the entire bitfield, then do the magic to sign-extend it if 349 // necessary. This results in somewhat more code than necessary for the common 350 // case (one load), since two shifts accomplish both the masking and sign 351 // extension. 352 unsigned LowBits = std::min(BitfieldSize, EltTySize - StartBit); 353 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "tmp"); 354 355 // Shift to proper location. 356 if (StartBit) 357 Val = Builder.CreateLShr(Val, llvm::ConstantInt::get(EltTy, StartBit), 358 "bf.lo"); 359 360 // Mask off unused bits. 361 llvm::Constant *LowMask = llvm::ConstantInt::get(VMContext, 362 llvm::APInt::getLowBitsSet(EltTySize, LowBits)); 363 Val = Builder.CreateAnd(Val, LowMask, "bf.lo.cleared"); 364 365 // Fetch the high bits if necessary. 366 if (LowBits < BitfieldSize) { 367 unsigned HighBits = BitfieldSize - LowBits; 368 llvm::Value *HighPtr = Builder.CreateGEP(Ptr, llvm::ConstantInt::get( 369 llvm::Type::getInt32Ty(VMContext), 1), "bf.ptr.hi"); 370 llvm::Value *HighVal = Builder.CreateLoad(HighPtr, 371 LV.isVolatileQualified(), 372 "tmp"); 373 374 // Mask off unused bits. 375 llvm::Constant *HighMask = llvm::ConstantInt::get(VMContext, 376 llvm::APInt::getLowBitsSet(EltTySize, HighBits)); 377 HighVal = Builder.CreateAnd(HighVal, HighMask, "bf.lo.cleared"); 378 379 // Shift to proper location and or in to bitfield value. 380 HighVal = Builder.CreateShl(HighVal, 381 llvm::ConstantInt::get(EltTy, LowBits)); 382 Val = Builder.CreateOr(Val, HighVal, "bf.val"); 383 } 384 385 // Sign extend if necessary. 386 if (LV.isBitfieldSigned()) { 387 llvm::Value *ExtraBits = llvm::ConstantInt::get(EltTy, 388 EltTySize - BitfieldSize); 389 Val = Builder.CreateAShr(Builder.CreateShl(Val, ExtraBits), 390 ExtraBits, "bf.val.sext"); 391 } 392 393 // The bitfield type and the normal type differ when the storage sizes differ 394 // (currently just _Bool). 395 Val = Builder.CreateIntCast(Val, ConvertType(ExprType), false, "tmp"); 396 397 return RValue::get(Val); 398 } 399 400 RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV, 401 QualType ExprType) { 402 return EmitObjCPropertyGet(LV.getPropertyRefExpr()); 403 } 404 405 RValue CodeGenFunction::EmitLoadOfKVCRefLValue(LValue LV, 406 QualType ExprType) { 407 return EmitObjCPropertyGet(LV.getKVCRefExpr()); 408 } 409 410 // If this is a reference to a subset of the elements of a vector, create an 411 // appropriate shufflevector. 412 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV, 413 QualType ExprType) { 414 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(), 415 LV.isVolatileQualified(), "tmp"); 416 417 const llvm::Constant *Elts = LV.getExtVectorElts(); 418 419 // If the result of the expression is a non-vector type, we must be extracting 420 // a single element. Just codegen as an extractelement. 421 const VectorType *ExprVT = ExprType->getAsVectorType(); 422 if (!ExprVT) { 423 unsigned InIdx = getAccessedFieldNo(0, Elts); 424 llvm::Value *Elt = llvm::ConstantInt::get( 425 llvm::Type::getInt32Ty(VMContext), InIdx); 426 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp")); 427 } 428 429 // Always use shuffle vector to try to retain the original program structure 430 unsigned NumResultElts = ExprVT->getNumElements(); 431 432 llvm::SmallVector<llvm::Constant*, 4> Mask; 433 for (unsigned i = 0; i != NumResultElts; ++i) { 434 unsigned InIdx = getAccessedFieldNo(i, Elts); 435 Mask.push_back(llvm::ConstantInt::get( 436 llvm::Type::getInt32Ty(VMContext), InIdx)); 437 } 438 439 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size()); 440 Vec = Builder.CreateShuffleVector(Vec, 441 llvm::UndefValue::get(Vec->getType()), 442 MaskV, "tmp"); 443 return RValue::get(Vec); 444 } 445 446 447 448 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 449 /// lvalue, where both are guaranteed to the have the same type, and that type 450 /// is 'Ty'. 451 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, 452 QualType Ty) { 453 if (!Dst.isSimple()) { 454 if (Dst.isVectorElt()) { 455 // Read/modify/write the vector, inserting the new element. 456 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), 457 Dst.isVolatileQualified(), "tmp"); 458 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(), 459 Dst.getVectorIdx(), "vecins"); 460 Builder.CreateStore(Vec, Dst.getVectorAddr(),Dst.isVolatileQualified()); 461 return; 462 } 463 464 // If this is an update of extended vector elements, insert them as 465 // appropriate. 466 if (Dst.isExtVectorElt()) 467 return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty); 468 469 if (Dst.isBitfield()) 470 return EmitStoreThroughBitfieldLValue(Src, Dst, Ty); 471 472 if (Dst.isPropertyRef()) 473 return EmitStoreThroughPropertyRefLValue(Src, Dst, Ty); 474 475 if (Dst.isKVCRef()) 476 return EmitStoreThroughKVCRefLValue(Src, Dst, Ty); 477 478 assert(0 && "Unknown LValue type"); 479 } 480 481 if (Dst.isObjCWeak() && !Dst.isNonGC()) { 482 // load of a __weak object. 483 llvm::Value *LvalueDst = Dst.getAddress(); 484 llvm::Value *src = Src.getScalarVal(); 485 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst); 486 return; 487 } 488 489 if (Dst.isObjCStrong() && !Dst.isNonGC()) { 490 // load of a __strong object. 491 llvm::Value *LvalueDst = Dst.getAddress(); 492 llvm::Value *src = Src.getScalarVal(); 493 #if 0 494 // FIXME: We cannot positively determine if we have an 'ivar' assignment, 495 // object assignment or an unknown assignment. For now, generate call to 496 // objc_assign_strongCast assignment which is a safe, but consevative 497 // assumption. 498 if (Dst.isObjCIvar()) 499 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, LvalueDst); 500 else 501 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst); 502 #endif 503 if (Dst.isGlobalObjCRef()) 504 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst); 505 else 506 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst); 507 return; 508 } 509 510 assert(Src.isScalar() && "Can't emit an agg store with this method"); 511 EmitStoreOfScalar(Src.getScalarVal(), Dst.getAddress(), 512 Dst.isVolatileQualified(), Ty); 513 } 514 515 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 516 QualType Ty, 517 llvm::Value **Result) { 518 unsigned StartBit = Dst.getBitfieldStartBit(); 519 unsigned BitfieldSize = Dst.getBitfieldSize(); 520 llvm::Value *Ptr = Dst.getBitfieldAddr(); 521 522 const llvm::Type *EltTy = 523 cast<llvm::PointerType>(Ptr->getType())->getElementType(); 524 unsigned EltTySize = CGM.getTargetData().getTypeSizeInBits(EltTy); 525 526 // Get the new value, cast to the appropriate type and masked to exactly the 527 // size of the bit-field. 528 llvm::Value *SrcVal = Src.getScalarVal(); 529 llvm::Value *NewVal = Builder.CreateIntCast(SrcVal, EltTy, false, "tmp"); 530 llvm::Constant *Mask = llvm::ConstantInt::get(VMContext, 531 llvm::APInt::getLowBitsSet(EltTySize, BitfieldSize)); 532 NewVal = Builder.CreateAnd(NewVal, Mask, "bf.value"); 533 534 // Return the new value of the bit-field, if requested. 535 if (Result) { 536 // Cast back to the proper type for result. 537 const llvm::Type *SrcTy = SrcVal->getType(); 538 llvm::Value *SrcTrunc = Builder.CreateIntCast(NewVal, SrcTy, false, 539 "bf.reload.val"); 540 541 // Sign extend if necessary. 542 if (Dst.isBitfieldSigned()) { 543 unsigned SrcTySize = CGM.getTargetData().getTypeSizeInBits(SrcTy); 544 llvm::Value *ExtraBits = llvm::ConstantInt::get(SrcTy, 545 SrcTySize - BitfieldSize); 546 SrcTrunc = Builder.CreateAShr(Builder.CreateShl(SrcTrunc, ExtraBits), 547 ExtraBits, "bf.reload.sext"); 548 } 549 550 *Result = SrcTrunc; 551 } 552 553 // In some cases the bitfield may straddle two memory locations. Emit the low 554 // part first and check to see if the high needs to be done. 555 unsigned LowBits = std::min(BitfieldSize, EltTySize - StartBit); 556 llvm::Value *LowVal = Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), 557 "bf.prev.low"); 558 559 // Compute the mask for zero-ing the low part of this bitfield. 560 llvm::Constant *InvMask = 561 llvm::ConstantInt::get(VMContext, 562 ~llvm::APInt::getBitsSet(EltTySize, StartBit, StartBit + LowBits)); 563 564 // Compute the new low part as 565 // LowVal = (LowVal & InvMask) | (NewVal << StartBit), 566 // with the shift of NewVal implicitly stripping the high bits. 567 llvm::Value *NewLowVal = 568 Builder.CreateShl(NewVal, llvm::ConstantInt::get(EltTy, StartBit), 569 "bf.value.lo"); 570 LowVal = Builder.CreateAnd(LowVal, InvMask, "bf.prev.lo.cleared"); 571 LowVal = Builder.CreateOr(LowVal, NewLowVal, "bf.new.lo"); 572 573 // Write back. 574 Builder.CreateStore(LowVal, Ptr, Dst.isVolatileQualified()); 575 576 // If the low part doesn't cover the bitfield emit a high part. 577 if (LowBits < BitfieldSize) { 578 unsigned HighBits = BitfieldSize - LowBits; 579 llvm::Value *HighPtr = Builder.CreateGEP(Ptr, llvm::ConstantInt::get( 580 llvm::Type::getInt32Ty(VMContext), 1), "bf.ptr.hi"); 581 llvm::Value *HighVal = Builder.CreateLoad(HighPtr, 582 Dst.isVolatileQualified(), 583 "bf.prev.hi"); 584 585 // Compute the mask for zero-ing the high part of this bitfield. 586 llvm::Constant *InvMask = 587 llvm::ConstantInt::get(VMContext, ~llvm::APInt::getLowBitsSet(EltTySize, 588 HighBits)); 589 590 // Compute the new high part as 591 // HighVal = (HighVal & InvMask) | (NewVal lshr LowBits), 592 // where the high bits of NewVal have already been cleared and the 593 // shift stripping the low bits. 594 llvm::Value *NewHighVal = 595 Builder.CreateLShr(NewVal, llvm::ConstantInt::get(EltTy, LowBits), 596 "bf.value.high"); 597 HighVal = Builder.CreateAnd(HighVal, InvMask, "bf.prev.hi.cleared"); 598 HighVal = Builder.CreateOr(HighVal, NewHighVal, "bf.new.hi"); 599 600 // Write back. 601 Builder.CreateStore(HighVal, HighPtr, Dst.isVolatileQualified()); 602 } 603 } 604 605 void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src, 606 LValue Dst, 607 QualType Ty) { 608 EmitObjCPropertySet(Dst.getPropertyRefExpr(), Src); 609 } 610 611 void CodeGenFunction::EmitStoreThroughKVCRefLValue(RValue Src, 612 LValue Dst, 613 QualType Ty) { 614 EmitObjCPropertySet(Dst.getKVCRefExpr(), Src); 615 } 616 617 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src, 618 LValue Dst, 619 QualType Ty) { 620 // This access turns into a read/modify/write of the vector. Load the input 621 // value now. 622 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(), 623 Dst.isVolatileQualified(), "tmp"); 624 const llvm::Constant *Elts = Dst.getExtVectorElts(); 625 626 llvm::Value *SrcVal = Src.getScalarVal(); 627 628 if (const VectorType *VTy = Ty->getAsVectorType()) { 629 unsigned NumSrcElts = VTy->getNumElements(); 630 unsigned NumDstElts = 631 cast<llvm::VectorType>(Vec->getType())->getNumElements(); 632 if (NumDstElts == NumSrcElts) { 633 // Use shuffle vector is the src and destination are the same number of 634 // elements and restore the vector mask since it is on the side it will be 635 // stored. 636 llvm::SmallVector<llvm::Constant*, 4> Mask(NumDstElts); 637 for (unsigned i = 0; i != NumSrcElts; ++i) { 638 unsigned InIdx = getAccessedFieldNo(i, Elts); 639 Mask[InIdx] = llvm::ConstantInt::get( 640 llvm::Type::getInt32Ty(VMContext), i); 641 } 642 643 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size()); 644 Vec = Builder.CreateShuffleVector(SrcVal, 645 llvm::UndefValue::get(Vec->getType()), 646 MaskV, "tmp"); 647 } else if (NumDstElts > NumSrcElts) { 648 // Extended the source vector to the same length and then shuffle it 649 // into the destination. 650 // FIXME: since we're shuffling with undef, can we just use the indices 651 // into that? This could be simpler. 652 llvm::SmallVector<llvm::Constant*, 4> ExtMask; 653 unsigned i; 654 for (i = 0; i != NumSrcElts; ++i) 655 ExtMask.push_back(llvm::ConstantInt::get( 656 llvm::Type::getInt32Ty(VMContext), i)); 657 for (; i != NumDstElts; ++i) 658 ExtMask.push_back(llvm::UndefValue::get( 659 llvm::Type::getInt32Ty(VMContext))); 660 llvm::Value *ExtMaskV = llvm::ConstantVector::get(&ExtMask[0], 661 ExtMask.size()); 662 llvm::Value *ExtSrcVal = 663 Builder.CreateShuffleVector(SrcVal, 664 llvm::UndefValue::get(SrcVal->getType()), 665 ExtMaskV, "tmp"); 666 // build identity 667 llvm::SmallVector<llvm::Constant*, 4> Mask; 668 for (unsigned i = 0; i != NumDstElts; ++i) { 669 Mask.push_back(llvm::ConstantInt::get( 670 llvm::Type::getInt32Ty(VMContext), i)); 671 } 672 // modify when what gets shuffled in 673 for (unsigned i = 0; i != NumSrcElts; ++i) { 674 unsigned Idx = getAccessedFieldNo(i, Elts); 675 Mask[Idx] = llvm::ConstantInt::get( 676 llvm::Type::getInt32Ty(VMContext), i+NumDstElts); 677 } 678 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size()); 679 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV, "tmp"); 680 } else { 681 // We should never shorten the vector 682 assert(0 && "unexpected shorten vector length"); 683 } 684 } else { 685 // If the Src is a scalar (not a vector) it must be updating one element. 686 unsigned InIdx = getAccessedFieldNo(0, Elts); 687 llvm::Value *Elt = llvm::ConstantInt::get( 688 llvm::Type::getInt32Ty(VMContext), InIdx); 689 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp"); 690 } 691 692 Builder.CreateStore(Vec, Dst.getExtVectorAddr(), Dst.isVolatileQualified()); 693 } 694 695 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) { 696 const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()); 697 698 if (VD && (VD->isBlockVarDecl() || isa<ParmVarDecl>(VD) || 699 isa<ImplicitParamDecl>(VD))) { 700 LValue LV; 701 bool NonGCable = VD->hasLocalStorage() && 702 !VD->hasAttr<BlocksAttr>(); 703 if (VD->hasExternalStorage()) { 704 llvm::Value *V = CGM.GetAddrOfGlobalVar(VD); 705 if (VD->getType()->isReferenceType()) 706 V = Builder.CreateLoad(V, "tmp"); 707 LV = LValue::MakeAddr(V, E->getType().getCVRQualifiers(), 708 getContext().getObjCGCAttrKind(E->getType()), 709 E->getType().getAddressSpace()); 710 } else { 711 llvm::Value *V = LocalDeclMap[VD]; 712 assert(V && "DeclRefExpr not entered in LocalDeclMap?"); 713 // local variables do not get their gc attribute set. 714 QualType::GCAttrTypes attr = QualType::GCNone; 715 // local static? 716 if (!NonGCable) 717 attr = getContext().getObjCGCAttrKind(E->getType()); 718 if (VD->hasAttr<BlocksAttr>()) { 719 bool needsCopyDispose = BlockRequiresCopying(VD->getType()); 720 const llvm::Type *PtrStructTy = V->getType(); 721 const llvm::Type *Ty = PtrStructTy; 722 Ty = llvm::PointerType::get(Ty, 0); 723 V = Builder.CreateStructGEP(V, 1, "forwarding"); 724 V = Builder.CreateBitCast(V, Ty); 725 V = Builder.CreateLoad(V, false); 726 V = Builder.CreateBitCast(V, PtrStructTy); 727 V = Builder.CreateStructGEP(V, needsCopyDispose*2 + 4, "x"); 728 } 729 if (VD->getType()->isReferenceType()) 730 V = Builder.CreateLoad(V, "tmp"); 731 LV = LValue::MakeAddr(V, E->getType().getCVRQualifiers(), attr, 732 E->getType().getAddressSpace()); 733 } 734 LValue::SetObjCNonGC(LV, NonGCable); 735 return LV; 736 } else if (VD && VD->isFileVarDecl()) { 737 llvm::Value *V = CGM.GetAddrOfGlobalVar(VD); 738 if (VD->getType()->isReferenceType()) 739 V = Builder.CreateLoad(V, "tmp"); 740 LValue LV = LValue::MakeAddr(V, E->getType().getCVRQualifiers(), 741 getContext().getObjCGCAttrKind(E->getType()), 742 E->getType().getAddressSpace()); 743 if (LV.isObjCStrong()) 744 LV.SetGlobalObjCRef(LV, true); 745 return LV; 746 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) { 747 llvm::Value* V = CGM.GetAddrOfFunction(FD); 748 if (!FD->hasPrototype()) { 749 if (const FunctionProtoType *Proto = 750 FD->getType()->getAsFunctionProtoType()) { 751 // Ugly case: for a K&R-style definition, the type of the definition 752 // isn't the same as the type of a use. Correct for this with a 753 // bitcast. 754 QualType NoProtoType = 755 getContext().getFunctionNoProtoType(Proto->getResultType()); 756 NoProtoType = getContext().getPointerType(NoProtoType); 757 V = Builder.CreateBitCast(V, ConvertType(NoProtoType), "tmp"); 758 } 759 } 760 return LValue::MakeAddr(V, E->getType().getCVRQualifiers(), 761 getContext().getObjCGCAttrKind(E->getType()), 762 E->getType().getAddressSpace()); 763 } else if (const ImplicitParamDecl *IPD = 764 dyn_cast<ImplicitParamDecl>(E->getDecl())) { 765 llvm::Value *V = LocalDeclMap[IPD]; 766 assert(V && "BlockVarDecl not entered in LocalDeclMap?"); 767 return LValue::MakeAddr(V, E->getType().getCVRQualifiers(), 768 getContext().getObjCGCAttrKind(E->getType()), 769 E->getType().getAddressSpace()); 770 } 771 assert(0 && "Unimp declref"); 772 //an invalid LValue, but the assert will 773 //ensure that this point is never reached. 774 return LValue(); 775 } 776 777 LValue CodeGenFunction::EmitBlockDeclRefLValue(const BlockDeclRefExpr *E) { 778 return LValue::MakeAddr(GetAddrOfBlockDecl(E), 779 E->getType().getCVRQualifiers(), 780 getContext().getObjCGCAttrKind(E->getType()), 781 E->getType().getAddressSpace()); 782 } 783 784 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) { 785 // __extension__ doesn't affect lvalue-ness. 786 if (E->getOpcode() == UnaryOperator::Extension) 787 return EmitLValue(E->getSubExpr()); 788 789 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType()); 790 switch (E->getOpcode()) { 791 default: assert(0 && "Unknown unary operator lvalue!"); 792 case UnaryOperator::Deref: 793 { 794 QualType T = E->getSubExpr()->getType()->getPointeeType(); 795 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type"); 796 797 LValue LV = LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()), 798 T.getCVRQualifiers(), 799 getContext().getObjCGCAttrKind(T), 800 ExprTy.getAddressSpace()); 801 // We should not generate __weak write barrier on indirect reference 802 // of a pointer to object; as in void foo (__weak id *param); *param = 0; 803 // But, we continue to generate __strong write barrier on indirect write 804 // into a pointer to object. 805 if (getContext().getLangOptions().ObjC1 && 806 getContext().getLangOptions().getGCMode() != LangOptions::NonGC && 807 LV.isObjCWeak()) 808 LValue::SetObjCNonGC(LV, !E->isOBJCGCCandidate(getContext())); 809 return LV; 810 } 811 case UnaryOperator::Real: 812 case UnaryOperator::Imag: 813 LValue LV = EmitLValue(E->getSubExpr()); 814 unsigned Idx = E->getOpcode() == UnaryOperator::Imag; 815 return LValue::MakeAddr(Builder.CreateStructGEP(LV.getAddress(), 816 Idx, "idx"), 817 ExprTy.getCVRQualifiers(), 818 QualType::GCNone, 819 ExprTy.getAddressSpace()); 820 } 821 } 822 823 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) { 824 return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromLiteral(E), 0); 825 } 826 827 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) { 828 return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromObjCEncode(E), 0); 829 } 830 831 832 LValue CodeGenFunction::EmitPredefinedFunctionName(unsigned Type) { 833 std::string GlobalVarName; 834 835 switch (Type) { 836 default: 837 assert(0 && "Invalid type"); 838 case PredefinedExpr::Func: 839 GlobalVarName = "__func__."; 840 break; 841 case PredefinedExpr::Function: 842 GlobalVarName = "__FUNCTION__."; 843 break; 844 case PredefinedExpr::PrettyFunction: 845 GlobalVarName = "__PRETTY_FUNCTION__."; 846 break; 847 } 848 849 std::string FunctionName = 850 PredefinedExpr::ComputeName(getContext(), (PredefinedExpr::IdentType)Type, 851 CurCodeDecl); 852 853 GlobalVarName += FunctionName; 854 llvm::Constant *C = 855 CGM.GetAddrOfConstantCString(FunctionName, GlobalVarName.c_str()); 856 return LValue::MakeAddr(C, 0); 857 } 858 859 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) { 860 switch (E->getIdentType()) { 861 default: 862 return EmitUnsupportedLValue(E, "predefined expression"); 863 case PredefinedExpr::Func: 864 case PredefinedExpr::Function: 865 case PredefinedExpr::PrettyFunction: 866 return EmitPredefinedFunctionName(E->getIdentType()); 867 } 868 } 869 870 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) { 871 // The index must always be an integer, which is not an aggregate. Emit it. 872 llvm::Value *Idx = EmitScalarExpr(E->getIdx()); 873 QualType IdxTy = E->getIdx()->getType(); 874 bool IdxSigned = IdxTy->isSignedIntegerType(); 875 876 // If the base is a vector type, then we are forming a vector element lvalue 877 // with this subscript. 878 if (E->getBase()->getType()->isVectorType()) { 879 // Emit the vector as an lvalue to get its address. 880 LValue LHS = EmitLValue(E->getBase()); 881 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!"); 882 Idx = Builder.CreateIntCast(Idx, 883 llvm::Type::getInt32Ty(VMContext), IdxSigned, "vidx"); 884 return LValue::MakeVectorElt(LHS.getAddress(), Idx, 885 E->getBase()->getType().getCVRQualifiers()); 886 } 887 888 // The base must be a pointer, which is not an aggregate. Emit it. 889 llvm::Value *Base = EmitScalarExpr(E->getBase()); 890 891 // Extend or truncate the index type to 32 or 64-bits. 892 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 893 if (IdxBitwidth != LLVMPointerWidth) 894 Idx = Builder.CreateIntCast(Idx, 895 llvm::IntegerType::get(VMContext, LLVMPointerWidth), 896 IdxSigned, "idxprom"); 897 898 // We know that the pointer points to a type of the correct size, unless the 899 // size is a VLA or Objective-C interface. 900 llvm::Value *Address = 0; 901 if (const VariableArrayType *VAT = 902 getContext().getAsVariableArrayType(E->getType())) { 903 llvm::Value *VLASize = GetVLASize(VAT); 904 905 Idx = Builder.CreateMul(Idx, VLASize); 906 907 QualType BaseType = getContext().getBaseElementType(VAT); 908 909 uint64_t BaseTypeSize = getContext().getTypeSize(BaseType) / 8; 910 Idx = Builder.CreateUDiv(Idx, 911 llvm::ConstantInt::get(Idx->getType(), 912 BaseTypeSize)); 913 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx"); 914 } else if (const ObjCInterfaceType *OIT = 915 dyn_cast<ObjCInterfaceType>(E->getType())) { 916 llvm::Value *InterfaceSize = 917 llvm::ConstantInt::get(Idx->getType(), 918 getContext().getTypeSize(OIT) / 8); 919 920 Idx = Builder.CreateMul(Idx, InterfaceSize); 921 922 llvm::Type *i8PTy = 923 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); 924 Address = Builder.CreateGEP(Builder.CreateBitCast(Base, i8PTy), 925 Idx, "arrayidx"); 926 Address = Builder.CreateBitCast(Address, Base->getType()); 927 } else { 928 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx"); 929 } 930 931 QualType T = E->getBase()->getType()->getPointeeType(); 932 assert(!T.isNull() && 933 "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type"); 934 935 LValue LV = LValue::MakeAddr(Address, 936 T.getCVRQualifiers(), 937 getContext().getObjCGCAttrKind(T), 938 E->getBase()->getType().getAddressSpace()); 939 if (getContext().getLangOptions().ObjC1 && 940 getContext().getLangOptions().getGCMode() != LangOptions::NonGC) 941 LValue::SetObjCNonGC(LV, !E->isOBJCGCCandidate(getContext())); 942 return LV; 943 } 944 945 static 946 llvm::Constant *GenerateConstantVector(llvm::LLVMContext &VMContext, 947 llvm::SmallVector<unsigned, 4> &Elts) { 948 llvm::SmallVector<llvm::Constant *, 4> CElts; 949 950 for (unsigned i = 0, e = Elts.size(); i != e; ++i) 951 CElts.push_back(llvm::ConstantInt::get( 952 llvm::Type::getInt32Ty(VMContext), Elts[i])); 953 954 return llvm::ConstantVector::get(&CElts[0], CElts.size()); 955 } 956 957 LValue CodeGenFunction:: 958 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) { 959 // Emit the base vector as an l-value. 960 LValue Base; 961 962 // ExtVectorElementExpr's base can either be a vector or pointer to vector. 963 if (!E->isArrow()) { 964 assert(E->getBase()->getType()->isVectorType()); 965 Base = EmitLValue(E->getBase()); 966 } else { 967 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>(); 968 llvm::Value *Ptr = EmitScalarExpr(E->getBase()); 969 Base = LValue::MakeAddr(Ptr, PT->getPointeeType().getCVRQualifiers(), 970 QualType::GCNone, 971 PT->getPointeeType().getAddressSpace()); 972 } 973 974 // Encode the element access list into a vector of unsigned indices. 975 llvm::SmallVector<unsigned, 4> Indices; 976 E->getEncodedElementAccess(Indices); 977 978 if (Base.isSimple()) { 979 llvm::Constant *CV = GenerateConstantVector(VMContext, Indices); 980 return LValue::MakeExtVectorElt(Base.getAddress(), CV, 981 Base.getQualifiers()); 982 } 983 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!"); 984 985 llvm::Constant *BaseElts = Base.getExtVectorElts(); 986 llvm::SmallVector<llvm::Constant *, 4> CElts; 987 988 for (unsigned i = 0, e = Indices.size(); i != e; ++i) { 989 if (isa<llvm::ConstantAggregateZero>(BaseElts)) 990 CElts.push_back(llvm::ConstantInt::get( 991 llvm::Type::getInt32Ty(VMContext), 0)); 992 else 993 CElts.push_back(BaseElts->getOperand(Indices[i])); 994 } 995 llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size()); 996 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, 997 Base.getQualifiers()); 998 } 999 1000 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) { 1001 bool isUnion = false; 1002 bool isIvar = false; 1003 bool isNonGC = false; 1004 Expr *BaseExpr = E->getBase(); 1005 llvm::Value *BaseValue = NULL; 1006 unsigned CVRQualifiers=0; 1007 1008 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 1009 if (E->isArrow()) { 1010 BaseValue = EmitScalarExpr(BaseExpr); 1011 const PointerType *PTy = 1012 BaseExpr->getType()->getAs<PointerType>(); 1013 if (PTy->getPointeeType()->isUnionType()) 1014 isUnion = true; 1015 CVRQualifiers = PTy->getPointeeType().getCVRQualifiers(); 1016 } else if (isa<ObjCPropertyRefExpr>(BaseExpr->IgnoreParens()) || 1017 isa<ObjCImplicitSetterGetterRefExpr>( 1018 BaseExpr->IgnoreParens())) { 1019 RValue RV = EmitObjCPropertyGet(BaseExpr); 1020 BaseValue = RV.getAggregateAddr(); 1021 if (BaseExpr->getType()->isUnionType()) 1022 isUnion = true; 1023 CVRQualifiers = BaseExpr->getType().getCVRQualifiers(); 1024 } else { 1025 LValue BaseLV = EmitLValue(BaseExpr); 1026 if (BaseLV.isObjCIvar()) 1027 isIvar = true; 1028 if (BaseLV.isNonGC()) 1029 isNonGC = true; 1030 // FIXME: this isn't right for bitfields. 1031 BaseValue = BaseLV.getAddress(); 1032 QualType BaseTy = BaseExpr->getType(); 1033 if (BaseTy->isUnionType()) 1034 isUnion = true; 1035 CVRQualifiers = BaseTy.getCVRQualifiers(); 1036 } 1037 1038 FieldDecl *Field = dyn_cast<FieldDecl>(E->getMemberDecl()); 1039 // FIXME: Handle non-field member expressions 1040 assert(Field && "No code generation for non-field member references"); 1041 LValue MemExpLV = EmitLValueForField(BaseValue, Field, isUnion, 1042 CVRQualifiers); 1043 LValue::SetObjCIvar(MemExpLV, isIvar); 1044 LValue::SetObjCNonGC(MemExpLV, isNonGC); 1045 return MemExpLV; 1046 } 1047 1048 LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value* BaseValue, 1049 FieldDecl* Field, 1050 unsigned CVRQualifiers) { 1051 CodeGenTypes::BitFieldInfo Info = CGM.getTypes().getBitFieldInfo(Field); 1052 1053 // FIXME: CodeGenTypes should expose a method to get the appropriate type for 1054 // FieldTy (the appropriate type is ABI-dependent). 1055 const llvm::Type *FieldTy = 1056 CGM.getTypes().ConvertTypeForMem(Field->getType()); 1057 const llvm::PointerType *BaseTy = 1058 cast<llvm::PointerType>(BaseValue->getType()); 1059 unsigned AS = BaseTy->getAddressSpace(); 1060 BaseValue = Builder.CreateBitCast(BaseValue, 1061 llvm::PointerType::get(FieldTy, AS), 1062 "tmp"); 1063 1064 llvm::Value *Idx = 1065 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Info.FieldNo); 1066 llvm::Value *V = Builder.CreateGEP(BaseValue, Idx, "tmp"); 1067 1068 return LValue::MakeBitfield(V, Info.Start, Info.Size, 1069 Field->getType()->isSignedIntegerType(), 1070 Field->getType().getCVRQualifiers()|CVRQualifiers); 1071 } 1072 1073 LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue, 1074 FieldDecl* Field, 1075 bool isUnion, 1076 unsigned CVRQualifiers) { 1077 if (Field->isBitField()) 1078 return EmitLValueForBitfield(BaseValue, Field, CVRQualifiers); 1079 1080 unsigned idx = CGM.getTypes().getLLVMFieldNo(Field); 1081 llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp"); 1082 1083 // Match union field type. 1084 if (isUnion) { 1085 const llvm::Type *FieldTy = 1086 CGM.getTypes().ConvertTypeForMem(Field->getType()); 1087 const llvm::PointerType * BaseTy = 1088 cast<llvm::PointerType>(BaseValue->getType()); 1089 unsigned AS = BaseTy->getAddressSpace(); 1090 V = Builder.CreateBitCast(V, 1091 llvm::PointerType::get(FieldTy, AS), 1092 "tmp"); 1093 } 1094 if (Field->getType()->isReferenceType()) 1095 V = Builder.CreateLoad(V, "tmp"); 1096 1097 QualType::GCAttrTypes attr = QualType::GCNone; 1098 if (CGM.getLangOptions().ObjC1 && 1099 CGM.getLangOptions().getGCMode() != LangOptions::NonGC) { 1100 QualType Ty = Field->getType(); 1101 attr = Ty.getObjCGCAttr(); 1102 if (attr != QualType::GCNone) { 1103 // __weak attribute on a field is ignored. 1104 if (attr == QualType::Weak) 1105 attr = QualType::GCNone; 1106 } else if (Ty->isObjCObjectPointerType()) 1107 attr = QualType::Strong; 1108 } 1109 LValue LV = 1110 LValue::MakeAddr(V, 1111 Field->getType().getCVRQualifiers()|CVRQualifiers, 1112 attr, 1113 Field->getType().getAddressSpace()); 1114 return LV; 1115 } 1116 1117 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr* E){ 1118 const llvm::Type *LTy = ConvertType(E->getType()); 1119 llvm::Value *DeclPtr = CreateTempAlloca(LTy, ".compoundliteral"); 1120 1121 const Expr* InitExpr = E->getInitializer(); 1122 LValue Result = LValue::MakeAddr(DeclPtr, E->getType().getCVRQualifiers(), 1123 QualType::GCNone, 1124 E->getType().getAddressSpace()); 1125 1126 if (E->getType()->isComplexType()) { 1127 EmitComplexExprIntoAddr(InitExpr, DeclPtr, false); 1128 } else if (hasAggregateLLVMType(E->getType())) { 1129 EmitAnyExpr(InitExpr, DeclPtr, false); 1130 } else { 1131 EmitStoreThroughLValue(EmitAnyExpr(InitExpr), Result, E->getType()); 1132 } 1133 1134 return Result; 1135 } 1136 1137 LValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator* E) { 1138 if (E->isLvalue(getContext()) == Expr::LV_Valid) 1139 return EmitUnsupportedLValue(E, "conditional operator"); 1140 1141 // ?: here should be an aggregate. 1142 assert((hasAggregateLLVMType(E->getType()) && 1143 !E->getType()->isAnyComplexType()) && 1144 "Unexpected conditional operator!"); 1145 1146 llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType())); 1147 EmitAggExpr(E, Temp, false); 1148 1149 return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(), 1150 getContext().getObjCGCAttrKind(E->getType()), 1151 E->getType().getAddressSpace()); 1152 1153 } 1154 1155 /// EmitCastLValue - Casts are never lvalues. If a cast is needed by the code 1156 /// generator in an lvalue context, then it must mean that we need the address 1157 /// of an aggregate in order to access one of its fields. This can happen for 1158 /// all the reasons that casts are permitted with aggregate result, including 1159 /// noop aggregate casts, and cast from scalar to union. 1160 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) { 1161 // If this is an aggregate-to-aggregate cast, just use the input's address as 1162 // the lvalue. 1163 if (E->getCastKind() == CastExpr::CK_NoOp || 1164 E->getCastKind() == CastExpr::CK_ConstructorConversion || 1165 E->getCastKind() == CastExpr::CK_UserDefinedConversion) 1166 return EmitLValue(E->getSubExpr()); 1167 1168 // If this is an lvalue cast, treat it as a no-op. 1169 // FIXME: We shouldn't need to check for this explicitly! 1170 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 1171 if (ICE->isLvalueCast()) 1172 return EmitLValue(E->getSubExpr()); 1173 1174 // Otherwise, we must have a cast from scalar to union. 1175 assert(E->getCastKind() == CastExpr::CK_ToUnion && 1176 "Expected scalar-to-union cast"); 1177 1178 // Casts are only lvalues when the source and destination types are the same. 1179 llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType())); 1180 EmitAnyExpr(E->getSubExpr(), Temp, false); 1181 1182 return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(), 1183 getContext().getObjCGCAttrKind(E->getType()), 1184 E->getType().getAddressSpace()); 1185 } 1186 1187 //===--------------------------------------------------------------------===// 1188 // Expression Emission 1189 //===--------------------------------------------------------------------===// 1190 1191 1192 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) { 1193 // Builtins never have block type. 1194 if (E->getCallee()->getType()->isBlockPointerType()) 1195 return EmitBlockCallExpr(E); 1196 1197 if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E)) 1198 return EmitCXXMemberCallExpr(CE); 1199 1200 const Decl *TargetDecl = 0; 1201 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E->getCallee())) { 1202 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) { 1203 TargetDecl = DRE->getDecl(); 1204 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(TargetDecl)) 1205 if (unsigned builtinID = FD->getBuiltinID()) 1206 return EmitBuiltinExpr(FD, builtinID, E); 1207 } 1208 } 1209 1210 if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E)) 1211 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl)) 1212 return EmitCXXOperatorMemberCallExpr(CE, MD); 1213 1214 if (isa<CXXPseudoDestructorExpr>(E->getCallee())) { 1215 // C++ [expr.pseudo]p1: 1216 // The result shall only be used as the operand for the function call 1217 // operator (), and the result of such a call has type void. The only 1218 // effect is the evaluation of the postfix-expression before the dot or 1219 // arrow. 1220 EmitScalarExpr(E->getCallee()); 1221 return RValue::get(0); 1222 } 1223 1224 llvm::Value *Callee = EmitScalarExpr(E->getCallee()); 1225 return EmitCall(Callee, E->getCallee()->getType(), 1226 E->arg_begin(), E->arg_end(), TargetDecl); 1227 } 1228 1229 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) { 1230 // Comma expressions just emit their LHS then their RHS as an l-value. 1231 if (E->getOpcode() == BinaryOperator::Comma) { 1232 EmitAnyExpr(E->getLHS()); 1233 return EmitLValue(E->getRHS()); 1234 } 1235 1236 // Can only get l-value for binary operator expressions which are a 1237 // simple assignment of aggregate type. 1238 if (E->getOpcode() != BinaryOperator::Assign) 1239 return EmitUnsupportedLValue(E, "binary l-value expression"); 1240 1241 llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType())); 1242 EmitAggExpr(E, Temp, false); 1243 // FIXME: Are these qualifiers correct? 1244 return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(), 1245 getContext().getObjCGCAttrKind(E->getType()), 1246 E->getType().getAddressSpace()); 1247 } 1248 1249 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) { 1250 RValue RV = EmitCallExpr(E); 1251 1252 if (RV.isScalar()) { 1253 assert(E->getCallReturnType()->isReferenceType() && 1254 "Can't have a scalar return unless the return type is a " 1255 "reference type!"); 1256 1257 return LValue::MakeAddr(RV.getScalarVal(), E->getType().getCVRQualifiers(), 1258 getContext().getObjCGCAttrKind(E->getType()), 1259 E->getType().getAddressSpace()); 1260 } 1261 1262 return LValue::MakeAddr(RV.getAggregateAddr(), 1263 E->getType().getCVRQualifiers(), 1264 getContext().getObjCGCAttrKind(E->getType()), 1265 E->getType().getAddressSpace()); 1266 } 1267 1268 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) { 1269 // FIXME: This shouldn't require another copy. 1270 llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType())); 1271 EmitAggExpr(E, Temp, false); 1272 return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(), 1273 QualType::GCNone, E->getType().getAddressSpace()); 1274 } 1275 1276 LValue 1277 CodeGenFunction::EmitCXXConditionDeclLValue(const CXXConditionDeclExpr *E) { 1278 EmitLocalBlockVarDecl(*E->getVarDecl()); 1279 return EmitDeclRefLValue(E); 1280 } 1281 1282 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) { 1283 llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(E->getType()), "tmp"); 1284 EmitCXXConstructExpr(Temp, E); 1285 return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(), 1286 QualType::GCNone, E->getType().getAddressSpace()); 1287 } 1288 1289 LValue 1290 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) { 1291 LValue LV = EmitLValue(E->getSubExpr()); 1292 1293 PushCXXTemporary(E->getTemporary(), LV.getAddress()); 1294 1295 return LV; 1296 } 1297 1298 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) { 1299 // Can only get l-value for message expression returning aggregate type 1300 RValue RV = EmitObjCMessageExpr(E); 1301 // FIXME: can this be volatile? 1302 return LValue::MakeAddr(RV.getAggregateAddr(), 1303 E->getType().getCVRQualifiers(), 1304 getContext().getObjCGCAttrKind(E->getType()), 1305 E->getType().getAddressSpace()); 1306 } 1307 1308 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface, 1309 const ObjCIvarDecl *Ivar) { 1310 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar); 1311 } 1312 1313 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy, 1314 llvm::Value *BaseValue, 1315 const ObjCIvarDecl *Ivar, 1316 unsigned CVRQualifiers) { 1317 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue, 1318 Ivar, CVRQualifiers); 1319 } 1320 1321 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) { 1322 // FIXME: A lot of the code below could be shared with EmitMemberExpr. 1323 llvm::Value *BaseValue = 0; 1324 const Expr *BaseExpr = E->getBase(); 1325 unsigned CVRQualifiers = 0; 1326 QualType ObjectTy; 1327 if (E->isArrow()) { 1328 BaseValue = EmitScalarExpr(BaseExpr); 1329 ObjectTy = BaseExpr->getType()->getPointeeType(); 1330 CVRQualifiers = ObjectTy.getCVRQualifiers(); 1331 } else { 1332 LValue BaseLV = EmitLValue(BaseExpr); 1333 // FIXME: this isn't right for bitfields. 1334 BaseValue = BaseLV.getAddress(); 1335 ObjectTy = BaseExpr->getType(); 1336 CVRQualifiers = ObjectTy.getCVRQualifiers(); 1337 } 1338 1339 return EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(), CVRQualifiers); 1340 } 1341 1342 LValue 1343 CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) { 1344 // This is a special l-value that just issues sends when we load or store 1345 // through it. 1346 return LValue::MakePropertyRef(E, E->getType().getCVRQualifiers()); 1347 } 1348 1349 LValue 1350 CodeGenFunction::EmitObjCKVCRefLValue( 1351 const ObjCImplicitSetterGetterRefExpr *E) { 1352 // This is a special l-value that just issues sends when we load or store 1353 // through it. 1354 return LValue::MakeKVCRef(E, E->getType().getCVRQualifiers()); 1355 } 1356 1357 LValue 1358 CodeGenFunction::EmitObjCSuperExprLValue(const ObjCSuperExpr *E) { 1359 return EmitUnsupportedLValue(E, "use of super"); 1360 } 1361 1362 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) { 1363 1364 // Can only get l-value for message expression returning aggregate type 1365 RValue RV = EmitAnyExprToTemp(E); 1366 // FIXME: can this be volatile? 1367 return LValue::MakeAddr(RV.getAggregateAddr(), 1368 E->getType().getCVRQualifiers(), 1369 getContext().getObjCGCAttrKind(E->getType()), 1370 E->getType().getAddressSpace()); 1371 } 1372 1373 1374 RValue CodeGenFunction::EmitCall(llvm::Value *Callee, QualType CalleeType, 1375 CallExpr::const_arg_iterator ArgBeg, 1376 CallExpr::const_arg_iterator ArgEnd, 1377 const Decl *TargetDecl) { 1378 // Get the actual function type. The callee type will always be a pointer to 1379 // function type or a block pointer type. 1380 assert(CalleeType->isFunctionPointerType() && 1381 "Call must have function pointer type!"); 1382 1383 QualType FnType = CalleeType->getAs<PointerType>()->getPointeeType(); 1384 QualType ResultType = FnType->getAsFunctionType()->getResultType(); 1385 1386 CallArgList Args; 1387 EmitCallArgs(Args, FnType->getAsFunctionProtoType(), ArgBeg, ArgEnd); 1388 1389 // FIXME: We should not need to do this, it should be part of the function 1390 // type. 1391 unsigned CallingConvention = 0; 1392 if (const llvm::Function *F = 1393 dyn_cast<llvm::Function>(Callee->stripPointerCasts())) 1394 CallingConvention = F->getCallingConv(); 1395 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args, 1396 CallingConvention), 1397 Callee, Args, TargetDecl); 1398 } 1399