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