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/Support/Compiler.h" 24 #include "llvm/Intrinsics.h" 25 using namespace clang; 26 using namespace CodeGen; 27 28 //===----------------------------------------------------------------------===// 29 // Aggregate Expression Emitter 30 //===----------------------------------------------------------------------===// 31 32 namespace { 33 class VISIBILITY_HIDDEN AggExprEmitter : public StmtVisitor<AggExprEmitter> { 34 CodeGenFunction &CGF; 35 CGBuilderTy &Builder; 36 llvm::Value *DestPtr; 37 bool VolatileDest; 38 bool IgnoreResult; 39 bool IsInitializer; 40 bool RequiresGCollection; 41 public: 42 AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool v, 43 bool ignore, bool isinit, bool requiresGCollection) 44 : CGF(cgf), Builder(CGF.Builder), 45 DestPtr(destPtr), VolatileDest(v), IgnoreResult(ignore), 46 IsInitializer(isinit), RequiresGCollection(requiresGCollection) { 47 } 48 49 //===--------------------------------------------------------------------===// 50 // Utilities 51 //===--------------------------------------------------------------------===// 52 53 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 54 /// represents a value lvalue, this method emits the address of the lvalue, 55 /// then loads the result into DestPtr. 56 void EmitAggLoadOfLValue(const Expr *E); 57 58 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 59 void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false); 60 void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false); 61 62 //===--------------------------------------------------------------------===// 63 // Visitor Methods 64 //===--------------------------------------------------------------------===// 65 66 void VisitStmt(Stmt *S) { 67 CGF.ErrorUnsupported(S, "aggregate expression"); 68 } 69 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); } 70 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); } 71 72 // l-values. 73 void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); } 74 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); } 75 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); } 76 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); } 77 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 78 EmitAggLoadOfLValue(E); 79 } 80 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 81 EmitAggLoadOfLValue(E); 82 } 83 void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { 84 EmitAggLoadOfLValue(E); 85 } 86 void VisitPredefinedExpr(const PredefinedExpr *E) { 87 EmitAggLoadOfLValue(E); 88 } 89 90 // Operators. 91 void VisitCastExpr(CastExpr *E); 92 void VisitCallExpr(const CallExpr *E); 93 void VisitStmtExpr(const StmtExpr *E); 94 void VisitBinaryOperator(const BinaryOperator *BO); 95 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO); 96 void VisitBinAssign(const BinaryOperator *E); 97 void VisitBinComma(const BinaryOperator *E); 98 void VisitUnaryAddrOf(const UnaryOperator *E); 99 100 void VisitObjCMessageExpr(ObjCMessageExpr *E); 101 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 102 EmitAggLoadOfLValue(E); 103 } 104 void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E); 105 void VisitObjCImplicitSetterGetterRefExpr(ObjCImplicitSetterGetterRefExpr *E); 106 107 void VisitConditionalOperator(const ConditionalOperator *CO); 108 void VisitChooseExpr(const ChooseExpr *CE); 109 void VisitInitListExpr(InitListExpr *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 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 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. 134 void 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. 140 void 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. 167 void 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 179 void 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_BaseToDerivedMemberPointer: { 226 QualType SrcType = E->getSubExpr()->getType(); 227 228 llvm::Value *Src = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(SrcType), 229 "tmp"); 230 CGF.EmitAggExpr(E->getSubExpr(), Src, SrcType.isVolatileQualified()); 231 232 llvm::Value *SrcPtr = Builder.CreateStructGEP(Src, 0, "src.ptr"); 233 SrcPtr = Builder.CreateLoad(SrcPtr); 234 235 llvm::Value *SrcAdj = Builder.CreateStructGEP(Src, 1, "src.adj"); 236 SrcAdj = Builder.CreateLoad(SrcAdj); 237 238 llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr"); 239 Builder.CreateStore(SrcPtr, DstPtr, VolatileDest); 240 241 llvm::Value *DstAdj = Builder.CreateStructGEP(DestPtr, 1, "dst.adj"); 242 243 // Now See if we need to update the adjustment. 244 const CXXRecordDecl *SrcDecl = 245 cast<CXXRecordDecl>(SrcType->getAs<MemberPointerType>()-> 246 getClass()->getAs<RecordType>()->getDecl()); 247 const CXXRecordDecl *DstDecl = 248 cast<CXXRecordDecl>(E->getType()->getAs<MemberPointerType>()-> 249 getClass()->getAs<RecordType>()->getDecl()); 250 251 llvm::Constant *Adj = CGF.CGM.GetCXXBaseClassOffset(DstDecl, SrcDecl); 252 if (Adj) 253 SrcAdj = Builder.CreateAdd(SrcAdj, Adj, "adj"); 254 255 Builder.CreateStore(SrcAdj, DstAdj, VolatileDest); 256 break; 257 } 258 } 259 } 260 261 void AggExprEmitter::VisitCallExpr(const CallExpr *E) { 262 if (E->getCallReturnType()->isReferenceType()) { 263 EmitAggLoadOfLValue(E); 264 return; 265 } 266 267 RValue RV = CGF.EmitCallExpr(E); 268 EmitFinalDestCopy(E, RV); 269 } 270 271 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) { 272 RValue RV = CGF.EmitObjCMessageExpr(E); 273 EmitFinalDestCopy(E, RV); 274 } 275 276 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 277 RValue RV = CGF.EmitObjCPropertyGet(E); 278 EmitFinalDestCopy(E, RV); 279 } 280 281 void AggExprEmitter::VisitObjCImplicitSetterGetterRefExpr( 282 ObjCImplicitSetterGetterRefExpr *E) { 283 RValue RV = CGF.EmitObjCPropertyGet(E); 284 EmitFinalDestCopy(E, RV); 285 } 286 287 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) { 288 CGF.EmitAnyExpr(E->getLHS(), 0, false, true); 289 CGF.EmitAggExpr(E->getRHS(), DestPtr, VolatileDest, 290 /*IgnoreResult=*/false, IsInitializer); 291 } 292 293 void AggExprEmitter::VisitUnaryAddrOf(const UnaryOperator *E) { 294 // We have a member function pointer. 295 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>(); 296 (void) MPT; 297 assert(MPT->getPointeeType()->isFunctionProtoType() && 298 "Unexpected member pointer type!"); 299 300 const DeclRefExpr *DRE = cast<DeclRefExpr>(E->getSubExpr()); 301 const CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 302 303 const llvm::Type *PtrDiffTy = 304 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 305 306 llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr"); 307 llvm::Value *FuncPtr; 308 309 if (MD->isVirtual()) { 310 int64_t Index = 311 CGF.CGM.getVtableInfo().getMethodVtableIndex(MD); 312 313 FuncPtr = llvm::ConstantInt::get(PtrDiffTy, Index + 1); 314 } else { 315 FuncPtr = llvm::ConstantExpr::getPtrToInt(CGF.CGM.GetAddrOfFunction(MD), 316 PtrDiffTy); 317 } 318 Builder.CreateStore(FuncPtr, DstPtr, VolatileDest); 319 320 llvm::Value *AdjPtr = Builder.CreateStructGEP(DestPtr, 1, "dst.adj"); 321 322 // The adjustment will always be 0. 323 Builder.CreateStore(llvm::ConstantInt::get(PtrDiffTy, 0), AdjPtr, 324 VolatileDest); 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.CreateTempAlloca(CGF.ConvertType(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.CreateTempAlloca(CGF.ConvertType(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().NeXTRuntime) { 372 QualType LHSTy = E->getLHS()->getType(); 373 if (const RecordType *FDTTy = LHSTy.getTypePtr()->getAs<RecordType>()) 374 RequiresGCollection = FDTTy->getDecl()->hasObjectMember(); 375 } 376 // Codegen the RHS so that it stores directly into the LHS. 377 CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified(), 378 false, false, RequiresGCollection); 379 EmitFinalDestCopy(E, LHS, true); 380 } 381 } 382 383 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) { 384 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 385 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 386 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 387 388 llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond()); 389 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock); 390 391 CGF.PushConditionalTempDestruction(); 392 CGF.EmitBlock(LHSBlock); 393 394 // Handle the GNU extension for missing LHS. 395 assert(E->getLHS() && "Must have LHS for aggregate value"); 396 397 Visit(E->getLHS()); 398 CGF.PopConditionalTempDestruction(); 399 CGF.EmitBranch(ContBlock); 400 401 CGF.PushConditionalTempDestruction(); 402 CGF.EmitBlock(RHSBlock); 403 404 Visit(E->getRHS()); 405 CGF.PopConditionalTempDestruction(); 406 CGF.EmitBranch(ContBlock); 407 408 CGF.EmitBlock(ContBlock); 409 } 410 411 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) { 412 Visit(CE->getChosenSubExpr(CGF.getContext())); 413 } 414 415 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 416 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 417 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 418 419 if (!ArgPtr) { 420 CGF.ErrorUnsupported(VE, "aggregate va_arg expression"); 421 return; 422 } 423 424 EmitFinalDestCopy(VE, LValue::MakeAddr(ArgPtr, Qualifiers())); 425 } 426 427 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 428 llvm::Value *Val = DestPtr; 429 430 if (!Val) { 431 // Create a temporary variable. 432 Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp"); 433 434 // FIXME: volatile 435 CGF.EmitAggExpr(E->getSubExpr(), Val, false); 436 } else 437 Visit(E->getSubExpr()); 438 439 // Don't make this a live temporary if we're emitting an initializer expr. 440 if (!IsInitializer) 441 CGF.PushCXXTemporary(E->getTemporary(), Val); 442 } 443 444 void 445 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) { 446 llvm::Value *Val = DestPtr; 447 448 if (!Val) { 449 // Create a temporary variable. 450 Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp"); 451 } 452 453 CGF.EmitCXXConstructExpr(Val, E); 454 } 455 456 void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) { 457 CGF.EmitCXXExprWithTemporaries(E, DestPtr, VolatileDest, IsInitializer); 458 } 459 460 void AggExprEmitter::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) { 461 LValue lvalue = LValue::MakeAddr(DestPtr, Qualifiers()); 462 EmitNullInitializationToLValue(lvalue, E->getType()); 463 } 464 465 void AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) { 466 // FIXME: Ignore result? 467 // FIXME: Are initializers affected by volatile? 468 if (isa<ImplicitValueInitExpr>(E)) { 469 EmitNullInitializationToLValue(LV, E->getType()); 470 } else if (E->getType()->isComplexType()) { 471 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false); 472 } else if (CGF.hasAggregateLLVMType(E->getType())) { 473 CGF.EmitAnyExpr(E, LV.getAddress(), false); 474 } else { 475 CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, E->getType()); 476 } 477 } 478 479 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) { 480 if (!CGF.hasAggregateLLVMType(T)) { 481 // For non-aggregates, we can store zero 482 llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T)); 483 CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T); 484 } else { 485 // Otherwise, just memset the whole thing to zero. This is legal 486 // because in LLVM, all default initializers are guaranteed to have a 487 // bit pattern of all zeros. 488 // FIXME: That isn't true for member pointers! 489 // There's a potential optimization opportunity in combining 490 // memsets; that would be easy for arrays, but relatively 491 // difficult for structures with the current code. 492 CGF.EmitMemSetToZero(LV.getAddress(), T); 493 } 494 } 495 496 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { 497 #if 0 498 // FIXME: Disabled while we figure out what to do about 499 // test/CodeGen/bitfield.c 500 // 501 // If we can, prefer a copy from a global; this is a lot less code for long 502 // globals, and it's easier for the current optimizers to analyze. 503 // FIXME: Should we really be doing this? Should we try to avoid cases where 504 // we emit a global with a lot of zeros? Should we try to avoid short 505 // globals? 506 if (E->isConstantInitializer(CGF.getContext(), 0)) { 507 llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, &CGF); 508 llvm::GlobalVariable* GV = 509 new llvm::GlobalVariable(C->getType(), true, 510 llvm::GlobalValue::InternalLinkage, 511 C, "", &CGF.CGM.getModule(), 0); 512 EmitFinalDestCopy(E, LValue::MakeAddr(GV, 0)); 513 return; 514 } 515 #endif 516 if (E->hadArrayRangeDesignator()) { 517 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 518 } 519 520 // Handle initialization of an array. 521 if (E->getType()->isArrayType()) { 522 const llvm::PointerType *APType = 523 cast<llvm::PointerType>(DestPtr->getType()); 524 const llvm::ArrayType *AType = 525 cast<llvm::ArrayType>(APType->getElementType()); 526 527 uint64_t NumInitElements = E->getNumInits(); 528 529 if (E->getNumInits() > 0) { 530 QualType T1 = E->getType(); 531 QualType T2 = E->getInit(0)->getType(); 532 if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) { 533 EmitAggLoadOfLValue(E->getInit(0)); 534 return; 535 } 536 } 537 538 uint64_t NumArrayElements = AType->getNumElements(); 539 QualType ElementType = CGF.getContext().getCanonicalType(E->getType()); 540 ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType(); 541 542 // FIXME: were we intentionally ignoring address spaces and GC attributes? 543 Qualifiers Quals = CGF.MakeQualifiers(ElementType); 544 545 for (uint64_t i = 0; i != NumArrayElements; ++i) { 546 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 547 if (i < NumInitElements) 548 EmitInitializationToLValue(E->getInit(i), 549 LValue::MakeAddr(NextVal, Quals)); 550 else 551 EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, Quals), 552 ElementType); 553 } 554 return; 555 } 556 557 assert(E->getType()->isRecordType() && "Only support structs/unions here!"); 558 559 // Do struct initialization; this code just sets each individual member 560 // to the approprate value. This makes bitfield support automatic; 561 // the disadvantage is that the generated code is more difficult for 562 // the optimizer, especially with bitfields. 563 unsigned NumInitElements = E->getNumInits(); 564 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl(); 565 unsigned CurInitVal = 0; 566 567 if (E->getType()->isUnionType()) { 568 // Only initialize one field of a union. The field itself is 569 // specified by the initializer list. 570 if (!E->getInitializedFieldInUnion()) { 571 // Empty union; we have nothing to do. 572 573 #ifndef NDEBUG 574 // Make sure that it's really an empty and not a failure of 575 // semantic analysis. 576 for (RecordDecl::field_iterator Field = SD->field_begin(), 577 FieldEnd = SD->field_end(); 578 Field != FieldEnd; ++Field) 579 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed"); 580 #endif 581 return; 582 } 583 584 // FIXME: volatility 585 FieldDecl *Field = E->getInitializedFieldInUnion(); 586 LValue FieldLoc = CGF.EmitLValueForField(DestPtr, Field, true, 0); 587 588 if (NumInitElements) { 589 // Store the initializer into the field 590 EmitInitializationToLValue(E->getInit(0), FieldLoc); 591 } else { 592 // Default-initialize to null 593 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 594 } 595 596 return; 597 } 598 599 // Here we iterate over the fields; this makes it simpler to both 600 // default-initialize fields and skip over unnamed fields. 601 for (RecordDecl::field_iterator Field = SD->field_begin(), 602 FieldEnd = SD->field_end(); 603 Field != FieldEnd; ++Field) { 604 // We're done once we hit the flexible array member 605 if (Field->getType()->isIncompleteArrayType()) 606 break; 607 608 if (Field->isUnnamedBitfield()) 609 continue; 610 611 // FIXME: volatility 612 LValue FieldLoc = CGF.EmitLValueForField(DestPtr, *Field, false, 0); 613 // We never generate write-barries for initialized fields. 614 LValue::SetObjCNonGC(FieldLoc, true); 615 if (CurInitVal < NumInitElements) { 616 // Store the initializer into the field 617 EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc); 618 } else { 619 // We're out of initalizers; default-initialize to null 620 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 621 } 622 } 623 } 624 625 //===----------------------------------------------------------------------===// 626 // Entry Points into this File 627 //===----------------------------------------------------------------------===// 628 629 /// EmitAggExpr - Emit the computation of the specified expression of aggregate 630 /// type. The result is computed into DestPtr. Note that if DestPtr is null, 631 /// the value of the aggregate expression is not needed. If VolatileDest is 632 /// true, DestPtr cannot be 0. 633 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr, 634 bool VolatileDest, bool IgnoreResult, 635 bool IsInitializer, 636 bool RequiresGCollection) { 637 assert(E && hasAggregateLLVMType(E->getType()) && 638 "Invalid aggregate expression to emit"); 639 assert ((DestPtr != 0 || VolatileDest == false) 640 && "volatile aggregate can't be 0"); 641 642 AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult, IsInitializer, 643 RequiresGCollection) 644 .Visit(const_cast<Expr*>(E)); 645 } 646 647 void CodeGenFunction::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) { 648 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 649 650 EmitMemSetToZero(DestPtr, Ty); 651 } 652 653 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr, 654 llvm::Value *SrcPtr, QualType Ty, 655 bool isVolatile) { 656 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 657 658 // Aggregate assignment turns into llvm.memcpy. This is almost valid per 659 // C99 6.5.16.1p3, which states "If the value being stored in an object is 660 // read from another object that overlaps in anyway the storage of the first 661 // object, then the overlap shall be exact and the two objects shall have 662 // qualified or unqualified versions of a compatible type." 663 // 664 // memcpy is not defined if the source and destination pointers are exactly 665 // equal, but other compilers do this optimization, and almost every memcpy 666 // implementation handles this case safely. If there is a libc that does not 667 // safely handle this, we can add a target hook. 668 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext); 669 if (DestPtr->getType() != BP) 670 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 671 if (SrcPtr->getType() != BP) 672 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp"); 673 674 // Get size and alignment info for this aggregate. 675 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 676 677 // FIXME: Handle variable sized types. 678 const llvm::Type *IntPtr = 679 llvm::IntegerType::get(VMContext, LLVMPointerWidth); 680 681 // FIXME: If we have a volatile struct, the optimizer can remove what might 682 // appear to be `extra' memory ops: 683 // 684 // volatile struct { int i; } a, b; 685 // 686 // int main() { 687 // a = b; 688 // a = b; 689 // } 690 // 691 // we need to use a differnt call here. We use isVolatile to indicate when 692 // either the source or the destination is volatile. 693 Builder.CreateCall4(CGM.getMemCpyFn(), 694 DestPtr, SrcPtr, 695 // TypeInfo.first describes size in bits. 696 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 697 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 698 TypeInfo.second/8)); 699 } 700