1 //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate 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 Aggregate 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/DeclCXX.h" 19 #include "clang/AST/StmtVisitor.h" 20 #include "llvm/Constants.h" 21 #include "llvm/Function.h" 22 #include "llvm/GlobalVariable.h" 23 #include "llvm/Intrinsics.h" 24 using namespace clang; 25 using namespace CodeGen; 26 27 //===----------------------------------------------------------------------===// 28 // Aggregate Expression Emitter 29 //===----------------------------------------------------------------------===// 30 31 namespace { 32 class AggExprEmitter : public StmtVisitor<AggExprEmitter> { 33 CodeGenFunction &CGF; 34 CGBuilderTy &Builder; 35 llvm::Value *DestPtr; 36 bool VolatileDest; 37 bool IgnoreResult; 38 bool IsInitializer; 39 bool RequiresGCollection; 40 41 ReturnValueSlot getReturnValueSlot() const { 42 // If the destination slot requires garbage collection, we can't 43 // use the real return value slot, because we have to use the GC 44 // API. 45 if (RequiresGCollection) return ReturnValueSlot(); 46 47 return ReturnValueSlot(DestPtr, VolatileDest); 48 } 49 50 public: 51 AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool v, 52 bool ignore, bool isinit, bool requiresGCollection) 53 : CGF(cgf), Builder(CGF.Builder), 54 DestPtr(destPtr), VolatileDest(v), IgnoreResult(ignore), 55 IsInitializer(isinit), RequiresGCollection(requiresGCollection) { 56 } 57 58 //===--------------------------------------------------------------------===// 59 // Utilities 60 //===--------------------------------------------------------------------===// 61 62 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 63 /// represents a value lvalue, this method emits the address of the lvalue, 64 /// then loads the result into DestPtr. 65 void EmitAggLoadOfLValue(const Expr *E); 66 67 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 68 void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false); 69 void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false); 70 71 void EmitGCMove(const Expr *E, RValue Src); 72 73 bool TypeRequiresGCollection(QualType T); 74 75 //===--------------------------------------------------------------------===// 76 // Visitor Methods 77 //===--------------------------------------------------------------------===// 78 79 void VisitStmt(Stmt *S) { 80 CGF.ErrorUnsupported(S, "aggregate expression"); 81 } 82 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); } 83 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); } 84 85 // l-values. 86 void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); } 87 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); } 88 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); } 89 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); } 90 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 91 EmitAggLoadOfLValue(E); 92 } 93 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 94 EmitAggLoadOfLValue(E); 95 } 96 void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { 97 EmitAggLoadOfLValue(E); 98 } 99 void VisitPredefinedExpr(const PredefinedExpr *E) { 100 EmitAggLoadOfLValue(E); 101 } 102 103 // Operators. 104 void VisitCastExpr(CastExpr *E); 105 void VisitCallExpr(const CallExpr *E); 106 void VisitStmtExpr(const StmtExpr *E); 107 void VisitBinaryOperator(const BinaryOperator *BO); 108 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO); 109 void VisitBinAssign(const BinaryOperator *E); 110 void VisitBinComma(const BinaryOperator *E); 111 void VisitUnaryAddrOf(const UnaryOperator *E); 112 113 void VisitObjCMessageExpr(ObjCMessageExpr *E); 114 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 115 EmitAggLoadOfLValue(E); 116 } 117 void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E); 118 void VisitObjCImplicitSetterGetterRefExpr(ObjCImplicitSetterGetterRefExpr *E); 119 120 void VisitConditionalOperator(const ConditionalOperator *CO); 121 void VisitChooseExpr(const ChooseExpr *CE); 122 void VisitInitListExpr(InitListExpr *E); 123 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E); 124 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 125 Visit(DAE->getExpr()); 126 } 127 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E); 128 void VisitCXXConstructExpr(const CXXConstructExpr *E); 129 void VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E); 130 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E); 131 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); } 132 133 void VisitVAArgExpr(VAArgExpr *E); 134 135 void EmitInitializationToLValue(Expr *E, LValue Address, QualType T); 136 void EmitNullInitializationToLValue(LValue Address, QualType T); 137 // case Expr::ChooseExprClass: 138 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); } 139 }; 140 } // end anonymous namespace. 141 142 //===----------------------------------------------------------------------===// 143 // Utilities 144 //===----------------------------------------------------------------------===// 145 146 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 147 /// represents a value lvalue, this method emits the address of the lvalue, 148 /// then loads the result into DestPtr. 149 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) { 150 LValue LV = CGF.EmitLValue(E); 151 EmitFinalDestCopy(E, LV); 152 } 153 154 /// \brief True if the given aggregate type requires special GC API calls. 155 bool AggExprEmitter::TypeRequiresGCollection(QualType T) { 156 // Only record types have members that might require garbage collection. 157 const RecordType *RecordTy = T->getAs<RecordType>(); 158 if (!RecordTy) return false; 159 160 // Don't mess with non-trivial C++ types. 161 RecordDecl *Record = RecordTy->getDecl(); 162 if (isa<CXXRecordDecl>(Record) && 163 (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() || 164 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor())) 165 return false; 166 167 // Check whether the type has an object member. 168 return Record->hasObjectMember(); 169 } 170 171 /// \brief Perform the final move to DestPtr if RequiresGCollection is set. 172 /// 173 /// The idea is that you do something like this: 174 /// RValue Result = EmitSomething(..., getReturnValueSlot()); 175 /// EmitGCMove(E, Result); 176 /// If GC doesn't interfere, this will cause the result to be emitted 177 /// directly into the return value slot. If GC does interfere, a final 178 /// move will be performed. 179 void AggExprEmitter::EmitGCMove(const Expr *E, RValue Src) { 180 if (RequiresGCollection) { 181 std::pair<uint64_t, unsigned> TypeInfo = 182 CGF.getContext().getTypeInfo(E->getType()); 183 unsigned long size = TypeInfo.first/8; 184 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType()); 185 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size); 186 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, DestPtr, 187 Src.getAggregateAddr(), 188 SizeVal); 189 } 190 } 191 192 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 193 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) { 194 assert(Src.isAggregate() && "value must be aggregate value!"); 195 196 // If the result is ignored, don't copy from the value. 197 if (DestPtr == 0) { 198 if (!Src.isVolatileQualified() || (IgnoreResult && Ignore)) 199 return; 200 // If the source is volatile, we must read from it; to do that, we need 201 // some place to put it. 202 DestPtr = CGF.CreateMemTemp(E->getType(), "agg.tmp"); 203 } 204 205 if (RequiresGCollection) { 206 std::pair<uint64_t, unsigned> TypeInfo = 207 CGF.getContext().getTypeInfo(E->getType()); 208 unsigned long size = TypeInfo.first/8; 209 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType()); 210 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size); 211 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, 212 DestPtr, Src.getAggregateAddr(), 213 SizeVal); 214 return; 215 } 216 // If the result of the assignment is used, copy the LHS there also. 217 // FIXME: Pass VolatileDest as well. I think we also need to merge volatile 218 // from the source as well, as we can't eliminate it if either operand 219 // is volatile, unless copy has volatile for both source and destination.. 220 CGF.EmitAggregateCopy(DestPtr, Src.getAggregateAddr(), E->getType(), 221 VolatileDest|Src.isVolatileQualified()); 222 } 223 224 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 225 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) { 226 assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc"); 227 228 EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(), 229 Src.isVolatileQualified()), 230 Ignore); 231 } 232 233 //===----------------------------------------------------------------------===// 234 // Visitor Methods 235 //===----------------------------------------------------------------------===// 236 237 void AggExprEmitter::VisitCastExpr(CastExpr *E) { 238 if (!DestPtr && E->getCastKind() != CastExpr::CK_Dynamic) { 239 Visit(E->getSubExpr()); 240 return; 241 } 242 243 switch (E->getCastKind()) { 244 default: assert(0 && "Unhandled cast kind!"); 245 246 case CastExpr::CK_Dynamic: { 247 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?"); 248 LValue LV = CGF.EmitCheckedLValue(E->getSubExpr()); 249 // FIXME: Do we also need to handle property references here? 250 if (LV.isSimple()) 251 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E)); 252 else 253 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast"); 254 255 if (DestPtr) 256 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination"); 257 break; 258 } 259 260 case CastExpr::CK_ToUnion: { 261 // GCC union extension 262 QualType Ty = E->getSubExpr()->getType(); 263 QualType PtrTy = CGF.getContext().getPointerType(Ty); 264 llvm::Value *CastPtr = Builder.CreateBitCast(DestPtr, 265 CGF.ConvertType(PtrTy)); 266 EmitInitializationToLValue(E->getSubExpr(), CGF.MakeAddrLValue(CastPtr, Ty), 267 Ty); 268 break; 269 } 270 271 case CastExpr::CK_DerivedToBase: 272 case CastExpr::CK_BaseToDerived: 273 case CastExpr::CK_UncheckedDerivedToBase: { 274 assert(0 && "cannot perform hierarchy conversion in EmitAggExpr: " 275 "should have been unpacked before we got here"); 276 break; 277 } 278 279 // FIXME: Remove the CK_Unknown check here. 280 case CastExpr::CK_Unknown: 281 case CastExpr::CK_NoOp: 282 case CastExpr::CK_UserDefinedConversion: 283 case CastExpr::CK_ConstructorConversion: 284 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(), 285 E->getType()) && 286 "Implicit cast types must be compatible"); 287 Visit(E->getSubExpr()); 288 break; 289 290 case CastExpr::CK_NullToMemberPointer: { 291 // If the subexpression's type is the C++0x nullptr_t, emit the 292 // subexpression, which may have side effects. 293 if (E->getSubExpr()->getType()->isNullPtrType()) 294 Visit(E->getSubExpr()); 295 296 const llvm::Type *PtrDiffTy = 297 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 298 299 llvm::Value *NullValue = llvm::Constant::getNullValue(PtrDiffTy); 300 llvm::Value *Ptr = Builder.CreateStructGEP(DestPtr, 0, "ptr"); 301 Builder.CreateStore(NullValue, Ptr, VolatileDest); 302 303 llvm::Value *Adj = Builder.CreateStructGEP(DestPtr, 1, "adj"); 304 Builder.CreateStore(NullValue, Adj, VolatileDest); 305 306 break; 307 } 308 309 case CastExpr::CK_LValueBitCast: 310 llvm_unreachable("there are no lvalue bit-casts on aggregates"); 311 break; 312 313 case CastExpr::CK_BitCast: { 314 // This must be a member function pointer cast. 315 Visit(E->getSubExpr()); 316 break; 317 } 318 319 case CastExpr::CK_DerivedToBaseMemberPointer: 320 case CastExpr::CK_BaseToDerivedMemberPointer: { 321 QualType SrcType = E->getSubExpr()->getType(); 322 323 llvm::Value *Src = CGF.CreateMemTemp(SrcType, "tmp"); 324 CGF.EmitAggExpr(E->getSubExpr(), Src, SrcType.isVolatileQualified()); 325 326 // Note that the AST doesn't distinguish between checked and 327 // unchecked member pointer conversions, so we always have to 328 // implement checked conversions here. This is inefficient for 329 // ABIs where an actual null check is thus required; fortunately, 330 // the Itanium and ARM ABIs ignore the adjustment value when 331 // considering null-ness. 332 CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, E, Src, 333 DestPtr, VolatileDest); 334 break; 335 } 336 } 337 } 338 339 void AggExprEmitter::VisitCallExpr(const CallExpr *E) { 340 if (E->getCallReturnType()->isReferenceType()) { 341 EmitAggLoadOfLValue(E); 342 return; 343 } 344 345 RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot()); 346 EmitGCMove(E, RV); 347 } 348 349 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) { 350 RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot()); 351 EmitGCMove(E, RV); 352 } 353 354 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 355 RValue RV = CGF.EmitObjCPropertyGet(E, getReturnValueSlot()); 356 EmitGCMove(E, RV); 357 } 358 359 void AggExprEmitter::VisitObjCImplicitSetterGetterRefExpr( 360 ObjCImplicitSetterGetterRefExpr *E) { 361 RValue RV = CGF.EmitObjCPropertyGet(E, getReturnValueSlot()); 362 EmitGCMove(E, RV); 363 } 364 365 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) { 366 CGF.EmitAnyExpr(E->getLHS(), 0, false, true); 367 CGF.EmitAggExpr(E->getRHS(), DestPtr, VolatileDest, 368 /*IgnoreResult=*/false, IsInitializer); 369 } 370 371 void AggExprEmitter::VisitUnaryAddrOf(const UnaryOperator *E) { 372 // We have a member function pointer. 373 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>(); 374 (void) MPT; 375 assert(MPT->getPointeeType()->isFunctionProtoType() && 376 "Unexpected member pointer type!"); 377 378 // The creation of member function pointers has no side effects; if 379 // there is no destination pointer, we have nothing to do. 380 if (!DestPtr) 381 return; 382 383 const DeclRefExpr *DRE = cast<DeclRefExpr>(E->getSubExpr()); 384 const CXXMethodDecl *MD = 385 cast<CXXMethodDecl>(DRE->getDecl())->getCanonicalDecl(); 386 387 const llvm::Type *PtrDiffTy = 388 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 389 390 llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr"); 391 llvm::Value *FuncPtr = CGF.CGM.GetCXXMemberFunctionPointerValue(MD); 392 Builder.CreateStore(FuncPtr, DstPtr, VolatileDest); 393 394 llvm::Value *AdjPtr = Builder.CreateStructGEP(DestPtr, 1, "dst.adj"); 395 // The adjustment will always be 0. 396 Builder.CreateStore(llvm::ConstantInt::get(PtrDiffTy, 0), AdjPtr, 397 VolatileDest); 398 } 399 400 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) { 401 CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest); 402 } 403 404 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) { 405 if (E->getOpcode() == BinaryOperator::PtrMemD || 406 E->getOpcode() == BinaryOperator::PtrMemI) 407 VisitPointerToDataMemberBinaryOperator(E); 408 else 409 CGF.ErrorUnsupported(E, "aggregate binary expression"); 410 } 411 412 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator( 413 const BinaryOperator *E) { 414 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E); 415 EmitFinalDestCopy(E, LV); 416 } 417 418 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { 419 // For an assignment to work, the value on the right has 420 // to be compatible with the value on the left. 421 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(), 422 E->getRHS()->getType()) 423 && "Invalid assignment"); 424 LValue LHS = CGF.EmitLValue(E->getLHS()); 425 426 // We have to special case property setters, otherwise we must have 427 // a simple lvalue (no aggregates inside vectors, bitfields). 428 if (LHS.isPropertyRef()) { 429 llvm::Value *AggLoc = DestPtr; 430 if (!AggLoc) 431 AggLoc = CGF.CreateMemTemp(E->getRHS()->getType()); 432 CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest); 433 CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(), 434 RValue::getAggregate(AggLoc, VolatileDest)); 435 } else if (LHS.isKVCRef()) { 436 llvm::Value *AggLoc = DestPtr; 437 if (!AggLoc) 438 AggLoc = CGF.CreateMemTemp(E->getRHS()->getType()); 439 CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest); 440 CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(), 441 RValue::getAggregate(AggLoc, VolatileDest)); 442 } else { 443 bool RequiresGCollection = false; 444 if (CGF.getContext().getLangOptions().getGCMode()) 445 RequiresGCollection = TypeRequiresGCollection(E->getLHS()->getType()); 446 447 // Codegen the RHS so that it stores directly into the LHS. 448 CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified(), 449 false, false, RequiresGCollection); 450 EmitFinalDestCopy(E, LHS, true); 451 } 452 } 453 454 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) { 455 if (!E->getLHS()) { 456 CGF.ErrorUnsupported(E, "conditional operator with missing LHS"); 457 return; 458 } 459 460 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 461 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 462 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 463 464 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock); 465 466 CGF.BeginConditionalBranch(); 467 CGF.EmitBlock(LHSBlock); 468 469 // Handle the GNU extension for missing LHS. 470 assert(E->getLHS() && "Must have LHS for aggregate value"); 471 472 Visit(E->getLHS()); 473 CGF.EndConditionalBranch(); 474 CGF.EmitBranch(ContBlock); 475 476 CGF.BeginConditionalBranch(); 477 CGF.EmitBlock(RHSBlock); 478 479 Visit(E->getRHS()); 480 CGF.EndConditionalBranch(); 481 CGF.EmitBranch(ContBlock); 482 483 CGF.EmitBlock(ContBlock); 484 } 485 486 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) { 487 Visit(CE->getChosenSubExpr(CGF.getContext())); 488 } 489 490 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 491 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 492 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 493 494 if (!ArgPtr) { 495 CGF.ErrorUnsupported(VE, "aggregate va_arg expression"); 496 return; 497 } 498 499 EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType())); 500 } 501 502 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 503 llvm::Value *Val = DestPtr; 504 505 if (!Val) { 506 // Create a temporary variable. 507 Val = CGF.CreateMemTemp(E->getType(), "tmp"); 508 509 // FIXME: volatile 510 CGF.EmitAggExpr(E->getSubExpr(), Val, false); 511 } else 512 Visit(E->getSubExpr()); 513 514 // Don't make this a live temporary if we're emitting an initializer expr. 515 if (!IsInitializer) 516 CGF.EmitCXXTemporary(E->getTemporary(), Val); 517 } 518 519 void 520 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) { 521 llvm::Value *Val = DestPtr; 522 523 if (!Val) // Create a temporary variable. 524 Val = CGF.CreateMemTemp(E->getType(), "tmp"); 525 526 if (E->requiresZeroInitialization()) 527 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Val, E->getType()), 528 E->getType()); 529 530 CGF.EmitCXXConstructExpr(Val, E); 531 } 532 533 void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) { 534 llvm::Value *Val = DestPtr; 535 536 CGF.EmitCXXExprWithTemporaries(E, Val, VolatileDest, IsInitializer); 537 } 538 539 void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) { 540 llvm::Value *Val = DestPtr; 541 542 if (!Val) { 543 // Create a temporary variable. 544 Val = CGF.CreateMemTemp(E->getType(), "tmp"); 545 } 546 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Val, E->getType()), 547 E->getType()); 548 } 549 550 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) { 551 llvm::Value *Val = DestPtr; 552 553 if (!Val) { 554 // Create a temporary variable. 555 Val = CGF.CreateMemTemp(E->getType(), "tmp"); 556 } 557 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Val, E->getType()), 558 E->getType()); 559 } 560 561 void 562 AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV, QualType T) { 563 // FIXME: Ignore result? 564 // FIXME: Are initializers affected by volatile? 565 if (isa<ImplicitValueInitExpr>(E)) { 566 EmitNullInitializationToLValue(LV, T); 567 } else if (T->isReferenceType()) { 568 RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0); 569 CGF.EmitStoreThroughLValue(RV, LV, T); 570 } else if (T->isAnyComplexType()) { 571 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false); 572 } else if (CGF.hasAggregateLLVMType(T)) { 573 CGF.EmitAnyExpr(E, LV.getAddress(), false); 574 } else { 575 CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, T); 576 } 577 } 578 579 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) { 580 if (!CGF.hasAggregateLLVMType(T)) { 581 // For non-aggregates, we can store zero 582 llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T)); 583 CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T); 584 } else { 585 // There's a potential optimization opportunity in combining 586 // memsets; that would be easy for arrays, but relatively 587 // difficult for structures with the current code. 588 CGF.EmitNullInitialization(LV.getAddress(), T); 589 } 590 } 591 592 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { 593 #if 0 594 // FIXME: Assess perf here? Figure out what cases are worth optimizing here 595 // (Length of globals? Chunks of zeroed-out space?). 596 // 597 // If we can, prefer a copy from a global; this is a lot less code for long 598 // globals, and it's easier for the current optimizers to analyze. 599 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) { 600 llvm::GlobalVariable* GV = 601 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true, 602 llvm::GlobalValue::InternalLinkage, C, ""); 603 EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType())); 604 return; 605 } 606 #endif 607 if (E->hadArrayRangeDesignator()) { 608 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 609 } 610 611 // Handle initialization of an array. 612 if (E->getType()->isArrayType()) { 613 const llvm::PointerType *APType = 614 cast<llvm::PointerType>(DestPtr->getType()); 615 const llvm::ArrayType *AType = 616 cast<llvm::ArrayType>(APType->getElementType()); 617 618 uint64_t NumInitElements = E->getNumInits(); 619 620 if (E->getNumInits() > 0) { 621 QualType T1 = E->getType(); 622 QualType T2 = E->getInit(0)->getType(); 623 if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) { 624 EmitAggLoadOfLValue(E->getInit(0)); 625 return; 626 } 627 } 628 629 uint64_t NumArrayElements = AType->getNumElements(); 630 QualType ElementType = CGF.getContext().getCanonicalType(E->getType()); 631 ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType(); 632 633 // FIXME: were we intentionally ignoring address spaces and GC attributes? 634 635 for (uint64_t i = 0; i != NumArrayElements; ++i) { 636 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 637 LValue LV = CGF.MakeAddrLValue(NextVal, ElementType); 638 if (i < NumInitElements) 639 EmitInitializationToLValue(E->getInit(i), LV, ElementType); 640 641 else 642 EmitNullInitializationToLValue(LV, ElementType); 643 } 644 return; 645 } 646 647 assert(E->getType()->isRecordType() && "Only support structs/unions here!"); 648 649 // Do struct initialization; this code just sets each individual member 650 // to the approprate value. This makes bitfield support automatic; 651 // the disadvantage is that the generated code is more difficult for 652 // the optimizer, especially with bitfields. 653 unsigned NumInitElements = E->getNumInits(); 654 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl(); 655 unsigned CurInitVal = 0; 656 657 if (E->getType()->isUnionType()) { 658 // Only initialize one field of a union. The field itself is 659 // specified by the initializer list. 660 if (!E->getInitializedFieldInUnion()) { 661 // Empty union; we have nothing to do. 662 663 #ifndef NDEBUG 664 // Make sure that it's really an empty and not a failure of 665 // semantic analysis. 666 for (RecordDecl::field_iterator Field = SD->field_begin(), 667 FieldEnd = SD->field_end(); 668 Field != FieldEnd; ++Field) 669 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed"); 670 #endif 671 return; 672 } 673 674 // FIXME: volatility 675 FieldDecl *Field = E->getInitializedFieldInUnion(); 676 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0); 677 678 if (NumInitElements) { 679 // Store the initializer into the field 680 EmitInitializationToLValue(E->getInit(0), FieldLoc, Field->getType()); 681 } else { 682 // Default-initialize to null 683 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 684 } 685 686 return; 687 } 688 689 // If we're initializing the whole aggregate, just do it in place. 690 // FIXME: This is a hack around an AST bug (PR6537). 691 if (NumInitElements == 1 && E->getType() == E->getInit(0)->getType()) { 692 EmitInitializationToLValue(E->getInit(0), 693 CGF.MakeAddrLValue(DestPtr, E->getType()), 694 E->getType()); 695 return; 696 } 697 698 699 // Here we iterate over the fields; this makes it simpler to both 700 // default-initialize fields and skip over unnamed fields. 701 for (RecordDecl::field_iterator Field = SD->field_begin(), 702 FieldEnd = SD->field_end(); 703 Field != FieldEnd; ++Field) { 704 // We're done once we hit the flexible array member 705 if (Field->getType()->isIncompleteArrayType()) 706 break; 707 708 if (Field->isUnnamedBitfield()) 709 continue; 710 711 // FIXME: volatility 712 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, *Field, 0); 713 // We never generate write-barries for initialized fields. 714 FieldLoc.setNonGC(true); 715 if (CurInitVal < NumInitElements) { 716 // Store the initializer into the field. 717 EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc, 718 Field->getType()); 719 } else { 720 // We're out of initalizers; default-initialize to null 721 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 722 } 723 } 724 } 725 726 //===----------------------------------------------------------------------===// 727 // Entry Points into this File 728 //===----------------------------------------------------------------------===// 729 730 /// EmitAggExpr - Emit the computation of the specified expression of aggregate 731 /// type. The result is computed into DestPtr. Note that if DestPtr is null, 732 /// the value of the aggregate expression is not needed. If VolatileDest is 733 /// true, DestPtr cannot be 0. 734 // 735 // FIXME: Take Qualifiers object. 736 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr, 737 bool VolatileDest, bool IgnoreResult, 738 bool IsInitializer, 739 bool RequiresGCollection) { 740 assert(E && hasAggregateLLVMType(E->getType()) && 741 "Invalid aggregate expression to emit"); 742 assert ((DestPtr != 0 || VolatileDest == false) 743 && "volatile aggregate can't be 0"); 744 745 AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult, IsInitializer, 746 RequiresGCollection) 747 .Visit(const_cast<Expr*>(E)); 748 } 749 750 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) { 751 assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!"); 752 llvm::Value *Temp = CreateMemTemp(E->getType()); 753 LValue LV = MakeAddrLValue(Temp, E->getType()); 754 EmitAggExpr(E, Temp, LV.isVolatileQualified()); 755 return LV; 756 } 757 758 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr, 759 llvm::Value *SrcPtr, QualType Ty, 760 bool isVolatile) { 761 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 762 763 if (getContext().getLangOptions().CPlusPlus) { 764 if (const RecordType *RT = Ty->getAs<RecordType>()) { 765 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); 766 assert((Record->hasTrivialCopyConstructor() || 767 Record->hasTrivialCopyAssignment()) && 768 "Trying to aggregate-copy a type without a trivial copy " 769 "constructor or assignment operator"); 770 // Ignore empty classes in C++. 771 if (Record->isEmpty()) 772 return; 773 } 774 } 775 776 // Aggregate assignment turns into llvm.memcpy. This is almost valid per 777 // C99 6.5.16.1p3, which states "If the value being stored in an object is 778 // read from another object that overlaps in anyway the storage of the first 779 // object, then the overlap shall be exact and the two objects shall have 780 // qualified or unqualified versions of a compatible type." 781 // 782 // memcpy is not defined if the source and destination pointers are exactly 783 // equal, but other compilers do this optimization, and almost every memcpy 784 // implementation handles this case safely. If there is a libc that does not 785 // safely handle this, we can add a target hook. 786 787 // Get size and alignment info for this aggregate. 788 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 789 790 // FIXME: Handle variable sized types. 791 792 // FIXME: If we have a volatile struct, the optimizer can remove what might 793 // appear to be `extra' memory ops: 794 // 795 // volatile struct { int i; } a, b; 796 // 797 // int main() { 798 // a = b; 799 // a = b; 800 // } 801 // 802 // we need to use a different call here. We use isVolatile to indicate when 803 // either the source or the destination is volatile. 804 805 const llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType()); 806 const llvm::Type *DBP = 807 llvm::Type::getInt8PtrTy(VMContext, DPT->getAddressSpace()); 808 DestPtr = Builder.CreateBitCast(DestPtr, DBP, "tmp"); 809 810 const llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType()); 811 const llvm::Type *SBP = 812 llvm::Type::getInt8PtrTy(VMContext, SPT->getAddressSpace()); 813 SrcPtr = Builder.CreateBitCast(SrcPtr, SBP, "tmp"); 814 815 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) { 816 RecordDecl *Record = RecordTy->getDecl(); 817 if (Record->hasObjectMember()) { 818 unsigned long size = TypeInfo.first/8; 819 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 820 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size); 821 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, 822 SizeVal); 823 return; 824 } 825 } else if (getContext().getAsArrayType(Ty)) { 826 QualType BaseType = getContext().getBaseElementType(Ty); 827 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 828 if (RecordTy->getDecl()->hasObjectMember()) { 829 unsigned long size = TypeInfo.first/8; 830 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 831 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size); 832 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, 833 SizeVal); 834 return; 835 } 836 } 837 } 838 839 Builder.CreateCall5(CGM.getMemCpyFn(DestPtr->getType(), SrcPtr->getType(), 840 IntPtrTy), 841 DestPtr, SrcPtr, 842 // TypeInfo.first describes size in bits. 843 llvm::ConstantInt::get(IntPtrTy, TypeInfo.first/8), 844 Builder.getInt32(TypeInfo.second/8), 845 Builder.getInt1(isVolatile)); 846 } 847