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