blob: 12def6728f519753158c6630cc611be274e4cbe8 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-function state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Peter Collingbournea4ae2292011-10-06 18:51:56 +000016#include "CGCUDARuntime.h"
John McCall4c40d982010-08-31 07:33:07 +000017#include "CGCXXABI.h"
Eli Friedman3f2af102008-05-22 01:40:10 +000018#include "CGDebugInfo.h"
John McCallf1549f62010-07-06 01:34:17 +000019#include "CGException.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner31a09842008-11-12 08:04:58 +000021#include "clang/AST/APValue.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000023#include "clang/AST/Decl.h"
Anders Carlsson2b77ba82009-04-04 20:47:02 +000024#include "clang/AST/DeclCXX.h"
Mike Stump6a1e0eb2009-12-04 23:26:17 +000025#include "clang/AST/StmtCXX.h"
Chris Lattner7255a2d2010-06-22 00:03:40 +000026#include "clang/Frontend/CodeGenOptions.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000027#include "llvm/Target/TargetData.h"
Chris Lattner7255a2d2010-06-22 00:03:40 +000028#include "llvm/Intrinsics.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30using namespace CodeGen;
31
Mike Stump1eb44332009-09-09 15:08:12 +000032CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
John McCall5936e332011-02-15 09:22:45 +000033 : CodeGenTypeCache(cgm), CGM(cgm),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000034 Target(CGM.getContext().getTargetInfo()), Builder(cgm.getModule().getContext()),
John McCallf85e1932011-06-15 23:02:42 +000035 AutoreleaseResult(false), BlockInfo(0), BlockPointer(0),
John McCall777d6e52011-08-11 02:22:43 +000036 NormalCleanupDest(0), NextCleanupDestIndex(1),
37 EHResumeBlock(0), ExceptionSlot(0), EHSelectorSlot(0),
John McCall93c332a2011-05-28 21:13:02 +000038 DebugInfo(0), DisableDebugInfo(false), DidCallStackSave(false),
39 IndirectBranch(0), SwitchInsn(0), CaseRangeBlock(0), UnreachableBlock(0),
John McCall25049412010-02-16 22:04:33 +000040 CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
John McCall150b4622011-01-26 04:00:11 +000041 OutermostConditional(0), TerminateLandingPad(0), TerminateHandler(0),
Chris Lattner83252dc2010-07-20 21:07:09 +000042 TrapBB(0) {
Anders Carlssonc1cfdf82011-02-20 00:20:27 +000043
Mike Stump9c276ae2009-12-12 01:27:46 +000044 CatchUndefined = getContext().getLangOptions().CatchUndefined;
John McCall4c40d982010-08-31 07:33:07 +000045 CGM.getCXXABI().getMangleContext().startNewFunction();
Chris Lattner41110242008-06-17 18:05:57 +000046}
Reid Spencer5f016e22007-07-11 17:01:13 +000047
Reid Spencer5f016e22007-07-11 17:01:13 +000048
Chris Lattner9cbe4f02011-07-09 17:41:47 +000049llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000050 return CGM.getTypes().ConvertTypeForMem(T);
51}
52
Chris Lattner9cbe4f02011-07-09 17:41:47 +000053llvm::Type *CodeGenFunction::ConvertType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +000054 return CGM.getTypes().ConvertType(T);
55}
56
John McCallf2aac842011-05-15 02:34:36 +000057bool CodeGenFunction::hasAggregateLLVMType(QualType type) {
58 switch (type.getCanonicalType()->getTypeClass()) {
59#define TYPE(name, parent)
60#define ABSTRACT_TYPE(name, parent)
61#define NON_CANONICAL_TYPE(name, parent) case Type::name:
62#define DEPENDENT_TYPE(name, parent) case Type::name:
63#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
64#include "clang/AST/TypeNodes.def"
65 llvm_unreachable("non-canonical or dependent type in IR-generation");
66
67 case Type::Builtin:
68 case Type::Pointer:
69 case Type::BlockPointer:
70 case Type::LValueReference:
71 case Type::RValueReference:
72 case Type::MemberPointer:
73 case Type::Vector:
74 case Type::ExtVector:
75 case Type::FunctionProto:
76 case Type::FunctionNoProto:
77 case Type::Enum:
78 case Type::ObjCObjectPointer:
79 return false;
80
81 // Complexes, arrays, records, and Objective-C objects.
82 case Type::Complex:
83 case Type::ConstantArray:
84 case Type::IncompleteArray:
85 case Type::VariableArray:
86 case Type::Record:
87 case Type::ObjCObject:
88 case Type::ObjCInterface:
89 return true;
90 }
91 llvm_unreachable("unknown type kind!");
Reid Spencer5f016e22007-07-11 17:01:13 +000092}
93
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000094void CodeGenFunction::EmitReturnBlock() {
95 // For cleanliness, we try to avoid emitting the return block for
96 // simple cases.
97 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
98
99 if (CurBB) {
100 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
101
Daniel Dunbar96e18b02009-07-19 08:24:34 +0000102 // We have a valid insert point, reuse it if it is empty or there are no
103 // explicit jumps to the return block.
John McCallff8e1152010-07-23 21:56:41 +0000104 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
105 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
106 delete ReturnBlock.getBlock();
Daniel Dunbar96e18b02009-07-19 08:24:34 +0000107 } else
John McCallff8e1152010-07-23 21:56:41 +0000108 EmitBlock(ReturnBlock.getBlock());
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000109 return;
110 }
111
112 // Otherwise, if the return block is the target of a single direct
113 // branch then we can just put the code in that block instead. This
114 // cleans up functions which started with a unified return block.
John McCallff8e1152010-07-23 21:56:41 +0000115 if (ReturnBlock.getBlock()->hasOneUse()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000116 llvm::BranchInst *BI =
John McCallff8e1152010-07-23 21:56:41 +0000117 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin());
John McCallf1549f62010-07-06 01:34:17 +0000118 if (BI && BI->isUnconditional() &&
John McCallff8e1152010-07-23 21:56:41 +0000119 BI->getSuccessor(0) == ReturnBlock.getBlock()) {
Eric Christopheracae0112011-09-09 21:53:04 +0000120 // Reset insertion point, including debug location, and delete the branch.
121 Builder.SetCurrentDebugLocation(BI->getDebugLoc());
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000122 Builder.SetInsertPoint(BI->getParent());
123 BI->eraseFromParent();
John McCallff8e1152010-07-23 21:56:41 +0000124 delete ReturnBlock.getBlock();
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000125 return;
126 }
127 }
128
Mike Stumpf5408fe2009-05-16 07:57:57 +0000129 // FIXME: We are at an unreachable point, there is no reason to emit the block
130 // unless it has uses. However, we still need a place to put the debug
131 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000132
John McCallff8e1152010-07-23 21:56:41 +0000133 EmitBlock(ReturnBlock.getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000134}
135
136static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
137 if (!BB) return;
138 if (!BB->use_empty())
139 return CGF.CurFn->getBasicBlockList().push_back(BB);
140 delete BB;
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000141}
142
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000143void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnerda138702007-07-16 21:28:45 +0000144 assert(BreakContinueStack.empty() &&
145 "mismatched push/pop in break/continue stack!");
Mike Stump1eb44332009-09-09 15:08:12 +0000146
John McCallf85e1932011-06-15 23:02:42 +0000147 // Pop any cleanups that might have been associated with the
148 // parameters. Do this in whatever block we're currently in; it's
149 // important to do this before we enter the return block or return
150 // edges will be *really* confused.
151 if (EHStack.stable_begin() != PrologueCleanupDepth)
152 PopCleanupBlocks(PrologueCleanupDepth);
153
Mike Stump1eb44332009-09-09 15:08:12 +0000154 // Emit function epilog (to return).
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000155 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000156
Daniel Dunbara18652f2011-02-10 17:32:22 +0000157 if (ShouldInstrumentFunction())
158 EmitFunctionInstrumentation("__cyg_profile_func_exit");
Chris Lattner7255a2d2010-06-22 00:03:40 +0000159
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000160 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000161 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000162 DI->setLocation(EndLoc);
Devang Patel5a6fbcf2010-07-22 22:29:16 +0000163 DI->EmitFunctionEnd(Builder);
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000164 }
165
Chris Lattner35b21b82010-06-27 01:06:27 +0000166 EmitFunctionEpilog(*CurFnInfo);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000167 EmitEndEHSpec(CurCodeDecl);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000168
John McCallf1549f62010-07-06 01:34:17 +0000169 assert(EHStack.empty() &&
170 "did not remove all scopes from cleanup stack!");
171
Chris Lattnerd9becd12009-10-28 23:59:40 +0000172 // If someone did an indirect goto, emit the indirect goto block at the end of
173 // the function.
174 if (IndirectBranch) {
175 EmitBlock(IndirectBranch->getParent());
176 Builder.ClearInsertionPoint();
177 }
178
Chris Lattner5a2fa142007-12-02 06:32:24 +0000179 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000180 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000181 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000182 Ptr->eraseFromParent();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000183
184 // If someone took the address of a label but never did an indirect goto, we
185 // made a zero entry PHI node, which is illegal, zap it now.
186 if (IndirectBranch) {
187 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
188 if (PN->getNumIncomingValues() == 0) {
189 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
190 PN->eraseFromParent();
191 }
192 }
John McCallf1549f62010-07-06 01:34:17 +0000193
John McCall777d6e52011-08-11 02:22:43 +0000194 EmitIfUsed(*this, EHResumeBlock);
John McCallf1549f62010-07-06 01:34:17 +0000195 EmitIfUsed(*this, TerminateLandingPad);
196 EmitIfUsed(*this, TerminateHandler);
197 EmitIfUsed(*this, UnreachableBlock);
John McCall744016d2010-07-06 23:57:41 +0000198
199 if (CGM.getCodeGenOpts().EmitDeclMetadata)
200 EmitDeclMetadata();
Reid Spencer5f016e22007-07-11 17:01:13 +0000201}
202
Chris Lattner7255a2d2010-06-22 00:03:40 +0000203/// ShouldInstrumentFunction - Return true if the current function should be
204/// instrumented with __cyg_profile_func_* calls
205bool CodeGenFunction::ShouldInstrumentFunction() {
206 if (!CGM.getCodeGenOpts().InstrumentFunctions)
207 return false;
Ted Kremenek7aa488a2011-05-16 23:49:20 +0000208 if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
Chris Lattner7255a2d2010-06-22 00:03:40 +0000209 return false;
210 return true;
211}
212
213/// EmitFunctionInstrumentation - Emit LLVM code to call the specified
214/// instrumentation function with the current function and the call site, if
215/// function instrumentation is enabled.
216void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
Chris Lattner8dab6572010-06-23 05:21:28 +0000217 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000218 llvm::PointerType *PointerTy = Int8PtrTy;
219 llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +0000220 llvm::FunctionType *FunctionTy =
Benjamin Kramer95d318c2011-05-28 14:26:31 +0000221 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
222 ProfileFuncArgs, false);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000223
224 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
225 llvm::CallInst *CallSite = Builder.CreateCall(
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000226 CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
Chris Lattner77b89b82010-06-27 07:15:29 +0000227 llvm::ConstantInt::get(Int32Ty, 0),
Chris Lattner7255a2d2010-06-22 00:03:40 +0000228 "callsite");
229
Chris Lattner8dab6572010-06-23 05:21:28 +0000230 Builder.CreateCall2(F,
231 llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
232 CallSite);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000233}
234
Roman Divackybe4c8702011-02-10 16:52:03 +0000235void CodeGenFunction::EmitMCountInstrumentation() {
236 llvm::FunctionType *FTy =
237 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), false);
238
239 llvm::Constant *MCountFn = CGM.CreateRuntimeFunction(FTy,
240 Target.getMCountName());
241 Builder.CreateCall(MCountFn);
242}
243
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000244void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000245 llvm::Function *Fn,
John McCalld26bc762011-03-09 04:27:21 +0000246 const CGFunctionInfo &FnInfo,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000247 const FunctionArgList &Args,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000248 SourceLocation StartLoc) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000249 const Decl *D = GD.getDecl();
250
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000251 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000252 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000253 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000254 CurFn = Fn;
John McCalld26bc762011-03-09 04:27:21 +0000255 CurFnInfo = &FnInfo;
Chris Lattner41110242008-06-17 18:05:57 +0000256 assert(CurFn->isDeclaration() && "Function already has body?");
257
Jakob Stoklund Olesena3fe2842010-02-09 00:10:00 +0000258 // Pass inline keyword to optimizer if it appears explicitly on any
259 // declaration.
260 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
261 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
262 RE = FD->redecls_end(); RI != RE; ++RI)
263 if (RI->isInlineSpecified()) {
264 Fn->addFnAttr(llvm::Attribute::InlineHint);
265 break;
266 }
267
Peter Collingbournef315fa82011-02-14 01:42:53 +0000268 if (getContext().getLangOptions().OpenCL) {
269 // Add metadata for a kernel function.
270 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
271 if (FD->hasAttr<OpenCLKernelAttr>()) {
272 llvm::LLVMContext &Context = getLLVMContext();
273 llvm::NamedMDNode *OpenCLMetadata =
274 CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
275
276 llvm::Value *Op = Fn;
Jay Foad6f141652011-04-21 19:59:12 +0000277 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Op));
Peter Collingbournef315fa82011-02-14 01:42:53 +0000278 }
279 }
280
Daniel Dunbar55e87422008-11-11 02:29:29 +0000281 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000282
Chris Lattner41110242008-06-17 18:05:57 +0000283 // Create a marker to make it easy to insert allocas into the entryblock
284 // later. Don't create this with the builder, because we don't want it
285 // folded.
Chris Lattner77b89b82010-06-27 07:15:29 +0000286 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
287 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000288 if (Builder.isNamePreserving())
289 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000290
John McCallf1549f62010-07-06 01:34:17 +0000291 ReturnBlock = getJumpDestInCurrentScope("return");
Mike Stump1eb44332009-09-09 15:08:12 +0000292
Chris Lattner41110242008-06-17 18:05:57 +0000293 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000295 // Emit subprogram debug descriptor.
Anders Carlssone896d982009-02-13 08:11:52 +0000296 if (CGDebugInfo *DI = getDebugInfo()) {
John McCalle23cf432010-12-14 08:05:40 +0000297 // FIXME: what is going on here and why does it ignore all these
298 // interesting type properties?
299 QualType FnType =
300 getContext().getFunctionType(RetTy, 0, 0,
301 FunctionProtoType::ExtProtoInfo());
302
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000303 DI->setLocation(StartLoc);
Devang Patel9c6c3a02010-01-14 00:36:21 +0000304 DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000305 }
306
Daniel Dunbara18652f2011-02-10 17:32:22 +0000307 if (ShouldInstrumentFunction())
308 EmitFunctionInstrumentation("__cyg_profile_func_enter");
Chris Lattner7255a2d2010-06-22 00:03:40 +0000309
Roman Divackybe4c8702011-02-10 16:52:03 +0000310 if (CGM.getCodeGenOpts().InstrumentForProfiling)
311 EmitMCountInstrumentation();
312
Eli Friedmanb17daf92009-12-04 02:43:40 +0000313 if (RetTy->isVoidType()) {
314 // Void type; nothing to return.
315 ReturnValue = 0;
316 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
317 hasAggregateLLVMType(CurFnInfo->getReturnType())) {
318 // Indirect aggregate return; emit returned value directly into sret slot.
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000319 // This reduces code size, and affects correctness in C++.
Eli Friedmanb17daf92009-12-04 02:43:40 +0000320 ReturnValue = CurFn->arg_begin();
321 } else {
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000322 ReturnValue = CreateIRTemp(RetTy, "retval");
John McCallf85e1932011-06-15 23:02:42 +0000323
324 // Tell the epilog emitter to autorelease the result. We do this
325 // now so that various specialized functions can suppress it
326 // during their IR-generation.
327 if (getLangOptions().ObjCAutoRefCount &&
328 !CurFnInfo->isReturnsRetained() &&
329 RetTy->isObjCRetainableType())
330 AutoreleaseResult = true;
Eli Friedmanb17daf92009-12-04 02:43:40 +0000331 }
332
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000333 EmitStartEHSpec(CurCodeDecl);
John McCallf85e1932011-06-15 23:02:42 +0000334
335 PrologueCleanupDepth = EHStack.stable_begin();
Daniel Dunbar88b53962009-02-02 22:03:45 +0000336 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000337
John McCall4c40d982010-08-31 07:33:07 +0000338 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
339 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
John McCall25049412010-02-16 22:04:33 +0000340
Anders Carlsson751358f2008-12-20 21:28:43 +0000341 // If any of the arguments have a variably modified type, make sure to
342 // emit the type size.
343 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
344 i != e; ++i) {
John McCalld26bc762011-03-09 04:27:21 +0000345 QualType Ty = (*i)->getType();
Anders Carlsson751358f2008-12-20 21:28:43 +0000346
347 if (Ty->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000348 EmitVariablyModifiedType(Ty);
Anders Carlsson751358f2008-12-20 21:28:43 +0000349 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000350}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000351
John McCall9fc6a772010-02-19 09:25:03 +0000352void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
353 const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
Douglas Gregor06a9f362010-05-01 20:49:11 +0000354 assert(FD->getBody());
355 EmitStmt(FD->getBody());
John McCalla355e072010-02-18 03:17:58 +0000356}
357
John McCall39dad532010-08-03 22:46:07 +0000358/// Tries to mark the given function nounwind based on the
359/// non-existence of any throwing calls within it. We believe this is
360/// lightweight enough to do at -O0.
361static void TryMarkNoThrow(llvm::Function *F) {
John McCallb3a29f12010-08-11 22:38:33 +0000362 // LLVM treats 'nounwind' on a function as part of the type, so we
363 // can't do this on functions that can be overwritten.
364 if (F->mayBeOverridden()) return;
365
John McCall39dad532010-08-03 22:46:07 +0000366 for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
367 for (llvm::BasicBlock::iterator
368 BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
Bill Wendling285cfd82011-09-19 20:31:14 +0000369 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) {
John McCall39dad532010-08-03 22:46:07 +0000370 if (!Call->doesNotThrow())
371 return;
Bill Wendling285cfd82011-09-19 20:31:14 +0000372 } else if (isa<llvm::ResumeInst>(&*BI)) {
373 return;
374 }
John McCall39dad532010-08-03 22:46:07 +0000375 F->setDoesNotThrow(true);
376}
377
John McCalld26bc762011-03-09 04:27:21 +0000378void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
379 const CGFunctionInfo &FnInfo) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000380 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
381
Anders Carlssone896d982009-02-13 08:11:52 +0000382 // Check if we should generate debug info for this function.
Devang Patelaa112892011-03-07 18:45:56 +0000383 if (CGM.getModuleDebugInfo() && !FD->hasAttr<NoDebugAttr>())
384 DebugInfo = CGM.getModuleDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Daniel Dunbar7c086512008-09-09 23:14:03 +0000386 FunctionArgList Args;
John McCall4c40d982010-08-31 07:33:07 +0000387 QualType ResTy = FD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Mike Stump6a1e0eb2009-12-04 23:26:17 +0000389 CurGD = GD;
John McCall4c40d982010-08-31 07:33:07 +0000390 if (isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isInstance())
391 CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000392
John McCalld26bc762011-03-09 04:27:21 +0000393 if (FD->getNumParams())
Daniel Dunbar7c086512008-09-09 23:14:03 +0000394 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +0000395 Args.push_back(FD->getParamDecl(i));
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000396
John McCalla355e072010-02-18 03:17:58 +0000397 SourceRange BodyRange;
398 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
Anders Carlsson4365bba2009-11-06 02:55:43 +0000399
John McCalla355e072010-02-18 03:17:58 +0000400 // Emit the standard function prologue.
John McCalld26bc762011-03-09 04:27:21 +0000401 StartFunction(GD, ResTy, Fn, FnInfo, Args, BodyRange.getBegin());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000402
John McCalla355e072010-02-18 03:17:58 +0000403 // Generate the body of the function.
John McCall9fc6a772010-02-19 09:25:03 +0000404 if (isa<CXXDestructorDecl>(FD))
405 EmitDestructorBody(Args);
406 else if (isa<CXXConstructorDecl>(FD))
407 EmitConstructorBody(Args);
Peter Collingbournea4ae2292011-10-06 18:51:56 +0000408 else if (getContext().getLangOptions().CUDA &&
409 !CGM.getCodeGenOpts().CUDAIsDevice &&
410 FD->hasAttr<CUDAGlobalAttr>())
411 CGM.getCUDARuntime().EmitDeviceStubBody(*this, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000412 else
413 EmitFunctionBody(Args);
Anders Carlsson1851a122010-02-07 19:45:40 +0000414
John McCalla355e072010-02-18 03:17:58 +0000415 // Emit the standard function epilogue.
416 FinishFunction(BodyRange.getEnd());
John McCall39dad532010-08-03 22:46:07 +0000417
418 // If we haven't marked the function nothrow through other means, do
419 // a quick pass now to see if we can.
420 if (!CurFn->doesNotThrow())
421 TryMarkNoThrow(CurFn);
Chris Lattner41110242008-06-17 18:05:57 +0000422}
423
Chris Lattner0946ccd2008-11-11 07:41:27 +0000424/// ContainsLabel - Return true if the statement contains a label in it. If
425/// this statement is not executed normally, it not containing a label means
426/// that we can just remove the code.
427bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
428 // Null statement, not a label!
429 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Chris Lattner0946ccd2008-11-11 07:41:27 +0000431 // If this is a label, we have to emit the code, consider something like:
432 // if (0) { ... foo: bar(); } goto foo;
Chris Lattneref425a62011-02-28 00:18:40 +0000433 //
434 // TODO: If anyone cared, we could track __label__'s, since we know that you
435 // can't jump to one from outside their declared region.
Chris Lattner0946ccd2008-11-11 07:41:27 +0000436 if (isa<LabelStmt>(S))
437 return true;
Chris Lattneref425a62011-02-28 00:18:40 +0000438
Chris Lattner0946ccd2008-11-11 07:41:27 +0000439 // If this is a case/default statement, and we haven't seen a switch, we have
440 // to emit the code.
441 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
442 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Chris Lattner0946ccd2008-11-11 07:41:27 +0000444 // If this is a switch statement, we want to ignore cases below it.
445 if (isa<SwitchStmt>(S))
446 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Chris Lattner0946ccd2008-11-11 07:41:27 +0000448 // Scan subexpressions for verboten labels.
John McCall7502c1d2011-02-13 04:07:26 +0000449 for (Stmt::const_child_range I = S->children(); I; ++I)
Chris Lattner0946ccd2008-11-11 07:41:27 +0000450 if (ContainsLabel(*I, IgnoreCaseStmts))
451 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Chris Lattner0946ccd2008-11-11 07:41:27 +0000453 return false;
454}
455
Chris Lattneref425a62011-02-28 00:18:40 +0000456/// containsBreak - Return true if the statement contains a break out of it.
457/// If the statement (recursively) contains a switch or loop with a break
458/// inside of it, this is fine.
459bool CodeGenFunction::containsBreak(const Stmt *S) {
460 // Null statement, not a label!
461 if (S == 0) return false;
462
463 // If this is a switch or loop that defines its own break scope, then we can
464 // include it and anything inside of it.
465 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
466 isa<ForStmt>(S))
Chris Lattner2bef7f52011-02-28 00:42:31 +0000467 return false;
468
469 if (isa<BreakStmt>(S))
Chris Lattneref425a62011-02-28 00:18:40 +0000470 return true;
471
472 // Scan subexpressions for verboten breaks.
473 for (Stmt::const_child_range I = S->children(); I; ++I)
474 if (containsBreak(*I))
475 return true;
476
477 return false;
478}
479
Chris Lattner31a09842008-11-12 08:04:58 +0000480
Chris Lattnerc2c90012011-02-27 23:02:32 +0000481/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
482/// to a constant, or if it does but contains a label, return false. If it
483/// constant folds return true and set the boolean result in Result.
484bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
485 bool &ResultBool) {
Chris Lattneref425a62011-02-28 00:18:40 +0000486 llvm::APInt ResultInt;
487 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
488 return false;
489
490 ResultBool = ResultInt.getBoolValue();
491 return true;
492}
493
494/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
495/// to a constant, or if it does but contains a label, return false. If it
496/// constant folds return true and set the folded value.
497bool CodeGenFunction::
498ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APInt &ResultInt) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000499 // FIXME: Rename and handle conversion of other evaluatable things
500 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000501 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000502 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000503 Result.HasSideEffects)
Chris Lattnerc2c90012011-02-27 23:02:32 +0000504 return false; // Not foldable, not integer or not fully evaluatable.
Chris Lattneref425a62011-02-28 00:18:40 +0000505
Chris Lattner31a09842008-11-12 08:04:58 +0000506 if (CodeGenFunction::ContainsLabel(Cond))
Chris Lattnerc2c90012011-02-27 23:02:32 +0000507 return false; // Contains a label.
Chris Lattneref425a62011-02-28 00:18:40 +0000508
509 ResultInt = Result.Val.getInt();
Chris Lattnerc2c90012011-02-27 23:02:32 +0000510 return true;
Chris Lattner31a09842008-11-12 08:04:58 +0000511}
512
513
Chris Lattneref425a62011-02-28 00:18:40 +0000514
Chris Lattner31a09842008-11-12 08:04:58 +0000515/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
516/// statement) to the specified blocks. Based on the condition, this might try
517/// to simplify the codegen of the conditional based on the branch.
518///
519void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
520 llvm::BasicBlock *TrueBlock,
521 llvm::BasicBlock *FalseBlock) {
Peter Collingbournef111d932011-04-15 00:35:48 +0000522 Cond = Cond->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Chris Lattner31a09842008-11-12 08:04:58 +0000524 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
525 // Handle X && Y in a condition.
John McCall2de56d12010-08-25 11:45:40 +0000526 if (CondBOp->getOpcode() == BO_LAnd) {
Chris Lattner31a09842008-11-12 08:04:58 +0000527 // If we have "1 && X", simplify the code. "0 && X" would have constant
528 // folded if the case was simple enough.
Bill Wendlinge3eb83b2011-03-04 21:46:03 +0000529 bool ConstantBool = false;
Chris Lattnerc2c90012011-02-27 23:02:32 +0000530 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
531 ConstantBool) {
Chris Lattner31a09842008-11-12 08:04:58 +0000532 // br(1 && X) -> br(X).
533 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
534 }
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Chris Lattner31a09842008-11-12 08:04:58 +0000536 // If we have "X && 1", simplify the code to use an uncond branch.
537 // "X && 0" would have been constant folded to 0.
Chris Lattnerc2c90012011-02-27 23:02:32 +0000538 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
539 ConstantBool) {
Chris Lattner31a09842008-11-12 08:04:58 +0000540 // br(X && 1) -> br(X).
541 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
542 }
Mike Stump1eb44332009-09-09 15:08:12 +0000543
Chris Lattner31a09842008-11-12 08:04:58 +0000544 // Emit the LHS as a conditional. If the LHS conditional is false, we
545 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000546 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
John McCall150b4622011-01-26 04:00:11 +0000547
548 ConditionalEvaluation eval(*this);
Chris Lattner31a09842008-11-12 08:04:58 +0000549 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
550 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000551
Anders Carlsson08e9e452010-01-24 00:20:05 +0000552 // Any temporaries created here are conditional.
John McCall150b4622011-01-26 04:00:11 +0000553 eval.begin(*this);
Chris Lattner31a09842008-11-12 08:04:58 +0000554 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
John McCall150b4622011-01-26 04:00:11 +0000555 eval.end(*this);
Anders Carlsson08e9e452010-01-24 00:20:05 +0000556
Chris Lattner31a09842008-11-12 08:04:58 +0000557 return;
Chris Lattnerc2c90012011-02-27 23:02:32 +0000558 }
559
560 if (CondBOp->getOpcode() == BO_LOr) {
Chris Lattner31a09842008-11-12 08:04:58 +0000561 // If we have "0 || X", simplify the code. "1 || X" would have constant
562 // folded if the case was simple enough.
Bill Wendlinge3eb83b2011-03-04 21:46:03 +0000563 bool ConstantBool = false;
Chris Lattnerc2c90012011-02-27 23:02:32 +0000564 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
565 !ConstantBool) {
Chris Lattner31a09842008-11-12 08:04:58 +0000566 // br(0 || X) -> br(X).
567 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
568 }
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Chris Lattner31a09842008-11-12 08:04:58 +0000570 // If we have "X || 0", simplify the code to use an uncond branch.
571 // "X || 1" would have been constant folded to 1.
Chris Lattnerc2c90012011-02-27 23:02:32 +0000572 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
573 !ConstantBool) {
Chris Lattner31a09842008-11-12 08:04:58 +0000574 // br(X || 0) -> br(X).
575 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
576 }
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Chris Lattner31a09842008-11-12 08:04:58 +0000578 // Emit the LHS as a conditional. If the LHS conditional is true, we
579 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000580 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
John McCall150b4622011-01-26 04:00:11 +0000581
582 ConditionalEvaluation eval(*this);
Chris Lattner31a09842008-11-12 08:04:58 +0000583 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
584 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Anders Carlsson08e9e452010-01-24 00:20:05 +0000586 // Any temporaries created here are conditional.
John McCall150b4622011-01-26 04:00:11 +0000587 eval.begin(*this);
Chris Lattner31a09842008-11-12 08:04:58 +0000588 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
John McCall150b4622011-01-26 04:00:11 +0000589 eval.end(*this);
Anders Carlsson08e9e452010-01-24 00:20:05 +0000590
Chris Lattner31a09842008-11-12 08:04:58 +0000591 return;
592 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000593 }
Mike Stump1eb44332009-09-09 15:08:12 +0000594
Chris Lattner552f4c42008-11-12 08:13:36 +0000595 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
596 // br(!x, t, f) -> br(x, f, t)
John McCall2de56d12010-08-25 11:45:40 +0000597 if (CondUOp->getOpcode() == UO_LNot)
Chris Lattner552f4c42008-11-12 08:13:36 +0000598 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000599 }
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Daniel Dunbar09b14892008-11-12 10:30:32 +0000601 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
602 // Handle ?: operator.
603
604 // Just ignore GNU ?: extension.
605 if (CondOp->getLHS()) {
606 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
607 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
608 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
John McCall150b4622011-01-26 04:00:11 +0000609
610 ConditionalEvaluation cond(*this);
Daniel Dunbar09b14892008-11-12 10:30:32 +0000611 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
John McCall150b4622011-01-26 04:00:11 +0000612
613 cond.begin(*this);
Daniel Dunbar09b14892008-11-12 10:30:32 +0000614 EmitBlock(LHSBlock);
615 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
John McCall150b4622011-01-26 04:00:11 +0000616 cond.end(*this);
617
618 cond.begin(*this);
Daniel Dunbar09b14892008-11-12 10:30:32 +0000619 EmitBlock(RHSBlock);
620 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
John McCall150b4622011-01-26 04:00:11 +0000621 cond.end(*this);
622
Daniel Dunbar09b14892008-11-12 10:30:32 +0000623 return;
624 }
625 }
626
Chris Lattner31a09842008-11-12 08:04:58 +0000627 // Emit the code with the fully general case.
628 llvm::Value *CondV = EvaluateExprAsBool(Cond);
629 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
630}
631
Daniel Dunbar488e9932008-08-16 00:56:44 +0000632/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000633/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000634void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
635 bool OmitOnError) {
636 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000637}
638
John McCall71433252011-02-01 21:35:06 +0000639/// emitNonZeroVLAInit - Emit the "zero" initialization of a
640/// variable-length array whose elements have a non-zero bit-pattern.
641///
642/// \param src - a char* pointing to the bit-pattern for a single
643/// base element of the array
644/// \param sizeInChars - the total size of the VLA, in chars
645/// \param align - the total alignment of the VLA
646static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
647 llvm::Value *dest, llvm::Value *src,
648 llvm::Value *sizeInChars) {
649 std::pair<CharUnits,CharUnits> baseSizeAndAlign
650 = CGF.getContext().getTypeInfoInChars(baseType);
651
652 CGBuilderTy &Builder = CGF.Builder;
653
654 llvm::Value *baseSizeInChars
655 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
656
Chris Lattner2acc6e32011-07-18 04:24:23 +0000657 llvm::Type *i8p = Builder.getInt8PtrTy();
John McCall71433252011-02-01 21:35:06 +0000658
659 llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
660 llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
661
662 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
663 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
664 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
665
666 // Make a loop over the VLA. C99 guarantees that the VLA element
667 // count must be nonzero.
668 CGF.EmitBlock(loopBB);
669
Jay Foadbbf3bac2011-03-30 11:28:58 +0000670 llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur");
John McCall71433252011-02-01 21:35:06 +0000671 cur->addIncoming(begin, originBB);
672
673 // memcpy the individual element bit-pattern.
674 Builder.CreateMemCpy(cur, src, baseSizeInChars,
675 baseSizeAndAlign.second.getQuantity(),
676 /*volatile*/ false);
677
678 // Go to the next element.
679 llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next");
680
681 // Leave if that's the end of the VLA.
682 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
683 Builder.CreateCondBr(done, contBB, loopBB);
684 cur->addIncoming(next, loopBB);
685
686 CGF.EmitBlock(contBB);
687}
688
Anders Carlsson1884eb02010-05-22 17:35:42 +0000689void
690CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
Anders Carlsson0d7c5832010-05-03 01:20:20 +0000691 // Ignore empty classes in C++.
692 if (getContext().getLangOptions().CPlusPlus) {
693 if (const RecordType *RT = Ty->getAs<RecordType>()) {
694 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
695 return;
696 }
697 }
John McCall90217182010-08-07 08:21:30 +0000698
699 // Cast the dest ptr to the appropriate i8 pointer type.
700 unsigned DestAS =
701 cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000702 llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000703 if (DestPtr->getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +0000704 DestPtr = Builder.CreateBitCast(DestPtr, BP);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000705
706 // Get size and alignment info for this aggregate.
Ken Dyck79be76c2011-04-22 17:51:05 +0000707 std::pair<CharUnits, CharUnits> TypeInfo =
708 getContext().getTypeInfoInChars(Ty);
709 CharUnits Size = TypeInfo.first;
710 CharUnits Align = TypeInfo.second;
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000711
John McCall5576d9b2011-01-14 10:37:58 +0000712 llvm::Value *SizeVal;
John McCall71433252011-02-01 21:35:06 +0000713 const VariableArrayType *vla;
Mike Stump1eb44332009-09-09 15:08:12 +0000714
John McCall5576d9b2011-01-14 10:37:58 +0000715 // Don't bother emitting a zero-byte memset.
Ken Dyck79be76c2011-04-22 17:51:05 +0000716 if (Size.isZero()) {
John McCall5576d9b2011-01-14 10:37:58 +0000717 // But note that getTypeInfo returns 0 for a VLA.
718 if (const VariableArrayType *vlaType =
719 dyn_cast_or_null<VariableArrayType>(
720 getContext().getAsArrayType(Ty))) {
John McCallbc8d40d2011-06-24 21:55:10 +0000721 QualType eltType;
722 llvm::Value *numElts;
723 llvm::tie(numElts, eltType) = getVLASize(vlaType);
724
725 SizeVal = numElts;
726 CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
727 if (!eltSize.isOne())
728 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
John McCall71433252011-02-01 21:35:06 +0000729 vla = vlaType;
John McCall5576d9b2011-01-14 10:37:58 +0000730 } else {
731 return;
732 }
733 } else {
John McCallbc8d40d2011-06-24 21:55:10 +0000734 SizeVal = CGM.getSize(Size);
John McCall71433252011-02-01 21:35:06 +0000735 vla = 0;
John McCall5576d9b2011-01-14 10:37:58 +0000736 }
John McCall90217182010-08-07 08:21:30 +0000737
738 // If the type contains a pointer to data member we can't memset it to zero.
739 // Instead, create a null constant and copy it to the destination.
John McCall71433252011-02-01 21:35:06 +0000740 // TODO: there are other patterns besides zero that we can usefully memset,
741 // like -1, which happens to be the pattern used by member-pointers.
John McCallf16aa102010-08-22 21:01:12 +0000742 if (!CGM.getTypes().isZeroInitializable(Ty)) {
John McCall71433252011-02-01 21:35:06 +0000743 // For a VLA, emit a single element, then splat that over the VLA.
744 if (vla) Ty = getContext().getBaseElementType(vla);
John McCall5576d9b2011-01-14 10:37:58 +0000745
John McCall90217182010-08-07 08:21:30 +0000746 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
747
748 llvm::GlobalVariable *NullVariable =
749 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
750 /*isConstant=*/true,
751 llvm::GlobalVariable::PrivateLinkage,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000752 NullConstant, Twine());
John McCall90217182010-08-07 08:21:30 +0000753 llvm::Value *SrcPtr =
754 Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
755
John McCall71433252011-02-01 21:35:06 +0000756 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
757
John McCall90217182010-08-07 08:21:30 +0000758 // Get and call the appropriate llvm.memcpy overload.
Ken Dyck79be76c2011-04-22 17:51:05 +0000759 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false);
John McCall90217182010-08-07 08:21:30 +0000760 return;
761 }
762
763 // Otherwise, just memset the whole thing to zero. This is legal
764 // because in LLVM, all default initializers (other than the ones we just
765 // handled above) are guaranteed to have a bit pattern of all zeros.
Ken Dyck79be76c2011-04-22 17:51:05 +0000766 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal,
767 Align.getQuantity(), false);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000768}
769
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000770llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000771 // Make sure that there is a block for the indirect goto.
772 if (IndirectBranch == 0)
773 GetIndirectGotoBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000774
John McCallff8e1152010-07-23 21:56:41 +0000775 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000776
Chris Lattnerd9becd12009-10-28 23:59:40 +0000777 // Make sure the indirect branch includes all of the address-taken blocks.
778 IndirectBranch->addDestination(BB);
779 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000780}
781
782llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000783 // If we already made the indirect branch for indirect goto, return its block.
784 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000785
Chris Lattnerd9becd12009-10-28 23:59:40 +0000786 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000787
788 // Create the PHI node that indirect gotos will add entries to.
Jay Foadbbf3bac2011-03-30 11:28:58 +0000789 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
790 "indirect.goto.dest");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000791
Chris Lattnerd9becd12009-10-28 23:59:40 +0000792 // Create the indirect branch instruction.
793 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
794 return IndirectBranch->getParent();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000795}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000796
John McCallbdc4d802011-07-09 01:37:26 +0000797/// Computes the length of an array in elements, as well as the base
798/// element type and a properly-typed first element pointer.
799llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
800 QualType &baseType,
801 llvm::Value *&addr) {
802 const ArrayType *arrayType = origArrayType;
803
804 // If it's a VLA, we have to load the stored size. Note that
805 // this is the size of the VLA in bytes, not its size in elements.
806 llvm::Value *numVLAElements = 0;
807 if (isa<VariableArrayType>(arrayType)) {
808 numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
809
810 // Walk into all VLAs. This doesn't require changes to addr,
811 // which has type T* where T is the first non-VLA element type.
812 do {
813 QualType elementType = arrayType->getElementType();
814 arrayType = getContext().getAsArrayType(elementType);
815
816 // If we only have VLA components, 'addr' requires no adjustment.
817 if (!arrayType) {
818 baseType = elementType;
819 return numVLAElements;
820 }
821 } while (isa<VariableArrayType>(arrayType));
822
823 // We get out here only if we find a constant array type
824 // inside the VLA.
825 }
826
827 // We have some number of constant-length arrays, so addr should
828 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
829 // down to the first element of addr.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000830 SmallVector<llvm::Value*, 8> gepIndices;
John McCallbdc4d802011-07-09 01:37:26 +0000831
832 // GEP down to the array type.
833 llvm::ConstantInt *zero = Builder.getInt32(0);
834 gepIndices.push_back(zero);
835
836 // It's more efficient to calculate the count from the LLVM
837 // constant-length arrays than to re-evaluate the array bounds.
838 uint64_t countFromCLAs = 1;
839
Chris Lattner2acc6e32011-07-18 04:24:23 +0000840 llvm::ArrayType *llvmArrayType =
John McCallbdc4d802011-07-09 01:37:26 +0000841 cast<llvm::ArrayType>(
842 cast<llvm::PointerType>(addr->getType())->getElementType());
843 while (true) {
844 assert(isa<ConstantArrayType>(arrayType));
845 assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
846 == llvmArrayType->getNumElements());
847
848 gepIndices.push_back(zero);
849 countFromCLAs *= llvmArrayType->getNumElements();
850
851 llvmArrayType =
852 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
853 if (!llvmArrayType) break;
854
855 arrayType = getContext().getAsArrayType(arrayType->getElementType());
856 assert(arrayType && "LLVM and Clang types are out-of-synch");
857 }
858
859 baseType = arrayType->getElementType();
860
861 // Create the actual GEP.
Jay Foad0f6ac7c2011-07-22 08:16:57 +0000862 addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin");
John McCallbdc4d802011-07-09 01:37:26 +0000863
864 llvm::Value *numElements
865 = llvm::ConstantInt::get(SizeTy, countFromCLAs);
866
867 // If we had any VLA dimensions, factor them in.
868 if (numVLAElements)
869 numElements = Builder.CreateNUWMul(numVLAElements, numElements);
870
871 return numElements;
872}
873
John McCallbc8d40d2011-06-24 21:55:10 +0000874std::pair<llvm::Value*, QualType>
875CodeGenFunction::getVLASize(QualType type) {
876 const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
877 assert(vla && "type was not a variable array type!");
878 return getVLASize(vla);
Anders Carlssonf666b772008-12-20 20:27:15 +0000879}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000880
John McCallbc8d40d2011-06-24 21:55:10 +0000881std::pair<llvm::Value*, QualType>
882CodeGenFunction::getVLASize(const VariableArrayType *type) {
883 // The number of elements so far; always size_t.
884 llvm::Value *numElements = 0;
885
886 QualType elementType;
887 do {
888 elementType = type->getElementType();
889 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
890 assert(vlaSize && "no size for VLA!");
891 assert(vlaSize->getType() == SizeTy);
892
893 if (!numElements) {
894 numElements = vlaSize;
895 } else {
896 // It's undefined behavior if this wraps around, so mark it that way.
897 numElements = Builder.CreateNUWMul(numElements, vlaSize);
898 }
899 } while ((type = getContext().getAsVariableArrayType(elementType)));
900
901 return std::pair<llvm::Value*,QualType>(numElements, elementType);
902}
903
904void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
905 assert(type->isVariablyModifiedType() &&
Anders Carlsson60d35412008-12-20 20:46:34 +0000906 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Daniel Dunbard286f052009-07-19 06:58:07 +0000908 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000909
John McCallbc8d40d2011-06-24 21:55:10 +0000910 // We're going to walk down into the type and look for VLA
911 // expressions.
912 type = type.getCanonicalType();
913 do {
914 assert(type->isVariablyModifiedType());
Mike Stump1eb44332009-09-09 15:08:12 +0000915
John McCallbc8d40d2011-06-24 21:55:10 +0000916 const Type *ty = type.getTypePtr();
917 switch (ty->getTypeClass()) {
918#define TYPE(Class, Base)
919#define ABSTRACT_TYPE(Class, Base)
920#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
921#define DEPENDENT_TYPE(Class, Base) case Type::Class:
922#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
923#include "clang/AST/TypeNodes.def"
924 llvm_unreachable("unexpected dependent or non-canonical type!");
Mike Stump1eb44332009-09-09 15:08:12 +0000925
John McCallbc8d40d2011-06-24 21:55:10 +0000926 // These types are never variably-modified.
927 case Type::Builtin:
928 case Type::Complex:
929 case Type::Vector:
930 case Type::ExtVector:
931 case Type::Record:
932 case Type::Enum:
933 case Type::ObjCObject:
934 case Type::ObjCInterface:
935 case Type::ObjCObjectPointer:
936 llvm_unreachable("type class is never variably-modified!");
Mike Stump1eb44332009-09-09 15:08:12 +0000937
John McCallbc8d40d2011-06-24 21:55:10 +0000938 case Type::Pointer:
939 type = cast<PointerType>(ty)->getPointeeType();
940 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000941
John McCallbc8d40d2011-06-24 21:55:10 +0000942 case Type::BlockPointer:
943 type = cast<BlockPointerType>(ty)->getPointeeType();
944 break;
945
946 case Type::LValueReference:
947 case Type::RValueReference:
948 type = cast<ReferenceType>(ty)->getPointeeType();
949 break;
950
951 case Type::MemberPointer:
952 type = cast<MemberPointerType>(ty)->getPointeeType();
953 break;
954
955 case Type::ConstantArray:
956 case Type::IncompleteArray:
957 // Losing element qualification here is fine.
958 type = cast<ArrayType>(ty)->getElementType();
959 break;
960
961 case Type::VariableArray: {
962 // Losing element qualification here is fine.
963 const VariableArrayType *vat = cast<VariableArrayType>(ty);
964
965 // Unknown size indication requires no size computation.
966 // Otherwise, evaluate and record it.
967 if (const Expr *size = vat->getSizeExpr()) {
968 // It's possible that we might have emitted this already,
969 // e.g. with a typedef and a pointer to it.
970 llvm::Value *&entry = VLASizeMap[size];
971 if (!entry) {
972 // Always zexting here would be wrong if it weren't
973 // undefined behavior to have a negative bound.
974 entry = Builder.CreateIntCast(EmitScalarExpr(size), SizeTy,
975 /*signed*/ false);
976 }
977 }
978 type = vat->getElementType();
979 break;
Anders Carlsson60d35412008-12-20 20:46:34 +0000980 }
Mike Stump1eb44332009-09-09 15:08:12 +0000981
John McCallbc8d40d2011-06-24 21:55:10 +0000982 case Type::FunctionProto:
983 case Type::FunctionNoProto:
984 type = cast<FunctionType>(ty)->getResultType();
985 break;
986 }
987 } while (type->isVariablyModifiedType());
Anders Carlssondcc90d82008-12-12 07:19:02 +0000988}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000989
990llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
Dan Gohmanbc07a552010-10-29 22:47:07 +0000991 if (getContext().getBuiltinVaListType()->isArrayType())
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000992 return EmitScalarExpr(E);
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000993 return EmitLValue(E).getAddress();
994}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000995
Devang Patel8d308382010-08-10 07:24:25 +0000996void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
John McCall189d6ef2010-10-09 01:34:31 +0000997 llvm::Constant *Init) {
Devang Patel25c2c8f2010-08-10 17:53:33 +0000998 assert (Init && "Invalid DeclRefExpr initializer!");
999 if (CGDebugInfo *Dbg = getDebugInfo())
Devang Pateld2829b72010-10-06 15:58:57 +00001000 Dbg->EmitGlobalVariable(E->getDecl(), Init);
Devang Patel8d308382010-08-10 07:24:25 +00001001}
John McCall56ca35d2011-02-17 10:25:35 +00001002
1003CodeGenFunction::PeepholeProtection
1004CodeGenFunction::protectFromPeepholes(RValue rvalue) {
1005 // At the moment, the only aggressive peephole we do in IR gen
1006 // is trunc(zext) folding, but if we add more, we can easily
1007 // extend this protection.
1008
1009 if (!rvalue.isScalar()) return PeepholeProtection();
1010 llvm::Value *value = rvalue.getScalarVal();
1011 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
1012
1013 // Just make an extra bitcast.
1014 assert(HaveInsertPoint());
1015 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
1016 Builder.GetInsertBlock());
1017
1018 PeepholeProtection protection;
1019 protection.Inst = inst;
1020 return protection;
1021}
1022
1023void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
1024 if (!protection.Inst) return;
1025
1026 // In theory, we could try to duplicate the peepholes now, but whatever.
1027 protection.Inst->eraseFromParent();
1028}
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001029
1030llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
1031 llvm::Value *AnnotatedVal,
1032 llvm::StringRef AnnotationStr,
1033 SourceLocation Location) {
1034 llvm::Value *Args[4] = {
1035 AnnotatedVal,
1036 Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
1037 Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
1038 CGM.EmitAnnotationLineNo(Location)
1039 };
1040 return Builder.CreateCall(AnnotationFn, Args);
1041}
1042
1043void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
1044 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1045 // FIXME We create a new bitcast for every annotation because that's what
1046 // llvm-gcc was doing.
1047 for (specific_attr_iterator<AnnotateAttr>
1048 ai = D->specific_attr_begin<AnnotateAttr>(),
1049 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
1050 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
1051 Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
1052 (*ai)->getAnnotation(), D->getLocation());
1053}
1054
1055llvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
1056 llvm::Value *V) {
1057 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1058 llvm::Type *VTy = V->getType();
1059 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
1060 CGM.Int8PtrTy);
1061
1062 for (specific_attr_iterator<AnnotateAttr>
1063 ai = D->specific_attr_begin<AnnotateAttr>(),
1064 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) {
1065 // FIXME Always emit the cast inst so we can differentiate between
1066 // annotation on the first field of a struct and annotation on the struct
1067 // itself.
1068 if (VTy != CGM.Int8PtrTy)
1069 V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
1070 V = EmitAnnotationCall(F, V, (*ai)->getAnnotation(), D->getLocation());
1071 V = Builder.CreateBitCast(V, VTy);
1072 }
1073
1074 return V;
1075}