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