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