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