blob: 9f359185381715de075a2b64f12d1f778fc5716e [file] [log] [blame]
Chris Lattnerbed31442007-05-28 01:07:47 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerbed31442007-05-28 01:07:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-function state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Peter Collingbournefa4d6032011-10-06 18:51:56 +000015#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Eli Friedman17630752008-05-22 01:40:10 +000017#include "CGDebugInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000018#include "CGOpenMPRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "CodeGenModule.h"
Justin Bogneref512b92014-01-06 22:27:43 +000020#include "CodeGenPGO.h"
Peter Collingbourneb453cd62013-10-20 21:29:19 +000021#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000023#include "clang/AST/Decl.h"
Anders Carlsson468fa632009-04-04 20:47:02 +000024#include "clang/AST/DeclCXX.h"
Mike Stumpbee78dd2009-12-04 23:26:17 +000025#include "clang/AST/StmtCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000027#include "clang/CodeGen/CGFunctionInfo.h"
Chris Lattner3c77a352010-06-22 00:03:40 +000028#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000029#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/MDBuilder.h"
32#include "llvm/IR/Operator.h"
Chris Lattnerbed31442007-05-28 01:07:47 +000033using namespace clang;
34using namespace CodeGen;
35
Fariborz Jahanian63628032012-06-26 16:06:38 +000036CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
David Blaikie92848de2013-08-26 20:33:21 +000037 : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
Alexander Musman515ad8c2014-05-22 08:54:05 +000038 Builder(cgm.getModule().getContext(), llvm::ConstantFolder(),
Alexey Samsonov24cad992014-07-17 18:46:27 +000039 CGBuilderInserterTy(this)),
40 CapturedStmtInfo(nullptr), SanOpts(&CGM.getLangOpts().Sanitize),
Reid Kleckner19819442014-07-25 21:39:46 +000041 IsSanitizerScope(false), CurFuncIsThunk(false), AutoreleaseResult(false),
Reid Kleckner9b3e3df2014-09-04 20:04:38 +000042 SawAsmBlock(false), BlockInfo(nullptr), BlockPointer(nullptr),
Reid Kleckner19819442014-07-25 21:39:46 +000043 LambdaThisCaptureField(nullptr), NormalCleanupDest(nullptr),
44 NextCleanupDestIndex(1), FirstBlockInfo(nullptr), EHResumeBlock(nullptr),
45 ExceptionSlot(nullptr), EHSelectorSlot(nullptr),
46 DebugInfo(CGM.getModuleDebugInfo()), DisableDebugInfo(false),
47 DidCallStackSave(false), IndirectBranch(nullptr), PGO(cgm),
48 SwitchInsn(nullptr), SwitchWeights(nullptr), CaseRangeBlock(nullptr),
49 UnreachableBlock(nullptr), NumReturnExprs(0), NumSimpleReturnExprs(0),
50 CXXABIThisDecl(nullptr), CXXABIThisValue(nullptr), CXXThisValue(nullptr),
Craig Topper8a13c412014-05-21 05:09:00 +000051 CXXDefaultInitExprThis(nullptr), CXXStructorImplicitParamDecl(nullptr),
52 CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
53 CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
54 TerminateHandler(nullptr), TrapBB(nullptr) {
Fariborz Jahanian63628032012-06-26 16:06:38 +000055 if (!suppressNewContext)
56 CGM.getCXXABI().getMangleContext().startNewFunction();
Michael Ilseman7a167ee2012-12-04 00:36:06 +000057
58 llvm::FastMathFlags FMF;
59 if (CGM.getLangOpts().FastMath)
Benjamin Kramer7464efc2012-12-09 21:58:24 +000060 FMF.setUnsafeAlgebra();
Michael Ilseman7a167ee2012-12-04 00:36:06 +000061 if (CGM.getLangOpts().FiniteMathOnly) {
Benjamin Kramer7464efc2012-12-09 21:58:24 +000062 FMF.setNoNaNs();
63 FMF.setNoInfs();
Michael Ilseman7a167ee2012-12-04 00:36:06 +000064 }
65 Builder.SetFastMathFlags(FMF);
Chris Lattner5696e7b2008-06-17 18:05:57 +000066}
Chris Lattnerd1af2d22007-05-29 23:17:50 +000067
John McCall08ef4662011-11-10 08:15:53 +000068CodeGenFunction::~CodeGenFunction() {
Richard Smith736a9472013-06-12 20:42:33 +000069 assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
70
John McCall08ef4662011-11-10 08:15:53 +000071 // If there are any unclaimed block infos, go ahead and destroy them
72 // now. This can happen if IR-gen gets clever and skips evaluating
73 // something.
74 if (FirstBlockInfo)
75 destroyBlockInfos(FirstBlockInfo);
Alexey Bataev9959db52014-05-06 10:08:46 +000076
77 if (getLangOpts().OpenMP) {
78 CGM.getOpenMPRuntime().FunctionFinished(*this);
79 }
John McCall08ef4662011-11-10 08:15:53 +000080}
81
David Majnemer99281062014-09-18 22:05:54 +000082LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
83 CharUnits Alignment;
84 if (CGM.getCXXABI().isTypeInfoCalculable(T)) {
85 Alignment = getContext().getTypeAlignInChars(T);
86 unsigned MaxAlign = getContext().getLangOpts().MaxTypeAlign;
87 if (MaxAlign && Alignment.getQuantity() > MaxAlign &&
88 !getContext().isAlignmentRequired(T))
89 Alignment = CharUnits::fromQuantity(MaxAlign);
90 }
91 return LValue::MakeAddr(V, T, Alignment, getContext(), CGM.getTBAAInfo(T));
92}
Chris Lattnerd1af2d22007-05-29 23:17:50 +000093
Chris Lattnera5f58b02011-07-09 17:41:47 +000094llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
Daniel Dunbaree3da872009-02-03 23:03:55 +000095 return CGM.getTypes().ConvertTypeForMem(T);
96}
97
Chris Lattnera5f58b02011-07-09 17:41:47 +000098llvm::Type *CodeGenFunction::ConvertType(QualType T) {
Chris Lattnerf033c142007-06-22 19:05:19 +000099 return CGM.getTypes().ConvertType(T);
Chris Lattner45bb9142007-06-09 02:28:57 +0000100}
Chris Lattnerd1af2d22007-05-29 23:17:50 +0000101
John McCall47fb9502013-03-07 21:37:08 +0000102TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
103 type = type.getCanonicalType();
104 while (true) {
105 switch (type->getTypeClass()) {
John McCall745ae282011-05-15 02:34:36 +0000106#define TYPE(name, parent)
107#define ABSTRACT_TYPE(name, parent)
108#define NON_CANONICAL_TYPE(name, parent) case Type::name:
109#define DEPENDENT_TYPE(name, parent) case Type::name:
110#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
111#include "clang/AST/TypeNodes.def"
John McCall47fb9502013-03-07 21:37:08 +0000112 llvm_unreachable("non-canonical or dependent type in IR-generation");
John McCall745ae282011-05-15 02:34:36 +0000113
Richard Smith27d807c2013-04-30 13:56:41 +0000114 case Type::Auto:
115 llvm_unreachable("undeduced auto type in IR-generation");
116
John McCall47fb9502013-03-07 21:37:08 +0000117 // Various scalar types.
118 case Type::Builtin:
119 case Type::Pointer:
120 case Type::BlockPointer:
121 case Type::LValueReference:
122 case Type::RValueReference:
123 case Type::MemberPointer:
124 case Type::Vector:
125 case Type::ExtVector:
126 case Type::FunctionProto:
127 case Type::FunctionNoProto:
128 case Type::Enum:
129 case Type::ObjCObjectPointer:
130 return TEK_Scalar;
John McCall745ae282011-05-15 02:34:36 +0000131
John McCall47fb9502013-03-07 21:37:08 +0000132 // Complexes.
133 case Type::Complex:
134 return TEK_Complex;
Eli Friedman0dfb8892011-10-06 23:00:33 +0000135
John McCall47fb9502013-03-07 21:37:08 +0000136 // Arrays, records, and Objective-C objects.
137 case Type::ConstantArray:
138 case Type::IncompleteArray:
139 case Type::VariableArray:
140 case Type::Record:
141 case Type::ObjCObject:
142 case Type::ObjCInterface:
143 return TEK_Aggregate;
144
145 // We operate on atomic values according to their underlying type.
146 case Type::Atomic:
147 type = cast<AtomicType>(type)->getValueType();
148 continue;
149 }
150 llvm_unreachable("unknown type kind!");
John McCall745ae282011-05-15 02:34:36 +0000151 }
Chris Lattner54fb19e2007-06-22 22:02:34 +0000152}
153
David Blaikie357aafb2013-02-01 19:09:49 +0000154void CodeGenFunction::EmitReturnBlock() {
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000155 // For cleanliness, we try to avoid emitting the return block for
156 // simple cases.
157 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
158
159 if (CurBB) {
160 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
161
Daniel Dunbarea3060a2009-07-19 08:24:34 +0000162 // We have a valid insert point, reuse it if it is empty or there are no
163 // explicit jumps to the return block.
John McCallad5d61e2010-07-23 21:56:41 +0000164 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
165 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
166 delete ReturnBlock.getBlock();
Daniel Dunbarea3060a2009-07-19 08:24:34 +0000167 } else
John McCallad5d61e2010-07-23 21:56:41 +0000168 EmitBlock(ReturnBlock.getBlock());
David Blaikie357aafb2013-02-01 19:09:49 +0000169 return;
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000170 }
171
172 // Otherwise, if the return block is the target of a single direct
173 // branch then we can just put the code in that block instead. This
174 // cleans up functions which started with a unified return block.
John McCallad5d61e2010-07-23 21:56:41 +0000175 if (ReturnBlock.getBlock()->hasOneUse()) {
Mike Stump11289f42009-09-09 15:08:12 +0000176 llvm::BranchInst *BI =
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000177 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
John McCallbd309292010-07-06 01:34:17 +0000178 if (BI && BI->isUnconditional() &&
John McCallad5d61e2010-07-23 21:56:41 +0000179 BI->getSuccessor(0) == ReturnBlock.getBlock()) {
David Blaikie1d969f42013-02-23 19:20:56 +0000180 // Reset insertion point, including debug location, and delete the
181 // branch. This is really subtle and only works because the next change
182 // in location will hit the caching in CGDebugInfo::EmitLocation and not
183 // override this.
Eric Christopher65c5c912011-09-09 21:53:04 +0000184 Builder.SetCurrentDebugLocation(BI->getDebugLoc());
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000185 Builder.SetInsertPoint(BI->getParent());
186 BI->eraseFromParent();
John McCallad5d61e2010-07-23 21:56:41 +0000187 delete ReturnBlock.getBlock();
David Blaikie357aafb2013-02-01 19:09:49 +0000188 return;
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000189 }
190 }
191
Mike Stump18bb9282009-05-16 07:57:57 +0000192 // FIXME: We are at an unreachable point, there is no reason to emit the block
193 // unless it has uses. However, we still need a place to put the debug
194 // region.end for now.
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000195
John McCallad5d61e2010-07-23 21:56:41 +0000196 EmitBlock(ReturnBlock.getBlock());
John McCallbd309292010-07-06 01:34:17 +0000197}
198
199static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
200 if (!BB) return;
201 if (!BB->use_empty())
202 return CGF.CurFn->getBasicBlockList().push_back(BB);
203 delete BB;
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000204}
205
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000206void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnere73e4322007-07-16 21:28:45 +0000207 assert(BreakContinueStack.empty() &&
208 "mismatched push/pop in break/continue stack!");
Mike Stump11289f42009-09-09 15:08:12 +0000209
Adrian Prantl52bf3c42013-05-03 20:11:48 +0000210 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
Adrian Prantl524ba1f2013-07-25 00:23:42 +0000211 && NumSimpleReturnExprs == NumReturnExprs
212 && ReturnBlock.getBlock()->use_empty();
213 // Usually the return expression is evaluated before the cleanup
214 // code. If the function contains only a simple return statement,
215 // such as a constant, the location before the cleanup code becomes
216 // the last useful breakpoint in the function, because the simple
217 // return expression will be evaluated after the cleanup code. To be
218 // safe, set the debug location for cleanup code to the location of
219 // the return statement. Otherwise the cleanup code should be at the
220 // end of the function's lexical scope.
221 //
222 // If there are multiple branches to the return block, the branch
223 // instructions will get the location of the return statements and
224 // all will be fine.
Adrian Prantl3be10542013-05-02 17:30:20 +0000225 if (CGDebugInfo *DI = getDebugInfo()) {
Adrian Prantl52bf3c42013-05-03 20:11:48 +0000226 if (OnlySimpleReturnStmts)
Adrian Prantle83b1302014-01-07 22:05:52 +0000227 DI->EmitLocation(Builder, LastStopPoint);
Adrian Prantl3be10542013-05-02 17:30:20 +0000228 else
Adrian Prantle83b1302014-01-07 22:05:52 +0000229 DI->EmitLocation(Builder, EndLoc);
Adrian Prantl3be10542013-05-02 17:30:20 +0000230 }
David Blaikie357aafb2013-02-01 19:09:49 +0000231
John McCall31168b02011-06-15 23:02:42 +0000232 // Pop any cleanups that might have been associated with the
233 // parameters. Do this in whatever block we're currently in; it's
234 // important to do this before we enter the return block or return
235 // edges will be *really* confused.
Adrian Prantl3be10542013-05-02 17:30:20 +0000236 bool EmitRetDbgLoc = true;
237 if (EHStack.stable_begin() != PrologueCleanupDepth) {
Adrian Prantldc237b52013-05-16 00:41:26 +0000238 PopCleanupBlocks(PrologueCleanupDepth);
John McCall31168b02011-06-15 23:02:42 +0000239
Adrian Prantl3be10542013-05-02 17:30:20 +0000240 // Make sure the line table doesn't jump back into the body for
241 // the ret after it's been at EndLoc.
242 EmitRetDbgLoc = false;
243
244 if (CGDebugInfo *DI = getDebugInfo())
Adrian Prantl52bf3c42013-05-03 20:11:48 +0000245 if (OnlySimpleReturnStmts)
Adrian Prantle83b1302014-01-07 22:05:52 +0000246 DI->EmitLocation(Builder, EndLoc);
Adrian Prantl3be10542013-05-02 17:30:20 +0000247 }
248
Mike Stump11289f42009-09-09 15:08:12 +0000249 // Emit function epilog (to return).
David Blaikie357aafb2013-02-01 19:09:49 +0000250 EmitReturnBlock();
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000251
Daniel Dunbar468a8f82011-02-10 17:32:22 +0000252 if (ShouldInstrumentFunction())
253 EmitFunctionInstrumentation("__cyg_profile_func_exit");
Chris Lattner3c77a352010-06-22 00:03:40 +0000254
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000255 // Emit debug descriptor for function end.
Anders Carlsson63784f42009-02-13 08:11:52 +0000256 if (CGDebugInfo *DI = getDebugInfo()) {
Devang Patel0884a602010-07-22 22:29:16 +0000257 DI->EmitFunctionEnd(Builder);
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000258 }
259
Nick Lewycky2d84e842013-10-02 02:29:49 +0000260 EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
Mike Stump1d849212009-12-07 23:38:24 +0000261 EmitEndEHSpec(CurCodeDecl);
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000262
John McCallbd309292010-07-06 01:34:17 +0000263 assert(EHStack.empty() &&
264 "did not remove all scopes from cleanup stack!");
265
Chris Lattner6c4d2552009-10-28 23:59:40 +0000266 // If someone did an indirect goto, emit the indirect goto block at the end of
267 // the function.
268 if (IndirectBranch) {
269 EmitBlock(IndirectBranch->getParent());
270 Builder.ClearInsertionPoint();
271 }
Michael Ilseman686240a2012-12-04 00:29:55 +0000272
Chris Lattnerc48023b2007-12-02 06:32:24 +0000273 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner2739d2b2009-03-31 22:17:44 +0000274 llvm::Instruction *Ptr = AllocaInsertPt;
Craig Topper8a13c412014-05-21 05:09:00 +0000275 AllocaInsertPt = nullptr;
Chris Lattner2739d2b2009-03-31 22:17:44 +0000276 Ptr->eraseFromParent();
Michael Ilseman686240a2012-12-04 00:29:55 +0000277
Chris Lattner6c4d2552009-10-28 23:59:40 +0000278 // If someone took the address of a label but never did an indirect goto, we
279 // made a zero entry PHI node, which is illegal, zap it now.
280 if (IndirectBranch) {
281 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
282 if (PN->getNumIncomingValues() == 0) {
283 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
284 PN->eraseFromParent();
285 }
286 }
John McCallbd309292010-07-06 01:34:17 +0000287
John McCall8e4c74b2011-08-11 02:22:43 +0000288 EmitIfUsed(*this, EHResumeBlock);
John McCallbd309292010-07-06 01:34:17 +0000289 EmitIfUsed(*this, TerminateLandingPad);
290 EmitIfUsed(*this, TerminateHandler);
291 EmitIfUsed(*this, UnreachableBlock);
John McCall09ae0322010-07-06 23:57:41 +0000292
293 if (CGM.getCodeGenOpts().EmitDeclMetadata)
294 EmitDeclMetadata();
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000295
296 for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
297 I = DeferredReplacements.begin(),
298 E = DeferredReplacements.end();
299 I != E; ++I) {
300 I->first->replaceAllUsesWith(I->second);
301 I->first->eraseFromParent();
302 }
Chris Lattnerd1af2d22007-05-29 23:17:50 +0000303}
Chris Lattner308f4312007-05-29 23:50:05 +0000304
Chris Lattner3c77a352010-06-22 00:03:40 +0000305/// ShouldInstrumentFunction - Return true if the current function should be
306/// instrumented with __cyg_profile_func_* calls
307bool CodeGenFunction::ShouldInstrumentFunction() {
308 if (!CGM.getCodeGenOpts().InstrumentFunctions)
309 return false;
Ted Kremenekc249c412011-05-16 23:49:20 +0000310 if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
Chris Lattner3c77a352010-06-22 00:03:40 +0000311 return false;
312 return true;
313}
314
315/// EmitFunctionInstrumentation - Emit LLVM code to call the specified
316/// instrumentation function with the current function and the call site, if
317/// function instrumentation is enabled.
318void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
Chris Lattnerb48a2d52010-06-23 05:21:28 +0000319 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
Chris Lattnera5f58b02011-07-09 17:41:47 +0000320 llvm::PointerType *PointerTy = Int8PtrTy;
321 llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
Chris Lattner2192fe52011-07-18 04:24:23 +0000322 llvm::FunctionType *FunctionTy =
Chris Lattnerece04092012-02-07 00:39:47 +0000323 llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
Chris Lattner3c77a352010-06-22 00:03:40 +0000324
325 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
326 llvm::CallInst *CallSite = Builder.CreateCall(
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000327 CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
Chris Lattner5e016ae2010-06-27 07:15:29 +0000328 llvm::ConstantInt::get(Int32Ty, 0),
Chris Lattner3c77a352010-06-22 00:03:40 +0000329 "callsite");
330
John McCall882987f2013-02-28 19:01:20 +0000331 llvm::Value *args[] = {
332 llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
333 CallSite
334 };
335
336 EmitNounwindRuntimeCall(F, args);
Chris Lattner3c77a352010-06-22 00:03:40 +0000337}
338
Roman Divacky178e01602011-02-10 16:52:03 +0000339void CodeGenFunction::EmitMCountInstrumentation() {
Chris Lattnerece04092012-02-07 00:39:47 +0000340 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
Roman Divacky178e01602011-02-10 16:52:03 +0000341
John McCallc8e01702013-04-16 22:48:15 +0000342 llvm::Constant *MCountFn =
343 CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName());
John McCall882987f2013-02-28 19:01:20 +0000344 EmitNounwindRuntimeCall(MCountFn);
Roman Divacky178e01602011-02-10 16:52:03 +0000345}
346
Tanya Lattner7445ada2012-07-11 23:02:10 +0000347// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
348// information in the program executable. The argument information stored
349// includes the argument name, its type, the address and access qualifiers used.
Tanya Lattner7445ada2012-07-11 23:02:10 +0000350static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
351 CodeGenModule &CGM,llvm::LLVMContext &Context,
Guy Benyeifb36ede2013-03-24 13:58:12 +0000352 SmallVector <llvm::Value*, 5> &kernelMDArgs,
353 CGBuilderTy& Builder, ASTContext &ASTCtx) {
354 // Create MDNodes that represent the kernel arg metadata.
Tanya Lattner7445ada2012-07-11 23:02:10 +0000355 // Each MDNode is a list in the form of "key", N number of values which is
356 // the same number of values as their are kernel arguments.
Michael Ilseman686240a2012-12-04 00:29:55 +0000357
Joey Gouly92a47442014-04-04 13:43:57 +0000358 const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
359
Guy Benyeifb36ede2013-03-24 13:58:12 +0000360 // MDNode for the kernel argument address space qualifiers.
361 SmallVector<llvm::Value*, 8> addressQuals;
362 addressQuals.push_back(llvm::MDString::get(Context, "kernel_arg_addr_space"));
363
364 // MDNode for the kernel argument access qualifiers (images only).
365 SmallVector<llvm::Value*, 8> accessQuals;
366 accessQuals.push_back(llvm::MDString::get(Context, "kernel_arg_access_qual"));
367
368 // MDNode for the kernel argument type names.
369 SmallVector<llvm::Value*, 8> argTypeNames;
370 argTypeNames.push_back(llvm::MDString::get(Context, "kernel_arg_type"));
371
Fraser Cormackdadc3712014-07-30 14:39:53 +0000372 // MDNode for the kernel argument base type names.
373 SmallVector<llvm::Value*, 8> argBaseTypeNames;
374 argBaseTypeNames.push_back(
375 llvm::MDString::get(Context, "kernel_arg_base_type"));
376
Guy Benyeifb36ede2013-03-24 13:58:12 +0000377 // MDNode for the kernel argument type qualifiers.
378 SmallVector<llvm::Value*, 8> argTypeQuals;
379 argTypeQuals.push_back(llvm::MDString::get(Context, "kernel_arg_type_qual"));
380
Tanya Lattner7445ada2012-07-11 23:02:10 +0000381 // MDNode for the kernel argument names.
382 SmallVector<llvm::Value*, 8> argNames;
383 argNames.push_back(llvm::MDString::get(Context, "kernel_arg_name"));
Michael Ilseman686240a2012-12-04 00:29:55 +0000384
Tanya Lattner7445ada2012-07-11 23:02:10 +0000385 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
386 const ParmVarDecl *parm = FD->getParamDecl(i);
Guy Benyeifb36ede2013-03-24 13:58:12 +0000387 QualType ty = parm->getType();
388 std::string typeQuals;
389
390 if (ty->isPointerType()) {
391 QualType pointeeTy = ty->getPointeeType();
392
393 // Get address qualifier.
394 addressQuals.push_back(Builder.getInt32(ASTCtx.getTargetAddressSpace(
395 pointeeTy.getAddressSpace())));
396
397 // Get argument type name.
Joey Gouly92a47442014-04-04 13:43:57 +0000398 std::string typeName =
399 pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
Guy Benyeifb36ede2013-03-24 13:58:12 +0000400
401 // Turn "unsigned type" to "utype"
402 std::string::size_type pos = typeName.find("unsigned");
Fraser Cormack152493b2014-07-30 13:41:12 +0000403 if (pointeeTy.isCanonical() && pos != std::string::npos)
Benjamin Krameref89ae02013-03-24 16:04:55 +0000404 typeName.erase(pos+1, 8);
Guy Benyeifb36ede2013-03-24 13:58:12 +0000405
406 argTypeNames.push_back(llvm::MDString::get(Context, typeName));
407
Fraser Cormackdadc3712014-07-30 14:39:53 +0000408 std::string baseTypeName =
409 pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
410 Policy) +
411 "*";
412
413 // Turn "unsigned type" to "utype"
414 pos = baseTypeName.find("unsigned");
415 if (pos != std::string::npos)
416 baseTypeName.erase(pos+1, 8);
417
418 argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
419
Guy Benyeifb36ede2013-03-24 13:58:12 +0000420 // Get argument type qualifiers:
421 if (ty.isRestrictQualified())
422 typeQuals = "restrict";
423 if (pointeeTy.isConstQualified() ||
424 (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
Benjamin Krameref89ae02013-03-24 16:04:55 +0000425 typeQuals += typeQuals.empty() ? "const" : " const";
Guy Benyeifb36ede2013-03-24 13:58:12 +0000426 if (pointeeTy.isVolatileQualified())
Benjamin Krameref89ae02013-03-24 16:04:55 +0000427 typeQuals += typeQuals.empty() ? "volatile" : " volatile";
Guy Benyeifb36ede2013-03-24 13:58:12 +0000428 } else {
Pekka Jaaskelainen3587b322014-01-09 13:37:30 +0000429 uint32_t AddrSpc = 0;
430 if (ty->isImageType())
431 AddrSpc =
432 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
Bob Wilson95a27b02014-02-17 19:20:59 +0000433
Pekka Jaaskelainen3587b322014-01-09 13:37:30 +0000434 addressQuals.push_back(Builder.getInt32(AddrSpc));
Guy Benyeifb36ede2013-03-24 13:58:12 +0000435
436 // Get argument type name.
Joey Gouly92a47442014-04-04 13:43:57 +0000437 std::string typeName = ty.getUnqualifiedType().getAsString(Policy);
Guy Benyeifb36ede2013-03-24 13:58:12 +0000438
439 // Turn "unsigned type" to "utype"
440 std::string::size_type pos = typeName.find("unsigned");
Fraser Cormack152493b2014-07-30 13:41:12 +0000441 if (ty.isCanonical() && pos != std::string::npos)
Benjamin Krameref89ae02013-03-24 16:04:55 +0000442 typeName.erase(pos+1, 8);
Guy Benyeifb36ede2013-03-24 13:58:12 +0000443
444 argTypeNames.push_back(llvm::MDString::get(Context, typeName));
445
Fraser Cormackdadc3712014-07-30 14:39:53 +0000446 std::string baseTypeName =
447 ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
448
449 // Turn "unsigned type" to "utype"
450 pos = baseTypeName.find("unsigned");
451 if (pos != std::string::npos)
452 baseTypeName.erase(pos+1, 8);
453
454 argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
455
Guy Benyeifb36ede2013-03-24 13:58:12 +0000456 // Get argument type qualifiers:
457 if (ty.isConstQualified())
458 typeQuals = "const";
459 if (ty.isVolatileQualified())
Benjamin Krameref89ae02013-03-24 16:04:55 +0000460 typeQuals += typeQuals.empty() ? "volatile" : " volatile";
Guy Benyeifb36ede2013-03-24 13:58:12 +0000461 }
Justin Bogner0f066062013-11-22 10:20:40 +0000462
Guy Benyeifb36ede2013-03-24 13:58:12 +0000463 argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
464
465 // Get image access qualifier:
466 if (ty->isImageType()) {
Aaron Ballmanc4327992013-12-19 03:09:10 +0000467 const OpenCLImageAccessAttr *A = parm->getAttr<OpenCLImageAccessAttr>();
Aaron Ballman26891332014-01-14 17:41:53 +0000468 if (A && A->isWriteOnly())
Guy Benyeifb36ede2013-03-24 13:58:12 +0000469 accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
470 else
471 accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
Aaron Ballman26891332014-01-14 17:41:53 +0000472 // FIXME: what about read_write?
Guy Benyeifb36ede2013-03-24 13:58:12 +0000473 } else
474 accessQuals.push_back(llvm::MDString::get(Context, "none"));
Michael Ilseman686240a2012-12-04 00:29:55 +0000475
Tanya Lattner7445ada2012-07-11 23:02:10 +0000476 // Get argument name.
477 argNames.push_back(llvm::MDString::get(Context, parm->getName()));
Tanya Lattner7445ada2012-07-11 23:02:10 +0000478 }
Guy Benyeifb36ede2013-03-24 13:58:12 +0000479
480 kernelMDArgs.push_back(llvm::MDNode::get(Context, addressQuals));
481 kernelMDArgs.push_back(llvm::MDNode::get(Context, accessQuals));
482 kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames));
Fraser Cormackdadc3712014-07-30 14:39:53 +0000483 kernelMDArgs.push_back(llvm::MDNode::get(Context, argBaseTypeNames));
Guy Benyeifb36ede2013-03-24 13:58:12 +0000484 kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals));
Tanya Lattner7445ada2012-07-11 23:02:10 +0000485 kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames));
486}
487
Michael Ilseman686240a2012-12-04 00:29:55 +0000488void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +0000489 llvm::Function *Fn)
490{
491 if (!FD->hasAttr<OpenCLKernelAttr>())
492 return;
493
494 llvm::LLVMContext &Context = getLLVMContext();
495
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000496 SmallVector <llvm::Value*, 5> kernelMDArgs;
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +0000497 kernelMDArgs.push_back(Fn);
498
Tanya Lattner7445ada2012-07-11 23:02:10 +0000499 if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
Guy Benyeifb36ede2013-03-24 13:58:12 +0000500 GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs,
501 Builder, getContext());
Michael Ilseman686240a2012-12-04 00:29:55 +0000502
Aaron Ballmanc4327992013-12-19 03:09:10 +0000503 if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
504 QualType hintQTy = A->getTypeHint();
Joey Goulyaba589c2013-03-08 09:42:32 +0000505 const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
506 bool isSignedInteger =
507 hintQTy->isSignedIntegerType() ||
508 (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
509 llvm::Value *attrMDArgs[] = {
510 llvm::MDString::get(Context, "vec_type_hint"),
Aaron Ballmanc4327992013-12-19 03:09:10 +0000511 llvm::UndefValue::get(CGM.getTypes().ConvertType(A->getTypeHint())),
Joey Goulyaba589c2013-03-08 09:42:32 +0000512 llvm::ConstantInt::get(
513 llvm::IntegerType::get(Context, 32),
514 llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0)))
515 };
516 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
517 }
518
Aaron Ballmanc4327992013-12-19 03:09:10 +0000519 if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
Benjamin Kramerc1b78412012-11-15 16:40:35 +0000520 llvm::Value *attrMDArgs[] = {
521 llvm::MDString::get(Context, "work_group_size_hint"),
Aaron Ballmanc4327992013-12-19 03:09:10 +0000522 Builder.getInt32(A->getXDim()),
523 Builder.getInt32(A->getYDim()),
524 Builder.getInt32(A->getZDim())
Benjamin Kramerc1b78412012-11-15 16:40:35 +0000525 };
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +0000526 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
527 }
528
Aaron Ballmanc4327992013-12-19 03:09:10 +0000529 if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
Benjamin Kramerc1b78412012-11-15 16:40:35 +0000530 llvm::Value *attrMDArgs[] = {
531 llvm::MDString::get(Context, "reqd_work_group_size"),
Aaron Ballmanc4327992013-12-19 03:09:10 +0000532 Builder.getInt32(A->getXDim()),
533 Builder.getInt32(A->getYDim()),
534 Builder.getInt32(A->getZDim())
Benjamin Kramerc1b78412012-11-15 16:40:35 +0000535 };
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +0000536 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
537 }
538
539 llvm::MDNode *kernelMDNode = llvm::MDNode::get(Context, kernelMDArgs);
540 llvm::NamedMDNode *OpenCLKernelMetadata =
541 CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
542 OpenCLKernelMetadata->addOperand(kernelMDNode);
543}
544
Adrian Prantl2cede0f2014-04-29 01:07:59 +0000545/// Determine whether the function F ends with a return stmt.
546static bool endsWithReturn(const Decl* F) {
547 const Stmt *Body = nullptr;
548 if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
549 Body = FD->getBody();
550 else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
551 Body = OMD->getBody();
552
553 if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
554 auto LastStmt = CS->body_rbegin();
555 if (LastStmt != CS->body_rend())
556 return isa<ReturnStmt>(*LastStmt);
557 }
558 return false;
559}
560
John McCalldec348f72013-05-03 07:33:41 +0000561void CodeGenFunction::StartFunction(GlobalDecl GD,
562 QualType RetTy,
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000563 llvm::Function *Fn,
John McCalla738c252011-03-09 04:27:21 +0000564 const CGFunctionInfo &FnInfo,
Daniel Dunbar354d2782008-10-18 18:22:23 +0000565 const FunctionArgList &Args,
Adrian Prantl42d71b92014-04-10 23:21:53 +0000566 SourceLocation Loc,
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000567 SourceLocation StartLoc) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000568 const Decl *D = GD.getDecl();
Michael Ilseman686240a2012-12-04 00:29:55 +0000569
Anders Carlssonf4478e92009-02-09 20:20:56 +0000570 DidCallStackSave = false;
John McCalldec348f72013-05-03 07:33:41 +0000571 CurCodeDecl = D;
Craig Topper8a13c412014-05-21 05:09:00 +0000572 CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000573 FnRetTy = RetTy;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000574 CurFn = Fn;
John McCalla738c252011-03-09 04:27:21 +0000575 CurFnInfo = &FnInfo;
Chris Lattner5696e7b2008-06-17 18:05:57 +0000576 assert(CurFn->isDeclaration() && "Function already has body?");
577
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000578 if (CGM.getSanitizerBlacklist().isIn(*Fn))
Will Dietzf54319c2013-01-18 11:30:38 +0000579 SanOpts = &SanitizerOptions::Disabled;
Will Dietzf54319c2013-01-18 11:30:38 +0000580
Jakob Stoklund Olesen819e54b2010-02-09 00:10:00 +0000581 // Pass inline keyword to optimizer if it appears explicitly on any
Roman Divackydd9bfb22014-01-15 19:07:16 +0000582 // declaration. Also, in the case of -fno-inline attach NoInline
David Majnemer19d7d542014-02-25 10:51:14 +0000583 // attribute to all function that are not marked AlwaysInline.
Roman Divackydd9bfb22014-01-15 19:07:16 +0000584 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
585 if (!CGM.getCodeGenOpts().NoInline) {
Aaron Ballman86c93902014-03-06 23:45:36 +0000586 for (auto RI : FD->redecls())
Chad Rosier883b2572012-03-14 23:32:11 +0000587 if (RI->isInlineSpecified()) {
Bill Wendling207f0532012-12-20 19:27:06 +0000588 Fn->addFnAttr(llvm::Attribute::InlineHint);
Chad Rosier883b2572012-03-14 23:32:11 +0000589 break;
590 }
David Majnemer67e541e1c2014-02-25 09:53:29 +0000591 } else if (!FD->hasAttr<AlwaysInlineAttr>())
Roman Divackydd9bfb22014-01-15 19:07:16 +0000592 Fn->addFnAttr(llvm::Attribute::NoInline);
593 }
Jakob Stoklund Olesen819e54b2010-02-09 00:10:00 +0000594
Richard Smith9c6890a2012-11-01 22:30:59 +0000595 if (getLangOpts().OpenCL) {
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000596 // Add metadata for a kernel function.
597 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +0000598 EmitOpenCLKernelMetadata(FD, Fn);
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000599 }
600
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000601 // If we are checking function types, emit a function type signature as
602 // prefix data.
603 if (getLangOpts().CPlusPlus && SanOpts->Function) {
604 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
605 if (llvm::Constant *PrefixSig =
606 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
607 llvm::Constant *FTRTTIConst =
608 CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
609 llvm::Constant *PrefixStructElems[] = { PrefixSig, FTRTTIConst };
610 llvm::Constant *PrefixStructConst =
611 llvm::ConstantStruct::getAnon(PrefixStructElems, /*Packed=*/true);
612 Fn->setPrefixData(PrefixStructConst);
613 }
614 }
615 }
616
Daniel Dunbar75283ff2008-11-11 02:29:29 +0000617 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000618
Chris Lattner5696e7b2008-06-17 18:05:57 +0000619 // Create a marker to make it easy to insert allocas into the entryblock
620 // later. Don't create this with the builder, because we don't want it
621 // folded.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000622 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
623 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
Chris Lattner47640222009-03-22 00:24:14 +0000624 if (Builder.isNamePreserving())
625 AllocaInsertPt->setName("allocapt");
Mike Stump11289f42009-09-09 15:08:12 +0000626
John McCallbd309292010-07-06 01:34:17 +0000627 ReturnBlock = getJumpDestInCurrentScope("return");
Mike Stump11289f42009-09-09 15:08:12 +0000628
Chris Lattner5696e7b2008-06-17 18:05:57 +0000629 Builder.SetInsertPoint(EntryBB);
Mike Stump11289f42009-09-09 15:08:12 +0000630
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000631 // Emit subprogram debug descriptor.
Anders Carlsson63784f42009-02-13 08:11:52 +0000632 if (CGDebugInfo *DI = getDebugInfo()) {
Jordan Rose5c382722013-03-08 21:51:21 +0000633 SmallVector<QualType, 16> ArgTypes;
Eric Christopher4b4beb22011-10-21 23:30:10 +0000634 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
635 i != e; ++i) {
Jordan Rose5c382722013-03-08 21:51:21 +0000636 ArgTypes.push_back((*i)->getType());
Eric Christopher4b4beb22011-10-21 23:30:10 +0000637 }
638
John McCalldb40c7f2010-12-14 08:05:40 +0000639 QualType FnType =
Jordan Rose5c382722013-03-08 21:51:21 +0000640 getContext().getFunctionType(RetTy, ArgTypes,
John McCalldb40c7f2010-12-14 08:05:40 +0000641 FunctionProtoType::ExtProtoInfo());
Adrian Prantl42d71b92014-04-10 23:21:53 +0000642 DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder);
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000643 }
644
Daniel Dunbar468a8f82011-02-10 17:32:22 +0000645 if (ShouldInstrumentFunction())
646 EmitFunctionInstrumentation("__cyg_profile_func_enter");
Chris Lattner3c77a352010-06-22 00:03:40 +0000647
Roman Divacky178e01602011-02-10 16:52:03 +0000648 if (CGM.getCodeGenOpts().InstrumentForProfiling)
649 EmitMCountInstrumentation();
650
Eli Friedman4b1942c2009-12-04 02:43:40 +0000651 if (RetTy->isVoidType()) {
652 // Void type; nothing to return.
Craig Topper8a13c412014-05-21 05:09:00 +0000653 ReturnValue = nullptr;
Adrian Prantl2cede0f2014-04-29 01:07:59 +0000654
655 // Count the implicit return.
656 if (!endsWithReturn(D))
657 ++NumReturnExprs;
Eli Friedman4b1942c2009-12-04 02:43:40 +0000658 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +0000659 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
Eli Friedman4b1942c2009-12-04 02:43:40 +0000660 // Indirect aggregate return; emit returned value directly into sret slot.
Daniel Dunbarfd09df72010-02-16 19:45:20 +0000661 // This reduces code size, and affects correctness in C++.
Reid Kleckner37abaca2014-05-09 22:46:15 +0000662 auto AI = CurFn->arg_begin();
663 if (CurFnInfo->getReturnInfo().isSRetAfterThis())
664 ++AI;
665 ReturnValue = AI;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000666 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
667 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
668 // Load the sret pointer from the argument struct and return into that.
669 unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
670 llvm::Function::arg_iterator EI = CurFn->arg_end();
671 --EI;
672 llvm::Value *Addr = Builder.CreateStructGEP(EI, Idx);
673 ReturnValue = Builder.CreateLoad(Addr, "agg.result");
Eli Friedman4b1942c2009-12-04 02:43:40 +0000674 } else {
Daniel Dunbarfd09df72010-02-16 19:45:20 +0000675 ReturnValue = CreateIRTemp(RetTy, "retval");
John McCall31168b02011-06-15 23:02:42 +0000676
677 // Tell the epilog emitter to autorelease the result. We do this
678 // now so that various specialized functions can suppress it
679 // during their IR-generation.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000680 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000681 !CurFnInfo->isReturnsRetained() &&
682 RetTy->isObjCRetainableType())
683 AutoreleaseResult = true;
Eli Friedman4b1942c2009-12-04 02:43:40 +0000684 }
685
Mike Stump1d849212009-12-07 23:38:24 +0000686 EmitStartEHSpec(CurCodeDecl);
John McCall31168b02011-06-15 23:02:42 +0000687
688 PrologueCleanupDepth = EHStack.stable_begin();
Daniel Dunbard931a872009-02-02 22:03:45 +0000689 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump11289f42009-09-09 15:08:12 +0000690
Eli Friedman9fbeba02012-02-11 02:57:39 +0000691 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
John McCall5d865c322010-08-31 07:33:07 +0000692 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
Eli Friedman9fbeba02012-02-11 02:57:39 +0000693 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
694 if (MD->getParent()->isLambda() &&
695 MD->getOverloadedOperator() == OO_Call) {
696 // We're in a lambda; figure out the captures.
697 MD->getParent()->getCaptureFields(LambdaCaptureFields,
698 LambdaThisCaptureField);
699 if (LambdaThisCaptureField) {
700 // If this lambda captures this, load it.
John McCalldec348f72013-05-03 07:33:41 +0000701 LValue ThisLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
Nick Lewycky2d84e842013-10-02 02:29:49 +0000702 CXXThisValue = EmitLoadOfLValue(ThisLValue,
703 SourceLocation()).getScalarVal();
Eli Friedman9fbeba02012-02-11 02:57:39 +0000704 }
Alexey Bataev39c81e22014-08-28 04:28:19 +0000705 for (auto *FD : MD->getParent()->fields()) {
706 if (FD->hasCapturedVLAType()) {
707 auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
708 SourceLocation()).getScalarVal();
709 auto VAT = FD->getCapturedVLAType();
710 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
711 }
712 }
Eli Friedman9fbeba02012-02-11 02:57:39 +0000713 } else {
714 // Not in a lambda; just use 'this' from the method.
715 // FIXME: Should we generate a new load for each use of 'this'? The
716 // fast register allocator would be happier...
717 CXXThisValue = CXXABIThisValue;
718 }
719 }
John McCall347132b2010-02-16 22:04:33 +0000720
Anders Carlssonc20879a2008-12-20 21:28:43 +0000721 // If any of the arguments have a variably modified type, make sure to
722 // emit the type size.
723 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
724 i != e; ++i) {
Eli Friedman1f576832012-11-14 22:09:59 +0000725 const VarDecl *VD = *i;
726
727 // Dig out the type as written from ParmVarDecls; it's unclear whether
728 // the standard (C99 6.9.1p10) requires this, but we're following the
729 // precedent set by gcc.
730 QualType Ty;
731 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
732 Ty = PVD->getOriginalType();
733 else
734 Ty = VD->getType();
Anders Carlssonc20879a2008-12-20 21:28:43 +0000735
736 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000737 EmitVariablyModifiedType(Ty);
Anders Carlssonc20879a2008-12-20 21:28:43 +0000738 }
Eric Christopher7cdf9482011-10-13 21:45:18 +0000739 // Emit a location at the end of the prologue.
740 if (CGDebugInfo *DI = getDebugInfo())
741 DI->EmitLocation(Builder, StartLoc);
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000742}
Eli Friedman3d421e12008-08-25 21:31:01 +0000743
Richard Smithb47c36f2013-11-05 09:12:18 +0000744void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
745 const Stmt *Body) {
Justin Bogneref512b92014-01-06 22:27:43 +0000746 RegionCounter Cnt = getPGORegionCounter(Body);
747 Cnt.beginRegion(Builder);
Richard Smithb47c36f2013-11-05 09:12:18 +0000748 if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
David Blaikie0a21d0d2013-01-26 22:16:26 +0000749 EmitCompoundStmtWithoutScope(*S);
750 else
Richard Smithb47c36f2013-11-05 09:12:18 +0000751 EmitStmt(Body);
John McCall89b12b32010-02-18 03:17:58 +0000752}
753
Bob Wilsonbf854f02014-02-17 19:21:09 +0000754/// When instrumenting to collect profile data, the counts for some blocks
755/// such as switch cases need to not include the fall-through counts, so
756/// emit a branch around the instrumentation code. When not instrumenting,
757/// this just calls EmitBlock().
758void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
759 RegionCounter &Cnt) {
Craig Topper8a13c412014-05-21 05:09:00 +0000760 llvm::BasicBlock *SkipCountBB = nullptr;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000761 if (HaveInsertPoint() && CGM.getCodeGenOpts().ProfileInstrGenerate) {
762 // When instrumenting for profiling, the fallthrough to certain
763 // statements needs to skip over the instrumentation code so that we
764 // get an accurate count.
765 SkipCountBB = createBasicBlock("skipcount");
766 EmitBranch(SkipCountBB);
767 }
768 EmitBlock(BB);
769 Cnt.beginRegion(Builder, /*AddIncomingFallThrough=*/true);
770 if (SkipCountBB)
771 EmitBlock(SkipCountBB);
772}
773
John McCall8601a752010-08-03 22:46:07 +0000774/// Tries to mark the given function nounwind based on the
775/// non-existence of any throwing calls within it. We believe this is
776/// lightweight enough to do at -O0.
777static void TryMarkNoThrow(llvm::Function *F) {
John McCall59966992010-08-11 22:38:33 +0000778 // LLVM treats 'nounwind' on a function as part of the type, so we
779 // can't do this on functions that can be overwritten.
780 if (F->mayBeOverridden()) return;
781
John McCall8601a752010-08-03 22:46:07 +0000782 for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
783 for (llvm::BasicBlock::iterator
784 BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
Bill Wendlingf0724e82011-09-19 20:31:14 +0000785 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) {
John McCall8601a752010-08-03 22:46:07 +0000786 if (!Call->doesNotThrow())
787 return;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000788 } else if (isa<llvm::ResumeInst>(&*BI)) {
789 return;
790 }
Bill Wendling73e465e2012-10-10 03:13:20 +0000791 F->setDoesNotThrow();
John McCall8601a752010-08-03 22:46:07 +0000792}
793
Richard Smithb47c36f2013-11-05 09:12:18 +0000794static void EmitSizedDeallocationFunction(CodeGenFunction &CGF,
795 const FunctionDecl *UnsizedDealloc) {
796 // This is a weak discardable definition of the sized deallocation function.
797 CGF.CurFn->setLinkage(llvm::Function::LinkOnceAnyLinkage);
798
799 // Call the unsized deallocation function and forward the first argument
800 // unchanged.
801 llvm::Constant *Unsized = CGF.CGM.GetAddrOfFunction(UnsizedDealloc);
802 CGF.Builder.CreateCall(Unsized, &*CGF.CurFn->arg_begin());
803}
804
John McCalla738c252011-03-09 04:27:21 +0000805void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
806 const CGFunctionInfo &FnInfo) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000807 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael Ilseman686240a2012-12-04 00:29:55 +0000808
Anders Carlsson63784f42009-02-13 08:11:52 +0000809 // Check if we should generate debug info for this function.
David Blaikie92848de2013-08-26 20:33:21 +0000810 if (FD->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000811 DebugInfo = nullptr; // disable debug info indefinitely for this function
Mike Stump11289f42009-09-09 15:08:12 +0000812
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000813 FunctionArgList Args;
Alp Toker314cc812014-01-25 16:55:45 +0000814 QualType ResTy = FD->getReturnType();
Mike Stump11289f42009-09-09 15:08:12 +0000815
Mike Stumpbee78dd2009-12-04 23:26:17 +0000816 CurGD = GD;
Reid Kleckner89077a12013-12-17 19:46:40 +0000817 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
818 if (MD && MD->isInstance()) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000819 if (CGM.getCXXABI().HasThisReturn(GD))
820 ResTy = MD->getThisType(getContext());
Reid Kleckner89077a12013-12-17 19:46:40 +0000821 CGM.getCXXABI().buildThisParam(*this, Args);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000822 }
Alexey Samsonov3551e312014-08-13 20:06:24 +0000823
824 Args.append(FD->param_begin(), FD->param_end());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000825
Reid Kleckner89077a12013-12-17 19:46:40 +0000826 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
827 CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
828
John McCall89b12b32010-02-18 03:17:58 +0000829 SourceRange BodyRange;
830 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
Adrian Prantldc237b52013-05-16 00:41:26 +0000831 CurEHLocation = BodyRange.getEnd();
Anders Carlsson438cf922009-11-06 02:55:43 +0000832
Adrian Prantl42d71b92014-04-10 23:21:53 +0000833 // Use the location of the start of the function to determine where
834 // the function definition is located. By default use the location
835 // of the declaration as the location for the subprogram. A function
836 // may lack a declaration in the source code if it is created by code
837 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
Alexey Samsonovcb1ad6f2014-07-08 20:23:18 +0000838 SourceLocation Loc = FD->getLocation();
Adrian Prantl42d71b92014-04-10 23:21:53 +0000839
Alexey Samsonovcb1ad6f2014-07-08 20:23:18 +0000840 // If this is a function specialization then use the pattern body
841 // as the location for the function.
842 if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
843 if (SpecDecl->hasBody(SpecDecl))
844 Loc = SpecDecl->getLocation();
Adrian Prantl42d71b92014-04-10 23:21:53 +0000845
John McCall89b12b32010-02-18 03:17:58 +0000846 // Emit the standard function prologue.
Adrian Prantl42d71b92014-04-10 23:21:53 +0000847 StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
Anders Carlsson438cf922009-11-06 02:55:43 +0000848
John McCall89b12b32010-02-18 03:17:58 +0000849 // Generate the body of the function.
Alex Lorenzee024992014-08-04 18:41:51 +0000850 PGO.checkGlobalDecl(GD);
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000851 PGO.assignRegionCounters(GD.getDecl(), CurFn);
John McCallb81884d2010-02-19 09:25:03 +0000852 if (isa<CXXDestructorDecl>(FD))
853 EmitDestructorBody(Args);
854 else if (isa<CXXConstructorDecl>(FD))
855 EmitConstructorBody(Args);
Richard Smith9c6890a2012-11-01 22:30:59 +0000856 else if (getLangOpts().CUDA &&
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000857 !CGM.getCodeGenOpts().CUDAIsDevice &&
858 FD->hasAttr<CUDAGlobalAttr>())
859 CGM.getCUDARuntime().EmitDeviceStubBody(*this, Args);
Eli Friedman5a6d5072012-02-16 01:37:33 +0000860 else if (isa<CXXConversionDecl>(FD) &&
Douglas Gregor355efbb2012-02-17 03:02:34 +0000861 cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
862 // The lambda conversion to block pointer is special; the semantics can't be
863 // expressed in the AST, so IRGen needs to special-case it.
864 EmitLambdaToBlockPointerBody(Args);
865 } else if (isa<CXXMethodDecl>(FD) &&
866 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
Faisal Vali2b391ab2013-09-26 19:54:12 +0000867 // The lambda static invoker function is special, because it forwards or
Douglas Gregor355efbb2012-02-17 03:02:34 +0000868 // clones the body of the function call operator (but is actually static).
869 EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
Lang Hamesbf122742013-02-17 07:22:09 +0000870 } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
Nick Lewyckyb39be1f2013-09-10 05:14:39 +0000871 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
872 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
Lang Hamesbf122742013-02-17 07:22:09 +0000873 // Implicit copy-assignment gets the same special treatment as implicit
874 // copy-constructors.
875 emitImplicitAssignmentOperatorBody(Args);
Richard Smithb47c36f2013-11-05 09:12:18 +0000876 } else if (Stmt *Body = FD->getBody()) {
877 EmitFunctionBody(Args, Body);
878 } else if (FunctionDecl *UnsizedDealloc =
879 FD->getCorrespondingUnsizedGlobalDeallocationFunction()) {
880 // Global sized deallocation functions get an implicit weak definition if
881 // they don't have an explicit definition.
882 EmitSizedDeallocationFunction(*this, UnsizedDealloc);
883 } else
884 llvm_unreachable("no definition for emitted function");
Anders Carlssonff8cce42010-02-07 19:45:40 +0000885
Richard Smith9f9e5822012-10-04 23:52:29 +0000886 // C++11 [stmt.return]p2:
887 // Flowing off the end of a function [...] results in undefined behavior in
888 // a value-returning function.
889 // C11 6.9.1p12:
890 // If the '}' that terminates a function is reached, and the value of the
891 // function call is used by the caller, the behavior is undefined.
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000892 if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
Alp Toker314cc812014-01-25 16:55:45 +0000893 !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
Alexey Samsonov24cad992014-07-17 18:46:27 +0000894 if (SanOpts->Return) {
895 SanitizerScope SanScope(this);
Richard Smithe30752c2012-10-09 19:52:38 +0000896 EmitCheck(Builder.getFalse(), "missing_return",
897 EmitCheckSourceLocation(FD->getLocation()),
Craig Topper5fc8fc22014-08-27 06:28:36 +0000898 None, CRK_Unrecoverable);
Alexey Samsonov24cad992014-07-17 18:46:27 +0000899 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0)
Richard Smith6b4ebcc2012-10-15 00:23:07 +0000900 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::trap));
Richard Smith9f9e5822012-10-04 23:52:29 +0000901 Builder.CreateUnreachable();
902 Builder.ClearInsertionPoint();
903 }
904
John McCall89b12b32010-02-18 03:17:58 +0000905 // Emit the standard function epilogue.
906 FinishFunction(BodyRange.getEnd());
John McCall8601a752010-08-03 22:46:07 +0000907
908 // If we haven't marked the function nothrow through other means, do
909 // a quick pass now to see if we can.
910 if (!CurFn->doesNotThrow())
911 TryMarkNoThrow(CurFn);
Justin Bogneref512b92014-01-06 22:27:43 +0000912
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000913 PGO.emitInstrumentationData();
Justin Bogneref512b92014-01-06 22:27:43 +0000914 PGO.destroyRegionCounters();
Chris Lattner5696e7b2008-06-17 18:05:57 +0000915}
916
Chris Lattner5b1964b2008-11-11 07:41:27 +0000917/// ContainsLabel - Return true if the statement contains a label in it. If
918/// this statement is not executed normally, it not containing a label means
919/// that we can just remove the code.
920bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
921 // Null statement, not a label!
Craig Topper8a13c412014-05-21 05:09:00 +0000922 if (!S) return false;
Mike Stump11289f42009-09-09 15:08:12 +0000923
Chris Lattner5b1964b2008-11-11 07:41:27 +0000924 // If this is a label, we have to emit the code, consider something like:
925 // if (0) { ... foo: bar(); } goto foo;
Chris Lattner29911cc2011-02-28 00:18:40 +0000926 //
927 // TODO: If anyone cared, we could track __label__'s, since we know that you
928 // can't jump to one from outside their declared region.
Chris Lattner5b1964b2008-11-11 07:41:27 +0000929 if (isa<LabelStmt>(S))
930 return true;
Michael Ilseman686240a2012-12-04 00:29:55 +0000931
Chris Lattner5b1964b2008-11-11 07:41:27 +0000932 // If this is a case/default statement, and we haven't seen a switch, we have
933 // to emit the code.
934 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
935 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000936
Chris Lattner5b1964b2008-11-11 07:41:27 +0000937 // If this is a switch statement, we want to ignore cases below it.
938 if (isa<SwitchStmt>(S))
939 IgnoreCaseStmts = true;
Mike Stump11289f42009-09-09 15:08:12 +0000940
Chris Lattner5b1964b2008-11-11 07:41:27 +0000941 // Scan subexpressions for verboten labels.
John McCall8322c3a2011-02-13 04:07:26 +0000942 for (Stmt::const_child_range I = S->children(); I; ++I)
Chris Lattner5b1964b2008-11-11 07:41:27 +0000943 if (ContainsLabel(*I, IgnoreCaseStmts))
944 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000945
Chris Lattner5b1964b2008-11-11 07:41:27 +0000946 return false;
947}
948
Chris Lattner29911cc2011-02-28 00:18:40 +0000949/// containsBreak - Return true if the statement contains a break out of it.
950/// If the statement (recursively) contains a switch or loop with a break
951/// inside of it, this is fine.
952bool CodeGenFunction::containsBreak(const Stmt *S) {
953 // Null statement, not a label!
Craig Topper8a13c412014-05-21 05:09:00 +0000954 if (!S) return false;
Chris Lattner29911cc2011-02-28 00:18:40 +0000955
956 // If this is a switch or loop that defines its own break scope, then we can
957 // include it and anything inside of it.
958 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
959 isa<ForStmt>(S))
Chris Lattner30db8282011-02-28 00:42:31 +0000960 return false;
Michael Ilseman686240a2012-12-04 00:29:55 +0000961
Chris Lattner30db8282011-02-28 00:42:31 +0000962 if (isa<BreakStmt>(S))
Chris Lattner29911cc2011-02-28 00:18:40 +0000963 return true;
Michael Ilseman686240a2012-12-04 00:29:55 +0000964
Chris Lattner29911cc2011-02-28 00:18:40 +0000965 // Scan subexpressions for verboten breaks.
966 for (Stmt::const_child_range I = S->children(); I; ++I)
967 if (containsBreak(*I))
968 return true;
Michael Ilseman686240a2012-12-04 00:29:55 +0000969
Chris Lattner29911cc2011-02-28 00:18:40 +0000970 return false;
971}
972
Chris Lattnercd439292008-11-12 08:04:58 +0000973
Chris Lattner41c6ab52011-02-27 23:02:32 +0000974/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
975/// to a constant, or if it does but contains a label, return false. If it
976/// constant folds return true and set the boolean result in Result.
977bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
978 bool &ResultBool) {
Richard Trieuc320c742012-07-23 20:21:35 +0000979 llvm::APSInt ResultInt;
Chris Lattner29911cc2011-02-28 00:18:40 +0000980 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
981 return false;
Michael Ilseman686240a2012-12-04 00:29:55 +0000982
Chris Lattner29911cc2011-02-28 00:18:40 +0000983 ResultBool = ResultInt.getBoolValue();
984 return true;
985}
986
987/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
988/// to a constant, or if it does but contains a label, return false. If it
989/// constant folds return true and set the folded value.
990bool CodeGenFunction::
Richard Trieuc320c742012-07-23 20:21:35 +0000991ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &ResultInt) {
Daniel Dunbarf32443c2008-11-12 22:37:10 +0000992 // FIXME: Rename and handle conversion of other evaluatable things
993 // to bool.
Richard Smith5fab0c92011-12-28 19:48:30 +0000994 llvm::APSInt Int;
995 if (!Cond->EvaluateAsInt(Int, getContext()))
Chris Lattner41c6ab52011-02-27 23:02:32 +0000996 return false; // Not foldable, not integer or not fully evaluatable.
Richard Smith5fab0c92011-12-28 19:48:30 +0000997
Chris Lattnercd439292008-11-12 08:04:58 +0000998 if (CodeGenFunction::ContainsLabel(Cond))
Chris Lattner41c6ab52011-02-27 23:02:32 +0000999 return false; // Contains a label.
Richard Smith5fab0c92011-12-28 19:48:30 +00001000
1001 ResultInt = Int;
Chris Lattner41c6ab52011-02-27 23:02:32 +00001002 return true;
Chris Lattnercd439292008-11-12 08:04:58 +00001003}
1004
1005
Chris Lattner29911cc2011-02-28 00:18:40 +00001006
Chris Lattnercd439292008-11-12 08:04:58 +00001007/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1008/// statement) to the specified blocks. Based on the condition, this might try
1009/// to simplify the codegen of the conditional based on the branch.
1010///
1011void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1012 llvm::BasicBlock *TrueBlock,
Justin Bogneref512b92014-01-06 22:27:43 +00001013 llvm::BasicBlock *FalseBlock,
1014 uint64_t TrueCount) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001015 Cond = Cond->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +00001016
Chris Lattnercd439292008-11-12 08:04:58 +00001017 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
Justin Bogneref512b92014-01-06 22:27:43 +00001018
Chris Lattnercd439292008-11-12 08:04:58 +00001019 // Handle X && Y in a condition.
John McCalle3027922010-08-25 11:45:40 +00001020 if (CondBOp->getOpcode() == BO_LAnd) {
Bob Wilsonbf854f02014-02-17 19:21:09 +00001021 RegionCounter Cnt = getPGORegionCounter(CondBOp);
1022
Chris Lattnercd439292008-11-12 08:04:58 +00001023 // If we have "1 && X", simplify the code. "0 && X" would have constant
1024 // folded if the case was simple enough.
Bill Wendling6c9540e2011-03-04 21:46:03 +00001025 bool ConstantBool = false;
Chris Lattner41c6ab52011-02-27 23:02:32 +00001026 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1027 ConstantBool) {
Chris Lattnercd439292008-11-12 08:04:58 +00001028 // br(1 && X) -> br(X).
Justin Bogneref512b92014-01-06 22:27:43 +00001029 Cnt.beginRegion(Builder);
1030 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1031 TrueCount);
Chris Lattnercd439292008-11-12 08:04:58 +00001032 }
Mike Stump11289f42009-09-09 15:08:12 +00001033
Chris Lattnercd439292008-11-12 08:04:58 +00001034 // If we have "X && 1", simplify the code to use an uncond branch.
1035 // "X && 0" would have been constant folded to 0.
Chris Lattner41c6ab52011-02-27 23:02:32 +00001036 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1037 ConstantBool) {
Chris Lattnercd439292008-11-12 08:04:58 +00001038 // br(X && 1) -> br(X).
Justin Bogneref512b92014-01-06 22:27:43 +00001039 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1040 TrueCount);
Chris Lattnercd439292008-11-12 08:04:58 +00001041 }
Mike Stump11289f42009-09-09 15:08:12 +00001042
Chris Lattnercd439292008-11-12 08:04:58 +00001043 // Emit the LHS as a conditional. If the LHS conditional is false, we
1044 // want to jump to the FalseBlock.
Daniel Dunbara612e792008-11-13 01:38:36 +00001045 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Justin Bogneref512b92014-01-06 22:27:43 +00001046 // The counter tells us how often we evaluate RHS, and all of TrueCount
1047 // can be propagated to that branch.
1048 uint64_t RHSCount = Cnt.getCount();
John McCallce1de612011-01-26 04:00:11 +00001049
1050 ConditionalEvaluation eval(*this);
Justin Bogneref512b92014-01-06 22:27:43 +00001051 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
Chris Lattnercd439292008-11-12 08:04:58 +00001052 EmitBlock(LHSTrue);
Mike Stump11289f42009-09-09 15:08:12 +00001053
Anders Carlsson60ddba62010-01-24 00:20:05 +00001054 // Any temporaries created here are conditional.
Justin Bogneref512b92014-01-06 22:27:43 +00001055 Cnt.beginRegion(Builder);
John McCallce1de612011-01-26 04:00:11 +00001056 eval.begin(*this);
Justin Bogneref512b92014-01-06 22:27:43 +00001057 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
John McCallce1de612011-01-26 04:00:11 +00001058 eval.end(*this);
Anders Carlsson60ddba62010-01-24 00:20:05 +00001059
Chris Lattnercd439292008-11-12 08:04:58 +00001060 return;
Chris Lattner41c6ab52011-02-27 23:02:32 +00001061 }
Michael Ilseman686240a2012-12-04 00:29:55 +00001062
Chris Lattner41c6ab52011-02-27 23:02:32 +00001063 if (CondBOp->getOpcode() == BO_LOr) {
Bob Wilsonbf854f02014-02-17 19:21:09 +00001064 RegionCounter Cnt = getPGORegionCounter(CondBOp);
1065
Chris Lattnercd439292008-11-12 08:04:58 +00001066 // If we have "0 || X", simplify the code. "1 || X" would have constant
1067 // folded if the case was simple enough.
Bill Wendling6c9540e2011-03-04 21:46:03 +00001068 bool ConstantBool = false;
Chris Lattner41c6ab52011-02-27 23:02:32 +00001069 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1070 !ConstantBool) {
Chris Lattnercd439292008-11-12 08:04:58 +00001071 // br(0 || X) -> br(X).
Justin Bogneref512b92014-01-06 22:27:43 +00001072 Cnt.beginRegion(Builder);
1073 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1074 TrueCount);
Chris Lattnercd439292008-11-12 08:04:58 +00001075 }
Mike Stump11289f42009-09-09 15:08:12 +00001076
Chris Lattnercd439292008-11-12 08:04:58 +00001077 // If we have "X || 0", simplify the code to use an uncond branch.
1078 // "X || 1" would have been constant folded to 1.
Chris Lattner41c6ab52011-02-27 23:02:32 +00001079 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1080 !ConstantBool) {
Chris Lattnercd439292008-11-12 08:04:58 +00001081 // br(X || 0) -> br(X).
Justin Bogneref512b92014-01-06 22:27:43 +00001082 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1083 TrueCount);
Chris Lattnercd439292008-11-12 08:04:58 +00001084 }
Mike Stump11289f42009-09-09 15:08:12 +00001085
Chris Lattnercd439292008-11-12 08:04:58 +00001086 // Emit the LHS as a conditional. If the LHS conditional is true, we
1087 // want to jump to the TrueBlock.
Daniel Dunbara612e792008-11-13 01:38:36 +00001088 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Justin Bogneref512b92014-01-06 22:27:43 +00001089 // We have the count for entry to the RHS and for the whole expression
1090 // being true, so we can divy up True count between the short circuit and
1091 // the RHS.
Justin Bognerbe614c72014-01-23 02:54:30 +00001092 uint64_t LHSCount = Cnt.getParentCount() - Cnt.getCount();
Justin Bogneref512b92014-01-06 22:27:43 +00001093 uint64_t RHSCount = TrueCount - LHSCount;
John McCallce1de612011-01-26 04:00:11 +00001094
1095 ConditionalEvaluation eval(*this);
Justin Bogneref512b92014-01-06 22:27:43 +00001096 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
Chris Lattnercd439292008-11-12 08:04:58 +00001097 EmitBlock(LHSFalse);
Mike Stump11289f42009-09-09 15:08:12 +00001098
Anders Carlsson60ddba62010-01-24 00:20:05 +00001099 // Any temporaries created here are conditional.
Justin Bogneref512b92014-01-06 22:27:43 +00001100 Cnt.beginRegion(Builder);
John McCallce1de612011-01-26 04:00:11 +00001101 eval.begin(*this);
Justin Bogneref512b92014-01-06 22:27:43 +00001102 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
1103
John McCallce1de612011-01-26 04:00:11 +00001104 eval.end(*this);
Anders Carlsson60ddba62010-01-24 00:20:05 +00001105
Chris Lattnercd439292008-11-12 08:04:58 +00001106 return;
1107 }
Chris Lattnerd9537732008-11-12 08:13:36 +00001108 }
Mike Stump11289f42009-09-09 15:08:12 +00001109
Chris Lattnerd9537732008-11-12 08:13:36 +00001110 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1111 // br(!x, t, f) -> br(x, f, t)
Justin Bogneref512b92014-01-06 22:27:43 +00001112 if (CondUOp->getOpcode() == UO_LNot) {
1113 // Negate the count.
1114 uint64_t FalseCount = PGO.getCurrentRegionCount() - TrueCount;
1115 // Negate the condition and swap the destination blocks.
1116 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1117 FalseCount);
1118 }
Chris Lattnercd439292008-11-12 08:04:58 +00001119 }
Mike Stump11289f42009-09-09 15:08:12 +00001120
Daniel Dunbarbf3c22e2008-11-12 10:30:32 +00001121 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
Eli Friedman248f8982012-02-14 03:54:45 +00001122 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1123 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1124 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
Daniel Dunbarbf3c22e2008-11-12 10:30:32 +00001125
Justin Bogneref512b92014-01-06 22:27:43 +00001126 RegionCounter Cnt = getPGORegionCounter(CondOp);
Eli Friedman248f8982012-02-14 03:54:45 +00001127 ConditionalEvaluation cond(*this);
Justin Bogneref512b92014-01-06 22:27:43 +00001128 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock, Cnt.getCount());
1129
1130 // When computing PGO branch weights, we only know the overall count for
1131 // the true block. This code is essentially doing tail duplication of the
1132 // naive code-gen, introducing new edges for which counts are not
1133 // available. Divide the counts proportionally between the LHS and RHS of
1134 // the conditional operator.
1135 uint64_t LHSScaledTrueCount = 0;
1136 if (TrueCount) {
Bob Wilsonbf854f02014-02-17 19:21:09 +00001137 double LHSRatio = Cnt.getCount() / (double) Cnt.getParentCount();
Justin Bogneref512b92014-01-06 22:27:43 +00001138 LHSScaledTrueCount = TrueCount * LHSRatio;
1139 }
John McCallce1de612011-01-26 04:00:11 +00001140
Eli Friedman248f8982012-02-14 03:54:45 +00001141 cond.begin(*this);
1142 EmitBlock(LHSBlock);
Justin Bogneref512b92014-01-06 22:27:43 +00001143 Cnt.beginRegion(Builder);
1144 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
1145 LHSScaledTrueCount);
Eli Friedman248f8982012-02-14 03:54:45 +00001146 cond.end(*this);
John McCallce1de612011-01-26 04:00:11 +00001147
Eli Friedman248f8982012-02-14 03:54:45 +00001148 cond.begin(*this);
1149 EmitBlock(RHSBlock);
Justin Bogneref512b92014-01-06 22:27:43 +00001150 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
1151 TrueCount - LHSScaledTrueCount);
Eli Friedman248f8982012-02-14 03:54:45 +00001152 cond.end(*this);
John McCallce1de612011-01-26 04:00:11 +00001153
Eli Friedman248f8982012-02-14 03:54:45 +00001154 return;
Daniel Dunbarbf3c22e2008-11-12 10:30:32 +00001155 }
1156
Richard Smithea852322013-05-07 21:53:22 +00001157 if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1158 // Conditional operator handling can give us a throw expression as a
1159 // condition for a case like:
1160 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1161 // Fold this to:
1162 // br(c, throw x, br(y, t, f))
1163 EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1164 return;
1165 }
1166
Justin Bogneref512b92014-01-06 22:27:43 +00001167 // Create branch weights based on the number of times we get here and the
1168 // number of times the condition should be true.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001169 uint64_t CurrentCount = std::max(PGO.getCurrentRegionCount(), TrueCount);
Justin Bogneref512b92014-01-06 22:27:43 +00001170 llvm::MDNode *Weights = PGO.createBranchWeights(TrueCount,
1171 CurrentCount - TrueCount);
1172
Chris Lattnercd439292008-11-12 08:04:58 +00001173 // Emit the code with the fully general case.
1174 llvm::Value *CondV = EvaluateExprAsBool(Cond);
Justin Bogneref512b92014-01-06 22:27:43 +00001175 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights);
Chris Lattnercd439292008-11-12 08:04:58 +00001176}
1177
Daniel Dunbara7c8cf62008-08-16 00:56:44 +00001178/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerfc944342007-12-02 01:43:38 +00001179/// specified stmt yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +00001180void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1181 CGM.ErrorUnsupported(S, Type);
Chris Lattnerfc944342007-12-02 01:43:38 +00001182}
1183
John McCall2725aa12011-02-01 21:35:06 +00001184/// emitNonZeroVLAInit - Emit the "zero" initialization of a
1185/// variable-length array whose elements have a non-zero bit-pattern.
1186///
James Dennettbe302452012-06-15 22:10:14 +00001187/// \param baseType the inner-most element type of the array
John McCall2725aa12011-02-01 21:35:06 +00001188/// \param src - a char* pointing to the bit-pattern for a single
1189/// base element of the array
1190/// \param sizeInChars - the total size of the VLA, in chars
John McCall2725aa12011-02-01 21:35:06 +00001191static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
Michael Ilseman686240a2012-12-04 00:29:55 +00001192 llvm::Value *dest, llvm::Value *src,
John McCall2725aa12011-02-01 21:35:06 +00001193 llvm::Value *sizeInChars) {
1194 std::pair<CharUnits,CharUnits> baseSizeAndAlign
1195 = CGF.getContext().getTypeInfoInChars(baseType);
1196
1197 CGBuilderTy &Builder = CGF.Builder;
1198
1199 llvm::Value *baseSizeInChars
1200 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
1201
Chris Lattner2192fe52011-07-18 04:24:23 +00001202 llvm::Type *i8p = Builder.getInt8PtrTy();
John McCall2725aa12011-02-01 21:35:06 +00001203
1204 llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
1205 llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
1206
1207 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
1208 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
1209 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
1210
1211 // Make a loop over the VLA. C99 guarantees that the VLA element
1212 // count must be nonzero.
1213 CGF.EmitBlock(loopBB);
1214
Jay Foad20c0f022011-03-30 11:28:58 +00001215 llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur");
John McCall2725aa12011-02-01 21:35:06 +00001216 cur->addIncoming(begin, originBB);
1217
1218 // memcpy the individual element bit-pattern.
1219 Builder.CreateMemCpy(cur, src, baseSizeInChars,
1220 baseSizeAndAlign.second.getQuantity(),
1221 /*volatile*/ false);
1222
1223 // Go to the next element.
1224 llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next");
1225
1226 // Leave if that's the end of the VLA.
1227 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
1228 Builder.CreateCondBr(done, contBB, loopBB);
1229 cur->addIncoming(next, loopBB);
1230
1231 CGF.EmitBlock(contBB);
Michael Ilseman686240a2012-12-04 00:29:55 +00001232}
John McCall2725aa12011-02-01 21:35:06 +00001233
Anders Carlssonc0964b62010-05-22 17:35:42 +00001234void
1235CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
Anders Carlsson16e94af2010-05-03 01:20:20 +00001236 // Ignore empty classes in C++.
Richard Smith9c6890a2012-11-01 22:30:59 +00001237 if (getLangOpts().CPlusPlus) {
Anders Carlsson16e94af2010-05-03 01:20:20 +00001238 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1239 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1240 return;
1241 }
1242 }
John McCall7cd1d972010-08-07 08:21:30 +00001243
1244 // Cast the dest ptr to the appropriate i8 pointer type.
1245 unsigned DestAS =
1246 cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
Chris Lattner2192fe52011-07-18 04:24:23 +00001247 llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
Anders Carlsson2e744e82008-08-30 19:51:14 +00001248 if (DestPtr->getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001249 DestPtr = Builder.CreateBitCast(DestPtr, BP);
Anders Carlsson2e744e82008-08-30 19:51:14 +00001250
1251 // Get size and alignment info for this aggregate.
Michael Ilseman686240a2012-12-04 00:29:55 +00001252 std::pair<CharUnits, CharUnits> TypeInfo =
Ken Dyckc5c416f2011-04-22 17:51:05 +00001253 getContext().getTypeInfoInChars(Ty);
1254 CharUnits Size = TypeInfo.first;
1255 CharUnits Align = TypeInfo.second;
Anders Carlsson2e744e82008-08-30 19:51:14 +00001256
John McCalla08ffd22011-01-14 10:37:58 +00001257 llvm::Value *SizeVal;
John McCall2725aa12011-02-01 21:35:06 +00001258 const VariableArrayType *vla;
Mike Stump11289f42009-09-09 15:08:12 +00001259
John McCalla08ffd22011-01-14 10:37:58 +00001260 // Don't bother emitting a zero-byte memset.
Ken Dyckc5c416f2011-04-22 17:51:05 +00001261 if (Size.isZero()) {
John McCalla08ffd22011-01-14 10:37:58 +00001262 // But note that getTypeInfo returns 0 for a VLA.
1263 if (const VariableArrayType *vlaType =
1264 dyn_cast_or_null<VariableArrayType>(
1265 getContext().getAsArrayType(Ty))) {
John McCall23c29fe2011-06-24 21:55:10 +00001266 QualType eltType;
1267 llvm::Value *numElts;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001268 std::tie(numElts, eltType) = getVLASize(vlaType);
John McCall23c29fe2011-06-24 21:55:10 +00001269
1270 SizeVal = numElts;
1271 CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
1272 if (!eltSize.isOne())
1273 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
John McCall2725aa12011-02-01 21:35:06 +00001274 vla = vlaType;
John McCalla08ffd22011-01-14 10:37:58 +00001275 } else {
1276 return;
1277 }
1278 } else {
John McCall23c29fe2011-06-24 21:55:10 +00001279 SizeVal = CGM.getSize(Size);
Craig Topper8a13c412014-05-21 05:09:00 +00001280 vla = nullptr;
John McCalla08ffd22011-01-14 10:37:58 +00001281 }
John McCall7cd1d972010-08-07 08:21:30 +00001282
1283 // If the type contains a pointer to data member we can't memset it to zero.
1284 // Instead, create a null constant and copy it to the destination.
John McCall2725aa12011-02-01 21:35:06 +00001285 // TODO: there are other patterns besides zero that we can usefully memset,
1286 // like -1, which happens to be the pattern used by member-pointers.
John McCall614dbdc2010-08-22 21:01:12 +00001287 if (!CGM.getTypes().isZeroInitializable(Ty)) {
John McCall2725aa12011-02-01 21:35:06 +00001288 // For a VLA, emit a single element, then splat that over the VLA.
1289 if (vla) Ty = getContext().getBaseElementType(vla);
John McCalla08ffd22011-01-14 10:37:58 +00001290
John McCall7cd1d972010-08-07 08:21:30 +00001291 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1292
Michael Ilseman686240a2012-12-04 00:29:55 +00001293 llvm::GlobalVariable *NullVariable =
John McCall7cd1d972010-08-07 08:21:30 +00001294 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
Michael Ilseman686240a2012-12-04 00:29:55 +00001295 /*isConstant=*/true,
John McCall7cd1d972010-08-07 08:21:30 +00001296 llvm::GlobalVariable::PrivateLinkage,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001297 NullConstant, Twine());
John McCall7cd1d972010-08-07 08:21:30 +00001298 llvm::Value *SrcPtr =
1299 Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
1300
John McCall2725aa12011-02-01 21:35:06 +00001301 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1302
John McCall7cd1d972010-08-07 08:21:30 +00001303 // Get and call the appropriate llvm.memcpy overload.
Ken Dyckc5c416f2011-04-22 17:51:05 +00001304 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false);
John McCall7cd1d972010-08-07 08:21:30 +00001305 return;
Michael Ilseman686240a2012-12-04 00:29:55 +00001306 }
1307
John McCall7cd1d972010-08-07 08:21:30 +00001308 // Otherwise, just memset the whole thing to zero. This is legal
1309 // because in LLVM, all default initializers (other than the ones we just
1310 // handled above) are guaranteed to have a bit pattern of all zeros.
Michael Ilseman686240a2012-12-04 00:29:55 +00001311 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal,
Ken Dyckc5c416f2011-04-22 17:51:05 +00001312 Align.getQuantity(), false);
Anders Carlsson2e744e82008-08-30 19:51:14 +00001313}
1314
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001315llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
Chris Lattner6c4d2552009-10-28 23:59:40 +00001316 // Make sure that there is a block for the indirect goto.
Craig Topper8a13c412014-05-21 05:09:00 +00001317 if (!IndirectBranch)
Chris Lattner6c4d2552009-10-28 23:59:40 +00001318 GetIndirectGotoBlock();
Michael Ilseman686240a2012-12-04 00:29:55 +00001319
John McCallad5d61e2010-07-23 21:56:41 +00001320 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
Michael Ilseman686240a2012-12-04 00:29:55 +00001321
Chris Lattner6c4d2552009-10-28 23:59:40 +00001322 // Make sure the indirect branch includes all of the address-taken blocks.
1323 IndirectBranch->addDestination(BB);
1324 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner2bb5cb42009-10-13 06:55:33 +00001325}
1326
1327llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattner6c4d2552009-10-28 23:59:40 +00001328 // If we already made the indirect branch for indirect goto, return its block.
1329 if (IndirectBranch) return IndirectBranch->getParent();
Michael Ilseman686240a2012-12-04 00:29:55 +00001330
Chris Lattner6c4d2552009-10-28 23:59:40 +00001331 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Michael Ilseman686240a2012-12-04 00:29:55 +00001332
Chris Lattner2bb5cb42009-10-13 06:55:33 +00001333 // Create the PHI node that indirect gotos will add entries to.
Jay Foad20c0f022011-03-30 11:28:58 +00001334 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
1335 "indirect.goto.dest");
Michael Ilseman686240a2012-12-04 00:29:55 +00001336
Chris Lattner6c4d2552009-10-28 23:59:40 +00001337 // Create the indirect branch instruction.
1338 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1339 return IndirectBranch->getParent();
Daniel Dunbar88402ce2008-08-04 16:51:22 +00001340}
Anders Carlsson13abd7e2008-11-04 05:30:00 +00001341
John McCall82fe67b2011-07-09 01:37:26 +00001342/// Computes the length of an array in elements, as well as the base
1343/// element type and a properly-typed first element pointer.
1344llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
1345 QualType &baseType,
1346 llvm::Value *&addr) {
1347 const ArrayType *arrayType = origArrayType;
1348
1349 // If it's a VLA, we have to load the stored size. Note that
1350 // this is the size of the VLA in bytes, not its size in elements.
Craig Topper8a13c412014-05-21 05:09:00 +00001351 llvm::Value *numVLAElements = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001352 if (isa<VariableArrayType>(arrayType)) {
1353 numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
1354
1355 // Walk into all VLAs. This doesn't require changes to addr,
1356 // which has type T* where T is the first non-VLA element type.
1357 do {
1358 QualType elementType = arrayType->getElementType();
1359 arrayType = getContext().getAsArrayType(elementType);
1360
1361 // If we only have VLA components, 'addr' requires no adjustment.
1362 if (!arrayType) {
1363 baseType = elementType;
1364 return numVLAElements;
1365 }
1366 } while (isa<VariableArrayType>(arrayType));
1367
1368 // We get out here only if we find a constant array type
1369 // inside the VLA.
1370 }
1371
1372 // We have some number of constant-length arrays, so addr should
1373 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
1374 // down to the first element of addr.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001375 SmallVector<llvm::Value*, 8> gepIndices;
John McCall82fe67b2011-07-09 01:37:26 +00001376
1377 // GEP down to the array type.
1378 llvm::ConstantInt *zero = Builder.getInt32(0);
1379 gepIndices.push_back(zero);
1380
John McCall82fe67b2011-07-09 01:37:26 +00001381 uint64_t countFromCLAs = 1;
Richard Smithf3c37e82012-04-22 05:51:36 +00001382 QualType eltType;
John McCall82fe67b2011-07-09 01:37:26 +00001383
Chris Lattner2192fe52011-07-18 04:24:23 +00001384 llvm::ArrayType *llvmArrayType =
Richard Smithf3c37e82012-04-22 05:51:36 +00001385 dyn_cast<llvm::ArrayType>(
John McCall82fe67b2011-07-09 01:37:26 +00001386 cast<llvm::PointerType>(addr->getType())->getElementType());
Richard Smithf3c37e82012-04-22 05:51:36 +00001387 while (llvmArrayType) {
John McCall82fe67b2011-07-09 01:37:26 +00001388 assert(isa<ConstantArrayType>(arrayType));
1389 assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
1390 == llvmArrayType->getNumElements());
1391
1392 gepIndices.push_back(zero);
1393 countFromCLAs *= llvmArrayType->getNumElements();
Richard Smithf3c37e82012-04-22 05:51:36 +00001394 eltType = arrayType->getElementType();
John McCall82fe67b2011-07-09 01:37:26 +00001395
1396 llvmArrayType =
1397 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
John McCall82fe67b2011-07-09 01:37:26 +00001398 arrayType = getContext().getAsArrayType(arrayType->getElementType());
Richard Smithf3c37e82012-04-22 05:51:36 +00001399 assert((!llvmArrayType || arrayType) &&
1400 "LLVM and Clang types are out-of-synch");
John McCall82fe67b2011-07-09 01:37:26 +00001401 }
1402
Richard Smithf3c37e82012-04-22 05:51:36 +00001403 if (arrayType) {
1404 // From this point onwards, the Clang array type has been emitted
1405 // as some other type (probably a packed struct). Compute the array
1406 // size, and just emit the 'begin' expression as a bitcast.
1407 while (arrayType) {
1408 countFromCLAs *=
1409 cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
1410 eltType = arrayType->getElementType();
1411 arrayType = getContext().getAsArrayType(eltType);
1412 }
John McCall82fe67b2011-07-09 01:37:26 +00001413
Micah Villmowea2fea22012-10-25 15:39:14 +00001414 unsigned AddressSpace = addr->getType()->getPointerAddressSpace();
Richard Smithf3c37e82012-04-22 05:51:36 +00001415 llvm::Type *BaseType = ConvertType(eltType)->getPointerTo(AddressSpace);
1416 addr = Builder.CreateBitCast(addr, BaseType, "array.begin");
1417 } else {
1418 // Create the actual GEP.
1419 addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin");
1420 }
1421
1422 baseType = eltType;
John McCall82fe67b2011-07-09 01:37:26 +00001423
1424 llvm::Value *numElements
1425 = llvm::ConstantInt::get(SizeTy, countFromCLAs);
1426
1427 // If we had any VLA dimensions, factor them in.
1428 if (numVLAElements)
1429 numElements = Builder.CreateNUWMul(numVLAElements, numElements);
1430
1431 return numElements;
1432}
1433
John McCall23c29fe2011-06-24 21:55:10 +00001434std::pair<llvm::Value*, QualType>
1435CodeGenFunction::getVLASize(QualType type) {
1436 const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
1437 assert(vla && "type was not a variable array type!");
1438 return getVLASize(vla);
Anders Carlssone388a5b2008-12-20 20:27:15 +00001439}
Anders Carlssonccbe9202008-12-12 07:19:02 +00001440
John McCall23c29fe2011-06-24 21:55:10 +00001441std::pair<llvm::Value*, QualType>
1442CodeGenFunction::getVLASize(const VariableArrayType *type) {
1443 // The number of elements so far; always size_t.
Craig Topper8a13c412014-05-21 05:09:00 +00001444 llvm::Value *numElements = nullptr;
John McCall23c29fe2011-06-24 21:55:10 +00001445
1446 QualType elementType;
1447 do {
1448 elementType = type->getElementType();
1449 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
1450 assert(vlaSize && "no size for VLA!");
1451 assert(vlaSize->getType() == SizeTy);
1452
1453 if (!numElements) {
1454 numElements = vlaSize;
1455 } else {
1456 // It's undefined behavior if this wraps around, so mark it that way.
Alexey Samsonovcb3f8122014-03-20 10:48:29 +00001457 // FIXME: Teach -fsanitize=undefined to trap this.
John McCall23c29fe2011-06-24 21:55:10 +00001458 numElements = Builder.CreateNUWMul(numElements, vlaSize);
1459 }
1460 } while ((type = getContext().getAsVariableArrayType(elementType)));
1461
1462 return std::pair<llvm::Value*,QualType>(numElements, elementType);
1463}
1464
1465void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
1466 assert(type->isVariablyModifiedType() &&
Anders Carlsson8a01b792008-12-20 20:46:34 +00001467 "Must pass variably modified type to EmitVLASizes!");
Mike Stump11289f42009-09-09 15:08:12 +00001468
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001469 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00001470
John McCall23c29fe2011-06-24 21:55:10 +00001471 // We're going to walk down into the type and look for VLA
1472 // expressions.
John McCall23c29fe2011-06-24 21:55:10 +00001473 do {
1474 assert(type->isVariablyModifiedType());
Mike Stump11289f42009-09-09 15:08:12 +00001475
John McCall23c29fe2011-06-24 21:55:10 +00001476 const Type *ty = type.getTypePtr();
1477 switch (ty->getTypeClass()) {
Abramo Bagnara1cd83682012-01-07 10:52:36 +00001478
John McCall23c29fe2011-06-24 21:55:10 +00001479#define TYPE(Class, Base)
1480#define ABSTRACT_TYPE(Class, Base)
Abramo Bagnara1cd83682012-01-07 10:52:36 +00001481#define NON_CANONICAL_TYPE(Class, Base)
John McCall23c29fe2011-06-24 21:55:10 +00001482#define DEPENDENT_TYPE(Class, Base) case Type::Class:
Abramo Bagnara1cd83682012-01-07 10:52:36 +00001483#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
John McCall23c29fe2011-06-24 21:55:10 +00001484#include "clang/AST/TypeNodes.def"
Abramo Bagnara1cd83682012-01-07 10:52:36 +00001485 llvm_unreachable("unexpected dependent type!");
Mike Stump11289f42009-09-09 15:08:12 +00001486
John McCall23c29fe2011-06-24 21:55:10 +00001487 // These types are never variably-modified.
1488 case Type::Builtin:
1489 case Type::Complex:
1490 case Type::Vector:
1491 case Type::ExtVector:
1492 case Type::Record:
1493 case Type::Enum:
Abramo Bagnarafa95ed42012-01-11 08:19:46 +00001494 case Type::Elaborated:
1495 case Type::TemplateSpecialization:
John McCall23c29fe2011-06-24 21:55:10 +00001496 case Type::ObjCObject:
1497 case Type::ObjCInterface:
1498 case Type::ObjCObjectPointer:
1499 llvm_unreachable("type class is never variably-modified!");
Mike Stump11289f42009-09-09 15:08:12 +00001500
Reid Kleckner0503a872013-12-05 01:23:43 +00001501 case Type::Adjusted:
1502 type = cast<AdjustedType>(ty)->getAdjustedType();
1503 break;
1504
Reid Kleckner8a365022013-06-24 17:51:48 +00001505 case Type::Decayed:
1506 type = cast<DecayedType>(ty)->getPointeeType();
1507 break;
1508
John McCall23c29fe2011-06-24 21:55:10 +00001509 case Type::Pointer:
1510 type = cast<PointerType>(ty)->getPointeeType();
1511 break;
Mike Stump11289f42009-09-09 15:08:12 +00001512
John McCall23c29fe2011-06-24 21:55:10 +00001513 case Type::BlockPointer:
1514 type = cast<BlockPointerType>(ty)->getPointeeType();
1515 break;
1516
1517 case Type::LValueReference:
1518 case Type::RValueReference:
1519 type = cast<ReferenceType>(ty)->getPointeeType();
1520 break;
1521
1522 case Type::MemberPointer:
1523 type = cast<MemberPointerType>(ty)->getPointeeType();
1524 break;
1525
1526 case Type::ConstantArray:
1527 case Type::IncompleteArray:
1528 // Losing element qualification here is fine.
1529 type = cast<ArrayType>(ty)->getElementType();
1530 break;
1531
1532 case Type::VariableArray: {
1533 // Losing element qualification here is fine.
1534 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1535
1536 // Unknown size indication requires no size computation.
1537 // Otherwise, evaluate and record it.
1538 if (const Expr *size = vat->getSizeExpr()) {
1539 // It's possible that we might have emitted this already,
1540 // e.g. with a typedef and a pointer to it.
1541 llvm::Value *&entry = VLASizeMap[size];
1542 if (!entry) {
Richard Smith481652b2012-10-10 01:11:12 +00001543 llvm::Value *Size = EmitScalarExpr(size);
1544
1545 // C11 6.7.6.2p5:
1546 // If the size is an expression that is not an integer constant
1547 // expression [...] each time it is evaluated it shall have a value
1548 // greater than zero.
Will Dietzf54319c2013-01-18 11:30:38 +00001549 if (SanOpts->VLABound &&
Richard Smithb1b0ab42012-11-05 22:21:05 +00001550 size->getType()->isSignedIntegerType()) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00001551 SanitizerScope SanScope(this);
Richard Smith481652b2012-10-10 01:11:12 +00001552 llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
1553 llvm::Constant *StaticArgs[] = {
1554 EmitCheckSourceLocation(size->getLocStart()),
1555 EmitCheckTypeDescriptor(size->getType())
1556 };
1557 EmitCheck(Builder.CreateICmpSGT(Size, Zero),
Will Dietz88e02332012-12-02 19:50:33 +00001558 "vla_bound_not_positive", StaticArgs, Size,
1559 CRK_Recoverable);
Richard Smith481652b2012-10-10 01:11:12 +00001560 }
1561
John McCall23c29fe2011-06-24 21:55:10 +00001562 // Always zexting here would be wrong if it weren't
1563 // undefined behavior to have a negative bound.
Richard Smith8772bd82012-10-10 01:12:11 +00001564 entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
John McCall23c29fe2011-06-24 21:55:10 +00001565 }
1566 }
1567 type = vat->getElementType();
1568 break;
Anders Carlsson8a01b792008-12-20 20:46:34 +00001569 }
Mike Stump11289f42009-09-09 15:08:12 +00001570
Abramo Bagnara1cd83682012-01-07 10:52:36 +00001571 case Type::FunctionProto:
John McCall23c29fe2011-06-24 21:55:10 +00001572 case Type::FunctionNoProto:
Alp Toker314cc812014-01-25 16:55:45 +00001573 type = cast<FunctionType>(ty)->getReturnType();
John McCall23c29fe2011-06-24 21:55:10 +00001574 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001575
Abramo Bagnarafa95ed42012-01-11 08:19:46 +00001576 case Type::Paren:
1577 case Type::TypeOf:
1578 case Type::UnaryTransform:
1579 case Type::Attributed:
1580 case Type::SubstTemplateTypeParm:
David Blaikie66ed89d2013-07-13 21:08:08 +00001581 case Type::PackExpansion:
Abramo Bagnarafa95ed42012-01-11 08:19:46 +00001582 // Keep walking after single level desugaring.
1583 type = type.getSingleStepDesugaredType(getContext());
1584 break;
1585
1586 case Type::Typedef:
1587 case Type::Decltype:
1588 case Type::Auto:
1589 // Stop walking: nothing to do.
1590 return;
1591
1592 case Type::TypeOfExpr:
1593 // Stop walking: emit typeof expression.
1594 EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
1595 return;
1596
Eli Friedman0dfb8892011-10-06 23:00:33 +00001597 case Type::Atomic:
1598 type = cast<AtomicType>(ty)->getValueType();
1599 break;
John McCall23c29fe2011-06-24 21:55:10 +00001600 }
1601 } while (type->isVariablyModifiedType());
Anders Carlssonccbe9202008-12-12 07:19:02 +00001602}
Eli Friedmanddea0ad2009-01-20 17:46:04 +00001603
1604llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
Dan Gohmane9e32dc2010-10-29 22:47:07 +00001605 if (getContext().getBuiltinVaListType()->isArrayType())
Eli Friedmanddea0ad2009-01-20 17:46:04 +00001606 return EmitScalarExpr(E);
Eli Friedmanddea0ad2009-01-20 17:46:04 +00001607 return EmitLValue(E).getAddress();
1608}
Anders Carlsson15cb75a2009-02-07 22:53:43 +00001609
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001610void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
1611 llvm::Constant *Init) {
Devang Pateldc866e12010-08-10 17:53:33 +00001612 assert (Init && "Invalid DeclRefExpr initializer!");
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001613 if (CGDebugInfo *Dbg = getDebugInfo())
1614 if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1615 Dbg->EmitGlobalVariable(E->getDecl(), Init);
Devang Patele03edfd2010-08-10 07:24:25 +00001616}
John McCallc07a0c72011-02-17 10:25:35 +00001617
1618CodeGenFunction::PeepholeProtection
1619CodeGenFunction::protectFromPeepholes(RValue rvalue) {
1620 // At the moment, the only aggressive peephole we do in IR gen
1621 // is trunc(zext) folding, but if we add more, we can easily
1622 // extend this protection.
1623
1624 if (!rvalue.isScalar()) return PeepholeProtection();
1625 llvm::Value *value = rvalue.getScalarVal();
1626 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
1627
1628 // Just make an extra bitcast.
1629 assert(HaveInsertPoint());
1630 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
1631 Builder.GetInsertBlock());
1632
1633 PeepholeProtection protection;
1634 protection.Inst = inst;
1635 return protection;
1636}
1637
1638void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
1639 if (!protection.Inst) return;
1640
1641 // In theory, we could try to duplicate the peepholes now, but whatever.
1642 protection.Inst->eraseFromParent();
1643}
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001644
1645llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
1646 llvm::Value *AnnotatedVal,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001647 StringRef AnnotationStr,
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001648 SourceLocation Location) {
1649 llvm::Value *Args[4] = {
1650 AnnotatedVal,
1651 Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
1652 Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
1653 CGM.EmitAnnotationLineNo(Location)
1654 };
1655 return Builder.CreateCall(AnnotationFn, Args);
1656}
1657
1658void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
1659 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1660 // FIXME We create a new bitcast for every annotation because that's what
1661 // llvm-gcc was doing.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001662 for (const auto *I : D->specific_attrs<AnnotateAttr>())
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001663 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
1664 Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001665 I->getAnnotation(), D->getLocation());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001666}
1667
1668llvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
1669 llvm::Value *V) {
1670 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1671 llvm::Type *VTy = V->getType();
1672 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
1673 CGM.Int8PtrTy);
1674
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001675 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001676 // FIXME Always emit the cast inst so we can differentiate between
1677 // annotation on the first field of a struct and annotation on the struct
1678 // itself.
1679 if (VTy != CGM.Int8PtrTy)
1680 V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001681 V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001682 V = Builder.CreateBitCast(V, VTy);
1683 }
1684
1685 return V;
1686}
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00001687
1688CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
Alexander Musman515ad8c2014-05-22 08:54:05 +00001689
Alexey Samsonov24cad992014-07-17 18:46:27 +00001690CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
1691 : CGF(CGF) {
1692 assert(!CGF->IsSanitizerScope);
1693 CGF->IsSanitizerScope = true;
1694}
1695
1696CodeGenFunction::SanitizerScope::~SanitizerScope() {
1697 CGF->IsSanitizerScope = false;
1698}
1699
Alexander Musman515ad8c2014-05-22 08:54:05 +00001700void CodeGenFunction::InsertHelper(llvm::Instruction *I,
1701 const llvm::Twine &Name,
1702 llvm::BasicBlock *BB,
1703 llvm::BasicBlock::iterator InsertPt) const {
1704 LoopStack.InsertHelper(I);
Kostya Serebryany4ee69042014-08-26 02:29:59 +00001705 if (IsSanitizerScope)
1706 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
Alexander Musman515ad8c2014-05-22 08:54:05 +00001707}
1708
1709template <bool PreserveNames>
1710void CGBuilderInserter<PreserveNames>::InsertHelper(
1711 llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
1712 llvm::BasicBlock::iterator InsertPt) const {
1713 llvm::IRBuilderDefaultInserter<PreserveNames>::InsertHelper(I, Name, BB,
1714 InsertPt);
1715 if (CGF)
1716 CGF->InsertHelper(I, Name, BB, InsertPt);
1717}
1718
1719#ifdef NDEBUG
1720#define PreserveNames false
1721#else
1722#define PreserveNames true
1723#endif
1724template void CGBuilderInserter<PreserveNames>::InsertHelper(
1725 llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
1726 llvm::BasicBlock::iterator InsertPt) const;
1727#undef PreserveNames