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 "CGObjCRuntime.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/DeclObjC.h" 19 #include "llvm/Target/TargetData.h" 20 using namespace clang; 21 using namespace CodeGen; 22 23 //===--------------------------------------------------------------------===// 24 // Miscellaneous Helper Methods 25 //===--------------------------------------------------------------------===// 26 27 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 28 /// block. 29 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty, 30 const char *Name) { 31 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt); 32 } 33 34 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 35 /// expression and compare the result against zero, returning an Int1Ty value. 36 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) { 37 QualType BoolTy = getContext().BoolTy; 38 if (!E->getType()->isAnyComplexType()) 39 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy); 40 41 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy); 42 } 43 44 /// EmitAnyExpr - Emit code to compute the specified expression which can have 45 /// any type. The result is returned as an RValue struct. If this is an 46 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 47 /// the result should be returned. 48 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, llvm::Value *AggLoc, 49 bool isAggLocVolatile) { 50 if (!hasAggregateLLVMType(E->getType())) 51 return RValue::get(EmitScalarExpr(E)); 52 else if (E->getType()->isAnyComplexType()) 53 return RValue::getComplex(EmitComplexExpr(E)); 54 55 EmitAggExpr(E, AggLoc, isAggLocVolatile); 56 return RValue::getAggregate(AggLoc); 57 } 58 59 /// getAccessedFieldNo - Given an encoded value and a result number, return 60 /// the input field number being accessed. 61 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx, 62 const llvm::Constant *Elts) { 63 if (isa<llvm::ConstantAggregateZero>(Elts)) 64 return 0; 65 66 return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue(); 67 } 68 69 70 //===----------------------------------------------------------------------===// 71 // LValue Expression Emission 72 //===----------------------------------------------------------------------===// 73 74 /// EmitLValue - Emit code to compute a designator that specifies the location 75 /// of the expression. 76 /// 77 /// This can return one of two things: a simple address or a bitfield 78 /// reference. In either case, the LLVM Value* in the LValue structure is 79 /// guaranteed to be an LLVM pointer type. 80 /// 81 /// If this returns a bitfield reference, nothing about the pointee type of 82 /// the LLVM value is known: For example, it may not be a pointer to an 83 /// integer. 84 /// 85 /// If this returns a normal address, and if the lvalue's C type is fixed 86 /// size, this method guarantees that the returned pointer type will point to 87 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 88 /// variable length type, this is not possible. 89 /// 90 LValue CodeGenFunction::EmitLValue(const Expr *E) { 91 switch (E->getStmtClass()) { 92 default: { 93 ErrorUnsupported(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. 125 RValue 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 169 RValue 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. 234 RValue 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'. 291 void 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 330 void 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 401 void 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 435 LValue 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 467 LValue 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 489 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) { 490 return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromLiteral(E), 0); 491 } 492 493 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) { 494 std::string FunctionName; 495 if(const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl)) { 496 FunctionName = FD->getName(); 497 } 498 else { 499 assert(0 && "Attempting to load predefined constant for invalid decl type"); 500 } 501 std::string GlobalVarName; 502 503 switch (E->getIdentType()) { 504 default: 505 assert(0 && "unknown pre-defined ident type"); 506 case PredefinedExpr::Func: 507 GlobalVarName = "__func__."; 508 break; 509 case PredefinedExpr::Function: 510 GlobalVarName = "__FUNCTION__."; 511 break; 512 case PredefinedExpr::PrettyFunction: 513 // FIXME:: Demangle C++ method names 514 GlobalVarName = "__PRETTY_FUNCTION__."; 515 break; 516 } 517 518 GlobalVarName += FunctionName; 519 520 // FIXME: Can cache/reuse these within the module. 521 llvm::Constant *C=llvm::ConstantArray::get(FunctionName); 522 523 // Create a global variable for this. 524 C = new llvm::GlobalVariable(C->getType(), true, 525 llvm::GlobalValue::InternalLinkage, 526 C, GlobalVarName, CurFn->getParent()); 527 return LValue::MakeAddr(C,0); 528 } 529 530 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) { 531 // The index must always be an integer, which is not an aggregate. Emit it. 532 llvm::Value *Idx = EmitScalarExpr(E->getIdx()); 533 534 // If the base is a vector type, then we are forming a vector element lvalue 535 // with this subscript. 536 if (E->getBase()->getType()->isVectorType()) { 537 // Emit the vector as an lvalue to get its address. 538 LValue LHS = EmitLValue(E->getBase()); 539 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!"); 540 // FIXME: This should properly sign/zero/extend or truncate Idx to i32. 541 return LValue::MakeVectorElt(LHS.getAddress(), Idx, 542 E->getBase()->getType().getCVRQualifiers()); 543 } 544 545 // The base must be a pointer, which is not an aggregate. Emit it. 546 llvm::Value *Base = EmitScalarExpr(E->getBase()); 547 548 // Extend or truncate the index type to 32 or 64-bits. 549 QualType IdxTy = E->getIdx()->getType(); 550 bool IdxSigned = IdxTy->isSignedIntegerType(); 551 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 552 if (IdxBitwidth != LLVMPointerWidth) 553 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth), 554 IdxSigned, "idxprom"); 555 556 // We know that the pointer points to a type of the correct size, unless the 557 // size is a VLA. 558 if (!E->getType()->isConstantSizeType()) 559 assert(0 && "VLA idx not implemented"); 560 QualType ExprTy = getContext().getCanonicalType(E->getBase()->getType()); 561 562 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"), 563 ExprTy->getAsPointerType()->getPointeeType() 564 .getCVRQualifiers()); 565 } 566 567 static 568 llvm::Constant *GenerateConstantVector(llvm::SmallVector<unsigned, 4> &Elts) { 569 llvm::SmallVector<llvm::Constant *, 4> CElts; 570 571 for (unsigned i = 0, e = Elts.size(); i != e; ++i) 572 CElts.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, Elts[i])); 573 574 return llvm::ConstantVector::get(&CElts[0], CElts.size()); 575 } 576 577 LValue CodeGenFunction:: 578 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) { 579 // Emit the base vector as an l-value. 580 LValue Base = EmitLValue(E->getBase()); 581 582 // Encode the element access list into a vector of unsigned indices. 583 llvm::SmallVector<unsigned, 4> Indices; 584 E->getEncodedElementAccess(Indices); 585 586 if (Base.isSimple()) { 587 llvm::Constant *CV = GenerateConstantVector(Indices); 588 return LValue::MakeExtVectorElt(Base.getAddress(), CV, 589 E->getBase()->getType().getCVRQualifiers()); 590 } 591 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!"); 592 593 llvm::Constant *BaseElts = Base.getExtVectorElts(); 594 llvm::SmallVector<llvm::Constant *, 4> CElts; 595 596 for (unsigned i = 0, e = Indices.size(); i != e; ++i) { 597 if (isa<llvm::ConstantAggregateZero>(BaseElts)) 598 CElts.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0)); 599 else 600 CElts.push_back(BaseElts->getOperand(Indices[i])); 601 } 602 llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size()); 603 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, 604 E->getBase()->getType().getCVRQualifiers()); 605 } 606 607 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) { 608 bool isUnion = false; 609 Expr *BaseExpr = E->getBase(); 610 llvm::Value *BaseValue = NULL; 611 unsigned CVRQualifiers=0; 612 613 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 614 if (E->isArrow()) { 615 BaseValue = EmitScalarExpr(BaseExpr); 616 const PointerType *PTy = 617 cast<PointerType>(getContext().getCanonicalType(BaseExpr->getType())); 618 if (PTy->getPointeeType()->isUnionType()) 619 isUnion = true; 620 CVRQualifiers = PTy->getPointeeType().getCVRQualifiers(); 621 } 622 else { 623 LValue BaseLV = EmitLValue(BaseExpr); 624 // FIXME: this isn't right for bitfields. 625 BaseValue = BaseLV.getAddress(); 626 if (BaseExpr->getType()->isUnionType()) 627 isUnion = true; 628 CVRQualifiers = BaseExpr->getType().getCVRQualifiers(); 629 } 630 631 FieldDecl *Field = E->getMemberDecl(); 632 return EmitLValueForField(BaseValue, Field, isUnion, CVRQualifiers); 633 } 634 635 LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue, 636 FieldDecl* Field, 637 bool isUnion, 638 unsigned CVRQualifiers) 639 { 640 llvm::Value *V; 641 unsigned idx = CGM.getTypes().getLLVMFieldNo(Field); 642 643 if (Field->isBitField()) { 644 // FIXME: CodeGenTypes should expose a method to get the appropriate 645 // type for FieldTy (the appropriate type is ABI-dependent). 646 const llvm::Type *FieldTy = CGM.getTypes().ConvertTypeForMem(Field->getType()); 647 const llvm::PointerType *BaseTy = 648 cast<llvm::PointerType>(BaseValue->getType()); 649 unsigned AS = BaseTy->getAddressSpace(); 650 BaseValue = Builder.CreateBitCast(BaseValue, 651 llvm::PointerType::get(FieldTy, AS), 652 "tmp"); 653 V = Builder.CreateGEP(BaseValue, 654 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx), 655 "tmp"); 656 657 CodeGenTypes::BitFieldInfo bitFieldInfo = 658 CGM.getTypes().getBitFieldInfo(Field); 659 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size, 660 Field->getType()->isSignedIntegerType(), 661 Field->getType().getCVRQualifiers()|CVRQualifiers); 662 } 663 664 V = Builder.CreateStructGEP(BaseValue, idx, "tmp"); 665 666 // Match union field type. 667 if (isUnion) { 668 const llvm::Type *FieldTy = 669 CGM.getTypes().ConvertTypeForMem(Field->getType()); 670 const llvm::PointerType * BaseTy = 671 cast<llvm::PointerType>(BaseValue->getType()); 672 unsigned AS = BaseTy->getAddressSpace(); 673 V = Builder.CreateBitCast(V, 674 llvm::PointerType::get(FieldTy, AS), 675 "tmp"); 676 } 677 678 return LValue::MakeAddr(V, 679 Field->getType().getCVRQualifiers()|CVRQualifiers); 680 } 681 682 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr* E) 683 { 684 const llvm::Type *LTy = ConvertType(E->getType()); 685 llvm::Value *DeclPtr = CreateTempAlloca(LTy, ".compoundliteral"); 686 687 const Expr* InitExpr = E->getInitializer(); 688 LValue Result = LValue::MakeAddr(DeclPtr, E->getType().getCVRQualifiers()); 689 690 if (E->getType()->isComplexType()) { 691 EmitComplexExprIntoAddr(InitExpr, DeclPtr, false); 692 } else if (hasAggregateLLVMType(E->getType())) { 693 EmitAnyExpr(InitExpr, DeclPtr, false); 694 } else { 695 EmitStoreThroughLValue(EmitAnyExpr(InitExpr), Result, E->getType()); 696 } 697 698 return Result; 699 } 700 701 //===--------------------------------------------------------------------===// 702 // Expression Emission 703 //===--------------------------------------------------------------------===// 704 705 706 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) { 707 if (const ImplicitCastExpr *IcExpr = 708 dyn_cast<const ImplicitCastExpr>(E->getCallee())) 709 if (const DeclRefExpr *DRExpr = 710 dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr())) 711 if (const FunctionDecl *FDecl = 712 dyn_cast<const FunctionDecl>(DRExpr->getDecl())) 713 if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID()) 714 return EmitBuiltinExpr(builtinID, E); 715 716 llvm::Value *Callee = EmitScalarExpr(E->getCallee()); 717 return EmitCallExpr(Callee, E->getCallee()->getType(), 718 E->arg_begin(), E->arg_end()); 719 } 720 721 RValue CodeGenFunction::EmitCallExpr(Expr *FnExpr, 722 CallExpr::const_arg_iterator ArgBeg, 723 CallExpr::const_arg_iterator ArgEnd) { 724 725 llvm::Value *Callee = EmitScalarExpr(FnExpr); 726 return EmitCallExpr(Callee, FnExpr->getType(), ArgBeg, ArgEnd); 727 } 728 729 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) { 730 // Can only get l-value for call expression returning aggregate type 731 RValue RV = EmitCallExpr(E); 732 // FIXME: can this be volatile? 733 return LValue::MakeAddr(RV.getAggregateAddr(), 734 E->getType().getCVRQualifiers()); 735 } 736 737 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) { 738 // Objective-C objects are traditionally C structures with their layout 739 // defined at compile-time. In some implementations, their layout is not 740 // defined until run time in order to allow instance variables to be added to 741 // a class without recompiling all of the subclasses. If this is the case 742 // then the CGObjCRuntime subclass must return true to LateBoundIvars and 743 // implement the lookup itself. 744 if (CGM.getObjCRuntime().LateBoundIVars()) { 745 assert(0 && "FIXME: Implement support for late-bound instance variables"); 746 return LValue(); // Not reached. 747 } 748 749 // Get a structure type for the object 750 QualType ExprTy = E->getBase()->getType(); 751 const llvm::Type *ObjectType = ConvertType(ExprTy); 752 // TODO: Add a special case for isa (index 0) 753 // Work out which index the ivar is 754 const ObjCIvarDecl *Decl = E->getDecl(); 755 unsigned Index = CGM.getTypes().getLLVMFieldNo(Decl); 756 757 // Get object pointer and coerce object pointer to correct type. 758 llvm::Value *Object = EmitLValue(E->getBase()).getAddress(); 759 // FIXME: Volatility 760 Object = Builder.CreateLoad(Object, E->getDecl()->getName()); 761 if (Object->getType() != ObjectType) 762 Object = Builder.CreateBitCast(Object, ObjectType); 763 764 765 // Return a pointer to the right element. 766 // FIXME: volatile 767 return LValue::MakeAddr(Builder.CreateStructGEP(Object, Index, 768 Decl->getName()),0); 769 } 770 771 RValue CodeGenFunction::EmitCallExpr(llvm::Value *Callee, QualType FnType, 772 CallExpr::const_arg_iterator ArgBeg, 773 CallExpr::const_arg_iterator ArgEnd) { 774 775 // The callee type will always be a pointer to function type, get the function 776 // type. 777 FnType = FnType->getAsPointerType()->getPointeeType(); 778 QualType ResultType = FnType->getAsFunctionType()->getResultType(); 779 return EmitCallExprExt(Callee, ResultType, ArgBeg, ArgEnd, 0, 0); 780 } 781 782 RValue CodeGenFunction::EmitCallExprExt(llvm::Value *Callee, 783 QualType ResultType, 784 CallExpr::const_arg_iterator ArgBeg, 785 CallExpr::const_arg_iterator ArgEnd, 786 llvm::Value **ExtraArgs, 787 unsigned NumExtraArgs) { 788 llvm::SmallVector<llvm::Value*, 16> Args; 789 790 // Handle struct-return functions by passing a pointer to the location that 791 // we would like to return into. 792 if (hasAggregateLLVMType(ResultType)) { 793 // Create a temporary alloca to hold the result of the call. :( 794 Args.push_back(CreateTempAlloca(ConvertType(ResultType))); 795 // FIXME: set the stret attribute on the argument. 796 } 797 798 Args.insert(Args.end(), ExtraArgs, ExtraArgs + NumExtraArgs); 799 800 for (CallExpr::const_arg_iterator I = ArgBeg; I != ArgEnd; ++I) { 801 QualType ArgTy = I->getType(); 802 803 if (!hasAggregateLLVMType(ArgTy)) { 804 // Scalar argument is passed by-value. 805 Args.push_back(EmitScalarExpr(*I)); 806 } else if (ArgTy->isAnyComplexType()) { 807 // Make a temporary alloca to pass the argument. 808 llvm::Value *DestMem = CreateTempAlloca(ConvertType(ArgTy)); 809 EmitComplexExprIntoAddr(*I, DestMem, false); 810 Args.push_back(DestMem); 811 } else { 812 llvm::Value *DestMem = CreateTempAlloca(ConvertType(ArgTy)); 813 EmitAggExpr(*I, DestMem, false); 814 Args.push_back(DestMem); 815 } 816 } 817 818 llvm::CallInst *CI = Builder.CreateCall(Callee,&Args[0],&Args[0]+Args.size()); 819 820 // Note that there is parallel code in SetFunctionAttributes in CodeGenModule 821 llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList; 822 if (hasAggregateLLVMType(ResultType)) 823 ParamAttrList.push_back( 824 llvm::ParamAttrsWithIndex::get(1, llvm::ParamAttr::StructRet)); 825 unsigned increment = NumExtraArgs + (hasAggregateLLVMType(ResultType) ? 2 : 1); 826 827 unsigned i = 0; 828 for (CallExpr::const_arg_iterator I = ArgBeg; I != ArgEnd; ++I, ++i) { 829 QualType ParamType = I->getType(); 830 unsigned ParamAttrs = 0; 831 if (ParamType->isRecordType()) 832 ParamAttrs |= llvm::ParamAttr::ByVal; 833 if (ParamType->isSignedIntegerType() && ParamType->isPromotableIntegerType()) 834 ParamAttrs |= llvm::ParamAttr::SExt; 835 if (ParamType->isUnsignedIntegerType() && ParamType->isPromotableIntegerType()) 836 ParamAttrs |= llvm::ParamAttr::ZExt; 837 if (ParamAttrs) 838 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(i + increment, 839 ParamAttrs)); 840 } 841 CI->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(), 842 ParamAttrList.size())); 843 844 if (const llvm::Function *F = dyn_cast<llvm::Function>(Callee)) 845 CI->setCallingConv(F->getCallingConv()); 846 if (CI->getType() != llvm::Type::VoidTy) 847 CI->setName("call"); 848 else if (ResultType->isAnyComplexType()) 849 return RValue::getComplex(LoadComplexFromAddr(Args[0], false)); 850 else if (hasAggregateLLVMType(ResultType)) 851 // Struct return. 852 return RValue::getAggregate(Args[0]); 853 else { 854 // void return. 855 assert(ResultType->isVoidType() && "Should only have a void expr here"); 856 CI = 0; 857 } 858 859 return RValue::get(CI); 860 } 861