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 AggValueSlot Dest; 36 bool IgnoreResult; 37 38 ReturnValueSlot getReturnValueSlot() const { 39 // If the destination slot requires garbage collection, we can't 40 // use the real return value slot, because we have to use the GC 41 // API. 42 if (Dest.requiresGCollection()) return ReturnValueSlot(); 43 44 return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile()); 45 } 46 47 AggValueSlot EnsureSlot(QualType T) { 48 if (!Dest.isIgnored()) return Dest; 49 return CGF.CreateAggTemp(T, "agg.tmp.ensured"); 50 } 51 52 public: 53 AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, 54 bool ignore) 55 : CGF(cgf), Builder(CGF.Builder), Dest(Dest), 56 IgnoreResult(ignore) { 57 } 58 59 //===--------------------------------------------------------------------===// 60 // Utilities 61 //===--------------------------------------------------------------------===// 62 63 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 64 /// represents a value lvalue, this method emits the address of the lvalue, 65 /// then loads the result into DestPtr. 66 void EmitAggLoadOfLValue(const Expr *E); 67 68 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 69 void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false); 70 void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false); 71 72 void EmitGCMove(const Expr *E, RValue Src); 73 74 bool TypeRequiresGCollection(QualType T); 75 76 //===--------------------------------------------------------------------===// 77 // Visitor Methods 78 //===--------------------------------------------------------------------===// 79 80 void VisitStmt(Stmt *S) { 81 CGF.ErrorUnsupported(S, "aggregate expression"); 82 } 83 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); } 84 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); } 85 86 // l-values. 87 void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); } 88 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); } 89 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); } 90 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); } 91 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 92 EmitAggLoadOfLValue(E); 93 } 94 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 95 EmitAggLoadOfLValue(E); 96 } 97 void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { 98 EmitAggLoadOfLValue(E); 99 } 100 void VisitPredefinedExpr(const PredefinedExpr *E) { 101 EmitAggLoadOfLValue(E); 102 } 103 104 // Operators. 105 void VisitCastExpr(CastExpr *E); 106 void VisitCallExpr(const CallExpr *E); 107 void VisitStmtExpr(const StmtExpr *E); 108 void VisitBinaryOperator(const BinaryOperator *BO); 109 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO); 110 void VisitBinAssign(const BinaryOperator *E); 111 void VisitBinComma(const BinaryOperator *E); 112 113 void VisitObjCMessageExpr(ObjCMessageExpr *E); 114 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 115 EmitAggLoadOfLValue(E); 116 } 117 void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E); 118 119 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO); 120 void VisitChooseExpr(const ChooseExpr *CE); 121 void VisitInitListExpr(InitListExpr *E); 122 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E); 123 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 124 Visit(DAE->getExpr()); 125 } 126 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E); 127 void VisitCXXConstructExpr(const CXXConstructExpr *E); 128 void VisitExprWithCleanups(ExprWithCleanups *E); 129 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E); 130 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); } 131 132 void VisitOpaqueValueExpr(OpaqueValueExpr *E); 133 134 void VisitVAArgExpr(VAArgExpr *E); 135 136 void EmitInitializationToLValue(Expr *E, LValue Address, QualType T); 137 void EmitNullInitializationToLValue(LValue Address, QualType T); 138 // case Expr::ChooseExprClass: 139 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); } 140 }; 141 } // end anonymous namespace. 142 143 //===----------------------------------------------------------------------===// 144 // Utilities 145 //===----------------------------------------------------------------------===// 146 147 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 148 /// represents a value lvalue, this method emits the address of the lvalue, 149 /// then loads the result into DestPtr. 150 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) { 151 LValue LV = CGF.EmitLValue(E); 152 EmitFinalDestCopy(E, LV); 153 } 154 155 /// \brief True if the given aggregate type requires special GC API calls. 156 bool AggExprEmitter::TypeRequiresGCollection(QualType T) { 157 // Only record types have members that might require garbage collection. 158 const RecordType *RecordTy = T->getAs<RecordType>(); 159 if (!RecordTy) return false; 160 161 // Don't mess with non-trivial C++ types. 162 RecordDecl *Record = RecordTy->getDecl(); 163 if (isa<CXXRecordDecl>(Record) && 164 (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() || 165 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor())) 166 return false; 167 168 // Check whether the type has an object member. 169 return Record->hasObjectMember(); 170 } 171 172 /// \brief Perform the final move to DestPtr if RequiresGCollection is set. 173 /// 174 /// The idea is that you do something like this: 175 /// RValue Result = EmitSomething(..., getReturnValueSlot()); 176 /// EmitGCMove(E, Result); 177 /// If GC doesn't interfere, this will cause the result to be emitted 178 /// directly into the return value slot. If GC does interfere, a final 179 /// move will be performed. 180 void AggExprEmitter::EmitGCMove(const Expr *E, RValue Src) { 181 if (Dest.requiresGCollection()) { 182 std::pair<uint64_t, unsigned> TypeInfo = 183 CGF.getContext().getTypeInfo(E->getType()); 184 unsigned long size = TypeInfo.first/8; 185 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType()); 186 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size); 187 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, Dest.getAddr(), 188 Src.getAggregateAddr(), 189 SizeVal); 190 } 191 } 192 193 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 194 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) { 195 assert(Src.isAggregate() && "value must be aggregate value!"); 196 197 // If Dest is ignored, then we're evaluating an aggregate expression 198 // in a context (like an expression statement) that doesn't care 199 // about the result. C says that an lvalue-to-rvalue conversion is 200 // performed in these cases; C++ says that it is not. In either 201 // case, we don't actually need to do anything unless the value is 202 // volatile. 203 if (Dest.isIgnored()) { 204 if (!Src.isVolatileQualified() || 205 CGF.CGM.getLangOptions().CPlusPlus || 206 (IgnoreResult && Ignore)) 207 return; 208 209 // If the source is volatile, we must read from it; to do that, we need 210 // some place to put it. 211 Dest = CGF.CreateAggTemp(E->getType(), "agg.tmp"); 212 } 213 214 if (Dest.requiresGCollection()) { 215 std::pair<uint64_t, unsigned> TypeInfo = 216 CGF.getContext().getTypeInfo(E->getType()); 217 unsigned long size = TypeInfo.first/8; 218 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType()); 219 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size); 220 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, 221 Dest.getAddr(), 222 Src.getAggregateAddr(), 223 SizeVal); 224 return; 225 } 226 // If the result of the assignment is used, copy the LHS there also. 227 // FIXME: Pass VolatileDest as well. I think we also need to merge volatile 228 // from the source as well, as we can't eliminate it if either operand 229 // is volatile, unless copy has volatile for both source and destination.. 230 CGF.EmitAggregateCopy(Dest.getAddr(), Src.getAggregateAddr(), E->getType(), 231 Dest.isVolatile()|Src.isVolatileQualified()); 232 } 233 234 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 235 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) { 236 assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc"); 237 238 EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(), 239 Src.isVolatileQualified()), 240 Ignore); 241 } 242 243 //===----------------------------------------------------------------------===// 244 // Visitor Methods 245 //===----------------------------------------------------------------------===// 246 247 void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) { 248 EmitFinalDestCopy(e, CGF.getOpaqueLValueMapping(e)); 249 } 250 251 void AggExprEmitter::VisitCastExpr(CastExpr *E) { 252 if (Dest.isIgnored() && E->getCastKind() != CK_Dynamic) { 253 Visit(E->getSubExpr()); 254 return; 255 } 256 257 switch (E->getCastKind()) { 258 case CK_Dynamic: { 259 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?"); 260 LValue LV = CGF.EmitCheckedLValue(E->getSubExpr()); 261 // FIXME: Do we also need to handle property references here? 262 if (LV.isSimple()) 263 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E)); 264 else 265 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast"); 266 267 if (!Dest.isIgnored()) 268 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination"); 269 break; 270 } 271 272 case CK_ToUnion: { 273 // GCC union extension 274 QualType Ty = E->getSubExpr()->getType(); 275 QualType PtrTy = CGF.getContext().getPointerType(Ty); 276 llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(), 277 CGF.ConvertType(PtrTy)); 278 EmitInitializationToLValue(E->getSubExpr(), CGF.MakeAddrLValue(CastPtr, Ty), 279 Ty); 280 break; 281 } 282 283 case CK_DerivedToBase: 284 case CK_BaseToDerived: 285 case CK_UncheckedDerivedToBase: { 286 assert(0 && "cannot perform hierarchy conversion in EmitAggExpr: " 287 "should have been unpacked before we got here"); 288 break; 289 } 290 291 case CK_GetObjCProperty: { 292 LValue LV = CGF.EmitLValue(E->getSubExpr()); 293 assert(LV.isPropertyRef()); 294 RValue RV = CGF.EmitLoadOfPropertyRefLValue(LV, getReturnValueSlot()); 295 EmitGCMove(E, RV); 296 break; 297 } 298 299 case CK_LValueToRValue: // hope for downstream optimization 300 case CK_NoOp: 301 case CK_UserDefinedConversion: 302 case CK_ConstructorConversion: 303 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(), 304 E->getType()) && 305 "Implicit cast types must be compatible"); 306 Visit(E->getSubExpr()); 307 break; 308 309 case CK_LValueBitCast: 310 llvm_unreachable("should not be emitting lvalue bitcast as rvalue"); 311 break; 312 313 case CK_ResolveUnknownAnyType: 314 case CK_ResolveUnknownAnyTypeToReference: 315 EmitAggLoadOfLValue(E); 316 break; 317 318 case CK_Dependent: 319 case CK_BitCast: 320 case CK_ArrayToPointerDecay: 321 case CK_FunctionToPointerDecay: 322 case CK_NullToPointer: 323 case CK_NullToMemberPointer: 324 case CK_BaseToDerivedMemberPointer: 325 case CK_DerivedToBaseMemberPointer: 326 case CK_MemberPointerToBoolean: 327 case CK_IntegralToPointer: 328 case CK_PointerToIntegral: 329 case CK_PointerToBoolean: 330 case CK_ToVoid: 331 case CK_VectorSplat: 332 case CK_IntegralCast: 333 case CK_IntegralToBoolean: 334 case CK_IntegralToFloating: 335 case CK_FloatingToIntegral: 336 case CK_FloatingToBoolean: 337 case CK_FloatingCast: 338 case CK_AnyPointerToObjCPointerCast: 339 case CK_AnyPointerToBlockPointerCast: 340 case CK_ObjCObjectLValueCast: 341 case CK_FloatingRealToComplex: 342 case CK_FloatingComplexToReal: 343 case CK_FloatingComplexToBoolean: 344 case CK_FloatingComplexCast: 345 case CK_FloatingComplexToIntegralComplex: 346 case CK_IntegralRealToComplex: 347 case CK_IntegralComplexToReal: 348 case CK_IntegralComplexToBoolean: 349 case CK_IntegralComplexCast: 350 case CK_IntegralComplexToFloatingComplex: 351 llvm_unreachable("cast kind invalid for aggregate types"); 352 } 353 } 354 355 void AggExprEmitter::VisitCallExpr(const CallExpr *E) { 356 if (E->getCallReturnType()->isReferenceType()) { 357 EmitAggLoadOfLValue(E); 358 return; 359 } 360 361 RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot()); 362 EmitGCMove(E, RV); 363 } 364 365 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) { 366 RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot()); 367 EmitGCMove(E, RV); 368 } 369 370 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 371 llvm_unreachable("direct property access not surrounded by " 372 "lvalue-to-rvalue cast"); 373 } 374 375 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) { 376 CGF.EmitIgnoredExpr(E->getLHS()); 377 Visit(E->getRHS()); 378 } 379 380 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) { 381 CodeGenFunction::StmtExprEvaluation eval(CGF); 382 CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest); 383 } 384 385 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) { 386 if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI) 387 VisitPointerToDataMemberBinaryOperator(E); 388 else 389 CGF.ErrorUnsupported(E, "aggregate binary expression"); 390 } 391 392 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator( 393 const BinaryOperator *E) { 394 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E); 395 EmitFinalDestCopy(E, LV); 396 } 397 398 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { 399 // For an assignment to work, the value on the right has 400 // to be compatible with the value on the left. 401 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(), 402 E->getRHS()->getType()) 403 && "Invalid assignment"); 404 405 // FIXME: __block variables need the RHS evaluated first! 406 LValue LHS = CGF.EmitLValue(E->getLHS()); 407 408 // We have to special case property setters, otherwise we must have 409 // a simple lvalue (no aggregates inside vectors, bitfields). 410 if (LHS.isPropertyRef()) { 411 const ObjCPropertyRefExpr *RE = LHS.getPropertyRefExpr(); 412 QualType ArgType = RE->getSetterArgType(); 413 RValue Src; 414 if (ArgType->isReferenceType()) 415 Src = CGF.EmitReferenceBindingToExpr(E->getRHS(), 0); 416 else { 417 AggValueSlot Slot = EnsureSlot(E->getRHS()->getType()); 418 CGF.EmitAggExpr(E->getRHS(), Slot); 419 Src = Slot.asRValue(); 420 } 421 CGF.EmitStoreThroughPropertyRefLValue(Src, LHS); 422 } else { 423 bool GCollection = false; 424 if (CGF.getContext().getLangOptions().getGCMode()) 425 GCollection = TypeRequiresGCollection(E->getLHS()->getType()); 426 427 // Codegen the RHS so that it stores directly into the LHS. 428 AggValueSlot LHSSlot = AggValueSlot::forLValue(LHS, true, 429 GCollection); 430 CGF.EmitAggExpr(E->getRHS(), LHSSlot, false); 431 EmitFinalDestCopy(E, LHS, true); 432 } 433 } 434 435 void AggExprEmitter:: 436 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 437 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 438 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 439 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 440 441 // Bind the common expression if necessary. 442 CodeGenFunction::OpaqueValueMapping binding(CGF, E); 443 444 CodeGenFunction::ConditionalEvaluation eval(CGF); 445 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock); 446 447 // Save whether the destination's lifetime is externally managed. 448 bool DestLifetimeManaged = Dest.isLifetimeExternallyManaged(); 449 450 eval.begin(CGF); 451 CGF.EmitBlock(LHSBlock); 452 Visit(E->getTrueExpr()); 453 eval.end(CGF); 454 455 assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!"); 456 CGF.Builder.CreateBr(ContBlock); 457 458 // If the result of an agg expression is unused, then the emission 459 // of the LHS might need to create a destination slot. That's fine 460 // with us, and we can safely emit the RHS into the same slot, but 461 // we shouldn't claim that its lifetime is externally managed. 462 Dest.setLifetimeExternallyManaged(DestLifetimeManaged); 463 464 eval.begin(CGF); 465 CGF.EmitBlock(RHSBlock); 466 Visit(E->getFalseExpr()); 467 eval.end(CGF); 468 469 CGF.EmitBlock(ContBlock); 470 } 471 472 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) { 473 Visit(CE->getChosenSubExpr(CGF.getContext())); 474 } 475 476 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 477 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 478 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 479 480 if (!ArgPtr) { 481 CGF.ErrorUnsupported(VE, "aggregate va_arg expression"); 482 return; 483 } 484 485 EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType())); 486 } 487 488 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 489 // Ensure that we have a slot, but if we already do, remember 490 // whether its lifetime was externally managed. 491 bool WasManaged = Dest.isLifetimeExternallyManaged(); 492 Dest = EnsureSlot(E->getType()); 493 Dest.setLifetimeExternallyManaged(); 494 495 Visit(E->getSubExpr()); 496 497 // Set up the temporary's destructor if its lifetime wasn't already 498 // being managed. 499 if (!WasManaged) 500 CGF.EmitCXXTemporary(E->getTemporary(), Dest.getAddr()); 501 } 502 503 void 504 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) { 505 AggValueSlot Slot = EnsureSlot(E->getType()); 506 CGF.EmitCXXConstructExpr(E, Slot); 507 } 508 509 void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) { 510 CGF.EmitExprWithCleanups(E, Dest); 511 } 512 513 void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) { 514 QualType T = E->getType(); 515 AggValueSlot Slot = EnsureSlot(T); 516 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T), T); 517 } 518 519 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) { 520 QualType T = E->getType(); 521 AggValueSlot Slot = EnsureSlot(T); 522 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T), T); 523 } 524 525 /// isSimpleZero - If emitting this value will obviously just cause a store of 526 /// zero to memory, return true. This can return false if uncertain, so it just 527 /// handles simple cases. 528 static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) { 529 // (0) 530 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 531 return isSimpleZero(PE->getSubExpr(), CGF); 532 // 0 533 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) 534 return IL->getValue() == 0; 535 // +0.0 536 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E)) 537 return FL->getValue().isPosZero(); 538 // int() 539 if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) && 540 CGF.getTypes().isZeroInitializable(E->getType())) 541 return true; 542 // (int*)0 - Null pointer expressions. 543 if (const CastExpr *ICE = dyn_cast<CastExpr>(E)) 544 return ICE->getCastKind() == CK_NullToPointer; 545 // '\0' 546 if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) 547 return CL->getValue() == 0; 548 549 // Otherwise, hard case: conservatively return false. 550 return false; 551 } 552 553 554 void 555 AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV, QualType T) { 556 // FIXME: Ignore result? 557 // FIXME: Are initializers affected by volatile? 558 if (Dest.isZeroed() && isSimpleZero(E, CGF)) { 559 // Storing "i32 0" to a zero'd memory location is a noop. 560 } else if (isa<ImplicitValueInitExpr>(E)) { 561 EmitNullInitializationToLValue(LV, T); 562 } else if (T->isReferenceType()) { 563 RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0); 564 CGF.EmitStoreThroughLValue(RV, LV, T); 565 } else if (T->isAnyComplexType()) { 566 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false); 567 } else if (CGF.hasAggregateLLVMType(T)) { 568 CGF.EmitAggExpr(E, AggValueSlot::forAddr(LV.getAddress(), false, true, 569 false, Dest.isZeroed())); 570 } else { 571 CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV, T); 572 } 573 } 574 575 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) { 576 // If the destination slot is already zeroed out before the aggregate is 577 // copied into it, we don't have to emit any zeros here. 578 if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(T)) 579 return; 580 581 if (!CGF.hasAggregateLLVMType(T)) { 582 // For non-aggregates, we can store zero 583 llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T)); 584 CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T); 585 } else { 586 // There's a potential optimization opportunity in combining 587 // memsets; that would be easy for arrays, but relatively 588 // difficult for structures with the current code. 589 CGF.EmitNullInitialization(LV.getAddress(), T); 590 } 591 } 592 593 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { 594 #if 0 595 // FIXME: Assess perf here? Figure out what cases are worth optimizing here 596 // (Length of globals? Chunks of zeroed-out space?). 597 // 598 // If we can, prefer a copy from a global; this is a lot less code for long 599 // globals, and it's easier for the current optimizers to analyze. 600 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) { 601 llvm::GlobalVariable* GV = 602 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true, 603 llvm::GlobalValue::InternalLinkage, C, ""); 604 EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType())); 605 return; 606 } 607 #endif 608 if (E->hadArrayRangeDesignator()) 609 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 610 611 llvm::Value *DestPtr = Dest.getAddr(); 612 613 // Handle initialization of an array. 614 if (E->getType()->isArrayType()) { 615 const llvm::PointerType *APType = 616 cast<llvm::PointerType>(DestPtr->getType()); 617 const llvm::ArrayType *AType = 618 cast<llvm::ArrayType>(APType->getElementType()); 619 620 uint64_t NumInitElements = E->getNumInits(); 621 622 if (E->getNumInits() > 0) { 623 QualType T1 = E->getType(); 624 QualType T2 = E->getInit(0)->getType(); 625 if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) { 626 EmitAggLoadOfLValue(E->getInit(0)); 627 return; 628 } 629 } 630 631 uint64_t NumArrayElements = AType->getNumElements(); 632 QualType ElementType = CGF.getContext().getCanonicalType(E->getType()); 633 ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType(); 634 635 // FIXME: were we intentionally ignoring address spaces and GC attributes? 636 637 for (uint64_t i = 0; i != NumArrayElements; ++i) { 638 // If we're done emitting initializers and the destination is known-zeroed 639 // then we're done. 640 if (i == NumInitElements && 641 Dest.isZeroed() && 642 CGF.getTypes().isZeroInitializable(ElementType)) 643 break; 644 645 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 646 LValue LV = CGF.MakeAddrLValue(NextVal, ElementType); 647 648 if (i < NumInitElements) 649 EmitInitializationToLValue(E->getInit(i), LV, ElementType); 650 else 651 EmitNullInitializationToLValue(LV, ElementType); 652 653 // If the GEP didn't get used because of a dead zero init or something 654 // else, clean it up for -O0 builds and general tidiness. 655 if (llvm::GetElementPtrInst *GEP = 656 dyn_cast<llvm::GetElementPtrInst>(NextVal)) 657 if (GEP->use_empty()) 658 GEP->eraseFromParent(); 659 } 660 return; 661 } 662 663 assert(E->getType()->isRecordType() && "Only support structs/unions here!"); 664 665 // Do struct initialization; this code just sets each individual member 666 // to the approprate value. This makes bitfield support automatic; 667 // the disadvantage is that the generated code is more difficult for 668 // the optimizer, especially with bitfields. 669 unsigned NumInitElements = E->getNumInits(); 670 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl(); 671 672 if (E->getType()->isUnionType()) { 673 // Only initialize one field of a union. The field itself is 674 // specified by the initializer list. 675 if (!E->getInitializedFieldInUnion()) { 676 // Empty union; we have nothing to do. 677 678 #ifndef NDEBUG 679 // Make sure that it's really an empty and not a failure of 680 // semantic analysis. 681 for (RecordDecl::field_iterator Field = SD->field_begin(), 682 FieldEnd = SD->field_end(); 683 Field != FieldEnd; ++Field) 684 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed"); 685 #endif 686 return; 687 } 688 689 // FIXME: volatility 690 FieldDecl *Field = E->getInitializedFieldInUnion(); 691 692 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0); 693 if (NumInitElements) { 694 // Store the initializer into the field 695 EmitInitializationToLValue(E->getInit(0), FieldLoc, Field->getType()); 696 } else { 697 // Default-initialize to null. 698 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 699 } 700 701 return; 702 } 703 704 // Here we iterate over the fields; this makes it simpler to both 705 // default-initialize fields and skip over unnamed fields. 706 unsigned CurInitVal = 0; 707 for (RecordDecl::field_iterator Field = SD->field_begin(), 708 FieldEnd = SD->field_end(); 709 Field != FieldEnd; ++Field) { 710 // We're done once we hit the flexible array member 711 if (Field->getType()->isIncompleteArrayType()) 712 break; 713 714 if (Field->isUnnamedBitfield()) 715 continue; 716 717 // Don't emit GEP before a noop store of zero. 718 if (CurInitVal == NumInitElements && Dest.isZeroed() && 719 CGF.getTypes().isZeroInitializable(E->getType())) 720 break; 721 722 // FIXME: volatility 723 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, *Field, 0); 724 // We never generate write-barries for initialized fields. 725 FieldLoc.setNonGC(true); 726 727 if (CurInitVal < NumInitElements) { 728 // Store the initializer into the field. 729 EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc, 730 Field->getType()); 731 } else { 732 // We're out of initalizers; default-initialize to null 733 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 734 } 735 736 // If the GEP didn't get used because of a dead zero init or something 737 // else, clean it up for -O0 builds and general tidiness. 738 if (FieldLoc.isSimple()) 739 if (llvm::GetElementPtrInst *GEP = 740 dyn_cast<llvm::GetElementPtrInst>(FieldLoc.getAddress())) 741 if (GEP->use_empty()) 742 GEP->eraseFromParent(); 743 } 744 } 745 746 //===----------------------------------------------------------------------===// 747 // Entry Points into this File 748 //===----------------------------------------------------------------------===// 749 750 /// GetNumNonZeroBytesInInit - Get an approximate count of the number of 751 /// non-zero bytes that will be stored when outputting the initializer for the 752 /// specified initializer expression. 753 static uint64_t GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) { 754 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 755 return GetNumNonZeroBytesInInit(PE->getSubExpr(), CGF); 756 757 // 0 and 0.0 won't require any non-zero stores! 758 if (isSimpleZero(E, CGF)) return 0; 759 760 // If this is an initlist expr, sum up the size of sizes of the (present) 761 // elements. If this is something weird, assume the whole thing is non-zero. 762 const InitListExpr *ILE = dyn_cast<InitListExpr>(E); 763 if (ILE == 0 || !CGF.getTypes().isZeroInitializable(ILE->getType())) 764 return CGF.getContext().getTypeSize(E->getType())/8; 765 766 // InitListExprs for structs have to be handled carefully. If there are 767 // reference members, we need to consider the size of the reference, not the 768 // referencee. InitListExprs for unions and arrays can't have references. 769 if (const RecordType *RT = E->getType()->getAs<RecordType>()) { 770 if (!RT->isUnionType()) { 771 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl(); 772 uint64_t NumNonZeroBytes = 0; 773 774 unsigned ILEElement = 0; 775 for (RecordDecl::field_iterator Field = SD->field_begin(), 776 FieldEnd = SD->field_end(); Field != FieldEnd; ++Field) { 777 // We're done once we hit the flexible array member or run out of 778 // InitListExpr elements. 779 if (Field->getType()->isIncompleteArrayType() || 780 ILEElement == ILE->getNumInits()) 781 break; 782 if (Field->isUnnamedBitfield()) 783 continue; 784 785 const Expr *E = ILE->getInit(ILEElement++); 786 787 // Reference values are always non-null and have the width of a pointer. 788 if (Field->getType()->isReferenceType()) 789 NumNonZeroBytes += CGF.getContext().Target.getPointerWidth(0); 790 else 791 NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF); 792 } 793 794 return NumNonZeroBytes; 795 } 796 } 797 798 799 uint64_t NumNonZeroBytes = 0; 800 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) 801 NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF); 802 return NumNonZeroBytes; 803 } 804 805 /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of 806 /// zeros in it, emit a memset and avoid storing the individual zeros. 807 /// 808 static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E, 809 CodeGenFunction &CGF) { 810 // If the slot is already known to be zeroed, nothing to do. Don't mess with 811 // volatile stores. 812 if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == 0) return; 813 814 // If the type is 16-bytes or smaller, prefer individual stores over memset. 815 std::pair<uint64_t, unsigned> TypeInfo = 816 CGF.getContext().getTypeInfo(E->getType()); 817 if (TypeInfo.first/8 <= 16) 818 return; 819 820 // Check to see if over 3/4 of the initializer are known to be zero. If so, 821 // we prefer to emit memset + individual stores for the rest. 822 uint64_t NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF); 823 if (NumNonZeroBytes*4 > TypeInfo.first/8) 824 return; 825 826 // Okay, it seems like a good idea to use an initial memset, emit the call. 827 llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first/8); 828 unsigned Align = TypeInfo.second/8; 829 830 llvm::Value *Loc = Slot.getAddr(); 831 const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext()); 832 833 Loc = CGF.Builder.CreateBitCast(Loc, BP); 834 CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, Align, false); 835 836 // Tell the AggExprEmitter that the slot is known zero. 837 Slot.setZeroed(); 838 } 839 840 841 842 843 /// EmitAggExpr - Emit the computation of the specified expression of aggregate 844 /// type. The result is computed into DestPtr. Note that if DestPtr is null, 845 /// the value of the aggregate expression is not needed. If VolatileDest is 846 /// true, DestPtr cannot be 0. 847 /// 848 /// \param IsInitializer - true if this evaluation is initializing an 849 /// object whose lifetime is already being managed. 850 // 851 // FIXME: Take Qualifiers object. 852 void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot, 853 bool IgnoreResult) { 854 assert(E && hasAggregateLLVMType(E->getType()) && 855 "Invalid aggregate expression to emit"); 856 assert((Slot.getAddr() != 0 || Slot.isIgnored()) && 857 "slot has bits but no address"); 858 859 // Optimize the slot if possible. 860 CheckAggExprForMemSetUse(Slot, E, *this); 861 862 AggExprEmitter(*this, Slot, IgnoreResult).Visit(const_cast<Expr*>(E)); 863 } 864 865 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) { 866 assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!"); 867 llvm::Value *Temp = CreateMemTemp(E->getType()); 868 LValue LV = MakeAddrLValue(Temp, E->getType()); 869 EmitAggExpr(E, AggValueSlot::forAddr(Temp, LV.isVolatileQualified(), false)); 870 return LV; 871 } 872 873 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr, 874 llvm::Value *SrcPtr, QualType Ty, 875 bool isVolatile) { 876 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 877 878 if (getContext().getLangOptions().CPlusPlus) { 879 if (const RecordType *RT = Ty->getAs<RecordType>()) { 880 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); 881 assert((Record->hasTrivialCopyConstructor() || 882 Record->hasTrivialCopyAssignment()) && 883 "Trying to aggregate-copy a type without a trivial copy " 884 "constructor or assignment operator"); 885 // Ignore empty classes in C++. 886 if (Record->isEmpty()) 887 return; 888 } 889 } 890 891 // Aggregate assignment turns into llvm.memcpy. This is almost valid per 892 // C99 6.5.16.1p3, which states "If the value being stored in an object is 893 // read from another object that overlaps in anyway the storage of the first 894 // object, then the overlap shall be exact and the two objects shall have 895 // qualified or unqualified versions of a compatible type." 896 // 897 // memcpy is not defined if the source and destination pointers are exactly 898 // equal, but other compilers do this optimization, and almost every memcpy 899 // implementation handles this case safely. If there is a libc that does not 900 // safely handle this, we can add a target hook. 901 902 // Get size and alignment info for this aggregate. 903 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 904 905 // FIXME: Handle variable sized types. 906 907 // FIXME: If we have a volatile struct, the optimizer can remove what might 908 // appear to be `extra' memory ops: 909 // 910 // volatile struct { int i; } a, b; 911 // 912 // int main() { 913 // a = b; 914 // a = b; 915 // } 916 // 917 // we need to use a different call here. We use isVolatile to indicate when 918 // either the source or the destination is volatile. 919 920 const llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType()); 921 const llvm::Type *DBP = 922 llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace()); 923 DestPtr = Builder.CreateBitCast(DestPtr, DBP, "tmp"); 924 925 const llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType()); 926 const llvm::Type *SBP = 927 llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace()); 928 SrcPtr = Builder.CreateBitCast(SrcPtr, SBP, "tmp"); 929 930 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) { 931 RecordDecl *Record = RecordTy->getDecl(); 932 if (Record->hasObjectMember()) { 933 unsigned long size = TypeInfo.first/8; 934 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 935 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size); 936 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, 937 SizeVal); 938 return; 939 } 940 } else if (getContext().getAsArrayType(Ty)) { 941 QualType BaseType = getContext().getBaseElementType(Ty); 942 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 943 if (RecordTy->getDecl()->hasObjectMember()) { 944 unsigned long size = TypeInfo.first/8; 945 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 946 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size); 947 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, 948 SizeVal); 949 return; 950 } 951 } 952 } 953 954 Builder.CreateMemCpy(DestPtr, SrcPtr, 955 llvm::ConstantInt::get(IntPtrTy, TypeInfo.first/8), 956 TypeInfo.second/8, isVolatile); 957 } 958