1 //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This contains code to emit Aggregate Expr nodes as LLVM code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CodeGenModule.h" 16 #include "CGObjCRuntime.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/DeclCXX.h" 19 #include "clang/AST/StmtVisitor.h" 20 #include "llvm/Constants.h" 21 #include "llvm/Function.h" 22 #include "llvm/GlobalVariable.h" 23 #include "llvm/Intrinsics.h" 24 using namespace clang; 25 using namespace CodeGen; 26 27 //===----------------------------------------------------------------------===// 28 // Aggregate Expression Emitter 29 //===----------------------------------------------------------------------===// 30 31 namespace { 32 class AggExprEmitter : public StmtVisitor<AggExprEmitter> { 33 CodeGenFunction &CGF; 34 CGBuilderTy &Builder; 35 llvm::Value *DestPtr; 36 bool VolatileDest; 37 bool IgnoreResult; 38 bool IsInitializer; 39 bool RequiresGCollection; 40 public: 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 VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 76 EmitAggLoadOfLValue(E); 77 } 78 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 79 EmitAggLoadOfLValue(E); 80 } 81 void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { 82 EmitAggLoadOfLValue(E); 83 } 84 void VisitPredefinedExpr(const PredefinedExpr *E) { 85 EmitAggLoadOfLValue(E); 86 } 87 88 // Operators. 89 void VisitCastExpr(CastExpr *E); 90 void VisitCallExpr(const CallExpr *E); 91 void VisitStmtExpr(const StmtExpr *E); 92 void VisitBinaryOperator(const BinaryOperator *BO); 93 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO); 94 void VisitBinAssign(const BinaryOperator *E); 95 void VisitBinComma(const BinaryOperator *E); 96 void VisitUnaryAddrOf(const UnaryOperator *E); 97 98 void VisitObjCMessageExpr(ObjCMessageExpr *E); 99 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 100 EmitAggLoadOfLValue(E); 101 } 102 void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E); 103 void VisitObjCImplicitSetterGetterRefExpr(ObjCImplicitSetterGetterRefExpr *E); 104 105 void VisitConditionalOperator(const ConditionalOperator *CO); 106 void VisitChooseExpr(const ChooseExpr *CE); 107 void VisitInitListExpr(InitListExpr *E); 108 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *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. 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_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 268 void AggExprEmitter::VisitCallExpr(const CallExpr *E) { 269 if (E->getCallReturnType()->isReferenceType()) { 270 EmitAggLoadOfLValue(E); 271 return; 272 } 273 274 // If the struct doesn't require GC, we can just pass the destination 275 // directly to EmitCall. 276 if (!RequiresGCollection) { 277 CGF.EmitCallExpr(E, ReturnValueSlot(DestPtr, VolatileDest)); 278 return; 279 } 280 281 RValue RV = CGF.EmitCallExpr(E); 282 EmitFinalDestCopy(E, RV); 283 } 284 285 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) { 286 RValue RV = CGF.EmitObjCMessageExpr(E); 287 EmitFinalDestCopy(E, RV); 288 } 289 290 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 291 RValue RV = CGF.EmitObjCPropertyGet(E); 292 EmitFinalDestCopy(E, RV); 293 } 294 295 void AggExprEmitter::VisitObjCImplicitSetterGetterRefExpr( 296 ObjCImplicitSetterGetterRefExpr *E) { 297 RValue RV = CGF.EmitObjCPropertyGet(E); 298 EmitFinalDestCopy(E, RV); 299 } 300 301 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) { 302 CGF.EmitAnyExpr(E->getLHS(), 0, false, true); 303 CGF.EmitAggExpr(E->getRHS(), DestPtr, VolatileDest, 304 /*IgnoreResult=*/false, IsInitializer); 305 } 306 307 void AggExprEmitter::VisitUnaryAddrOf(const UnaryOperator *E) { 308 // We have a member function pointer. 309 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>(); 310 (void) MPT; 311 assert(MPT->getPointeeType()->isFunctionProtoType() && 312 "Unexpected member pointer type!"); 313 314 const DeclRefExpr *DRE = cast<DeclRefExpr>(E->getSubExpr()); 315 const CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 316 317 const llvm::Type *PtrDiffTy = 318 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 319 320 llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr"); 321 llvm::Value *FuncPtr; 322 323 if (MD->isVirtual()) { 324 int64_t Index = 325 CGF.CGM.getVtableInfo().getMethodVtableIndex(MD); 326 327 FuncPtr = llvm::ConstantInt::get(PtrDiffTy, Index + 1); 328 } else { 329 FuncPtr = llvm::ConstantExpr::getPtrToInt(CGF.CGM.GetAddrOfFunction(MD), 330 PtrDiffTy); 331 } 332 Builder.CreateStore(FuncPtr, DstPtr, VolatileDest); 333 334 llvm::Value *AdjPtr = Builder.CreateStructGEP(DestPtr, 1, "dst.adj"); 335 336 // The adjustment will always be 0. 337 Builder.CreateStore(llvm::ConstantInt::get(PtrDiffTy, 0), AdjPtr, 338 VolatileDest); 339 } 340 341 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) { 342 CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest); 343 } 344 345 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) { 346 if (E->getOpcode() == BinaryOperator::PtrMemD || 347 E->getOpcode() == BinaryOperator::PtrMemI) 348 VisitPointerToDataMemberBinaryOperator(E); 349 else 350 CGF.ErrorUnsupported(E, "aggregate binary expression"); 351 } 352 353 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator( 354 const BinaryOperator *E) { 355 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E); 356 EmitFinalDestCopy(E, LV); 357 } 358 359 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { 360 // For an assignment to work, the value on the right has 361 // to be compatible with the value on the left. 362 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(), 363 E->getRHS()->getType()) 364 && "Invalid assignment"); 365 LValue LHS = CGF.EmitLValue(E->getLHS()); 366 367 // We have to special case property setters, otherwise we must have 368 // a simple lvalue (no aggregates inside vectors, bitfields). 369 if (LHS.isPropertyRef()) { 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.getPropertyRefExpr(), 375 RValue::getAggregate(AggLoc, VolatileDest)); 376 } else if (LHS.isKVCRef()) { 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.getKVCRefExpr(), 382 RValue::getAggregate(AggLoc, VolatileDest)); 383 } else { 384 bool RequiresGCollection = false; 385 if (CGF.getContext().getLangOptions().NeXTRuntime) { 386 QualType LHSTy = E->getLHS()->getType(); 387 if (const RecordType *FDTTy = LHSTy.getTypePtr()->getAs<RecordType>()) 388 RequiresGCollection = FDTTy->getDecl()->hasObjectMember(); 389 } 390 // Codegen the RHS so that it stores directly into the LHS. 391 CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified(), 392 false, false, RequiresGCollection); 393 EmitFinalDestCopy(E, LHS, true); 394 } 395 } 396 397 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) { 398 if (!E->getLHS()) { 399 CGF.ErrorUnsupported(E, "conditional operator with missing LHS"); 400 return; 401 } 402 403 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 404 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 405 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 406 407 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock); 408 409 CGF.StartConditionalBranch(); 410 CGF.EmitBlock(LHSBlock); 411 412 // Handle the GNU extension for missing LHS. 413 assert(E->getLHS() && "Must have LHS for aggregate value"); 414 415 Visit(E->getLHS()); 416 CGF.FinishConditionalBranch(); 417 CGF.EmitBranch(ContBlock); 418 419 CGF.StartConditionalBranch(); 420 CGF.EmitBlock(RHSBlock); 421 422 Visit(E->getRHS()); 423 CGF.FinishConditionalBranch(); 424 CGF.EmitBranch(ContBlock); 425 426 CGF.EmitBlock(ContBlock); 427 } 428 429 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) { 430 Visit(CE->getChosenSubExpr(CGF.getContext())); 431 } 432 433 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 434 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 435 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 436 437 if (!ArgPtr) { 438 CGF.ErrorUnsupported(VE, "aggregate va_arg expression"); 439 return; 440 } 441 442 EmitFinalDestCopy(VE, LValue::MakeAddr(ArgPtr, Qualifiers())); 443 } 444 445 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *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 // FIXME: volatile 453 CGF.EmitAggExpr(E->getSubExpr(), Val, false); 454 } else 455 Visit(E->getSubExpr()); 456 457 // Don't make this a live temporary if we're emitting an initializer expr. 458 if (!IsInitializer) 459 CGF.PushCXXTemporary(E->getTemporary(), Val); 460 } 461 462 void 463 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) { 464 llvm::Value *Val = DestPtr; 465 466 if (!Val) { 467 // Create a temporary variable. 468 Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp"); 469 } 470 471 if (E->requiresZeroInitialization()) 472 EmitNullInitializationToLValue(LValue::MakeAddr(Val, 473 // FIXME: Qualifiers()? 474 E->getType().getQualifiers()), 475 E->getType()); 476 477 CGF.EmitCXXConstructExpr(Val, E); 478 } 479 480 void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) { 481 llvm::Value *Val = DestPtr; 482 483 if (!Val) { 484 // Create a temporary variable. 485 Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp"); 486 } 487 CGF.EmitCXXExprWithTemporaries(E, Val, VolatileDest, IsInitializer); 488 } 489 490 void AggExprEmitter::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) { 491 llvm::Value *Val = DestPtr; 492 493 if (!Val) { 494 // Create a temporary variable. 495 Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp"); 496 } 497 LValue LV = LValue::MakeAddr(Val, Qualifiers()); 498 EmitNullInitializationToLValue(LV, E->getType()); 499 } 500 501 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) { 502 llvm::Value *Val = DestPtr; 503 504 if (!Val) { 505 // Create a temporary variable. 506 Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp"); 507 } 508 LValue LV = LValue::MakeAddr(Val, Qualifiers()); 509 EmitNullInitializationToLValue(LV, E->getType()); 510 } 511 512 void AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) { 513 // FIXME: Ignore result? 514 // FIXME: Are initializers affected by volatile? 515 if (isa<ImplicitValueInitExpr>(E)) { 516 EmitNullInitializationToLValue(LV, E->getType()); 517 } else if (E->getType()->isComplexType()) { 518 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false); 519 } else if (CGF.hasAggregateLLVMType(E->getType())) { 520 CGF.EmitAnyExpr(E, LV.getAddress(), false); 521 } else { 522 CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, E->getType()); 523 } 524 } 525 526 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) { 527 if (!CGF.hasAggregateLLVMType(T)) { 528 // For non-aggregates, we can store zero 529 llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T)); 530 CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T); 531 } else { 532 // Otherwise, just memset the whole thing to zero. This is legal 533 // because in LLVM, all default initializers are guaranteed to have a 534 // bit pattern of all zeros. 535 // FIXME: That isn't true for member pointers! 536 // There's a potential optimization opportunity in combining 537 // memsets; that would be easy for arrays, but relatively 538 // difficult for structures with the current code. 539 CGF.EmitMemSetToZero(LV.getAddress(), T); 540 } 541 } 542 543 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { 544 #if 0 545 // FIXME: Assess perf here? Figure out what cases are worth optimizing here 546 // (Length of globals? Chunks of zeroed-out space?). 547 // 548 // If we can, prefer a copy from a global; this is a lot less code for long 549 // globals, and it's easier for the current optimizers to analyze. 550 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) { 551 llvm::GlobalVariable* GV = 552 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true, 553 llvm::GlobalValue::InternalLinkage, C, ""); 554 EmitFinalDestCopy(E, LValue::MakeAddr(GV, Qualifiers())); 555 return; 556 } 557 #endif 558 if (E->hadArrayRangeDesignator()) { 559 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 560 } 561 562 // Handle initialization of an array. 563 if (E->getType()->isArrayType()) { 564 const llvm::PointerType *APType = 565 cast<llvm::PointerType>(DestPtr->getType()); 566 const llvm::ArrayType *AType = 567 cast<llvm::ArrayType>(APType->getElementType()); 568 569 uint64_t NumInitElements = E->getNumInits(); 570 571 if (E->getNumInits() > 0) { 572 QualType T1 = E->getType(); 573 QualType T2 = E->getInit(0)->getType(); 574 if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) { 575 EmitAggLoadOfLValue(E->getInit(0)); 576 return; 577 } 578 } 579 580 uint64_t NumArrayElements = AType->getNumElements(); 581 QualType ElementType = CGF.getContext().getCanonicalType(E->getType()); 582 ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType(); 583 584 // FIXME: were we intentionally ignoring address spaces and GC attributes? 585 Qualifiers Quals = CGF.MakeQualifiers(ElementType); 586 587 for (uint64_t i = 0; i != NumArrayElements; ++i) { 588 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 589 if (i < NumInitElements) 590 EmitInitializationToLValue(E->getInit(i), 591 LValue::MakeAddr(NextVal, Quals)); 592 else 593 EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, Quals), 594 ElementType); 595 } 596 return; 597 } 598 599 assert(E->getType()->isRecordType() && "Only support structs/unions here!"); 600 601 // Do struct initialization; this code just sets each individual member 602 // to the approprate value. This makes bitfield support automatic; 603 // the disadvantage is that the generated code is more difficult for 604 // the optimizer, especially with bitfields. 605 unsigned NumInitElements = E->getNumInits(); 606 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl(); 607 unsigned CurInitVal = 0; 608 609 if (E->getType()->isUnionType()) { 610 // Only initialize one field of a union. The field itself is 611 // specified by the initializer list. 612 if (!E->getInitializedFieldInUnion()) { 613 // Empty union; we have nothing to do. 614 615 #ifndef NDEBUG 616 // Make sure that it's really an empty and not a failure of 617 // semantic analysis. 618 for (RecordDecl::field_iterator Field = SD->field_begin(), 619 FieldEnd = SD->field_end(); 620 Field != FieldEnd; ++Field) 621 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed"); 622 #endif 623 return; 624 } 625 626 // FIXME: volatility 627 FieldDecl *Field = E->getInitializedFieldInUnion(); 628 LValue FieldLoc = CGF.EmitLValueForField(DestPtr, Field, true, 0); 629 630 if (NumInitElements) { 631 // Store the initializer into the field 632 EmitInitializationToLValue(E->getInit(0), FieldLoc); 633 } else { 634 // Default-initialize to null 635 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 636 } 637 638 return; 639 } 640 641 // Here we iterate over the fields; this makes it simpler to both 642 // default-initialize fields and skip over unnamed fields. 643 for (RecordDecl::field_iterator Field = SD->field_begin(), 644 FieldEnd = SD->field_end(); 645 Field != FieldEnd; ++Field) { 646 // We're done once we hit the flexible array member 647 if (Field->getType()->isIncompleteArrayType()) 648 break; 649 650 if (Field->isUnnamedBitfield()) 651 continue; 652 653 // FIXME: volatility 654 LValue FieldLoc = CGF.EmitLValueForField(DestPtr, *Field, false, 0); 655 // We never generate write-barries for initialized fields. 656 LValue::SetObjCNonGC(FieldLoc, true); 657 if (CurInitVal < NumInitElements) { 658 // Store the initializer into the field 659 EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc); 660 } else { 661 // We're out of initalizers; default-initialize to null 662 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 663 } 664 } 665 } 666 667 //===----------------------------------------------------------------------===// 668 // Entry Points into this File 669 //===----------------------------------------------------------------------===// 670 671 /// EmitAggExpr - Emit the computation of the specified expression of aggregate 672 /// type. The result is computed into DestPtr. Note that if DestPtr is null, 673 /// the value of the aggregate expression is not needed. If VolatileDest is 674 /// true, DestPtr cannot be 0. 675 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr, 676 bool VolatileDest, bool IgnoreResult, 677 bool IsInitializer, 678 bool RequiresGCollection) { 679 assert(E && hasAggregateLLVMType(E->getType()) && 680 "Invalid aggregate expression to emit"); 681 assert ((DestPtr != 0 || VolatileDest == false) 682 && "volatile aggregate can't be 0"); 683 684 AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult, IsInitializer, 685 RequiresGCollection) 686 .Visit(const_cast<Expr*>(E)); 687 } 688 689 void CodeGenFunction::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) { 690 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 691 692 EmitMemSetToZero(DestPtr, Ty); 693 } 694 695 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr, 696 llvm::Value *SrcPtr, QualType Ty, 697 bool isVolatile) { 698 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 699 700 // Aggregate assignment turns into llvm.memcpy. This is almost valid per 701 // C99 6.5.16.1p3, which states "If the value being stored in an object is 702 // read from another object that overlaps in anyway the storage of the first 703 // object, then the overlap shall be exact and the two objects shall have 704 // qualified or unqualified versions of a compatible type." 705 // 706 // memcpy is not defined if the source and destination pointers are exactly 707 // equal, but other compilers do this optimization, and almost every memcpy 708 // implementation handles this case safely. If there is a libc that does not 709 // safely handle this, we can add a target hook. 710 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext); 711 if (DestPtr->getType() != BP) 712 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 713 if (SrcPtr->getType() != BP) 714 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp"); 715 716 // Get size and alignment info for this aggregate. 717 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 718 719 // FIXME: Handle variable sized types. 720 const llvm::Type *IntPtr = 721 llvm::IntegerType::get(VMContext, LLVMPointerWidth); 722 723 // FIXME: If we have a volatile struct, the optimizer can remove what might 724 // appear to be `extra' memory ops: 725 // 726 // volatile struct { int i; } a, b; 727 // 728 // int main() { 729 // a = b; 730 // a = b; 731 // } 732 // 733 // we need to use a differnt call here. We use isVolatile to indicate when 734 // either the source or the destination is volatile. 735 Builder.CreateCall4(CGM.getMemCpyFn(), 736 DestPtr, SrcPtr, 737 // TypeInfo.first describes size in bits. 738 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 739 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 740 TypeInfo.second/8)); 741 } 742