blob: 21f3e00ac07bec10c8d5115dda6c49e79e4b821e [file] [log] [blame]
Anders Carlsson87fc5a52008-08-22 16:00:37 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation.
11//
12//===----------------------------------------------------------------------===//
13
Mike Stump11289f42009-09-09 15:08:12 +000014// We might split this into multiple files if it gets too unwieldy
Anders Carlsson87fc5a52008-08-22 16:00:37 +000015
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Anders Carlsson1235bbc2009-04-13 18:03:33 +000018#include "Mangle.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000019#include "clang/AST/ASTContext.h"
Fariborz Jahaniandedf1e42009-07-25 21:12:28 +000020#include "clang/AST/RecordLayout.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000021#include "clang/AST/Decl.h"
Anders Carlssone5fd6f22009-04-03 22:50:24 +000022#include "clang/AST/DeclCXX.h"
Anders Carlsson131be8b2008-08-23 19:42:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlsson52d78a52009-09-27 18:58:34 +000024#include "clang/AST/StmtCXX.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000025#include "llvm/ADT/StringExtras.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000026using namespace clang;
27using namespace CodeGen;
28
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000029RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
30 llvm::Value *Callee,
31 llvm::Value *This,
32 CallExpr::const_arg_iterator ArgBeg,
33 CallExpr::const_arg_iterator ArgEnd) {
Mike Stump11289f42009-09-09 15:08:12 +000034 assert(MD->isInstance() &&
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000035 "Trying to emit a member call expr on a static method!");
36
John McCall9dd450b2009-09-21 23:43:11 +000037 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +000038
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000039 CallArgList Args;
Mike Stump11289f42009-09-09 15:08:12 +000040
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000041 // Push the this ptr.
42 Args.push_back(std::make_pair(RValue::get(This),
43 MD->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +000044
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000045 // And the rest of the call args
46 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
Mike Stump11289f42009-09-09 15:08:12 +000047
John McCall9dd450b2009-09-21 23:43:11 +000048 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000049 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
50 Callee, Args, MD);
51}
52
Anders Carlssond7432df2009-10-12 19:41:04 +000053/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
54/// expr can be devirtualized.
55static bool canDevirtualizeMemberFunctionCalls(const Expr *Base) {
56 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
57 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
58 // This is a record decl. We know the type and can devirtualize it.
59 return VD->getType()->isRecordType();
60 }
Anders Carlssonb61301f2009-10-12 19:45:47 +000061
62 return false;
Anders Carlssond7432df2009-10-12 19:41:04 +000063 }
64
Anders Carlssona1b54fd2009-10-12 19:59:15 +000065 // We can always devirtualize calls on temporary object expressions.
Anders Carlssonb61301f2009-10-12 19:45:47 +000066 if (isa<CXXTemporaryObjectExpr>(Base))
67 return true;
68
Anders Carlssona1b54fd2009-10-12 19:59:15 +000069 // And calls on bound temporaries.
70 if (isa<CXXBindTemporaryExpr>(Base))
71 return true;
72
Anders Carlsson2a017092009-10-12 19:51:33 +000073 // Check if this is a call expr that returns a record type.
74 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
75 return CE->getCallReturnType()->isRecordType();
76
Anders Carlssond7432df2009-10-12 19:41:04 +000077 // We can't devirtualize the call.
78 return false;
79}
80
Anders Carlssone5fd6f22009-04-03 22:50:24 +000081RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) {
Eli Friedman8aaff692009-12-08 02:09:46 +000082 if (isa<BinaryOperator>(CE->getCallee()->IgnoreParens()))
Anders Carlsson2ee3c012009-10-03 19:43:08 +000083 return EmitCXXMemberPointerCallExpr(CE);
84
Eli Friedman8aaff692009-12-08 02:09:46 +000085 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee()->IgnoreParens());
Anders Carlssone5fd6f22009-04-03 22:50:24 +000086 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
Anders Carlssonbd7d11f2009-05-11 23:37:08 +000087
Anders Carlsson8f4fd602009-09-29 03:54:11 +000088 if (MD->isStatic()) {
89 // The method is static, emit it as we would a regular call.
90 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
91 return EmitCall(Callee, getContext().getPointerType(MD->getType()),
92 CE->arg_begin(), CE->arg_end(), 0);
93
94 }
95
John McCall9dd450b2009-09-21 23:43:11 +000096 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stumpa523b2d2009-07-30 21:47:44 +000097
Mike Stump11289f42009-09-09 15:08:12 +000098 const llvm::Type *Ty =
99 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
Anders Carlsson03a409f2009-04-08 20:31:57 +0000100 FPT->isVariadic());
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000101 llvm::Value *This;
Mike Stump11289f42009-09-09 15:08:12 +0000102
Anders Carlssone5fd6f22009-04-03 22:50:24 +0000103 if (ME->isArrow())
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000104 This = EmitScalarExpr(ME->getBase());
Anders Carlssone5fd6f22009-04-03 22:50:24 +0000105 else {
106 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000107 This = BaseLV.getAddress();
Anders Carlssone5fd6f22009-04-03 22:50:24 +0000108 }
Mike Stumpa5588bf2009-08-26 20:46:33 +0000109
Eli Friedmanffc066f2009-11-26 07:45:48 +0000110 if (MD->isCopyAssignment() && MD->isTrivial()) {
111 // We don't like to generate the trivial copy assignment operator when
112 // it isn't necessary; just produce the proper effect here.
113 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
114 EmitAggregateCopy(This, RHS, CE->getType());
115 return RValue::get(This);
116 }
117
Douglas Gregorc1905232009-08-26 22:36:53 +0000118 // C++ [class.virtual]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000119 // Explicit qualification with the scope operator (5.1) suppresses the
Douglas Gregorc1905232009-08-26 22:36:53 +0000120 // virtual call mechanism.
Anders Carlssonb5296552009-10-11 23:55:52 +0000121 //
122 // We also don't emit a virtual call if the base expression has a record type
123 // because then we know what the type is.
Mike Stumpa5588bf2009-08-26 20:46:33 +0000124 llvm::Value *Callee;
Eli Friedmane6ce3542009-11-16 05:31:29 +0000125 if (const CXXDestructorDecl *Destructor
126 = dyn_cast<CXXDestructorDecl>(MD)) {
Eli Friedman84a7e342009-11-26 07:40:08 +0000127 if (Destructor->isTrivial())
128 return RValue::get(0);
Eli Friedmane6ce3542009-11-16 05:31:29 +0000129 if (MD->isVirtual() && !ME->hasQualifier() &&
130 !canDevirtualizeMemberFunctionCalls(ME->getBase())) {
131 Callee = BuildVirtualCall(Destructor, Dtor_Complete, This, Ty);
132 } else {
133 Callee = CGM.GetAddrOfFunction(GlobalDecl(Destructor, Dtor_Complete), Ty);
134 }
135 } else if (MD->isVirtual() && !ME->hasQualifier() &&
136 !canDevirtualizeMemberFunctionCalls(ME->getBase())) {
137 Callee = BuildVirtualCall(MD, This, Ty);
138 } else {
Anders Carlssonecf9bf02009-09-10 23:43:36 +0000139 Callee = CGM.GetAddrOfFunction(MD, Ty);
Eli Friedmane6ce3542009-11-16 05:31:29 +0000140 }
Mike Stump11289f42009-09-09 15:08:12 +0000141
142 return EmitCXXMemberCall(MD, Callee, This,
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000143 CE->arg_begin(), CE->arg_end());
Anders Carlssone5fd6f22009-04-03 22:50:24 +0000144}
Anders Carlssona5d077d2009-04-14 16:58:56 +0000145
Mike Stump11289f42009-09-09 15:08:12 +0000146RValue
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000147CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E) {
Eli Friedman8aaff692009-12-08 02:09:46 +0000148 const BinaryOperator *BO =
149 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
Anders Carlsson6bfee8f2009-10-13 17:41:28 +0000150 const Expr *BaseExpr = BO->getLHS();
151 const Expr *MemFnExpr = BO->getRHS();
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000152
Anders Carlsson6bfee8f2009-10-13 17:41:28 +0000153 const MemberPointerType *MPT =
154 MemFnExpr->getType()->getAs<MemberPointerType>();
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000155 const FunctionProtoType *FPT =
156 MPT->getPointeeType()->getAs<FunctionProtoType>();
157 const CXXRecordDecl *RD =
Douglas Gregor615ac672009-11-04 16:49:01 +0000158 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000159
160 const llvm::FunctionType *FTy =
161 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(RD, FPT),
162 FPT->isVariadic());
163
164 const llvm::Type *Int8PtrTy =
165 llvm::Type::getInt8Ty(VMContext)->getPointerTo();
166
167 // Get the member function pointer.
168 llvm::Value *MemFnPtr =
Anders Carlsson6bfee8f2009-10-13 17:41:28 +0000169 CreateTempAlloca(ConvertType(MemFnExpr->getType()), "mem.fn");
170 EmitAggExpr(MemFnExpr, MemFnPtr, /*VolatileDest=*/false);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000171
172 // Emit the 'this' pointer.
173 llvm::Value *This;
174
175 if (BO->getOpcode() == BinaryOperator::PtrMemI)
176 This = EmitScalarExpr(BaseExpr);
177 else
178 This = EmitLValue(BaseExpr).getAddress();
179
180 // Adjust it.
181 llvm::Value *Adj = Builder.CreateStructGEP(MemFnPtr, 1);
182 Adj = Builder.CreateLoad(Adj, "mem.fn.adj");
183
184 llvm::Value *Ptr = Builder.CreateBitCast(This, Int8PtrTy, "ptr");
185 Ptr = Builder.CreateGEP(Ptr, Adj, "adj");
186
187 This = Builder.CreateBitCast(Ptr, This->getType(), "this");
188
189 llvm::Value *FnPtr = Builder.CreateStructGEP(MemFnPtr, 0, "mem.fn.ptr");
190
191 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
192
193 llvm::Value *FnAsInt = Builder.CreateLoad(FnPtr, "fn");
194
195 // If the LSB in the function pointer is 1, the function pointer points to
196 // a virtual function.
197 llvm::Value *IsVirtual
198 = Builder.CreateAnd(FnAsInt, llvm::ConstantInt::get(PtrDiffTy, 1),
199 "and");
200
201 IsVirtual = Builder.CreateTrunc(IsVirtual,
202 llvm::Type::getInt1Ty(VMContext));
203
204 llvm::BasicBlock *FnVirtual = createBasicBlock("fn.virtual");
205 llvm::BasicBlock *FnNonVirtual = createBasicBlock("fn.nonvirtual");
206 llvm::BasicBlock *FnEnd = createBasicBlock("fn.end");
207
208 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
209 EmitBlock(FnVirtual);
210
211 const llvm::Type *VTableTy =
212 FTy->getPointerTo()->getPointerTo()->getPointerTo();
213
214 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy);
215 VTable = Builder.CreateLoad(VTable);
216
217 VTable = Builder.CreateGEP(VTable, FnAsInt, "fn");
218
219 // Since the function pointer is 1 plus the virtual table offset, we
220 // subtract 1 by using a GEP.
Mike Stump0d479e62009-10-09 01:25:47 +0000221 VTable = Builder.CreateConstGEP1_64(VTable, (uint64_t)-1);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000222
223 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "virtualfn");
224
225 EmitBranch(FnEnd);
226 EmitBlock(FnNonVirtual);
227
228 // If the function is not virtual, just load the pointer.
229 llvm::Value *NonVirtualFn = Builder.CreateLoad(FnPtr, "fn");
230 NonVirtualFn = Builder.CreateIntToPtr(NonVirtualFn, FTy->getPointerTo());
231
232 EmitBlock(FnEnd);
233
234 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo());
235 Callee->reserveOperandSpace(2);
236 Callee->addIncoming(VirtualFn, FnVirtual);
237 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
238
239 CallArgList Args;
240
241 QualType ThisType =
242 getContext().getPointerType(getContext().getTagDeclType(RD));
243
244 // Push the this ptr.
245 Args.push_back(std::make_pair(RValue::get(This), ThisType));
246
247 // And the rest of the call args
248 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
249 QualType ResultType = BO->getType()->getAs<FunctionType>()->getResultType();
250 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
251 Callee, Args, 0);
252}
253
254RValue
Anders Carlsson4034a952009-05-27 04:18:27 +0000255CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
256 const CXXMethodDecl *MD) {
Mike Stump11289f42009-09-09 15:08:12 +0000257 assert(MD->isInstance() &&
Anders Carlsson4034a952009-05-27 04:18:27 +0000258 "Trying to emit a member call expr on a static method!");
Mike Stump11289f42009-09-09 15:08:12 +0000259
Fariborz Jahanian4985b332009-08-13 21:09:41 +0000260 if (MD->isCopyAssignment()) {
261 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
262 if (ClassDecl->hasTrivialCopyAssignment()) {
263 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
264 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
265 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
266 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
267 QualType Ty = E->getType();
268 EmitAggregateCopy(This, Src, Ty);
269 return RValue::get(This);
270 }
271 }
Mike Stump11289f42009-09-09 15:08:12 +0000272
John McCall9dd450b2009-09-21 23:43:11 +0000273 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +0000274 const llvm::Type *Ty =
275 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
Mike Stump5a522352009-09-04 18:27:16 +0000276 FPT->isVariadic());
Mike Stump11289f42009-09-09 15:08:12 +0000277
Anders Carlsson4034a952009-05-27 04:18:27 +0000278 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
Mike Stump11289f42009-09-09 15:08:12 +0000279
Eli Friedmane6ce3542009-11-16 05:31:29 +0000280 llvm::Value *Callee;
281 if (MD->isVirtual() && !canDevirtualizeMemberFunctionCalls(E->getArg(0)))
282 Callee = BuildVirtualCall(MD, This, Ty);
283 else
284 Callee = CGM.GetAddrOfFunction(MD, Ty);
285
Anders Carlsson4034a952009-05-27 04:18:27 +0000286 return EmitCXXMemberCall(MD, Callee, This,
287 E->arg_begin() + 1, E->arg_end());
288}
289
Anders Carlssona5d077d2009-04-14 16:58:56 +0000290llvm::Value *CodeGenFunction::LoadCXXThis() {
Mike Stump11289f42009-09-09 15:08:12 +0000291 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
Anders Carlssona5d077d2009-04-14 16:58:56 +0000292 "Must be in a C++ member function decl to load 'this'");
293 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
294 "Must be in a C++ member function decl to load 'this'");
Mike Stump11289f42009-09-09 15:08:12 +0000295
Anders Carlssona5d077d2009-04-14 16:58:56 +0000296 // FIXME: What if we're inside a block?
Mike Stump18bb9282009-05-16 07:57:57 +0000297 // ans: See how CodeGenFunction::LoadObjCSelf() uses
298 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlssona5d077d2009-04-14 16:58:56 +0000299 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
300}
Anders Carlssonf7475242009-04-15 15:55:24 +0000301
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000302/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
303/// for-loop to call the default constructor on individual members of the
Anders Carlssond49844b2009-09-23 02:45:36 +0000304/// array.
305/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
306/// array type and 'ArrayPtr' points to the beginning fo the array.
307/// It is assumed that all relevant checks have been made by the caller.
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000308void
309CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson3a202f62009-11-24 18:43:52 +0000310 const ConstantArrayType *ArrayTy,
311 llvm::Value *ArrayPtr,
312 CallExpr::const_arg_iterator ArgBeg,
313 CallExpr::const_arg_iterator ArgEnd) {
314
Anders Carlssond49844b2009-09-23 02:45:36 +0000315 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
316 llvm::Value * NumElements =
317 llvm::ConstantInt::get(SizeTy,
318 getContext().getConstantArrayElementCount(ArrayTy));
319
Anders Carlsson3a202f62009-11-24 18:43:52 +0000320 EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd);
Anders Carlssond49844b2009-09-23 02:45:36 +0000321}
322
323void
324CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson3a202f62009-11-24 18:43:52 +0000325 llvm::Value *NumElements,
326 llvm::Value *ArrayPtr,
327 CallExpr::const_arg_iterator ArgBeg,
328 CallExpr::const_arg_iterator ArgEnd) {
Anders Carlssond49844b2009-09-23 02:45:36 +0000329 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump11289f42009-09-09 15:08:12 +0000330
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000331 // Create a temporary for the loop index and initialize it with 0.
Anders Carlssond49844b2009-09-23 02:45:36 +0000332 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
333 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Daniel Dunbardacbe6b2009-11-29 21:11:41 +0000334 Builder.CreateStore(Zero, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000335
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000336 // Start the loop with a block that tests the condition.
337 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
338 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +0000339
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000340 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000341
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000342 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump11289f42009-09-09 15:08:12 +0000343
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000344 // Generate: if (loop-index < number-of-elements fall to the loop body,
345 // otherwise, go to the block after the for-loop.
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000346 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
Anders Carlssond49844b2009-09-23 02:45:36 +0000347 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000348 // If the condition is true, execute the body.
349 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +0000350
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000351 EmitBlock(ForBody);
Mike Stump11289f42009-09-09 15:08:12 +0000352
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000353 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000354 // Inside the loop body, emit the constructor call on the array element.
Fariborz Jahaniandd46eb72009-08-20 01:01:06 +0000355 Counter = Builder.CreateLoad(IndexPtr);
Anders Carlssond49844b2009-09-23 02:45:36 +0000356 llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
357 "arrayidx");
Mike Stump11289f42009-09-09 15:08:12 +0000358
Anders Carlsson3a202f62009-11-24 18:43:52 +0000359 // C++ [class.temporary]p4:
360 // There are two contexts in which temporaries are destroyed at a different
Mike Stump26004912009-12-10 00:05:14 +0000361 // point than the end of the full-expression. The first context is when a
Anders Carlsson3a202f62009-11-24 18:43:52 +0000362 // default constructor is called to initialize an element of an array.
363 // If the constructor has one or more default arguments, the destruction of
364 // every temporary created in a default argument expression is sequenced
365 // before the construction of the next array element, if any.
366
367 // Keep track of the current number of live temporaries.
368 unsigned OldNumLiveTemporaries = LiveTemporaries.size();
369
370 EmitCXXConstructorCall(D, Ctor_Complete, Address, ArgBeg, ArgEnd);
371
372 // Pop temporaries.
373 while (LiveTemporaries.size() > OldNumLiveTemporaries)
374 PopCXXTemporary();
375
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000376 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000377
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000378 // Emit the increment of the loop counter.
Anders Carlssond49844b2009-09-23 02:45:36 +0000379 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000380 Counter = Builder.CreateLoad(IndexPtr);
381 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +0000382 Builder.CreateStore(NextVal, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000383
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000384 // Finally, branch back up to the condition for the next iteration.
385 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000386
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000387 // Emit the fall-through block.
388 EmitBlock(AfterFor, true);
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000389}
390
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000391/// EmitCXXAggrDestructorCall - calls the default destructor on array
392/// elements in reverse order of construction.
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000393void
Fariborz Jahanian9c837202009-08-20 20:54:15 +0000394CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
395 const ArrayType *Array,
396 llvm::Value *This) {
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000397 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
398 assert(CA && "Do we support VLA for destruction ?");
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +0000399 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
Anders Carlsson21122cf2009-12-13 20:04:38 +0000400
401 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
402 llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +0000403 EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
404}
405
406/// EmitCXXAggrDestructorCall - calls the default destructor on array
407/// elements in reverse order of construction.
408void
409CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
410 llvm::Value *UpperCount,
411 llvm::Value *This) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000412 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
413 llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
414
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000415 // Create a temporary for the loop index and initialize it with count of
416 // array elements.
Anders Carlsson21122cf2009-12-13 20:04:38 +0000417 llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
418
419 // Store the number of elements in the index pointer.
Daniel Dunbardacbe6b2009-11-29 21:11:41 +0000420 Builder.CreateStore(UpperCount, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000421
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000422 // Start the loop with a block that tests the condition.
423 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
424 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +0000425
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000426 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000427
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000428 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump11289f42009-09-09 15:08:12 +0000429
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000430 // Generate: if (loop-index != 0 fall to the loop body,
431 // otherwise, go to the block after the for-loop.
Mike Stump11289f42009-09-09 15:08:12 +0000432 llvm::Value* zeroConstant =
Anders Carlsson21122cf2009-12-13 20:04:38 +0000433 llvm::Constant::getNullValue(SizeLTy);
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000434 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
435 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
436 "isne");
437 // If the condition is true, execute the body.
438 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +0000439
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000440 EmitBlock(ForBody);
Mike Stump11289f42009-09-09 15:08:12 +0000441
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000442 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
443 // Inside the loop body, emit the constructor call on the array element.
444 Counter = Builder.CreateLoad(IndexPtr);
445 Counter = Builder.CreateSub(Counter, One);
446 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Fariborz Jahanianbe641492009-11-30 22:07:18 +0000447 EmitCXXDestructorCall(D, Dtor_Complete, Address);
Mike Stump11289f42009-09-09 15:08:12 +0000448
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000449 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000450
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000451 // Emit the decrement of the loop counter.
452 Counter = Builder.CreateLoad(IndexPtr);
453 Counter = Builder.CreateSub(Counter, One, "dec");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +0000454 Builder.CreateStore(Counter, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000455
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000456 // Finally, branch back up to the condition for the next iteration.
457 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000458
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000459 // Emit the fall-through block.
460 EmitBlock(AfterFor, true);
Fariborz Jahanian9c837202009-08-20 20:54:15 +0000461}
462
Mike Stumpea950e22009-11-18 18:57:56 +0000463/// GenerateCXXAggrDestructorHelper - Generates a helper function which when
464/// invoked, calls the default destructor on array elements in reverse order of
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000465/// construction.
466llvm::Constant *
467CodeGenFunction::GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
468 const ArrayType *Array,
469 llvm::Value *This) {
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000470 FunctionArgList Args;
471 ImplicitParamDecl *Dst =
472 ImplicitParamDecl::Create(getContext(), 0,
473 SourceLocation(), 0,
474 getContext().getPointerType(getContext().VoidTy));
475 Args.push_back(std::make_pair(Dst, Dst->getType()));
476
477 llvm::SmallString<16> Name;
Eli Friedmand5bc94e2009-12-10 02:21:21 +0000478 llvm::raw_svector_ostream(Name) << "__tcf_" << (++UniqueAggrDestructorCount);
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000479 QualType R = getContext().VoidTy;
480 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(R, Args);
481 const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false);
482 llvm::Function *Fn =
483 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerb11118b2009-12-11 13:33:18 +0000484 Name.str(),
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000485 &CGM.getModule());
Benjamin Kramerb11118b2009-12-11 13:33:18 +0000486 IdentifierInfo *II = &CGM.getContext().Idents.get(Name.str());
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000487 FunctionDecl *FD = FunctionDecl::Create(getContext(),
488 getContext().getTranslationUnitDecl(),
489 SourceLocation(), II, R, 0,
490 FunctionDecl::Static,
491 false, true);
492 StartFunction(FD, R, Fn, Args, SourceLocation());
493 QualType BaseElementTy = getContext().getBaseElementType(Array);
494 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
495 BasePtr = llvm::PointerType::getUnqual(BasePtr);
496 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(This, BasePtr);
497 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
498 FinishFunction();
499 llvm::Type *Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),
500 0);
501 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
502 return m;
503}
504
Fariborz Jahanian9c837202009-08-20 20:54:15 +0000505void
Mike Stump11289f42009-09-09 15:08:12 +0000506CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
507 CXXCtorType Type,
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000508 llvm::Value *This,
509 CallExpr::const_arg_iterator ArgBeg,
510 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian42af5ba2009-08-14 20:11:43 +0000511 if (D->isCopyConstructor(getContext())) {
512 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
513 if (ClassDecl->hasTrivialCopyConstructor()) {
514 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
515 "EmitCXXConstructorCall - user declared copy constructor");
516 const Expr *E = (*ArgBeg);
517 QualType Ty = E->getType();
518 llvm::Value *Src = EmitLValue(E).getAddress();
519 EmitAggregateCopy(This, Src, Ty);
520 return;
521 }
Eli Friedman84a7e342009-11-26 07:40:08 +0000522 } else if (D->isTrivial()) {
523 // FIXME: Track down why we're trying to generate calls to the trivial
524 // default constructor!
525 return;
Fariborz Jahanian42af5ba2009-08-14 20:11:43 +0000526 }
Mike Stump11289f42009-09-09 15:08:12 +0000527
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000528 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
529
530 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000531}
532
Anders Carlssonce460522009-12-04 19:33:17 +0000533void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
Anders Carlsson0a637412009-05-29 21:03:38 +0000534 CXXDtorType Type,
535 llvm::Value *This) {
Anders Carlssonce460522009-12-04 19:33:17 +0000536 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
537
538 CallArgList Args;
Mike Stump11289f42009-09-09 15:08:12 +0000539
Anders Carlssonce460522009-12-04 19:33:17 +0000540 // Push the this ptr.
541 Args.push_back(std::make_pair(RValue::get(This),
542 DD->getThisType(getContext())));
543
544 // Add a VTT parameter if necessary.
545 // FIXME: This should not be a dummy null parameter!
546 if (Type == Dtor_Base && DD->getParent()->getNumVBases() != 0) {
547 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
548
549 Args.push_back(std::make_pair(RValue::get(CGM.EmitNullConstant(T)), T));
550 }
551
552 // FIXME: We should try to share this code with EmitCXXMemberCall.
553
554 QualType ResultType = DD->getType()->getAs<FunctionType>()->getResultType();
555 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args), Callee, Args, DD);
Anders Carlsson0a637412009-05-29 21:03:38 +0000556}
557
Mike Stump11289f42009-09-09 15:08:12 +0000558void
559CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
Anders Carlsson1619a5042009-05-03 17:47:16 +0000560 const CXXConstructExpr *E) {
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000561 assert(Dest && "Must have a destination!");
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000562 const CXXConstructorDecl *CD = E->getConstructor();
Fariborz Jahanian29baa2b2009-10-28 21:07:28 +0000563 const ConstantArrayType *Array =
564 getContext().getAsConstantArrayType(E->getType());
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000565 // For a copy constructor, even if it is trivial, must fall thru so
566 // its argument is code-gen'ed.
567 if (!CD->isCopyConstructor(getContext())) {
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000568 QualType InitType = E->getType();
Fariborz Jahanian29baa2b2009-10-28 21:07:28 +0000569 if (Array)
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000570 InitType = getContext().getBaseElementType(Array);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000571 const CXXRecordDecl *RD =
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000572 cast<CXXRecordDecl>(InitType->getAs<RecordType>()->getDecl());
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000573 if (RD->hasTrivialConstructor())
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000574 return;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000575 }
Mike Stump11289f42009-09-09 15:08:12 +0000576 // Code gen optimization to eliminate copy constructor and return
Fariborz Jahanianeb869762009-08-06 01:02:49 +0000577 // its first argument instead.
Anders Carlsson9cedbef2009-08-22 22:30:33 +0000578 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
Anders Carlsson78cfaa92009-11-13 04:34:45 +0000579 const Expr *Arg = E->getArg(0);
Douglas Gregore1314a62009-12-18 05:02:21 +0000580
581 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
582 if (isa<CXXBindTemporaryExpr>(ICE->getSubExpr()))
583 Arg = cast<CXXBindTemporaryExpr>(ICE->getSubExpr())->getSubExpr();
584 } else if (const CXXBindTemporaryExpr *BindExpr =
585 dyn_cast<CXXBindTemporaryExpr>(Arg))
Anders Carlsson78cfaa92009-11-13 04:34:45 +0000586 Arg = BindExpr->getSubExpr();
587
588 EmitAggExpr(Arg, Dest, false);
Fariborz Jahanian00130932009-08-06 19:12:38 +0000589 return;
Fariborz Jahanianeb869762009-08-06 01:02:49 +0000590 }
Fariborz Jahanian29baa2b2009-10-28 21:07:28 +0000591 if (Array) {
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000592 QualType BaseElementTy = getContext().getBaseElementType(Array);
593 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
594 BasePtr = llvm::PointerType::getUnqual(BasePtr);
595 llvm::Value *BaseAddrPtr =
596 Builder.CreateBitCast(Dest, BasePtr);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000597
Anders Carlsson3a202f62009-11-24 18:43:52 +0000598 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
599 E->arg_begin(), E->arg_end());
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000600 }
601 else
602 // Call the constructor.
603 EmitCXXConstructorCall(CD, Ctor_Complete, Dest,
604 E->arg_begin(), E->arg_end());
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000605}
606
Anders Carlssonf7475242009-04-15 15:55:24 +0000607void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlssondae1abc2009-05-05 04:44:02 +0000608 EmitGlobal(GlobalDecl(D, Ctor_Complete));
609 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlssonf7475242009-04-15 15:55:24 +0000610}
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000611
Mike Stump11289f42009-09-09 15:08:12 +0000612void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000613 CXXCtorType Type) {
Mike Stump11289f42009-09-09 15:08:12 +0000614
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000615 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
Mike Stump11289f42009-09-09 15:08:12 +0000616
Anders Carlsson73fcc952009-09-11 00:07:24 +0000617 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
Mike Stump11289f42009-09-09 15:08:12 +0000618
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000619 SetFunctionDefinitionAttributes(D, Fn);
620 SetLLVMFunctionAttributesForDefinition(D, Fn);
621}
622
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000623llvm::Function *
Mike Stump11289f42009-09-09 15:08:12 +0000624CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000625 CXXCtorType Type) {
Fariborz Jahanianc2d71b52009-11-06 18:47:57 +0000626 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000627 const llvm::FunctionType *FTy =
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000628 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type),
Fariborz Jahanianc2d71b52009-11-06 18:47:57 +0000629 FPT->isVariadic());
Mike Stump11289f42009-09-09 15:08:12 +0000630
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000631 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattnere0be0df2009-05-12 21:21:08 +0000632 return cast<llvm::Function>(
633 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000634}
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000635
Mike Stump11289f42009-09-09 15:08:12 +0000636const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000637 CXXCtorType Type) {
638 llvm::SmallString<256> Name;
Daniel Dunbare128dd12009-11-21 09:06:22 +0000639 getMangleContext().mangleCXXCtor(D, Type, Name);
Mike Stump11289f42009-09-09 15:08:12 +0000640
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000641 Name += '\0';
642 return UniqueMangledName(Name.begin(), Name.end());
643}
644
645void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
Eli Friedmanb572c922009-11-14 04:19:37 +0000646 if (D->isVirtual())
Eli Friedmand777ccc2009-12-15 02:06:15 +0000647 EmitGlobal(GlobalDecl(D, Dtor_Deleting));
648 EmitGlobal(GlobalDecl(D, Dtor_Complete));
649 EmitGlobal(GlobalDecl(D, Dtor_Base));
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000650}
651
Mike Stump11289f42009-09-09 15:08:12 +0000652void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000653 CXXDtorType Type) {
654 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
Mike Stump11289f42009-09-09 15:08:12 +0000655
Anders Carlsson73fcc952009-09-11 00:07:24 +0000656 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
Mike Stump11289f42009-09-09 15:08:12 +0000657
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000658 SetFunctionDefinitionAttributes(D, Fn);
659 SetLLVMFunctionAttributesForDefinition(D, Fn);
660}
661
662llvm::Function *
Mike Stump11289f42009-09-09 15:08:12 +0000663CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000664 CXXDtorType Type) {
665 const llvm::FunctionType *FTy =
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000666 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), false);
Mike Stump11289f42009-09-09 15:08:12 +0000667
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000668 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattnere0be0df2009-05-12 21:21:08 +0000669 return cast<llvm::Function>(
670 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000671}
672
Mike Stump11289f42009-09-09 15:08:12 +0000673const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000674 CXXDtorType Type) {
675 llvm::SmallString<256> Name;
Daniel Dunbare128dd12009-11-21 09:06:22 +0000676 getMangleContext().mangleCXXDtor(D, Type, Name);
Mike Stump11289f42009-09-09 15:08:12 +0000677
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000678 Name += '\0';
679 return UniqueMangledName(Name.begin(), Name.end());
680}
Fariborz Jahanian83381cc2009-07-20 23:18:55 +0000681
Anders Carlssonc7785402009-11-26 02:32:05 +0000682llvm::Constant *
Eli Friedman551fe842009-12-03 04:27:05 +0000683CodeGenFunction::GenerateThunk(llvm::Function *Fn, GlobalDecl GD,
Anders Carlssonc7785402009-11-26 02:32:05 +0000684 bool Extern,
685 const ThunkAdjustment &ThisAdjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000686 return GenerateCovariantThunk(Fn, GD, Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000687 CovariantThunkAdjustment(ThisAdjustment,
688 ThunkAdjustment()));
Mike Stump5a522352009-09-04 18:27:16 +0000689}
690
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000691llvm::Value *
692CodeGenFunction::DynamicTypeAdjust(llvm::Value *V,
693 const ThunkAdjustment &Adjustment) {
694 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
695
Mike Stump77738202009-11-03 16:59:27 +0000696 const llvm::Type *OrigTy = V->getType();
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000697 if (Adjustment.NonVirtual) {
Mike Stump77738202009-11-03 16:59:27 +0000698 // Do the non-virtual adjustment
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000699 V = Builder.CreateBitCast(V, Int8PtrTy);
700 V = Builder.CreateConstInBoundsGEP1_64(V, Adjustment.NonVirtual);
Mike Stump77738202009-11-03 16:59:27 +0000701 V = Builder.CreateBitCast(V, OrigTy);
702 }
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000703
704 if (!Adjustment.Virtual)
705 return V;
706
707 assert(Adjustment.Virtual % (LLVMPointerWidth / 8) == 0 &&
708 "vtable entry unaligned");
709
710 // Do the virtual this adjustment
711 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
712 const llvm::Type *PtrDiffPtrTy = PtrDiffTy->getPointerTo();
713
714 llvm::Value *ThisVal = Builder.CreateBitCast(V, Int8PtrTy);
715 V = Builder.CreateBitCast(V, PtrDiffPtrTy->getPointerTo());
716 V = Builder.CreateLoad(V, "vtable");
717
718 llvm::Value *VTablePtr = V;
719 uint64_t VirtualAdjustment = Adjustment.Virtual / (LLVMPointerWidth / 8);
720 V = Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
721 V = Builder.CreateLoad(V);
722 V = Builder.CreateGEP(ThisVal, V);
723
724 return Builder.CreateBitCast(V, OrigTy);
Mike Stump77738202009-11-03 16:59:27 +0000725}
726
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000727llvm::Constant *
728CodeGenFunction::GenerateCovariantThunk(llvm::Function *Fn,
Eli Friedman551fe842009-12-03 04:27:05 +0000729 GlobalDecl GD, bool Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000730 const CovariantThunkAdjustment &Adjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000731 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump33ccd9e2009-11-02 23:22:01 +0000732 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump80f6ac52009-09-11 23:25:56 +0000733
734 FunctionArgList Args;
735 ImplicitParamDecl *ThisDecl =
736 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
737 MD->getThisType(getContext()));
738 Args.push_back(std::make_pair(ThisDecl, ThisDecl->getType()));
739 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
740 e = MD->param_end();
741 i != e; ++i) {
742 ParmVarDecl *D = *i;
743 Args.push_back(std::make_pair(D, D->getType()));
744 }
745 IdentifierInfo *II
746 = &CGM.getContext().Idents.get("__thunk_named_foo_");
747 FunctionDecl *FD = FunctionDecl::Create(getContext(),
748 getContext().getTranslationUnitDecl(),
Mike Stump33ccd9e2009-11-02 23:22:01 +0000749 SourceLocation(), II, ResultType, 0,
Mike Stump80f6ac52009-09-11 23:25:56 +0000750 Extern
751 ? FunctionDecl::Extern
752 : FunctionDecl::Static,
753 false, true);
Mike Stump33ccd9e2009-11-02 23:22:01 +0000754 StartFunction(FD, ResultType, Fn, Args, SourceLocation());
755
756 // generate body
Mike Stumpf3589722009-11-03 02:12:59 +0000757 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
758 const llvm::Type *Ty =
759 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
760 FPT->isVariadic());
Eli Friedman551fe842009-12-03 04:27:05 +0000761 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000762
Mike Stump33ccd9e2009-11-02 23:22:01 +0000763 CallArgList CallArgs;
764
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000765 bool ShouldAdjustReturnPointer = true;
Mike Stumpf3589722009-11-03 02:12:59 +0000766 QualType ArgType = MD->getThisType(getContext());
767 llvm::Value *Arg = Builder.CreateLoad(LocalDeclMap[ThisDecl], "this");
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000768 if (!Adjustment.ThisAdjustment.isEmpty()) {
Mike Stump77738202009-11-03 16:59:27 +0000769 // Do the this adjustment.
Mike Stump71609a22009-11-04 00:53:51 +0000770 const llvm::Type *OrigTy = Callee->getType();
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000771 Arg = DynamicTypeAdjust(Arg, Adjustment.ThisAdjustment);
772
773 if (!Adjustment.ReturnAdjustment.isEmpty()) {
774 const CovariantThunkAdjustment &ReturnAdjustment =
775 CovariantThunkAdjustment(ThunkAdjustment(),
776 Adjustment.ReturnAdjustment);
777
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000778 Callee = CGM.BuildCovariantThunk(GD, Extern, ReturnAdjustment);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000779
Mike Stump71609a22009-11-04 00:53:51 +0000780 Callee = Builder.CreateBitCast(Callee, OrigTy);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000781 ShouldAdjustReturnPointer = false;
Mike Stump71609a22009-11-04 00:53:51 +0000782 }
783 }
784
Mike Stumpf3589722009-11-03 02:12:59 +0000785 CallArgs.push_back(std::make_pair(RValue::get(Arg), ArgType));
786
Mike Stump33ccd9e2009-11-02 23:22:01 +0000787 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
788 e = MD->param_end();
789 i != e; ++i) {
790 ParmVarDecl *D = *i;
791 QualType ArgType = D->getType();
792
793 // llvm::Value *Arg = CGF.GetAddrOfLocalVar(Dst);
Eli Friedman4039f352009-12-03 04:49:52 +0000794 Expr *Arg = new (getContext()) DeclRefExpr(D, ArgType.getNonReferenceType(),
795 SourceLocation());
Mike Stump33ccd9e2009-11-02 23:22:01 +0000796 CallArgs.push_back(std::make_pair(EmitCallArg(Arg, ArgType), ArgType));
797 }
798
Mike Stump31e1d432009-11-02 23:47:45 +0000799 RValue RV = EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
800 Callee, CallArgs, MD);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000801 if (ShouldAdjustReturnPointer && !Adjustment.ReturnAdjustment.isEmpty()) {
Mike Stumpc5507682009-11-05 06:32:02 +0000802 bool CanBeZero = !(ResultType->isReferenceType()
803 // FIXME: attr nonnull can't be zero either
804 /* || ResultType->hasAttr<NonNullAttr>() */ );
Mike Stump77738202009-11-03 16:59:27 +0000805 // Do the return result adjustment.
Mike Stumpc5507682009-11-05 06:32:02 +0000806 if (CanBeZero) {
807 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
808 llvm::BasicBlock *ZeroBlock = createBasicBlock();
809 llvm::BasicBlock *ContBlock = createBasicBlock();
Mike Stumpb8da7a02009-11-05 06:12:26 +0000810
Mike Stumpc5507682009-11-05 06:32:02 +0000811 const llvm::Type *Ty = RV.getScalarVal()->getType();
812 llvm::Value *Zero = llvm::Constant::getNullValue(Ty);
813 Builder.CreateCondBr(Builder.CreateICmpNE(RV.getScalarVal(), Zero),
814 NonZeroBlock, ZeroBlock);
815 EmitBlock(NonZeroBlock);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000816 llvm::Value *NZ =
817 DynamicTypeAdjust(RV.getScalarVal(), Adjustment.ReturnAdjustment);
Mike Stumpc5507682009-11-05 06:32:02 +0000818 EmitBranch(ContBlock);
819 EmitBlock(ZeroBlock);
820 llvm::Value *Z = RV.getScalarVal();
821 EmitBlock(ContBlock);
822 llvm::PHINode *RVOrZero = Builder.CreatePHI(Ty);
823 RVOrZero->reserveOperandSpace(2);
824 RVOrZero->addIncoming(NZ, NonZeroBlock);
825 RVOrZero->addIncoming(Z, ZeroBlock);
826 RV = RValue::get(RVOrZero);
827 } else
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000828 RV = RValue::get(DynamicTypeAdjust(RV.getScalarVal(),
829 Adjustment.ReturnAdjustment));
Mike Stump33ccd9e2009-11-02 23:22:01 +0000830 }
831
Mike Stump31e1d432009-11-02 23:47:45 +0000832 if (!ResultType->isVoidType())
833 EmitReturnOfRValue(RV, ResultType);
834
Mike Stump80f6ac52009-09-11 23:25:56 +0000835 FinishFunction();
836 return Fn;
837}
838
Anders Carlssonc7785402009-11-26 02:32:05 +0000839llvm::Constant *
Eli Friedman8174f2c2009-12-06 22:01:30 +0000840CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
841 const ThunkAdjustment &ThisAdjustment) {
842 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
843
844 // Compute mangled name
845 llvm::SmallString<256> OutName;
846 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
847 getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(), ThisAdjustment,
848 OutName);
849 else
850 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
851 OutName += '\0';
852 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
853
854 // Get function for mangled name
855 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
856 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
857}
858
859llvm::Constant *
860CodeGenModule::GetAddrOfCovariantThunk(GlobalDecl GD,
861 const CovariantThunkAdjustment &Adjustment) {
862 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
863
864 // Compute mangled name
865 llvm::SmallString<256> OutName;
866 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
867 OutName += '\0';
868 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
869
870 // Get function for mangled name
871 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
872 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
873}
874
875void CodeGenModule::BuildThunksForVirtual(GlobalDecl GD) {
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000876 CGVtableInfo::AdjustmentVectorTy *AdjPtr = getVtableInfo().getAdjustments(GD);
877 if (!AdjPtr)
878 return;
879 CGVtableInfo::AdjustmentVectorTy &Adj = *AdjPtr;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000880 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000881 for (unsigned i = 0; i < Adj.size(); i++) {
882 GlobalDecl OGD = Adj[i].first;
883 const CXXMethodDecl *OMD = cast<CXXMethodDecl>(OGD.getDecl());
Eli Friedman8174f2c2009-12-06 22:01:30 +0000884 QualType nc_oret = OMD->getType()->getAs<FunctionType>()->getResultType();
885 CanQualType oret = getContext().getCanonicalType(nc_oret);
886 QualType nc_ret = MD->getType()->getAs<FunctionType>()->getResultType();
887 CanQualType ret = getContext().getCanonicalType(nc_ret);
888 ThunkAdjustment ReturnAdjustment;
889 if (oret != ret) {
890 QualType qD = nc_ret->getPointeeType();
891 QualType qB = nc_oret->getPointeeType();
892 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
893 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
894 ReturnAdjustment = ComputeThunkAdjustment(D, B);
895 }
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000896 ThunkAdjustment ThisAdjustment = Adj[i].second;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000897 bool Extern = !cast<CXXRecordDecl>(OMD->getDeclContext())->isInAnonymousNamespace();
898 if (!ReturnAdjustment.isEmpty() || !ThisAdjustment.isEmpty()) {
899 CovariantThunkAdjustment CoAdj(ThisAdjustment, ReturnAdjustment);
900 llvm::Constant *FnConst;
901 if (!ReturnAdjustment.isEmpty())
902 FnConst = GetAddrOfCovariantThunk(GD, CoAdj);
903 else
904 FnConst = GetAddrOfThunk(GD, ThisAdjustment);
905 if (!isa<llvm::Function>(FnConst)) {
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000906 llvm::Constant *SubExpr =
907 cast<llvm::ConstantExpr>(FnConst)->getOperand(0);
908 llvm::Function *OldFn = cast<llvm::Function>(SubExpr);
909 std::string Name = OldFn->getNameStr();
910 GlobalDeclMap.erase(UniqueMangledName(Name.data(),
911 Name.data() + Name.size() + 1));
912 llvm::Constant *NewFnConst;
913 if (!ReturnAdjustment.isEmpty())
914 NewFnConst = GetAddrOfCovariantThunk(GD, CoAdj);
915 else
916 NewFnConst = GetAddrOfThunk(GD, ThisAdjustment);
917 llvm::Function *NewFn = cast<llvm::Function>(NewFnConst);
918 NewFn->takeName(OldFn);
919 llvm::Constant *NewPtrForOldDecl =
920 llvm::ConstantExpr::getBitCast(NewFn, OldFn->getType());
921 OldFn->replaceAllUsesWith(NewPtrForOldDecl);
922 OldFn->eraseFromParent();
923 FnConst = NewFn;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000924 }
925 llvm::Function *Fn = cast<llvm::Function>(FnConst);
926 if (Fn->isDeclaration()) {
927 llvm::GlobalVariable::LinkageTypes linktype;
928 linktype = llvm::GlobalValue::WeakAnyLinkage;
929 if (!Extern)
930 linktype = llvm::GlobalValue::InternalLinkage;
931 Fn->setLinkage(linktype);
932 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
933 Fn->addFnAttr(llvm::Attribute::NoUnwind);
934 Fn->setAlignment(2);
935 CodeGenFunction(*this).GenerateCovariantThunk(Fn, GD, Extern, CoAdj);
936 }
937 }
Eli Friedman8174f2c2009-12-06 22:01:30 +0000938 }
939}
940
941llvm::Constant *
Eli Friedman551fe842009-12-03 04:27:05 +0000942CodeGenModule::BuildThunk(GlobalDecl GD, bool Extern,
Anders Carlssonc7785402009-11-26 02:32:05 +0000943 const ThunkAdjustment &ThisAdjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000944 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump5a522352009-09-04 18:27:16 +0000945 llvm::SmallString<256> OutName;
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000946 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(MD)) {
947 getMangleContext().mangleCXXDtorThunk(D, GD.getDtorType(), ThisAdjustment,
948 OutName);
949 } else
950 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
Anders Carlssonc7785402009-11-26 02:32:05 +0000951
Mike Stump5a522352009-09-04 18:27:16 +0000952 llvm::GlobalVariable::LinkageTypes linktype;
953 linktype = llvm::GlobalValue::WeakAnyLinkage;
954 if (!Extern)
955 linktype = llvm::GlobalValue::InternalLinkage;
956 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
John McCall9dd450b2009-09-21 23:43:11 +0000957 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump5a522352009-09-04 18:27:16 +0000958 const llvm::FunctionType *FTy =
959 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
960 FPT->isVariadic());
961
Daniel Dunbare128dd12009-11-21 09:06:22 +0000962 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
Mike Stump5a522352009-09-04 18:27:16 +0000963 &getModule());
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000964 CodeGenFunction(*this).GenerateThunk(Fn, GD, Extern, ThisAdjustment);
Mike Stump5a522352009-09-04 18:27:16 +0000965 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
966 return m;
967}
968
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000969llvm::Constant *
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000970CodeGenModule::BuildCovariantThunk(const GlobalDecl &GD, bool Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000971 const CovariantThunkAdjustment &Adjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000972 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump80f6ac52009-09-11 23:25:56 +0000973 llvm::SmallString<256> OutName;
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000974 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
Mike Stump80f6ac52009-09-11 23:25:56 +0000975 llvm::GlobalVariable::LinkageTypes linktype;
976 linktype = llvm::GlobalValue::WeakAnyLinkage;
977 if (!Extern)
978 linktype = llvm::GlobalValue::InternalLinkage;
979 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
John McCall9dd450b2009-09-21 23:43:11 +0000980 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump80f6ac52009-09-11 23:25:56 +0000981 const llvm::FunctionType *FTy =
982 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
983 FPT->isVariadic());
984
Daniel Dunbare128dd12009-11-21 09:06:22 +0000985 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
Mike Stump80f6ac52009-09-11 23:25:56 +0000986 &getModule());
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000987 CodeGenFunction(*this).GenerateCovariantThunk(Fn, MD, Extern, Adjustment);
Mike Stump80f6ac52009-09-11 23:25:56 +0000988 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
989 return m;
990}
991
Mike Stumpa5588bf2009-08-26 20:46:33 +0000992llvm::Value *
Anders Carlssonc6d171e2009-10-06 22:43:30 +0000993CodeGenFunction::GetVirtualCXXBaseClassOffset(llvm::Value *This,
994 const CXXRecordDecl *ClassDecl,
995 const CXXRecordDecl *BaseClassDecl) {
Anders Carlssonc6d171e2009-10-06 22:43:30 +0000996 const llvm::Type *Int8PtrTy =
997 llvm::Type::getInt8Ty(VMContext)->getPointerTo();
998
999 llvm::Value *VTablePtr = Builder.CreateBitCast(This,
1000 Int8PtrTy->getPointerTo());
1001 VTablePtr = Builder.CreateLoad(VTablePtr, "vtable");
1002
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001003 int64_t VBaseOffsetIndex =
1004 CGM.getVtableInfo().getVirtualBaseOffsetIndex(ClassDecl, BaseClassDecl);
1005
Anders Carlssonc6d171e2009-10-06 22:43:30 +00001006 llvm::Value *VBaseOffsetPtr =
Mike Stumpb9c9b352009-11-04 01:11:15 +00001007 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetIndex, "vbase.offset.ptr");
Anders Carlssonc6d171e2009-10-06 22:43:30 +00001008 const llvm::Type *PtrDiffTy =
1009 ConvertType(getContext().getPointerDiffType());
1010
1011 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1012 PtrDiffTy->getPointerTo());
1013
1014 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1015
1016 return VBaseOffset;
1017}
1018
Anders Carlssonf942ee02009-11-27 20:47:55 +00001019static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VtableIndex,
Anders Carlssone828c362009-11-13 04:45:41 +00001020 llvm::Value *This, const llvm::Type *Ty) {
1021 Ty = Ty->getPointerTo()->getPointerTo()->getPointerTo();
Anders Carlsson32bfb1c2009-10-03 14:56:57 +00001022
Anders Carlssone828c362009-11-13 04:45:41 +00001023 llvm::Value *Vtable = CGF.Builder.CreateBitCast(This, Ty);
1024 Vtable = CGF.Builder.CreateLoad(Vtable);
1025
1026 llvm::Value *VFuncPtr =
1027 CGF.Builder.CreateConstInBoundsGEP1_64(Vtable, VtableIndex, "vfn");
1028 return CGF.Builder.CreateLoad(VFuncPtr);
1029}
1030
1031llvm::Value *
1032CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
1033 const llvm::Type *Ty) {
1034 MD = MD->getCanonicalDecl();
Anders Carlssonf942ee02009-11-27 20:47:55 +00001035 uint64_t VtableIndex = CGM.getVtableInfo().getMethodVtableIndex(MD);
Anders Carlssone828c362009-11-13 04:45:41 +00001036
1037 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
1038}
1039
1040llvm::Value *
1041CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
1042 llvm::Value *&This, const llvm::Type *Ty) {
1043 DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
Anders Carlssonf942ee02009-11-27 20:47:55 +00001044 uint64_t VtableIndex =
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001045 CGM.getVtableInfo().getMethodVtableIndex(GlobalDecl(DD, Type));
Anders Carlssone828c362009-11-13 04:45:41 +00001046
1047 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
Mike Stumpa5588bf2009-08-26 20:46:33 +00001048}
1049
Fariborz Jahanian56263842009-08-21 18:30:26 +00001050/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1051/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1052/// copy or via a copy constructor call.
Fariborz Jahanian2c73b1d2009-08-26 00:23:27 +00001053// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
Mike Stump11289f42009-09-09 15:08:12 +00001054void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001055 llvm::Value *Src,
1056 const ArrayType *Array,
Mike Stump11289f42009-09-09 15:08:12 +00001057 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001058 QualType Ty) {
1059 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1060 assert(CA && "VLA cannot be copied over");
1061 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
Mike Stump11289f42009-09-09 15:08:12 +00001062
Fariborz Jahanian56263842009-08-21 18:30:26 +00001063 // Create a temporary for the loop index and initialize it with 0.
1064 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1065 "loop.index");
Mike Stump11289f42009-09-09 15:08:12 +00001066 llvm::Value* zeroConstant =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001067 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001068 Builder.CreateStore(zeroConstant, IndexPtr);
Fariborz Jahanian56263842009-08-21 18:30:26 +00001069 // Start the loop with a block that tests the condition.
1070 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1071 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +00001072
Fariborz Jahanian56263842009-08-21 18:30:26 +00001073 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001074
Fariborz Jahanian56263842009-08-21 18:30:26 +00001075 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1076 // Generate: if (loop-index < number-of-elements fall to the loop body,
1077 // otherwise, go to the block after the for-loop.
1078 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Mike Stump11289f42009-09-09 15:08:12 +00001079 llvm::Value * NumElementsPtr =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001080 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1081 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001082 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001083 "isless");
1084 // If the condition is true, execute the body.
1085 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +00001086
Fariborz Jahanian56263842009-08-21 18:30:26 +00001087 EmitBlock(ForBody);
1088 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1089 // Inside the loop body, emit the constructor call on the array element.
1090 Counter = Builder.CreateLoad(IndexPtr);
1091 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1092 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1093 if (BitwiseCopy)
1094 EmitAggregateCopy(Dest, Src, Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001095 else if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001096 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001097 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001098 Ctor_Complete);
1099 CallArgList CallArgs;
1100 // Push the this (Dest) ptr.
1101 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1102 BaseCopyCtor->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001103
Fariborz Jahanian56263842009-08-21 18:30:26 +00001104 // Push the Src ptr.
1105 CallArgs.push_back(std::make_pair(RValue::get(Src),
Mike Stumpb9c9b352009-11-04 01:11:15 +00001106 BaseCopyCtor->getParamDecl(0)->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001107 QualType ResultType =
John McCall9dd450b2009-09-21 23:43:11 +00001108 BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanian56263842009-08-21 18:30:26 +00001109 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1110 Callee, CallArgs, BaseCopyCtor);
1111 }
1112 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001113
Fariborz Jahanian56263842009-08-21 18:30:26 +00001114 // Emit the increment of the loop counter.
1115 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1116 Counter = Builder.CreateLoad(IndexPtr);
1117 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001118 Builder.CreateStore(NextVal, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001119
Fariborz Jahanian56263842009-08-21 18:30:26 +00001120 // Finally, branch back up to the condition for the next iteration.
1121 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001122
Fariborz Jahanian56263842009-08-21 18:30:26 +00001123 // Emit the fall-through block.
1124 EmitBlock(AfterFor, true);
1125}
1126
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001127/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
Mike Stump11289f42009-09-09 15:08:12 +00001128/// array of objects from SrcValue to DestValue. Assignment can be either a
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001129/// bitwise assignment or via a copy assignment operator function call.
1130/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
Mike Stump11289f42009-09-09 15:08:12 +00001131void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001132 llvm::Value *Src,
1133 const ArrayType *Array,
Mike Stump11289f42009-09-09 15:08:12 +00001134 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001135 QualType Ty) {
1136 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1137 assert(CA && "VLA cannot be asssigned");
1138 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
Mike Stump11289f42009-09-09 15:08:12 +00001139
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001140 // Create a temporary for the loop index and initialize it with 0.
1141 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1142 "loop.index");
Mike Stump11289f42009-09-09 15:08:12 +00001143 llvm::Value* zeroConstant =
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001144 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001145 Builder.CreateStore(zeroConstant, IndexPtr);
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001146 // Start the loop with a block that tests the condition.
1147 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1148 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +00001149
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001150 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001151
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001152 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1153 // Generate: if (loop-index < number-of-elements fall to the loop body,
1154 // otherwise, go to the block after the for-loop.
1155 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Mike Stump11289f42009-09-09 15:08:12 +00001156 llvm::Value * NumElementsPtr =
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001157 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1158 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001159 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001160 "isless");
1161 // If the condition is true, execute the body.
1162 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +00001163
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001164 EmitBlock(ForBody);
1165 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1166 // Inside the loop body, emit the assignment operator call on array element.
1167 Counter = Builder.CreateLoad(IndexPtr);
1168 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1169 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1170 const CXXMethodDecl *MD = 0;
1171 if (BitwiseAssign)
1172 EmitAggregateCopy(Dest, Src, Ty);
1173 else {
1174 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1175 MD);
1176 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1177 (void)hasCopyAssign;
John McCall9dd450b2009-09-21 23:43:11 +00001178 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001179 const llvm::Type *LTy =
1180 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1181 FPT->isVariadic());
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001182 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
Mike Stump11289f42009-09-09 15:08:12 +00001183
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001184 CallArgList CallArgs;
1185 // Push the this (Dest) ptr.
1186 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1187 MD->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001188
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001189 // Push the Src ptr.
1190 CallArgs.push_back(std::make_pair(RValue::get(Src),
1191 MD->getParamDecl(0)->getType()));
John McCall9dd450b2009-09-21 23:43:11 +00001192 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001193 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1194 Callee, CallArgs, MD);
1195 }
1196 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001197
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001198 // Emit the increment of the loop counter.
1199 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1200 Counter = Builder.CreateLoad(IndexPtr);
1201 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001202 Builder.CreateStore(NextVal, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001203
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001204 // Finally, branch back up to the condition for the next iteration.
1205 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001206
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001207 // Emit the fall-through block.
1208 EmitBlock(AfterFor, true);
1209}
1210
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001211/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1212/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanian56263842009-08-21 18:30:26 +00001213/// or via a copy constructor call.
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001214void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001215 llvm::Value *Dest, llvm::Value *Src,
Mike Stump11289f42009-09-09 15:08:12 +00001216 const CXXRecordDecl *ClassDecl,
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001217 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1218 if (ClassDecl) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001219 Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
1220 /*NullCheckValue=*/false);
1221 Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
1222 /*NullCheckValue=*/false);
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001223 }
1224 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1225 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001226 return;
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001227 }
Mike Stump11289f42009-09-09 15:08:12 +00001228
1229 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian7c3d7f62009-08-08 00:59:58 +00001230 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001231 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001232 Ctor_Complete);
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001233 CallArgList CallArgs;
1234 // Push the this (Dest) ptr.
1235 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1236 BaseCopyCtor->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001237
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001238 // Push the Src ptr.
1239 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian2a26e352009-08-10 17:20:45 +00001240 BaseCopyCtor->getParamDecl(0)->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001241 QualType ResultType =
John McCall9dd450b2009-09-21 23:43:11 +00001242 BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001243 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1244 Callee, CallArgs, BaseCopyCtor);
1245 }
1246}
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001247
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001248/// EmitClassCopyAssignment - This routine generates code to copy assign a class
Mike Stump11289f42009-09-09 15:08:12 +00001249/// object from SrcValue to DestValue. Assignment can be either a bitwise
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001250/// assignment of via an assignment operator call.
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001251// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001252void CodeGenFunction::EmitClassCopyAssignment(
1253 llvm::Value *Dest, llvm::Value *Src,
Mike Stump11289f42009-09-09 15:08:12 +00001254 const CXXRecordDecl *ClassDecl,
1255 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001256 QualType Ty) {
1257 if (ClassDecl) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001258 Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
1259 /*NullCheckValue=*/false);
1260 Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
1261 /*NullCheckValue=*/false);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001262 }
1263 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1264 EmitAggregateCopy(Dest, Src, Ty);
1265 return;
1266 }
Mike Stump11289f42009-09-09 15:08:12 +00001267
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001268 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001269 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001270 MD);
1271 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1272 (void)ConstCopyAssignOp;
1273
John McCall9dd450b2009-09-21 23:43:11 +00001274 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00001275 const llvm::Type *LTy =
1276 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001277 FPT->isVariadic());
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001278 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
Mike Stump11289f42009-09-09 15:08:12 +00001279
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001280 CallArgList CallArgs;
1281 // Push the this (Dest) ptr.
1282 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1283 MD->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001284
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001285 // Push the Src ptr.
1286 CallArgs.push_back(std::make_pair(RValue::get(Src),
1287 MD->getParamDecl(0)->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001288 QualType ResultType =
John McCall9dd450b2009-09-21 23:43:11 +00001289 MD->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001290 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1291 Callee, CallArgs, MD);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001292}
1293
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001294/// SynthesizeDefaultConstructor - synthesize a default constructor
Mike Stump11289f42009-09-09 15:08:12 +00001295void
Anders Carlssonddf57d32009-09-14 05:32:02 +00001296CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *Ctor,
1297 CXXCtorType Type,
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001298 llvm::Function *Fn,
1299 const FunctionArgList &Args) {
Eli Friedman84a7e342009-11-26 07:40:08 +00001300 assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
Anders Carlssonddf57d32009-09-14 05:32:02 +00001301 StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
1302 SourceLocation());
1303 EmitCtorPrologue(Ctor, Type);
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001304 FinishFunction();
1305}
1306
Mike Stumpb9c9b352009-11-04 01:11:15 +00001307/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a
1308/// copy constructor, in accordance with section 12.8 (p7 and p8) of C++03
Mike Stump11289f42009-09-09 15:08:12 +00001309/// The implicitly-defined copy constructor for class X performs a memberwise
Mike Stumpb9c9b352009-11-04 01:11:15 +00001310/// copy of its subobjects. The order of copying is the same as the order of
1311/// initialization of bases and members in a user-defined constructor
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001312/// Each subobject is copied in the manner appropriate to its type:
Mike Stump11289f42009-09-09 15:08:12 +00001313/// if the subobject is of class type, the copy constructor for the class is
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001314/// used;
Mike Stump11289f42009-09-09 15:08:12 +00001315/// if the subobject is an array, each element is copied, in the manner
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001316/// appropriate to the element type;
Mike Stump11289f42009-09-09 15:08:12 +00001317/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001318/// used.
Mike Stump11289f42009-09-09 15:08:12 +00001319/// Virtual base class subobjects shall be copied only once by the
1320/// implicitly-defined copy constructor
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001321
Anders Carlssonddf57d32009-09-14 05:32:02 +00001322void
1323CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *Ctor,
1324 CXXCtorType Type,
1325 llvm::Function *Fn,
1326 const FunctionArgList &Args) {
Anders Carlsson73fcc952009-09-11 00:07:24 +00001327 const CXXRecordDecl *ClassDecl = Ctor->getParent();
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001328 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Mike Stumpb9c9b352009-11-04 01:11:15 +00001329 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
Eli Friedman84a7e342009-11-26 07:40:08 +00001330 assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
Anders Carlssonddf57d32009-09-14 05:32:02 +00001331 StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
1332 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001333
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001334 FunctionArgList::const_iterator i = Args.begin();
1335 const VarDecl *ThisArg = i->first;
1336 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1337 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1338 const VarDecl *SrcArg = (i+1)->first;
1339 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1340 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
Mike Stump11289f42009-09-09 15:08:12 +00001341
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001342 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1343 Base != ClassDecl->bases_end(); ++Base) {
1344 // FIXME. copy constrution of virtual base NYI
1345 if (Base->isVirtual())
1346 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001347
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001348 CXXRecordDecl *BaseClassDecl
1349 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001350 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1351 Base->getType());
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001352 }
Mike Stump11289f42009-09-09 15:08:12 +00001353
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001354 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1355 E = ClassDecl->field_end(); I != E; ++I) {
1356 const FieldDecl *Field = *I;
1357
1358 QualType FieldType = getContext().getCanonicalType(Field->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001359 const ConstantArrayType *Array =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001360 getContext().getAsConstantArrayType(FieldType);
1361 if (Array)
1362 FieldType = getContext().getBaseElementType(FieldType);
Mike Stump11289f42009-09-09 15:08:12 +00001363
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001364 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1365 CXXRecordDecl *FieldClassDecl
1366 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001367 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1368 LValue RHS = EmitLValueForField(LoadOfSrc, Field, false, 0);
Fariborz Jahanian56263842009-08-21 18:30:26 +00001369 if (Array) {
1370 const llvm::Type *BasePtr = ConvertType(FieldType);
1371 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Mike Stump11289f42009-09-09 15:08:12 +00001372 llvm::Value *DestBaseAddrPtr =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001373 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
Mike Stump11289f42009-09-09 15:08:12 +00001374 llvm::Value *SrcBaseAddrPtr =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001375 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1376 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1377 FieldClassDecl, FieldType);
1378 }
Mike Stump11289f42009-09-09 15:08:12 +00001379 else
1380 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahanian56263842009-08-21 18:30:26 +00001381 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001382 continue;
1383 }
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001384
1385 if (Field->getType()->isReferenceType()) {
1386 unsigned FieldIndex = CGM.getTypes().getLLVMFieldNo(Field);
1387
1388 llvm::Value *LHS = Builder.CreateStructGEP(LoadOfThis, FieldIndex,
1389 "lhs.ref");
1390
1391 llvm::Value *RHS = Builder.CreateStructGEP(LoadOfThis, FieldIndex,
1392 "rhs.ref");
1393
1394 // Load the value in RHS.
1395 RHS = Builder.CreateLoad(RHS);
1396
1397 // And store it in the LHS
1398 Builder.CreateStore(RHS, LHS);
1399
1400 continue;
1401 }
Fariborz Jahanian7cc52cf2009-08-10 18:34:26 +00001402 // Do a built-in assignment of scalar data members.
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001403 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1404 LValue RHS = EmitLValueForField(LoadOfSrc, Field, false, 0);
1405
Eli Friedmanc2ef2152009-11-16 21:47:41 +00001406 if (!hasAggregateLLVMType(Field->getType())) {
1407 RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
1408 EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
1409 } else if (Field->getType()->isAnyComplexType()) {
1410 ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
1411 RHS.isVolatileQualified());
1412 StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
1413 } else {
1414 EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
1415 }
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001416 }
Eli Friedmanbb5008a2009-12-08 06:46:18 +00001417
1418 InitializeVtablePtrs(ClassDecl);
Fariborz Jahanianf6bda5d2009-08-08 19:31:03 +00001419 FinishFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001420}
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001421
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001422/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
Mike Stump11289f42009-09-09 15:08:12 +00001423/// Before the implicitly-declared copy assignment operator for a class is
1424/// implicitly defined, all implicitly- declared copy assignment operators for
1425/// its direct base classes and its nonstatic data members shall have been
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001426/// implicitly defined. [12.8-p12]
Mike Stump11289f42009-09-09 15:08:12 +00001427/// The implicitly-defined copy assignment operator for class X performs
1428/// memberwise assignment of its subob- jects. The direct base classes of X are
1429/// assigned first, in the order of their declaration in
1430/// the base-specifier-list, and then the immediate nonstatic data members of X
1431/// are assigned, in the order in which they were declared in the class
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001432/// definition.Each subobject is assigned in the manner appropriate to its type:
Mike Stump11289f42009-09-09 15:08:12 +00001433/// if the subobject is of class type, the copy assignment operator for the
1434/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001435/// possible virtual overriding functions in more derived classes);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001436///
Mike Stump11289f42009-09-09 15:08:12 +00001437/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001438/// appropriate to the element type;
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001439///
Mike Stump11289f42009-09-09 15:08:12 +00001440/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001441/// used.
1442void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001443 llvm::Function *Fn,
1444 const FunctionArgList &Args) {
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001445
1446 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1447 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1448 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Anders Carlssonddf57d32009-09-14 05:32:02 +00001449 StartFunction(CD, CD->getResultType(), Fn, Args, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001450
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001451 FunctionArgList::const_iterator i = Args.begin();
1452 const VarDecl *ThisArg = i->first;
1453 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1454 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1455 const VarDecl *SrcArg = (i+1)->first;
1456 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1457 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
Mike Stump11289f42009-09-09 15:08:12 +00001458
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001459 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1460 Base != ClassDecl->bases_end(); ++Base) {
1461 // FIXME. copy assignment of virtual base NYI
1462 if (Base->isVirtual())
1463 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001464
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001465 CXXRecordDecl *BaseClassDecl
1466 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1467 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1468 Base->getType());
1469 }
Mike Stump11289f42009-09-09 15:08:12 +00001470
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001471 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1472 FieldEnd = ClassDecl->field_end();
1473 Field != FieldEnd; ++Field) {
1474 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001475 const ConstantArrayType *Array =
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001476 getContext().getAsConstantArrayType(FieldType);
1477 if (Array)
1478 FieldType = getContext().getBaseElementType(FieldType);
Mike Stump11289f42009-09-09 15:08:12 +00001479
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001480 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1481 CXXRecordDecl *FieldClassDecl
1482 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1483 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1484 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001485 if (Array) {
1486 const llvm::Type *BasePtr = ConvertType(FieldType);
1487 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1488 llvm::Value *DestBaseAddrPtr =
1489 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1490 llvm::Value *SrcBaseAddrPtr =
1491 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1492 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1493 FieldClassDecl, FieldType);
1494 }
1495 else
Mike Stump11289f42009-09-09 15:08:12 +00001496 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001497 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001498 continue;
1499 }
1500 // Do a built-in assignment of scalar data members.
1501 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1502 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Eli Friedmancd6a50f2009-12-08 01:57:53 +00001503 if (!hasAggregateLLVMType(Field->getType())) {
1504 RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
1505 EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
1506 } else if (Field->getType()->isAnyComplexType()) {
1507 ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
1508 RHS.isVolatileQualified());
1509 StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
1510 } else {
1511 EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
1512 }
Fariborz Jahanian92b3f472009-08-14 00:01:54 +00001513 }
Mike Stump11289f42009-09-09 15:08:12 +00001514
Fariborz Jahanian92b3f472009-08-14 00:01:54 +00001515 // return *this;
1516 Builder.CreateStore(LoadOfThis, ReturnValue);
Mike Stump11289f42009-09-09 15:08:12 +00001517
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001518 FinishFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001519}
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001520
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001521static void EmitBaseInitializer(CodeGenFunction &CGF,
1522 const CXXRecordDecl *ClassDecl,
1523 CXXBaseOrMemberInitializer *BaseInit,
1524 CXXCtorType CtorType) {
1525 assert(BaseInit->isBaseInitializer() &&
1526 "Must have base initializer!");
1527
1528 llvm::Value *ThisPtr = CGF.LoadCXXThis();
1529
1530 const Type *BaseType = BaseInit->getBaseClass();
1531 CXXRecordDecl *BaseClassDecl =
1532 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Anders Carlsson8c793172009-11-23 17:57:54 +00001533 llvm::Value *V = CGF.GetAddressOfBaseClass(ThisPtr, ClassDecl,
1534 BaseClassDecl,
1535 /*NullCheckValue=*/false);
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001536 CGF.EmitCXXConstructorCall(BaseInit->getConstructor(),
1537 CtorType, V,
1538 BaseInit->const_arg_begin(),
1539 BaseInit->const_arg_end());
1540}
1541
1542static void EmitMemberInitializer(CodeGenFunction &CGF,
1543 const CXXRecordDecl *ClassDecl,
1544 CXXBaseOrMemberInitializer *MemberInit) {
1545 assert(MemberInit->isMemberInitializer() &&
1546 "Must have member initializer!");
1547
1548 // non-static data member initializers.
1549 FieldDecl *Field = MemberInit->getMember();
Eli Friedman5e7d9692009-11-16 23:34:11 +00001550 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001551
1552 llvm::Value *ThisPtr = CGF.LoadCXXThis();
1553 LValue LHS;
1554 if (FieldType->isReferenceType()) {
1555 // FIXME: This is really ugly; should be refactored somehow
1556 unsigned idx = CGF.CGM.getTypes().getLLVMFieldNo(Field);
1557 llvm::Value *V = CGF.Builder.CreateStructGEP(ThisPtr, idx, "tmp");
1558 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
1559 LHS = LValue::MakeAddr(V, CGF.MakeQualifiers(FieldType));
1560 } else {
Eli Friedmanc1daba32009-11-16 22:58:01 +00001561 LHS = CGF.EmitLValueForField(ThisPtr, Field, ClassDecl->isUnion(), 0);
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001562 }
Eli Friedman5e7d9692009-11-16 23:34:11 +00001563
1564 // If we are initializing an anonymous union field, drill down to the field.
1565 if (MemberInit->getAnonUnionMember()) {
1566 Field = MemberInit->getAnonUnionMember();
1567 LHS = CGF.EmitLValueForField(LHS.getAddress(), Field,
1568 /*IsUnion=*/true, 0);
1569 FieldType = Field->getType();
1570 }
1571
1572 // If the field is an array, branch based on the element type.
1573 const ConstantArrayType *Array =
1574 CGF.getContext().getAsConstantArrayType(FieldType);
1575 if (Array)
1576 FieldType = CGF.getContext().getBaseElementType(FieldType);
1577
Eli Friedmane85ef712009-11-16 23:53:01 +00001578 // We lose the constructor for anonymous union members, so handle them
1579 // explicitly.
1580 // FIXME: This is somwhat ugly.
1581 if (MemberInit->getAnonUnionMember() && FieldType->getAs<RecordType>()) {
1582 if (MemberInit->getNumArgs())
1583 CGF.EmitAggExpr(*MemberInit->arg_begin(), LHS.getAddress(),
1584 LHS.isVolatileQualified());
1585 else
1586 CGF.EmitAggregateClear(LHS.getAddress(), Field->getType());
1587 return;
1588 }
1589
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001590 if (FieldType->getAs<RecordType>()) {
Eli Friedman5e7d9692009-11-16 23:34:11 +00001591 assert(MemberInit->getConstructor() &&
1592 "EmitCtorPrologue - no constructor to initialize member");
1593 if (Array) {
1594 const llvm::Type *BasePtr = CGF.ConvertType(FieldType);
1595 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1596 llvm::Value *BaseAddrPtr =
1597 CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1598 CGF.EmitCXXAggrConstructorCall(MemberInit->getConstructor(),
Anders Carlsson3a202f62009-11-24 18:43:52 +00001599 Array, BaseAddrPtr,
1600 MemberInit->const_arg_begin(),
1601 MemberInit->const_arg_end());
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001602 }
Eli Friedman5e7d9692009-11-16 23:34:11 +00001603 else
1604 CGF.EmitCXXConstructorCall(MemberInit->getConstructor(),
1605 Ctor_Complete, LHS.getAddress(),
1606 MemberInit->const_arg_begin(),
1607 MemberInit->const_arg_end());
1608 return;
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001609 }
1610
1611 assert(MemberInit->getNumArgs() == 1 && "Initializer count must be 1 only");
1612 Expr *RhsExpr = *MemberInit->arg_begin();
1613 RValue RHS;
Eli Friedmane85ef712009-11-16 23:53:01 +00001614 if (FieldType->isReferenceType()) {
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001615 RHS = CGF.EmitReferenceBindingToExpr(RhsExpr, FieldType,
1616 /*IsInitializer=*/true);
Fariborz Jahanian03f62ed2009-11-11 17:55:25 +00001617 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Eli Friedmane85ef712009-11-16 23:53:01 +00001618 } else if (Array) {
1619 CGF.EmitMemSetToZero(LHS.getAddress(), Field->getType());
1620 } else if (!CGF.hasAggregateLLVMType(RhsExpr->getType())) {
1621 RHS = RValue::get(CGF.EmitScalarExpr(RhsExpr, true));
1622 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
1623 } else if (RhsExpr->getType()->isAnyComplexType()) {
1624 CGF.EmitComplexExprIntoAddr(RhsExpr, LHS.getAddress(),
1625 LHS.isVolatileQualified());
1626 } else {
1627 // Handle member function pointers; other aggregates shouldn't get this far.
1628 CGF.EmitAggExpr(RhsExpr, LHS.getAddress(), LHS.isVolatileQualified());
1629 }
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001630}
1631
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001632/// EmitCtorPrologue - This routine generates necessary code to initialize
1633/// base classes and non-static data members belonging to this constructor.
Anders Carlsson6b8b4b42009-09-01 18:33:46 +00001634/// FIXME: This needs to take a CXXCtorType.
Anders Carlssonddf57d32009-09-14 05:32:02 +00001635void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1636 CXXCtorType CtorType) {
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001637 const CXXRecordDecl *ClassDecl = CD->getParent();
1638
Mike Stump6b2556f2009-08-06 13:41:24 +00001639 // FIXME: Add vbase initialization
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001640
Fariborz Jahaniandedf1e42009-07-25 21:12:28 +00001641 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001642 E = CD->init_end();
1643 B != E; ++B) {
1644 CXXBaseOrMemberInitializer *Member = (*B);
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001645
Anders Carlsson5852b132009-11-06 04:11:09 +00001646 assert(LiveTemporaries.empty() &&
1647 "Should not have any live temporaries at initializer start!");
1648
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001649 if (Member->isBaseInitializer())
1650 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
1651 else
1652 EmitMemberInitializer(*this, ClassDecl, Member);
Anders Carlsson5852b132009-11-06 04:11:09 +00001653
1654 // Pop any live temporaries that the initializers might have pushed.
1655 while (!LiveTemporaries.empty())
1656 PopCXXTemporary();
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001657 }
Mike Stumpbc78a722009-07-31 18:25:34 +00001658
Eli Friedman80888c72009-12-08 06:54:20 +00001659 InitializeVtablePtrs(ClassDecl);
Eli Friedmanbb5008a2009-12-08 06:46:18 +00001660}
1661
1662void CodeGenFunction::InitializeVtablePtrs(const CXXRecordDecl *ClassDecl) {
Anders Carlsson5a1a84f2009-12-05 18:38:15 +00001663 if (!ClassDecl->isDynamicClass())
1664 return;
1665
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001666 // Initialize the vtable pointer.
1667 // FIXME: This needs to initialize secondary vtable pointers too.
1668 llvm::Value *ThisPtr = LoadCXXThis();
Anders Carlsson5a1a84f2009-12-05 18:38:15 +00001669
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001670 llvm::Constant *Vtable = CGM.getVtableInfo().getVtable(ClassDecl);
1671 uint64_t AddressPoint = CGM.getVtableInfo().getVtableAddressPoint(ClassDecl);
1672
1673 llvm::Value *VtableAddressPoint =
1674 Builder.CreateConstInBoundsGEP2_64(Vtable, 0, AddressPoint);
1675
Anders Carlsson5a1a84f2009-12-05 18:38:15 +00001676 llvm::Value *VtableField =
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001677 Builder.CreateBitCast(ThisPtr,
1678 VtableAddressPoint->getType()->getPointerTo());
1679
1680 Builder.CreateStore(VtableAddressPoint, VtableField);
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001681}
Fariborz Jahanianaa01d2a2009-07-30 17:49:11 +00001682
1683/// EmitDtorEpilogue - Emit all code that comes at the end of class's
Mike Stump11289f42009-09-09 15:08:12 +00001684/// destructor. This is to call destructors on members and base classes
Fariborz Jahanianaa01d2a2009-07-30 17:49:11 +00001685/// in reverse order of their construction.
Anders Carlsson6b8b4b42009-09-01 18:33:46 +00001686/// FIXME: This needs to take a CXXDtorType.
Anders Carlssonddf57d32009-09-14 05:32:02 +00001687void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD,
1688 CXXDtorType DtorType) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001689 assert(!DD->isTrivial() &&
1690 "Should not emit dtor epilogue for trivial dtor!");
Mike Stump11289f42009-09-09 15:08:12 +00001691
Anders Carlssondee9a302009-11-17 04:44:12 +00001692 const CXXRecordDecl *ClassDecl = DD->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00001693
Anders Carlssondee9a302009-11-17 04:44:12 +00001694 // Collect the fields.
1695 llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
1696 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1697 E = ClassDecl->field_end(); I != E; ++I) {
1698 const FieldDecl *Field = *I;
1699
1700 QualType FieldType = getContext().getCanonicalType(Field->getType());
1701 FieldType = getContext().getBaseElementType(FieldType);
1702
1703 const RecordType *RT = FieldType->getAs<RecordType>();
1704 if (!RT)
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001705 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00001706
1707 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1708 if (FieldClassDecl->hasTrivialDestructor())
1709 continue;
1710
1711 FieldDecls.push_back(Field);
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001712 }
Anders Carlssond7872042009-11-15 23:03:25 +00001713
Anders Carlssondee9a302009-11-17 04:44:12 +00001714 // Now destroy the fields.
1715 for (size_t i = FieldDecls.size(); i > 0; --i) {
1716 const FieldDecl *Field = FieldDecls[i - 1];
1717
1718 QualType FieldType = Field->getType();
1719 const ConstantArrayType *Array =
1720 getContext().getAsConstantArrayType(FieldType);
1721 if (Array)
1722 FieldType = getContext().getBaseElementType(FieldType);
1723
1724 const RecordType *RT = FieldType->getAs<RecordType>();
1725 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1726
1727 llvm::Value *ThisPtr = LoadCXXThis();
1728
1729 LValue LHS = EmitLValueForField(ThisPtr, Field,
1730 /*isUnion=*/false,
1731 // FIXME: Qualifiers?
1732 /*CVRQualifiers=*/0);
1733 if (Array) {
1734 const llvm::Type *BasePtr = ConvertType(FieldType);
1735 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1736 llvm::Value *BaseAddrPtr =
1737 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1738 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1739 Array, BaseAddrPtr);
1740 } else
1741 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1742 Dtor_Complete, LHS.getAddress());
1743 }
1744
1745 // Destroy non-virtual bases.
1746 for (CXXRecordDecl::reverse_base_class_const_iterator I =
1747 ClassDecl->bases_rbegin(), E = ClassDecl->bases_rend(); I != E; ++I) {
1748 const CXXBaseSpecifier &Base = *I;
1749
1750 // Ignore virtual bases.
1751 if (Base.isVirtual())
1752 continue;
1753
1754 CXXRecordDecl *BaseClassDecl
1755 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1756
1757 // Ignore trivial destructors.
1758 if (BaseClassDecl->hasTrivialDestructor())
1759 continue;
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001760 const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1761
Anders Carlsson8c793172009-11-23 17:57:54 +00001762 llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1763 ClassDecl, BaseClassDecl,
1764 /*NullCheckValue=*/false);
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001765 EmitCXXDestructorCall(D, Dtor_Base, V);
Anders Carlssondee9a302009-11-17 04:44:12 +00001766 }
1767
1768 // If we're emitting a base destructor, we don't want to emit calls to the
1769 // virtual bases.
1770 if (DtorType == Dtor_Base)
1771 return;
1772
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001773 // Handle virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00001774 for (CXXRecordDecl::reverse_base_class_const_iterator I =
1775 ClassDecl->vbases_rbegin(), E = ClassDecl->vbases_rend(); I != E; ++I) {
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001776 const CXXBaseSpecifier &Base = *I;
1777 CXXRecordDecl *BaseClassDecl
1778 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1779
1780 // Ignore trivial destructors.
1781 if (BaseClassDecl->hasTrivialDestructor())
1782 continue;
1783 const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1784 llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1785 ClassDecl, BaseClassDecl,
1786 /*NullCheckValue=*/false);
1787 EmitCXXDestructorCall(D, Dtor_Base, V);
Anders Carlssondee9a302009-11-17 04:44:12 +00001788 }
1789
1790 // If we have a deleting destructor, emit a call to the delete operator.
Fariborz Jahanian037bcb52009-12-01 23:35:33 +00001791 if (DtorType == Dtor_Deleting) {
1792 assert(DD->getOperatorDelete() &&
1793 "operator delete missing - EmitDtorEpilogue");
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001794 EmitDeleteCall(DD->getOperatorDelete(), LoadCXXThis(),
1795 getContext().getTagDeclType(ClassDecl));
Fariborz Jahanian037bcb52009-12-01 23:35:33 +00001796 }
Fariborz Jahanianaa01d2a2009-07-30 17:49:11 +00001797}
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001798
Anders Carlssonddf57d32009-09-14 05:32:02 +00001799void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *Dtor,
1800 CXXDtorType DtorType,
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001801 llvm::Function *Fn,
1802 const FunctionArgList &Args) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001803 assert(!Dtor->getParent()->hasUserDeclaredDestructor() &&
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001804 "SynthesizeDefaultDestructor - destructor has user declaration");
Mike Stump11289f42009-09-09 15:08:12 +00001805
Anders Carlssonddf57d32009-09-14 05:32:02 +00001806 StartFunction(GlobalDecl(Dtor, DtorType), Dtor->getResultType(), Fn, Args,
1807 SourceLocation());
Anders Carlssondee9a302009-11-17 04:44:12 +00001808
Anders Carlssonddf57d32009-09-14 05:32:02 +00001809 EmitDtorEpilogue(Dtor, DtorType);
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001810 FinishFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001811}