blob: 011257b7499fe09fa9bb43020b85ab7822de5d91 [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)) {
Douglas Gregor357b6fd2009-12-18 05:19:44 +0000582 assert((ICE->getCastKind() == CastExpr::CK_NoOp ||
583 ICE->getCastKind() == CastExpr::CK_ConstructorConversion) &&
584 "Unknown implicit cast kind in constructor elision");
585 Arg = ICE->getSubExpr();
586 }
587
588 if (const CXXBindTemporaryExpr *BindExpr =
589 dyn_cast<CXXBindTemporaryExpr>(Arg))
Anders Carlsson78cfaa92009-11-13 04:34:45 +0000590 Arg = BindExpr->getSubExpr();
591
592 EmitAggExpr(Arg, Dest, false);
Fariborz Jahanian00130932009-08-06 19:12:38 +0000593 return;
Fariborz Jahanianeb869762009-08-06 01:02:49 +0000594 }
Fariborz Jahanian29baa2b2009-10-28 21:07:28 +0000595 if (Array) {
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000596 QualType BaseElementTy = getContext().getBaseElementType(Array);
597 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
598 BasePtr = llvm::PointerType::getUnqual(BasePtr);
599 llvm::Value *BaseAddrPtr =
600 Builder.CreateBitCast(Dest, BasePtr);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000601
Anders Carlsson3a202f62009-11-24 18:43:52 +0000602 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
603 E->arg_begin(), E->arg_end());
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000604 }
605 else
606 // Call the constructor.
607 EmitCXXConstructorCall(CD, Ctor_Complete, Dest,
608 E->arg_begin(), E->arg_end());
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000609}
610
Anders Carlssonf7475242009-04-15 15:55:24 +0000611void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlssondae1abc2009-05-05 04:44:02 +0000612 EmitGlobal(GlobalDecl(D, Ctor_Complete));
613 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlssonf7475242009-04-15 15:55:24 +0000614}
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000615
Mike Stump11289f42009-09-09 15:08:12 +0000616void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000617 CXXCtorType Type) {
Mike Stump11289f42009-09-09 15:08:12 +0000618
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000619 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
Mike Stump11289f42009-09-09 15:08:12 +0000620
Anders Carlsson73fcc952009-09-11 00:07:24 +0000621 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
Mike Stump11289f42009-09-09 15:08:12 +0000622
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000623 SetFunctionDefinitionAttributes(D, Fn);
624 SetLLVMFunctionAttributesForDefinition(D, Fn);
625}
626
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000627llvm::Function *
Mike Stump11289f42009-09-09 15:08:12 +0000628CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000629 CXXCtorType Type) {
Fariborz Jahanianc2d71b52009-11-06 18:47:57 +0000630 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000631 const llvm::FunctionType *FTy =
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000632 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type),
Fariborz Jahanianc2d71b52009-11-06 18:47:57 +0000633 FPT->isVariadic());
Mike Stump11289f42009-09-09 15:08:12 +0000634
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000635 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattnere0be0df2009-05-12 21:21:08 +0000636 return cast<llvm::Function>(
637 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000638}
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000639
Mike Stump11289f42009-09-09 15:08:12 +0000640const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000641 CXXCtorType Type) {
642 llvm::SmallString<256> Name;
Daniel Dunbare128dd12009-11-21 09:06:22 +0000643 getMangleContext().mangleCXXCtor(D, Type, Name);
Mike Stump11289f42009-09-09 15:08:12 +0000644
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000645 Name += '\0';
646 return UniqueMangledName(Name.begin(), Name.end());
647}
648
649void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
Eli Friedmanb572c922009-11-14 04:19:37 +0000650 if (D->isVirtual())
Eli Friedmand777ccc2009-12-15 02:06:15 +0000651 EmitGlobal(GlobalDecl(D, Dtor_Deleting));
652 EmitGlobal(GlobalDecl(D, Dtor_Complete));
653 EmitGlobal(GlobalDecl(D, Dtor_Base));
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000654}
655
Mike Stump11289f42009-09-09 15:08:12 +0000656void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000657 CXXDtorType Type) {
658 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
Mike Stump11289f42009-09-09 15:08:12 +0000659
Anders Carlsson73fcc952009-09-11 00:07:24 +0000660 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
Mike Stump11289f42009-09-09 15:08:12 +0000661
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000662 SetFunctionDefinitionAttributes(D, Fn);
663 SetLLVMFunctionAttributesForDefinition(D, Fn);
664}
665
666llvm::Function *
Mike Stump11289f42009-09-09 15:08:12 +0000667CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000668 CXXDtorType Type) {
669 const llvm::FunctionType *FTy =
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000670 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), false);
Mike Stump11289f42009-09-09 15:08:12 +0000671
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000672 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattnere0be0df2009-05-12 21:21:08 +0000673 return cast<llvm::Function>(
674 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000675}
676
Mike Stump11289f42009-09-09 15:08:12 +0000677const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000678 CXXDtorType Type) {
679 llvm::SmallString<256> Name;
Daniel Dunbare128dd12009-11-21 09:06:22 +0000680 getMangleContext().mangleCXXDtor(D, Type, Name);
Mike Stump11289f42009-09-09 15:08:12 +0000681
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000682 Name += '\0';
683 return UniqueMangledName(Name.begin(), Name.end());
684}
Fariborz Jahanian83381cc2009-07-20 23:18:55 +0000685
Anders Carlssonc7785402009-11-26 02:32:05 +0000686llvm::Constant *
Eli Friedman551fe842009-12-03 04:27:05 +0000687CodeGenFunction::GenerateThunk(llvm::Function *Fn, GlobalDecl GD,
Anders Carlssonc7785402009-11-26 02:32:05 +0000688 bool Extern,
689 const ThunkAdjustment &ThisAdjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000690 return GenerateCovariantThunk(Fn, GD, Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000691 CovariantThunkAdjustment(ThisAdjustment,
692 ThunkAdjustment()));
Mike Stump5a522352009-09-04 18:27:16 +0000693}
694
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000695llvm::Value *
696CodeGenFunction::DynamicTypeAdjust(llvm::Value *V,
697 const ThunkAdjustment &Adjustment) {
698 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
699
Mike Stump77738202009-11-03 16:59:27 +0000700 const llvm::Type *OrigTy = V->getType();
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000701 if (Adjustment.NonVirtual) {
Mike Stump77738202009-11-03 16:59:27 +0000702 // Do the non-virtual adjustment
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000703 V = Builder.CreateBitCast(V, Int8PtrTy);
704 V = Builder.CreateConstInBoundsGEP1_64(V, Adjustment.NonVirtual);
Mike Stump77738202009-11-03 16:59:27 +0000705 V = Builder.CreateBitCast(V, OrigTy);
706 }
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000707
708 if (!Adjustment.Virtual)
709 return V;
710
711 assert(Adjustment.Virtual % (LLVMPointerWidth / 8) == 0 &&
712 "vtable entry unaligned");
713
714 // Do the virtual this adjustment
715 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
716 const llvm::Type *PtrDiffPtrTy = PtrDiffTy->getPointerTo();
717
718 llvm::Value *ThisVal = Builder.CreateBitCast(V, Int8PtrTy);
719 V = Builder.CreateBitCast(V, PtrDiffPtrTy->getPointerTo());
720 V = Builder.CreateLoad(V, "vtable");
721
722 llvm::Value *VTablePtr = V;
723 uint64_t VirtualAdjustment = Adjustment.Virtual / (LLVMPointerWidth / 8);
724 V = Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
725 V = Builder.CreateLoad(V);
726 V = Builder.CreateGEP(ThisVal, V);
727
728 return Builder.CreateBitCast(V, OrigTy);
Mike Stump77738202009-11-03 16:59:27 +0000729}
730
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000731llvm::Constant *
732CodeGenFunction::GenerateCovariantThunk(llvm::Function *Fn,
Eli Friedman551fe842009-12-03 04:27:05 +0000733 GlobalDecl GD, bool Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000734 const CovariantThunkAdjustment &Adjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000735 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump33ccd9e2009-11-02 23:22:01 +0000736 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump80f6ac52009-09-11 23:25:56 +0000737
738 FunctionArgList Args;
739 ImplicitParamDecl *ThisDecl =
740 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
741 MD->getThisType(getContext()));
742 Args.push_back(std::make_pair(ThisDecl, ThisDecl->getType()));
743 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
744 e = MD->param_end();
745 i != e; ++i) {
746 ParmVarDecl *D = *i;
747 Args.push_back(std::make_pair(D, D->getType()));
748 }
749 IdentifierInfo *II
750 = &CGM.getContext().Idents.get("__thunk_named_foo_");
751 FunctionDecl *FD = FunctionDecl::Create(getContext(),
752 getContext().getTranslationUnitDecl(),
Mike Stump33ccd9e2009-11-02 23:22:01 +0000753 SourceLocation(), II, ResultType, 0,
Mike Stump80f6ac52009-09-11 23:25:56 +0000754 Extern
755 ? FunctionDecl::Extern
756 : FunctionDecl::Static,
757 false, true);
Mike Stump33ccd9e2009-11-02 23:22:01 +0000758 StartFunction(FD, ResultType, Fn, Args, SourceLocation());
759
760 // generate body
Mike Stumpf3589722009-11-03 02:12:59 +0000761 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
762 const llvm::Type *Ty =
763 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
764 FPT->isVariadic());
Eli Friedman551fe842009-12-03 04:27:05 +0000765 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000766
Mike Stump33ccd9e2009-11-02 23:22:01 +0000767 CallArgList CallArgs;
768
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000769 bool ShouldAdjustReturnPointer = true;
Mike Stumpf3589722009-11-03 02:12:59 +0000770 QualType ArgType = MD->getThisType(getContext());
771 llvm::Value *Arg = Builder.CreateLoad(LocalDeclMap[ThisDecl], "this");
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000772 if (!Adjustment.ThisAdjustment.isEmpty()) {
Mike Stump77738202009-11-03 16:59:27 +0000773 // Do the this adjustment.
Mike Stump71609a22009-11-04 00:53:51 +0000774 const llvm::Type *OrigTy = Callee->getType();
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000775 Arg = DynamicTypeAdjust(Arg, Adjustment.ThisAdjustment);
776
777 if (!Adjustment.ReturnAdjustment.isEmpty()) {
778 const CovariantThunkAdjustment &ReturnAdjustment =
779 CovariantThunkAdjustment(ThunkAdjustment(),
780 Adjustment.ReturnAdjustment);
781
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000782 Callee = CGM.BuildCovariantThunk(GD, Extern, ReturnAdjustment);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000783
Mike Stump71609a22009-11-04 00:53:51 +0000784 Callee = Builder.CreateBitCast(Callee, OrigTy);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000785 ShouldAdjustReturnPointer = false;
Mike Stump71609a22009-11-04 00:53:51 +0000786 }
787 }
788
Mike Stumpf3589722009-11-03 02:12:59 +0000789 CallArgs.push_back(std::make_pair(RValue::get(Arg), ArgType));
790
Mike Stump33ccd9e2009-11-02 23:22:01 +0000791 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
792 e = MD->param_end();
793 i != e; ++i) {
794 ParmVarDecl *D = *i;
795 QualType ArgType = D->getType();
796
797 // llvm::Value *Arg = CGF.GetAddrOfLocalVar(Dst);
Eli Friedman4039f352009-12-03 04:49:52 +0000798 Expr *Arg = new (getContext()) DeclRefExpr(D, ArgType.getNonReferenceType(),
799 SourceLocation());
Mike Stump33ccd9e2009-11-02 23:22:01 +0000800 CallArgs.push_back(std::make_pair(EmitCallArg(Arg, ArgType), ArgType));
801 }
802
Mike Stump31e1d432009-11-02 23:47:45 +0000803 RValue RV = EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
804 Callee, CallArgs, MD);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000805 if (ShouldAdjustReturnPointer && !Adjustment.ReturnAdjustment.isEmpty()) {
Mike Stumpc5507682009-11-05 06:32:02 +0000806 bool CanBeZero = !(ResultType->isReferenceType()
807 // FIXME: attr nonnull can't be zero either
808 /* || ResultType->hasAttr<NonNullAttr>() */ );
Mike Stump77738202009-11-03 16:59:27 +0000809 // Do the return result adjustment.
Mike Stumpc5507682009-11-05 06:32:02 +0000810 if (CanBeZero) {
811 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
812 llvm::BasicBlock *ZeroBlock = createBasicBlock();
813 llvm::BasicBlock *ContBlock = createBasicBlock();
Mike Stumpb8da7a02009-11-05 06:12:26 +0000814
Mike Stumpc5507682009-11-05 06:32:02 +0000815 const llvm::Type *Ty = RV.getScalarVal()->getType();
816 llvm::Value *Zero = llvm::Constant::getNullValue(Ty);
817 Builder.CreateCondBr(Builder.CreateICmpNE(RV.getScalarVal(), Zero),
818 NonZeroBlock, ZeroBlock);
819 EmitBlock(NonZeroBlock);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000820 llvm::Value *NZ =
821 DynamicTypeAdjust(RV.getScalarVal(), Adjustment.ReturnAdjustment);
Mike Stumpc5507682009-11-05 06:32:02 +0000822 EmitBranch(ContBlock);
823 EmitBlock(ZeroBlock);
824 llvm::Value *Z = RV.getScalarVal();
825 EmitBlock(ContBlock);
826 llvm::PHINode *RVOrZero = Builder.CreatePHI(Ty);
827 RVOrZero->reserveOperandSpace(2);
828 RVOrZero->addIncoming(NZ, NonZeroBlock);
829 RVOrZero->addIncoming(Z, ZeroBlock);
830 RV = RValue::get(RVOrZero);
831 } else
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000832 RV = RValue::get(DynamicTypeAdjust(RV.getScalarVal(),
833 Adjustment.ReturnAdjustment));
Mike Stump33ccd9e2009-11-02 23:22:01 +0000834 }
835
Mike Stump31e1d432009-11-02 23:47:45 +0000836 if (!ResultType->isVoidType())
837 EmitReturnOfRValue(RV, ResultType);
838
Mike Stump80f6ac52009-09-11 23:25:56 +0000839 FinishFunction();
840 return Fn;
841}
842
Anders Carlssonc7785402009-11-26 02:32:05 +0000843llvm::Constant *
Eli Friedman8174f2c2009-12-06 22:01:30 +0000844CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
845 const ThunkAdjustment &ThisAdjustment) {
846 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
847
848 // Compute mangled name
849 llvm::SmallString<256> OutName;
850 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
851 getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(), ThisAdjustment,
852 OutName);
853 else
854 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
855 OutName += '\0';
856 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
857
858 // Get function for mangled name
859 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
860 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
861}
862
863llvm::Constant *
864CodeGenModule::GetAddrOfCovariantThunk(GlobalDecl GD,
865 const CovariantThunkAdjustment &Adjustment) {
866 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
867
868 // Compute mangled name
869 llvm::SmallString<256> OutName;
870 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
871 OutName += '\0';
872 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
873
874 // Get function for mangled name
875 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
876 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
877}
878
879void CodeGenModule::BuildThunksForVirtual(GlobalDecl GD) {
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000880 CGVtableInfo::AdjustmentVectorTy *AdjPtr = getVtableInfo().getAdjustments(GD);
881 if (!AdjPtr)
882 return;
883 CGVtableInfo::AdjustmentVectorTy &Adj = *AdjPtr;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000884 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000885 for (unsigned i = 0; i < Adj.size(); i++) {
886 GlobalDecl OGD = Adj[i].first;
887 const CXXMethodDecl *OMD = cast<CXXMethodDecl>(OGD.getDecl());
Eli Friedman8174f2c2009-12-06 22:01:30 +0000888 QualType nc_oret = OMD->getType()->getAs<FunctionType>()->getResultType();
889 CanQualType oret = getContext().getCanonicalType(nc_oret);
890 QualType nc_ret = MD->getType()->getAs<FunctionType>()->getResultType();
891 CanQualType ret = getContext().getCanonicalType(nc_ret);
892 ThunkAdjustment ReturnAdjustment;
893 if (oret != ret) {
894 QualType qD = nc_ret->getPointeeType();
895 QualType qB = nc_oret->getPointeeType();
896 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
897 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
898 ReturnAdjustment = ComputeThunkAdjustment(D, B);
899 }
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000900 ThunkAdjustment ThisAdjustment = Adj[i].second;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000901 bool Extern = !cast<CXXRecordDecl>(OMD->getDeclContext())->isInAnonymousNamespace();
902 if (!ReturnAdjustment.isEmpty() || !ThisAdjustment.isEmpty()) {
903 CovariantThunkAdjustment CoAdj(ThisAdjustment, ReturnAdjustment);
904 llvm::Constant *FnConst;
905 if (!ReturnAdjustment.isEmpty())
906 FnConst = GetAddrOfCovariantThunk(GD, CoAdj);
907 else
908 FnConst = GetAddrOfThunk(GD, ThisAdjustment);
909 if (!isa<llvm::Function>(FnConst)) {
Eli Friedman31bc3ad2009-12-07 23:56:34 +0000910 llvm::Constant *SubExpr =
911 cast<llvm::ConstantExpr>(FnConst)->getOperand(0);
912 llvm::Function *OldFn = cast<llvm::Function>(SubExpr);
913 std::string Name = OldFn->getNameStr();
914 GlobalDeclMap.erase(UniqueMangledName(Name.data(),
915 Name.data() + Name.size() + 1));
916 llvm::Constant *NewFnConst;
917 if (!ReturnAdjustment.isEmpty())
918 NewFnConst = GetAddrOfCovariantThunk(GD, CoAdj);
919 else
920 NewFnConst = GetAddrOfThunk(GD, ThisAdjustment);
921 llvm::Function *NewFn = cast<llvm::Function>(NewFnConst);
922 NewFn->takeName(OldFn);
923 llvm::Constant *NewPtrForOldDecl =
924 llvm::ConstantExpr::getBitCast(NewFn, OldFn->getType());
925 OldFn->replaceAllUsesWith(NewPtrForOldDecl);
926 OldFn->eraseFromParent();
927 FnConst = NewFn;
Eli Friedman8174f2c2009-12-06 22:01:30 +0000928 }
929 llvm::Function *Fn = cast<llvm::Function>(FnConst);
930 if (Fn->isDeclaration()) {
931 llvm::GlobalVariable::LinkageTypes linktype;
932 linktype = llvm::GlobalValue::WeakAnyLinkage;
933 if (!Extern)
934 linktype = llvm::GlobalValue::InternalLinkage;
935 Fn->setLinkage(linktype);
936 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
937 Fn->addFnAttr(llvm::Attribute::NoUnwind);
938 Fn->setAlignment(2);
939 CodeGenFunction(*this).GenerateCovariantThunk(Fn, GD, Extern, CoAdj);
940 }
941 }
Eli Friedman8174f2c2009-12-06 22:01:30 +0000942 }
943}
944
945llvm::Constant *
Eli Friedman551fe842009-12-03 04:27:05 +0000946CodeGenModule::BuildThunk(GlobalDecl GD, bool Extern,
Anders Carlssonc7785402009-11-26 02:32:05 +0000947 const ThunkAdjustment &ThisAdjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000948 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump5a522352009-09-04 18:27:16 +0000949 llvm::SmallString<256> OutName;
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000950 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(MD)) {
951 getMangleContext().mangleCXXDtorThunk(D, GD.getDtorType(), ThisAdjustment,
952 OutName);
953 } else
954 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
Anders Carlssonc7785402009-11-26 02:32:05 +0000955
Mike Stump5a522352009-09-04 18:27:16 +0000956 llvm::GlobalVariable::LinkageTypes linktype;
957 linktype = llvm::GlobalValue::WeakAnyLinkage;
958 if (!Extern)
959 linktype = llvm::GlobalValue::InternalLinkage;
960 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
John McCall9dd450b2009-09-21 23:43:11 +0000961 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump5a522352009-09-04 18:27:16 +0000962 const llvm::FunctionType *FTy =
963 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
964 FPT->isVariadic());
965
Daniel Dunbare128dd12009-11-21 09:06:22 +0000966 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
Mike Stump5a522352009-09-04 18:27:16 +0000967 &getModule());
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000968 CodeGenFunction(*this).GenerateThunk(Fn, GD, Extern, ThisAdjustment);
Mike Stump5a522352009-09-04 18:27:16 +0000969 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
970 return m;
971}
972
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000973llvm::Constant *
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000974CodeGenModule::BuildCovariantThunk(const GlobalDecl &GD, bool Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000975 const CovariantThunkAdjustment &Adjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000976 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump80f6ac52009-09-11 23:25:56 +0000977 llvm::SmallString<256> OutName;
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000978 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
Mike Stump80f6ac52009-09-11 23:25:56 +0000979 llvm::GlobalVariable::LinkageTypes linktype;
980 linktype = llvm::GlobalValue::WeakAnyLinkage;
981 if (!Extern)
982 linktype = llvm::GlobalValue::InternalLinkage;
983 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
John McCall9dd450b2009-09-21 23:43:11 +0000984 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump80f6ac52009-09-11 23:25:56 +0000985 const llvm::FunctionType *FTy =
986 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
987 FPT->isVariadic());
988
Daniel Dunbare128dd12009-11-21 09:06:22 +0000989 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
Mike Stump80f6ac52009-09-11 23:25:56 +0000990 &getModule());
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000991 CodeGenFunction(*this).GenerateCovariantThunk(Fn, MD, Extern, Adjustment);
Mike Stump80f6ac52009-09-11 23:25:56 +0000992 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
993 return m;
994}
995
Mike Stumpa5588bf2009-08-26 20:46:33 +0000996llvm::Value *
Anders Carlssonc6d171e2009-10-06 22:43:30 +0000997CodeGenFunction::GetVirtualCXXBaseClassOffset(llvm::Value *This,
998 const CXXRecordDecl *ClassDecl,
999 const CXXRecordDecl *BaseClassDecl) {
Anders Carlssonc6d171e2009-10-06 22:43:30 +00001000 const llvm::Type *Int8PtrTy =
1001 llvm::Type::getInt8Ty(VMContext)->getPointerTo();
1002
1003 llvm::Value *VTablePtr = Builder.CreateBitCast(This,
1004 Int8PtrTy->getPointerTo());
1005 VTablePtr = Builder.CreateLoad(VTablePtr, "vtable");
1006
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001007 int64_t VBaseOffsetIndex =
1008 CGM.getVtableInfo().getVirtualBaseOffsetIndex(ClassDecl, BaseClassDecl);
1009
Anders Carlssonc6d171e2009-10-06 22:43:30 +00001010 llvm::Value *VBaseOffsetPtr =
Mike Stumpb9c9b352009-11-04 01:11:15 +00001011 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetIndex, "vbase.offset.ptr");
Anders Carlssonc6d171e2009-10-06 22:43:30 +00001012 const llvm::Type *PtrDiffTy =
1013 ConvertType(getContext().getPointerDiffType());
1014
1015 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1016 PtrDiffTy->getPointerTo());
1017
1018 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1019
1020 return VBaseOffset;
1021}
1022
Anders Carlssonf942ee02009-11-27 20:47:55 +00001023static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VtableIndex,
Anders Carlssone828c362009-11-13 04:45:41 +00001024 llvm::Value *This, const llvm::Type *Ty) {
1025 Ty = Ty->getPointerTo()->getPointerTo()->getPointerTo();
Anders Carlsson32bfb1c2009-10-03 14:56:57 +00001026
Anders Carlssone828c362009-11-13 04:45:41 +00001027 llvm::Value *Vtable = CGF.Builder.CreateBitCast(This, Ty);
1028 Vtable = CGF.Builder.CreateLoad(Vtable);
1029
1030 llvm::Value *VFuncPtr =
1031 CGF.Builder.CreateConstInBoundsGEP1_64(Vtable, VtableIndex, "vfn");
1032 return CGF.Builder.CreateLoad(VFuncPtr);
1033}
1034
1035llvm::Value *
1036CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
1037 const llvm::Type *Ty) {
1038 MD = MD->getCanonicalDecl();
Anders Carlssonf942ee02009-11-27 20:47:55 +00001039 uint64_t VtableIndex = CGM.getVtableInfo().getMethodVtableIndex(MD);
Anders Carlssone828c362009-11-13 04:45:41 +00001040
1041 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
1042}
1043
1044llvm::Value *
1045CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
1046 llvm::Value *&This, const llvm::Type *Ty) {
1047 DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
Anders Carlssonf942ee02009-11-27 20:47:55 +00001048 uint64_t VtableIndex =
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001049 CGM.getVtableInfo().getMethodVtableIndex(GlobalDecl(DD, Type));
Anders Carlssone828c362009-11-13 04:45:41 +00001050
1051 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
Mike Stumpa5588bf2009-08-26 20:46:33 +00001052}
1053
Fariborz Jahanian56263842009-08-21 18:30:26 +00001054/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1055/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1056/// copy or via a copy constructor call.
Fariborz Jahanian2c73b1d2009-08-26 00:23:27 +00001057// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
Mike Stump11289f42009-09-09 15:08:12 +00001058void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001059 llvm::Value *Src,
1060 const ArrayType *Array,
Mike Stump11289f42009-09-09 15:08:12 +00001061 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001062 QualType Ty) {
1063 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1064 assert(CA && "VLA cannot be copied over");
1065 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
Mike Stump11289f42009-09-09 15:08:12 +00001066
Fariborz Jahanian56263842009-08-21 18:30:26 +00001067 // Create a temporary for the loop index and initialize it with 0.
1068 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1069 "loop.index");
Mike Stump11289f42009-09-09 15:08:12 +00001070 llvm::Value* zeroConstant =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001071 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001072 Builder.CreateStore(zeroConstant, IndexPtr);
Fariborz Jahanian56263842009-08-21 18:30:26 +00001073 // Start the loop with a block that tests the condition.
1074 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1075 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +00001076
Fariborz Jahanian56263842009-08-21 18:30:26 +00001077 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001078
Fariborz Jahanian56263842009-08-21 18:30:26 +00001079 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1080 // Generate: if (loop-index < number-of-elements fall to the loop body,
1081 // otherwise, go to the block after the for-loop.
1082 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Mike Stump11289f42009-09-09 15:08:12 +00001083 llvm::Value * NumElementsPtr =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001084 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1085 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001086 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001087 "isless");
1088 // If the condition is true, execute the body.
1089 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +00001090
Fariborz Jahanian56263842009-08-21 18:30:26 +00001091 EmitBlock(ForBody);
1092 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1093 // Inside the loop body, emit the constructor call on the array element.
1094 Counter = Builder.CreateLoad(IndexPtr);
1095 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1096 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1097 if (BitwiseCopy)
1098 EmitAggregateCopy(Dest, Src, Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001099 else if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001100 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001101 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001102 Ctor_Complete);
1103 CallArgList CallArgs;
1104 // Push the this (Dest) ptr.
1105 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1106 BaseCopyCtor->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001107
Fariborz Jahanian56263842009-08-21 18:30:26 +00001108 // Push the Src ptr.
1109 CallArgs.push_back(std::make_pair(RValue::get(Src),
Mike Stumpb9c9b352009-11-04 01:11:15 +00001110 BaseCopyCtor->getParamDecl(0)->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001111 QualType ResultType =
John McCall9dd450b2009-09-21 23:43:11 +00001112 BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanian56263842009-08-21 18:30:26 +00001113 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1114 Callee, CallArgs, BaseCopyCtor);
1115 }
1116 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001117
Fariborz Jahanian56263842009-08-21 18:30:26 +00001118 // Emit the increment of the loop counter.
1119 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1120 Counter = Builder.CreateLoad(IndexPtr);
1121 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001122 Builder.CreateStore(NextVal, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001123
Fariborz Jahanian56263842009-08-21 18:30:26 +00001124 // Finally, branch back up to the condition for the next iteration.
1125 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001126
Fariborz Jahanian56263842009-08-21 18:30:26 +00001127 // Emit the fall-through block.
1128 EmitBlock(AfterFor, true);
1129}
1130
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001131/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
Mike Stump11289f42009-09-09 15:08:12 +00001132/// array of objects from SrcValue to DestValue. Assignment can be either a
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001133/// bitwise assignment or via a copy assignment operator function call.
1134/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
Mike Stump11289f42009-09-09 15:08:12 +00001135void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001136 llvm::Value *Src,
1137 const ArrayType *Array,
Mike Stump11289f42009-09-09 15:08:12 +00001138 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001139 QualType Ty) {
1140 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1141 assert(CA && "VLA cannot be asssigned");
1142 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
Mike Stump11289f42009-09-09 15:08:12 +00001143
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001144 // Create a temporary for the loop index and initialize it with 0.
1145 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1146 "loop.index");
Mike Stump11289f42009-09-09 15:08:12 +00001147 llvm::Value* zeroConstant =
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001148 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001149 Builder.CreateStore(zeroConstant, IndexPtr);
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001150 // Start the loop with a block that tests the condition.
1151 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1152 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +00001153
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001154 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001155
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001156 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1157 // Generate: if (loop-index < number-of-elements fall to the loop body,
1158 // otherwise, go to the block after the for-loop.
1159 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Mike Stump11289f42009-09-09 15:08:12 +00001160 llvm::Value * NumElementsPtr =
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001161 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1162 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001163 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001164 "isless");
1165 // If the condition is true, execute the body.
1166 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +00001167
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001168 EmitBlock(ForBody);
1169 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1170 // Inside the loop body, emit the assignment operator call on array element.
1171 Counter = Builder.CreateLoad(IndexPtr);
1172 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1173 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1174 const CXXMethodDecl *MD = 0;
1175 if (BitwiseAssign)
1176 EmitAggregateCopy(Dest, Src, Ty);
1177 else {
1178 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1179 MD);
1180 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1181 (void)hasCopyAssign;
John McCall9dd450b2009-09-21 23:43:11 +00001182 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001183 const llvm::Type *LTy =
1184 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1185 FPT->isVariadic());
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001186 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
Mike Stump11289f42009-09-09 15:08:12 +00001187
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001188 CallArgList CallArgs;
1189 // Push the this (Dest) ptr.
1190 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1191 MD->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001192
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001193 // Push the Src ptr.
1194 CallArgs.push_back(std::make_pair(RValue::get(Src),
1195 MD->getParamDecl(0)->getType()));
John McCall9dd450b2009-09-21 23:43:11 +00001196 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001197 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1198 Callee, CallArgs, MD);
1199 }
1200 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001201
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001202 // Emit the increment of the loop counter.
1203 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1204 Counter = Builder.CreateLoad(IndexPtr);
1205 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001206 Builder.CreateStore(NextVal, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001207
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001208 // Finally, branch back up to the condition for the next iteration.
1209 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001210
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001211 // Emit the fall-through block.
1212 EmitBlock(AfterFor, true);
1213}
1214
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001215/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1216/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanian56263842009-08-21 18:30:26 +00001217/// or via a copy constructor call.
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001218void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001219 llvm::Value *Dest, llvm::Value *Src,
Mike Stump11289f42009-09-09 15:08:12 +00001220 const CXXRecordDecl *ClassDecl,
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001221 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1222 if (ClassDecl) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001223 Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
1224 /*NullCheckValue=*/false);
1225 Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
1226 /*NullCheckValue=*/false);
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001227 }
1228 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1229 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001230 return;
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001231 }
Mike Stump11289f42009-09-09 15:08:12 +00001232
1233 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian7c3d7f62009-08-08 00:59:58 +00001234 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001235 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001236 Ctor_Complete);
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001237 CallArgList CallArgs;
1238 // Push the this (Dest) ptr.
1239 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1240 BaseCopyCtor->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001241
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001242 // Push the Src ptr.
1243 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian2a26e352009-08-10 17:20:45 +00001244 BaseCopyCtor->getParamDecl(0)->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001245 QualType ResultType =
John McCall9dd450b2009-09-21 23:43:11 +00001246 BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001247 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1248 Callee, CallArgs, BaseCopyCtor);
1249 }
1250}
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001251
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001252/// EmitClassCopyAssignment - This routine generates code to copy assign a class
Mike Stump11289f42009-09-09 15:08:12 +00001253/// object from SrcValue to DestValue. Assignment can be either a bitwise
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001254/// assignment of via an assignment operator call.
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001255// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001256void CodeGenFunction::EmitClassCopyAssignment(
1257 llvm::Value *Dest, llvm::Value *Src,
Mike Stump11289f42009-09-09 15:08:12 +00001258 const CXXRecordDecl *ClassDecl,
1259 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001260 QualType Ty) {
1261 if (ClassDecl) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001262 Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
1263 /*NullCheckValue=*/false);
1264 Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
1265 /*NullCheckValue=*/false);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001266 }
1267 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1268 EmitAggregateCopy(Dest, Src, Ty);
1269 return;
1270 }
Mike Stump11289f42009-09-09 15:08:12 +00001271
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001272 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001273 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001274 MD);
1275 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1276 (void)ConstCopyAssignOp;
1277
John McCall9dd450b2009-09-21 23:43:11 +00001278 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00001279 const llvm::Type *LTy =
1280 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001281 FPT->isVariadic());
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001282 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
Mike Stump11289f42009-09-09 15:08:12 +00001283
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001284 CallArgList CallArgs;
1285 // Push the this (Dest) ptr.
1286 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1287 MD->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001288
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001289 // Push the Src ptr.
1290 CallArgs.push_back(std::make_pair(RValue::get(Src),
1291 MD->getParamDecl(0)->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001292 QualType ResultType =
John McCall9dd450b2009-09-21 23:43:11 +00001293 MD->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001294 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1295 Callee, CallArgs, MD);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001296}
1297
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001298/// SynthesizeDefaultConstructor - synthesize a default constructor
Mike Stump11289f42009-09-09 15:08:12 +00001299void
Anders Carlssonddf57d32009-09-14 05:32:02 +00001300CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *Ctor,
1301 CXXCtorType Type,
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001302 llvm::Function *Fn,
1303 const FunctionArgList &Args) {
Eli Friedman84a7e342009-11-26 07:40:08 +00001304 assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
Anders Carlssonddf57d32009-09-14 05:32:02 +00001305 StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
1306 SourceLocation());
1307 EmitCtorPrologue(Ctor, Type);
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001308 FinishFunction();
1309}
1310
Mike Stumpb9c9b352009-11-04 01:11:15 +00001311/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a
1312/// copy constructor, in accordance with section 12.8 (p7 and p8) of C++03
Mike Stump11289f42009-09-09 15:08:12 +00001313/// The implicitly-defined copy constructor for class X performs a memberwise
Mike Stumpb9c9b352009-11-04 01:11:15 +00001314/// copy of its subobjects. The order of copying is the same as the order of
1315/// initialization of bases and members in a user-defined constructor
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001316/// Each subobject is copied in the manner appropriate to its type:
Mike Stump11289f42009-09-09 15:08:12 +00001317/// if the subobject is of class type, the copy constructor for the class is
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001318/// used;
Mike Stump11289f42009-09-09 15:08:12 +00001319/// if the subobject is an array, each element is copied, in the manner
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001320/// appropriate to the element type;
Mike Stump11289f42009-09-09 15:08:12 +00001321/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001322/// used.
Mike Stump11289f42009-09-09 15:08:12 +00001323/// Virtual base class subobjects shall be copied only once by the
1324/// implicitly-defined copy constructor
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001325
Anders Carlssonddf57d32009-09-14 05:32:02 +00001326void
1327CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *Ctor,
1328 CXXCtorType Type,
1329 llvm::Function *Fn,
1330 const FunctionArgList &Args) {
Anders Carlsson73fcc952009-09-11 00:07:24 +00001331 const CXXRecordDecl *ClassDecl = Ctor->getParent();
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001332 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Mike Stumpb9c9b352009-11-04 01:11:15 +00001333 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
Eli Friedman84a7e342009-11-26 07:40:08 +00001334 assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
Anders Carlssonddf57d32009-09-14 05:32:02 +00001335 StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
1336 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001337
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001338 FunctionArgList::const_iterator i = Args.begin();
1339 const VarDecl *ThisArg = i->first;
1340 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1341 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1342 const VarDecl *SrcArg = (i+1)->first;
1343 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1344 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
Mike Stump11289f42009-09-09 15:08:12 +00001345
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001346 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1347 Base != ClassDecl->bases_end(); ++Base) {
1348 // FIXME. copy constrution of virtual base NYI
1349 if (Base->isVirtual())
1350 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001351
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001352 CXXRecordDecl *BaseClassDecl
1353 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001354 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1355 Base->getType());
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001356 }
Mike Stump11289f42009-09-09 15:08:12 +00001357
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001358 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1359 E = ClassDecl->field_end(); I != E; ++I) {
1360 const FieldDecl *Field = *I;
1361
1362 QualType FieldType = getContext().getCanonicalType(Field->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001363 const ConstantArrayType *Array =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001364 getContext().getAsConstantArrayType(FieldType);
1365 if (Array)
1366 FieldType = getContext().getBaseElementType(FieldType);
Mike Stump11289f42009-09-09 15:08:12 +00001367
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001368 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1369 CXXRecordDecl *FieldClassDecl
1370 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001371 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1372 LValue RHS = EmitLValueForField(LoadOfSrc, Field, false, 0);
Fariborz Jahanian56263842009-08-21 18:30:26 +00001373 if (Array) {
1374 const llvm::Type *BasePtr = ConvertType(FieldType);
1375 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Mike Stump11289f42009-09-09 15:08:12 +00001376 llvm::Value *DestBaseAddrPtr =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001377 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
Mike Stump11289f42009-09-09 15:08:12 +00001378 llvm::Value *SrcBaseAddrPtr =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001379 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1380 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1381 FieldClassDecl, FieldType);
1382 }
Mike Stump11289f42009-09-09 15:08:12 +00001383 else
1384 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahanian56263842009-08-21 18:30:26 +00001385 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001386 continue;
1387 }
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001388
1389 if (Field->getType()->isReferenceType()) {
1390 unsigned FieldIndex = CGM.getTypes().getLLVMFieldNo(Field);
1391
1392 llvm::Value *LHS = Builder.CreateStructGEP(LoadOfThis, FieldIndex,
1393 "lhs.ref");
1394
1395 llvm::Value *RHS = Builder.CreateStructGEP(LoadOfThis, FieldIndex,
1396 "rhs.ref");
1397
1398 // Load the value in RHS.
1399 RHS = Builder.CreateLoad(RHS);
1400
1401 // And store it in the LHS
1402 Builder.CreateStore(RHS, LHS);
1403
1404 continue;
1405 }
Fariborz Jahanian7cc52cf2009-08-10 18:34:26 +00001406 // Do a built-in assignment of scalar data members.
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001407 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1408 LValue RHS = EmitLValueForField(LoadOfSrc, Field, false, 0);
1409
Eli Friedmanc2ef2152009-11-16 21:47:41 +00001410 if (!hasAggregateLLVMType(Field->getType())) {
1411 RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
1412 EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
1413 } else if (Field->getType()->isAnyComplexType()) {
1414 ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
1415 RHS.isVolatileQualified());
1416 StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
1417 } else {
1418 EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
1419 }
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001420 }
Eli Friedmanbb5008a2009-12-08 06:46:18 +00001421
1422 InitializeVtablePtrs(ClassDecl);
Fariborz Jahanianf6bda5d2009-08-08 19:31:03 +00001423 FinishFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001424}
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001425
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001426/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
Mike Stump11289f42009-09-09 15:08:12 +00001427/// Before the implicitly-declared copy assignment operator for a class is
1428/// implicitly defined, all implicitly- declared copy assignment operators for
1429/// its direct base classes and its nonstatic data members shall have been
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001430/// implicitly defined. [12.8-p12]
Mike Stump11289f42009-09-09 15:08:12 +00001431/// The implicitly-defined copy assignment operator for class X performs
1432/// memberwise assignment of its subob- jects. The direct base classes of X are
1433/// assigned first, in the order of their declaration in
1434/// the base-specifier-list, and then the immediate nonstatic data members of X
1435/// are assigned, in the order in which they were declared in the class
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001436/// definition.Each subobject is assigned in the manner appropriate to its type:
Mike Stump11289f42009-09-09 15:08:12 +00001437/// if the subobject is of class type, the copy assignment operator for the
1438/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001439/// possible virtual overriding functions in more derived classes);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001440///
Mike Stump11289f42009-09-09 15:08:12 +00001441/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001442/// appropriate to the element type;
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001443///
Mike Stump11289f42009-09-09 15:08:12 +00001444/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001445/// used.
1446void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001447 llvm::Function *Fn,
1448 const FunctionArgList &Args) {
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001449
1450 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1451 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1452 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Anders Carlssonddf57d32009-09-14 05:32:02 +00001453 StartFunction(CD, CD->getResultType(), Fn, Args, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001454
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001455 FunctionArgList::const_iterator i = Args.begin();
1456 const VarDecl *ThisArg = i->first;
1457 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1458 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1459 const VarDecl *SrcArg = (i+1)->first;
1460 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1461 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
Mike Stump11289f42009-09-09 15:08:12 +00001462
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001463 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1464 Base != ClassDecl->bases_end(); ++Base) {
1465 // FIXME. copy assignment of virtual base NYI
1466 if (Base->isVirtual())
1467 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001468
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001469 CXXRecordDecl *BaseClassDecl
1470 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1471 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1472 Base->getType());
1473 }
Mike Stump11289f42009-09-09 15:08:12 +00001474
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001475 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1476 FieldEnd = ClassDecl->field_end();
1477 Field != FieldEnd; ++Field) {
1478 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001479 const ConstantArrayType *Array =
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001480 getContext().getAsConstantArrayType(FieldType);
1481 if (Array)
1482 FieldType = getContext().getBaseElementType(FieldType);
Mike Stump11289f42009-09-09 15:08:12 +00001483
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001484 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1485 CXXRecordDecl *FieldClassDecl
1486 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1487 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1488 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001489 if (Array) {
1490 const llvm::Type *BasePtr = ConvertType(FieldType);
1491 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1492 llvm::Value *DestBaseAddrPtr =
1493 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1494 llvm::Value *SrcBaseAddrPtr =
1495 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1496 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1497 FieldClassDecl, FieldType);
1498 }
1499 else
Mike Stump11289f42009-09-09 15:08:12 +00001500 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001501 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001502 continue;
1503 }
1504 // Do a built-in assignment of scalar data members.
1505 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1506 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Eli Friedmancd6a50f2009-12-08 01:57:53 +00001507 if (!hasAggregateLLVMType(Field->getType())) {
1508 RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
1509 EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
1510 } else if (Field->getType()->isAnyComplexType()) {
1511 ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
1512 RHS.isVolatileQualified());
1513 StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
1514 } else {
1515 EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
1516 }
Fariborz Jahanian92b3f472009-08-14 00:01:54 +00001517 }
Mike Stump11289f42009-09-09 15:08:12 +00001518
Fariborz Jahanian92b3f472009-08-14 00:01:54 +00001519 // return *this;
1520 Builder.CreateStore(LoadOfThis, ReturnValue);
Mike Stump11289f42009-09-09 15:08:12 +00001521
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001522 FinishFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001523}
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001524
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001525static void EmitBaseInitializer(CodeGenFunction &CGF,
1526 const CXXRecordDecl *ClassDecl,
1527 CXXBaseOrMemberInitializer *BaseInit,
1528 CXXCtorType CtorType) {
1529 assert(BaseInit->isBaseInitializer() &&
1530 "Must have base initializer!");
1531
1532 llvm::Value *ThisPtr = CGF.LoadCXXThis();
1533
1534 const Type *BaseType = BaseInit->getBaseClass();
1535 CXXRecordDecl *BaseClassDecl =
1536 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Anders Carlsson8c793172009-11-23 17:57:54 +00001537 llvm::Value *V = CGF.GetAddressOfBaseClass(ThisPtr, ClassDecl,
1538 BaseClassDecl,
1539 /*NullCheckValue=*/false);
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001540 CGF.EmitCXXConstructorCall(BaseInit->getConstructor(),
1541 CtorType, V,
1542 BaseInit->const_arg_begin(),
1543 BaseInit->const_arg_end());
1544}
1545
1546static void EmitMemberInitializer(CodeGenFunction &CGF,
1547 const CXXRecordDecl *ClassDecl,
1548 CXXBaseOrMemberInitializer *MemberInit) {
1549 assert(MemberInit->isMemberInitializer() &&
1550 "Must have member initializer!");
1551
1552 // non-static data member initializers.
1553 FieldDecl *Field = MemberInit->getMember();
Eli Friedman5e7d9692009-11-16 23:34:11 +00001554 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001555
1556 llvm::Value *ThisPtr = CGF.LoadCXXThis();
1557 LValue LHS;
1558 if (FieldType->isReferenceType()) {
1559 // FIXME: This is really ugly; should be refactored somehow
1560 unsigned idx = CGF.CGM.getTypes().getLLVMFieldNo(Field);
1561 llvm::Value *V = CGF.Builder.CreateStructGEP(ThisPtr, idx, "tmp");
1562 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
1563 LHS = LValue::MakeAddr(V, CGF.MakeQualifiers(FieldType));
1564 } else {
Eli Friedmanc1daba32009-11-16 22:58:01 +00001565 LHS = CGF.EmitLValueForField(ThisPtr, Field, ClassDecl->isUnion(), 0);
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001566 }
Eli Friedman5e7d9692009-11-16 23:34:11 +00001567
1568 // If we are initializing an anonymous union field, drill down to the field.
1569 if (MemberInit->getAnonUnionMember()) {
1570 Field = MemberInit->getAnonUnionMember();
1571 LHS = CGF.EmitLValueForField(LHS.getAddress(), Field,
1572 /*IsUnion=*/true, 0);
1573 FieldType = Field->getType();
1574 }
1575
1576 // If the field is an array, branch based on the element type.
1577 const ConstantArrayType *Array =
1578 CGF.getContext().getAsConstantArrayType(FieldType);
1579 if (Array)
1580 FieldType = CGF.getContext().getBaseElementType(FieldType);
1581
Eli Friedmane85ef712009-11-16 23:53:01 +00001582 // We lose the constructor for anonymous union members, so handle them
1583 // explicitly.
1584 // FIXME: This is somwhat ugly.
1585 if (MemberInit->getAnonUnionMember() && FieldType->getAs<RecordType>()) {
1586 if (MemberInit->getNumArgs())
1587 CGF.EmitAggExpr(*MemberInit->arg_begin(), LHS.getAddress(),
1588 LHS.isVolatileQualified());
1589 else
1590 CGF.EmitAggregateClear(LHS.getAddress(), Field->getType());
1591 return;
1592 }
1593
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001594 if (FieldType->getAs<RecordType>()) {
Eli Friedman5e7d9692009-11-16 23:34:11 +00001595 assert(MemberInit->getConstructor() &&
1596 "EmitCtorPrologue - no constructor to initialize member");
1597 if (Array) {
1598 const llvm::Type *BasePtr = CGF.ConvertType(FieldType);
1599 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1600 llvm::Value *BaseAddrPtr =
1601 CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1602 CGF.EmitCXXAggrConstructorCall(MemberInit->getConstructor(),
Anders Carlsson3a202f62009-11-24 18:43:52 +00001603 Array, BaseAddrPtr,
1604 MemberInit->const_arg_begin(),
1605 MemberInit->const_arg_end());
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001606 }
Eli Friedman5e7d9692009-11-16 23:34:11 +00001607 else
1608 CGF.EmitCXXConstructorCall(MemberInit->getConstructor(),
1609 Ctor_Complete, LHS.getAddress(),
1610 MemberInit->const_arg_begin(),
1611 MemberInit->const_arg_end());
1612 return;
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001613 }
1614
1615 assert(MemberInit->getNumArgs() == 1 && "Initializer count must be 1 only");
1616 Expr *RhsExpr = *MemberInit->arg_begin();
1617 RValue RHS;
Eli Friedmane85ef712009-11-16 23:53:01 +00001618 if (FieldType->isReferenceType()) {
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001619 RHS = CGF.EmitReferenceBindingToExpr(RhsExpr, FieldType,
1620 /*IsInitializer=*/true);
Fariborz Jahanian03f62ed2009-11-11 17:55:25 +00001621 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Eli Friedmane85ef712009-11-16 23:53:01 +00001622 } else if (Array) {
1623 CGF.EmitMemSetToZero(LHS.getAddress(), Field->getType());
1624 } else if (!CGF.hasAggregateLLVMType(RhsExpr->getType())) {
1625 RHS = RValue::get(CGF.EmitScalarExpr(RhsExpr, true));
1626 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
1627 } else if (RhsExpr->getType()->isAnyComplexType()) {
1628 CGF.EmitComplexExprIntoAddr(RhsExpr, LHS.getAddress(),
1629 LHS.isVolatileQualified());
1630 } else {
1631 // Handle member function pointers; other aggregates shouldn't get this far.
1632 CGF.EmitAggExpr(RhsExpr, LHS.getAddress(), LHS.isVolatileQualified());
1633 }
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001634}
1635
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001636/// EmitCtorPrologue - This routine generates necessary code to initialize
1637/// base classes and non-static data members belonging to this constructor.
Anders Carlsson6b8b4b42009-09-01 18:33:46 +00001638/// FIXME: This needs to take a CXXCtorType.
Anders Carlssonddf57d32009-09-14 05:32:02 +00001639void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1640 CXXCtorType CtorType) {
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001641 const CXXRecordDecl *ClassDecl = CD->getParent();
1642
Mike Stump6b2556f2009-08-06 13:41:24 +00001643 // FIXME: Add vbase initialization
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001644
Fariborz Jahaniandedf1e42009-07-25 21:12:28 +00001645 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001646 E = CD->init_end();
1647 B != E; ++B) {
1648 CXXBaseOrMemberInitializer *Member = (*B);
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001649
Anders Carlsson5852b132009-11-06 04:11:09 +00001650 assert(LiveTemporaries.empty() &&
1651 "Should not have any live temporaries at initializer start!");
1652
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001653 if (Member->isBaseInitializer())
1654 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
1655 else
1656 EmitMemberInitializer(*this, ClassDecl, Member);
Anders Carlsson5852b132009-11-06 04:11:09 +00001657
1658 // Pop any live temporaries that the initializers might have pushed.
1659 while (!LiveTemporaries.empty())
1660 PopCXXTemporary();
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001661 }
Mike Stumpbc78a722009-07-31 18:25:34 +00001662
Eli Friedman80888c72009-12-08 06:54:20 +00001663 InitializeVtablePtrs(ClassDecl);
Eli Friedmanbb5008a2009-12-08 06:46:18 +00001664}
1665
1666void CodeGenFunction::InitializeVtablePtrs(const CXXRecordDecl *ClassDecl) {
Anders Carlsson5a1a84f2009-12-05 18:38:15 +00001667 if (!ClassDecl->isDynamicClass())
1668 return;
1669
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001670 // Initialize the vtable pointer.
1671 // FIXME: This needs to initialize secondary vtable pointers too.
1672 llvm::Value *ThisPtr = LoadCXXThis();
Anders Carlsson5a1a84f2009-12-05 18:38:15 +00001673
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001674 llvm::Constant *Vtable = CGM.getVtableInfo().getVtable(ClassDecl);
1675 uint64_t AddressPoint = CGM.getVtableInfo().getVtableAddressPoint(ClassDecl);
1676
1677 llvm::Value *VtableAddressPoint =
1678 Builder.CreateConstInBoundsGEP2_64(Vtable, 0, AddressPoint);
1679
Anders Carlsson5a1a84f2009-12-05 18:38:15 +00001680 llvm::Value *VtableField =
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001681 Builder.CreateBitCast(ThisPtr,
1682 VtableAddressPoint->getType()->getPointerTo());
1683
1684 Builder.CreateStore(VtableAddressPoint, VtableField);
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001685}
Fariborz Jahanianaa01d2a2009-07-30 17:49:11 +00001686
1687/// EmitDtorEpilogue - Emit all code that comes at the end of class's
Mike Stump11289f42009-09-09 15:08:12 +00001688/// destructor. This is to call destructors on members and base classes
Fariborz Jahanianaa01d2a2009-07-30 17:49:11 +00001689/// in reverse order of their construction.
Anders Carlsson6b8b4b42009-09-01 18:33:46 +00001690/// FIXME: This needs to take a CXXDtorType.
Anders Carlssonddf57d32009-09-14 05:32:02 +00001691void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD,
1692 CXXDtorType DtorType) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001693 assert(!DD->isTrivial() &&
1694 "Should not emit dtor epilogue for trivial dtor!");
Mike Stump11289f42009-09-09 15:08:12 +00001695
Anders Carlssondee9a302009-11-17 04:44:12 +00001696 const CXXRecordDecl *ClassDecl = DD->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00001697
Anders Carlssondee9a302009-11-17 04:44:12 +00001698 // Collect the fields.
1699 llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
1700 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1701 E = ClassDecl->field_end(); I != E; ++I) {
1702 const FieldDecl *Field = *I;
1703
1704 QualType FieldType = getContext().getCanonicalType(Field->getType());
1705 FieldType = getContext().getBaseElementType(FieldType);
1706
1707 const RecordType *RT = FieldType->getAs<RecordType>();
1708 if (!RT)
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001709 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00001710
1711 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1712 if (FieldClassDecl->hasTrivialDestructor())
1713 continue;
1714
1715 FieldDecls.push_back(Field);
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001716 }
Anders Carlssond7872042009-11-15 23:03:25 +00001717
Anders Carlssondee9a302009-11-17 04:44:12 +00001718 // Now destroy the fields.
1719 for (size_t i = FieldDecls.size(); i > 0; --i) {
1720 const FieldDecl *Field = FieldDecls[i - 1];
1721
1722 QualType FieldType = Field->getType();
1723 const ConstantArrayType *Array =
1724 getContext().getAsConstantArrayType(FieldType);
1725 if (Array)
1726 FieldType = getContext().getBaseElementType(FieldType);
1727
1728 const RecordType *RT = FieldType->getAs<RecordType>();
1729 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1730
1731 llvm::Value *ThisPtr = LoadCXXThis();
1732
1733 LValue LHS = EmitLValueForField(ThisPtr, Field,
1734 /*isUnion=*/false,
1735 // FIXME: Qualifiers?
1736 /*CVRQualifiers=*/0);
1737 if (Array) {
1738 const llvm::Type *BasePtr = ConvertType(FieldType);
1739 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1740 llvm::Value *BaseAddrPtr =
1741 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1742 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1743 Array, BaseAddrPtr);
1744 } else
1745 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1746 Dtor_Complete, LHS.getAddress());
1747 }
1748
1749 // Destroy non-virtual bases.
1750 for (CXXRecordDecl::reverse_base_class_const_iterator I =
1751 ClassDecl->bases_rbegin(), E = ClassDecl->bases_rend(); I != E; ++I) {
1752 const CXXBaseSpecifier &Base = *I;
1753
1754 // Ignore virtual bases.
1755 if (Base.isVirtual())
1756 continue;
1757
1758 CXXRecordDecl *BaseClassDecl
1759 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1760
1761 // Ignore trivial destructors.
1762 if (BaseClassDecl->hasTrivialDestructor())
1763 continue;
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001764 const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1765
Anders Carlsson8c793172009-11-23 17:57:54 +00001766 llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1767 ClassDecl, BaseClassDecl,
1768 /*NullCheckValue=*/false);
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001769 EmitCXXDestructorCall(D, Dtor_Base, V);
Anders Carlssondee9a302009-11-17 04:44:12 +00001770 }
1771
1772 // If we're emitting a base destructor, we don't want to emit calls to the
1773 // virtual bases.
1774 if (DtorType == Dtor_Base)
1775 return;
1776
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001777 // Handle virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00001778 for (CXXRecordDecl::reverse_base_class_const_iterator I =
1779 ClassDecl->vbases_rbegin(), E = ClassDecl->vbases_rend(); I != E; ++I) {
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001780 const CXXBaseSpecifier &Base = *I;
1781 CXXRecordDecl *BaseClassDecl
1782 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1783
1784 // Ignore trivial destructors.
1785 if (BaseClassDecl->hasTrivialDestructor())
1786 continue;
1787 const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1788 llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1789 ClassDecl, BaseClassDecl,
1790 /*NullCheckValue=*/false);
1791 EmitCXXDestructorCall(D, Dtor_Base, V);
Anders Carlssondee9a302009-11-17 04:44:12 +00001792 }
1793
1794 // If we have a deleting destructor, emit a call to the delete operator.
Fariborz Jahanian037bcb52009-12-01 23:35:33 +00001795 if (DtorType == Dtor_Deleting) {
1796 assert(DD->getOperatorDelete() &&
1797 "operator delete missing - EmitDtorEpilogue");
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001798 EmitDeleteCall(DD->getOperatorDelete(), LoadCXXThis(),
1799 getContext().getTagDeclType(ClassDecl));
Fariborz Jahanian037bcb52009-12-01 23:35:33 +00001800 }
Fariborz Jahanianaa01d2a2009-07-30 17:49:11 +00001801}
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001802
Anders Carlssonddf57d32009-09-14 05:32:02 +00001803void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *Dtor,
1804 CXXDtorType DtorType,
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001805 llvm::Function *Fn,
1806 const FunctionArgList &Args) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001807 assert(!Dtor->getParent()->hasUserDeclaredDestructor() &&
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001808 "SynthesizeDefaultDestructor - destructor has user declaration");
Mike Stump11289f42009-09-09 15:08:12 +00001809
Anders Carlssonddf57d32009-09-14 05:32:02 +00001810 StartFunction(GlobalDecl(Dtor, DtorType), Dtor->getResultType(), Fn, Args,
1811 SourceLocation());
Anders Carlssondee9a302009-11-17 04:44:12 +00001812
Anders Carlssonddf57d32009-09-14 05:32:02 +00001813 EmitDtorEpilogue(Dtor, DtorType);
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001814 FinishFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001815}