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