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