blob: 170f965e80d98ac4364ca7ed64f13195faef4d31 [file] [log] [blame]
Anders Carlsson5b955922009-11-24 05:51:11 +00001//===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
Anders Carlsson5d58a1d2009-09-12 04:27:24 +00002//
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 dealing with C++ code generation of classes
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000015#include "clang/AST/CXXInheritance.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000016#include "clang/AST/RecordLayout.h"
John McCall9fc6a772010-02-19 09:25:03 +000017#include "clang/AST/StmtCXX.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000018
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000019using namespace clang;
20using namespace CodeGen;
21
Anders Carlsson2f1986b2009-10-06 22:43:30 +000022static uint64_t
Anders Carlsson34a2d382010-04-24 21:06:20 +000023ComputeNonVirtualBaseClassOffset(ASTContext &Context,
24 const CXXRecordDecl *DerivedClass,
25 CXXBaseSpecifierArray::iterator Start,
26 CXXBaseSpecifierArray::iterator End) {
27 uint64_t Offset = 0;
28
29 const CXXRecordDecl *RD = DerivedClass;
30
31 for (CXXBaseSpecifierArray::iterator I = Start; I != End; ++I) {
32 const CXXBaseSpecifier *Base = *I;
33 assert(!Base->isVirtual() && "Should not see virtual bases here!");
34
35 // Get the layout.
36 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
37
38 const CXXRecordDecl *BaseDecl =
39 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
40
41 // Add the offset.
42 Offset += Layout.getBaseClassOffset(BaseDecl);
43
44 RD = BaseDecl;
45 }
46
47 // FIXME: We should not use / 8 here.
48 return Offset / 8;
49}
50
51static uint64_t
John McCallbff225e2010-02-16 04:15:37 +000052ComputeNonVirtualBaseClassOffset(ASTContext &Context,
53 const CXXBasePath &Path,
Anders Carlsson2f1986b2009-10-06 22:43:30 +000054 unsigned Start) {
55 uint64_t Offset = 0;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000056
Anders Carlsson2f1986b2009-10-06 22:43:30 +000057 for (unsigned i = Start, e = Path.size(); i != e; ++i) {
58 const CXXBasePathElement& Element = Path[i];
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000059
Anders Carlsson2f1986b2009-10-06 22:43:30 +000060 // Get the layout.
61 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000062
Anders Carlsson2f1986b2009-10-06 22:43:30 +000063 const CXXBaseSpecifier *BS = Element.Base;
64 assert(!BS->isVirtual() && "Should not see virtual bases here!");
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000065
Anders Carlsson2f1986b2009-10-06 22:43:30 +000066 const CXXRecordDecl *Base =
67 cast<CXXRecordDecl>(BS->getType()->getAs<RecordType>()->getDecl());
68
69 // Add the offset.
70 Offset += Layout.getBaseClassOffset(Base) / 8;
71 }
72
73 return Offset;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000074}
75
Anders Carlsson84080ec2009-09-29 03:13:20 +000076llvm::Constant *
Anders Carlssona04efdf2010-04-24 21:23:59 +000077CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
78 const CXXBaseSpecifierArray &BasePath) {
79 assert(!BasePath.empty() && "Base path should not be empty!");
80
81 uint64_t Offset =
82 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
83 BasePath.begin(), BasePath.end());
84 if (!Offset)
85 return 0;
86
87 const llvm::Type *PtrDiffTy =
88 Types.ConvertType(getContext().getPointerDiffType());
89
90 return llvm::ConstantInt::get(PtrDiffTy, Offset);
Anders Carlsson84080ec2009-09-29 03:13:20 +000091}
92
John McCallbff225e2010-02-16 04:15:37 +000093/// Gets the address of a virtual base class within a complete object.
94/// This should only be used for (1) non-virtual bases or (2) virtual bases
95/// when the type is known to be complete (e.g. in complete destructors).
96///
97/// The object pointed to by 'This' is assumed to be non-null.
98llvm::Value *
99CodeGenFunction::GetAddressOfBaseOfCompleteClass(llvm::Value *This,
100 bool isBaseVirtual,
101 const CXXRecordDecl *Derived,
102 const CXXRecordDecl *Base) {
103 // 'this' must be a pointer (in some address space) to Derived.
104 assert(This->getType()->isPointerTy() &&
105 cast<llvm::PointerType>(This->getType())->getElementType()
106 == ConvertType(Derived));
107
108 // Compute the offset of the virtual base.
109 uint64_t Offset;
110 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
111 if (isBaseVirtual)
112 Offset = Layout.getVBaseClassOffset(Base);
113 else
114 Offset = Layout.getBaseClassOffset(Base);
115
116 // Shift and cast down to the base type.
117 // TODO: for complete types, this should be possible with a GEP.
118 llvm::Value *V = This;
119 if (Offset) {
120 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
121 V = Builder.CreateBitCast(V, Int8PtrTy);
122 V = Builder.CreateConstInBoundsGEP1_64(V, Offset / 8);
123 }
124 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
125
126 return V;
Anders Carlssond103f9f2010-03-28 19:40:00 +0000127}
John McCallbff225e2010-02-16 04:15:37 +0000128
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000129static llvm::Value *
130ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr,
131 uint64_t NonVirtual, llvm::Value *Virtual) {
132 const llvm::Type *PtrDiffTy =
133 CGF.ConvertType(CGF.getContext().getPointerDiffType());
134
135 llvm::Value *NonVirtualOffset = 0;
136 if (NonVirtual)
137 NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy, NonVirtual);
138
139 llvm::Value *BaseOffset;
140 if (Virtual) {
141 if (NonVirtualOffset)
142 BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset);
143 else
144 BaseOffset = Virtual;
145 } else
146 BaseOffset = NonVirtualOffset;
147
148 // Apply the base offset.
149 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
150 ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
151 ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
152
153 return ThisPtr;
154}
155
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000156llvm::Value *
Anders Carlsson34a2d382010-04-24 21:06:20 +0000157CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
158 const CXXRecordDecl *ClassDecl,
159 const CXXBaseSpecifierArray &BasePath,
160 bool NullCheckValue) {
161 assert(!BasePath.empty() && "Base path should not be empty!");
162
163 CXXBaseSpecifierArray::iterator Start = BasePath.begin();
164 const CXXRecordDecl *VBase = 0;
165
166 // Get the virtual base.
167 if ((*Start)->isVirtual()) {
168 VBase =
169 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
170 ++Start;
171 }
172
173 uint64_t NonVirtualOffset =
174 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : ClassDecl,
175 Start, BasePath.end());
176
177 // Get the base pointer type.
178 const llvm::Type *BasePtrTy =
Anders Carlssonfc89c312010-04-24 21:12:55 +0000179 ConvertType((BasePath.end()[-1])->getType())->getPointerTo();
Anders Carlsson34a2d382010-04-24 21:06:20 +0000180
181 if (!NonVirtualOffset && !VBase) {
182 // Just cast back.
183 return Builder.CreateBitCast(Value, BasePtrTy);
184 }
185
186 llvm::BasicBlock *CastNull = 0;
187 llvm::BasicBlock *CastNotNull = 0;
188 llvm::BasicBlock *CastEnd = 0;
189
190 if (NullCheckValue) {
191 CastNull = createBasicBlock("cast.null");
192 CastNotNull = createBasicBlock("cast.notnull");
193 CastEnd = createBasicBlock("cast.end");
194
195 llvm::Value *IsNull =
196 Builder.CreateICmpEQ(Value,
197 llvm::Constant::getNullValue(Value->getType()));
198 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
199 EmitBlock(CastNotNull);
200 }
201
202 llvm::Value *VirtualOffset = 0;
203
204 if (VBase)
205 VirtualOffset = GetVirtualBaseClassOffset(Value, ClassDecl, VBase);
206
207 // Apply the offsets.
208 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
209 VirtualOffset);
210
211 // Cast back.
212 Value = Builder.CreateBitCast(Value, BasePtrTy);
213
214 if (NullCheckValue) {
215 Builder.CreateBr(CastEnd);
216 EmitBlock(CastNull);
217 Builder.CreateBr(CastEnd);
218 EmitBlock(CastEnd);
219
220 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
221 PHI->reserveOperandSpace(2);
222 PHI->addIncoming(Value, CastNotNull);
223 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
224 CastNull);
225 Value = PHI;
226 }
227
228 return Value;
229}
230
231llvm::Value *
Anders Carlssona88ad562010-04-24 21:51:08 +0000232CodeGenFunction::OldGetAddressOfBaseClass(llvm::Value *Value,
233 const CXXRecordDecl *Class,
234 const CXXRecordDecl *BaseClass) {
Anders Carlssondfd03302009-09-22 21:58:22 +0000235 QualType BTy =
236 getContext().getCanonicalType(
John McCallbff225e2010-02-16 04:15:37 +0000237 getContext().getTypeDeclType(BaseClass));
Anders Carlssondfd03302009-09-22 21:58:22 +0000238 const llvm::Type *BasePtrTy = llvm::PointerType::getUnqual(ConvertType(BTy));
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000239
Anders Carlssonbb7e17b2010-01-31 01:36:53 +0000240 if (Class == BaseClass) {
Anders Carlssondfd03302009-09-22 21:58:22 +0000241 // Just cast back.
Anders Carlssona3697c92009-11-23 17:57:54 +0000242 return Builder.CreateBitCast(Value, BasePtrTy);
Anders Carlssondfd03302009-09-22 21:58:22 +0000243 }
Anders Carlsson905a1002010-01-31 02:39:02 +0000244
Anders Carlsson2692d822010-04-20 05:07:22 +0000245#ifndef NDEBUG
246 CXXBasePaths Paths(/*FindAmbiguities=*/true,
247 /*RecordPaths=*/true, /*DetectVirtual=*/false);
248#else
Anders Carlsson905a1002010-01-31 02:39:02 +0000249 CXXBasePaths Paths(/*FindAmbiguities=*/false,
250 /*RecordPaths=*/true, /*DetectVirtual=*/false);
Anders Carlsson2692d822010-04-20 05:07:22 +0000251#endif
Anders Carlsson905a1002010-01-31 02:39:02 +0000252 if (!const_cast<CXXRecordDecl *>(Class)->
253 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseClass), Paths)) {
254 assert(false && "Class must be derived from the passed in base class!");
255 return 0;
256 }
257
Anders Carlssonc2a9b792010-04-21 18:03:05 +0000258#if 0
259 // FIXME: Re-enable this assert when the underlying bugs have been fixed.
Anders Carlsson2692d822010-04-20 05:07:22 +0000260 assert(!Paths.isAmbiguous(BTy) && "Path is ambiguous");
Anders Carlssonc2a9b792010-04-21 18:03:05 +0000261#endif
Anders Carlsson2692d822010-04-20 05:07:22 +0000262
Anders Carlsson905a1002010-01-31 02:39:02 +0000263 unsigned Start = 0;
Anders Carlsson905a1002010-01-31 02:39:02 +0000264
265 const CXXBasePath &Path = Paths.front();
266 const CXXRecordDecl *VBase = 0;
267 for (unsigned i = 0, e = Path.size(); i != e; ++i) {
268 const CXXBasePathElement& Element = Path[i];
269 if (Element.Base->isVirtual()) {
270 Start = i+1;
271 QualType VBaseType = Element.Base->getType();
272 VBase = cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
273 }
274 }
275
276 uint64_t Offset =
John McCallbff225e2010-02-16 04:15:37 +0000277 ComputeNonVirtualBaseClassOffset(getContext(), Paths.front(), Start);
Eli Friedman4a5dc242009-11-10 22:48:10 +0000278
Anders Carlsson905a1002010-01-31 02:39:02 +0000279 if (!Offset && !VBase) {
280 // Just cast back.
281 return Builder.CreateBitCast(Value, BasePtrTy);
282 }
283
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000284 llvm::Value *VirtualOffset = 0;
285
Anders Carlsson905a1002010-01-31 02:39:02 +0000286 if (VBase)
287 VirtualOffset = GetVirtualBaseClassOffset(Value, Class, VBase);
Eli Friedman4a5dc242009-11-10 22:48:10 +0000288
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000289 // Apply the offsets.
290 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, Offset, VirtualOffset);
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000291
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000292 // Cast back.
Anders Carlssona3697c92009-11-23 17:57:54 +0000293 Value = Builder.CreateBitCast(Value, BasePtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000294 return Value;
295}
296
297llvm::Value *
298CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlssonbb7e17b2010-01-31 01:36:53 +0000299 const CXXRecordDecl *DerivedClass,
Anders Carlssona04efdf2010-04-24 21:23:59 +0000300 const CXXBaseSpecifierArray &BasePath,
Anders Carlssona3697c92009-11-23 17:57:54 +0000301 bool NullCheckValue) {
Anders Carlssona04efdf2010-04-24 21:23:59 +0000302 assert(!BasePath.empty() && "Base path should not be empty!");
303
Anders Carlssona3697c92009-11-23 17:57:54 +0000304 QualType DerivedTy =
305 getContext().getCanonicalType(
Anders Carlssonbb7e17b2010-01-31 01:36:53 +0000306 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(DerivedClass)));
Anders Carlssona3697c92009-11-23 17:57:54 +0000307 const llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
308
Anders Carlssona552ea72010-01-31 01:43:37 +0000309 llvm::Value *NonVirtualOffset =
Anders Carlssona04efdf2010-04-24 21:23:59 +0000310 CGM.GetNonVirtualBaseClassOffset(DerivedClass, BasePath);
Anders Carlssona552ea72010-01-31 01:43:37 +0000311
312 if (!NonVirtualOffset) {
313 // No offset, we can just cast back.
314 return Builder.CreateBitCast(Value, DerivedPtrTy);
315 }
316
Anders Carlssona3697c92009-11-23 17:57:54 +0000317 llvm::BasicBlock *CastNull = 0;
318 llvm::BasicBlock *CastNotNull = 0;
319 llvm::BasicBlock *CastEnd = 0;
320
321 if (NullCheckValue) {
322 CastNull = createBasicBlock("cast.null");
323 CastNotNull = createBasicBlock("cast.notnull");
324 CastEnd = createBasicBlock("cast.end");
325
326 llvm::Value *IsNull =
327 Builder.CreateICmpEQ(Value,
328 llvm::Constant::getNullValue(Value->getType()));
329 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
330 EmitBlock(CastNotNull);
331 }
332
Anders Carlssona552ea72010-01-31 01:43:37 +0000333 // Apply the offset.
334 Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
335 Value = Builder.CreateSub(Value, NonVirtualOffset);
336 Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
337
338 // Just cast.
339 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000340
341 if (NullCheckValue) {
342 Builder.CreateBr(CastEnd);
343 EmitBlock(CastNull);
344 Builder.CreateBr(CastEnd);
345 EmitBlock(CastEnd);
346
347 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
348 PHI->reserveOperandSpace(2);
349 PHI->addIncoming(Value, CastNotNull);
350 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
351 CastNull);
352 Value = PHI;
353 }
354
355 return Value;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000356}
Anders Carlsson607d0372009-12-24 22:46:43 +0000357
Anders Carlsson21c9ad92010-03-30 03:27:09 +0000358/// EmitCopyCtorCall - Emit a call to a copy constructor.
359static void
360EmitCopyCtorCall(CodeGenFunction &CGF,
361 const CXXConstructorDecl *CopyCtor, CXXCtorType CopyCtorType,
362 llvm::Value *ThisPtr, llvm::Value *VTT, llvm::Value *Src) {
363 llvm::Value *Callee = CGF.CGM.GetAddrOfCXXConstructor(CopyCtor, CopyCtorType);
364
365 CallArgList CallArgs;
366
367 // Push the this ptr.
368 CallArgs.push_back(std::make_pair(RValue::get(ThisPtr),
369 CopyCtor->getThisType(CGF.getContext())));
370
371 // Push the VTT parameter if necessary.
372 if (VTT) {
373 QualType T = CGF.getContext().getPointerType(CGF.getContext().VoidPtrTy);
374 CallArgs.push_back(std::make_pair(RValue::get(VTT), T));
375 }
376
377 // Push the Src ptr.
378 CallArgs.push_back(std::make_pair(RValue::get(Src),
379 CopyCtor->getParamDecl(0)->getType()));
380
381
382 {
383 CodeGenFunction::CXXTemporariesCleanupScope Scope(CGF);
384
385 // If the copy constructor has default arguments, emit them.
386 for (unsigned I = 1, E = CopyCtor->getNumParams(); I < E; ++I) {
387 const ParmVarDecl *Param = CopyCtor->getParamDecl(I);
388 const Expr *DefaultArgExpr = Param->getDefaultArg();
389
390 assert(DefaultArgExpr && "Ctor parameter must have default arg!");
391
392 QualType ArgType = Param->getType();
393 CallArgs.push_back(std::make_pair(CGF.EmitCallArg(DefaultArgExpr,
394 ArgType),
395 ArgType));
396 }
397
398 const FunctionProtoType *FPT =
399 CopyCtor->getType()->getAs<FunctionProtoType>();
400 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(CallArgs, FPT),
401 Callee, ReturnValueSlot(), CallArgs, CopyCtor);
402 }
403}
404
Anders Carlsson607d0372009-12-24 22:46:43 +0000405/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
406/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
407/// copy or via a copy constructor call.
408// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
409void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
410 llvm::Value *Src,
411 const ArrayType *Array,
412 const CXXRecordDecl *BaseClassDecl,
413 QualType Ty) {
414 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
415 assert(CA && "VLA cannot be copied over");
416 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
417
418 // Create a temporary for the loop index and initialize it with 0.
419 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
420 "loop.index");
421 llvm::Value* zeroConstant =
422 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
423 Builder.CreateStore(zeroConstant, IndexPtr);
424 // Start the loop with a block that tests the condition.
425 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
426 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
427
428 EmitBlock(CondBlock);
429
430 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
431 // Generate: if (loop-index < number-of-elements fall to the loop body,
432 // otherwise, go to the block after the for-loop.
433 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
434 llvm::Value * NumElementsPtr =
435 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
436 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
437 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
438 "isless");
439 // If the condition is true, execute the body.
440 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
441
442 EmitBlock(ForBody);
443 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
444 // Inside the loop body, emit the constructor call on the array element.
445 Counter = Builder.CreateLoad(IndexPtr);
446 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
447 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
448 if (BitwiseCopy)
449 EmitAggregateCopy(Dest, Src, Ty);
450 else if (CXXConstructorDecl *BaseCopyCtor =
Anders Carlsson8887bdc2010-03-30 03:30:08 +0000451 BaseClassDecl->getCopyConstructor(getContext(), 0))
452 EmitCopyCtorCall(*this, BaseCopyCtor, Ctor_Complete, Dest, 0, Src);
Anders Carlsson607d0372009-12-24 22:46:43 +0000453
Anders Carlsson607d0372009-12-24 22:46:43 +0000454 EmitBlock(ContinueBlock);
455
456 // Emit the increment of the loop counter.
457 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
458 Counter = Builder.CreateLoad(IndexPtr);
459 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
460 Builder.CreateStore(NextVal, IndexPtr);
461
462 // Finally, branch back up to the condition for the next iteration.
463 EmitBranch(CondBlock);
464
465 // Emit the fall-through block.
466 EmitBlock(AfterFor, true);
467}
468
469/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
470/// array of objects from SrcValue to DestValue. Assignment can be either a
471/// bitwise assignment or via a copy assignment operator function call.
472/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
473void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
474 llvm::Value *Src,
475 const ArrayType *Array,
476 const CXXRecordDecl *BaseClassDecl,
477 QualType Ty) {
478 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
479 assert(CA && "VLA cannot be asssigned");
480 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
481
482 // Create a temporary for the loop index and initialize it with 0.
483 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
484 "loop.index");
485 llvm::Value* zeroConstant =
486 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
487 Builder.CreateStore(zeroConstant, IndexPtr);
488 // Start the loop with a block that tests the condition.
489 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
490 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
491
492 EmitBlock(CondBlock);
493
494 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
495 // Generate: if (loop-index < number-of-elements fall to the loop body,
496 // otherwise, go to the block after the for-loop.
497 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
498 llvm::Value * NumElementsPtr =
499 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
500 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
501 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
502 "isless");
503 // If the condition is true, execute the body.
504 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
505
506 EmitBlock(ForBody);
507 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
508 // Inside the loop body, emit the assignment operator call on array element.
509 Counter = Builder.CreateLoad(IndexPtr);
510 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
511 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
512 const CXXMethodDecl *MD = 0;
513 if (BitwiseAssign)
514 EmitAggregateCopy(Dest, Src, Ty);
515 else {
Eli Friedman8a850ba2010-01-15 20:06:11 +0000516 BaseClassDecl->hasConstCopyAssignment(getContext(), MD);
517 assert(MD && "EmitClassAggrCopyAssignment - No user assign");
Anders Carlsson607d0372009-12-24 22:46:43 +0000518 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
519 const llvm::Type *LTy =
520 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
521 FPT->isVariadic());
522 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
523
524 CallArgList CallArgs;
525 // Push the this (Dest) ptr.
526 CallArgs.push_back(std::make_pair(RValue::get(Dest),
527 MD->getThisType(getContext())));
528
529 // Push the Src ptr.
Eli Friedman8a850ba2010-01-15 20:06:11 +0000530 QualType SrcTy = MD->getParamDecl(0)->getType();
531 RValue SrcValue = SrcTy->isReferenceType() ? RValue::get(Src) :
532 RValue::getAggregate(Src);
533 CallArgs.push_back(std::make_pair(SrcValue, SrcTy));
John McCall04a67a62010-02-05 21:31:56 +0000534 EmitCall(CGM.getTypes().getFunctionInfo(CallArgs, FPT),
Anders Carlsson607d0372009-12-24 22:46:43 +0000535 Callee, ReturnValueSlot(), CallArgs, MD);
536 }
537 EmitBlock(ContinueBlock);
538
539 // Emit the increment of the loop counter.
540 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
541 Counter = Builder.CreateLoad(IndexPtr);
542 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
543 Builder.CreateStore(NextVal, IndexPtr);
544
545 // Finally, branch back up to the condition for the next iteration.
546 EmitBranch(CondBlock);
547
548 // Emit the fall-through block.
549 EmitBlock(AfterFor, true);
550}
551
Anders Carlssonc997d422010-01-02 01:01:18 +0000552/// GetVTTParameter - Return the VTT parameter that should be passed to a
553/// base constructor/destructor with virtual bases.
554static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000555 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000556 // This constructor/destructor does not need a VTT parameter.
557 return 0;
558 }
559
560 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
561 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000562
Anders Carlssonc997d422010-01-02 01:01:18 +0000563 llvm::Value *VTT;
564
John McCall3b477332010-02-18 19:59:28 +0000565 uint64_t SubVTTIndex;
566
567 // If the record matches the base, this is the complete ctor/dtor
568 // variant calling the base variant in a class with virtual bases.
569 if (RD == Base) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000570 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000571 "doing no-op VTT offset in base dtor/ctor?");
572 SubVTTIndex = 0;
573 } else {
Anders Carlssonaf440352010-03-23 04:11:45 +0000574 SubVTTIndex = CGF.CGM.getVTables().getSubVTTIndex(RD, Base);
John McCall3b477332010-02-18 19:59:28 +0000575 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
576 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000577
Anders Carlssonaf440352010-03-23 04:11:45 +0000578 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000579 // A VTT parameter was passed to the constructor, use it.
580 VTT = CGF.LoadCXXVTT();
581 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
582 } else {
583 // We're the complete constructor, so get the VTT by name.
Anders Carlssonaf440352010-03-23 04:11:45 +0000584 VTT = CGF.CGM.getVTables().getVTT(RD);
Anders Carlssonc997d422010-01-02 01:01:18 +0000585 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
586 }
587
588 return VTT;
589}
590
591
Anders Carlsson607d0372009-12-24 22:46:43 +0000592/// EmitClassMemberwiseCopy - This routine generates code to copy a class
Anders Carlsson6444c412010-04-24 22:36:50 +0000593/// object from SrcValue to DestValue.
594void CodeGenFunction::EmitClassMemberwiseCopy(llvm::Value *Dest,
595 llvm::Value *Src,
596 const CXXRecordDecl *ClassDecl) {
597 if (ClassDecl->hasTrivialCopyConstructor()) {
598 EmitAggregateCopy(Dest, Src, getContext().getTagDeclType(ClassDecl));
599 return;
600 }
601
602 // FIXME: Does this get the right copy constructor?
603 const CXXConstructorDecl *CopyConstructor =
604 ClassDecl->getCopyConstructor(getContext(), 0);
605 assert(CopyConstructor && "Did not find copy constructor!");
Anders Carlssonc997d422010-01-02 01:01:18 +0000606
Anders Carlsson6444c412010-04-24 22:36:50 +0000607 EmitCopyCtorCall(*this, CopyConstructor, Ctor_Complete, Dest, 0, Src);
Anders Carlsson607d0372009-12-24 22:46:43 +0000608}
609
610/// EmitClassCopyAssignment - This routine generates code to copy assign a class
611/// object from SrcValue to DestValue. Assignment can be either a bitwise
612/// assignment of via an assignment operator call.
613// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
614void CodeGenFunction::EmitClassCopyAssignment(
615 llvm::Value *Dest, llvm::Value *Src,
616 const CXXRecordDecl *ClassDecl,
617 const CXXRecordDecl *BaseClassDecl,
618 QualType Ty) {
619 if (ClassDecl) {
Anders Carlssona88ad562010-04-24 21:51:08 +0000620 Dest = OldGetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl);
621 Src = OldGetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl);
Anders Carlsson607d0372009-12-24 22:46:43 +0000622 }
623 if (BaseClassDecl->hasTrivialCopyAssignment()) {
624 EmitAggregateCopy(Dest, Src, Ty);
625 return;
626 }
627
628 const CXXMethodDecl *MD = 0;
Eli Friedman8a850ba2010-01-15 20:06:11 +0000629 BaseClassDecl->hasConstCopyAssignment(getContext(), MD);
630 assert(MD && "EmitClassCopyAssignment - missing copy assign");
Anders Carlsson607d0372009-12-24 22:46:43 +0000631
632 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
633 const llvm::Type *LTy =
634 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
635 FPT->isVariadic());
636 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
637
638 CallArgList CallArgs;
639 // Push the this (Dest) ptr.
640 CallArgs.push_back(std::make_pair(RValue::get(Dest),
641 MD->getThisType(getContext())));
642
643 // Push the Src ptr.
Eli Friedman8a850ba2010-01-15 20:06:11 +0000644 QualType SrcTy = MD->getParamDecl(0)->getType();
645 RValue SrcValue = SrcTy->isReferenceType() ? RValue::get(Src) :
646 RValue::getAggregate(Src);
647 CallArgs.push_back(std::make_pair(SrcValue, SrcTy));
John McCall04a67a62010-02-05 21:31:56 +0000648 EmitCall(CGM.getTypes().getFunctionInfo(CallArgs, FPT),
Anders Carlsson607d0372009-12-24 22:46:43 +0000649 Callee, ReturnValueSlot(), CallArgs, MD);
650}
651
Anders Carlsson607d0372009-12-24 22:46:43 +0000652/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a
653/// copy constructor, in accordance with section 12.8 (p7 and p8) of C++03
654/// The implicitly-defined copy constructor for class X performs a memberwise
655/// copy of its subobjects. The order of copying is the same as the order of
656/// initialization of bases and members in a user-defined constructor
657/// Each subobject is copied in the manner appropriate to its type:
658/// if the subobject is of class type, the copy constructor for the class is
659/// used;
660/// if the subobject is an array, each element is copied, in the manner
661/// appropriate to the element type;
662/// if the subobject is of scalar type, the built-in assignment operator is
663/// used.
664/// Virtual base class subobjects shall be copied only once by the
665/// implicitly-defined copy constructor
666
667void
John McCall9fc6a772010-02-19 09:25:03 +0000668CodeGenFunction::SynthesizeCXXCopyConstructor(const FunctionArgList &Args) {
669 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
Anders Carlsson607d0372009-12-24 22:46:43 +0000670 const CXXRecordDecl *ClassDecl = Ctor->getParent();
671 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
672 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
673 assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
Anders Carlsson607d0372009-12-24 22:46:43 +0000674
675 FunctionArgList::const_iterator i = Args.begin();
676 const VarDecl *ThisArg = i->first;
677 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
678 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
679 const VarDecl *SrcArg = (i+1)->first;
680 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
681 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
682
Anders Carlsson607d0372009-12-24 22:46:43 +0000683 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
684 E = ClassDecl->field_end(); I != E; ++I) {
685 const FieldDecl *Field = *I;
686
687 QualType FieldType = getContext().getCanonicalType(Field->getType());
688 const ConstantArrayType *Array =
689 getContext().getAsConstantArrayType(FieldType);
690 if (Array)
691 FieldType = getContext().getBaseElementType(FieldType);
692
693 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
694 CXXRecordDecl *FieldClassDecl
695 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Anders Carlssone6d2a532010-01-29 05:05:36 +0000696 LValue LHS = EmitLValueForField(LoadOfThis, Field, 0);
697 LValue RHS = EmitLValueForField(LoadOfSrc, Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000698 if (Array) {
699 const llvm::Type *BasePtr = ConvertType(FieldType);
700 BasePtr = llvm::PointerType::getUnqual(BasePtr);
701 llvm::Value *DestBaseAddrPtr =
702 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
703 llvm::Value *SrcBaseAddrPtr =
704 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
705 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
706 FieldClassDecl, FieldType);
707 }
708 else
709 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
Anders Carlsson6444c412010-04-24 22:36:50 +0000710 FieldClassDecl);
Anders Carlsson607d0372009-12-24 22:46:43 +0000711 continue;
712 }
713
Anders Carlsson607d0372009-12-24 22:46:43 +0000714 // Do a built-in assignment of scalar data members.
Anders Carlsson9cfe0ec2010-01-29 05:41:25 +0000715 LValue LHS = EmitLValueForFieldInitialization(LoadOfThis, Field, 0);
716 LValue RHS = EmitLValueForFieldInitialization(LoadOfSrc, Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000717
718 if (!hasAggregateLLVMType(Field->getType())) {
719 RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
720 EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
721 } else if (Field->getType()->isAnyComplexType()) {
722 ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
723 RHS.isVolatileQualified());
724 StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
725 } else {
726 EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
727 }
728 }
729
Anders Carlsson603d6d12010-03-28 21:07:49 +0000730 InitializeVTablePointers(ClassDecl);
Anders Carlsson607d0372009-12-24 22:46:43 +0000731}
732
733/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
734/// Before the implicitly-declared copy assignment operator for a class is
735/// implicitly defined, all implicitly- declared copy assignment operators for
736/// its direct base classes and its nonstatic data members shall have been
737/// implicitly defined. [12.8-p12]
738/// The implicitly-defined copy assignment operator for class X performs
739/// memberwise assignment of its subob- jects. The direct base classes of X are
740/// assigned first, in the order of their declaration in
741/// the base-specifier-list, and then the immediate nonstatic data members of X
742/// are assigned, in the order in which they were declared in the class
743/// definition.Each subobject is assigned in the manner appropriate to its type:
744/// if the subobject is of class type, the copy assignment operator for the
745/// class is used (as if by explicit qualification; that is, ignoring any
746/// possible virtual overriding functions in more derived classes);
747///
748/// if the subobject is an array, each element is assigned, in the manner
749/// appropriate to the element type;
750///
751/// if the subobject is of scalar type, the built-in assignment operator is
752/// used.
John McCall9fc6a772010-02-19 09:25:03 +0000753void CodeGenFunction::SynthesizeCXXCopyAssignment(const FunctionArgList &Args) {
754 const CXXMethodDecl *CD = cast<CXXMethodDecl>(CurGD.getDecl());
Anders Carlsson607d0372009-12-24 22:46:43 +0000755 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
756 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
757 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Anders Carlsson607d0372009-12-24 22:46:43 +0000758
759 FunctionArgList::const_iterator i = Args.begin();
760 const VarDecl *ThisArg = i->first;
761 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
762 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
763 const VarDecl *SrcArg = (i+1)->first;
764 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
765 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
766
767 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
768 Base != ClassDecl->bases_end(); ++Base) {
769 // FIXME. copy assignment of virtual base NYI
770 if (Base->isVirtual())
771 continue;
772
773 CXXRecordDecl *BaseClassDecl
774 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
775 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
776 Base->getType());
777 }
778
779 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
780 FieldEnd = ClassDecl->field_end();
781 Field != FieldEnd; ++Field) {
782 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
783 const ConstantArrayType *Array =
784 getContext().getAsConstantArrayType(FieldType);
785 if (Array)
786 FieldType = getContext().getBaseElementType(FieldType);
787
788 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
789 CXXRecordDecl *FieldClassDecl
790 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Anders Carlssone6d2a532010-01-29 05:05:36 +0000791 LValue LHS = EmitLValueForField(LoadOfThis, *Field, 0);
792 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000793 if (Array) {
794 const llvm::Type *BasePtr = ConvertType(FieldType);
795 BasePtr = llvm::PointerType::getUnqual(BasePtr);
796 llvm::Value *DestBaseAddrPtr =
797 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
798 llvm::Value *SrcBaseAddrPtr =
799 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
800 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
801 FieldClassDecl, FieldType);
802 }
803 else
804 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
805 0 /*ClassDecl*/, FieldClassDecl, FieldType);
806 continue;
807 }
808 // Do a built-in assignment of scalar data members.
Anders Carlssone6d2a532010-01-29 05:05:36 +0000809 LValue LHS = EmitLValueForField(LoadOfThis, *Field, 0);
810 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000811 if (!hasAggregateLLVMType(Field->getType())) {
812 RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
813 EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
814 } else if (Field->getType()->isAnyComplexType()) {
815 ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
816 RHS.isVolatileQualified());
817 StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
818 } else {
819 EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
820 }
821 }
822
823 // return *this;
824 Builder.CreateStore(LoadOfThis, ReturnValue);
Anders Carlsson607d0372009-12-24 22:46:43 +0000825}
826
827static void EmitBaseInitializer(CodeGenFunction &CGF,
828 const CXXRecordDecl *ClassDecl,
829 CXXBaseOrMemberInitializer *BaseInit,
830 CXXCtorType CtorType) {
831 assert(BaseInit->isBaseInitializer() &&
832 "Must have base initializer!");
833
834 llvm::Value *ThisPtr = CGF.LoadCXXThis();
835
836 const Type *BaseType = BaseInit->getBaseClass();
837 CXXRecordDecl *BaseClassDecl =
838 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
839
Anders Carlsson80638c52010-04-12 00:51:03 +0000840 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000841
842 // The base constructor doesn't construct virtual bases.
843 if (CtorType == Ctor_Base && isBaseVirtual)
844 return;
845
John McCallbff225e2010-02-16 04:15:37 +0000846 // We can pretend to be a complete class because it only matters for
847 // virtual bases, and we only do virtual bases for complete ctors.
848 llvm::Value *V = ThisPtr;
849 V = CGF.GetAddressOfBaseOfCompleteClass(V, isBaseVirtual,
850 ClassDecl, BaseClassDecl);
851
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000852 CGF.EmitAggExpr(BaseInit->getInit(), V, false, false, true);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000853
854 if (CGF.Exceptions && !BaseClassDecl->hasTrivialDestructor()) {
855 // FIXME: Is this OK for C++0x delegating constructors?
856 CodeGenFunction::EHCleanupBlock Cleanup(CGF);
857
Anders Carlsson594d5e82010-02-06 20:00:21 +0000858 CXXDestructorDecl *DD = BaseClassDecl->getDestructor(CGF.getContext());
859 CGF.EmitCXXDestructorCall(DD, Dtor_Base, V);
860 }
Anders Carlsson607d0372009-12-24 22:46:43 +0000861}
862
863static void EmitMemberInitializer(CodeGenFunction &CGF,
864 const CXXRecordDecl *ClassDecl,
865 CXXBaseOrMemberInitializer *MemberInit) {
866 assert(MemberInit->isMemberInitializer() &&
867 "Must have member initializer!");
868
869 // non-static data member initializers.
870 FieldDecl *Field = MemberInit->getMember();
871 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
872
873 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Anders Carlsson06a29702010-01-29 05:24:29 +0000874 LValue LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
875
Anders Carlsson607d0372009-12-24 22:46:43 +0000876 // If we are initializing an anonymous union field, drill down to the field.
877 if (MemberInit->getAnonUnionMember()) {
878 Field = MemberInit->getAnonUnionMember();
Anders Carlssone6d2a532010-01-29 05:05:36 +0000879 LHS = CGF.EmitLValueForField(LHS.getAddress(), Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000880 FieldType = Field->getType();
881 }
882
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000883 // FIXME: If there's no initializer and the CXXBaseOrMemberInitializer
884 // was implicitly generated, we shouldn't be zeroing memory.
Anders Carlsson607d0372009-12-24 22:46:43 +0000885 RValue RHS;
886 if (FieldType->isReferenceType()) {
Anders Carlssona64a8692010-02-03 16:38:03 +0000887 RHS = CGF.EmitReferenceBindingToExpr(MemberInit->getInit(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000888 /*IsInitializer=*/true);
Anders Carlsson607d0372009-12-24 22:46:43 +0000889 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Eli Friedman3bb94122010-01-31 19:07:50 +0000890 } else if (FieldType->isArrayType() && !MemberInit->getInit()) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000891 CGF.EmitMemSetToZero(LHS.getAddress(), Field->getType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000892 } else if (!CGF.hasAggregateLLVMType(Field->getType())) {
893 RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit(), true));
Anders Carlsson607d0372009-12-24 22:46:43 +0000894 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000895 } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
896 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
Anders Carlsson607d0372009-12-24 22:46:43 +0000897 LHS.isVolatileQualified());
898 } else {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000899 CGF.EmitAggExpr(MemberInit->getInit(), LHS.getAddress(),
900 LHS.isVolatileQualified(), false, true);
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000901
902 if (!CGF.Exceptions)
903 return;
904
905 const RecordType *RT = FieldType->getAs<RecordType>();
906 if (!RT)
907 return;
908
909 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
910 if (!RD->hasTrivialDestructor()) {
911 // FIXME: Is this OK for C++0x delegating constructors?
912 CodeGenFunction::EHCleanupBlock Cleanup(CGF);
913
914 llvm::Value *ThisPtr = CGF.LoadCXXThis();
915 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0);
916
917 CXXDestructorDecl *DD = RD->getDestructor(CGF.getContext());
918 CGF.EmitCXXDestructorCall(DD, Dtor_Complete, LHS.getAddress());
919 }
Anders Carlsson607d0372009-12-24 22:46:43 +0000920 }
921}
922
John McCallc0bf4622010-02-23 00:48:20 +0000923/// Checks whether the given constructor is a valid subject for the
924/// complete-to-base constructor delegation optimization, i.e.
925/// emitting the complete constructor as a simple call to the base
926/// constructor.
927static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
928
929 // Currently we disable the optimization for classes with virtual
930 // bases because (1) the addresses of parameter variables need to be
931 // consistent across all initializers but (2) the delegate function
932 // call necessarily creates a second copy of the parameter variable.
933 //
934 // The limiting example (purely theoretical AFAIK):
935 // struct A { A(int &c) { c++; } };
936 // struct B : virtual A {
937 // B(int count) : A(count) { printf("%d\n", count); }
938 // };
939 // ...although even this example could in principle be emitted as a
940 // delegation since the address of the parameter doesn't escape.
941 if (Ctor->getParent()->getNumVBases()) {
942 // TODO: white-list trivial vbase initializers. This case wouldn't
943 // be subject to the restrictions below.
944
945 // TODO: white-list cases where:
946 // - there are no non-reference parameters to the constructor
947 // - the initializers don't access any non-reference parameters
948 // - the initializers don't take the address of non-reference
949 // parameters
950 // - etc.
951 // If we ever add any of the above cases, remember that:
952 // - function-try-blocks will always blacklist this optimization
953 // - we need to perform the constructor prologue and cleanup in
954 // EmitConstructorBody.
955
956 return false;
957 }
958
959 // We also disable the optimization for variadic functions because
960 // it's impossible to "re-pass" varargs.
961 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
962 return false;
963
964 return true;
965}
966
John McCall9fc6a772010-02-19 09:25:03 +0000967/// EmitConstructorBody - Emits the body of the current constructor.
968void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
969 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
970 CXXCtorType CtorType = CurGD.getCtorType();
971
John McCallc0bf4622010-02-23 00:48:20 +0000972 // Before we go any further, try the complete->base constructor
973 // delegation optimization.
974 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
975 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
976 return;
977 }
978
John McCall9fc6a772010-02-19 09:25:03 +0000979 Stmt *Body = Ctor->getBody();
980
John McCallc0bf4622010-02-23 00:48:20 +0000981 // Enter the function-try-block before the constructor prologue if
982 // applicable.
John McCall9fc6a772010-02-19 09:25:03 +0000983 CXXTryStmtInfo TryInfo;
John McCallc0bf4622010-02-23 00:48:20 +0000984 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
985
986 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000987 TryInfo = EnterCXXTryStmt(*cast<CXXTryStmt>(Body));
988
989 unsigned CleanupStackSize = CleanupEntries.size();
990
John McCallc0bf4622010-02-23 00:48:20 +0000991 // Emit the constructor prologue, i.e. the base and member
992 // initializers.
John McCall9fc6a772010-02-19 09:25:03 +0000993 EmitCtorPrologue(Ctor, CtorType);
994
995 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000996 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000997 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
998 else if (Body)
999 EmitStmt(Body);
1000 else {
1001 assert(Ctor->isImplicit() && "bodyless ctor not implicit");
1002 if (!Ctor->isDefaultConstructor()) {
1003 assert(Ctor->isCopyConstructor());
1004 SynthesizeCXXCopyConstructor(Args);
1005 }
1006 }
1007
1008 // Emit any cleanup blocks associated with the member or base
1009 // initializers, which includes (along the exceptional path) the
1010 // destructors for those members and bases that were fully
1011 // constructed.
1012 EmitCleanupBlocks(CleanupStackSize);
1013
John McCallc0bf4622010-02-23 00:48:20 +00001014 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +00001015 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), TryInfo);
1016}
1017
Anders Carlsson607d0372009-12-24 22:46:43 +00001018/// EmitCtorPrologue - This routine generates necessary code to initialize
1019/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +00001020void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1021 CXXCtorType CtorType) {
1022 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001023
1024 llvm::SmallVector<CXXBaseOrMemberInitializer *, 8> MemberInitializers;
Anders Carlsson607d0372009-12-24 22:46:43 +00001025
Anders Carlsson607d0372009-12-24 22:46:43 +00001026 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1027 E = CD->init_end();
1028 B != E; ++B) {
1029 CXXBaseOrMemberInitializer *Member = (*B);
1030
1031 assert(LiveTemporaries.empty() &&
1032 "Should not have any live temporaries at initializer start!");
1033
1034 if (Member->isBaseInitializer())
1035 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
1036 else
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001037 MemberInitializers.push_back(Member);
Anders Carlsson607d0372009-12-24 22:46:43 +00001038 }
1039
Anders Carlsson603d6d12010-03-28 21:07:49 +00001040 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001041
1042 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I) {
1043 assert(LiveTemporaries.empty() &&
1044 "Should not have any live temporaries at initializer start!");
1045
1046 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I]);
1047 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001048}
1049
John McCall9fc6a772010-02-19 09:25:03 +00001050/// EmitDestructorBody - Emits the body of the current destructor.
1051void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1052 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1053 CXXDtorType DtorType = CurGD.getDtorType();
1054
1055 Stmt *Body = Dtor->getBody();
1056
1057 // If the body is a function-try-block, enter the try before
1058 // anything else --- unless we're in a deleting destructor, in which
1059 // case we're just going to call the complete destructor and then
1060 // call operator delete() on the way out.
1061 CXXTryStmtInfo TryInfo;
1062 bool isTryBody = (DtorType != Dtor_Deleting &&
1063 Body && isa<CXXTryStmt>(Body));
1064 if (isTryBody)
1065 TryInfo = EnterCXXTryStmt(*cast<CXXTryStmt>(Body));
1066
1067 llvm::BasicBlock *DtorEpilogue = createBasicBlock("dtor.epilogue");
1068 PushCleanupBlock(DtorEpilogue);
1069
1070 bool SkipBody = false; // should get jump-threaded
1071
1072 // If this is the deleting variant, just invoke the complete
1073 // variant, then call the appropriate operator delete() on the way
1074 // out.
1075 if (DtorType == Dtor_Deleting) {
1076 EmitCXXDestructorCall(Dtor, Dtor_Complete, LoadCXXThis());
1077 SkipBody = true;
1078
1079 // If this is the complete variant, just invoke the base variant;
1080 // the epilogue will destruct the virtual bases. But we can't do
1081 // this optimization if the body is a function-try-block, because
1082 // we'd introduce *two* handler blocks.
1083 } else if (!isTryBody && DtorType == Dtor_Complete) {
1084 EmitCXXDestructorCall(Dtor, Dtor_Base, LoadCXXThis());
1085 SkipBody = true;
1086
1087 // Otherwise, we're in the base variant, so we need to ensure the
1088 // vtable ptrs are right before emitting the body.
1089 } else {
Anders Carlsson603d6d12010-03-28 21:07:49 +00001090 InitializeVTablePointers(Dtor->getParent());
John McCall9fc6a772010-02-19 09:25:03 +00001091 }
1092
1093 // Emit the body of the statement.
1094 if (SkipBody)
1095 (void) 0;
1096 else if (isTryBody)
1097 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1098 else if (Body)
1099 EmitStmt(Body);
1100 else {
1101 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1102 // nothing to do besides what's in the epilogue
1103 }
1104
1105 // Jump to the cleanup block.
1106 CleanupBlockInfo Info = PopCleanupBlock();
1107 assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
1108 EmitBlock(DtorEpilogue);
1109
1110 // Emit the destructor epilogue now. If this is a complete
1111 // destructor with a function-try-block, perform the base epilogue
1112 // as well.
1113 if (isTryBody && DtorType == Dtor_Complete)
1114 EmitDtorEpilogue(Dtor, Dtor_Base);
1115 EmitDtorEpilogue(Dtor, DtorType);
1116
1117 // Link up the cleanup information.
1118 if (Info.SwitchBlock)
1119 EmitBlock(Info.SwitchBlock);
1120 if (Info.EndBlock)
1121 EmitBlock(Info.EndBlock);
1122
1123 // Exit the try if applicable.
1124 if (isTryBody)
1125 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), TryInfo);
1126}
1127
Anders Carlsson607d0372009-12-24 22:46:43 +00001128/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1129/// destructor. This is to call destructors on members and base classes
1130/// in reverse order of their construction.
Anders Carlsson607d0372009-12-24 22:46:43 +00001131void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD,
1132 CXXDtorType DtorType) {
1133 assert(!DD->isTrivial() &&
1134 "Should not emit dtor epilogue for trivial dtor!");
1135
1136 const CXXRecordDecl *ClassDecl = DD->getParent();
1137
John McCall3b477332010-02-18 19:59:28 +00001138 // In a deleting destructor, we've already called the complete
1139 // destructor as a subroutine, so we just have to delete the
1140 // appropriate value.
1141 if (DtorType == Dtor_Deleting) {
1142 assert(DD->getOperatorDelete() &&
1143 "operator delete missing - EmitDtorEpilogue");
1144 EmitDeleteCall(DD->getOperatorDelete(), LoadCXXThis(),
1145 getContext().getTagDeclType(ClassDecl));
1146 return;
1147 }
1148
1149 // For complete destructors, we've already called the base
1150 // destructor (in GenerateBody), so we just need to destruct all the
1151 // virtual bases.
1152 if (DtorType == Dtor_Complete) {
1153 // Handle virtual bases.
1154 for (CXXRecordDecl::reverse_base_class_const_iterator I =
1155 ClassDecl->vbases_rbegin(), E = ClassDecl->vbases_rend();
1156 I != E; ++I) {
1157 const CXXBaseSpecifier &Base = *I;
1158 CXXRecordDecl *BaseClassDecl
1159 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1160
1161 // Ignore trivial destructors.
1162 if (BaseClassDecl->hasTrivialDestructor())
1163 continue;
1164 const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1165 llvm::Value *V = GetAddressOfBaseOfCompleteClass(LoadCXXThis(),
1166 true,
1167 ClassDecl,
1168 BaseClassDecl);
1169 EmitCXXDestructorCall(D, Dtor_Base, V);
1170 }
1171 return;
1172 }
1173
1174 assert(DtorType == Dtor_Base);
1175
Anders Carlsson607d0372009-12-24 22:46:43 +00001176 // Collect the fields.
1177 llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
1178 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1179 E = ClassDecl->field_end(); I != E; ++I) {
1180 const FieldDecl *Field = *I;
1181
1182 QualType FieldType = getContext().getCanonicalType(Field->getType());
1183 FieldType = getContext().getBaseElementType(FieldType);
1184
1185 const RecordType *RT = FieldType->getAs<RecordType>();
1186 if (!RT)
1187 continue;
1188
1189 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1190 if (FieldClassDecl->hasTrivialDestructor())
1191 continue;
1192
1193 FieldDecls.push_back(Field);
1194 }
1195
1196 // Now destroy the fields.
1197 for (size_t i = FieldDecls.size(); i > 0; --i) {
1198 const FieldDecl *Field = FieldDecls[i - 1];
1199
1200 QualType FieldType = Field->getType();
1201 const ConstantArrayType *Array =
1202 getContext().getAsConstantArrayType(FieldType);
1203 if (Array)
1204 FieldType = getContext().getBaseElementType(FieldType);
1205
1206 const RecordType *RT = FieldType->getAs<RecordType>();
1207 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1208
1209 llvm::Value *ThisPtr = LoadCXXThis();
1210
1211 LValue LHS = EmitLValueForField(ThisPtr, Field,
Anders Carlsson607d0372009-12-24 22:46:43 +00001212 // FIXME: Qualifiers?
1213 /*CVRQualifiers=*/0);
1214 if (Array) {
1215 const llvm::Type *BasePtr = ConvertType(FieldType);
1216 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1217 llvm::Value *BaseAddrPtr =
1218 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1219 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1220 Array, BaseAddrPtr);
1221 } else
1222 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1223 Dtor_Complete, LHS.getAddress());
1224 }
1225
1226 // Destroy non-virtual bases.
1227 for (CXXRecordDecl::reverse_base_class_const_iterator I =
1228 ClassDecl->bases_rbegin(), E = ClassDecl->bases_rend(); I != E; ++I) {
1229 const CXXBaseSpecifier &Base = *I;
1230
1231 // Ignore virtual bases.
1232 if (Base.isVirtual())
1233 continue;
1234
1235 CXXRecordDecl *BaseClassDecl
1236 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1237
1238 // Ignore trivial destructors.
1239 if (BaseClassDecl->hasTrivialDestructor())
1240 continue;
1241 const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1242
Anders Carlssona88ad562010-04-24 21:51:08 +00001243 llvm::Value *V = OldGetAddressOfBaseClass(LoadCXXThis(),
1244 ClassDecl, BaseClassDecl);
Anders Carlsson607d0372009-12-24 22:46:43 +00001245 EmitCXXDestructorCall(D, Dtor_Base, V);
1246 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001247}
1248
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001249/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
1250/// for-loop to call the default constructor on individual members of the
1251/// array.
1252/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
1253/// array type and 'ArrayPtr' points to the beginning fo the array.
1254/// It is assumed that all relevant checks have been made by the caller.
1255void
1256CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1257 const ConstantArrayType *ArrayTy,
1258 llvm::Value *ArrayPtr,
1259 CallExpr::const_arg_iterator ArgBeg,
1260 CallExpr::const_arg_iterator ArgEnd) {
1261
1262 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1263 llvm::Value * NumElements =
1264 llvm::ConstantInt::get(SizeTy,
1265 getContext().getConstantArrayElementCount(ArrayTy));
1266
1267 EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd);
1268}
1269
1270void
1271CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1272 llvm::Value *NumElements,
1273 llvm::Value *ArrayPtr,
1274 CallExpr::const_arg_iterator ArgBeg,
1275 CallExpr::const_arg_iterator ArgEnd) {
1276 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1277
1278 // Create a temporary for the loop index and initialize it with 0.
1279 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
1280 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
1281 Builder.CreateStore(Zero, IndexPtr);
1282
1283 // Start the loop with a block that tests the condition.
1284 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1285 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1286
1287 EmitBlock(CondBlock);
1288
1289 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1290
1291 // Generate: if (loop-index < number-of-elements fall to the loop body,
1292 // otherwise, go to the block after the for-loop.
1293 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1294 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
1295 // If the condition is true, execute the body.
1296 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1297
1298 EmitBlock(ForBody);
1299
1300 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1301 // Inside the loop body, emit the constructor call on the array element.
1302 Counter = Builder.CreateLoad(IndexPtr);
1303 llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
1304 "arrayidx");
1305
1306 // C++ [class.temporary]p4:
1307 // There are two contexts in which temporaries are destroyed at a different
1308 // point than the end of the full-expression. The first context is when a
1309 // default constructor is called to initialize an element of an array.
1310 // If the constructor has one or more default arguments, the destruction of
1311 // every temporary created in a default argument expression is sequenced
1312 // before the construction of the next array element, if any.
1313
1314 // Keep track of the current number of live temporaries.
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001315 {
1316 CXXTemporariesCleanupScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001317
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001318 EmitCXXConstructorCall(D, Ctor_Complete, Address, ArgBeg, ArgEnd);
1319 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001320
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001321 EmitBlock(ContinueBlock);
1322
1323 // Emit the increment of the loop counter.
1324 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
1325 Counter = Builder.CreateLoad(IndexPtr);
1326 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1327 Builder.CreateStore(NextVal, IndexPtr);
1328
1329 // Finally, branch back up to the condition for the next iteration.
1330 EmitBranch(CondBlock);
1331
1332 // Emit the fall-through block.
1333 EmitBlock(AfterFor, true);
1334}
1335
1336/// EmitCXXAggrDestructorCall - calls the default destructor on array
1337/// elements in reverse order of construction.
1338void
1339CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1340 const ArrayType *Array,
1341 llvm::Value *This) {
1342 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1343 assert(CA && "Do we support VLA for destruction ?");
1344 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
1345
1346 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1347 llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
1348 EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
1349}
1350
1351/// EmitCXXAggrDestructorCall - calls the default destructor on array
1352/// elements in reverse order of construction.
1353void
1354CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1355 llvm::Value *UpperCount,
1356 llvm::Value *This) {
1357 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1358 llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
1359
1360 // Create a temporary for the loop index and initialize it with count of
1361 // array elements.
1362 llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
1363
1364 // Store the number of elements in the index pointer.
1365 Builder.CreateStore(UpperCount, IndexPtr);
1366
1367 // Start the loop with a block that tests the condition.
1368 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1369 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1370
1371 EmitBlock(CondBlock);
1372
1373 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1374
1375 // Generate: if (loop-index != 0 fall to the loop body,
1376 // otherwise, go to the block after the for-loop.
1377 llvm::Value* zeroConstant =
1378 llvm::Constant::getNullValue(SizeLTy);
1379 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1380 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
1381 "isne");
1382 // If the condition is true, execute the body.
1383 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
1384
1385 EmitBlock(ForBody);
1386
1387 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1388 // Inside the loop body, emit the constructor call on the array element.
1389 Counter = Builder.CreateLoad(IndexPtr);
1390 Counter = Builder.CreateSub(Counter, One);
1391 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
1392 EmitCXXDestructorCall(D, Dtor_Complete, Address);
1393
1394 EmitBlock(ContinueBlock);
1395
1396 // Emit the decrement of the loop counter.
1397 Counter = Builder.CreateLoad(IndexPtr);
1398 Counter = Builder.CreateSub(Counter, One, "dec");
1399 Builder.CreateStore(Counter, IndexPtr);
1400
1401 // Finally, branch back up to the condition for the next iteration.
1402 EmitBranch(CondBlock);
1403
1404 // Emit the fall-through block.
1405 EmitBlock(AfterFor, true);
1406}
1407
1408/// GenerateCXXAggrDestructorHelper - Generates a helper function which when
1409/// invoked, calls the default destructor on array elements in reverse order of
1410/// construction.
1411llvm::Constant *
1412CodeGenFunction::GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
1413 const ArrayType *Array,
1414 llvm::Value *This) {
1415 FunctionArgList Args;
1416 ImplicitParamDecl *Dst =
1417 ImplicitParamDecl::Create(getContext(), 0,
1418 SourceLocation(), 0,
1419 getContext().getPointerType(getContext().VoidTy));
1420 Args.push_back(std::make_pair(Dst, Dst->getType()));
1421
1422 llvm::SmallString<16> Name;
1423 llvm::raw_svector_ostream(Name) << "__tcf_" << (++UniqueAggrDestructorCount);
1424 QualType R = getContext().VoidTy;
John McCall04a67a62010-02-05 21:31:56 +00001425 const CGFunctionInfo &FI
Rafael Espindola264ba482010-03-30 20:24:48 +00001426 = CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001427 const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false);
1428 llvm::Function *Fn =
1429 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
1430 Name.str(),
1431 &CGM.getModule());
1432 IdentifierInfo *II = &CGM.getContext().Idents.get(Name.str());
1433 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1434 getContext().getTranslationUnitDecl(),
1435 SourceLocation(), II, R, 0,
1436 FunctionDecl::Static,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001437 FunctionDecl::None,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001438 false, true);
1439 StartFunction(FD, R, Fn, Args, SourceLocation());
1440 QualType BaseElementTy = getContext().getBaseElementType(Array);
1441 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
1442 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1443 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(This, BasePtr);
1444 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
1445 FinishFunction();
1446 llvm::Type *Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),
1447 0);
1448 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
1449 return m;
1450}
1451
Anders Carlssonc997d422010-01-02 01:01:18 +00001452
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001453void
1454CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1455 CXXCtorType Type,
1456 llvm::Value *This,
1457 CallExpr::const_arg_iterator ArgBeg,
1458 CallExpr::const_arg_iterator ArgEnd) {
John McCall8b6bbeb2010-02-06 00:25:16 +00001459 if (D->isTrivial()) {
1460 if (ArgBeg == ArgEnd) {
1461 // Trivial default constructor, no codegen required.
1462 assert(D->isDefaultConstructor() &&
1463 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001464 return;
1465 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001466
1467 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1468 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1469
John McCall8b6bbeb2010-02-06 00:25:16 +00001470 const Expr *E = (*ArgBeg);
1471 QualType Ty = E->getType();
1472 llvm::Value *Src = EmitLValue(E).getAddress();
1473 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001474 return;
1475 }
1476
Anders Carlssonc997d422010-01-02 01:01:18 +00001477 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type));
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001478 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1479
Anders Carlssonc997d422010-01-02 01:01:18 +00001480 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001481}
1482
John McCallc0bf4622010-02-23 00:48:20 +00001483void
1484CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1485 CXXCtorType CtorType,
1486 const FunctionArgList &Args) {
1487 CallArgList DelegateArgs;
1488
1489 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1490 assert(I != E && "no parameters to constructor");
1491
1492 // this
1493 DelegateArgs.push_back(std::make_pair(RValue::get(LoadCXXThis()),
1494 I->second));
1495 ++I;
1496
1497 // vtt
1498 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType))) {
1499 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
1500 DelegateArgs.push_back(std::make_pair(RValue::get(VTT), VoidPP));
1501
Anders Carlssonaf440352010-03-23 04:11:45 +00001502 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001503 assert(I != E && "cannot skip vtt parameter, already done with args");
1504 assert(I->second == VoidPP && "skipping parameter not of vtt type");
1505 ++I;
1506 }
1507 }
1508
1509 // Explicit arguments.
1510 for (; I != E; ++I) {
1511
1512 const VarDecl *Param = I->first;
1513 QualType ArgType = Param->getType(); // because we're passing it to itself
1514
1515 // StartFunction converted the ABI-lowered parameter(s) into a
1516 // local alloca. We need to turn that into an r-value suitable
1517 // for EmitCall.
1518 llvm::Value *Local = GetAddrOfLocalVar(Param);
1519 RValue Arg;
1520
1521 // For the most part, we just need to load the alloca, except:
1522 // 1) aggregate r-values are actually pointers to temporaries, and
1523 // 2) references to aggregates are pointers directly to the aggregate.
1524 // I don't know why references to non-aggregates are different here.
1525 if (ArgType->isReferenceType()) {
1526 const ReferenceType *RefType = ArgType->getAs<ReferenceType>();
1527 if (hasAggregateLLVMType(RefType->getPointeeType()))
1528 Arg = RValue::getAggregate(Local);
1529 else
1530 // Locals which are references to scalars are represented
1531 // with allocas holding the pointer.
1532 Arg = RValue::get(Builder.CreateLoad(Local));
1533 } else {
1534 if (hasAggregateLLVMType(ArgType))
1535 Arg = RValue::getAggregate(Local);
1536 else
1537 Arg = RValue::get(EmitLoadOfScalar(Local, false, ArgType));
1538 }
1539
1540 DelegateArgs.push_back(std::make_pair(Arg, ArgType));
1541 }
1542
1543 EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
1544 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1545 ReturnValueSlot(), DelegateArgs, Ctor);
1546}
1547
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001548void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1549 CXXDtorType Type,
1550 llvm::Value *This) {
Anders Carlssonc997d422010-01-02 01:01:18 +00001551 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type));
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001552 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
1553
Anders Carlssonc997d422010-01-02 01:01:18 +00001554 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001555}
1556
1557llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001558CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1559 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001560 const CXXRecordDecl *BaseClassDecl) {
1561 const llvm::Type *Int8PtrTy =
1562 llvm::Type::getInt8Ty(VMContext)->getPointerTo();
1563
1564 llvm::Value *VTablePtr = Builder.CreateBitCast(This,
1565 Int8PtrTy->getPointerTo());
1566 VTablePtr = Builder.CreateLoad(VTablePtr, "vtable");
1567
Anders Carlssonbba16072010-03-11 07:15:17 +00001568 int64_t VBaseOffsetOffset =
Anders Carlssonaf440352010-03-23 04:11:45 +00001569 CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001570
1571 llvm::Value *VBaseOffsetPtr =
Anders Carlssonbba16072010-03-11 07:15:17 +00001572 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset, "vbase.offset.ptr");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001573 const llvm::Type *PtrDiffTy =
1574 ConvertType(getContext().getPointerDiffType());
1575
1576 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1577 PtrDiffTy->getPointerTo());
1578
1579 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1580
1581 return VBaseOffset;
1582}
1583
Anders Carlssond103f9f2010-03-28 19:40:00 +00001584void
1585CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001586 const CXXRecordDecl *NearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001587 llvm::Constant *VTable,
1588 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001589 const CXXRecordDecl *RD = Base.getBase();
1590
Anders Carlssond103f9f2010-03-28 19:40:00 +00001591 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001592 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001593
Anders Carlssonc83f1062010-03-29 01:08:49 +00001594 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001595 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001596 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001597 // Get the secondary vpointer index.
1598 uint64_t VirtualPointerIndex =
1599 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1600
1601 /// Load the VTT.
1602 llvm::Value *VTT = LoadCXXVTT();
1603 if (VirtualPointerIndex)
1604 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1605
1606 // And load the address point from the VTT.
1607 VTableAddressPoint = Builder.CreateLoad(VTT);
1608 } else {
Anders Carlsson64c9eca2010-03-29 02:08:26 +00001609 uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001610 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001611 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001612 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001613
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001614 // Compute where to store the address point.
Anders Carlsson3e79c302010-04-20 18:05:10 +00001615 llvm::Value *VTableField;
1616
1617 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1618 // We need to use the virtual base offset offset because the virtual base
1619 // might have a different offset in the most derived class.
Anders Carlssona88ad562010-04-24 21:51:08 +00001620 VTableField = OldGetAddressOfBaseClass(LoadCXXThis(), VTableClass, RD);
Anders Carlsson3e79c302010-04-20 18:05:10 +00001621 } else {
1622 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001623
Anders Carlsson3e79c302010-04-20 18:05:10 +00001624 VTableField = Builder.CreateBitCast(LoadCXXThis(), Int8PtrTy);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001625 VTableField =
Anders Carlsson3e79c302010-04-20 18:05:10 +00001626 Builder.CreateConstInBoundsGEP1_64(VTableField, Base.getBaseOffset() / 8);
1627 }
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001628
Anders Carlssond103f9f2010-03-28 19:40:00 +00001629 // Finally, store the address point.
1630 const llvm::Type *AddressPointPtrTy =
1631 VTableAddressPoint->getType()->getPointerTo();
1632 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1633 Builder.CreateStore(VTableAddressPoint, VTableField);
1634}
1635
Anders Carlsson603d6d12010-03-28 21:07:49 +00001636void
1637CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001638 const CXXRecordDecl *NearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001639 bool BaseIsNonVirtualPrimaryBase,
1640 llvm::Constant *VTable,
1641 const CXXRecordDecl *VTableClass,
1642 VisitedVirtualBasesSetTy& VBases) {
1643 // If this base is a non-virtual primary base the address point has already
1644 // been set.
1645 if (!BaseIsNonVirtualPrimaryBase) {
1646 // Initialize the vtable pointer for this base.
Anders Carlsson3e79c302010-04-20 18:05:10 +00001647 InitializeVTablePointer(Base, NearestVBase, VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001648 }
1649
1650 const CXXRecordDecl *RD = Base.getBase();
1651
1652 // Traverse bases.
1653 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1654 E = RD->bases_end(); I != E; ++I) {
1655 CXXRecordDecl *BaseDecl
1656 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1657
1658 // Ignore classes without a vtable.
1659 if (!BaseDecl->isDynamicClass())
1660 continue;
1661
1662 uint64_t BaseOffset;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001663 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001664
1665 if (I->isVirtual()) {
1666 // Check if we've visited this virtual base before.
1667 if (!VBases.insert(BaseDecl))
1668 continue;
1669
1670 const ASTRecordLayout &Layout =
1671 getContext().getASTRecordLayout(VTableClass);
1672
Anders Carlsson603d6d12010-03-28 21:07:49 +00001673 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001674 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001675 } else {
1676 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1677
1678 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001679 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001680 }
1681
1682 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001683 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001684 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001685 VTable, VTableClass, VBases);
1686 }
1687}
1688
1689void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1690 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001691 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001692 return;
1693
Anders Carlsson07036902010-03-26 04:39:42 +00001694 // Get the VTable.
1695 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001696
Anders Carlsson603d6d12010-03-28 21:07:49 +00001697 // Initialize the vtable pointers for this class and all of its bases.
1698 VisitedVirtualBasesSetTy VBases;
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001699 InitializeVTablePointers(BaseSubobject(RD, 0), /*NearestVBase=*/0,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001700 /*BaseIsNonVirtualPrimaryBase=*/false,
1701 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001702}