blob: f4b483b51584f97ca4d38b4fc7f82c78c494a1ac [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"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/Basic/TargetInfo.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000021#include "clang/AST/Decl.h"
Anders Carlsson2b77ba82009-04-04 20:47:02 +000022#include "clang/AST/DeclCXX.h"
Mike Stump6a1e0eb2009-12-04 23:26:17 +000023#include "clang/AST/StmtCXX.h"
Chris Lattner7255a2d2010-06-22 00:03:40 +000024#include "clang/Frontend/CodeGenOptions.h"
Chris Lattner7255a2d2010-06-22 00:03:40 +000025#include "llvm/Intrinsics.h"
Duncan Sands10e675d2012-04-16 17:24:31 +000026#include "llvm/Support/MDBuilder.h"
27#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028using namespace clang;
29using namespace CodeGen;
30
Mike Stump1eb44332009-09-09 15:08:12 +000031CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
John McCall5936e332011-02-15 09:22:45 +000032 : CodeGenTypeCache(cgm), CGM(cgm),
Eli Friedmancec5ebd2012-02-11 02:57:39 +000033 Target(CGM.getContext().getTargetInfo()),
34 Builder(cgm.getModule().getContext()),
John McCallf85e1932011-06-15 23:02:42 +000035 AutoreleaseResult(false), BlockInfo(0), BlockPointer(0),
Eli Friedman23f02672012-03-01 04:01:32 +000036 LambdaThisCaptureField(0), NormalCleanupDest(0), NextCleanupDestIndex(1),
Eli Friedmancec5ebd2012-02-11 02:57:39 +000037 FirstBlockInfo(0), 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),
Eli Friedmancec5ebd2012-02-11 02:57:39 +000040 CXXABIThisDecl(0), CXXABIThisValue(0), CXXThisValue(0), CXXVTTDecl(0),
41 CXXVTTValue(0), OutermostConditional(0), TerminateLandingPad(0),
42 TerminateHandler(0), TrapBB(0) {
Anders Carlssonc1cfdf82011-02-20 00:20:27 +000043
David Blaikie4e4d0842012-03-11 07:00:24 +000044 CatchUndefined = getContext().getLangOpts().CatchUndefined;
Duncan Sands10e675d2012-04-16 17:24:31 +000045 if (getContext().getLangOpts().FastMath) {
46 llvm::MDBuilder MDHelper(Builder.getContext());
47 Builder.SetDefaultFPMathTag(MDHelper.createFastFPMath());
48 }
John McCall4c40d982010-08-31 07:33:07 +000049 CGM.getCXXABI().getMangleContext().startNewFunction();
Chris Lattner41110242008-06-17 18:05:57 +000050}
Reid Spencer5f016e22007-07-11 17:01:13 +000051
John McCall1a343eb2011-11-10 08:15:53 +000052CodeGenFunction::~CodeGenFunction() {
53 // If there are any unclaimed block infos, go ahead and destroy them
54 // now. This can happen if IR-gen gets clever and skips evaluating
55 // something.
56 if (FirstBlockInfo)
57 destroyBlockInfos(FirstBlockInfo);
58}
59
Reid Spencer5f016e22007-07-11 17:01:13 +000060
Chris Lattner9cbe4f02011-07-09 17:41:47 +000061llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000062 return CGM.getTypes().ConvertTypeForMem(T);
63}
64
Chris Lattner9cbe4f02011-07-09 17:41:47 +000065llvm::Type *CodeGenFunction::ConvertType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +000066 return CGM.getTypes().ConvertType(T);
67}
68
John McCallf2aac842011-05-15 02:34:36 +000069bool CodeGenFunction::hasAggregateLLVMType(QualType type) {
70 switch (type.getCanonicalType()->getTypeClass()) {
71#define TYPE(name, parent)
72#define ABSTRACT_TYPE(name, parent)
73#define NON_CANONICAL_TYPE(name, parent) case Type::name:
74#define DEPENDENT_TYPE(name, parent) case Type::name:
75#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
76#include "clang/AST/TypeNodes.def"
77 llvm_unreachable("non-canonical or dependent type in IR-generation");
78
79 case Type::Builtin:
80 case Type::Pointer:
81 case Type::BlockPointer:
82 case Type::LValueReference:
83 case Type::RValueReference:
84 case Type::MemberPointer:
85 case Type::Vector:
86 case Type::ExtVector:
87 case Type::FunctionProto:
88 case Type::FunctionNoProto:
89 case Type::Enum:
90 case Type::ObjCObjectPointer:
91 return false;
92
93 // Complexes, arrays, records, and Objective-C objects.
94 case Type::Complex:
95 case Type::ConstantArray:
96 case Type::IncompleteArray:
97 case Type::VariableArray:
98 case Type::Record:
99 case Type::ObjCObject:
100 case Type::ObjCInterface:
101 return true;
Eli Friedmanb001de72011-10-06 23:00:33 +0000102
103 // In IRGen, atomic types are just the underlying type
104 case Type::Atomic:
105 return hasAggregateLLVMType(type->getAs<AtomicType>()->getValueType());
John McCallf2aac842011-05-15 02:34:36 +0000106 }
107 llvm_unreachable("unknown type kind!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000108}
109
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000110void CodeGenFunction::EmitReturnBlock() {
111 // For cleanliness, we try to avoid emitting the return block for
112 // simple cases.
113 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
114
115 if (CurBB) {
116 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
117
Daniel Dunbar96e18b02009-07-19 08:24:34 +0000118 // We have a valid insert point, reuse it if it is empty or there are no
119 // explicit jumps to the return block.
John McCallff8e1152010-07-23 21:56:41 +0000120 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
121 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
122 delete ReturnBlock.getBlock();
Daniel Dunbar96e18b02009-07-19 08:24:34 +0000123 } else
John McCallff8e1152010-07-23 21:56:41 +0000124 EmitBlock(ReturnBlock.getBlock());
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000125 return;
126 }
127
128 // Otherwise, if the return block is the target of a single direct
129 // branch then we can just put the code in that block instead. This
130 // cleans up functions which started with a unified return block.
John McCallff8e1152010-07-23 21:56:41 +0000131 if (ReturnBlock.getBlock()->hasOneUse()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000132 llvm::BranchInst *BI =
John McCallff8e1152010-07-23 21:56:41 +0000133 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin());
John McCallf1549f62010-07-06 01:34:17 +0000134 if (BI && BI->isUnconditional() &&
John McCallff8e1152010-07-23 21:56:41 +0000135 BI->getSuccessor(0) == ReturnBlock.getBlock()) {
Eric Christopheracae0112011-09-09 21:53:04 +0000136 // Reset insertion point, including debug location, and delete the branch.
137 Builder.SetCurrentDebugLocation(BI->getDebugLoc());
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000138 Builder.SetInsertPoint(BI->getParent());
139 BI->eraseFromParent();
John McCallff8e1152010-07-23 21:56:41 +0000140 delete ReturnBlock.getBlock();
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000141 return;
142 }
143 }
144
Mike Stumpf5408fe2009-05-16 07:57:57 +0000145 // FIXME: We are at an unreachable point, there is no reason to emit the block
146 // unless it has uses. However, we still need a place to put the debug
147 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000148
John McCallff8e1152010-07-23 21:56:41 +0000149 EmitBlock(ReturnBlock.getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000150}
151
152static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
153 if (!BB) return;
154 if (!BB->use_empty())
155 return CGF.CurFn->getBasicBlockList().push_back(BB);
156 delete BB;
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000157}
158
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000159void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnerda138702007-07-16 21:28:45 +0000160 assert(BreakContinueStack.empty() &&
161 "mismatched push/pop in break/continue stack!");
Mike Stump1eb44332009-09-09 15:08:12 +0000162
John McCallf85e1932011-06-15 23:02:42 +0000163 // Pop any cleanups that might have been associated with the
164 // parameters. Do this in whatever block we're currently in; it's
165 // important to do this before we enter the return block or return
166 // edges will be *really* confused.
167 if (EHStack.stable_begin() != PrologueCleanupDepth)
168 PopCleanupBlocks(PrologueCleanupDepth);
169
Mike Stump1eb44332009-09-09 15:08:12 +0000170 // Emit function epilog (to return).
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000171 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000172
Daniel Dunbara18652f2011-02-10 17:32:22 +0000173 if (ShouldInstrumentFunction())
174 EmitFunctionInstrumentation("__cyg_profile_func_exit");
Chris Lattner7255a2d2010-06-22 00:03:40 +0000175
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000176 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000177 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000178 DI->setLocation(EndLoc);
Devang Patel5a6fbcf2010-07-22 22:29:16 +0000179 DI->EmitFunctionEnd(Builder);
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000180 }
181
Chris Lattner35b21b82010-06-27 01:06:27 +0000182 EmitFunctionEpilog(*CurFnInfo);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000183 EmitEndEHSpec(CurCodeDecl);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000184
John McCallf1549f62010-07-06 01:34:17 +0000185 assert(EHStack.empty() &&
186 "did not remove all scopes from cleanup stack!");
187
Chris Lattnerd9becd12009-10-28 23:59:40 +0000188 // If someone did an indirect goto, emit the indirect goto block at the end of
189 // the function.
190 if (IndirectBranch) {
191 EmitBlock(IndirectBranch->getParent());
192 Builder.ClearInsertionPoint();
193 }
194
Chris Lattner5a2fa142007-12-02 06:32:24 +0000195 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000196 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000197 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000198 Ptr->eraseFromParent();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000199
200 // If someone took the address of a label but never did an indirect goto, we
201 // made a zero entry PHI node, which is illegal, zap it now.
202 if (IndirectBranch) {
203 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
204 if (PN->getNumIncomingValues() == 0) {
205 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
206 PN->eraseFromParent();
207 }
208 }
John McCallf1549f62010-07-06 01:34:17 +0000209
John McCall777d6e52011-08-11 02:22:43 +0000210 EmitIfUsed(*this, EHResumeBlock);
John McCallf1549f62010-07-06 01:34:17 +0000211 EmitIfUsed(*this, TerminateLandingPad);
212 EmitIfUsed(*this, TerminateHandler);
213 EmitIfUsed(*this, UnreachableBlock);
John McCall744016d2010-07-06 23:57:41 +0000214
215 if (CGM.getCodeGenOpts().EmitDeclMetadata)
216 EmitDeclMetadata();
Reid Spencer5f016e22007-07-11 17:01:13 +0000217}
218
Chris Lattner7255a2d2010-06-22 00:03:40 +0000219/// ShouldInstrumentFunction - Return true if the current function should be
220/// instrumented with __cyg_profile_func_* calls
221bool CodeGenFunction::ShouldInstrumentFunction() {
222 if (!CGM.getCodeGenOpts().InstrumentFunctions)
223 return false;
Ted Kremenek7aa488a2011-05-16 23:49:20 +0000224 if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
Chris Lattner7255a2d2010-06-22 00:03:40 +0000225 return false;
226 return true;
227}
228
229/// EmitFunctionInstrumentation - Emit LLVM code to call the specified
230/// instrumentation function with the current function and the call site, if
231/// function instrumentation is enabled.
232void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
Chris Lattner8dab6572010-06-23 05:21:28 +0000233 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000234 llvm::PointerType *PointerTy = Int8PtrTy;
235 llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +0000236 llvm::FunctionType *FunctionTy =
Chris Lattner8b418682012-02-07 00:39:47 +0000237 llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000238
239 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
240 llvm::CallInst *CallSite = Builder.CreateCall(
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000241 CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
Chris Lattner77b89b82010-06-27 07:15:29 +0000242 llvm::ConstantInt::get(Int32Ty, 0),
Chris Lattner7255a2d2010-06-22 00:03:40 +0000243 "callsite");
244
Chris Lattner8dab6572010-06-23 05:21:28 +0000245 Builder.CreateCall2(F,
246 llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
247 CallSite);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000248}
249
Roman Divackybe4c8702011-02-10 16:52:03 +0000250void CodeGenFunction::EmitMCountInstrumentation() {
Chris Lattner8b418682012-02-07 00:39:47 +0000251 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
Roman Divackybe4c8702011-02-10 16:52:03 +0000252
253 llvm::Constant *MCountFn = CGM.CreateRuntimeFunction(FTy,
254 Target.getMCountName());
255 Builder.CreateCall(MCountFn);
256}
257
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000258void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000259 llvm::Function *Fn,
John McCalld26bc762011-03-09 04:27:21 +0000260 const CGFunctionInfo &FnInfo,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000261 const FunctionArgList &Args,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000262 SourceLocation StartLoc) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000263 const Decl *D = GD.getDecl();
264
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000265 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000266 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000267 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000268 CurFn = Fn;
John McCalld26bc762011-03-09 04:27:21 +0000269 CurFnInfo = &FnInfo;
Chris Lattner41110242008-06-17 18:05:57 +0000270 assert(CurFn->isDeclaration() && "Function already has body?");
271
Jakob Stoklund Olesena3fe2842010-02-09 00:10:00 +0000272 // Pass inline keyword to optimizer if it appears explicitly on any
273 // declaration.
Chad Rosier8fbe3852012-03-14 23:32:11 +0000274 if (!CGM.getCodeGenOpts().NoInline)
275 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
276 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
277 RE = FD->redecls_end(); RI != RE; ++RI)
278 if (RI->isInlineSpecified()) {
279 Fn->addFnAttr(llvm::Attribute::InlineHint);
280 break;
281 }
Jakob Stoklund Olesena3fe2842010-02-09 00:10:00 +0000282
David Blaikie4e4d0842012-03-11 07:00:24 +0000283 if (getContext().getLangOpts().OpenCL) {
Peter Collingbournef315fa82011-02-14 01:42:53 +0000284 // Add metadata for a kernel function.
285 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
286 if (FD->hasAttr<OpenCLKernelAttr>()) {
287 llvm::LLVMContext &Context = getLLVMContext();
288 llvm::NamedMDNode *OpenCLMetadata =
289 CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
290
291 llvm::Value *Op = Fn;
Jay Foad6f141652011-04-21 19:59:12 +0000292 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Op));
Peter Collingbournef315fa82011-02-14 01:42:53 +0000293 }
294 }
295
Daniel Dunbar55e87422008-11-11 02:29:29 +0000296 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000297
Chris Lattner41110242008-06-17 18:05:57 +0000298 // Create a marker to make it easy to insert allocas into the entryblock
299 // later. Don't create this with the builder, because we don't want it
300 // folded.
Chris Lattner77b89b82010-06-27 07:15:29 +0000301 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
302 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000303 if (Builder.isNamePreserving())
304 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000305
John McCallf1549f62010-07-06 01:34:17 +0000306 ReturnBlock = getJumpDestInCurrentScope("return");
Mike Stump1eb44332009-09-09 15:08:12 +0000307
Chris Lattner41110242008-06-17 18:05:57 +0000308 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000309
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000310 // Emit subprogram debug descriptor.
Anders Carlssone896d982009-02-13 08:11:52 +0000311 if (CGDebugInfo *DI = getDebugInfo()) {
Eric Christopher06253662011-10-21 23:30:10 +0000312 unsigned NumArgs = 0;
313 QualType *ArgsArray = new QualType[Args.size()];
314 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
315 i != e; ++i) {
316 ArgsArray[NumArgs++] = (*i)->getType();
317 }
318
John McCalle23cf432010-12-14 08:05:40 +0000319 QualType FnType =
Eric Christopher06253662011-10-21 23:30:10 +0000320 getContext().getFunctionType(RetTy, ArgsArray, NumArgs,
John McCalle23cf432010-12-14 08:05:40 +0000321 FunctionProtoType::ExtProtoInfo());
322
Benjamin Kramer2a04f1c2011-10-24 17:22:36 +0000323 delete[] ArgsArray;
Eric Christopher06253662011-10-21 23:30:10 +0000324
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000325 DI->setLocation(StartLoc);
Devang Patel9c6c3a02010-01-14 00:36:21 +0000326 DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000327 }
328
Daniel Dunbara18652f2011-02-10 17:32:22 +0000329 if (ShouldInstrumentFunction())
330 EmitFunctionInstrumentation("__cyg_profile_func_enter");
Chris Lattner7255a2d2010-06-22 00:03:40 +0000331
Roman Divackybe4c8702011-02-10 16:52:03 +0000332 if (CGM.getCodeGenOpts().InstrumentForProfiling)
333 EmitMCountInstrumentation();
334
Eli Friedmanb17daf92009-12-04 02:43:40 +0000335 if (RetTy->isVoidType()) {
336 // Void type; nothing to return.
337 ReturnValue = 0;
338 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
339 hasAggregateLLVMType(CurFnInfo->getReturnType())) {
340 // Indirect aggregate return; emit returned value directly into sret slot.
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000341 // This reduces code size, and affects correctness in C++.
Eli Friedmanb17daf92009-12-04 02:43:40 +0000342 ReturnValue = CurFn->arg_begin();
343 } else {
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000344 ReturnValue = CreateIRTemp(RetTy, "retval");
John McCallf85e1932011-06-15 23:02:42 +0000345
346 // Tell the epilog emitter to autorelease the result. We do this
347 // now so that various specialized functions can suppress it
348 // during their IR-generation.
David Blaikie4e4d0842012-03-11 07:00:24 +0000349 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000350 !CurFnInfo->isReturnsRetained() &&
351 RetTy->isObjCRetainableType())
352 AutoreleaseResult = true;
Eli Friedmanb17daf92009-12-04 02:43:40 +0000353 }
354
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000355 EmitStartEHSpec(CurCodeDecl);
John McCallf85e1932011-06-15 23:02:42 +0000356
357 PrologueCleanupDepth = EHStack.stable_begin();
Daniel Dunbar88b53962009-02-02 22:03:45 +0000358 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000360 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
John McCall4c40d982010-08-31 07:33:07 +0000361 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000362 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
363 if (MD->getParent()->isLambda() &&
364 MD->getOverloadedOperator() == OO_Call) {
365 // We're in a lambda; figure out the captures.
366 MD->getParent()->getCaptureFields(LambdaCaptureFields,
367 LambdaThisCaptureField);
368 if (LambdaThisCaptureField) {
369 // If this lambda captures this, load it.
Eli Friedman377ecc72012-04-16 03:54:45 +0000370 QualType LambdaTagType =
371 getContext().getTagDeclType(LambdaThisCaptureField->getParent());
372 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue,
373 LambdaTagType);
374 LValue ThisLValue = EmitLValueForField(LambdaLV,
375 LambdaThisCaptureField);
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000376 CXXThisValue = EmitLoadOfLValue(ThisLValue).getScalarVal();
377 }
378 } else {
379 // Not in a lambda; just use 'this' from the method.
380 // FIXME: Should we generate a new load for each use of 'this'? The
381 // fast register allocator would be happier...
382 CXXThisValue = CXXABIThisValue;
383 }
384 }
John McCall25049412010-02-16 22:04:33 +0000385
Anders Carlsson751358f2008-12-20 21:28:43 +0000386 // If any of the arguments have a variably modified type, make sure to
387 // emit the type size.
388 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
389 i != e; ++i) {
John McCalld26bc762011-03-09 04:27:21 +0000390 QualType Ty = (*i)->getType();
Anders Carlsson751358f2008-12-20 21:28:43 +0000391
392 if (Ty->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000393 EmitVariablyModifiedType(Ty);
Anders Carlsson751358f2008-12-20 21:28:43 +0000394 }
Eric Christopher73fb3502011-10-13 21:45:18 +0000395 // Emit a location at the end of the prologue.
396 if (CGDebugInfo *DI = getDebugInfo())
397 DI->EmitLocation(Builder, StartLoc);
Daniel Dunbar7c086512008-09-09 23:14:03 +0000398}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000399
John McCall9fc6a772010-02-19 09:25:03 +0000400void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
401 const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
Douglas Gregor06a9f362010-05-01 20:49:11 +0000402 assert(FD->getBody());
403 EmitStmt(FD->getBody());
John McCalla355e072010-02-18 03:17:58 +0000404}
405
John McCall39dad532010-08-03 22:46:07 +0000406/// Tries to mark the given function nounwind based on the
407/// non-existence of any throwing calls within it. We believe this is
408/// lightweight enough to do at -O0.
409static void TryMarkNoThrow(llvm::Function *F) {
John McCallb3a29f12010-08-11 22:38:33 +0000410 // LLVM treats 'nounwind' on a function as part of the type, so we
411 // can't do this on functions that can be overwritten.
412 if (F->mayBeOverridden()) return;
413
John McCall39dad532010-08-03 22:46:07 +0000414 for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
415 for (llvm::BasicBlock::iterator
416 BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
Bill Wendling285cfd82011-09-19 20:31:14 +0000417 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) {
John McCall39dad532010-08-03 22:46:07 +0000418 if (!Call->doesNotThrow())
419 return;
Bill Wendling285cfd82011-09-19 20:31:14 +0000420 } else if (isa<llvm::ResumeInst>(&*BI)) {
421 return;
422 }
John McCall39dad532010-08-03 22:46:07 +0000423 F->setDoesNotThrow(true);
424}
425
John McCalld26bc762011-03-09 04:27:21 +0000426void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
427 const CGFunctionInfo &FnInfo) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000428 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
429
Anders Carlssone896d982009-02-13 08:11:52 +0000430 // Check if we should generate debug info for this function.
Devang Patelaa112892011-03-07 18:45:56 +0000431 if (CGM.getModuleDebugInfo() && !FD->hasAttr<NoDebugAttr>())
432 DebugInfo = CGM.getModuleDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Daniel Dunbar7c086512008-09-09 23:14:03 +0000434 FunctionArgList Args;
John McCall4c40d982010-08-31 07:33:07 +0000435 QualType ResTy = FD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Mike Stump6a1e0eb2009-12-04 23:26:17 +0000437 CurGD = GD;
John McCall4c40d982010-08-31 07:33:07 +0000438 if (isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isInstance())
439 CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Chad Rosier6e94f6c2012-02-18 00:37:07 +0000441 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
442 Args.push_back(FD->getParamDecl(i));
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000443
John McCalla355e072010-02-18 03:17:58 +0000444 SourceRange BodyRange;
445 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
Anders Carlsson4365bba2009-11-06 02:55:43 +0000446
John McCalla355e072010-02-18 03:17:58 +0000447 // Emit the standard function prologue.
John McCalld26bc762011-03-09 04:27:21 +0000448 StartFunction(GD, ResTy, Fn, FnInfo, Args, BodyRange.getBegin());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000449
John McCalla355e072010-02-18 03:17:58 +0000450 // Generate the body of the function.
John McCall9fc6a772010-02-19 09:25:03 +0000451 if (isa<CXXDestructorDecl>(FD))
452 EmitDestructorBody(Args);
453 else if (isa<CXXConstructorDecl>(FD))
454 EmitConstructorBody(Args);
David Blaikie4e4d0842012-03-11 07:00:24 +0000455 else if (getContext().getLangOpts().CUDA &&
Peter Collingbournea4ae2292011-10-06 18:51:56 +0000456 !CGM.getCodeGenOpts().CUDAIsDevice &&
457 FD->hasAttr<CUDAGlobalAttr>())
458 CGM.getCUDARuntime().EmitDeviceStubBody(*this, Args);
Eli Friedmanbd89f8c2012-02-16 01:37:33 +0000459 else if (isa<CXXConversionDecl>(FD) &&
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000460 cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
461 // The lambda conversion to block pointer is special; the semantics can't be
462 // expressed in the AST, so IRGen needs to special-case it.
463 EmitLambdaToBlockPointerBody(Args);
464 } else if (isa<CXXMethodDecl>(FD) &&
465 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
466 // The lambda "__invoke" function is special, because it forwards or
467 // clones the body of the function call operator (but is actually static).
468 EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
Eli Friedmanbd89f8c2012-02-16 01:37:33 +0000469 }
John McCall9fc6a772010-02-19 09:25:03 +0000470 else
471 EmitFunctionBody(Args);
Anders Carlsson1851a122010-02-07 19:45:40 +0000472
John McCalla355e072010-02-18 03:17:58 +0000473 // Emit the standard function epilogue.
474 FinishFunction(BodyRange.getEnd());
John McCall39dad532010-08-03 22:46:07 +0000475
476 // If we haven't marked the function nothrow through other means, do
477 // a quick pass now to see if we can.
478 if (!CurFn->doesNotThrow())
479 TryMarkNoThrow(CurFn);
Chris Lattner41110242008-06-17 18:05:57 +0000480}
481
Chris Lattner0946ccd2008-11-11 07:41:27 +0000482/// ContainsLabel - Return true if the statement contains a label in it. If
483/// this statement is not executed normally, it not containing a label means
484/// that we can just remove the code.
485bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
486 // Null statement, not a label!
487 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Chris Lattner0946ccd2008-11-11 07:41:27 +0000489 // If this is a label, we have to emit the code, consider something like:
490 // if (0) { ... foo: bar(); } goto foo;
Chris Lattneref425a62011-02-28 00:18:40 +0000491 //
492 // TODO: If anyone cared, we could track __label__'s, since we know that you
493 // can't jump to one from outside their declared region.
Chris Lattner0946ccd2008-11-11 07:41:27 +0000494 if (isa<LabelStmt>(S))
495 return true;
Chris Lattneref425a62011-02-28 00:18:40 +0000496
Chris Lattner0946ccd2008-11-11 07:41:27 +0000497 // If this is a case/default statement, and we haven't seen a switch, we have
498 // to emit the code.
499 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
500 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Chris Lattner0946ccd2008-11-11 07:41:27 +0000502 // If this is a switch statement, we want to ignore cases below it.
503 if (isa<SwitchStmt>(S))
504 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Chris Lattner0946ccd2008-11-11 07:41:27 +0000506 // Scan subexpressions for verboten labels.
John McCall7502c1d2011-02-13 04:07:26 +0000507 for (Stmt::const_child_range I = S->children(); I; ++I)
Chris Lattner0946ccd2008-11-11 07:41:27 +0000508 if (ContainsLabel(*I, IgnoreCaseStmts))
509 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Chris Lattner0946ccd2008-11-11 07:41:27 +0000511 return false;
512}
513
Chris Lattneref425a62011-02-28 00:18:40 +0000514/// containsBreak - Return true if the statement contains a break out of it.
515/// If the statement (recursively) contains a switch or loop with a break
516/// inside of it, this is fine.
517bool CodeGenFunction::containsBreak(const Stmt *S) {
518 // Null statement, not a label!
519 if (S == 0) return false;
520
521 // If this is a switch or loop that defines its own break scope, then we can
522 // include it and anything inside of it.
523 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
524 isa<ForStmt>(S))
Chris Lattner2bef7f52011-02-28 00:42:31 +0000525 return false;
526
527 if (isa<BreakStmt>(S))
Chris Lattneref425a62011-02-28 00:18:40 +0000528 return true;
529
530 // Scan subexpressions for verboten breaks.
531 for (Stmt::const_child_range I = S->children(); I; ++I)
532 if (containsBreak(*I))
533 return true;
534
535 return false;
536}
537
Chris Lattner31a09842008-11-12 08:04:58 +0000538
Chris Lattnerc2c90012011-02-27 23:02:32 +0000539/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
540/// to a constant, or if it does but contains a label, return false. If it
541/// constant folds return true and set the boolean result in Result.
542bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
543 bool &ResultBool) {
Chris Lattneref425a62011-02-28 00:18:40 +0000544 llvm::APInt ResultInt;
545 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
546 return false;
547
548 ResultBool = ResultInt.getBoolValue();
549 return true;
550}
551
552/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
553/// to a constant, or if it does but contains a label, return false. If it
554/// constant folds return true and set the folded value.
555bool CodeGenFunction::
556ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APInt &ResultInt) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000557 // FIXME: Rename and handle conversion of other evaluatable things
558 // to bool.
Richard Smith80d4b552011-12-28 19:48:30 +0000559 llvm::APSInt Int;
560 if (!Cond->EvaluateAsInt(Int, getContext()))
Chris Lattnerc2c90012011-02-27 23:02:32 +0000561 return false; // Not foldable, not integer or not fully evaluatable.
Richard Smith80d4b552011-12-28 19:48:30 +0000562
Chris Lattner31a09842008-11-12 08:04:58 +0000563 if (CodeGenFunction::ContainsLabel(Cond))
Chris Lattnerc2c90012011-02-27 23:02:32 +0000564 return false; // Contains a label.
Richard Smith80d4b552011-12-28 19:48:30 +0000565
566 ResultInt = Int;
Chris Lattnerc2c90012011-02-27 23:02:32 +0000567 return true;
Chris Lattner31a09842008-11-12 08:04:58 +0000568}
569
570
Chris Lattneref425a62011-02-28 00:18:40 +0000571
Chris Lattner31a09842008-11-12 08:04:58 +0000572/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
573/// statement) to the specified blocks. Based on the condition, this might try
574/// to simplify the codegen of the conditional based on the branch.
575///
576void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
577 llvm::BasicBlock *TrueBlock,
578 llvm::BasicBlock *FalseBlock) {
Peter Collingbournef111d932011-04-15 00:35:48 +0000579 Cond = Cond->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +0000580
Chris Lattner31a09842008-11-12 08:04:58 +0000581 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
582 // Handle X && Y in a condition.
John McCall2de56d12010-08-25 11:45:40 +0000583 if (CondBOp->getOpcode() == BO_LAnd) {
Chris Lattner31a09842008-11-12 08:04:58 +0000584 // If we have "1 && X", simplify the code. "0 && X" would have constant
585 // folded if the case was simple enough.
Bill Wendlinge3eb83b2011-03-04 21:46:03 +0000586 bool ConstantBool = false;
Chris Lattnerc2c90012011-02-27 23:02:32 +0000587 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
588 ConstantBool) {
Chris Lattner31a09842008-11-12 08:04:58 +0000589 // br(1 && X) -> br(X).
590 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
591 }
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Chris Lattner31a09842008-11-12 08:04:58 +0000593 // If we have "X && 1", simplify the code to use an uncond branch.
594 // "X && 0" would have been constant folded to 0.
Chris Lattnerc2c90012011-02-27 23:02:32 +0000595 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
596 ConstantBool) {
Chris Lattner31a09842008-11-12 08:04:58 +0000597 // br(X && 1) -> br(X).
598 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
599 }
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Chris Lattner31a09842008-11-12 08:04:58 +0000601 // Emit the LHS as a conditional. If the LHS conditional is false, we
602 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000603 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
John McCall150b4622011-01-26 04:00:11 +0000604
605 ConditionalEvaluation eval(*this);
Chris Lattner31a09842008-11-12 08:04:58 +0000606 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
607 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Anders Carlsson08e9e452010-01-24 00:20:05 +0000609 // Any temporaries created here are conditional.
John McCall150b4622011-01-26 04:00:11 +0000610 eval.begin(*this);
Chris Lattner31a09842008-11-12 08:04:58 +0000611 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
John McCall150b4622011-01-26 04:00:11 +0000612 eval.end(*this);
Anders Carlsson08e9e452010-01-24 00:20:05 +0000613
Chris Lattner31a09842008-11-12 08:04:58 +0000614 return;
Chris Lattnerc2c90012011-02-27 23:02:32 +0000615 }
616
617 if (CondBOp->getOpcode() == BO_LOr) {
Chris Lattner31a09842008-11-12 08:04:58 +0000618 // If we have "0 || X", simplify the code. "1 || X" would have constant
619 // folded if the case was simple enough.
Bill Wendlinge3eb83b2011-03-04 21:46:03 +0000620 bool ConstantBool = false;
Chris Lattnerc2c90012011-02-27 23:02:32 +0000621 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
622 !ConstantBool) {
Chris Lattner31a09842008-11-12 08:04:58 +0000623 // br(0 || X) -> br(X).
624 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
625 }
Mike Stump1eb44332009-09-09 15:08:12 +0000626
Chris Lattner31a09842008-11-12 08:04:58 +0000627 // If we have "X || 0", simplify the code to use an uncond branch.
628 // "X || 1" would have been constant folded to 1.
Chris Lattnerc2c90012011-02-27 23:02:32 +0000629 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
630 !ConstantBool) {
Chris Lattner31a09842008-11-12 08:04:58 +0000631 // br(X || 0) -> br(X).
632 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
633 }
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Chris Lattner31a09842008-11-12 08:04:58 +0000635 // Emit the LHS as a conditional. If the LHS conditional is true, we
636 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000637 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
John McCall150b4622011-01-26 04:00:11 +0000638
639 ConditionalEvaluation eval(*this);
Chris Lattner31a09842008-11-12 08:04:58 +0000640 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
641 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000642
Anders Carlsson08e9e452010-01-24 00:20:05 +0000643 // Any temporaries created here are conditional.
John McCall150b4622011-01-26 04:00:11 +0000644 eval.begin(*this);
Chris Lattner31a09842008-11-12 08:04:58 +0000645 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
John McCall150b4622011-01-26 04:00:11 +0000646 eval.end(*this);
Anders Carlsson08e9e452010-01-24 00:20:05 +0000647
Chris Lattner31a09842008-11-12 08:04:58 +0000648 return;
649 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000650 }
Mike Stump1eb44332009-09-09 15:08:12 +0000651
Chris Lattner552f4c42008-11-12 08:13:36 +0000652 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
653 // br(!x, t, f) -> br(x, f, t)
John McCall2de56d12010-08-25 11:45:40 +0000654 if (CondUOp->getOpcode() == UO_LNot)
Chris Lattner552f4c42008-11-12 08:13:36 +0000655 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000656 }
Mike Stump1eb44332009-09-09 15:08:12 +0000657
Daniel Dunbar09b14892008-11-12 10:30:32 +0000658 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
Eli Friedmandf33a352012-02-14 03:54:45 +0000659 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
660 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
661 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
Daniel Dunbar09b14892008-11-12 10:30:32 +0000662
Eli Friedmandf33a352012-02-14 03:54:45 +0000663 ConditionalEvaluation cond(*this);
664 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
John McCall150b4622011-01-26 04:00:11 +0000665
Eli Friedmandf33a352012-02-14 03:54:45 +0000666 cond.begin(*this);
667 EmitBlock(LHSBlock);
668 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
669 cond.end(*this);
John McCall150b4622011-01-26 04:00:11 +0000670
Eli Friedmandf33a352012-02-14 03:54:45 +0000671 cond.begin(*this);
672 EmitBlock(RHSBlock);
673 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
674 cond.end(*this);
John McCall150b4622011-01-26 04:00:11 +0000675
Eli Friedmandf33a352012-02-14 03:54:45 +0000676 return;
Daniel Dunbar09b14892008-11-12 10:30:32 +0000677 }
678
Chris Lattner31a09842008-11-12 08:04:58 +0000679 // Emit the code with the fully general case.
680 llvm::Value *CondV = EvaluateExprAsBool(Cond);
681 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
682}
683
Daniel Dunbar488e9932008-08-16 00:56:44 +0000684/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000685/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000686void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
687 bool OmitOnError) {
688 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000689}
690
John McCall71433252011-02-01 21:35:06 +0000691/// emitNonZeroVLAInit - Emit the "zero" initialization of a
692/// variable-length array whose elements have a non-zero bit-pattern.
693///
694/// \param src - a char* pointing to the bit-pattern for a single
695/// base element of the array
696/// \param sizeInChars - the total size of the VLA, in chars
697/// \param align - the total alignment of the VLA
698static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
699 llvm::Value *dest, llvm::Value *src,
700 llvm::Value *sizeInChars) {
701 std::pair<CharUnits,CharUnits> baseSizeAndAlign
702 = CGF.getContext().getTypeInfoInChars(baseType);
703
704 CGBuilderTy &Builder = CGF.Builder;
705
706 llvm::Value *baseSizeInChars
707 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
708
Chris Lattner2acc6e32011-07-18 04:24:23 +0000709 llvm::Type *i8p = Builder.getInt8PtrTy();
John McCall71433252011-02-01 21:35:06 +0000710
711 llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
712 llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
713
714 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
715 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
716 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
717
718 // Make a loop over the VLA. C99 guarantees that the VLA element
719 // count must be nonzero.
720 CGF.EmitBlock(loopBB);
721
Jay Foadbbf3bac2011-03-30 11:28:58 +0000722 llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur");
John McCall71433252011-02-01 21:35:06 +0000723 cur->addIncoming(begin, originBB);
724
725 // memcpy the individual element bit-pattern.
726 Builder.CreateMemCpy(cur, src, baseSizeInChars,
727 baseSizeAndAlign.second.getQuantity(),
728 /*volatile*/ false);
729
730 // Go to the next element.
731 llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next");
732
733 // Leave if that's the end of the VLA.
734 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
735 Builder.CreateCondBr(done, contBB, loopBB);
736 cur->addIncoming(next, loopBB);
737
738 CGF.EmitBlock(contBB);
739}
740
Anders Carlsson1884eb02010-05-22 17:35:42 +0000741void
742CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
Anders Carlsson0d7c5832010-05-03 01:20:20 +0000743 // Ignore empty classes in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000744 if (getContext().getLangOpts().CPlusPlus) {
Anders Carlsson0d7c5832010-05-03 01:20:20 +0000745 if (const RecordType *RT = Ty->getAs<RecordType>()) {
746 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
747 return;
748 }
749 }
John McCall90217182010-08-07 08:21:30 +0000750
751 // Cast the dest ptr to the appropriate i8 pointer type.
752 unsigned DestAS =
753 cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000754 llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000755 if (DestPtr->getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +0000756 DestPtr = Builder.CreateBitCast(DestPtr, BP);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000757
758 // Get size and alignment info for this aggregate.
Ken Dyck79be76c2011-04-22 17:51:05 +0000759 std::pair<CharUnits, CharUnits> TypeInfo =
760 getContext().getTypeInfoInChars(Ty);
761 CharUnits Size = TypeInfo.first;
762 CharUnits Align = TypeInfo.second;
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000763
John McCall5576d9b2011-01-14 10:37:58 +0000764 llvm::Value *SizeVal;
John McCall71433252011-02-01 21:35:06 +0000765 const VariableArrayType *vla;
Mike Stump1eb44332009-09-09 15:08:12 +0000766
John McCall5576d9b2011-01-14 10:37:58 +0000767 // Don't bother emitting a zero-byte memset.
Ken Dyck79be76c2011-04-22 17:51:05 +0000768 if (Size.isZero()) {
John McCall5576d9b2011-01-14 10:37:58 +0000769 // But note that getTypeInfo returns 0 for a VLA.
770 if (const VariableArrayType *vlaType =
771 dyn_cast_or_null<VariableArrayType>(
772 getContext().getAsArrayType(Ty))) {
John McCallbc8d40d2011-06-24 21:55:10 +0000773 QualType eltType;
774 llvm::Value *numElts;
775 llvm::tie(numElts, eltType) = getVLASize(vlaType);
776
777 SizeVal = numElts;
778 CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
779 if (!eltSize.isOne())
780 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
John McCall71433252011-02-01 21:35:06 +0000781 vla = vlaType;
John McCall5576d9b2011-01-14 10:37:58 +0000782 } else {
783 return;
784 }
785 } else {
John McCallbc8d40d2011-06-24 21:55:10 +0000786 SizeVal = CGM.getSize(Size);
John McCall71433252011-02-01 21:35:06 +0000787 vla = 0;
John McCall5576d9b2011-01-14 10:37:58 +0000788 }
John McCall90217182010-08-07 08:21:30 +0000789
790 // If the type contains a pointer to data member we can't memset it to zero.
791 // Instead, create a null constant and copy it to the destination.
John McCall71433252011-02-01 21:35:06 +0000792 // TODO: there are other patterns besides zero that we can usefully memset,
793 // like -1, which happens to be the pattern used by member-pointers.
John McCallf16aa102010-08-22 21:01:12 +0000794 if (!CGM.getTypes().isZeroInitializable(Ty)) {
John McCall71433252011-02-01 21:35:06 +0000795 // For a VLA, emit a single element, then splat that over the VLA.
796 if (vla) Ty = getContext().getBaseElementType(vla);
John McCall5576d9b2011-01-14 10:37:58 +0000797
John McCall90217182010-08-07 08:21:30 +0000798 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
799
800 llvm::GlobalVariable *NullVariable =
801 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
802 /*isConstant=*/true,
803 llvm::GlobalVariable::PrivateLinkage,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000804 NullConstant, Twine());
John McCall90217182010-08-07 08:21:30 +0000805 llvm::Value *SrcPtr =
806 Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
807
John McCall71433252011-02-01 21:35:06 +0000808 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
809
John McCall90217182010-08-07 08:21:30 +0000810 // Get and call the appropriate llvm.memcpy overload.
Ken Dyck79be76c2011-04-22 17:51:05 +0000811 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false);
John McCall90217182010-08-07 08:21:30 +0000812 return;
813 }
814
815 // Otherwise, just memset the whole thing to zero. This is legal
816 // because in LLVM, all default initializers (other than the ones we just
817 // handled above) are guaranteed to have a bit pattern of all zeros.
Ken Dyck79be76c2011-04-22 17:51:05 +0000818 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal,
819 Align.getQuantity(), false);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000820}
821
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000822llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000823 // Make sure that there is a block for the indirect goto.
824 if (IndirectBranch == 0)
825 GetIndirectGotoBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000826
John McCallff8e1152010-07-23 21:56:41 +0000827 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000828
Chris Lattnerd9becd12009-10-28 23:59:40 +0000829 // Make sure the indirect branch includes all of the address-taken blocks.
830 IndirectBranch->addDestination(BB);
831 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000832}
833
834llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000835 // If we already made the indirect branch for indirect goto, return its block.
836 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000837
Chris Lattnerd9becd12009-10-28 23:59:40 +0000838 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000839
840 // Create the PHI node that indirect gotos will add entries to.
Jay Foadbbf3bac2011-03-30 11:28:58 +0000841 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
842 "indirect.goto.dest");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000843
Chris Lattnerd9becd12009-10-28 23:59:40 +0000844 // Create the indirect branch instruction.
845 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
846 return IndirectBranch->getParent();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000847}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000848
John McCallbdc4d802011-07-09 01:37:26 +0000849/// Computes the length of an array in elements, as well as the base
850/// element type and a properly-typed first element pointer.
851llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
852 QualType &baseType,
853 llvm::Value *&addr) {
854 const ArrayType *arrayType = origArrayType;
855
856 // If it's a VLA, we have to load the stored size. Note that
857 // this is the size of the VLA in bytes, not its size in elements.
858 llvm::Value *numVLAElements = 0;
859 if (isa<VariableArrayType>(arrayType)) {
860 numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
861
862 // Walk into all VLAs. This doesn't require changes to addr,
863 // which has type T* where T is the first non-VLA element type.
864 do {
865 QualType elementType = arrayType->getElementType();
866 arrayType = getContext().getAsArrayType(elementType);
867
868 // If we only have VLA components, 'addr' requires no adjustment.
869 if (!arrayType) {
870 baseType = elementType;
871 return numVLAElements;
872 }
873 } while (isa<VariableArrayType>(arrayType));
874
875 // We get out here only if we find a constant array type
876 // inside the VLA.
877 }
878
879 // We have some number of constant-length arrays, so addr should
880 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
881 // down to the first element of addr.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000882 SmallVector<llvm::Value*, 8> gepIndices;
John McCallbdc4d802011-07-09 01:37:26 +0000883
884 // GEP down to the array type.
885 llvm::ConstantInt *zero = Builder.getInt32(0);
886 gepIndices.push_back(zero);
887
888 // It's more efficient to calculate the count from the LLVM
889 // constant-length arrays than to re-evaluate the array bounds.
890 uint64_t countFromCLAs = 1;
891
Chris Lattner2acc6e32011-07-18 04:24:23 +0000892 llvm::ArrayType *llvmArrayType =
John McCallbdc4d802011-07-09 01:37:26 +0000893 cast<llvm::ArrayType>(
894 cast<llvm::PointerType>(addr->getType())->getElementType());
895 while (true) {
896 assert(isa<ConstantArrayType>(arrayType));
897 assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
898 == llvmArrayType->getNumElements());
899
900 gepIndices.push_back(zero);
901 countFromCLAs *= llvmArrayType->getNumElements();
902
903 llvmArrayType =
904 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
905 if (!llvmArrayType) break;
906
907 arrayType = getContext().getAsArrayType(arrayType->getElementType());
908 assert(arrayType && "LLVM and Clang types are out-of-synch");
909 }
910
911 baseType = arrayType->getElementType();
912
913 // Create the actual GEP.
Jay Foad0f6ac7c2011-07-22 08:16:57 +0000914 addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin");
John McCallbdc4d802011-07-09 01:37:26 +0000915
916 llvm::Value *numElements
917 = llvm::ConstantInt::get(SizeTy, countFromCLAs);
918
919 // If we had any VLA dimensions, factor them in.
920 if (numVLAElements)
921 numElements = Builder.CreateNUWMul(numVLAElements, numElements);
922
923 return numElements;
924}
925
John McCallbc8d40d2011-06-24 21:55:10 +0000926std::pair<llvm::Value*, QualType>
927CodeGenFunction::getVLASize(QualType type) {
928 const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
929 assert(vla && "type was not a variable array type!");
930 return getVLASize(vla);
Anders Carlssonf666b772008-12-20 20:27:15 +0000931}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000932
John McCallbc8d40d2011-06-24 21:55:10 +0000933std::pair<llvm::Value*, QualType>
934CodeGenFunction::getVLASize(const VariableArrayType *type) {
935 // The number of elements so far; always size_t.
936 llvm::Value *numElements = 0;
937
938 QualType elementType;
939 do {
940 elementType = type->getElementType();
941 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
942 assert(vlaSize && "no size for VLA!");
943 assert(vlaSize->getType() == SizeTy);
944
945 if (!numElements) {
946 numElements = vlaSize;
947 } else {
948 // It's undefined behavior if this wraps around, so mark it that way.
949 numElements = Builder.CreateNUWMul(numElements, vlaSize);
950 }
951 } while ((type = getContext().getAsVariableArrayType(elementType)));
952
953 return std::pair<llvm::Value*,QualType>(numElements, elementType);
954}
955
956void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
957 assert(type->isVariablyModifiedType() &&
Anders Carlsson60d35412008-12-20 20:46:34 +0000958 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Daniel Dunbard286f052009-07-19 06:58:07 +0000960 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000961
John McCallbc8d40d2011-06-24 21:55:10 +0000962 // We're going to walk down into the type and look for VLA
963 // expressions.
John McCallbc8d40d2011-06-24 21:55:10 +0000964 do {
965 assert(type->isVariablyModifiedType());
Mike Stump1eb44332009-09-09 15:08:12 +0000966
John McCallbc8d40d2011-06-24 21:55:10 +0000967 const Type *ty = type.getTypePtr();
968 switch (ty->getTypeClass()) {
Abramo Bagnara06284c12012-01-07 10:52:36 +0000969
John McCallbc8d40d2011-06-24 21:55:10 +0000970#define TYPE(Class, Base)
971#define ABSTRACT_TYPE(Class, Base)
Abramo Bagnara06284c12012-01-07 10:52:36 +0000972#define NON_CANONICAL_TYPE(Class, Base)
John McCallbc8d40d2011-06-24 21:55:10 +0000973#define DEPENDENT_TYPE(Class, Base) case Type::Class:
Abramo Bagnara06284c12012-01-07 10:52:36 +0000974#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
John McCallbc8d40d2011-06-24 21:55:10 +0000975#include "clang/AST/TypeNodes.def"
Abramo Bagnara06284c12012-01-07 10:52:36 +0000976 llvm_unreachable("unexpected dependent type!");
Mike Stump1eb44332009-09-09 15:08:12 +0000977
John McCallbc8d40d2011-06-24 21:55:10 +0000978 // These types are never variably-modified.
979 case Type::Builtin:
980 case Type::Complex:
981 case Type::Vector:
982 case Type::ExtVector:
983 case Type::Record:
984 case Type::Enum:
Abramo Bagnara5ff53b22012-01-11 08:19:46 +0000985 case Type::Elaborated:
986 case Type::TemplateSpecialization:
John McCallbc8d40d2011-06-24 21:55:10 +0000987 case Type::ObjCObject:
988 case Type::ObjCInterface:
989 case Type::ObjCObjectPointer:
990 llvm_unreachable("type class is never variably-modified!");
Mike Stump1eb44332009-09-09 15:08:12 +0000991
John McCallbc8d40d2011-06-24 21:55:10 +0000992 case Type::Pointer:
993 type = cast<PointerType>(ty)->getPointeeType();
994 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000995
John McCallbc8d40d2011-06-24 21:55:10 +0000996 case Type::BlockPointer:
997 type = cast<BlockPointerType>(ty)->getPointeeType();
998 break;
999
1000 case Type::LValueReference:
1001 case Type::RValueReference:
1002 type = cast<ReferenceType>(ty)->getPointeeType();
1003 break;
1004
1005 case Type::MemberPointer:
1006 type = cast<MemberPointerType>(ty)->getPointeeType();
1007 break;
1008
1009 case Type::ConstantArray:
1010 case Type::IncompleteArray:
1011 // Losing element qualification here is fine.
1012 type = cast<ArrayType>(ty)->getElementType();
1013 break;
1014
1015 case Type::VariableArray: {
1016 // Losing element qualification here is fine.
1017 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1018
1019 // Unknown size indication requires no size computation.
1020 // Otherwise, evaluate and record it.
1021 if (const Expr *size = vat->getSizeExpr()) {
1022 // It's possible that we might have emitted this already,
1023 // e.g. with a typedef and a pointer to it.
1024 llvm::Value *&entry = VLASizeMap[size];
1025 if (!entry) {
1026 // Always zexting here would be wrong if it weren't
1027 // undefined behavior to have a negative bound.
1028 entry = Builder.CreateIntCast(EmitScalarExpr(size), SizeTy,
1029 /*signed*/ false);
1030 }
1031 }
1032 type = vat->getElementType();
1033 break;
Anders Carlsson60d35412008-12-20 20:46:34 +00001034 }
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Abramo Bagnara06284c12012-01-07 10:52:36 +00001036 case Type::FunctionProto:
John McCallbc8d40d2011-06-24 21:55:10 +00001037 case Type::FunctionNoProto:
1038 type = cast<FunctionType>(ty)->getResultType();
1039 break;
Eli Friedmanb001de72011-10-06 23:00:33 +00001040
Abramo Bagnara5ff53b22012-01-11 08:19:46 +00001041 case Type::Paren:
1042 case Type::TypeOf:
1043 case Type::UnaryTransform:
1044 case Type::Attributed:
1045 case Type::SubstTemplateTypeParm:
1046 // Keep walking after single level desugaring.
1047 type = type.getSingleStepDesugaredType(getContext());
1048 break;
1049
1050 case Type::Typedef:
1051 case Type::Decltype:
1052 case Type::Auto:
1053 // Stop walking: nothing to do.
1054 return;
1055
1056 case Type::TypeOfExpr:
1057 // Stop walking: emit typeof expression.
1058 EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
1059 return;
1060
Eli Friedmanb001de72011-10-06 23:00:33 +00001061 case Type::Atomic:
1062 type = cast<AtomicType>(ty)->getValueType();
1063 break;
John McCallbc8d40d2011-06-24 21:55:10 +00001064 }
1065 } while (type->isVariablyModifiedType());
Anders Carlssondcc90d82008-12-12 07:19:02 +00001066}
Eli Friedman4fd0aa52009-01-20 17:46:04 +00001067
1068llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
Dan Gohmanbc07a552010-10-29 22:47:07 +00001069 if (getContext().getBuiltinVaListType()->isArrayType())
Eli Friedman4fd0aa52009-01-20 17:46:04 +00001070 return EmitScalarExpr(E);
Eli Friedman4fd0aa52009-01-20 17:46:04 +00001071 return EmitLValue(E).getAddress();
1072}
Anders Carlsson6ccc4762009-02-07 22:53:43 +00001073
Devang Patel8d308382010-08-10 07:24:25 +00001074void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
John McCall189d6ef2010-10-09 01:34:31 +00001075 llvm::Constant *Init) {
Devang Patel25c2c8f2010-08-10 17:53:33 +00001076 assert (Init && "Invalid DeclRefExpr initializer!");
1077 if (CGDebugInfo *Dbg = getDebugInfo())
Devang Pateld2829b72010-10-06 15:58:57 +00001078 Dbg->EmitGlobalVariable(E->getDecl(), Init);
Devang Patel8d308382010-08-10 07:24:25 +00001079}
John McCall56ca35d2011-02-17 10:25:35 +00001080
1081CodeGenFunction::PeepholeProtection
1082CodeGenFunction::protectFromPeepholes(RValue rvalue) {
1083 // At the moment, the only aggressive peephole we do in IR gen
1084 // is trunc(zext) folding, but if we add more, we can easily
1085 // extend this protection.
1086
1087 if (!rvalue.isScalar()) return PeepholeProtection();
1088 llvm::Value *value = rvalue.getScalarVal();
1089 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
1090
1091 // Just make an extra bitcast.
1092 assert(HaveInsertPoint());
1093 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
1094 Builder.GetInsertBlock());
1095
1096 PeepholeProtection protection;
1097 protection.Inst = inst;
1098 return protection;
1099}
1100
1101void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
1102 if (!protection.Inst) return;
1103
1104 // In theory, we could try to duplicate the peepholes now, but whatever.
1105 protection.Inst->eraseFromParent();
1106}
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001107
1108llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
1109 llvm::Value *AnnotatedVal,
1110 llvm::StringRef AnnotationStr,
1111 SourceLocation Location) {
1112 llvm::Value *Args[4] = {
1113 AnnotatedVal,
1114 Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
1115 Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
1116 CGM.EmitAnnotationLineNo(Location)
1117 };
1118 return Builder.CreateCall(AnnotationFn, Args);
1119}
1120
1121void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
1122 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1123 // FIXME We create a new bitcast for every annotation because that's what
1124 // llvm-gcc was doing.
1125 for (specific_attr_iterator<AnnotateAttr>
1126 ai = D->specific_attr_begin<AnnotateAttr>(),
1127 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
1128 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
1129 Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
1130 (*ai)->getAnnotation(), D->getLocation());
1131}
1132
1133llvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
1134 llvm::Value *V) {
1135 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1136 llvm::Type *VTy = V->getType();
1137 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
1138 CGM.Int8PtrTy);
1139
1140 for (specific_attr_iterator<AnnotateAttr>
1141 ai = D->specific_attr_begin<AnnotateAttr>(),
1142 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) {
1143 // FIXME Always emit the cast inst so we can differentiate between
1144 // annotation on the first field of a struct and annotation on the struct
1145 // itself.
1146 if (VTy != CGM.Int8PtrTy)
1147 V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
1148 V = EmitAnnotationCall(F, V, (*ai)->getAnnotation(), D->getLocation());
1149 V = Builder.CreateBitCast(V, VTy);
1150 }
1151
1152 return V;
1153}