blob: 0b77584dd93c2f96df9c865812d01308eb548090 [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
Mike Stump11289f42009-09-09 15:08:12 +000029void
Fariborz Jahanian1254a092009-11-10 19:24:06 +000030CodeGenFunction::EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
Anders Carlssonf40886a2009-08-08 21:45:14 +000031 llvm::Constant *DeclPtr) {
Anders Carlsson52d78a52009-09-27 18:58:34 +000032 const llvm::Type *Int8PtrTy =
33 llvm::Type::getInt8Ty(VMContext)->getPointerTo();
Mike Stump11289f42009-09-09 15:08:12 +000034
Anders Carlssonf40886a2009-08-08 21:45:14 +000035 std::vector<const llvm::Type *> Params;
36 Params.push_back(Int8PtrTy);
Mike Stump11289f42009-09-09 15:08:12 +000037
Anders Carlssonf40886a2009-08-08 21:45:14 +000038 // Get the destructor function type
Mike Stump11289f42009-09-09 15:08:12 +000039 const llvm::Type *DtorFnTy =
Owen Anderson41a75022009-08-13 21:57:51 +000040 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
Anders Carlssonf40886a2009-08-08 21:45:14 +000041 DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
Mike Stump11289f42009-09-09 15:08:12 +000042
Anders Carlssonf40886a2009-08-08 21:45:14 +000043 Params.clear();
44 Params.push_back(DtorFnTy);
45 Params.push_back(Int8PtrTy);
46 Params.push_back(Int8PtrTy);
Mike Stump11289f42009-09-09 15:08:12 +000047
Anders Carlssonf40886a2009-08-08 21:45:14 +000048 // Get the __cxa_atexit function type
49 // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
Mike Stump11289f42009-09-09 15:08:12 +000050 const llvm::FunctionType *AtExitFnTy =
Anders Carlssonf40886a2009-08-08 21:45:14 +000051 llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
Mike Stump11289f42009-09-09 15:08:12 +000052
Anders Carlssonf40886a2009-08-08 21:45:14 +000053 llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
54 "__cxa_atexit");
Mike Stump11289f42009-09-09 15:08:12 +000055
Anders Carlssonf40886a2009-08-08 21:45:14 +000056 llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
57 "__dso_handle");
Anders Carlssonf40886a2009-08-08 21:45:14 +000058 llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
59 llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
60 llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
61 Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args));
62}
63
Mike Stump11289f42009-09-09 15:08:12 +000064void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
Anders Carlssonf40886a2009-08-08 21:45:14 +000065 llvm::Constant *DeclPtr) {
66 assert(D.hasGlobalStorage() &&
67 "VarDecl must have global storage!");
Mike Stump11289f42009-09-09 15:08:12 +000068
Anders Carlssonf40886a2009-08-08 21:45:14 +000069 const Expr *Init = D.getInit();
70 QualType T = D.getType();
Mike Stump53f9ded2009-11-03 23:25:48 +000071 bool isVolatile = getContext().getCanonicalType(T).isVolatileQualified();
Mike Stump11289f42009-09-09 15:08:12 +000072
Anders Carlssonf40886a2009-08-08 21:45:14 +000073 if (T->isReferenceType()) {
Anders Carlsson49033712009-08-17 18:24:57 +000074 ErrorUnsupported(Init, "global variable that binds to a reference");
Anders Carlssonf40886a2009-08-08 21:45:14 +000075 } else if (!hasAggregateLLVMType(T)) {
76 llvm::Value *V = EmitScalarExpr(Init);
Mike Stump53f9ded2009-11-03 23:25:48 +000077 EmitStoreOfScalar(V, DeclPtr, isVolatile, T);
Anders Carlssonf40886a2009-08-08 21:45:14 +000078 } else if (T->isAnyComplexType()) {
Mike Stump53f9ded2009-11-03 23:25:48 +000079 EmitComplexExprIntoAddr(Init, DeclPtr, isVolatile);
Anders Carlssonf40886a2009-08-08 21:45:14 +000080 } else {
Mike Stump53f9ded2009-11-03 23:25:48 +000081 EmitAggExpr(Init, DeclPtr, isVolatile);
Fariborz Jahaniane6c81122009-11-11 01:13:34 +000082 // Avoid generating destructor(s) for initialized objects.
83 if (!isa<CXXConstructExpr>(Init))
84 return;
Fariborz Jahanian1254a092009-11-10 19:24:06 +000085 const ConstantArrayType *Array = getContext().getAsConstantArrayType(T);
86 if (Array)
87 T = getContext().getBaseElementType(Array);
88
Anders Carlssonf40886a2009-08-08 21:45:14 +000089 if (const RecordType *RT = T->getAs<RecordType>()) {
90 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian1254a092009-11-10 19:24:06 +000091 if (!RD->hasTrivialDestructor()) {
92 llvm::Constant *DtorFn;
93 if (Array) {
94 DtorFn = CodeGenFunction(CGM).GenerateCXXAggrDestructorHelper(
95 RD->getDestructor(getContext()),
96 Array, DeclPtr);
97 DeclPtr =
98 llvm::Constant::getNullValue(llvm::Type::getInt8PtrTy(VMContext));
99 }
100 else
101 DtorFn = CGM.GetAddrOfCXXDestructor(RD->getDestructor(getContext()),
102 Dtor_Complete);
103 EmitCXXGlobalDtorRegistration(DtorFn, DeclPtr);
104 }
Anders Carlssonf40886a2009-08-08 21:45:14 +0000105 }
106 }
107}
108
Anders Carlssonb8be93f2009-08-08 23:24:23 +0000109void
110CodeGenModule::EmitCXXGlobalInitFunc() {
111 if (CXXGlobalInits.empty())
112 return;
Mike Stump11289f42009-09-09 15:08:12 +0000113
Mike Stumpb9c9b352009-11-04 01:11:15 +0000114 const llvm::FunctionType *FTy
115 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
116 false);
Mike Stump11289f42009-09-09 15:08:12 +0000117
Anders Carlssonb8be93f2009-08-08 23:24:23 +0000118 // Create our global initialization function.
119 // FIXME: Should this be tweakable by targets?
Mike Stump11289f42009-09-09 15:08:12 +0000120 llvm::Function *Fn =
Anders Carlssonb8be93f2009-08-08 23:24:23 +0000121 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
122 "__cxx_global_initialization", &TheModule);
Mike Stump11289f42009-09-09 15:08:12 +0000123
Anders Carlssonb8be93f2009-08-08 23:24:23 +0000124 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
Benjamin Kramerb57e5d22009-08-08 23:43:26 +0000125 &CXXGlobalInits[0],
Anders Carlssonb8be93f2009-08-08 23:24:23 +0000126 CXXGlobalInits.size());
127 AddGlobalCtor(Fn);
128}
129
130void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
131 const VarDecl **Decls,
132 unsigned NumDecls) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000133 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(),
Anders Carlssonb8be93f2009-08-08 23:24:23 +0000134 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000135
Anders Carlssonb8be93f2009-08-08 23:24:23 +0000136 for (unsigned i = 0; i != NumDecls; ++i) {
137 const VarDecl *D = Decls[i];
Mike Stump11289f42009-09-09 15:08:12 +0000138
Anders Carlssonb8be93f2009-08-08 23:24:23 +0000139 llvm::Constant *DeclPtr = CGM.GetAddrOfGlobalVar(D);
140 EmitCXXGlobalVarDeclInit(*D, DeclPtr);
141 }
142 FinishFunction();
143}
144
Mike Stump11289f42009-09-09 15:08:12 +0000145void
146CodeGenFunction::EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
Anders Carlssonf40886a2009-08-08 21:45:14 +0000147 llvm::GlobalVariable *GV) {
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000148 // FIXME: This should use __cxa_guard_{acquire,release}?
149
Anders Carlsson87fc5a52008-08-22 16:00:37 +0000150 assert(!getContext().getLangOptions().ThreadsafeStatics &&
151 "thread safe statics are currently not supported!");
Anders Carlsson87fc5a52008-08-22 16:00:37 +0000152
Anders Carlsson1235bbc2009-04-13 18:03:33 +0000153 llvm::SmallString<256> GuardVName;
Daniel Dunbare128dd12009-11-21 09:06:22 +0000154 CGM.getMangleContext().mangleGuardVariable(&D, GuardVName);
Mike Stump11289f42009-09-09 15:08:12 +0000155
Anders Carlsson87fc5a52008-08-22 16:00:37 +0000156 // Create the guard variable.
Mike Stump11289f42009-09-09 15:08:12 +0000157 llvm::GlobalValue *GuardV =
Mike Stumpb9c9b352009-11-04 01:11:15 +0000158 new llvm::GlobalVariable(CGM.getModule(), llvm::Type::getInt64Ty(VMContext),
159 false, GV->getLinkage(),
160 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)),
Daniel Dunbar58bc48c2009-08-19 20:04:03 +0000161 GuardVName.str());
Mike Stump11289f42009-09-09 15:08:12 +0000162
Anders Carlsson87fc5a52008-08-22 16:00:37 +0000163 // Load the first byte of the guard variable.
Mike Stumpb9c9b352009-11-04 01:11:15 +0000164 const llvm::Type *PtrTy
165 = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump11289f42009-09-09 15:08:12 +0000166 llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy),
Anders Carlsson87fc5a52008-08-22 16:00:37 +0000167 "tmp");
Mike Stump11289f42009-09-09 15:08:12 +0000168
Anders Carlsson87fc5a52008-08-22 16:00:37 +0000169 // Compare it against 0.
Mike Stumpb9c9b352009-11-04 01:11:15 +0000170 llvm::Value *nullValue
171 = llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext));
Anders Carlsson87fc5a52008-08-22 16:00:37 +0000172 llvm::Value *ICmp = Builder.CreateICmpEQ(V, nullValue , "tobool");
Mike Stump11289f42009-09-09 15:08:12 +0000173
Daniel Dunbar75283ff2008-11-11 02:29:29 +0000174 llvm::BasicBlock *InitBlock = createBasicBlock("init");
Daniel Dunbara612e792008-11-13 01:38:36 +0000175 llvm::BasicBlock *EndBlock = createBasicBlock("init.end");
Anders Carlsson87fc5a52008-08-22 16:00:37 +0000176
177 // If the guard variable is 0, jump to the initializer code.
178 Builder.CreateCondBr(ICmp, InitBlock, EndBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000179
Anders Carlsson87fc5a52008-08-22 16:00:37 +0000180 EmitBlock(InitBlock);
181
Anders Carlssonf40886a2009-08-08 21:45:14 +0000182 EmitCXXGlobalVarDeclInit(D, GV);
183
Mike Stumpb9c9b352009-11-04 01:11:15 +0000184 Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext),
185 1),
Anders Carlsson87fc5a52008-08-22 16:00:37 +0000186 Builder.CreateBitCast(GuardV, PtrTy));
Mike Stump11289f42009-09-09 15:08:12 +0000187
Anders Carlsson87fc5a52008-08-22 16:00:37 +0000188 EmitBlock(EndBlock);
Anders Carlsson87fc5a52008-08-22 16:00:37 +0000189}
190
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000191RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
192 llvm::Value *Callee,
193 llvm::Value *This,
194 CallExpr::const_arg_iterator ArgBeg,
195 CallExpr::const_arg_iterator ArgEnd) {
Mike Stump11289f42009-09-09 15:08:12 +0000196 assert(MD->isInstance() &&
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000197 "Trying to emit a member call expr on a static method!");
198
John McCall9dd450b2009-09-21 23:43:11 +0000199 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +0000200
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000201 CallArgList Args;
Mike Stump11289f42009-09-09 15:08:12 +0000202
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000203 // Push the this ptr.
204 Args.push_back(std::make_pair(RValue::get(This),
205 MD->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +0000206
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000207 // And the rest of the call args
208 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000209
John McCall9dd450b2009-09-21 23:43:11 +0000210 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000211 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
212 Callee, Args, MD);
213}
214
Anders Carlssond7432df2009-10-12 19:41:04 +0000215/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
216/// expr can be devirtualized.
217static bool canDevirtualizeMemberFunctionCalls(const Expr *Base) {
218 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
219 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
220 // This is a record decl. We know the type and can devirtualize it.
221 return VD->getType()->isRecordType();
222 }
Anders Carlssonb61301f2009-10-12 19:45:47 +0000223
224 return false;
Anders Carlssond7432df2009-10-12 19:41:04 +0000225 }
226
Anders Carlssona1b54fd2009-10-12 19:59:15 +0000227 // We can always devirtualize calls on temporary object expressions.
Anders Carlssonb61301f2009-10-12 19:45:47 +0000228 if (isa<CXXTemporaryObjectExpr>(Base))
229 return true;
230
Anders Carlssona1b54fd2009-10-12 19:59:15 +0000231 // And calls on bound temporaries.
232 if (isa<CXXBindTemporaryExpr>(Base))
233 return true;
234
Anders Carlsson2a017092009-10-12 19:51:33 +0000235 // Check if this is a call expr that returns a record type.
236 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
237 return CE->getCallReturnType()->isRecordType();
238
Anders Carlssond7432df2009-10-12 19:41:04 +0000239 // We can't devirtualize the call.
240 return false;
241}
242
Anders Carlssone5fd6f22009-04-03 22:50:24 +0000243RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) {
Eli Friedman8aaff692009-12-08 02:09:46 +0000244 if (isa<BinaryOperator>(CE->getCallee()->IgnoreParens()))
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000245 return EmitCXXMemberPointerCallExpr(CE);
246
Eli Friedman8aaff692009-12-08 02:09:46 +0000247 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee()->IgnoreParens());
Anders Carlssone5fd6f22009-04-03 22:50:24 +0000248 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000249
Anders Carlsson8f4fd602009-09-29 03:54:11 +0000250 if (MD->isStatic()) {
251 // The method is static, emit it as we would a regular call.
252 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
253 return EmitCall(Callee, getContext().getPointerType(MD->getType()),
254 CE->arg_begin(), CE->arg_end(), 0);
255
256 }
257
John McCall9dd450b2009-09-21 23:43:11 +0000258 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stumpa523b2d2009-07-30 21:47:44 +0000259
Mike Stump11289f42009-09-09 15:08:12 +0000260 const llvm::Type *Ty =
261 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
Anders Carlsson03a409f2009-04-08 20:31:57 +0000262 FPT->isVariadic());
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000263 llvm::Value *This;
Mike Stump11289f42009-09-09 15:08:12 +0000264
Anders Carlssone5fd6f22009-04-03 22:50:24 +0000265 if (ME->isArrow())
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000266 This = EmitScalarExpr(ME->getBase());
Anders Carlssone5fd6f22009-04-03 22:50:24 +0000267 else {
268 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000269 This = BaseLV.getAddress();
Anders Carlssone5fd6f22009-04-03 22:50:24 +0000270 }
Mike Stumpa5588bf2009-08-26 20:46:33 +0000271
Eli Friedmanffc066f2009-11-26 07:45:48 +0000272 if (MD->isCopyAssignment() && MD->isTrivial()) {
273 // We don't like to generate the trivial copy assignment operator when
274 // it isn't necessary; just produce the proper effect here.
275 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
276 EmitAggregateCopy(This, RHS, CE->getType());
277 return RValue::get(This);
278 }
279
Douglas Gregorc1905232009-08-26 22:36:53 +0000280 // C++ [class.virtual]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000281 // Explicit qualification with the scope operator (5.1) suppresses the
Douglas Gregorc1905232009-08-26 22:36:53 +0000282 // virtual call mechanism.
Anders Carlssonb5296552009-10-11 23:55:52 +0000283 //
284 // We also don't emit a virtual call if the base expression has a record type
285 // because then we know what the type is.
Mike Stumpa5588bf2009-08-26 20:46:33 +0000286 llvm::Value *Callee;
Eli Friedmane6ce3542009-11-16 05:31:29 +0000287 if (const CXXDestructorDecl *Destructor
288 = dyn_cast<CXXDestructorDecl>(MD)) {
Eli Friedman84a7e342009-11-26 07:40:08 +0000289 if (Destructor->isTrivial())
290 return RValue::get(0);
Eli Friedmane6ce3542009-11-16 05:31:29 +0000291 if (MD->isVirtual() && !ME->hasQualifier() &&
292 !canDevirtualizeMemberFunctionCalls(ME->getBase())) {
293 Callee = BuildVirtualCall(Destructor, Dtor_Complete, This, Ty);
294 } else {
295 Callee = CGM.GetAddrOfFunction(GlobalDecl(Destructor, Dtor_Complete), Ty);
296 }
297 } else if (MD->isVirtual() && !ME->hasQualifier() &&
298 !canDevirtualizeMemberFunctionCalls(ME->getBase())) {
299 Callee = BuildVirtualCall(MD, This, Ty);
300 } else {
Anders Carlssonecf9bf02009-09-10 23:43:36 +0000301 Callee = CGM.GetAddrOfFunction(MD, Ty);
Eli Friedmane6ce3542009-11-16 05:31:29 +0000302 }
Mike Stump11289f42009-09-09 15:08:12 +0000303
304 return EmitCXXMemberCall(MD, Callee, This,
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000305 CE->arg_begin(), CE->arg_end());
Anders Carlssone5fd6f22009-04-03 22:50:24 +0000306}
Anders Carlssona5d077d2009-04-14 16:58:56 +0000307
Mike Stump11289f42009-09-09 15:08:12 +0000308RValue
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000309CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E) {
Eli Friedman8aaff692009-12-08 02:09:46 +0000310 const BinaryOperator *BO =
311 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
Anders Carlsson6bfee8f2009-10-13 17:41:28 +0000312 const Expr *BaseExpr = BO->getLHS();
313 const Expr *MemFnExpr = BO->getRHS();
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000314
Anders Carlsson6bfee8f2009-10-13 17:41:28 +0000315 const MemberPointerType *MPT =
316 MemFnExpr->getType()->getAs<MemberPointerType>();
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000317 const FunctionProtoType *FPT =
318 MPT->getPointeeType()->getAs<FunctionProtoType>();
319 const CXXRecordDecl *RD =
Douglas Gregor615ac672009-11-04 16:49:01 +0000320 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000321
322 const llvm::FunctionType *FTy =
323 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(RD, FPT),
324 FPT->isVariadic());
325
326 const llvm::Type *Int8PtrTy =
327 llvm::Type::getInt8Ty(VMContext)->getPointerTo();
328
329 // Get the member function pointer.
330 llvm::Value *MemFnPtr =
Anders Carlsson6bfee8f2009-10-13 17:41:28 +0000331 CreateTempAlloca(ConvertType(MemFnExpr->getType()), "mem.fn");
332 EmitAggExpr(MemFnExpr, MemFnPtr, /*VolatileDest=*/false);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000333
334 // Emit the 'this' pointer.
335 llvm::Value *This;
336
337 if (BO->getOpcode() == BinaryOperator::PtrMemI)
338 This = EmitScalarExpr(BaseExpr);
339 else
340 This = EmitLValue(BaseExpr).getAddress();
341
342 // Adjust it.
343 llvm::Value *Adj = Builder.CreateStructGEP(MemFnPtr, 1);
344 Adj = Builder.CreateLoad(Adj, "mem.fn.adj");
345
346 llvm::Value *Ptr = Builder.CreateBitCast(This, Int8PtrTy, "ptr");
347 Ptr = Builder.CreateGEP(Ptr, Adj, "adj");
348
349 This = Builder.CreateBitCast(Ptr, This->getType(), "this");
350
351 llvm::Value *FnPtr = Builder.CreateStructGEP(MemFnPtr, 0, "mem.fn.ptr");
352
353 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
354
355 llvm::Value *FnAsInt = Builder.CreateLoad(FnPtr, "fn");
356
357 // If the LSB in the function pointer is 1, the function pointer points to
358 // a virtual function.
359 llvm::Value *IsVirtual
360 = Builder.CreateAnd(FnAsInt, llvm::ConstantInt::get(PtrDiffTy, 1),
361 "and");
362
363 IsVirtual = Builder.CreateTrunc(IsVirtual,
364 llvm::Type::getInt1Ty(VMContext));
365
366 llvm::BasicBlock *FnVirtual = createBasicBlock("fn.virtual");
367 llvm::BasicBlock *FnNonVirtual = createBasicBlock("fn.nonvirtual");
368 llvm::BasicBlock *FnEnd = createBasicBlock("fn.end");
369
370 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
371 EmitBlock(FnVirtual);
372
373 const llvm::Type *VTableTy =
374 FTy->getPointerTo()->getPointerTo()->getPointerTo();
375
376 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy);
377 VTable = Builder.CreateLoad(VTable);
378
379 VTable = Builder.CreateGEP(VTable, FnAsInt, "fn");
380
381 // Since the function pointer is 1 plus the virtual table offset, we
382 // subtract 1 by using a GEP.
Mike Stump0d479e62009-10-09 01:25:47 +0000383 VTable = Builder.CreateConstGEP1_64(VTable, (uint64_t)-1);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000384
385 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "virtualfn");
386
387 EmitBranch(FnEnd);
388 EmitBlock(FnNonVirtual);
389
390 // If the function is not virtual, just load the pointer.
391 llvm::Value *NonVirtualFn = Builder.CreateLoad(FnPtr, "fn");
392 NonVirtualFn = Builder.CreateIntToPtr(NonVirtualFn, FTy->getPointerTo());
393
394 EmitBlock(FnEnd);
395
396 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo());
397 Callee->reserveOperandSpace(2);
398 Callee->addIncoming(VirtualFn, FnVirtual);
399 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
400
401 CallArgList Args;
402
403 QualType ThisType =
404 getContext().getPointerType(getContext().getTagDeclType(RD));
405
406 // Push the this ptr.
407 Args.push_back(std::make_pair(RValue::get(This), ThisType));
408
409 // And the rest of the call args
410 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
411 QualType ResultType = BO->getType()->getAs<FunctionType>()->getResultType();
412 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
413 Callee, Args, 0);
414}
415
416RValue
Anders Carlsson4034a952009-05-27 04:18:27 +0000417CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
418 const CXXMethodDecl *MD) {
Mike Stump11289f42009-09-09 15:08:12 +0000419 assert(MD->isInstance() &&
Anders Carlsson4034a952009-05-27 04:18:27 +0000420 "Trying to emit a member call expr on a static method!");
Mike Stump11289f42009-09-09 15:08:12 +0000421
Fariborz Jahanian4985b332009-08-13 21:09:41 +0000422 if (MD->isCopyAssignment()) {
423 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
424 if (ClassDecl->hasTrivialCopyAssignment()) {
425 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
426 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
427 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
428 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
429 QualType Ty = E->getType();
430 EmitAggregateCopy(This, Src, Ty);
431 return RValue::get(This);
432 }
433 }
Mike Stump11289f42009-09-09 15:08:12 +0000434
John McCall9dd450b2009-09-21 23:43:11 +0000435 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +0000436 const llvm::Type *Ty =
437 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
Mike Stump5a522352009-09-04 18:27:16 +0000438 FPT->isVariadic());
Mike Stump11289f42009-09-09 15:08:12 +0000439
Anders Carlsson4034a952009-05-27 04:18:27 +0000440 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
Mike Stump11289f42009-09-09 15:08:12 +0000441
Eli Friedmane6ce3542009-11-16 05:31:29 +0000442 llvm::Value *Callee;
443 if (MD->isVirtual() && !canDevirtualizeMemberFunctionCalls(E->getArg(0)))
444 Callee = BuildVirtualCall(MD, This, Ty);
445 else
446 Callee = CGM.GetAddrOfFunction(MD, Ty);
447
Anders Carlsson4034a952009-05-27 04:18:27 +0000448 return EmitCXXMemberCall(MD, Callee, This,
449 E->arg_begin() + 1, E->arg_end());
450}
451
Anders Carlssona5d077d2009-04-14 16:58:56 +0000452llvm::Value *CodeGenFunction::LoadCXXThis() {
Mike Stump11289f42009-09-09 15:08:12 +0000453 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
Anders Carlssona5d077d2009-04-14 16:58:56 +0000454 "Must be in a C++ member function decl to load 'this'");
455 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
456 "Must be in a C++ member function decl to load 'this'");
Mike Stump11289f42009-09-09 15:08:12 +0000457
Anders Carlssona5d077d2009-04-14 16:58:56 +0000458 // FIXME: What if we're inside a block?
Mike Stump18bb9282009-05-16 07:57:57 +0000459 // ans: See how CodeGenFunction::LoadObjCSelf() uses
460 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlssona5d077d2009-04-14 16:58:56 +0000461 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
462}
Anders Carlssonf7475242009-04-15 15:55:24 +0000463
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000464/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
465/// for-loop to call the default constructor on individual members of the
Anders Carlssond49844b2009-09-23 02:45:36 +0000466/// array.
467/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
468/// array type and 'ArrayPtr' points to the beginning fo the array.
469/// It is assumed that all relevant checks have been made by the caller.
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000470void
471CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson3a202f62009-11-24 18:43:52 +0000472 const ConstantArrayType *ArrayTy,
473 llvm::Value *ArrayPtr,
474 CallExpr::const_arg_iterator ArgBeg,
475 CallExpr::const_arg_iterator ArgEnd) {
476
Anders Carlssond49844b2009-09-23 02:45:36 +0000477 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
478 llvm::Value * NumElements =
479 llvm::ConstantInt::get(SizeTy,
480 getContext().getConstantArrayElementCount(ArrayTy));
481
Anders Carlsson3a202f62009-11-24 18:43:52 +0000482 EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd);
Anders Carlssond49844b2009-09-23 02:45:36 +0000483}
484
485void
486CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson3a202f62009-11-24 18:43:52 +0000487 llvm::Value *NumElements,
488 llvm::Value *ArrayPtr,
489 CallExpr::const_arg_iterator ArgBeg,
490 CallExpr::const_arg_iterator ArgEnd) {
Anders Carlssond49844b2009-09-23 02:45:36 +0000491 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump11289f42009-09-09 15:08:12 +0000492
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000493 // Create a temporary for the loop index and initialize it with 0.
Anders Carlssond49844b2009-09-23 02:45:36 +0000494 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
495 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Daniel Dunbardacbe6b2009-11-29 21:11:41 +0000496 Builder.CreateStore(Zero, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000497
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000498 // Start the loop with a block that tests the condition.
499 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
500 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +0000501
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000502 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000503
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000504 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump11289f42009-09-09 15:08:12 +0000505
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000506 // Generate: if (loop-index < number-of-elements fall to the loop body,
507 // otherwise, go to the block after the for-loop.
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000508 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
Anders Carlssond49844b2009-09-23 02:45:36 +0000509 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000510 // If the condition is true, execute the body.
511 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +0000512
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000513 EmitBlock(ForBody);
Mike Stump11289f42009-09-09 15:08:12 +0000514
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000515 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000516 // Inside the loop body, emit the constructor call on the array element.
Fariborz Jahaniandd46eb72009-08-20 01:01:06 +0000517 Counter = Builder.CreateLoad(IndexPtr);
Anders Carlssond49844b2009-09-23 02:45:36 +0000518 llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
519 "arrayidx");
Mike Stump11289f42009-09-09 15:08:12 +0000520
Anders Carlsson3a202f62009-11-24 18:43:52 +0000521 // C++ [class.temporary]p4:
522 // There are two contexts in which temporaries are destroyed at a different
523 // point than the end of the full- expression. The first context is when a
524 // default constructor is called to initialize an element of an array.
525 // If the constructor has one or more default arguments, the destruction of
526 // every temporary created in a default argument expression is sequenced
527 // before the construction of the next array element, if any.
528
529 // Keep track of the current number of live temporaries.
530 unsigned OldNumLiveTemporaries = LiveTemporaries.size();
531
532 EmitCXXConstructorCall(D, Ctor_Complete, Address, ArgBeg, ArgEnd);
533
534 // Pop temporaries.
535 while (LiveTemporaries.size() > OldNumLiveTemporaries)
536 PopCXXTemporary();
537
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000538 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000539
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000540 // Emit the increment of the loop counter.
Anders Carlssond49844b2009-09-23 02:45:36 +0000541 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000542 Counter = Builder.CreateLoad(IndexPtr);
543 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +0000544 Builder.CreateStore(NextVal, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000545
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000546 // Finally, branch back up to the condition for the next iteration.
547 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000548
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000549 // Emit the fall-through block.
550 EmitBlock(AfterFor, true);
Fariborz Jahanian431c8832009-08-19 20:55:16 +0000551}
552
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000553/// EmitCXXAggrDestructorCall - calls the default destructor on array
554/// elements in reverse order of construction.
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000555void
Fariborz Jahanian9c837202009-08-20 20:54:15 +0000556CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
557 const ArrayType *Array,
558 llvm::Value *This) {
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000559 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
560 assert(CA && "Do we support VLA for destruction ?");
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +0000561 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
562 llvm::Value* ElementCountPtr =
563 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), ElementCount);
564 EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
565}
566
567/// EmitCXXAggrDestructorCall - calls the default destructor on array
568/// elements in reverse order of construction.
569void
570CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
571 llvm::Value *UpperCount,
572 llvm::Value *This) {
Mike Stump11289f42009-09-09 15:08:12 +0000573 llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000574 1);
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000575 // Create a temporary for the loop index and initialize it with count of
576 // array elements.
577 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
578 "loop.index");
579 // Index = ElementCount;
Daniel Dunbardacbe6b2009-11-29 21:11:41 +0000580 Builder.CreateStore(UpperCount, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000581
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000582 // Start the loop with a block that tests the condition.
583 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
584 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +0000585
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000586 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000587
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000588 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump11289f42009-09-09 15:08:12 +0000589
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000590 // Generate: if (loop-index != 0 fall to the loop body,
591 // otherwise, go to the block after the for-loop.
Mike Stump11289f42009-09-09 15:08:12 +0000592 llvm::Value* zeroConstant =
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000593 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
594 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
595 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
596 "isne");
597 // If the condition is true, execute the body.
598 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +0000599
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000600 EmitBlock(ForBody);
Mike Stump11289f42009-09-09 15:08:12 +0000601
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000602 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
603 // Inside the loop body, emit the constructor call on the array element.
604 Counter = Builder.CreateLoad(IndexPtr);
605 Counter = Builder.CreateSub(Counter, One);
606 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Fariborz Jahanianbe641492009-11-30 22:07:18 +0000607 EmitCXXDestructorCall(D, Dtor_Complete, Address);
Mike Stump11289f42009-09-09 15:08:12 +0000608
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000609 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000610
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000611 // Emit the decrement of the loop counter.
612 Counter = Builder.CreateLoad(IndexPtr);
613 Counter = Builder.CreateSub(Counter, One, "dec");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +0000614 Builder.CreateStore(Counter, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000615
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000616 // Finally, branch back up to the condition for the next iteration.
617 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000618
Fariborz Jahanian1a606ab2009-08-20 23:02:58 +0000619 // Emit the fall-through block.
620 EmitBlock(AfterFor, true);
Fariborz Jahanian9c837202009-08-20 20:54:15 +0000621}
622
Mike Stumpea950e22009-11-18 18:57:56 +0000623/// GenerateCXXAggrDestructorHelper - Generates a helper function which when
624/// invoked, calls the default destructor on array elements in reverse order of
Fariborz Jahanian1254a092009-11-10 19:24:06 +0000625/// construction.
626llvm::Constant *
627CodeGenFunction::GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
628 const ArrayType *Array,
629 llvm::Value *This) {
630 static int UniqueCount;
631 FunctionArgList Args;
632 ImplicitParamDecl *Dst =
633 ImplicitParamDecl::Create(getContext(), 0,
634 SourceLocation(), 0,
635 getContext().getPointerType(getContext().VoidTy));
636 Args.push_back(std::make_pair(Dst, Dst->getType()));
637
638 llvm::SmallString<16> Name;
639 llvm::raw_svector_ostream(Name) << "__tcf_" << (++UniqueCount);
640 QualType R = getContext().VoidTy;
641 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(R, Args);
642 const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false);
643 llvm::Function *Fn =
644 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
645 Name.c_str(),
646 &CGM.getModule());
647 IdentifierInfo *II
648 = &CGM.getContext().Idents.get(Name.c_str());
649 FunctionDecl *FD = FunctionDecl::Create(getContext(),
650 getContext().getTranslationUnitDecl(),
651 SourceLocation(), II, R, 0,
652 FunctionDecl::Static,
653 false, true);
654 StartFunction(FD, R, Fn, Args, SourceLocation());
655 QualType BaseElementTy = getContext().getBaseElementType(Array);
656 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
657 BasePtr = llvm::PointerType::getUnqual(BasePtr);
658 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(This, BasePtr);
659 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
660 FinishFunction();
661 llvm::Type *Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),
662 0);
663 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
664 return m;
665}
666
Fariborz Jahanian9c837202009-08-20 20:54:15 +0000667void
Mike Stump11289f42009-09-09 15:08:12 +0000668CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
669 CXXCtorType Type,
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000670 llvm::Value *This,
671 CallExpr::const_arg_iterator ArgBeg,
672 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian42af5ba2009-08-14 20:11:43 +0000673 if (D->isCopyConstructor(getContext())) {
674 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
675 if (ClassDecl->hasTrivialCopyConstructor()) {
676 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
677 "EmitCXXConstructorCall - user declared copy constructor");
678 const Expr *E = (*ArgBeg);
679 QualType Ty = E->getType();
680 llvm::Value *Src = EmitLValue(E).getAddress();
681 EmitAggregateCopy(This, Src, Ty);
682 return;
683 }
Eli Friedman84a7e342009-11-26 07:40:08 +0000684 } else if (D->isTrivial()) {
685 // FIXME: Track down why we're trying to generate calls to the trivial
686 // default constructor!
687 return;
Fariborz Jahanian42af5ba2009-08-14 20:11:43 +0000688 }
Mike Stump11289f42009-09-09 15:08:12 +0000689
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000690 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
691
692 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000693}
694
Anders Carlssonce460522009-12-04 19:33:17 +0000695void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
Anders Carlsson0a637412009-05-29 21:03:38 +0000696 CXXDtorType Type,
697 llvm::Value *This) {
Anders Carlssonce460522009-12-04 19:33:17 +0000698 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
699
700 CallArgList Args;
Mike Stump11289f42009-09-09 15:08:12 +0000701
Anders Carlssonce460522009-12-04 19:33:17 +0000702 // Push the this ptr.
703 Args.push_back(std::make_pair(RValue::get(This),
704 DD->getThisType(getContext())));
705
706 // Add a VTT parameter if necessary.
707 // FIXME: This should not be a dummy null parameter!
708 if (Type == Dtor_Base && DD->getParent()->getNumVBases() != 0) {
709 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
710
711 Args.push_back(std::make_pair(RValue::get(CGM.EmitNullConstant(T)), T));
712 }
713
714 // FIXME: We should try to share this code with EmitCXXMemberCall.
715
716 QualType ResultType = DD->getType()->getAs<FunctionType>()->getResultType();
717 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args), Callee, Args, DD);
Anders Carlsson0a637412009-05-29 21:03:38 +0000718}
719
Mike Stump11289f42009-09-09 15:08:12 +0000720void
721CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
Anders Carlsson1619a5042009-05-03 17:47:16 +0000722 const CXXConstructExpr *E) {
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000723 assert(Dest && "Must have a destination!");
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000724 const CXXConstructorDecl *CD = E->getConstructor();
Fariborz Jahanian29baa2b2009-10-28 21:07:28 +0000725 const ConstantArrayType *Array =
726 getContext().getAsConstantArrayType(E->getType());
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000727 // For a copy constructor, even if it is trivial, must fall thru so
728 // its argument is code-gen'ed.
729 if (!CD->isCopyConstructor(getContext())) {
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000730 QualType InitType = E->getType();
Fariborz Jahanian29baa2b2009-10-28 21:07:28 +0000731 if (Array)
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000732 InitType = getContext().getBaseElementType(Array);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000733 const CXXRecordDecl *RD =
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000734 cast<CXXRecordDecl>(InitType->getAs<RecordType>()->getDecl());
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000735 if (RD->hasTrivialConstructor())
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000736 return;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +0000737 }
Mike Stump11289f42009-09-09 15:08:12 +0000738 // Code gen optimization to eliminate copy constructor and return
Fariborz Jahanianeb869762009-08-06 01:02:49 +0000739 // its first argument instead.
Anders Carlsson9cedbef2009-08-22 22:30:33 +0000740 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
Anders Carlsson78cfaa92009-11-13 04:34:45 +0000741 const Expr *Arg = E->getArg(0);
742
743 if (const CXXBindTemporaryExpr *BindExpr =
744 dyn_cast<CXXBindTemporaryExpr>(Arg))
745 Arg = BindExpr->getSubExpr();
746
747 EmitAggExpr(Arg, Dest, false);
Fariborz Jahanian00130932009-08-06 19:12:38 +0000748 return;
Fariborz Jahanianeb869762009-08-06 01:02:49 +0000749 }
Fariborz Jahanian29baa2b2009-10-28 21:07:28 +0000750 if (Array) {
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000751 QualType BaseElementTy = getContext().getBaseElementType(Array);
752 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
753 BasePtr = llvm::PointerType::getUnqual(BasePtr);
754 llvm::Value *BaseAddrPtr =
755 Builder.CreateBitCast(Dest, BasePtr);
Anders Carlsson3a202f62009-11-24 18:43:52 +0000756 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
757 E->arg_begin(), E->arg_end());
Fariborz Jahanianf1639ff2009-10-28 20:55:41 +0000758 }
759 else
760 // Call the constructor.
761 EmitCXXConstructorCall(CD, Ctor_Complete, Dest,
762 E->arg_begin(), E->arg_end());
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000763}
764
Anders Carlssonf7475242009-04-15 15:55:24 +0000765void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlssondae1abc2009-05-05 04:44:02 +0000766 EmitGlobal(GlobalDecl(D, Ctor_Complete));
767 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlssonf7475242009-04-15 15:55:24 +0000768}
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000769
Mike Stump11289f42009-09-09 15:08:12 +0000770void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000771 CXXCtorType Type) {
Mike Stump11289f42009-09-09 15:08:12 +0000772
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000773 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
Mike Stump11289f42009-09-09 15:08:12 +0000774
Anders Carlsson73fcc952009-09-11 00:07:24 +0000775 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
Mike Stump11289f42009-09-09 15:08:12 +0000776
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000777 SetFunctionDefinitionAttributes(D, Fn);
778 SetLLVMFunctionAttributesForDefinition(D, Fn);
779}
780
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000781llvm::Function *
Mike Stump11289f42009-09-09 15:08:12 +0000782CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000783 CXXCtorType Type) {
Fariborz Jahanianc2d71b52009-11-06 18:47:57 +0000784 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000785 const llvm::FunctionType *FTy =
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000786 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type),
Fariborz Jahanianc2d71b52009-11-06 18:47:57 +0000787 FPT->isVariadic());
Mike Stump11289f42009-09-09 15:08:12 +0000788
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000789 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattnere0be0df2009-05-12 21:21:08 +0000790 return cast<llvm::Function>(
791 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000792}
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000793
Mike Stump11289f42009-09-09 15:08:12 +0000794const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000795 CXXCtorType Type) {
796 llvm::SmallString<256> Name;
Daniel Dunbare128dd12009-11-21 09:06:22 +0000797 getMangleContext().mangleCXXCtor(D, Type, Name);
Mike Stump11289f42009-09-09 15:08:12 +0000798
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000799 Name += '\0';
800 return UniqueMangledName(Name.begin(), Name.end());
801}
802
803void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
Eli Friedmanb572c922009-11-14 04:19:37 +0000804 if (D->isVirtual())
Eli Friedman250534c2009-11-27 01:42:12 +0000805 EmitGlobalDefinition(GlobalDecl(D, Dtor_Deleting));
806 EmitGlobalDefinition(GlobalDecl(D, Dtor_Complete));
807 EmitGlobalDefinition(GlobalDecl(D, Dtor_Base));
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000808}
809
Mike Stump11289f42009-09-09 15:08:12 +0000810void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000811 CXXDtorType Type) {
812 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
Mike Stump11289f42009-09-09 15:08:12 +0000813
Anders Carlsson73fcc952009-09-11 00:07:24 +0000814 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
Mike Stump11289f42009-09-09 15:08:12 +0000815
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000816 SetFunctionDefinitionAttributes(D, Fn);
817 SetLLVMFunctionAttributesForDefinition(D, Fn);
818}
819
820llvm::Function *
Mike Stump11289f42009-09-09 15:08:12 +0000821CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000822 CXXDtorType Type) {
823 const llvm::FunctionType *FTy =
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000824 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), false);
Mike Stump11289f42009-09-09 15:08:12 +0000825
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000826 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattnere0be0df2009-05-12 21:21:08 +0000827 return cast<llvm::Function>(
828 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000829}
830
Mike Stump11289f42009-09-09 15:08:12 +0000831const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000832 CXXDtorType Type) {
833 llvm::SmallString<256> Name;
Daniel Dunbare128dd12009-11-21 09:06:22 +0000834 getMangleContext().mangleCXXDtor(D, Type, Name);
Mike Stump11289f42009-09-09 15:08:12 +0000835
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000836 Name += '\0';
837 return UniqueMangledName(Name.begin(), Name.end());
838}
Fariborz Jahanian83381cc2009-07-20 23:18:55 +0000839
Anders Carlssonc7785402009-11-26 02:32:05 +0000840llvm::Constant *
Eli Friedman551fe842009-12-03 04:27:05 +0000841CodeGenFunction::GenerateThunk(llvm::Function *Fn, GlobalDecl GD,
Anders Carlssonc7785402009-11-26 02:32:05 +0000842 bool Extern,
843 const ThunkAdjustment &ThisAdjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000844 return GenerateCovariantThunk(Fn, GD, Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000845 CovariantThunkAdjustment(ThisAdjustment,
846 ThunkAdjustment()));
Mike Stump5a522352009-09-04 18:27:16 +0000847}
848
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000849llvm::Value *
850CodeGenFunction::DynamicTypeAdjust(llvm::Value *V,
851 const ThunkAdjustment &Adjustment) {
852 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
853
Mike Stump77738202009-11-03 16:59:27 +0000854 const llvm::Type *OrigTy = V->getType();
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000855 if (Adjustment.NonVirtual) {
Mike Stump77738202009-11-03 16:59:27 +0000856 // Do the non-virtual adjustment
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000857 V = Builder.CreateBitCast(V, Int8PtrTy);
858 V = Builder.CreateConstInBoundsGEP1_64(V, Adjustment.NonVirtual);
Mike Stump77738202009-11-03 16:59:27 +0000859 V = Builder.CreateBitCast(V, OrigTy);
860 }
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000861
862 if (!Adjustment.Virtual)
863 return V;
864
865 assert(Adjustment.Virtual % (LLVMPointerWidth / 8) == 0 &&
866 "vtable entry unaligned");
867
868 // Do the virtual this adjustment
869 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
870 const llvm::Type *PtrDiffPtrTy = PtrDiffTy->getPointerTo();
871
872 llvm::Value *ThisVal = Builder.CreateBitCast(V, Int8PtrTy);
873 V = Builder.CreateBitCast(V, PtrDiffPtrTy->getPointerTo());
874 V = Builder.CreateLoad(V, "vtable");
875
876 llvm::Value *VTablePtr = V;
877 uint64_t VirtualAdjustment = Adjustment.Virtual / (LLVMPointerWidth / 8);
878 V = Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
879 V = Builder.CreateLoad(V);
880 V = Builder.CreateGEP(ThisVal, V);
881
882 return Builder.CreateBitCast(V, OrigTy);
Mike Stump77738202009-11-03 16:59:27 +0000883}
884
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000885llvm::Constant *
886CodeGenFunction::GenerateCovariantThunk(llvm::Function *Fn,
Eli Friedman551fe842009-12-03 04:27:05 +0000887 GlobalDecl GD, bool Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000888 const CovariantThunkAdjustment &Adjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000889 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump33ccd9e2009-11-02 23:22:01 +0000890 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump80f6ac52009-09-11 23:25:56 +0000891
892 FunctionArgList Args;
893 ImplicitParamDecl *ThisDecl =
894 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
895 MD->getThisType(getContext()));
896 Args.push_back(std::make_pair(ThisDecl, ThisDecl->getType()));
897 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
898 e = MD->param_end();
899 i != e; ++i) {
900 ParmVarDecl *D = *i;
901 Args.push_back(std::make_pair(D, D->getType()));
902 }
903 IdentifierInfo *II
904 = &CGM.getContext().Idents.get("__thunk_named_foo_");
905 FunctionDecl *FD = FunctionDecl::Create(getContext(),
906 getContext().getTranslationUnitDecl(),
Mike Stump33ccd9e2009-11-02 23:22:01 +0000907 SourceLocation(), II, ResultType, 0,
Mike Stump80f6ac52009-09-11 23:25:56 +0000908 Extern
909 ? FunctionDecl::Extern
910 : FunctionDecl::Static,
911 false, true);
Mike Stump33ccd9e2009-11-02 23:22:01 +0000912 StartFunction(FD, ResultType, Fn, Args, SourceLocation());
913
914 // generate body
Mike Stumpf3589722009-11-03 02:12:59 +0000915 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
916 const llvm::Type *Ty =
917 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
918 FPT->isVariadic());
Eli Friedman551fe842009-12-03 04:27:05 +0000919 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000920
Mike Stump33ccd9e2009-11-02 23:22:01 +0000921 CallArgList CallArgs;
922
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000923 bool ShouldAdjustReturnPointer = true;
Mike Stumpf3589722009-11-03 02:12:59 +0000924 QualType ArgType = MD->getThisType(getContext());
925 llvm::Value *Arg = Builder.CreateLoad(LocalDeclMap[ThisDecl], "this");
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000926 if (!Adjustment.ThisAdjustment.isEmpty()) {
Mike Stump77738202009-11-03 16:59:27 +0000927 // Do the this adjustment.
Mike Stump71609a22009-11-04 00:53:51 +0000928 const llvm::Type *OrigTy = Callee->getType();
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000929 Arg = DynamicTypeAdjust(Arg, Adjustment.ThisAdjustment);
930
931 if (!Adjustment.ReturnAdjustment.isEmpty()) {
932 const CovariantThunkAdjustment &ReturnAdjustment =
933 CovariantThunkAdjustment(ThunkAdjustment(),
934 Adjustment.ReturnAdjustment);
935
Mike Stumpe2d4a2c2009-12-03 03:47:56 +0000936 Callee = CGM.BuildCovariantThunk(GD, Extern, ReturnAdjustment);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000937
Mike Stump71609a22009-11-04 00:53:51 +0000938 Callee = Builder.CreateBitCast(Callee, OrigTy);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000939 ShouldAdjustReturnPointer = false;
Mike Stump71609a22009-11-04 00:53:51 +0000940 }
941 }
942
Mike Stumpf3589722009-11-03 02:12:59 +0000943 CallArgs.push_back(std::make_pair(RValue::get(Arg), ArgType));
944
Mike Stump33ccd9e2009-11-02 23:22:01 +0000945 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
946 e = MD->param_end();
947 i != e; ++i) {
948 ParmVarDecl *D = *i;
949 QualType ArgType = D->getType();
950
951 // llvm::Value *Arg = CGF.GetAddrOfLocalVar(Dst);
Eli Friedman4039f352009-12-03 04:49:52 +0000952 Expr *Arg = new (getContext()) DeclRefExpr(D, ArgType.getNonReferenceType(),
953 SourceLocation());
Mike Stump33ccd9e2009-11-02 23:22:01 +0000954 CallArgs.push_back(std::make_pair(EmitCallArg(Arg, ArgType), ArgType));
955 }
956
Mike Stump31e1d432009-11-02 23:47:45 +0000957 RValue RV = EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
958 Callee, CallArgs, MD);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000959 if (ShouldAdjustReturnPointer && !Adjustment.ReturnAdjustment.isEmpty()) {
Mike Stumpc5507682009-11-05 06:32:02 +0000960 bool CanBeZero = !(ResultType->isReferenceType()
961 // FIXME: attr nonnull can't be zero either
962 /* || ResultType->hasAttr<NonNullAttr>() */ );
Mike Stump77738202009-11-03 16:59:27 +0000963 // Do the return result adjustment.
Mike Stumpc5507682009-11-05 06:32:02 +0000964 if (CanBeZero) {
965 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
966 llvm::BasicBlock *ZeroBlock = createBasicBlock();
967 llvm::BasicBlock *ContBlock = createBasicBlock();
Mike Stumpb8da7a02009-11-05 06:12:26 +0000968
Mike Stumpc5507682009-11-05 06:32:02 +0000969 const llvm::Type *Ty = RV.getScalarVal()->getType();
970 llvm::Value *Zero = llvm::Constant::getNullValue(Ty);
971 Builder.CreateCondBr(Builder.CreateICmpNE(RV.getScalarVal(), Zero),
972 NonZeroBlock, ZeroBlock);
973 EmitBlock(NonZeroBlock);
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000974 llvm::Value *NZ =
975 DynamicTypeAdjust(RV.getScalarVal(), Adjustment.ReturnAdjustment);
Mike Stumpc5507682009-11-05 06:32:02 +0000976 EmitBranch(ContBlock);
977 EmitBlock(ZeroBlock);
978 llvm::Value *Z = RV.getScalarVal();
979 EmitBlock(ContBlock);
980 llvm::PHINode *RVOrZero = Builder.CreatePHI(Ty);
981 RVOrZero->reserveOperandSpace(2);
982 RVOrZero->addIncoming(NZ, NonZeroBlock);
983 RVOrZero->addIncoming(Z, ZeroBlock);
984 RV = RValue::get(RVOrZero);
985 } else
Anders Carlsson2f87c4f2009-11-26 03:09:37 +0000986 RV = RValue::get(DynamicTypeAdjust(RV.getScalarVal(),
987 Adjustment.ReturnAdjustment));
Mike Stump33ccd9e2009-11-02 23:22:01 +0000988 }
989
Mike Stump31e1d432009-11-02 23:47:45 +0000990 if (!ResultType->isVoidType())
991 EmitReturnOfRValue(RV, ResultType);
992
Mike Stump80f6ac52009-09-11 23:25:56 +0000993 FinishFunction();
994 return Fn;
995}
996
Anders Carlssonc7785402009-11-26 02:32:05 +0000997llvm::Constant *
Eli Friedman8174f2c2009-12-06 22:01:30 +0000998CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
999 const ThunkAdjustment &ThisAdjustment) {
1000 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1001
1002 // Compute mangled name
1003 llvm::SmallString<256> OutName;
1004 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
1005 getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(), ThisAdjustment,
1006 OutName);
1007 else
1008 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
1009 OutName += '\0';
1010 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
1011
1012 // Get function for mangled name
1013 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
1014 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
1015}
1016
1017llvm::Constant *
1018CodeGenModule::GetAddrOfCovariantThunk(GlobalDecl GD,
1019 const CovariantThunkAdjustment &Adjustment) {
1020 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1021
1022 // Compute mangled name
1023 llvm::SmallString<256> OutName;
1024 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
1025 OutName += '\0';
1026 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
1027
1028 // Get function for mangled name
1029 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
1030 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
1031}
1032
1033void CodeGenModule::BuildThunksForVirtual(GlobalDecl GD) {
Eli Friedman31bc3ad2009-12-07 23:56:34 +00001034 CGVtableInfo::AdjustmentVectorTy *AdjPtr = getVtableInfo().getAdjustments(GD);
1035 if (!AdjPtr)
1036 return;
1037 CGVtableInfo::AdjustmentVectorTy &Adj = *AdjPtr;
Eli Friedman8174f2c2009-12-06 22:01:30 +00001038 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Eli Friedman31bc3ad2009-12-07 23:56:34 +00001039 for (unsigned i = 0; i < Adj.size(); i++) {
1040 GlobalDecl OGD = Adj[i].first;
1041 const CXXMethodDecl *OMD = cast<CXXMethodDecl>(OGD.getDecl());
Eli Friedman8174f2c2009-12-06 22:01:30 +00001042 QualType nc_oret = OMD->getType()->getAs<FunctionType>()->getResultType();
1043 CanQualType oret = getContext().getCanonicalType(nc_oret);
1044 QualType nc_ret = MD->getType()->getAs<FunctionType>()->getResultType();
1045 CanQualType ret = getContext().getCanonicalType(nc_ret);
1046 ThunkAdjustment ReturnAdjustment;
1047 if (oret != ret) {
1048 QualType qD = nc_ret->getPointeeType();
1049 QualType qB = nc_oret->getPointeeType();
1050 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
1051 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
1052 ReturnAdjustment = ComputeThunkAdjustment(D, B);
1053 }
Eli Friedman31bc3ad2009-12-07 23:56:34 +00001054 ThunkAdjustment ThisAdjustment = Adj[i].second;
Eli Friedman8174f2c2009-12-06 22:01:30 +00001055 bool Extern = !cast<CXXRecordDecl>(OMD->getDeclContext())->isInAnonymousNamespace();
1056 if (!ReturnAdjustment.isEmpty() || !ThisAdjustment.isEmpty()) {
1057 CovariantThunkAdjustment CoAdj(ThisAdjustment, ReturnAdjustment);
1058 llvm::Constant *FnConst;
1059 if (!ReturnAdjustment.isEmpty())
1060 FnConst = GetAddrOfCovariantThunk(GD, CoAdj);
1061 else
1062 FnConst = GetAddrOfThunk(GD, ThisAdjustment);
1063 if (!isa<llvm::Function>(FnConst)) {
Eli Friedman31bc3ad2009-12-07 23:56:34 +00001064 llvm::Constant *SubExpr =
1065 cast<llvm::ConstantExpr>(FnConst)->getOperand(0);
1066 llvm::Function *OldFn = cast<llvm::Function>(SubExpr);
1067 std::string Name = OldFn->getNameStr();
1068 GlobalDeclMap.erase(UniqueMangledName(Name.data(),
1069 Name.data() + Name.size() + 1));
1070 llvm::Constant *NewFnConst;
1071 if (!ReturnAdjustment.isEmpty())
1072 NewFnConst = GetAddrOfCovariantThunk(GD, CoAdj);
1073 else
1074 NewFnConst = GetAddrOfThunk(GD, ThisAdjustment);
1075 llvm::Function *NewFn = cast<llvm::Function>(NewFnConst);
1076 NewFn->takeName(OldFn);
1077 llvm::Constant *NewPtrForOldDecl =
1078 llvm::ConstantExpr::getBitCast(NewFn, OldFn->getType());
1079 OldFn->replaceAllUsesWith(NewPtrForOldDecl);
1080 OldFn->eraseFromParent();
1081 FnConst = NewFn;
Eli Friedman8174f2c2009-12-06 22:01:30 +00001082 }
1083 llvm::Function *Fn = cast<llvm::Function>(FnConst);
1084 if (Fn->isDeclaration()) {
1085 llvm::GlobalVariable::LinkageTypes linktype;
1086 linktype = llvm::GlobalValue::WeakAnyLinkage;
1087 if (!Extern)
1088 linktype = llvm::GlobalValue::InternalLinkage;
1089 Fn->setLinkage(linktype);
1090 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
1091 Fn->addFnAttr(llvm::Attribute::NoUnwind);
1092 Fn->setAlignment(2);
1093 CodeGenFunction(*this).GenerateCovariantThunk(Fn, GD, Extern, CoAdj);
1094 }
1095 }
Eli Friedman8174f2c2009-12-06 22:01:30 +00001096 }
1097}
1098
1099llvm::Constant *
Eli Friedman551fe842009-12-03 04:27:05 +00001100CodeGenModule::BuildThunk(GlobalDecl GD, bool Extern,
Anders Carlssonc7785402009-11-26 02:32:05 +00001101 const ThunkAdjustment &ThisAdjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +00001102 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump5a522352009-09-04 18:27:16 +00001103 llvm::SmallString<256> OutName;
Mike Stumpe2d4a2c2009-12-03 03:47:56 +00001104 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(MD)) {
1105 getMangleContext().mangleCXXDtorThunk(D, GD.getDtorType(), ThisAdjustment,
1106 OutName);
1107 } else
1108 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
Anders Carlssonc7785402009-11-26 02:32:05 +00001109
Mike Stump5a522352009-09-04 18:27:16 +00001110 llvm::GlobalVariable::LinkageTypes linktype;
1111 linktype = llvm::GlobalValue::WeakAnyLinkage;
1112 if (!Extern)
1113 linktype = llvm::GlobalValue::InternalLinkage;
1114 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
John McCall9dd450b2009-09-21 23:43:11 +00001115 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump5a522352009-09-04 18:27:16 +00001116 const llvm::FunctionType *FTy =
1117 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
1118 FPT->isVariadic());
1119
Daniel Dunbare128dd12009-11-21 09:06:22 +00001120 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
Mike Stump5a522352009-09-04 18:27:16 +00001121 &getModule());
Mike Stumpe2d4a2c2009-12-03 03:47:56 +00001122 CodeGenFunction(*this).GenerateThunk(Fn, GD, Extern, ThisAdjustment);
Mike Stump5a522352009-09-04 18:27:16 +00001123 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
1124 return m;
1125}
1126
Anders Carlsson2f87c4f2009-11-26 03:09:37 +00001127llvm::Constant *
Mike Stumpe2d4a2c2009-12-03 03:47:56 +00001128CodeGenModule::BuildCovariantThunk(const GlobalDecl &GD, bool Extern,
Anders Carlsson2f87c4f2009-11-26 03:09:37 +00001129 const CovariantThunkAdjustment &Adjustment) {
Mike Stumpe2d4a2c2009-12-03 03:47:56 +00001130 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Mike Stump80f6ac52009-09-11 23:25:56 +00001131 llvm::SmallString<256> OutName;
Anders Carlsson2f87c4f2009-11-26 03:09:37 +00001132 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
Mike Stump80f6ac52009-09-11 23:25:56 +00001133 llvm::GlobalVariable::LinkageTypes linktype;
1134 linktype = llvm::GlobalValue::WeakAnyLinkage;
1135 if (!Extern)
1136 linktype = llvm::GlobalValue::InternalLinkage;
1137 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
John McCall9dd450b2009-09-21 23:43:11 +00001138 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump80f6ac52009-09-11 23:25:56 +00001139 const llvm::FunctionType *FTy =
1140 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
1141 FPT->isVariadic());
1142
Daniel Dunbare128dd12009-11-21 09:06:22 +00001143 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
Mike Stump80f6ac52009-09-11 23:25:56 +00001144 &getModule());
Anders Carlsson2f87c4f2009-11-26 03:09:37 +00001145 CodeGenFunction(*this).GenerateCovariantThunk(Fn, MD, Extern, Adjustment);
Mike Stump80f6ac52009-09-11 23:25:56 +00001146 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
1147 return m;
1148}
1149
Mike Stumpa5588bf2009-08-26 20:46:33 +00001150llvm::Value *
Anders Carlssonc6d171e2009-10-06 22:43:30 +00001151CodeGenFunction::GetVirtualCXXBaseClassOffset(llvm::Value *This,
1152 const CXXRecordDecl *ClassDecl,
1153 const CXXRecordDecl *BaseClassDecl) {
Anders Carlssonc6d171e2009-10-06 22:43:30 +00001154 const llvm::Type *Int8PtrTy =
1155 llvm::Type::getInt8Ty(VMContext)->getPointerTo();
1156
1157 llvm::Value *VTablePtr = Builder.CreateBitCast(This,
1158 Int8PtrTy->getPointerTo());
1159 VTablePtr = Builder.CreateLoad(VTablePtr, "vtable");
1160
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001161 int64_t VBaseOffsetIndex =
1162 CGM.getVtableInfo().getVirtualBaseOffsetIndex(ClassDecl, BaseClassDecl);
1163
Anders Carlssonc6d171e2009-10-06 22:43:30 +00001164 llvm::Value *VBaseOffsetPtr =
Mike Stumpb9c9b352009-11-04 01:11:15 +00001165 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetIndex, "vbase.offset.ptr");
Anders Carlssonc6d171e2009-10-06 22:43:30 +00001166 const llvm::Type *PtrDiffTy =
1167 ConvertType(getContext().getPointerDiffType());
1168
1169 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1170 PtrDiffTy->getPointerTo());
1171
1172 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1173
1174 return VBaseOffset;
1175}
1176
Anders Carlssonf942ee02009-11-27 20:47:55 +00001177static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VtableIndex,
Anders Carlssone828c362009-11-13 04:45:41 +00001178 llvm::Value *This, const llvm::Type *Ty) {
1179 Ty = Ty->getPointerTo()->getPointerTo()->getPointerTo();
Anders Carlsson32bfb1c2009-10-03 14:56:57 +00001180
Anders Carlssone828c362009-11-13 04:45:41 +00001181 llvm::Value *Vtable = CGF.Builder.CreateBitCast(This, Ty);
1182 Vtable = CGF.Builder.CreateLoad(Vtable);
1183
1184 llvm::Value *VFuncPtr =
1185 CGF.Builder.CreateConstInBoundsGEP1_64(Vtable, VtableIndex, "vfn");
1186 return CGF.Builder.CreateLoad(VFuncPtr);
1187}
1188
1189llvm::Value *
1190CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
1191 const llvm::Type *Ty) {
1192 MD = MD->getCanonicalDecl();
Anders Carlssonf942ee02009-11-27 20:47:55 +00001193 uint64_t VtableIndex = CGM.getVtableInfo().getMethodVtableIndex(MD);
Anders Carlssone828c362009-11-13 04:45:41 +00001194
1195 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
1196}
1197
1198llvm::Value *
1199CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
1200 llvm::Value *&This, const llvm::Type *Ty) {
1201 DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
Anders Carlssonf942ee02009-11-27 20:47:55 +00001202 uint64_t VtableIndex =
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001203 CGM.getVtableInfo().getMethodVtableIndex(GlobalDecl(DD, Type));
Anders Carlssone828c362009-11-13 04:45:41 +00001204
1205 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
Mike Stumpa5588bf2009-08-26 20:46:33 +00001206}
1207
Fariborz Jahanian56263842009-08-21 18:30:26 +00001208/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1209/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1210/// copy or via a copy constructor call.
Fariborz Jahanian2c73b1d2009-08-26 00:23:27 +00001211// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
Mike Stump11289f42009-09-09 15:08:12 +00001212void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001213 llvm::Value *Src,
1214 const ArrayType *Array,
Mike Stump11289f42009-09-09 15:08:12 +00001215 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001216 QualType Ty) {
1217 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1218 assert(CA && "VLA cannot be copied over");
1219 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
Mike Stump11289f42009-09-09 15:08:12 +00001220
Fariborz Jahanian56263842009-08-21 18:30:26 +00001221 // Create a temporary for the loop index and initialize it with 0.
1222 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1223 "loop.index");
Mike Stump11289f42009-09-09 15:08:12 +00001224 llvm::Value* zeroConstant =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001225 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001226 Builder.CreateStore(zeroConstant, IndexPtr);
Fariborz Jahanian56263842009-08-21 18:30:26 +00001227 // Start the loop with a block that tests the condition.
1228 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1229 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +00001230
Fariborz Jahanian56263842009-08-21 18:30:26 +00001231 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001232
Fariborz Jahanian56263842009-08-21 18:30:26 +00001233 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1234 // Generate: if (loop-index < number-of-elements fall to the loop body,
1235 // otherwise, go to the block after the for-loop.
1236 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Mike Stump11289f42009-09-09 15:08:12 +00001237 llvm::Value * NumElementsPtr =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001238 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1239 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001240 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001241 "isless");
1242 // If the condition is true, execute the body.
1243 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +00001244
Fariborz Jahanian56263842009-08-21 18:30:26 +00001245 EmitBlock(ForBody);
1246 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1247 // Inside the loop body, emit the constructor call on the array element.
1248 Counter = Builder.CreateLoad(IndexPtr);
1249 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1250 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1251 if (BitwiseCopy)
1252 EmitAggregateCopy(Dest, Src, Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001253 else if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001254 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001255 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
Fariborz Jahanian56263842009-08-21 18:30:26 +00001256 Ctor_Complete);
1257 CallArgList CallArgs;
1258 // Push the this (Dest) ptr.
1259 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1260 BaseCopyCtor->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001261
Fariborz Jahanian56263842009-08-21 18:30:26 +00001262 // Push the Src ptr.
1263 CallArgs.push_back(std::make_pair(RValue::get(Src),
Mike Stumpb9c9b352009-11-04 01:11:15 +00001264 BaseCopyCtor->getParamDecl(0)->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001265 QualType ResultType =
John McCall9dd450b2009-09-21 23:43:11 +00001266 BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanian56263842009-08-21 18:30:26 +00001267 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1268 Callee, CallArgs, BaseCopyCtor);
1269 }
1270 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001271
Fariborz Jahanian56263842009-08-21 18:30:26 +00001272 // Emit the increment of the loop counter.
1273 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1274 Counter = Builder.CreateLoad(IndexPtr);
1275 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001276 Builder.CreateStore(NextVal, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001277
Fariborz Jahanian56263842009-08-21 18:30:26 +00001278 // Finally, branch back up to the condition for the next iteration.
1279 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001280
Fariborz Jahanian56263842009-08-21 18:30:26 +00001281 // Emit the fall-through block.
1282 EmitBlock(AfterFor, true);
1283}
1284
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001285/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
Mike Stump11289f42009-09-09 15:08:12 +00001286/// array of objects from SrcValue to DestValue. Assignment can be either a
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001287/// bitwise assignment or via a copy assignment operator function call.
1288/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
Mike Stump11289f42009-09-09 15:08:12 +00001289void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001290 llvm::Value *Src,
1291 const ArrayType *Array,
Mike Stump11289f42009-09-09 15:08:12 +00001292 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001293 QualType Ty) {
1294 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1295 assert(CA && "VLA cannot be asssigned");
1296 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
Mike Stump11289f42009-09-09 15:08:12 +00001297
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001298 // Create a temporary for the loop index and initialize it with 0.
1299 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1300 "loop.index");
Mike Stump11289f42009-09-09 15:08:12 +00001301 llvm::Value* zeroConstant =
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001302 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001303 Builder.CreateStore(zeroConstant, IndexPtr);
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001304 // Start the loop with a block that tests the condition.
1305 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1306 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump11289f42009-09-09 15:08:12 +00001307
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001308 EmitBlock(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001309
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001310 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1311 // Generate: if (loop-index < number-of-elements fall to the loop body,
1312 // otherwise, go to the block after the for-loop.
1313 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Mike Stump11289f42009-09-09 15:08:12 +00001314 llvm::Value * NumElementsPtr =
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001315 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1316 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001317 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001318 "isless");
1319 // If the condition is true, execute the body.
1320 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
Mike Stump11289f42009-09-09 15:08:12 +00001321
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001322 EmitBlock(ForBody);
1323 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1324 // Inside the loop body, emit the assignment operator call on array element.
1325 Counter = Builder.CreateLoad(IndexPtr);
1326 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1327 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1328 const CXXMethodDecl *MD = 0;
1329 if (BitwiseAssign)
1330 EmitAggregateCopy(Dest, Src, Ty);
1331 else {
1332 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1333 MD);
1334 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1335 (void)hasCopyAssign;
John McCall9dd450b2009-09-21 23:43:11 +00001336 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001337 const llvm::Type *LTy =
1338 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1339 FPT->isVariadic());
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001340 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
Mike Stump11289f42009-09-09 15:08:12 +00001341
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001342 CallArgList CallArgs;
1343 // Push the this (Dest) ptr.
1344 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1345 MD->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001346
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001347 // Push the Src ptr.
1348 CallArgs.push_back(std::make_pair(RValue::get(Src),
1349 MD->getParamDecl(0)->getType()));
John McCall9dd450b2009-09-21 23:43:11 +00001350 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001351 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1352 Callee, CallArgs, MD);
1353 }
1354 EmitBlock(ContinueBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001355
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001356 // Emit the increment of the loop counter.
1357 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1358 Counter = Builder.CreateLoad(IndexPtr);
1359 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
Daniel Dunbardacbe6b2009-11-29 21:11:41 +00001360 Builder.CreateStore(NextVal, IndexPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001361
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001362 // Finally, branch back up to the condition for the next iteration.
1363 EmitBranch(CondBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001364
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001365 // Emit the fall-through block.
1366 EmitBlock(AfterFor, true);
1367}
1368
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001369/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1370/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanian56263842009-08-21 18:30:26 +00001371/// or via a copy constructor call.
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001372void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001373 llvm::Value *Dest, llvm::Value *Src,
Mike Stump11289f42009-09-09 15:08:12 +00001374 const CXXRecordDecl *ClassDecl,
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001375 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1376 if (ClassDecl) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001377 Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
1378 /*NullCheckValue=*/false);
1379 Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
1380 /*NullCheckValue=*/false);
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001381 }
1382 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1383 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001384 return;
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001385 }
Mike Stump11289f42009-09-09 15:08:12 +00001386
1387 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian7c3d7f62009-08-08 00:59:58 +00001388 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001389 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001390 Ctor_Complete);
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001391 CallArgList CallArgs;
1392 // Push the this (Dest) ptr.
1393 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1394 BaseCopyCtor->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001395
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001396 // Push the Src ptr.
1397 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian2a26e352009-08-10 17:20:45 +00001398 BaseCopyCtor->getParamDecl(0)->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001399 QualType ResultType =
John McCall9dd450b2009-09-21 23:43:11 +00001400 BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanianb68df0b2009-08-07 23:51:33 +00001401 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1402 Callee, CallArgs, BaseCopyCtor);
1403 }
1404}
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001405
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001406/// EmitClassCopyAssignment - This routine generates code to copy assign a class
Mike Stump11289f42009-09-09 15:08:12 +00001407/// object from SrcValue to DestValue. Assignment can be either a bitwise
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001408/// assignment of via an assignment operator call.
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001409// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001410void CodeGenFunction::EmitClassCopyAssignment(
1411 llvm::Value *Dest, llvm::Value *Src,
Mike Stump11289f42009-09-09 15:08:12 +00001412 const CXXRecordDecl *ClassDecl,
1413 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001414 QualType Ty) {
1415 if (ClassDecl) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001416 Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
1417 /*NullCheckValue=*/false);
1418 Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
1419 /*NullCheckValue=*/false);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001420 }
1421 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1422 EmitAggregateCopy(Dest, Src, Ty);
1423 return;
1424 }
Mike Stump11289f42009-09-09 15:08:12 +00001425
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001426 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001427 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001428 MD);
1429 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1430 (void)ConstCopyAssignOp;
1431
John McCall9dd450b2009-09-21 23:43:11 +00001432 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00001433 const llvm::Type *LTy =
1434 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001435 FPT->isVariadic());
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001436 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
Mike Stump11289f42009-09-09 15:08:12 +00001437
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001438 CallArgList CallArgs;
1439 // Push the this (Dest) ptr.
1440 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1441 MD->getThisType(getContext())));
Mike Stump11289f42009-09-09 15:08:12 +00001442
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001443 // Push the Src ptr.
1444 CallArgs.push_back(std::make_pair(RValue::get(Src),
1445 MD->getParamDecl(0)->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001446 QualType ResultType =
John McCall9dd450b2009-09-21 23:43:11 +00001447 MD->getType()->getAs<FunctionType>()->getResultType();
Fariborz Jahanian9b630c32009-08-13 00:53:36 +00001448 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1449 Callee, CallArgs, MD);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001450}
1451
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001452/// SynthesizeDefaultConstructor - synthesize a default constructor
Mike Stump11289f42009-09-09 15:08:12 +00001453void
Anders Carlssonddf57d32009-09-14 05:32:02 +00001454CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *Ctor,
1455 CXXCtorType Type,
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001456 llvm::Function *Fn,
1457 const FunctionArgList &Args) {
Eli Friedman84a7e342009-11-26 07:40:08 +00001458 assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
Anders Carlssonddf57d32009-09-14 05:32:02 +00001459 StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
1460 SourceLocation());
1461 EmitCtorPrologue(Ctor, Type);
Fariborz Jahanian9d3405c2009-08-10 18:46:38 +00001462 FinishFunction();
1463}
1464
Mike Stumpb9c9b352009-11-04 01:11:15 +00001465/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a
1466/// copy constructor, in accordance with section 12.8 (p7 and p8) of C++03
Mike Stump11289f42009-09-09 15:08:12 +00001467/// The implicitly-defined copy constructor for class X performs a memberwise
Mike Stumpb9c9b352009-11-04 01:11:15 +00001468/// copy of its subobjects. The order of copying is the same as the order of
1469/// initialization of bases and members in a user-defined constructor
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001470/// Each subobject is copied in the manner appropriate to its type:
Mike Stump11289f42009-09-09 15:08:12 +00001471/// if the subobject is of class type, the copy constructor for the class is
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001472/// used;
Mike Stump11289f42009-09-09 15:08:12 +00001473/// if the subobject is an array, each element is copied, in the manner
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001474/// appropriate to the element type;
Mike Stump11289f42009-09-09 15:08:12 +00001475/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001476/// used.
Mike Stump11289f42009-09-09 15:08:12 +00001477/// Virtual base class subobjects shall be copied only once by the
1478/// implicitly-defined copy constructor
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001479
Anders Carlssonddf57d32009-09-14 05:32:02 +00001480void
1481CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *Ctor,
1482 CXXCtorType Type,
1483 llvm::Function *Fn,
1484 const FunctionArgList &Args) {
Anders Carlsson73fcc952009-09-11 00:07:24 +00001485 const CXXRecordDecl *ClassDecl = Ctor->getParent();
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001486 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Mike Stumpb9c9b352009-11-04 01:11:15 +00001487 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
Eli Friedman84a7e342009-11-26 07:40:08 +00001488 assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
Anders Carlssonddf57d32009-09-14 05:32:02 +00001489 StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
1490 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001491
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001492 FunctionArgList::const_iterator i = Args.begin();
1493 const VarDecl *ThisArg = i->first;
1494 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1495 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1496 const VarDecl *SrcArg = (i+1)->first;
1497 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1498 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
Mike Stump11289f42009-09-09 15:08:12 +00001499
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001500 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1501 Base != ClassDecl->bases_end(); ++Base) {
1502 // FIXME. copy constrution of virtual base NYI
1503 if (Base->isVirtual())
1504 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001505
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001506 CXXRecordDecl *BaseClassDecl
1507 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24f38962009-08-08 23:32:22 +00001508 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1509 Base->getType());
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001510 }
Mike Stump11289f42009-09-09 15:08:12 +00001511
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001512 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1513 E = ClassDecl->field_end(); I != E; ++I) {
1514 const FieldDecl *Field = *I;
1515
1516 QualType FieldType = getContext().getCanonicalType(Field->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001517 const ConstantArrayType *Array =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001518 getContext().getAsConstantArrayType(FieldType);
1519 if (Array)
1520 FieldType = getContext().getBaseElementType(FieldType);
Mike Stump11289f42009-09-09 15:08:12 +00001521
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001522 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1523 CXXRecordDecl *FieldClassDecl
1524 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001525 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1526 LValue RHS = EmitLValueForField(LoadOfSrc, Field, false, 0);
Fariborz Jahanian56263842009-08-21 18:30:26 +00001527 if (Array) {
1528 const llvm::Type *BasePtr = ConvertType(FieldType);
1529 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Mike Stump11289f42009-09-09 15:08:12 +00001530 llvm::Value *DestBaseAddrPtr =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001531 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
Mike Stump11289f42009-09-09 15:08:12 +00001532 llvm::Value *SrcBaseAddrPtr =
Fariborz Jahanian56263842009-08-21 18:30:26 +00001533 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1534 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1535 FieldClassDecl, FieldType);
1536 }
Mike Stump11289f42009-09-09 15:08:12 +00001537 else
1538 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahanian56263842009-08-21 18:30:26 +00001539 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001540 continue;
1541 }
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001542
1543 if (Field->getType()->isReferenceType()) {
1544 unsigned FieldIndex = CGM.getTypes().getLLVMFieldNo(Field);
1545
1546 llvm::Value *LHS = Builder.CreateStructGEP(LoadOfThis, FieldIndex,
1547 "lhs.ref");
1548
1549 llvm::Value *RHS = Builder.CreateStructGEP(LoadOfThis, FieldIndex,
1550 "rhs.ref");
1551
1552 // Load the value in RHS.
1553 RHS = Builder.CreateLoad(RHS);
1554
1555 // And store it in the LHS
1556 Builder.CreateStore(RHS, LHS);
1557
1558 continue;
1559 }
Fariborz Jahanian7cc52cf2009-08-10 18:34:26 +00001560 // Do a built-in assignment of scalar data members.
Anders Carlsson3c9beab2009-11-24 21:08:10 +00001561 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1562 LValue RHS = EmitLValueForField(LoadOfSrc, Field, false, 0);
1563
Eli Friedmanc2ef2152009-11-16 21:47:41 +00001564 if (!hasAggregateLLVMType(Field->getType())) {
1565 RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
1566 EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
1567 } else if (Field->getType()->isAnyComplexType()) {
1568 ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
1569 RHS.isVolatileQualified());
1570 StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
1571 } else {
1572 EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
1573 }
Fariborz Jahanian59b32592009-08-08 00:15:41 +00001574 }
Fariborz Jahanianf6bda5d2009-08-08 19:31:03 +00001575 FinishFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001576}
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001577
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001578/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
Mike Stump11289f42009-09-09 15:08:12 +00001579/// Before the implicitly-declared copy assignment operator for a class is
1580/// implicitly defined, all implicitly- declared copy assignment operators for
1581/// its direct base classes and its nonstatic data members shall have been
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001582/// implicitly defined. [12.8-p12]
Mike Stump11289f42009-09-09 15:08:12 +00001583/// The implicitly-defined copy assignment operator for class X performs
1584/// memberwise assignment of its subob- jects. The direct base classes of X are
1585/// assigned first, in the order of their declaration in
1586/// the base-specifier-list, and then the immediate nonstatic data members of X
1587/// are assigned, in the order in which they were declared in the class
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001588/// definition.Each subobject is assigned in the manner appropriate to its type:
Mike Stump11289f42009-09-09 15:08:12 +00001589/// if the subobject is of class type, the copy assignment operator for the
1590/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001591/// possible virtual overriding functions in more derived classes);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001592///
Mike Stump11289f42009-09-09 15:08:12 +00001593/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001594/// appropriate to the element type;
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001595///
Mike Stump11289f42009-09-09 15:08:12 +00001596/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001597/// used.
1598void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001599 llvm::Function *Fn,
1600 const FunctionArgList &Args) {
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001601
1602 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1603 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1604 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Anders Carlssonddf57d32009-09-14 05:32:02 +00001605 StartFunction(CD, CD->getResultType(), Fn, Args, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001606
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001607 FunctionArgList::const_iterator i = Args.begin();
1608 const VarDecl *ThisArg = i->first;
1609 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1610 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1611 const VarDecl *SrcArg = (i+1)->first;
1612 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1613 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
Mike Stump11289f42009-09-09 15:08:12 +00001614
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001615 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1616 Base != ClassDecl->bases_end(); ++Base) {
1617 // FIXME. copy assignment of virtual base NYI
1618 if (Base->isVirtual())
1619 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001620
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001621 CXXRecordDecl *BaseClassDecl
1622 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1623 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1624 Base->getType());
1625 }
Mike Stump11289f42009-09-09 15:08:12 +00001626
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001627 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1628 FieldEnd = ClassDecl->field_end();
1629 Field != FieldEnd; ++Field) {
1630 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001631 const ConstantArrayType *Array =
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001632 getContext().getAsConstantArrayType(FieldType);
1633 if (Array)
1634 FieldType = getContext().getBaseElementType(FieldType);
Mike Stump11289f42009-09-09 15:08:12 +00001635
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001636 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1637 CXXRecordDecl *FieldClassDecl
1638 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1639 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1640 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001641 if (Array) {
1642 const llvm::Type *BasePtr = ConvertType(FieldType);
1643 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1644 llvm::Value *DestBaseAddrPtr =
1645 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1646 llvm::Value *SrcBaseAddrPtr =
1647 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1648 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1649 FieldClassDecl, FieldType);
1650 }
1651 else
Mike Stump11289f42009-09-09 15:08:12 +00001652 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahanian8adc9732009-08-21 22:34:55 +00001653 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00001654 continue;
1655 }
1656 // Do a built-in assignment of scalar data members.
1657 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1658 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Eli Friedmancd6a50f2009-12-08 01:57:53 +00001659 if (!hasAggregateLLVMType(Field->getType())) {
1660 RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
1661 EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
1662 } else if (Field->getType()->isAnyComplexType()) {
1663 ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
1664 RHS.isVolatileQualified());
1665 StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
1666 } else {
1667 EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
1668 }
Fariborz Jahanian92b3f472009-08-14 00:01:54 +00001669 }
Mike Stump11289f42009-09-09 15:08:12 +00001670
Fariborz Jahanian92b3f472009-08-14 00:01:54 +00001671 // return *this;
1672 Builder.CreateStore(LoadOfThis, ReturnValue);
Mike Stump11289f42009-09-09 15:08:12 +00001673
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00001674 FinishFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001675}
Fariborz Jahanian40134e72009-08-07 20:22:40 +00001676
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001677static void EmitBaseInitializer(CodeGenFunction &CGF,
1678 const CXXRecordDecl *ClassDecl,
1679 CXXBaseOrMemberInitializer *BaseInit,
1680 CXXCtorType CtorType) {
1681 assert(BaseInit->isBaseInitializer() &&
1682 "Must have base initializer!");
1683
1684 llvm::Value *ThisPtr = CGF.LoadCXXThis();
1685
1686 const Type *BaseType = BaseInit->getBaseClass();
1687 CXXRecordDecl *BaseClassDecl =
1688 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Anders Carlsson8c793172009-11-23 17:57:54 +00001689 llvm::Value *V = CGF.GetAddressOfBaseClass(ThisPtr, ClassDecl,
1690 BaseClassDecl,
1691 /*NullCheckValue=*/false);
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001692 CGF.EmitCXXConstructorCall(BaseInit->getConstructor(),
1693 CtorType, V,
1694 BaseInit->const_arg_begin(),
1695 BaseInit->const_arg_end());
1696}
1697
1698static void EmitMemberInitializer(CodeGenFunction &CGF,
1699 const CXXRecordDecl *ClassDecl,
1700 CXXBaseOrMemberInitializer *MemberInit) {
1701 assert(MemberInit->isMemberInitializer() &&
1702 "Must have member initializer!");
1703
1704 // non-static data member initializers.
1705 FieldDecl *Field = MemberInit->getMember();
Eli Friedman5e7d9692009-11-16 23:34:11 +00001706 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001707
1708 llvm::Value *ThisPtr = CGF.LoadCXXThis();
1709 LValue LHS;
1710 if (FieldType->isReferenceType()) {
1711 // FIXME: This is really ugly; should be refactored somehow
1712 unsigned idx = CGF.CGM.getTypes().getLLVMFieldNo(Field);
1713 llvm::Value *V = CGF.Builder.CreateStructGEP(ThisPtr, idx, "tmp");
1714 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
1715 LHS = LValue::MakeAddr(V, CGF.MakeQualifiers(FieldType));
1716 } else {
Eli Friedmanc1daba32009-11-16 22:58:01 +00001717 LHS = CGF.EmitLValueForField(ThisPtr, Field, ClassDecl->isUnion(), 0);
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001718 }
Eli Friedman5e7d9692009-11-16 23:34:11 +00001719
1720 // If we are initializing an anonymous union field, drill down to the field.
1721 if (MemberInit->getAnonUnionMember()) {
1722 Field = MemberInit->getAnonUnionMember();
1723 LHS = CGF.EmitLValueForField(LHS.getAddress(), Field,
1724 /*IsUnion=*/true, 0);
1725 FieldType = Field->getType();
1726 }
1727
1728 // If the field is an array, branch based on the element type.
1729 const ConstantArrayType *Array =
1730 CGF.getContext().getAsConstantArrayType(FieldType);
1731 if (Array)
1732 FieldType = CGF.getContext().getBaseElementType(FieldType);
1733
Eli Friedmane85ef712009-11-16 23:53:01 +00001734 // We lose the constructor for anonymous union members, so handle them
1735 // explicitly.
1736 // FIXME: This is somwhat ugly.
1737 if (MemberInit->getAnonUnionMember() && FieldType->getAs<RecordType>()) {
1738 if (MemberInit->getNumArgs())
1739 CGF.EmitAggExpr(*MemberInit->arg_begin(), LHS.getAddress(),
1740 LHS.isVolatileQualified());
1741 else
1742 CGF.EmitAggregateClear(LHS.getAddress(), Field->getType());
1743 return;
1744 }
1745
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001746 if (FieldType->getAs<RecordType>()) {
Eli Friedman5e7d9692009-11-16 23:34:11 +00001747 assert(MemberInit->getConstructor() &&
1748 "EmitCtorPrologue - no constructor to initialize member");
1749 if (Array) {
1750 const llvm::Type *BasePtr = CGF.ConvertType(FieldType);
1751 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1752 llvm::Value *BaseAddrPtr =
1753 CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1754 CGF.EmitCXXAggrConstructorCall(MemberInit->getConstructor(),
Anders Carlsson3a202f62009-11-24 18:43:52 +00001755 Array, BaseAddrPtr,
1756 MemberInit->const_arg_begin(),
1757 MemberInit->const_arg_end());
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001758 }
Eli Friedman5e7d9692009-11-16 23:34:11 +00001759 else
1760 CGF.EmitCXXConstructorCall(MemberInit->getConstructor(),
1761 Ctor_Complete, LHS.getAddress(),
1762 MemberInit->const_arg_begin(),
1763 MemberInit->const_arg_end());
1764 return;
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001765 }
1766
1767 assert(MemberInit->getNumArgs() == 1 && "Initializer count must be 1 only");
1768 Expr *RhsExpr = *MemberInit->arg_begin();
1769 RValue RHS;
Eli Friedmane85ef712009-11-16 23:53:01 +00001770 if (FieldType->isReferenceType()) {
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001771 RHS = CGF.EmitReferenceBindingToExpr(RhsExpr, FieldType,
1772 /*IsInitializer=*/true);
Fariborz Jahanian03f62ed2009-11-11 17:55:25 +00001773 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Eli Friedmane85ef712009-11-16 23:53:01 +00001774 } else if (Array) {
1775 CGF.EmitMemSetToZero(LHS.getAddress(), Field->getType());
1776 } else if (!CGF.hasAggregateLLVMType(RhsExpr->getType())) {
1777 RHS = RValue::get(CGF.EmitScalarExpr(RhsExpr, true));
1778 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
1779 } else if (RhsExpr->getType()->isAnyComplexType()) {
1780 CGF.EmitComplexExprIntoAddr(RhsExpr, LHS.getAddress(),
1781 LHS.isVolatileQualified());
1782 } else {
1783 // Handle member function pointers; other aggregates shouldn't get this far.
1784 CGF.EmitAggExpr(RhsExpr, LHS.getAddress(), LHS.isVolatileQualified());
1785 }
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001786}
1787
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001788/// EmitCtorPrologue - This routine generates necessary code to initialize
1789/// base classes and non-static data members belonging to this constructor.
Anders Carlsson6b8b4b42009-09-01 18:33:46 +00001790/// FIXME: This needs to take a CXXCtorType.
Anders Carlssonddf57d32009-09-14 05:32:02 +00001791void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1792 CXXCtorType CtorType) {
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001793 const CXXRecordDecl *ClassDecl = CD->getParent();
1794
Mike Stump6b2556f2009-08-06 13:41:24 +00001795 // FIXME: Add vbase initialization
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001796
Fariborz Jahaniandedf1e42009-07-25 21:12:28 +00001797 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001798 E = CD->init_end();
1799 B != E; ++B) {
1800 CXXBaseOrMemberInitializer *Member = (*B);
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001801
Anders Carlsson5852b132009-11-06 04:11:09 +00001802 assert(LiveTemporaries.empty() &&
1803 "Should not have any live temporaries at initializer start!");
1804
Anders Carlssona7cb98b2009-11-06 03:23:06 +00001805 if (Member->isBaseInitializer())
1806 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
1807 else
1808 EmitMemberInitializer(*this, ClassDecl, Member);
Anders Carlsson5852b132009-11-06 04:11:09 +00001809
1810 // Pop any live temporaries that the initializers might have pushed.
1811 while (!LiveTemporaries.empty())
1812 PopCXXTemporary();
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001813 }
Mike Stumpbc78a722009-07-31 18:25:34 +00001814
Anders Carlsson5a1a84f2009-12-05 18:38:15 +00001815 if (!ClassDecl->isDynamicClass())
1816 return;
1817
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001818 // Initialize the vtable pointer.
1819 // FIXME: This needs to initialize secondary vtable pointers too.
1820 llvm::Value *ThisPtr = LoadCXXThis();
Anders Carlsson5a1a84f2009-12-05 18:38:15 +00001821
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001822 llvm::Constant *Vtable = CGM.getVtableInfo().getVtable(ClassDecl);
1823 uint64_t AddressPoint = CGM.getVtableInfo().getVtableAddressPoint(ClassDecl);
1824
1825 llvm::Value *VtableAddressPoint =
1826 Builder.CreateConstInBoundsGEP2_64(Vtable, 0, AddressPoint);
1827
Anders Carlsson5a1a84f2009-12-05 18:38:15 +00001828 llvm::Value *VtableField =
Anders Carlssonb3f54b72009-12-05 21:28:12 +00001829 Builder.CreateBitCast(ThisPtr,
1830 VtableAddressPoint->getType()->getPointerTo());
1831
1832 Builder.CreateStore(VtableAddressPoint, VtableField);
Fariborz Jahanian83381cc2009-07-20 23:18:55 +00001833}
Fariborz Jahanianaa01d2a2009-07-30 17:49:11 +00001834
1835/// EmitDtorEpilogue - Emit all code that comes at the end of class's
Mike Stump11289f42009-09-09 15:08:12 +00001836/// destructor. This is to call destructors on members and base classes
Fariborz Jahanianaa01d2a2009-07-30 17:49:11 +00001837/// in reverse order of their construction.
Anders Carlsson6b8b4b42009-09-01 18:33:46 +00001838/// FIXME: This needs to take a CXXDtorType.
Anders Carlssonddf57d32009-09-14 05:32:02 +00001839void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD,
1840 CXXDtorType DtorType) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001841 assert(!DD->isTrivial() &&
1842 "Should not emit dtor epilogue for trivial dtor!");
Mike Stump11289f42009-09-09 15:08:12 +00001843
Anders Carlssondee9a302009-11-17 04:44:12 +00001844 const CXXRecordDecl *ClassDecl = DD->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00001845
Anders Carlssondee9a302009-11-17 04:44:12 +00001846 // Collect the fields.
1847 llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
1848 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1849 E = ClassDecl->field_end(); I != E; ++I) {
1850 const FieldDecl *Field = *I;
1851
1852 QualType FieldType = getContext().getCanonicalType(Field->getType());
1853 FieldType = getContext().getBaseElementType(FieldType);
1854
1855 const RecordType *RT = FieldType->getAs<RecordType>();
1856 if (!RT)
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001857 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00001858
1859 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1860 if (FieldClassDecl->hasTrivialDestructor())
1861 continue;
1862
1863 FieldDecls.push_back(Field);
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001864 }
Anders Carlssond7872042009-11-15 23:03:25 +00001865
Anders Carlssondee9a302009-11-17 04:44:12 +00001866 // Now destroy the fields.
1867 for (size_t i = FieldDecls.size(); i > 0; --i) {
1868 const FieldDecl *Field = FieldDecls[i - 1];
1869
1870 QualType FieldType = Field->getType();
1871 const ConstantArrayType *Array =
1872 getContext().getAsConstantArrayType(FieldType);
1873 if (Array)
1874 FieldType = getContext().getBaseElementType(FieldType);
1875
1876 const RecordType *RT = FieldType->getAs<RecordType>();
1877 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1878
1879 llvm::Value *ThisPtr = LoadCXXThis();
1880
1881 LValue LHS = EmitLValueForField(ThisPtr, Field,
1882 /*isUnion=*/false,
1883 // FIXME: Qualifiers?
1884 /*CVRQualifiers=*/0);
1885 if (Array) {
1886 const llvm::Type *BasePtr = ConvertType(FieldType);
1887 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1888 llvm::Value *BaseAddrPtr =
1889 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1890 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1891 Array, BaseAddrPtr);
1892 } else
1893 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1894 Dtor_Complete, LHS.getAddress());
1895 }
1896
1897 // Destroy non-virtual bases.
1898 for (CXXRecordDecl::reverse_base_class_const_iterator I =
1899 ClassDecl->bases_rbegin(), E = ClassDecl->bases_rend(); I != E; ++I) {
1900 const CXXBaseSpecifier &Base = *I;
1901
1902 // Ignore virtual bases.
1903 if (Base.isVirtual())
1904 continue;
1905
1906 CXXRecordDecl *BaseClassDecl
1907 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1908
1909 // Ignore trivial destructors.
1910 if (BaseClassDecl->hasTrivialDestructor())
1911 continue;
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001912 const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1913
Anders Carlsson8c793172009-11-23 17:57:54 +00001914 llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1915 ClassDecl, BaseClassDecl,
1916 /*NullCheckValue=*/false);
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001917 EmitCXXDestructorCall(D, Dtor_Base, V);
Anders Carlssondee9a302009-11-17 04:44:12 +00001918 }
1919
1920 // If we're emitting a base destructor, we don't want to emit calls to the
1921 // virtual bases.
1922 if (DtorType == Dtor_Base)
1923 return;
1924
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001925 // Handle virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00001926 for (CXXRecordDecl::reverse_base_class_const_iterator I =
1927 ClassDecl->vbases_rbegin(), E = ClassDecl->vbases_rend(); I != E; ++I) {
Fariborz Jahanianbe641492009-11-30 22:07:18 +00001928 const CXXBaseSpecifier &Base = *I;
1929 CXXRecordDecl *BaseClassDecl
1930 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1931
1932 // Ignore trivial destructors.
1933 if (BaseClassDecl->hasTrivialDestructor())
1934 continue;
1935 const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1936 llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1937 ClassDecl, BaseClassDecl,
1938 /*NullCheckValue=*/false);
1939 EmitCXXDestructorCall(D, Dtor_Base, V);
Anders Carlssondee9a302009-11-17 04:44:12 +00001940 }
1941
1942 // If we have a deleting destructor, emit a call to the delete operator.
Fariborz Jahanian037bcb52009-12-01 23:35:33 +00001943 if (DtorType == Dtor_Deleting) {
1944 assert(DD->getOperatorDelete() &&
1945 "operator delete missing - EmitDtorEpilogue");
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001946 EmitDeleteCall(DD->getOperatorDelete(), LoadCXXThis(),
1947 getContext().getTagDeclType(ClassDecl));
Fariborz Jahanian037bcb52009-12-01 23:35:33 +00001948 }
Fariborz Jahanianaa01d2a2009-07-30 17:49:11 +00001949}
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001950
Anders Carlssonddf57d32009-09-14 05:32:02 +00001951void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *Dtor,
1952 CXXDtorType DtorType,
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001953 llvm::Function *Fn,
1954 const FunctionArgList &Args) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001955 assert(!Dtor->getParent()->hasUserDeclaredDestructor() &&
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001956 "SynthesizeDefaultDestructor - destructor has user declaration");
Mike Stump11289f42009-09-09 15:08:12 +00001957
Anders Carlssonddf57d32009-09-14 05:32:02 +00001958 StartFunction(GlobalDecl(Dtor, DtorType), Dtor->getResultType(), Fn, Args,
1959 SourceLocation());
Anders Carlssondee9a302009-11-17 04:44:12 +00001960
Anders Carlssonddf57d32009-09-14 05:32:02 +00001961 EmitDtorEpilogue(Dtor, DtorType);
Fariborz Jahaniand172e912009-08-17 19:04:50 +00001962 FinishFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001963}