Deleted Added
full compact
CGClass.cpp (200583) CGClass.cpp (201361)
1//===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
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//===----------------------------------------------------------------------===//

--- 255 unchanged lines hidden (view full) ---

264 PHI->addIncoming(Value, CastNotNull);
265 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
266 CastNull);
267 Value = PHI;
268 }
269
270 return Value;
271}
1//===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
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//===----------------------------------------------------------------------===//

--- 255 unchanged lines hidden (view full) ---

264 PHI->addIncoming(Value, CastNotNull);
265 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
266 CastNull);
267 Value = PHI;
268 }
269
270 return Value;
271}
272
273/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
274/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
275/// copy or via a copy constructor call.
276// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
277void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
278 llvm::Value *Src,
279 const ArrayType *Array,
280 const CXXRecordDecl *BaseClassDecl,
281 QualType Ty) {
282 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
283 assert(CA && "VLA cannot be copied over");
284 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
285
286 // Create a temporary for the loop index and initialize it with 0.
287 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
288 "loop.index");
289 llvm::Value* zeroConstant =
290 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
291 Builder.CreateStore(zeroConstant, IndexPtr);
292 // Start the loop with a block that tests the condition.
293 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
294 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
295
296 EmitBlock(CondBlock);
297
298 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
299 // Generate: if (loop-index < number-of-elements fall to the loop body,
300 // otherwise, go to the block after the for-loop.
301 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
302 llvm::Value * NumElementsPtr =
303 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
304 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
305 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
306 "isless");
307 // If the condition is true, execute the body.
308 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
309
310 EmitBlock(ForBody);
311 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
312 // Inside the loop body, emit the constructor call on the array element.
313 Counter = Builder.CreateLoad(IndexPtr);
314 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
315 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
316 if (BitwiseCopy)
317 EmitAggregateCopy(Dest, Src, Ty);
318 else if (CXXConstructorDecl *BaseCopyCtor =
319 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
320 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
321 Ctor_Complete);
322 CallArgList CallArgs;
323 // Push the this (Dest) ptr.
324 CallArgs.push_back(std::make_pair(RValue::get(Dest),
325 BaseCopyCtor->getThisType(getContext())));
326
327 // Push the Src ptr.
328 CallArgs.push_back(std::make_pair(RValue::get(Src),
329 BaseCopyCtor->getParamDecl(0)->getType()));
330 QualType ResultType =
331 BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
332 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
333 Callee, ReturnValueSlot(), CallArgs, BaseCopyCtor);
334 }
335 EmitBlock(ContinueBlock);
336
337 // Emit the increment of the loop counter.
338 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
339 Counter = Builder.CreateLoad(IndexPtr);
340 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
341 Builder.CreateStore(NextVal, IndexPtr);
342
343 // Finally, branch back up to the condition for the next iteration.
344 EmitBranch(CondBlock);
345
346 // Emit the fall-through block.
347 EmitBlock(AfterFor, true);
348}
349
350/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
351/// array of objects from SrcValue to DestValue. Assignment can be either a
352/// bitwise assignment or via a copy assignment operator function call.
353/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
354void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
355 llvm::Value *Src,
356 const ArrayType *Array,
357 const CXXRecordDecl *BaseClassDecl,
358 QualType Ty) {
359 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
360 assert(CA && "VLA cannot be asssigned");
361 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
362
363 // Create a temporary for the loop index and initialize it with 0.
364 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
365 "loop.index");
366 llvm::Value* zeroConstant =
367 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
368 Builder.CreateStore(zeroConstant, IndexPtr);
369 // Start the loop with a block that tests the condition.
370 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
371 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
372
373 EmitBlock(CondBlock);
374
375 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
376 // Generate: if (loop-index < number-of-elements fall to the loop body,
377 // otherwise, go to the block after the for-loop.
378 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
379 llvm::Value * NumElementsPtr =
380 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
381 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
382 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
383 "isless");
384 // If the condition is true, execute the body.
385 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
386
387 EmitBlock(ForBody);
388 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
389 // Inside the loop body, emit the assignment operator call on array element.
390 Counter = Builder.CreateLoad(IndexPtr);
391 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
392 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
393 const CXXMethodDecl *MD = 0;
394 if (BitwiseAssign)
395 EmitAggregateCopy(Dest, Src, Ty);
396 else {
397 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
398 MD);
399 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
400 (void)hasCopyAssign;
401 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
402 const llvm::Type *LTy =
403 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
404 FPT->isVariadic());
405 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
406
407 CallArgList CallArgs;
408 // Push the this (Dest) ptr.
409 CallArgs.push_back(std::make_pair(RValue::get(Dest),
410 MD->getThisType(getContext())));
411
412 // Push the Src ptr.
413 CallArgs.push_back(std::make_pair(RValue::get(Src),
414 MD->getParamDecl(0)->getType()));
415 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
416 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
417 Callee, ReturnValueSlot(), CallArgs, MD);
418 }
419 EmitBlock(ContinueBlock);
420
421 // Emit the increment of the loop counter.
422 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
423 Counter = Builder.CreateLoad(IndexPtr);
424 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
425 Builder.CreateStore(NextVal, IndexPtr);
426
427 // Finally, branch back up to the condition for the next iteration.
428 EmitBranch(CondBlock);
429
430 // Emit the fall-through block.
431 EmitBlock(AfterFor, true);
432}
433
434/// EmitClassMemberwiseCopy - This routine generates code to copy a class
435/// object from SrcValue to DestValue. Copying can be either a bitwise copy
436/// or via a copy constructor call.
437void CodeGenFunction::EmitClassMemberwiseCopy(
438 llvm::Value *Dest, llvm::Value *Src,
439 const CXXRecordDecl *ClassDecl,
440 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
441 if (ClassDecl) {
442 Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
443 /*NullCheckValue=*/false);
444 Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
445 /*NullCheckValue=*/false);
446 }
447 if (BaseClassDecl->hasTrivialCopyConstructor()) {
448 EmitAggregateCopy(Dest, Src, Ty);
449 return;
450 }
451
452 if (CXXConstructorDecl *BaseCopyCtor =
453 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
454 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
455 Ctor_Complete);
456 CallArgList CallArgs;
457 // Push the this (Dest) ptr.
458 CallArgs.push_back(std::make_pair(RValue::get(Dest),
459 BaseCopyCtor->getThisType(getContext())));
460
461 // Push the Src ptr.
462 CallArgs.push_back(std::make_pair(RValue::get(Src),
463 BaseCopyCtor->getParamDecl(0)->getType()));
464 QualType ResultType =
465 BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
466 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
467 Callee, ReturnValueSlot(), CallArgs, BaseCopyCtor);
468 }
469}
470
471/// EmitClassCopyAssignment - This routine generates code to copy assign a class
472/// object from SrcValue to DestValue. Assignment can be either a bitwise
473/// assignment of via an assignment operator call.
474// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
475void CodeGenFunction::EmitClassCopyAssignment(
476 llvm::Value *Dest, llvm::Value *Src,
477 const CXXRecordDecl *ClassDecl,
478 const CXXRecordDecl *BaseClassDecl,
479 QualType Ty) {
480 if (ClassDecl) {
481 Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
482 /*NullCheckValue=*/false);
483 Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
484 /*NullCheckValue=*/false);
485 }
486 if (BaseClassDecl->hasTrivialCopyAssignment()) {
487 EmitAggregateCopy(Dest, Src, Ty);
488 return;
489 }
490
491 const CXXMethodDecl *MD = 0;
492 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
493 MD);
494 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
495 (void)ConstCopyAssignOp;
496
497 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
498 const llvm::Type *LTy =
499 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
500 FPT->isVariadic());
501 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
502
503 CallArgList CallArgs;
504 // Push the this (Dest) ptr.
505 CallArgs.push_back(std::make_pair(RValue::get(Dest),
506 MD->getThisType(getContext())));
507
508 // Push the Src ptr.
509 CallArgs.push_back(std::make_pair(RValue::get(Src),
510 MD->getParamDecl(0)->getType()));
511 QualType ResultType =
512 MD->getType()->getAs<FunctionType>()->getResultType();
513 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
514 Callee, ReturnValueSlot(), CallArgs, MD);
515}
516
517/// SynthesizeDefaultConstructor - synthesize a default constructor
518void
519CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *Ctor,
520 CXXCtorType Type,
521 llvm::Function *Fn,
522 const FunctionArgList &Args) {
523 assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
524 StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
525 SourceLocation());
526 EmitCtorPrologue(Ctor, Type);
527 FinishFunction();
528}
529
530/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a
531/// copy constructor, in accordance with section 12.8 (p7 and p8) of C++03
532/// The implicitly-defined copy constructor for class X performs a memberwise
533/// copy of its subobjects. The order of copying is the same as the order of
534/// initialization of bases and members in a user-defined constructor
535/// Each subobject is copied in the manner appropriate to its type:
536/// if the subobject is of class type, the copy constructor for the class is
537/// used;
538/// if the subobject is an array, each element is copied, in the manner
539/// appropriate to the element type;
540/// if the subobject is of scalar type, the built-in assignment operator is
541/// used.
542/// Virtual base class subobjects shall be copied only once by the
543/// implicitly-defined copy constructor
544
545void
546CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *Ctor,
547 CXXCtorType Type,
548 llvm::Function *Fn,
549 const FunctionArgList &Args) {
550 const CXXRecordDecl *ClassDecl = Ctor->getParent();
551 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
552 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
553 assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
554 StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
555 SourceLocation());
556
557 FunctionArgList::const_iterator i = Args.begin();
558 const VarDecl *ThisArg = i->first;
559 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
560 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
561 const VarDecl *SrcArg = (i+1)->first;
562 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
563 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
564
565 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
566 Base != ClassDecl->bases_end(); ++Base) {
567 // FIXME. copy constrution of virtual base NYI
568 if (Base->isVirtual())
569 continue;
570
571 CXXRecordDecl *BaseClassDecl
572 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
573 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
574 Base->getType());
575 }
576
577 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
578 E = ClassDecl->field_end(); I != E; ++I) {
579 const FieldDecl *Field = *I;
580
581 QualType FieldType = getContext().getCanonicalType(Field->getType());
582 const ConstantArrayType *Array =
583 getContext().getAsConstantArrayType(FieldType);
584 if (Array)
585 FieldType = getContext().getBaseElementType(FieldType);
586
587 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
588 CXXRecordDecl *FieldClassDecl
589 = cast<CXXRecordDecl>(FieldClassType->getDecl());
590 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
591 LValue RHS = EmitLValueForField(LoadOfSrc, Field, false, 0);
592 if (Array) {
593 const llvm::Type *BasePtr = ConvertType(FieldType);
594 BasePtr = llvm::PointerType::getUnqual(BasePtr);
595 llvm::Value *DestBaseAddrPtr =
596 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
597 llvm::Value *SrcBaseAddrPtr =
598 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
599 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
600 FieldClassDecl, FieldType);
601 }
602 else
603 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
604 0 /*ClassDecl*/, FieldClassDecl, FieldType);
605 continue;
606 }
607
608 if (Field->getType()->isReferenceType()) {
609 unsigned FieldIndex = CGM.getTypes().getLLVMFieldNo(Field);
610
611 llvm::Value *LHS = Builder.CreateStructGEP(LoadOfThis, FieldIndex,
612 "lhs.ref");
613
614 llvm::Value *RHS = Builder.CreateStructGEP(LoadOfThis, FieldIndex,
615 "rhs.ref");
616
617 // Load the value in RHS.
618 RHS = Builder.CreateLoad(RHS);
619
620 // And store it in the LHS
621 Builder.CreateStore(RHS, LHS);
622
623 continue;
624 }
625 // Do a built-in assignment of scalar data members.
626 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
627 LValue RHS = EmitLValueForField(LoadOfSrc, Field, false, 0);
628
629 if (!hasAggregateLLVMType(Field->getType())) {
630 RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
631 EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
632 } else if (Field->getType()->isAnyComplexType()) {
633 ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
634 RHS.isVolatileQualified());
635 StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
636 } else {
637 EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
638 }
639 }
640
641 InitializeVtablePtrs(ClassDecl);
642 FinishFunction();
643}
644
645/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
646/// Before the implicitly-declared copy assignment operator for a class is
647/// implicitly defined, all implicitly- declared copy assignment operators for
648/// its direct base classes and its nonstatic data members shall have been
649/// implicitly defined. [12.8-p12]
650/// The implicitly-defined copy assignment operator for class X performs
651/// memberwise assignment of its subob- jects. The direct base classes of X are
652/// assigned first, in the order of their declaration in
653/// the base-specifier-list, and then the immediate nonstatic data members of X
654/// are assigned, in the order in which they were declared in the class
655/// definition.Each subobject is assigned in the manner appropriate to its type:
656/// if the subobject is of class type, the copy assignment operator for the
657/// class is used (as if by explicit qualification; that is, ignoring any
658/// possible virtual overriding functions in more derived classes);
659///
660/// if the subobject is an array, each element is assigned, in the manner
661/// appropriate to the element type;
662///
663/// if the subobject is of scalar type, the built-in assignment operator is
664/// used.
665void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
666 llvm::Function *Fn,
667 const FunctionArgList &Args) {
668
669 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
670 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
671 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
672 StartFunction(CD, CD->getResultType(), Fn, Args, SourceLocation());
673
674 FunctionArgList::const_iterator i = Args.begin();
675 const VarDecl *ThisArg = i->first;
676 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
677 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
678 const VarDecl *SrcArg = (i+1)->first;
679 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
680 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
681
682 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
683 Base != ClassDecl->bases_end(); ++Base) {
684 // FIXME. copy assignment of virtual base NYI
685 if (Base->isVirtual())
686 continue;
687
688 CXXRecordDecl *BaseClassDecl
689 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
690 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
691 Base->getType());
692 }
693
694 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
695 FieldEnd = ClassDecl->field_end();
696 Field != FieldEnd; ++Field) {
697 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
698 const ConstantArrayType *Array =
699 getContext().getAsConstantArrayType(FieldType);
700 if (Array)
701 FieldType = getContext().getBaseElementType(FieldType);
702
703 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
704 CXXRecordDecl *FieldClassDecl
705 = cast<CXXRecordDecl>(FieldClassType->getDecl());
706 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
707 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
708 if (Array) {
709 const llvm::Type *BasePtr = ConvertType(FieldType);
710 BasePtr = llvm::PointerType::getUnqual(BasePtr);
711 llvm::Value *DestBaseAddrPtr =
712 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
713 llvm::Value *SrcBaseAddrPtr =
714 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
715 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
716 FieldClassDecl, FieldType);
717 }
718 else
719 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
720 0 /*ClassDecl*/, FieldClassDecl, FieldType);
721 continue;
722 }
723 // Do a built-in assignment of scalar data members.
724 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
725 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
726 if (!hasAggregateLLVMType(Field->getType())) {
727 RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
728 EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
729 } else if (Field->getType()->isAnyComplexType()) {
730 ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
731 RHS.isVolatileQualified());
732 StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
733 } else {
734 EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
735 }
736 }
737
738 // return *this;
739 Builder.CreateStore(LoadOfThis, ReturnValue);
740
741 FinishFunction();
742}
743
744static void EmitBaseInitializer(CodeGenFunction &CGF,
745 const CXXRecordDecl *ClassDecl,
746 CXXBaseOrMemberInitializer *BaseInit,
747 CXXCtorType CtorType) {
748 assert(BaseInit->isBaseInitializer() &&
749 "Must have base initializer!");
750
751 llvm::Value *ThisPtr = CGF.LoadCXXThis();
752
753 const Type *BaseType = BaseInit->getBaseClass();
754 CXXRecordDecl *BaseClassDecl =
755 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
756
757 // FIXME: This method of determining whether a base is virtual is ridiculous;
758 // it should be part of BaseInit.
759 bool isBaseVirtual = false;
760 for (CXXRecordDecl::base_class_const_iterator I = ClassDecl->vbases_begin(),
761 E = ClassDecl->vbases_end(); I != E; ++I)
762 if (I->getType()->getAs<RecordType>()->getDecl() == BaseClassDecl) {
763 isBaseVirtual = true;
764 break;
765 }
766
767 // The base constructor doesn't construct virtual bases.
768 if (CtorType == Ctor_Base && isBaseVirtual)
769 return;
770
771 // Compute the offset to the base; we do this directly instead of using
772 // GetAddressOfBaseClass because the class doesn't have a vtable pointer
773 // at this point.
774 // FIXME: This could be refactored back into GetAddressOfBaseClass if it took
775 // an extra parameter for whether the derived class is the complete object
776 // class.
777 const ASTRecordLayout &Layout =
778 CGF.getContext().getASTRecordLayout(ClassDecl);
779 uint64_t Offset;
780 if (isBaseVirtual)
781 Offset = Layout.getVBaseClassOffset(BaseClassDecl);
782 else
783 Offset = Layout.getBaseClassOffset(BaseClassDecl);
784 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
785 const llvm::Type *BaseClassType = CGF.ConvertType(QualType(BaseType, 0));
786 llvm::Value *V = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
787 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, Offset/8);
788 V = CGF.Builder.CreateBitCast(V, BaseClassType->getPointerTo());
789
790 // FIXME: This should always use Ctor_Base as the ctor type! (But that
791 // causes crashes in tests.)
792 CGF.EmitCXXConstructorCall(BaseInit->getConstructor(),
793 CtorType, V,
794 BaseInit->const_arg_begin(),
795 BaseInit->const_arg_end());
796}
797
798static void EmitMemberInitializer(CodeGenFunction &CGF,
799 const CXXRecordDecl *ClassDecl,
800 CXXBaseOrMemberInitializer *MemberInit) {
801 assert(MemberInit->isMemberInitializer() &&
802 "Must have member initializer!");
803
804 // non-static data member initializers.
805 FieldDecl *Field = MemberInit->getMember();
806 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
807
808 llvm::Value *ThisPtr = CGF.LoadCXXThis();
809 LValue LHS;
810 if (FieldType->isReferenceType()) {
811 // FIXME: This is really ugly; should be refactored somehow
812 unsigned idx = CGF.CGM.getTypes().getLLVMFieldNo(Field);
813 llvm::Value *V = CGF.Builder.CreateStructGEP(ThisPtr, idx, "tmp");
814 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
815 LHS = LValue::MakeAddr(V, CGF.MakeQualifiers(FieldType));
816 } else {
817 LHS = CGF.EmitLValueForField(ThisPtr, Field, ClassDecl->isUnion(), 0);
818 }
819
820 // If we are initializing an anonymous union field, drill down to the field.
821 if (MemberInit->getAnonUnionMember()) {
822 Field = MemberInit->getAnonUnionMember();
823 LHS = CGF.EmitLValueForField(LHS.getAddress(), Field,
824 /*IsUnion=*/true, 0);
825 FieldType = Field->getType();
826 }
827
828 // If the field is an array, branch based on the element type.
829 const ConstantArrayType *Array =
830 CGF.getContext().getAsConstantArrayType(FieldType);
831 if (Array)
832 FieldType = CGF.getContext().getBaseElementType(FieldType);
833
834 // We lose the constructor for anonymous union members, so handle them
835 // explicitly.
836 // FIXME: This is somwhat ugly.
837 if (MemberInit->getAnonUnionMember() && FieldType->getAs<RecordType>()) {
838 if (MemberInit->getNumArgs())
839 CGF.EmitAggExpr(*MemberInit->arg_begin(), LHS.getAddress(),
840 LHS.isVolatileQualified());
841 else
842 CGF.EmitAggregateClear(LHS.getAddress(), Field->getType());
843 return;
844 }
845
846 if (FieldType->getAs<RecordType>()) {
847 assert(MemberInit->getConstructor() &&
848 "EmitCtorPrologue - no constructor to initialize member");
849 if (Array) {
850 const llvm::Type *BasePtr = CGF.ConvertType(FieldType);
851 BasePtr = llvm::PointerType::getUnqual(BasePtr);
852 llvm::Value *BaseAddrPtr =
853 CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
854 CGF.EmitCXXAggrConstructorCall(MemberInit->getConstructor(),
855 Array, BaseAddrPtr,
856 MemberInit->const_arg_begin(),
857 MemberInit->const_arg_end());
858 }
859 else
860 CGF.EmitCXXConstructorCall(MemberInit->getConstructor(),
861 Ctor_Complete, LHS.getAddress(),
862 MemberInit->const_arg_begin(),
863 MemberInit->const_arg_end());
864 return;
865 }
866
867 assert(MemberInit->getNumArgs() == 1 && "Initializer count must be 1 only");
868 Expr *RhsExpr = *MemberInit->arg_begin();
869 RValue RHS;
870 if (FieldType->isReferenceType()) {
871 RHS = CGF.EmitReferenceBindingToExpr(RhsExpr, FieldType,
872 /*IsInitializer=*/true);
873 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
874 } else if (Array) {
875 CGF.EmitMemSetToZero(LHS.getAddress(), Field->getType());
876 } else if (!CGF.hasAggregateLLVMType(RhsExpr->getType())) {
877 RHS = RValue::get(CGF.EmitScalarExpr(RhsExpr, true));
878 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
879 } else if (RhsExpr->getType()->isAnyComplexType()) {
880 CGF.EmitComplexExprIntoAddr(RhsExpr, LHS.getAddress(),
881 LHS.isVolatileQualified());
882 } else {
883 // Handle member function pointers; other aggregates shouldn't get this far.
884 CGF.EmitAggExpr(RhsExpr, LHS.getAddress(), LHS.isVolatileQualified());
885 }
886}
887
888/// EmitCtorPrologue - This routine generates necessary code to initialize
889/// base classes and non-static data members belonging to this constructor.
890/// FIXME: This needs to take a CXXCtorType.
891void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
892 CXXCtorType CtorType) {
893 const CXXRecordDecl *ClassDecl = CD->getParent();
894
895 // FIXME: Add vbase initialization
896
897 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
898 E = CD->init_end();
899 B != E; ++B) {
900 CXXBaseOrMemberInitializer *Member = (*B);
901
902 assert(LiveTemporaries.empty() &&
903 "Should not have any live temporaries at initializer start!");
904
905 if (Member->isBaseInitializer())
906 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
907 else
908 EmitMemberInitializer(*this, ClassDecl, Member);
909
910 // Pop any live temporaries that the initializers might have pushed.
911 while (!LiveTemporaries.empty())
912 PopCXXTemporary();
913 }
914
915 InitializeVtablePtrs(ClassDecl);
916}
917
918/// EmitDtorEpilogue - Emit all code that comes at the end of class's
919/// destructor. This is to call destructors on members and base classes
920/// in reverse order of their construction.
921/// FIXME: This needs to take a CXXDtorType.
922void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD,
923 CXXDtorType DtorType) {
924 assert(!DD->isTrivial() &&
925 "Should not emit dtor epilogue for trivial dtor!");
926
927 const CXXRecordDecl *ClassDecl = DD->getParent();
928
929 // Collect the fields.
930 llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
931 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
932 E = ClassDecl->field_end(); I != E; ++I) {
933 const FieldDecl *Field = *I;
934
935 QualType FieldType = getContext().getCanonicalType(Field->getType());
936 FieldType = getContext().getBaseElementType(FieldType);
937
938 const RecordType *RT = FieldType->getAs<RecordType>();
939 if (!RT)
940 continue;
941
942 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
943 if (FieldClassDecl->hasTrivialDestructor())
944 continue;
945
946 FieldDecls.push_back(Field);
947 }
948
949 // Now destroy the fields.
950 for (size_t i = FieldDecls.size(); i > 0; --i) {
951 const FieldDecl *Field = FieldDecls[i - 1];
952
953 QualType FieldType = Field->getType();
954 const ConstantArrayType *Array =
955 getContext().getAsConstantArrayType(FieldType);
956 if (Array)
957 FieldType = getContext().getBaseElementType(FieldType);
958
959 const RecordType *RT = FieldType->getAs<RecordType>();
960 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
961
962 llvm::Value *ThisPtr = LoadCXXThis();
963
964 LValue LHS = EmitLValueForField(ThisPtr, Field,
965 /*isUnion=*/false,
966 // FIXME: Qualifiers?
967 /*CVRQualifiers=*/0);
968 if (Array) {
969 const llvm::Type *BasePtr = ConvertType(FieldType);
970 BasePtr = llvm::PointerType::getUnqual(BasePtr);
971 llvm::Value *BaseAddrPtr =
972 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
973 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
974 Array, BaseAddrPtr);
975 } else
976 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
977 Dtor_Complete, LHS.getAddress());
978 }
979
980 // Destroy non-virtual bases.
981 for (CXXRecordDecl::reverse_base_class_const_iterator I =
982 ClassDecl->bases_rbegin(), E = ClassDecl->bases_rend(); I != E; ++I) {
983 const CXXBaseSpecifier &Base = *I;
984
985 // Ignore virtual bases.
986 if (Base.isVirtual())
987 continue;
988
989 CXXRecordDecl *BaseClassDecl
990 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
991
992 // Ignore trivial destructors.
993 if (BaseClassDecl->hasTrivialDestructor())
994 continue;
995 const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
996
997 llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
998 ClassDecl, BaseClassDecl,
999 /*NullCheckValue=*/false);
1000 EmitCXXDestructorCall(D, Dtor_Base, V);
1001 }
1002
1003 // If we're emitting a base destructor, we don't want to emit calls to the
1004 // virtual bases.
1005 if (DtorType == Dtor_Base)
1006 return;
1007
1008 // Handle virtual bases.
1009 for (CXXRecordDecl::reverse_base_class_const_iterator I =
1010 ClassDecl->vbases_rbegin(), E = ClassDecl->vbases_rend(); I != E; ++I) {
1011 const CXXBaseSpecifier &Base = *I;
1012 CXXRecordDecl *BaseClassDecl
1013 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1014
1015 // Ignore trivial destructors.
1016 if (BaseClassDecl->hasTrivialDestructor())
1017 continue;
1018 const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1019 llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1020 ClassDecl, BaseClassDecl,
1021 /*NullCheckValue=*/false);
1022 EmitCXXDestructorCall(D, Dtor_Base, V);
1023 }
1024
1025 // If we have a deleting destructor, emit a call to the delete operator.
1026 if (DtorType == Dtor_Deleting) {
1027 assert(DD->getOperatorDelete() &&
1028 "operator delete missing - EmitDtorEpilogue");
1029 EmitDeleteCall(DD->getOperatorDelete(), LoadCXXThis(),
1030 getContext().getTagDeclType(ClassDecl));
1031 }
1032}
1033
1034void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *Dtor,
1035 CXXDtorType DtorType,
1036 llvm::Function *Fn,
1037 const FunctionArgList &Args) {
1038 assert(!Dtor->getParent()->hasUserDeclaredDestructor() &&
1039 "SynthesizeDefaultDestructor - destructor has user declaration");
1040
1041 StartFunction(GlobalDecl(Dtor, DtorType), Dtor->getResultType(), Fn, Args,
1042 SourceLocation());
1043
1044 EmitDtorEpilogue(Dtor, DtorType);
1045 FinishFunction();
1046}