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