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 41 ReturnValueSlot getReturnValueSlot() const { 42 // If the destination slot requires garbage collection, we can't 43 // use the real return value slot, because we have to use the GC 44 // API. 45 if (RequiresGCollection) return ReturnValueSlot(); 46 47 return ReturnValueSlot(DestPtr, VolatileDest); 48 } 49 50 public: 51 AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool v, 52 bool ignore, bool isinit, bool requiresGCollection) 53 : CGF(cgf), Builder(CGF.Builder), 54 DestPtr(destPtr), VolatileDest(v), IgnoreResult(ignore), 55 IsInitializer(isinit), RequiresGCollection(requiresGCollection) { 56 } 57 58 //===--------------------------------------------------------------------===// 59 // Utilities 60 //===--------------------------------------------------------------------===// 61 62 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 63 /// represents a value lvalue, this method emits the address of the lvalue, 64 /// then loads the result into DestPtr. 65 void EmitAggLoadOfLValue(const Expr *E); 66 67 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 68 void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false); 69 void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false); 70 71 void EmitGCMove(const Expr *E, RValue Src); 72 73 bool TypeRequiresGCollection(QualType T); 74 75 //===--------------------------------------------------------------------===// 76 // Visitor Methods 77 //===--------------------------------------------------------------------===// 78 79 void VisitStmt(Stmt *S) { 80 CGF.ErrorUnsupported(S, "aggregate expression"); 81 } 82 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); } 83 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); } 84 85 // l-values. 86 void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); } 87 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); } 88 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); } 89 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); } 90 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 91 EmitAggLoadOfLValue(E); 92 } 93 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 94 EmitAggLoadOfLValue(E); 95 } 96 void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { 97 EmitAggLoadOfLValue(E); 98 } 99 void VisitPredefinedExpr(const PredefinedExpr *E) { 100 EmitAggLoadOfLValue(E); 101 } 102 103 // Operators. 104 void VisitCastExpr(CastExpr *E); 105 void VisitCallExpr(const CallExpr *E); 106 void VisitStmtExpr(const StmtExpr *E); 107 void VisitBinaryOperator(const BinaryOperator *BO); 108 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO); 109 void VisitBinAssign(const BinaryOperator *E); 110 void VisitBinComma(const BinaryOperator *E); 111 112 void VisitObjCMessageExpr(ObjCMessageExpr *E); 113 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 114 EmitAggLoadOfLValue(E); 115 } 116 void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E); 117 void VisitObjCImplicitSetterGetterRefExpr(ObjCImplicitSetterGetterRefExpr *E); 118 119 void VisitConditionalOperator(const ConditionalOperator *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 VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E); 129 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E); 130 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); } 131 132 void VisitVAArgExpr(VAArgExpr *E); 133 134 void EmitInitializationToLValue(Expr *E, LValue Address, QualType T); 135 void EmitNullInitializationToLValue(LValue Address, QualType T); 136 // case Expr::ChooseExprClass: 137 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); } 138 }; 139 } // end anonymous namespace. 140 141 //===----------------------------------------------------------------------===// 142 // Utilities 143 //===----------------------------------------------------------------------===// 144 145 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 146 /// represents a value lvalue, this method emits the address of the lvalue, 147 /// then loads the result into DestPtr. 148 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) { 149 LValue LV = CGF.EmitLValue(E); 150 EmitFinalDestCopy(E, LV); 151 } 152 153 /// \brief True if the given aggregate type requires special GC API calls. 154 bool AggExprEmitter::TypeRequiresGCollection(QualType T) { 155 // Only record types have members that might require garbage collection. 156 const RecordType *RecordTy = T->getAs<RecordType>(); 157 if (!RecordTy) return false; 158 159 // Don't mess with non-trivial C++ types. 160 RecordDecl *Record = RecordTy->getDecl(); 161 if (isa<CXXRecordDecl>(Record) && 162 (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() || 163 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor())) 164 return false; 165 166 // Check whether the type has an object member. 167 return Record->hasObjectMember(); 168 } 169 170 /// \brief Perform the final move to DestPtr if RequiresGCollection is set. 171 /// 172 /// The idea is that you do something like this: 173 /// RValue Result = EmitSomething(..., getReturnValueSlot()); 174 /// EmitGCMove(E, Result); 175 /// If GC doesn't interfere, this will cause the result to be emitted 176 /// directly into the return value slot. If GC does interfere, a final 177 /// move will be performed. 178 void AggExprEmitter::EmitGCMove(const Expr *E, RValue Src) { 179 if (RequiresGCollection) { 180 std::pair<uint64_t, unsigned> TypeInfo = 181 CGF.getContext().getTypeInfo(E->getType()); 182 unsigned long size = TypeInfo.first/8; 183 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType()); 184 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size); 185 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, DestPtr, 186 Src.getAggregateAddr(), 187 SizeVal); 188 } 189 } 190 191 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 192 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) { 193 assert(Src.isAggregate() && "value must be aggregate value!"); 194 195 // If DestPtr is null, then we're evaluating an aggregate expression 196 // in a context (like an expression statement) that doesn't care 197 // about the result. C says that an lvalue-to-rvalue conversion is 198 // performed in these cases; C++ says that it is not. In either 199 // case, we don't actually need to do anything unless the value is 200 // volatile. 201 if (DestPtr == 0) { 202 if (!Src.isVolatileQualified() || 203 CGF.CGM.getLangOptions().CPlusPlus || 204 (IgnoreResult && Ignore)) 205 return; 206 207 // If the source is volatile, we must read from it; to do that, we need 208 // some place to put it. 209 DestPtr = CGF.CreateMemTemp(E->getType(), "agg.tmp"); 210 } 211 212 if (RequiresGCollection) { 213 std::pair<uint64_t, unsigned> TypeInfo = 214 CGF.getContext().getTypeInfo(E->getType()); 215 unsigned long size = TypeInfo.first/8; 216 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType()); 217 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size); 218 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, 219 DestPtr, 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(DestPtr, Src.getAggregateAddr(), E->getType(), 228 VolatileDest|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::VisitCastExpr(CastExpr *E) { 245 if (!DestPtr && E->getCastKind() != CastExpr::CK_Dynamic) { 246 Visit(E->getSubExpr()); 247 return; 248 } 249 250 switch (E->getCastKind()) { 251 default: assert(0 && "Unhandled cast kind!"); 252 253 case CastExpr::CK_Dynamic: { 254 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?"); 255 LValue LV = CGF.EmitCheckedLValue(E->getSubExpr()); 256 // FIXME: Do we also need to handle property references here? 257 if (LV.isSimple()) 258 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E)); 259 else 260 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast"); 261 262 if (DestPtr) 263 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination"); 264 break; 265 } 266 267 case CastExpr::CK_ToUnion: { 268 // GCC union extension 269 QualType Ty = E->getSubExpr()->getType(); 270 QualType PtrTy = CGF.getContext().getPointerType(Ty); 271 llvm::Value *CastPtr = Builder.CreateBitCast(DestPtr, 272 CGF.ConvertType(PtrTy)); 273 EmitInitializationToLValue(E->getSubExpr(), CGF.MakeAddrLValue(CastPtr, Ty), 274 Ty); 275 break; 276 } 277 278 case CastExpr::CK_DerivedToBase: 279 case CastExpr::CK_BaseToDerived: 280 case CastExpr::CK_UncheckedDerivedToBase: { 281 assert(0 && "cannot perform hierarchy conversion in EmitAggExpr: " 282 "should have been unpacked before we got here"); 283 break; 284 } 285 286 // FIXME: Remove the CK_Unknown check here. 287 case CastExpr::CK_Unknown: 288 case CastExpr::CK_NoOp: 289 case CastExpr::CK_UserDefinedConversion: 290 case CastExpr::CK_ConstructorConversion: 291 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(), 292 E->getType()) && 293 "Implicit cast types must be compatible"); 294 Visit(E->getSubExpr()); 295 break; 296 297 case CastExpr::CK_LValueBitCast: 298 llvm_unreachable("there are no lvalue bit-casts on aggregates"); 299 break; 300 } 301 } 302 303 void AggExprEmitter::VisitCallExpr(const CallExpr *E) { 304 if (E->getCallReturnType()->isReferenceType()) { 305 EmitAggLoadOfLValue(E); 306 return; 307 } 308 309 RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot()); 310 EmitGCMove(E, RV); 311 } 312 313 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) { 314 RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot()); 315 EmitGCMove(E, RV); 316 } 317 318 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 319 RValue RV = CGF.EmitObjCPropertyGet(E, getReturnValueSlot()); 320 EmitGCMove(E, RV); 321 } 322 323 void AggExprEmitter::VisitObjCImplicitSetterGetterRefExpr( 324 ObjCImplicitSetterGetterRefExpr *E) { 325 RValue RV = CGF.EmitObjCPropertyGet(E, getReturnValueSlot()); 326 EmitGCMove(E, RV); 327 } 328 329 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) { 330 CGF.EmitAnyExpr(E->getLHS(), 0, false, true); 331 CGF.EmitAggExpr(E->getRHS(), DestPtr, VolatileDest, 332 /*IgnoreResult=*/false, IsInitializer); 333 } 334 335 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) { 336 CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest); 337 } 338 339 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) { 340 if (E->getOpcode() == BinaryOperator::PtrMemD || 341 E->getOpcode() == BinaryOperator::PtrMemI) 342 VisitPointerToDataMemberBinaryOperator(E); 343 else 344 CGF.ErrorUnsupported(E, "aggregate binary expression"); 345 } 346 347 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator( 348 const BinaryOperator *E) { 349 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E); 350 EmitFinalDestCopy(E, LV); 351 } 352 353 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { 354 // For an assignment to work, the value on the right has 355 // to be compatible with the value on the left. 356 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(), 357 E->getRHS()->getType()) 358 && "Invalid assignment"); 359 LValue LHS = CGF.EmitLValue(E->getLHS()); 360 361 // We have to special case property setters, otherwise we must have 362 // a simple lvalue (no aggregates inside vectors, bitfields). 363 if (LHS.isPropertyRef()) { 364 llvm::Value *AggLoc = DestPtr; 365 if (!AggLoc) 366 AggLoc = CGF.CreateMemTemp(E->getRHS()->getType()); 367 CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest); 368 CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(), 369 RValue::getAggregate(AggLoc, VolatileDest)); 370 } else if (LHS.isKVCRef()) { 371 llvm::Value *AggLoc = DestPtr; 372 if (!AggLoc) 373 AggLoc = CGF.CreateMemTemp(E->getRHS()->getType()); 374 CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest); 375 CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(), 376 RValue::getAggregate(AggLoc, VolatileDest)); 377 } else { 378 bool RequiresGCollection = false; 379 if (CGF.getContext().getLangOptions().getGCMode()) 380 RequiresGCollection = TypeRequiresGCollection(E->getLHS()->getType()); 381 382 // Codegen the RHS so that it stores directly into the LHS. 383 CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified(), 384 false, false, RequiresGCollection); 385 EmitFinalDestCopy(E, LHS, true); 386 } 387 } 388 389 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) { 390 if (!E->getLHS()) { 391 CGF.ErrorUnsupported(E, "conditional operator with missing LHS"); 392 return; 393 } 394 395 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 396 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 397 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 398 399 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock); 400 401 CGF.BeginConditionalBranch(); 402 CGF.EmitBlock(LHSBlock); 403 404 // Handle the GNU extension for missing LHS. 405 assert(E->getLHS() && "Must have LHS for aggregate value"); 406 407 Visit(E->getLHS()); 408 CGF.EndConditionalBranch(); 409 CGF.EmitBranch(ContBlock); 410 411 CGF.BeginConditionalBranch(); 412 CGF.EmitBlock(RHSBlock); 413 414 Visit(E->getRHS()); 415 CGF.EndConditionalBranch(); 416 CGF.EmitBranch(ContBlock); 417 418 CGF.EmitBlock(ContBlock); 419 } 420 421 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) { 422 Visit(CE->getChosenSubExpr(CGF.getContext())); 423 } 424 425 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 426 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 427 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 428 429 if (!ArgPtr) { 430 CGF.ErrorUnsupported(VE, "aggregate va_arg expression"); 431 return; 432 } 433 434 EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType())); 435 } 436 437 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 438 llvm::Value *Val = DestPtr; 439 440 if (!Val) { 441 // Create a temporary variable. 442 Val = CGF.CreateMemTemp(E->getType(), "tmp"); 443 444 // FIXME: volatile 445 CGF.EmitAggExpr(E->getSubExpr(), Val, false); 446 } else 447 Visit(E->getSubExpr()); 448 449 // Don't make this a live temporary if we're emitting an initializer expr. 450 if (!IsInitializer) 451 CGF.EmitCXXTemporary(E->getTemporary(), Val); 452 } 453 454 void 455 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) { 456 llvm::Value *Val = DestPtr; 457 458 if (!Val) // Create a temporary variable. 459 Val = CGF.CreateMemTemp(E->getType(), "tmp"); 460 461 CGF.EmitCXXConstructExpr(Val, E); 462 } 463 464 void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) { 465 llvm::Value *Val = DestPtr; 466 467 CGF.EmitCXXExprWithTemporaries(E, Val, VolatileDest, IsInitializer); 468 } 469 470 void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) { 471 llvm::Value *Val = DestPtr; 472 473 if (!Val) { 474 // Create a temporary variable. 475 Val = CGF.CreateMemTemp(E->getType(), "tmp"); 476 } 477 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Val, E->getType()), 478 E->getType()); 479 } 480 481 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) { 482 llvm::Value *Val = DestPtr; 483 484 if (!Val) { 485 // Create a temporary variable. 486 Val = CGF.CreateMemTemp(E->getType(), "tmp"); 487 } 488 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Val, E->getType()), 489 E->getType()); 490 } 491 492 void 493 AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV, QualType T) { 494 // FIXME: Ignore result? 495 // FIXME: Are initializers affected by volatile? 496 if (isa<ImplicitValueInitExpr>(E)) { 497 EmitNullInitializationToLValue(LV, T); 498 } else if (T->isReferenceType()) { 499 RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0); 500 CGF.EmitStoreThroughLValue(RV, LV, T); 501 } else if (T->isAnyComplexType()) { 502 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false); 503 } else if (CGF.hasAggregateLLVMType(T)) { 504 CGF.EmitAnyExpr(E, LV.getAddress(), false); 505 } else { 506 CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, T); 507 } 508 } 509 510 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) { 511 if (!CGF.hasAggregateLLVMType(T)) { 512 // For non-aggregates, we can store zero 513 llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T)); 514 CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T); 515 } else { 516 // There's a potential optimization opportunity in combining 517 // memsets; that would be easy for arrays, but relatively 518 // difficult for structures with the current code. 519 CGF.EmitNullInitialization(LV.getAddress(), T); 520 } 521 } 522 523 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { 524 #if 0 525 // FIXME: Assess perf here? Figure out what cases are worth optimizing here 526 // (Length of globals? Chunks of zeroed-out space?). 527 // 528 // If we can, prefer a copy from a global; this is a lot less code for long 529 // globals, and it's easier for the current optimizers to analyze. 530 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) { 531 llvm::GlobalVariable* GV = 532 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true, 533 llvm::GlobalValue::InternalLinkage, C, ""); 534 EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType())); 535 return; 536 } 537 #endif 538 if (E->hadArrayRangeDesignator()) { 539 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 540 } 541 542 // Handle initialization of an array. 543 if (E->getType()->isArrayType()) { 544 const llvm::PointerType *APType = 545 cast<llvm::PointerType>(DestPtr->getType()); 546 const llvm::ArrayType *AType = 547 cast<llvm::ArrayType>(APType->getElementType()); 548 549 uint64_t NumInitElements = E->getNumInits(); 550 551 if (E->getNumInits() > 0) { 552 QualType T1 = E->getType(); 553 QualType T2 = E->getInit(0)->getType(); 554 if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) { 555 EmitAggLoadOfLValue(E->getInit(0)); 556 return; 557 } 558 } 559 560 uint64_t NumArrayElements = AType->getNumElements(); 561 QualType ElementType = CGF.getContext().getCanonicalType(E->getType()); 562 ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType(); 563 564 // FIXME: were we intentionally ignoring address spaces and GC attributes? 565 566 for (uint64_t i = 0; i != NumArrayElements; ++i) { 567 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 568 LValue LV = CGF.MakeAddrLValue(NextVal, ElementType); 569 if (i < NumInitElements) 570 EmitInitializationToLValue(E->getInit(i), LV, ElementType); 571 572 else 573 EmitNullInitializationToLValue(LV, ElementType); 574 } 575 return; 576 } 577 578 assert(E->getType()->isRecordType() && "Only support structs/unions here!"); 579 580 // Do struct initialization; this code just sets each individual member 581 // to the approprate value. This makes bitfield support automatic; 582 // the disadvantage is that the generated code is more difficult for 583 // the optimizer, especially with bitfields. 584 unsigned NumInitElements = E->getNumInits(); 585 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl(); 586 unsigned CurInitVal = 0; 587 588 if (E->getType()->isUnionType()) { 589 // Only initialize one field of a union. The field itself is 590 // specified by the initializer list. 591 if (!E->getInitializedFieldInUnion()) { 592 // Empty union; we have nothing to do. 593 594 #ifndef NDEBUG 595 // Make sure that it's really an empty and not a failure of 596 // semantic analysis. 597 for (RecordDecl::field_iterator Field = SD->field_begin(), 598 FieldEnd = SD->field_end(); 599 Field != FieldEnd; ++Field) 600 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed"); 601 #endif 602 return; 603 } 604 605 // FIXME: volatility 606 FieldDecl *Field = E->getInitializedFieldInUnion(); 607 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0); 608 609 if (NumInitElements) { 610 // Store the initializer into the field 611 EmitInitializationToLValue(E->getInit(0), FieldLoc, Field->getType()); 612 } else { 613 // Default-initialize to null 614 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 615 } 616 617 return; 618 } 619 620 // If we're initializing the whole aggregate, just do it in place. 621 // FIXME: This is a hack around an AST bug (PR6537). 622 if (NumInitElements == 1 && E->getType() == E->getInit(0)->getType()) { 623 EmitInitializationToLValue(E->getInit(0), 624 CGF.MakeAddrLValue(DestPtr, E->getType()), 625 E->getType()); 626 return; 627 } 628 629 630 // Here we iterate over the fields; this makes it simpler to both 631 // default-initialize fields and skip over unnamed fields. 632 for (RecordDecl::field_iterator Field = SD->field_begin(), 633 FieldEnd = SD->field_end(); 634 Field != FieldEnd; ++Field) { 635 // We're done once we hit the flexible array member 636 if (Field->getType()->isIncompleteArrayType()) 637 break; 638 639 if (Field->isUnnamedBitfield()) 640 continue; 641 642 // FIXME: volatility 643 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, *Field, 0); 644 // We never generate write-barries for initialized fields. 645 FieldLoc.setNonGC(true); 646 if (CurInitVal < NumInitElements) { 647 // Store the initializer into the field. 648 EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc, 649 Field->getType()); 650 } else { 651 // We're out of initalizers; default-initialize to null 652 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 653 } 654 } 655 } 656 657 //===----------------------------------------------------------------------===// 658 // Entry Points into this File 659 //===----------------------------------------------------------------------===// 660 661 /// EmitAggExpr - Emit the computation of the specified expression of aggregate 662 /// type. The result is computed into DestPtr. Note that if DestPtr is null, 663 /// the value of the aggregate expression is not needed. If VolatileDest is 664 /// true, DestPtr cannot be 0. 665 // 666 // FIXME: Take Qualifiers object. 667 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr, 668 bool VolatileDest, bool IgnoreResult, 669 bool IsInitializer, 670 bool RequiresGCollection) { 671 assert(E && hasAggregateLLVMType(E->getType()) && 672 "Invalid aggregate expression to emit"); 673 assert ((DestPtr != 0 || VolatileDest == false) 674 && "volatile aggregate can't be 0"); 675 676 AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult, IsInitializer, 677 RequiresGCollection) 678 .Visit(const_cast<Expr*>(E)); 679 } 680 681 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) { 682 assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!"); 683 llvm::Value *Temp = CreateMemTemp(E->getType()); 684 LValue LV = MakeAddrLValue(Temp, E->getType()); 685 EmitAggExpr(E, Temp, LV.isVolatileQualified()); 686 return LV; 687 } 688 689 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr, 690 llvm::Value *SrcPtr, QualType Ty, 691 bool isVolatile) { 692 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 693 694 if (getContext().getLangOptions().CPlusPlus) { 695 if (const RecordType *RT = Ty->getAs<RecordType>()) { 696 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); 697 assert((Record->hasTrivialCopyConstructor() || 698 Record->hasTrivialCopyAssignment()) && 699 "Trying to aggregate-copy a type without a trivial copy " 700 "constructor or assignment operator"); 701 // Ignore empty classes in C++. 702 if (Record->isEmpty()) 703 return; 704 } 705 } 706 707 // Aggregate assignment turns into llvm.memcpy. This is almost valid per 708 // C99 6.5.16.1p3, which states "If the value being stored in an object is 709 // read from another object that overlaps in anyway the storage of the first 710 // object, then the overlap shall be exact and the two objects shall have 711 // qualified or unqualified versions of a compatible type." 712 // 713 // memcpy is not defined if the source and destination pointers are exactly 714 // equal, but other compilers do this optimization, and almost every memcpy 715 // implementation handles this case safely. If there is a libc that does not 716 // safely handle this, we can add a target hook. 717 718 // Get size and alignment info for this aggregate. 719 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 720 721 // FIXME: Handle variable sized types. 722 723 // FIXME: If we have a volatile struct, the optimizer can remove what might 724 // appear to be `extra' memory ops: 725 // 726 // volatile struct { int i; } a, b; 727 // 728 // int main() { 729 // a = b; 730 // a = b; 731 // } 732 // 733 // we need to use a different call here. We use isVolatile to indicate when 734 // either the source or the destination is volatile. 735 736 const llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType()); 737 const llvm::Type *DBP = 738 llvm::Type::getInt8PtrTy(VMContext, DPT->getAddressSpace()); 739 DestPtr = Builder.CreateBitCast(DestPtr, DBP, "tmp"); 740 741 const llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType()); 742 const llvm::Type *SBP = 743 llvm::Type::getInt8PtrTy(VMContext, SPT->getAddressSpace()); 744 SrcPtr = Builder.CreateBitCast(SrcPtr, SBP, "tmp"); 745 746 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) { 747 RecordDecl *Record = RecordTy->getDecl(); 748 if (Record->hasObjectMember()) { 749 unsigned long size = TypeInfo.first/8; 750 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 751 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size); 752 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, 753 SizeVal); 754 return; 755 } 756 } else if (getContext().getAsArrayType(Ty)) { 757 QualType BaseType = getContext().getBaseElementType(Ty); 758 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 759 if (RecordTy->getDecl()->hasObjectMember()) { 760 unsigned long size = TypeInfo.first/8; 761 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 762 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size); 763 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, 764 SizeVal); 765 return; 766 } 767 } 768 } 769 770 Builder.CreateCall5(CGM.getMemCpyFn(DestPtr->getType(), SrcPtr->getType(), 771 IntPtrTy), 772 DestPtr, SrcPtr, 773 // TypeInfo.first describes size in bits. 774 llvm::ConstantInt::get(IntPtrTy, TypeInfo.first/8), 775 Builder.getInt32(TypeInfo.second/8), 776 Builder.getInt1(isVolatile)); 777 } 778