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