CGExpr.cpp revision 922696f03ec9637449e2cba260493808b4977cd3
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 "clang/AST/AST.h" 17#include "clang/Basic/TargetInfo.h" 18#include "llvm/Constants.h" 19#include "llvm/DerivedTypes.h" 20#include "llvm/Function.h" 21#include "llvm/GlobalVariable.h" 22#include "llvm/Support/MathExtras.h" 23#include "llvm/Target/TargetData.h" 24using namespace clang; 25using namespace CodeGen; 26 27//===--------------------------------------------------------------------===// 28// Miscellaneous Helper Methods 29//===--------------------------------------------------------------------===// 30 31/// CreateTempAlloca - This creates a alloca and inserts it into the entry 32/// block. 33llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty, 34 const char *Name) { 35 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt); 36} 37 38/// EvaluateExprAsBool - Perform the usual unary conversions on the specified 39/// expression and compare the result against zero, returning an Int1Ty value. 40llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) { 41 QualType BoolTy = getContext().BoolTy; 42 if (!E->getType()->isAnyComplexType()) 43 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy); 44 45 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy); 46} 47 48/// EmitAnyExpr - Emit code to compute the specified expression which can have 49/// any type. The result is returned as an RValue struct. If this is an 50/// aggregate expression, the aggloc/agglocvolatile arguments indicate where 51/// the result should be returned. 52RValue CodeGenFunction::EmitAnyExpr(const Expr *E, llvm::Value *AggLoc, 53 bool isAggLocVolatile) { 54 if (!hasAggregateLLVMType(E->getType())) 55 return RValue::get(EmitScalarExpr(E)); 56 else if (E->getType()->isAnyComplexType()) 57 return RValue::getComplex(EmitComplexExpr(E)); 58 59 EmitAggExpr(E, AggLoc, isAggLocVolatile); 60 return RValue::getAggregate(AggLoc); 61} 62 63 64//===----------------------------------------------------------------------===// 65// LValue Expression Emission 66//===----------------------------------------------------------------------===// 67 68/// EmitLValue - Emit code to compute a designator that specifies the location 69/// of the expression. 70/// 71/// This can return one of two things: a simple address or a bitfield 72/// reference. In either case, the LLVM Value* in the LValue structure is 73/// guaranteed to be an LLVM pointer type. 74/// 75/// If this returns a bitfield reference, nothing about the pointee type of 76/// the LLVM value is known: For example, it may not be a pointer to an 77/// integer. 78/// 79/// If this returns a normal address, and if the lvalue's C type is fixed 80/// size, this method guarantees that the returned pointer type will point to 81/// an LLVM type of the same size of the lvalue's type. If the lvalue has a 82/// variable length type, this is not possible. 83/// 84LValue CodeGenFunction::EmitLValue(const Expr *E) { 85 switch (E->getStmtClass()) { 86 default: { 87 printf("Statement class: %d\n", E->getStmtClass()); 88 WarnUnsupported(E, "l-value expression"); 89 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType())); 90 return LValue::MakeAddr(llvm::UndefValue::get(Ty)); 91 } 92 93 case Expr::CallExprClass: return EmitCallExprLValue(cast<CallExpr>(E)); 94 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E)); 95 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr()); 96 case Expr::PreDefinedExprClass: 97 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E)); 98 case Expr::StringLiteralClass: 99 return EmitStringLiteralLValue(cast<StringLiteral>(E)); 100 101 case Expr::ObjCIvarRefExprClass: 102 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E)); 103 104 case Expr::UnaryOperatorClass: 105 return EmitUnaryOpLValue(cast<UnaryOperator>(E)); 106 case Expr::ArraySubscriptExprClass: 107 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E)); 108 case Expr::ExtVectorElementExprClass: 109 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E)); 110 case Expr::MemberExprClass: return EmitMemberExpr(cast<MemberExpr>(E)); 111 case Expr::CompoundLiteralExprClass: 112 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E)); 113 } 114} 115 116/// EmitLoadOfLValue - Given an expression that represents a value lvalue, 117/// this method emits the address of the lvalue, then loads the result as an 118/// rvalue, returning the rvalue. 119RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) { 120 if (LV.isSimple()) { 121 llvm::Value *Ptr = LV.getAddress(); 122 const llvm::Type *EltTy = 123 cast<llvm::PointerType>(Ptr->getType())->getElementType(); 124 125 // Simple scalar l-value. 126 if (EltTy->isFirstClassType()) { 127 llvm::Value *V = Builder.CreateLoad(Ptr, "tmp"); 128 129 // Bool can have different representation in memory than in registers. 130 if (ExprType->isBooleanType()) { 131 if (V->getType() != llvm::Type::Int1Ty) 132 V = Builder.CreateTrunc(V, llvm::Type::Int1Ty, "tobool"); 133 } 134 135 return RValue::get(V); 136 } 137 138 assert(ExprType->isFunctionType() && "Unknown scalar value"); 139 return RValue::get(Ptr); 140 } 141 142 if (LV.isVectorElt()) { 143 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp"); 144 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(), 145 "vecext")); 146 } 147 148 // If this is a reference to a subset of the elements of a vector, either 149 // shuffle the input or extract/insert them as appropriate. 150 if (LV.isExtVectorElt()) 151 return EmitLoadOfExtVectorElementLValue(LV, ExprType); 152 153 if (LV.isBitfield()) 154 return EmitLoadOfBitfieldLValue(LV, ExprType); 155 156 assert(0 && "Unknown LValue type!"); 157 //an invalid RValue, but the assert will 158 //ensure that this point is never reached 159 return RValue(); 160} 161 162RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV, 163 QualType ExprType) { 164 llvm::Value *Ptr = LV.getBitfieldAddr(); 165 const llvm::Type *EltTy = 166 cast<llvm::PointerType>(Ptr->getType())->getElementType(); 167 unsigned EltTySize = EltTy->getPrimitiveSizeInBits(); 168 unsigned short BitfieldSize = LV.getBitfieldSize(); 169 unsigned short EndBit = LV.getBitfieldStartBit() + BitfieldSize; 170 171 llvm::Value *V = Builder.CreateLoad(Ptr, "tmp"); 172 173 llvm::Value *ShAmt = llvm::ConstantInt::get(EltTy, EltTySize - EndBit); 174 V = Builder.CreateShl(V, ShAmt, "tmp"); 175 176 ShAmt = llvm::ConstantInt::get(EltTy, EltTySize - BitfieldSize); 177 V = LV.isBitfieldSigned() ? 178 Builder.CreateAShr(V, ShAmt, "tmp") : 179 Builder.CreateLShr(V, ShAmt, "tmp"); 180 181 // The bitfield type and the normal type differ when the storage sizes 182 // differ (currently just _Bool). 183 V = Builder.CreateIntCast(V, ConvertType(ExprType), false, "tmp"); 184 185 return RValue::get(V); 186} 187 188// If this is a reference to a subset of the elements of a vector, either 189// shuffle the input or extract/insert them as appropriate. 190RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV, 191 QualType ExprType) { 192 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(), "tmp"); 193 194 const llvm::Constant *Elts = LV.getExtVectorElts(); 195 196 // If the result of the expression is a non-vector type, we must be 197 // extracting a single element. Just codegen as an extractelement. 198 const VectorType *ExprVT = ExprType->getAsVectorType(); 199 if (!ExprVT) { 200 unsigned InIdx = ExtVectorElementExpr::getAccessedFieldNo(0, Elts); 201 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx); 202 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp")); 203 } 204 205 // If the source and destination have the same number of elements, use a 206 // vector shuffle instead of insert/extracts. 207 unsigned NumResultElts = ExprVT->getNumElements(); 208 unsigned NumSourceElts = 209 cast<llvm::VectorType>(Vec->getType())->getNumElements(); 210 211 if (NumResultElts == NumSourceElts) { 212 llvm::SmallVector<llvm::Constant*, 4> Mask; 213 for (unsigned i = 0; i != NumResultElts; ++i) { 214 unsigned InIdx = ExtVectorElementExpr::getAccessedFieldNo(i, Elts); 215 Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx)); 216 } 217 218 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size()); 219 Vec = Builder.CreateShuffleVector(Vec, 220 llvm::UndefValue::get(Vec->getType()), 221 MaskV, "tmp"); 222 return RValue::get(Vec); 223 } 224 225 // Start out with an undef of the result type. 226 llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType)); 227 228 // Extract/Insert each element of the result. 229 for (unsigned i = 0; i != NumResultElts; ++i) { 230 unsigned InIdx = ExtVectorElementExpr::getAccessedFieldNo(i, Elts); 231 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx); 232 Elt = Builder.CreateExtractElement(Vec, Elt, "tmp"); 233 234 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i); 235 Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp"); 236 } 237 238 return RValue::get(Result); 239} 240 241 242 243/// EmitStoreThroughLValue - Store the specified rvalue into the specified 244/// lvalue, where both are guaranteed to the have the same type, and that type 245/// is 'Ty'. 246void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, 247 QualType Ty) { 248 if (!Dst.isSimple()) { 249 if (Dst.isVectorElt()) { 250 // Read/modify/write the vector, inserting the new element. 251 // FIXME: Volatility. 252 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp"); 253 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(), 254 Dst.getVectorIdx(), "vecins"); 255 Builder.CreateStore(Vec, Dst.getVectorAddr()); 256 return; 257 } 258 259 // If this is an update of extended vector elements, insert them as 260 // appropriate. 261 if (Dst.isExtVectorElt()) 262 return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty); 263 264 if (Dst.isBitfield()) 265 return EmitStoreThroughBitfieldLValue(Src, Dst, Ty); 266 267 assert(0 && "Unknown LValue type"); 268 } 269 270 llvm::Value *DstAddr = Dst.getAddress(); 271 assert(Src.isScalar() && "Can't emit an agg store with this method"); 272 // FIXME: Handle volatility etc. 273 const llvm::Type *SrcTy = Src.getScalarVal()->getType(); 274 const llvm::PointerType *DstPtr = cast<llvm::PointerType>(DstAddr->getType()); 275 const llvm::Type *AddrTy = DstPtr->getElementType(); 276 unsigned AS = DstPtr->getAddressSpace(); 277 278 if (AddrTy != SrcTy) 279 DstAddr = Builder.CreateBitCast(DstAddr, 280 llvm::PointerType::get(SrcTy, AS), 281 "storetmp"); 282 Builder.CreateStore(Src.getScalarVal(), DstAddr); 283} 284 285void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 286 QualType Ty) { 287 unsigned short StartBit = Dst.getBitfieldStartBit(); 288 unsigned short BitfieldSize = Dst.getBitfieldSize(); 289 llvm::Value *Ptr = Dst.getBitfieldAddr(); 290 291 llvm::Value *NewVal = Src.getScalarVal(); 292 llvm::Value *OldVal = Builder.CreateLoad(Ptr, "tmp"); 293 294 // The bitfield type and the normal type differ when the storage sizes 295 // differ (currently just _Bool). 296 const llvm::Type *EltTy = OldVal->getType(); 297 unsigned EltTySize = CGM.getTargetData().getABITypeSizeInBits(EltTy); 298 299 NewVal = Builder.CreateIntCast(NewVal, EltTy, false, "tmp"); 300 301 // Move the bits into the appropriate location 302 llvm::Value *ShAmt = llvm::ConstantInt::get(EltTy, StartBit); 303 NewVal = Builder.CreateShl(NewVal, ShAmt, "tmp"); 304 305 llvm::Constant *Mask = llvm::ConstantInt::get( 306 llvm::APInt::getBitsSet(EltTySize, StartBit, 307 StartBit + BitfieldSize)); 308 309 // Mask out any bits that shouldn't be set in the result. 310 NewVal = Builder.CreateAnd(NewVal, Mask, "tmp"); 311 312 // Next, mask out the bits this bit-field should include from the old value. 313 Mask = llvm::ConstantExpr::getNot(Mask); 314 OldVal = Builder.CreateAnd(OldVal, Mask, "tmp"); 315 316 // Finally, merge the two together and store it. 317 NewVal = Builder.CreateOr(OldVal, NewVal, "tmp"); 318 319 Builder.CreateStore(NewVal, Ptr); 320} 321 322void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src, 323 LValue Dst, 324 QualType Ty) { 325 // This access turns into a read/modify/write of the vector. Load the input 326 // value now. 327 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(), "tmp"); 328 // FIXME: Volatility. 329 const llvm::Constant *Elts = Dst.getExtVectorElts(); 330 331 llvm::Value *SrcVal = Src.getScalarVal(); 332 333 if (const VectorType *VTy = Ty->getAsVectorType()) { 334 unsigned NumSrcElts = VTy->getNumElements(); 335 336 // Extract/Insert each element. 337 for (unsigned i = 0; i != NumSrcElts; ++i) { 338 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i); 339 Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp"); 340 341 unsigned Idx = ExtVectorElementExpr::getAccessedFieldNo(i, Elts); 342 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx); 343 Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp"); 344 } 345 } else { 346 // If the Src is a scalar (not a vector) it must be updating one element. 347 unsigned InIdx = ExtVectorElementExpr::getAccessedFieldNo(0, Elts); 348 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx); 349 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp"); 350 } 351 352 Builder.CreateStore(Vec, Dst.getExtVectorAddr()); 353} 354 355 356LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) { 357 const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()); 358 359 if (VD && (VD->isBlockVarDecl() || isa<ParmVarDecl>(VD))) { 360 if (VD->getStorageClass() == VarDecl::Extern) 361 return LValue::MakeAddr(CGM.GetAddrOfGlobalVar(VD, false)); 362 else { 363 llvm::Value *V = LocalDeclMap[VD]; 364 assert(V && "BlockVarDecl not entered in LocalDeclMap?"); 365 return LValue::MakeAddr(V); 366 } 367 } else if (VD && VD->isFileVarDecl()) { 368 return LValue::MakeAddr(CGM.GetAddrOfGlobalVar(VD, false)); 369 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) { 370 return LValue::MakeAddr(CGM.GetAddrOfFunctionDecl(FD, false)); 371 } 372 assert(0 && "Unimp declref"); 373 //an invalid LValue, but the assert will 374 //ensure that this point is never reached. 375 return LValue(); 376} 377 378LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) { 379 // __extension__ doesn't affect lvalue-ness. 380 if (E->getOpcode() == UnaryOperator::Extension) 381 return EmitLValue(E->getSubExpr()); 382 383 switch (E->getOpcode()) { 384 default: assert(0 && "Unknown unary operator lvalue!"); 385 case UnaryOperator::Deref: 386 return LValue::MakeAddr(EmitScalarExpr(E->getSubExpr())); 387 case UnaryOperator::Real: 388 case UnaryOperator::Imag: 389 LValue LV = EmitLValue(E->getSubExpr()); 390 unsigned Idx = E->getOpcode() == UnaryOperator::Imag; 391 return LValue::MakeAddr(Builder.CreateStructGEP(LV.getAddress(), 392 Idx, "idx")); 393 } 394} 395 396LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) { 397 assert(!E->isWide() && "FIXME: Wide strings not supported yet!"); 398 // Get the string data 399 const char *StrData = E->getStrData(); 400 unsigned Len = E->getByteLength(); 401 std::string StringLiteral(StrData, StrData+Len); 402 403 // Resize the string to the right size 404 const ConstantArrayType *CAT = E->getType()->getAsConstantArrayType(); 405 uint64_t RealLen = CAT->getSize().getZExtValue(); 406 StringLiteral.resize(RealLen, '\0'); 407 408 return LValue::MakeAddr(CGM.GetAddrOfConstantString(StringLiteral)); 409} 410 411LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) { 412 std::string FunctionName; 413 if(const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl)) { 414 FunctionName = FD->getName(); 415 } 416 else { 417 assert(0 && "Attempting to load predefined constant for invalid decl type"); 418 } 419 std::string GlobalVarName; 420 421 switch (E->getIdentType()) { 422 default: 423 assert(0 && "unknown pre-defined ident type"); 424 case PreDefinedExpr::Func: 425 GlobalVarName = "__func__."; 426 break; 427 case PreDefinedExpr::Function: 428 GlobalVarName = "__FUNCTION__."; 429 break; 430 case PreDefinedExpr::PrettyFunction: 431 // FIXME:: Demangle C++ method names 432 GlobalVarName = "__PRETTY_FUNCTION__."; 433 break; 434 } 435 436 GlobalVarName += FunctionName; 437 438 // FIXME: Can cache/reuse these within the module. 439 llvm::Constant *C=llvm::ConstantArray::get(FunctionName); 440 441 // Create a global variable for this. 442 C = new llvm::GlobalVariable(C->getType(), true, 443 llvm::GlobalValue::InternalLinkage, 444 C, GlobalVarName, CurFn->getParent()); 445 return LValue::MakeAddr(C); 446} 447 448LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) { 449 // The index must always be an integer, which is not an aggregate. Emit it. 450 llvm::Value *Idx = EmitScalarExpr(E->getIdx()); 451 452 // If the base is a vector type, then we are forming a vector element lvalue 453 // with this subscript. 454 if (E->getLHS()->getType()->isVectorType()) { 455 // Emit the vector as an lvalue to get its address. 456 LValue LHS = EmitLValue(E->getLHS()); 457 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!"); 458 // FIXME: This should properly sign/zero/extend or truncate Idx to i32. 459 return LValue::MakeVectorElt(LHS.getAddress(), Idx); 460 } 461 462 // The base must be a pointer, which is not an aggregate. Emit it. 463 llvm::Value *Base = EmitScalarExpr(E->getBase()); 464 465 // Extend or truncate the index type to 32 or 64-bits. 466 QualType IdxTy = E->getIdx()->getType(); 467 bool IdxSigned = IdxTy->isSignedIntegerType(); 468 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 469 if (IdxBitwidth != LLVMPointerWidth) 470 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth), 471 IdxSigned, "idxprom"); 472 473 // We know that the pointer points to a type of the correct size, unless the 474 // size is a VLA. 475 if (!E->getType()->isConstantSizeType()) 476 assert(0 && "VLA idx not implemented"); 477 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx")); 478} 479 480static 481llvm::Constant *GenerateConstantVector(llvm::SmallVector<unsigned, 4> &Elts) { 482 llvm::SmallVector<llvm::Constant *, 4> CElts; 483 484 for (unsigned i = 0, e = Elts.size(); i != e; ++i) 485 CElts.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, Elts[i])); 486 487 return llvm::ConstantVector::get(&CElts[0], CElts.size()); 488} 489 490LValue CodeGenFunction:: 491EmitExtVectorElementExpr(const ExtVectorElementExpr *E) { 492 // Emit the base vector as an l-value. 493 LValue Base = EmitLValue(E->getBase()); 494 495 // Encode the element access list into a vector of unsigned indices. 496 llvm::SmallVector<unsigned, 4> Indices; 497 E->getEncodedElementAccess(Indices); 498 499 if (Base.isSimple()) { 500 llvm::Constant *CV = GenerateConstantVector(Indices); 501 return LValue::MakeExtVectorElt(Base.getAddress(), CV); 502 } 503 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!"); 504 505 llvm::Constant *BaseElts = Base.getExtVectorElts(); 506 llvm::SmallVector<llvm::Constant *, 4> CElts; 507 508 for (unsigned i = 0, e = Indices.size(); i != e; ++i) { 509 if (isa<llvm::ConstantAggregateZero>(BaseElts)) 510 CElts.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0)); 511 else 512 CElts.push_back(BaseElts->getOperand(Indices[i])); 513 } 514 llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size()); 515 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV); 516} 517 518LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) { 519 bool isUnion = false; 520 Expr *BaseExpr = E->getBase(); 521 llvm::Value *BaseValue = NULL; 522 523 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 524 if (E->isArrow()) { 525 BaseValue = EmitScalarExpr(BaseExpr); 526 const PointerType *PTy = 527 cast<PointerType>(BaseExpr->getType().getCanonicalType()); 528 if (PTy->getPointeeType()->isUnionType()) 529 isUnion = true; 530 } 531 else { 532 LValue BaseLV = EmitLValue(BaseExpr); 533 // FIXME: this isn't right for bitfields. 534 BaseValue = BaseLV.getAddress(); 535 if (BaseExpr->getType()->isUnionType()) 536 isUnion = true; 537 } 538 539 FieldDecl *Field = E->getMemberDecl(); 540 return EmitLValueForField(BaseValue, Field, isUnion); 541} 542 543LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue, 544 FieldDecl* Field, 545 bool isUnion) 546{ 547 llvm::Value *V; 548 unsigned idx = CGM.getTypes().getLLVMFieldNo(Field); 549 550 if (!Field->isBitField()) { 551 V = Builder.CreateStructGEP(BaseValue, idx, "tmp"); 552 } else { 553 // FIXME: CodeGenTypes should expose a method to get the appropriate 554 // type for FieldTy (the appropriate type is ABI-dependent). 555 unsigned EltTySize = 556 CGM.getTargetData().getABITypeSizeInBits(ConvertType(Field->getType())); 557 const llvm::Type *FieldTy = llvm::IntegerType::get(EltTySize); 558 const llvm::PointerType *BaseTy = 559 cast<llvm::PointerType>(BaseValue->getType()); 560 unsigned AS = BaseTy->getAddressSpace(); 561 BaseValue = Builder.CreateBitCast(BaseValue, 562 llvm::PointerType::get(FieldTy, AS), 563 "tmp"); 564 V = Builder.CreateGEP(BaseValue, 565 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx), 566 "tmp"); 567 } 568 569 // Match union field type. 570 if (isUnion) { 571 const llvm::Type * FieldTy = ConvertType(Field->getType()); 572 const llvm::PointerType * BaseTy = 573 cast<llvm::PointerType>(BaseValue->getType()); 574 if (FieldTy != BaseTy->getElementType()) { 575 unsigned AS = BaseTy->getAddressSpace(); 576 V = Builder.CreateBitCast(V, 577 llvm::PointerType::get(FieldTy, AS), 578 "tmp"); 579 } 580 } 581 582 if (!Field->isBitField()) 583 return LValue::MakeAddr(V); 584 585 CodeGenTypes::BitFieldInfo bitFieldInfo = 586 CGM.getTypes().getBitFieldInfo(Field); 587 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size, 588 Field->getType()->isSignedIntegerType()); 589} 590 591LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr* E) { 592 const llvm::Type *LTy = ConvertType(E->getType()); 593 llvm::Value *DeclPtr = CreateTempAlloca(LTy, ".compoundliteral"); 594 595 const Expr* InitExpr = E->getInitializer(); 596 LValue Result = LValue::MakeAddr(DeclPtr); 597 598 if (E->getType()->isComplexType()) { 599 EmitComplexExprIntoAddr(InitExpr, DeclPtr, false); 600 } else if (hasAggregateLLVMType(E->getType())) { 601 EmitAnyExpr(InitExpr, DeclPtr, false); 602 } else { 603 EmitStoreThroughLValue(EmitAnyExpr(InitExpr), Result, E->getType()); 604 } 605 606 return Result; 607} 608 609//===--------------------------------------------------------------------===// 610// Expression Emission 611//===--------------------------------------------------------------------===// 612 613 614RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) { 615 if (const ImplicitCastExpr *IcExpr = 616 dyn_cast<const ImplicitCastExpr>(E->getCallee())) 617 if (const DeclRefExpr *DRExpr = 618 dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr())) 619 if (const FunctionDecl *FDecl = 620 dyn_cast<const FunctionDecl>(DRExpr->getDecl())) 621 if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID()) 622 return EmitBuiltinExpr(builtinID, E); 623 624 llvm::Value *Callee = EmitScalarExpr(E->getCallee()); 625 return EmitCallExpr(Callee, E->getCallee()->getType(), 626 E->arg_begin(), E->getNumArgs()); 627} 628 629RValue CodeGenFunction::EmitCallExpr(Expr *FnExpr, Expr *const *Args, 630 unsigned NumArgs) { 631 llvm::Value *Callee = EmitScalarExpr(FnExpr); 632 return EmitCallExpr(Callee, FnExpr->getType(), Args, NumArgs); 633} 634 635LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) { 636 // Can only get l-value for call expression returning aggregate type 637 RValue RV = EmitCallExpr(E); 638 return LValue::MakeAddr(RV.getAggregateAddr()); 639} 640 641LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) { 642 // Objective-C objects are traditionally C structures with their layout 643 // defined at compile-time. In some implementations, their layout is not 644 // defined until run time in order to allow instance variables to be added to 645 // a class without recompiling all of the subclasses. If this is the case 646 // then the CGObjCRuntime subclass must return true to LateBoundIvars and 647 // implement the lookup itself. 648 if (CGM.getObjCRuntime()->LateBoundIVars()) { 649 assert(0 && "FIXME: Implement support for late-bound instance variables"); 650 return LValue(); // Not reached. 651 } 652 653 // Get a structure type for the object 654 QualType ExprTy = E->getBase()->getType(); 655 const llvm::Type *ObjectType = ConvertType(ExprTy); 656 // TODO: Add a special case for isa (index 0) 657 // Work out which index the ivar is 658 const ObjCIvarDecl *Decl = E->getDecl(); 659 unsigned Index = CGM.getTypes().getLLVMFieldNo(Decl); 660 661 // Get object pointer and coerce object pointer to correct type. 662 llvm::Value *Object = EmitLValue(E->getBase()).getAddress(); 663 Object = Builder.CreateLoad(Object, E->getDecl()->getName()); 664 if (Object->getType() != ObjectType) 665 Object = Builder.CreateBitCast(Object, ObjectType); 666 667 668 // Return a pointer to the right element. 669 return LValue::MakeAddr(Builder.CreateStructGEP(Object, Index, 670 Decl->getName())); 671} 672 673RValue CodeGenFunction::EmitCallExpr(llvm::Value *Callee, QualType FnType, 674 Expr *const *ArgExprs, unsigned NumArgs) { 675 // The callee type will always be a pointer to function type, get the function 676 // type. 677 FnType = cast<PointerType>(FnType.getCanonicalType())->getPointeeType(); 678 QualType ResultType = cast<FunctionType>(FnType)->getResultType(); 679 680 llvm::SmallVector<llvm::Value*, 16> Args; 681 682 // Handle struct-return functions by passing a pointer to the location that 683 // we would like to return into. 684 if (hasAggregateLLVMType(ResultType)) { 685 // Create a temporary alloca to hold the result of the call. :( 686 Args.push_back(CreateTempAlloca(ConvertType(ResultType))); 687 // FIXME: set the stret attribute on the argument. 688 } 689 690 for (unsigned i = 0, e = NumArgs; i != e; ++i) { 691 QualType ArgTy = ArgExprs[i]->getType(); 692 693 if (!hasAggregateLLVMType(ArgTy)) { 694 // Scalar argument is passed by-value. 695 Args.push_back(EmitScalarExpr(ArgExprs[i])); 696 } else if (ArgTy->isAnyComplexType()) { 697 // Make a temporary alloca to pass the argument. 698 llvm::Value *DestMem = CreateTempAlloca(ConvertType(ArgTy)); 699 EmitComplexExprIntoAddr(ArgExprs[i], DestMem, false); 700 Args.push_back(DestMem); 701 } else { 702 llvm::Value *DestMem = CreateTempAlloca(ConvertType(ArgTy)); 703 EmitAggExpr(ArgExprs[i], DestMem, false); 704 Args.push_back(DestMem); 705 } 706 } 707 708 llvm::CallInst *CI = Builder.CreateCall(Callee,&Args[0],&Args[0]+Args.size()); 709 if (const llvm::Function *F = dyn_cast<llvm::Function>(Callee)) 710 CI->setCallingConv(F->getCallingConv()); 711 if (CI->getType() != llvm::Type::VoidTy) 712 CI->setName("call"); 713 else if (ResultType->isAnyComplexType()) 714 return RValue::getComplex(LoadComplexFromAddr(Args[0], false)); 715 else if (hasAggregateLLVMType(ResultType)) 716 // Struct return. 717 return RValue::getAggregate(Args[0]); 718 else { 719 // void return. 720 assert(ResultType->isVoidType() && "Should only have a void expr here"); 721 CI = 0; 722 } 723 724 return RValue::get(CI); 725} 726