CGExprAgg.cpp revision 200583
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" 24using namespace clang; 25using namespace CodeGen; 26 27//===----------------------------------------------------------------------===// 28// Aggregate Expression Emitter 29//===----------------------------------------------------------------------===// 30 31namespace { 32class 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; 40public: 41 AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool v, 42 bool ignore, bool isinit, bool requiresGCollection) 43 : CGF(cgf), Builder(CGF.Builder), 44 DestPtr(destPtr), VolatileDest(v), IgnoreResult(ignore), 45 IsInitializer(isinit), RequiresGCollection(requiresGCollection) { 46 } 47 48 //===--------------------------------------------------------------------===// 49 // Utilities 50 //===--------------------------------------------------------------------===// 51 52 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 53 /// represents a value lvalue, this method emits the address of the lvalue, 54 /// then loads the result into DestPtr. 55 void EmitAggLoadOfLValue(const Expr *E); 56 57 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 58 void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false); 59 void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false); 60 61 //===--------------------------------------------------------------------===// 62 // Visitor Methods 63 //===--------------------------------------------------------------------===// 64 65 void VisitStmt(Stmt *S) { 66 CGF.ErrorUnsupported(S, "aggregate expression"); 67 } 68 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); } 69 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); } 70 71 // l-values. 72 void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); } 73 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); } 74 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); } 75 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); } 76 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 77 EmitAggLoadOfLValue(E); 78 } 79 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 80 EmitAggLoadOfLValue(E); 81 } 82 void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { 83 EmitAggLoadOfLValue(E); 84 } 85 void VisitPredefinedExpr(const PredefinedExpr *E) { 86 EmitAggLoadOfLValue(E); 87 } 88 89 // Operators. 90 void VisitCastExpr(CastExpr *E); 91 void VisitCallExpr(const CallExpr *E); 92 void VisitStmtExpr(const StmtExpr *E); 93 void VisitBinaryOperator(const BinaryOperator *BO); 94 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO); 95 void VisitBinAssign(const BinaryOperator *E); 96 void VisitBinComma(const BinaryOperator *E); 97 void VisitUnaryAddrOf(const UnaryOperator *E); 98 99 void VisitObjCMessageExpr(ObjCMessageExpr *E); 100 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 101 EmitAggLoadOfLValue(E); 102 } 103 void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E); 104 void VisitObjCImplicitSetterGetterRefExpr(ObjCImplicitSetterGetterRefExpr *E); 105 106 void VisitConditionalOperator(const ConditionalOperator *CO); 107 void VisitChooseExpr(const ChooseExpr *CE); 108 void VisitInitListExpr(InitListExpr *E); 109 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 110 Visit(DAE->getExpr()); 111 } 112 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E); 113 void VisitCXXConstructExpr(const CXXConstructExpr *E); 114 void VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E); 115 void VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E); 116 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); } 117 118 void VisitVAArgExpr(VAArgExpr *E); 119 120 void EmitInitializationToLValue(Expr *E, LValue Address); 121 void EmitNullInitializationToLValue(LValue Address, QualType T); 122 // case Expr::ChooseExprClass: 123 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); } 124}; 125} // end anonymous namespace. 126 127//===----------------------------------------------------------------------===// 128// Utilities 129//===----------------------------------------------------------------------===// 130 131/// EmitAggLoadOfLValue - Given an expression with aggregate type that 132/// represents a value lvalue, this method emits the address of the lvalue, 133/// then loads the result into DestPtr. 134void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) { 135 LValue LV = CGF.EmitLValue(E); 136 EmitFinalDestCopy(E, LV); 137} 138 139/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 140void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) { 141 assert(Src.isAggregate() && "value must be aggregate value!"); 142 143 // If the result is ignored, don't copy from the value. 144 if (DestPtr == 0) { 145 if (!Src.isVolatileQualified() || (IgnoreResult && Ignore)) 146 return; 147 // If the source is volatile, we must read from it; to do that, we need 148 // some place to put it. 149 DestPtr = CGF.CreateTempAlloca(CGF.ConvertType(E->getType()), "agg.tmp"); 150 } 151 152 if (RequiresGCollection) { 153 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, 154 DestPtr, Src.getAggregateAddr(), 155 E->getType()); 156 return; 157 } 158 // If the result of the assignment is used, copy the LHS there also. 159 // FIXME: Pass VolatileDest as well. I think we also need to merge volatile 160 // from the source as well, as we can't eliminate it if either operand 161 // is volatile, unless copy has volatile for both source and destination.. 162 CGF.EmitAggregateCopy(DestPtr, Src.getAggregateAddr(), E->getType(), 163 VolatileDest|Src.isVolatileQualified()); 164} 165 166/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 167void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) { 168 assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc"); 169 170 EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(), 171 Src.isVolatileQualified()), 172 Ignore); 173} 174 175//===----------------------------------------------------------------------===// 176// Visitor Methods 177//===----------------------------------------------------------------------===// 178 179void AggExprEmitter::VisitCastExpr(CastExpr *E) { 180 switch (E->getCastKind()) { 181 default: assert(0 && "Unhandled cast kind!"); 182 183 case CastExpr::CK_ToUnion: { 184 // GCC union extension 185 QualType PtrTy = 186 CGF.getContext().getPointerType(E->getSubExpr()->getType()); 187 llvm::Value *CastPtr = Builder.CreateBitCast(DestPtr, 188 CGF.ConvertType(PtrTy)); 189 EmitInitializationToLValue(E->getSubExpr(), 190 LValue::MakeAddr(CastPtr, Qualifiers())); 191 break; 192 } 193 194 // FIXME: Remove the CK_Unknown check here. 195 case CastExpr::CK_Unknown: 196 case CastExpr::CK_NoOp: 197 case CastExpr::CK_UserDefinedConversion: 198 case CastExpr::CK_ConstructorConversion: 199 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(), 200 E->getType()) && 201 "Implicit cast types must be compatible"); 202 Visit(E->getSubExpr()); 203 break; 204 205 case CastExpr::CK_NullToMemberPointer: { 206 const llvm::Type *PtrDiffTy = 207 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 208 209 llvm::Value *NullValue = llvm::Constant::getNullValue(PtrDiffTy); 210 llvm::Value *Ptr = Builder.CreateStructGEP(DestPtr, 0, "ptr"); 211 Builder.CreateStore(NullValue, Ptr, VolatileDest); 212 213 llvm::Value *Adj = Builder.CreateStructGEP(DestPtr, 1, "adj"); 214 Builder.CreateStore(NullValue, Adj, VolatileDest); 215 216 break; 217 } 218 219 case CastExpr::CK_BitCast: { 220 // This must be a member function pointer cast. 221 Visit(E->getSubExpr()); 222 break; 223 } 224 225 case CastExpr::CK_DerivedToBaseMemberPointer: 226 case CastExpr::CK_BaseToDerivedMemberPointer: { 227 QualType SrcType = E->getSubExpr()->getType(); 228 229 llvm::Value *Src = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(SrcType), 230 "tmp"); 231 CGF.EmitAggExpr(E->getSubExpr(), Src, SrcType.isVolatileQualified()); 232 233 llvm::Value *SrcPtr = Builder.CreateStructGEP(Src, 0, "src.ptr"); 234 SrcPtr = Builder.CreateLoad(SrcPtr); 235 236 llvm::Value *SrcAdj = Builder.CreateStructGEP(Src, 1, "src.adj"); 237 SrcAdj = Builder.CreateLoad(SrcAdj); 238 239 llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr"); 240 Builder.CreateStore(SrcPtr, DstPtr, VolatileDest); 241 242 llvm::Value *DstAdj = Builder.CreateStructGEP(DestPtr, 1, "dst.adj"); 243 244 // Now See if we need to update the adjustment. 245 const CXXRecordDecl *BaseDecl = 246 cast<CXXRecordDecl>(SrcType->getAs<MemberPointerType>()-> 247 getClass()->getAs<RecordType>()->getDecl()); 248 const CXXRecordDecl *DerivedDecl = 249 cast<CXXRecordDecl>(E->getType()->getAs<MemberPointerType>()-> 250 getClass()->getAs<RecordType>()->getDecl()); 251 if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer) 252 std::swap(DerivedDecl, BaseDecl); 253 254 llvm::Constant *Adj = CGF.CGM.GetCXXBaseClassOffset(DerivedDecl, BaseDecl); 255 if (Adj) { 256 if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer) 257 SrcAdj = Builder.CreateSub(SrcAdj, Adj, "adj"); 258 else 259 SrcAdj = Builder.CreateAdd(SrcAdj, Adj, "adj"); 260 } 261 262 Builder.CreateStore(SrcAdj, DstAdj, VolatileDest); 263 break; 264 } 265 } 266} 267 268void AggExprEmitter::VisitCallExpr(const CallExpr *E) { 269 if (E->getCallReturnType()->isReferenceType()) { 270 EmitAggLoadOfLValue(E); 271 return; 272 } 273 274 RValue RV = CGF.EmitCallExpr(E); 275 EmitFinalDestCopy(E, RV); 276} 277 278void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) { 279 RValue RV = CGF.EmitObjCMessageExpr(E); 280 EmitFinalDestCopy(E, RV); 281} 282 283void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 284 RValue RV = CGF.EmitObjCPropertyGet(E); 285 EmitFinalDestCopy(E, RV); 286} 287 288void AggExprEmitter::VisitObjCImplicitSetterGetterRefExpr( 289 ObjCImplicitSetterGetterRefExpr *E) { 290 RValue RV = CGF.EmitObjCPropertyGet(E); 291 EmitFinalDestCopy(E, RV); 292} 293 294void AggExprEmitter::VisitBinComma(const BinaryOperator *E) { 295 CGF.EmitAnyExpr(E->getLHS(), 0, false, true); 296 CGF.EmitAggExpr(E->getRHS(), DestPtr, VolatileDest, 297 /*IgnoreResult=*/false, IsInitializer); 298} 299 300void AggExprEmitter::VisitUnaryAddrOf(const UnaryOperator *E) { 301 // We have a member function pointer. 302 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>(); 303 (void) MPT; 304 assert(MPT->getPointeeType()->isFunctionProtoType() && 305 "Unexpected member pointer type!"); 306 307 const DeclRefExpr *DRE = cast<DeclRefExpr>(E->getSubExpr()); 308 const CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 309 310 const llvm::Type *PtrDiffTy = 311 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 312 313 llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr"); 314 llvm::Value *FuncPtr; 315 316 if (MD->isVirtual()) { 317 int64_t Index = 318 CGF.CGM.getVtableInfo().getMethodVtableIndex(MD); 319 320 FuncPtr = llvm::ConstantInt::get(PtrDiffTy, Index + 1); 321 } else { 322 FuncPtr = llvm::ConstantExpr::getPtrToInt(CGF.CGM.GetAddrOfFunction(MD), 323 PtrDiffTy); 324 } 325 Builder.CreateStore(FuncPtr, DstPtr, VolatileDest); 326 327 llvm::Value *AdjPtr = Builder.CreateStructGEP(DestPtr, 1, "dst.adj"); 328 329 // The adjustment will always be 0. 330 Builder.CreateStore(llvm::ConstantInt::get(PtrDiffTy, 0), AdjPtr, 331 VolatileDest); 332} 333 334void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) { 335 CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest); 336} 337 338void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) { 339 if (E->getOpcode() == BinaryOperator::PtrMemD || 340 E->getOpcode() == BinaryOperator::PtrMemI) 341 VisitPointerToDataMemberBinaryOperator(E); 342 else 343 CGF.ErrorUnsupported(E, "aggregate binary expression"); 344} 345 346void AggExprEmitter::VisitPointerToDataMemberBinaryOperator( 347 const BinaryOperator *E) { 348 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E); 349 EmitFinalDestCopy(E, LV); 350} 351 352void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { 353 // For an assignment to work, the value on the right has 354 // to be compatible with the value on the left. 355 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(), 356 E->getRHS()->getType()) 357 && "Invalid assignment"); 358 LValue LHS = CGF.EmitLValue(E->getLHS()); 359 360 // We have to special case property setters, otherwise we must have 361 // a simple lvalue (no aggregates inside vectors, bitfields). 362 if (LHS.isPropertyRef()) { 363 llvm::Value *AggLoc = DestPtr; 364 if (!AggLoc) 365 AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType())); 366 CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest); 367 CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(), 368 RValue::getAggregate(AggLoc, VolatileDest)); 369 } else if (LHS.isKVCRef()) { 370 llvm::Value *AggLoc = DestPtr; 371 if (!AggLoc) 372 AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType())); 373 CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest); 374 CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(), 375 RValue::getAggregate(AggLoc, VolatileDest)); 376 } else { 377 bool RequiresGCollection = false; 378 if (CGF.getContext().getLangOptions().NeXTRuntime) { 379 QualType LHSTy = E->getLHS()->getType(); 380 if (const RecordType *FDTTy = LHSTy.getTypePtr()->getAs<RecordType>()) 381 RequiresGCollection = FDTTy->getDecl()->hasObjectMember(); 382 } 383 // Codegen the RHS so that it stores directly into the LHS. 384 CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified(), 385 false, false, RequiresGCollection); 386 EmitFinalDestCopy(E, LHS, true); 387 } 388} 389 390void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) { 391 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 392 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 393 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 394 395 llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond()); 396 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock); 397 398 CGF.StartConditionalBranch(); 399 CGF.EmitBlock(LHSBlock); 400 401 // Handle the GNU extension for missing LHS. 402 assert(E->getLHS() && "Must have LHS for aggregate value"); 403 404 Visit(E->getLHS()); 405 CGF.FinishConditionalBranch(); 406 CGF.EmitBranch(ContBlock); 407 408 CGF.StartConditionalBranch(); 409 CGF.EmitBlock(RHSBlock); 410 411 Visit(E->getRHS()); 412 CGF.FinishConditionalBranch(); 413 CGF.EmitBranch(ContBlock); 414 415 CGF.EmitBlock(ContBlock); 416} 417 418void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) { 419 Visit(CE->getChosenSubExpr(CGF.getContext())); 420} 421 422void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 423 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 424 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 425 426 if (!ArgPtr) { 427 CGF.ErrorUnsupported(VE, "aggregate va_arg expression"); 428 return; 429 } 430 431 EmitFinalDestCopy(VE, LValue::MakeAddr(ArgPtr, Qualifiers())); 432} 433 434void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 435 llvm::Value *Val = DestPtr; 436 437 if (!Val) { 438 // Create a temporary variable. 439 Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp"); 440 441 // FIXME: volatile 442 CGF.EmitAggExpr(E->getSubExpr(), Val, false); 443 } else 444 Visit(E->getSubExpr()); 445 446 // Don't make this a live temporary if we're emitting an initializer expr. 447 if (!IsInitializer) 448 CGF.PushCXXTemporary(E->getTemporary(), Val); 449} 450 451void 452AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) { 453 llvm::Value *Val = DestPtr; 454 455 if (!Val) { 456 // Create a temporary variable. 457 Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp"); 458 } 459 460 CGF.EmitCXXConstructExpr(Val, E); 461} 462 463void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) { 464 CGF.EmitCXXExprWithTemporaries(E, DestPtr, VolatileDest, IsInitializer); 465} 466 467void AggExprEmitter::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) { 468 LValue lvalue = LValue::MakeAddr(DestPtr, Qualifiers()); 469 EmitNullInitializationToLValue(lvalue, E->getType()); 470} 471 472void AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) { 473 // FIXME: Ignore result? 474 // FIXME: Are initializers affected by volatile? 475 if (isa<ImplicitValueInitExpr>(E)) { 476 EmitNullInitializationToLValue(LV, E->getType()); 477 } else if (E->getType()->isComplexType()) { 478 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false); 479 } else if (CGF.hasAggregateLLVMType(E->getType())) { 480 CGF.EmitAnyExpr(E, LV.getAddress(), false); 481 } else { 482 CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, E->getType()); 483 } 484} 485 486void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) { 487 if (!CGF.hasAggregateLLVMType(T)) { 488 // For non-aggregates, we can store zero 489 llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T)); 490 CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T); 491 } else { 492 // Otherwise, just memset the whole thing to zero. This is legal 493 // because in LLVM, all default initializers are guaranteed to have a 494 // bit pattern of all zeros. 495 // FIXME: That isn't true for member pointers! 496 // There's a potential optimization opportunity in combining 497 // memsets; that would be easy for arrays, but relatively 498 // difficult for structures with the current code. 499 CGF.EmitMemSetToZero(LV.getAddress(), T); 500 } 501} 502 503void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { 504#if 0 505 // FIXME: Assess perf here? Figure out what cases are worth optimizing here 506 // (Length of globals? Chunks of zeroed-out space?). 507 // 508 // If we can, prefer a copy from a global; this is a lot less code for long 509 // globals, and it's easier for the current optimizers to analyze. 510 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) { 511 llvm::GlobalVariable* GV = 512 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true, 513 llvm::GlobalValue::InternalLinkage, C, ""); 514 EmitFinalDestCopy(E, LValue::MakeAddr(GV, Qualifiers())); 515 return; 516 } 517#endif 518 if (E->hadArrayRangeDesignator()) { 519 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 520 } 521 522 // Handle initialization of an array. 523 if (E->getType()->isArrayType()) { 524 const llvm::PointerType *APType = 525 cast<llvm::PointerType>(DestPtr->getType()); 526 const llvm::ArrayType *AType = 527 cast<llvm::ArrayType>(APType->getElementType()); 528 529 uint64_t NumInitElements = E->getNumInits(); 530 531 if (E->getNumInits() > 0) { 532 QualType T1 = E->getType(); 533 QualType T2 = E->getInit(0)->getType(); 534 if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) { 535 EmitAggLoadOfLValue(E->getInit(0)); 536 return; 537 } 538 } 539 540 uint64_t NumArrayElements = AType->getNumElements(); 541 QualType ElementType = CGF.getContext().getCanonicalType(E->getType()); 542 ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType(); 543 544 // FIXME: were we intentionally ignoring address spaces and GC attributes? 545 Qualifiers Quals = CGF.MakeQualifiers(ElementType); 546 547 for (uint64_t i = 0; i != NumArrayElements; ++i) { 548 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 549 if (i < NumInitElements) 550 EmitInitializationToLValue(E->getInit(i), 551 LValue::MakeAddr(NextVal, Quals)); 552 else 553 EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, Quals), 554 ElementType); 555 } 556 return; 557 } 558 559 assert(E->getType()->isRecordType() && "Only support structs/unions here!"); 560 561 // Do struct initialization; this code just sets each individual member 562 // to the approprate value. This makes bitfield support automatic; 563 // the disadvantage is that the generated code is more difficult for 564 // the optimizer, especially with bitfields. 565 unsigned NumInitElements = E->getNumInits(); 566 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl(); 567 unsigned CurInitVal = 0; 568 569 if (E->getType()->isUnionType()) { 570 // Only initialize one field of a union. The field itself is 571 // specified by the initializer list. 572 if (!E->getInitializedFieldInUnion()) { 573 // Empty union; we have nothing to do. 574 575#ifndef NDEBUG 576 // Make sure that it's really an empty and not a failure of 577 // semantic analysis. 578 for (RecordDecl::field_iterator Field = SD->field_begin(), 579 FieldEnd = SD->field_end(); 580 Field != FieldEnd; ++Field) 581 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed"); 582#endif 583 return; 584 } 585 586 // FIXME: volatility 587 FieldDecl *Field = E->getInitializedFieldInUnion(); 588 LValue FieldLoc = CGF.EmitLValueForField(DestPtr, Field, true, 0); 589 590 if (NumInitElements) { 591 // Store the initializer into the field 592 EmitInitializationToLValue(E->getInit(0), FieldLoc); 593 } else { 594 // Default-initialize to null 595 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 596 } 597 598 return; 599 } 600 601 // Here we iterate over the fields; this makes it simpler to both 602 // default-initialize fields and skip over unnamed fields. 603 for (RecordDecl::field_iterator Field = SD->field_begin(), 604 FieldEnd = SD->field_end(); 605 Field != FieldEnd; ++Field) { 606 // We're done once we hit the flexible array member 607 if (Field->getType()->isIncompleteArrayType()) 608 break; 609 610 if (Field->isUnnamedBitfield()) 611 continue; 612 613 // FIXME: volatility 614 LValue FieldLoc = CGF.EmitLValueForField(DestPtr, *Field, false, 0); 615 // We never generate write-barries for initialized fields. 616 LValue::SetObjCNonGC(FieldLoc, true); 617 if (CurInitVal < NumInitElements) { 618 // Store the initializer into the field 619 EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc); 620 } else { 621 // We're out of initalizers; default-initialize to null 622 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 623 } 624 } 625} 626 627//===----------------------------------------------------------------------===// 628// Entry Points into this File 629//===----------------------------------------------------------------------===// 630 631/// EmitAggExpr - Emit the computation of the specified expression of aggregate 632/// type. The result is computed into DestPtr. Note that if DestPtr is null, 633/// the value of the aggregate expression is not needed. If VolatileDest is 634/// true, DestPtr cannot be 0. 635void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr, 636 bool VolatileDest, bool IgnoreResult, 637 bool IsInitializer, 638 bool RequiresGCollection) { 639 assert(E && hasAggregateLLVMType(E->getType()) && 640 "Invalid aggregate expression to emit"); 641 assert ((DestPtr != 0 || VolatileDest == false) 642 && "volatile aggregate can't be 0"); 643 644 AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult, IsInitializer, 645 RequiresGCollection) 646 .Visit(const_cast<Expr*>(E)); 647} 648 649void CodeGenFunction::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) { 650 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 651 652 EmitMemSetToZero(DestPtr, Ty); 653} 654 655void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr, 656 llvm::Value *SrcPtr, QualType Ty, 657 bool isVolatile) { 658 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 659 660 // Aggregate assignment turns into llvm.memcpy. This is almost valid per 661 // C99 6.5.16.1p3, which states "If the value being stored in an object is 662 // read from another object that overlaps in anyway the storage of the first 663 // object, then the overlap shall be exact and the two objects shall have 664 // qualified or unqualified versions of a compatible type." 665 // 666 // memcpy is not defined if the source and destination pointers are exactly 667 // equal, but other compilers do this optimization, and almost every memcpy 668 // implementation handles this case safely. If there is a libc that does not 669 // safely handle this, we can add a target hook. 670 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext); 671 if (DestPtr->getType() != BP) 672 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 673 if (SrcPtr->getType() != BP) 674 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp"); 675 676 // Get size and alignment info for this aggregate. 677 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 678 679 // FIXME: Handle variable sized types. 680 const llvm::Type *IntPtr = 681 llvm::IntegerType::get(VMContext, LLVMPointerWidth); 682 683 // FIXME: If we have a volatile struct, the optimizer can remove what might 684 // appear to be `extra' memory ops: 685 // 686 // volatile struct { int i; } a, b; 687 // 688 // int main() { 689 // a = b; 690 // a = b; 691 // } 692 // 693 // we need to use a differnt call here. We use isVolatile to indicate when 694 // either the source or the destination is volatile. 695 Builder.CreateCall4(CGM.getMemCpyFn(), 696 DestPtr, SrcPtr, 697 // TypeInfo.first describes size in bits. 698 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 699 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 700 TypeInfo.second/8)); 701} 702