1f4a2713aSLionel Sambuc //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc // The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // This coordinates the per-function state used while generating code.
11f4a2713aSLionel Sambuc //
12f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
13f4a2713aSLionel Sambuc
14f4a2713aSLionel Sambuc #include "CodeGenFunction.h"
15f4a2713aSLionel Sambuc #include "CGCUDARuntime.h"
16f4a2713aSLionel Sambuc #include "CGCXXABI.h"
17f4a2713aSLionel Sambuc #include "CGDebugInfo.h"
18*0a6a1f1dSLionel Sambuc #include "CGOpenMPRuntime.h"
19f4a2713aSLionel Sambuc #include "CodeGenModule.h"
20*0a6a1f1dSLionel Sambuc #include "CodeGenPGO.h"
21f4a2713aSLionel Sambuc #include "TargetInfo.h"
22f4a2713aSLionel Sambuc #include "clang/AST/ASTContext.h"
23f4a2713aSLionel Sambuc #include "clang/AST/Decl.h"
24f4a2713aSLionel Sambuc #include "clang/AST/DeclCXX.h"
25f4a2713aSLionel Sambuc #include "clang/AST/StmtCXX.h"
26f4a2713aSLionel Sambuc #include "clang/Basic/TargetInfo.h"
27f4a2713aSLionel Sambuc #include "clang/CodeGen/CGFunctionInfo.h"
28f4a2713aSLionel Sambuc #include "clang/Frontend/CodeGenOptions.h"
29f4a2713aSLionel Sambuc #include "llvm/IR/DataLayout.h"
30f4a2713aSLionel Sambuc #include "llvm/IR/Intrinsics.h"
31f4a2713aSLionel Sambuc #include "llvm/IR/MDBuilder.h"
32f4a2713aSLionel Sambuc #include "llvm/IR/Operator.h"
33f4a2713aSLionel Sambuc using namespace clang;
34f4a2713aSLionel Sambuc using namespace CodeGen;
35f4a2713aSLionel Sambuc
CodeGenFunction(CodeGenModule & cgm,bool suppressNewContext)36f4a2713aSLionel Sambuc CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
37f4a2713aSLionel Sambuc : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
38*0a6a1f1dSLionel Sambuc Builder(cgm.getModule().getContext(), llvm::ConstantFolder(),
39*0a6a1f1dSLionel Sambuc CGBuilderInserterTy(this)),
40*0a6a1f1dSLionel Sambuc CurFn(nullptr), CapturedStmtInfo(nullptr),
41*0a6a1f1dSLionel Sambuc SanOpts(CGM.getLangOpts().Sanitize), IsSanitizerScope(false),
42*0a6a1f1dSLionel Sambuc CurFuncIsThunk(false), AutoreleaseResult(false), SawAsmBlock(false),
43*0a6a1f1dSLionel Sambuc BlockInfo(nullptr), BlockPointer(nullptr),
44*0a6a1f1dSLionel Sambuc LambdaThisCaptureField(nullptr), NormalCleanupDest(nullptr),
45*0a6a1f1dSLionel Sambuc NextCleanupDestIndex(1), FirstBlockInfo(nullptr), EHResumeBlock(nullptr),
46*0a6a1f1dSLionel Sambuc ExceptionSlot(nullptr), EHSelectorSlot(nullptr),
47*0a6a1f1dSLionel Sambuc DebugInfo(CGM.getModuleDebugInfo()), DisableDebugInfo(false),
48*0a6a1f1dSLionel Sambuc DidCallStackSave(false), IndirectBranch(nullptr), PGO(cgm),
49*0a6a1f1dSLionel Sambuc SwitchInsn(nullptr), SwitchWeights(nullptr), CaseRangeBlock(nullptr),
50*0a6a1f1dSLionel Sambuc UnreachableBlock(nullptr), NumReturnExprs(0), NumSimpleReturnExprs(0),
51*0a6a1f1dSLionel Sambuc CXXABIThisDecl(nullptr), CXXABIThisValue(nullptr), CXXThisValue(nullptr),
52*0a6a1f1dSLionel Sambuc CXXDefaultInitExprThis(nullptr), CXXStructorImplicitParamDecl(nullptr),
53*0a6a1f1dSLionel Sambuc CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
54*0a6a1f1dSLionel Sambuc CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
55*0a6a1f1dSLionel Sambuc TerminateHandler(nullptr), TrapBB(nullptr) {
56f4a2713aSLionel Sambuc if (!suppressNewContext)
57f4a2713aSLionel Sambuc CGM.getCXXABI().getMangleContext().startNewFunction();
58f4a2713aSLionel Sambuc
59f4a2713aSLionel Sambuc llvm::FastMathFlags FMF;
60f4a2713aSLionel Sambuc if (CGM.getLangOpts().FastMath)
61f4a2713aSLionel Sambuc FMF.setUnsafeAlgebra();
62f4a2713aSLionel Sambuc if (CGM.getLangOpts().FiniteMathOnly) {
63f4a2713aSLionel Sambuc FMF.setNoNaNs();
64f4a2713aSLionel Sambuc FMF.setNoInfs();
65f4a2713aSLionel Sambuc }
66*0a6a1f1dSLionel Sambuc if (CGM.getCodeGenOpts().NoNaNsFPMath) {
67*0a6a1f1dSLionel Sambuc FMF.setNoNaNs();
68*0a6a1f1dSLionel Sambuc }
69*0a6a1f1dSLionel Sambuc if (CGM.getCodeGenOpts().NoSignedZeros) {
70*0a6a1f1dSLionel Sambuc FMF.setNoSignedZeros();
71*0a6a1f1dSLionel Sambuc }
72f4a2713aSLionel Sambuc Builder.SetFastMathFlags(FMF);
73f4a2713aSLionel Sambuc }
74f4a2713aSLionel Sambuc
~CodeGenFunction()75f4a2713aSLionel Sambuc CodeGenFunction::~CodeGenFunction() {
76f4a2713aSLionel Sambuc assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
77f4a2713aSLionel Sambuc
78f4a2713aSLionel Sambuc // If there are any unclaimed block infos, go ahead and destroy them
79f4a2713aSLionel Sambuc // now. This can happen if IR-gen gets clever and skips evaluating
80f4a2713aSLionel Sambuc // something.
81f4a2713aSLionel Sambuc if (FirstBlockInfo)
82f4a2713aSLionel Sambuc destroyBlockInfos(FirstBlockInfo);
83*0a6a1f1dSLionel Sambuc
84*0a6a1f1dSLionel Sambuc if (getLangOpts().OpenMP) {
85*0a6a1f1dSLionel Sambuc CGM.getOpenMPRuntime().FunctionFinished(*this);
86*0a6a1f1dSLionel Sambuc }
87f4a2713aSLionel Sambuc }
88f4a2713aSLionel Sambuc
MakeNaturalAlignAddrLValue(llvm::Value * V,QualType T)89*0a6a1f1dSLionel Sambuc LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
90*0a6a1f1dSLionel Sambuc CharUnits Alignment;
91*0a6a1f1dSLionel Sambuc if (CGM.getCXXABI().isTypeInfoCalculable(T)) {
92*0a6a1f1dSLionel Sambuc Alignment = getContext().getTypeAlignInChars(T);
93*0a6a1f1dSLionel Sambuc unsigned MaxAlign = getContext().getLangOpts().MaxTypeAlign;
94*0a6a1f1dSLionel Sambuc if (MaxAlign && Alignment.getQuantity() > MaxAlign &&
95*0a6a1f1dSLionel Sambuc !getContext().isAlignmentRequired(T))
96*0a6a1f1dSLionel Sambuc Alignment = CharUnits::fromQuantity(MaxAlign);
97*0a6a1f1dSLionel Sambuc }
98*0a6a1f1dSLionel Sambuc return LValue::MakeAddr(V, T, Alignment, getContext(), CGM.getTBAAInfo(T));
99*0a6a1f1dSLionel Sambuc }
100f4a2713aSLionel Sambuc
ConvertTypeForMem(QualType T)101f4a2713aSLionel Sambuc llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
102f4a2713aSLionel Sambuc return CGM.getTypes().ConvertTypeForMem(T);
103f4a2713aSLionel Sambuc }
104f4a2713aSLionel Sambuc
ConvertType(QualType T)105f4a2713aSLionel Sambuc llvm::Type *CodeGenFunction::ConvertType(QualType T) {
106f4a2713aSLionel Sambuc return CGM.getTypes().ConvertType(T);
107f4a2713aSLionel Sambuc }
108f4a2713aSLionel Sambuc
getEvaluationKind(QualType type)109f4a2713aSLionel Sambuc TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
110f4a2713aSLionel Sambuc type = type.getCanonicalType();
111f4a2713aSLionel Sambuc while (true) {
112f4a2713aSLionel Sambuc switch (type->getTypeClass()) {
113f4a2713aSLionel Sambuc #define TYPE(name, parent)
114f4a2713aSLionel Sambuc #define ABSTRACT_TYPE(name, parent)
115f4a2713aSLionel Sambuc #define NON_CANONICAL_TYPE(name, parent) case Type::name:
116f4a2713aSLionel Sambuc #define DEPENDENT_TYPE(name, parent) case Type::name:
117f4a2713aSLionel Sambuc #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
118f4a2713aSLionel Sambuc #include "clang/AST/TypeNodes.def"
119f4a2713aSLionel Sambuc llvm_unreachable("non-canonical or dependent type in IR-generation");
120f4a2713aSLionel Sambuc
121f4a2713aSLionel Sambuc case Type::Auto:
122f4a2713aSLionel Sambuc llvm_unreachable("undeduced auto type in IR-generation");
123f4a2713aSLionel Sambuc
124f4a2713aSLionel Sambuc // Various scalar types.
125f4a2713aSLionel Sambuc case Type::Builtin:
126f4a2713aSLionel Sambuc case Type::Pointer:
127f4a2713aSLionel Sambuc case Type::BlockPointer:
128f4a2713aSLionel Sambuc case Type::LValueReference:
129f4a2713aSLionel Sambuc case Type::RValueReference:
130f4a2713aSLionel Sambuc case Type::MemberPointer:
131f4a2713aSLionel Sambuc case Type::Vector:
132f4a2713aSLionel Sambuc case Type::ExtVector:
133f4a2713aSLionel Sambuc case Type::FunctionProto:
134f4a2713aSLionel Sambuc case Type::FunctionNoProto:
135f4a2713aSLionel Sambuc case Type::Enum:
136f4a2713aSLionel Sambuc case Type::ObjCObjectPointer:
137f4a2713aSLionel Sambuc return TEK_Scalar;
138f4a2713aSLionel Sambuc
139f4a2713aSLionel Sambuc // Complexes.
140f4a2713aSLionel Sambuc case Type::Complex:
141f4a2713aSLionel Sambuc return TEK_Complex;
142f4a2713aSLionel Sambuc
143f4a2713aSLionel Sambuc // Arrays, records, and Objective-C objects.
144f4a2713aSLionel Sambuc case Type::ConstantArray:
145f4a2713aSLionel Sambuc case Type::IncompleteArray:
146f4a2713aSLionel Sambuc case Type::VariableArray:
147f4a2713aSLionel Sambuc case Type::Record:
148f4a2713aSLionel Sambuc case Type::ObjCObject:
149f4a2713aSLionel Sambuc case Type::ObjCInterface:
150f4a2713aSLionel Sambuc return TEK_Aggregate;
151f4a2713aSLionel Sambuc
152f4a2713aSLionel Sambuc // We operate on atomic values according to their underlying type.
153f4a2713aSLionel Sambuc case Type::Atomic:
154f4a2713aSLionel Sambuc type = cast<AtomicType>(type)->getValueType();
155f4a2713aSLionel Sambuc continue;
156f4a2713aSLionel Sambuc }
157f4a2713aSLionel Sambuc llvm_unreachable("unknown type kind!");
158f4a2713aSLionel Sambuc }
159f4a2713aSLionel Sambuc }
160f4a2713aSLionel Sambuc
EmitReturnBlock()161*0a6a1f1dSLionel Sambuc llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
162f4a2713aSLionel Sambuc // For cleanliness, we try to avoid emitting the return block for
163f4a2713aSLionel Sambuc // simple cases.
164f4a2713aSLionel Sambuc llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
165f4a2713aSLionel Sambuc
166f4a2713aSLionel Sambuc if (CurBB) {
167f4a2713aSLionel Sambuc assert(!CurBB->getTerminator() && "Unexpected terminated block.");
168f4a2713aSLionel Sambuc
169f4a2713aSLionel Sambuc // We have a valid insert point, reuse it if it is empty or there are no
170f4a2713aSLionel Sambuc // explicit jumps to the return block.
171f4a2713aSLionel Sambuc if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
172f4a2713aSLionel Sambuc ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
173f4a2713aSLionel Sambuc delete ReturnBlock.getBlock();
174f4a2713aSLionel Sambuc } else
175f4a2713aSLionel Sambuc EmitBlock(ReturnBlock.getBlock());
176*0a6a1f1dSLionel Sambuc return llvm::DebugLoc();
177f4a2713aSLionel Sambuc }
178f4a2713aSLionel Sambuc
179f4a2713aSLionel Sambuc // Otherwise, if the return block is the target of a single direct
180f4a2713aSLionel Sambuc // branch then we can just put the code in that block instead. This
181f4a2713aSLionel Sambuc // cleans up functions which started with a unified return block.
182f4a2713aSLionel Sambuc if (ReturnBlock.getBlock()->hasOneUse()) {
183f4a2713aSLionel Sambuc llvm::BranchInst *BI =
184*0a6a1f1dSLionel Sambuc dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
185f4a2713aSLionel Sambuc if (BI && BI->isUnconditional() &&
186f4a2713aSLionel Sambuc BI->getSuccessor(0) == ReturnBlock.getBlock()) {
187*0a6a1f1dSLionel Sambuc // Record/return the DebugLoc of the simple 'return' expression to be used
188*0a6a1f1dSLionel Sambuc // later by the actual 'ret' instruction.
189*0a6a1f1dSLionel Sambuc llvm::DebugLoc Loc = BI->getDebugLoc();
190f4a2713aSLionel Sambuc Builder.SetInsertPoint(BI->getParent());
191f4a2713aSLionel Sambuc BI->eraseFromParent();
192f4a2713aSLionel Sambuc delete ReturnBlock.getBlock();
193*0a6a1f1dSLionel Sambuc return Loc;
194f4a2713aSLionel Sambuc }
195f4a2713aSLionel Sambuc }
196f4a2713aSLionel Sambuc
197f4a2713aSLionel Sambuc // FIXME: We are at an unreachable point, there is no reason to emit the block
198f4a2713aSLionel Sambuc // unless it has uses. However, we still need a place to put the debug
199f4a2713aSLionel Sambuc // region.end for now.
200f4a2713aSLionel Sambuc
201f4a2713aSLionel Sambuc EmitBlock(ReturnBlock.getBlock());
202*0a6a1f1dSLionel Sambuc return llvm::DebugLoc();
203f4a2713aSLionel Sambuc }
204f4a2713aSLionel Sambuc
EmitIfUsed(CodeGenFunction & CGF,llvm::BasicBlock * BB)205f4a2713aSLionel Sambuc static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
206f4a2713aSLionel Sambuc if (!BB) return;
207f4a2713aSLionel Sambuc if (!BB->use_empty())
208f4a2713aSLionel Sambuc return CGF.CurFn->getBasicBlockList().push_back(BB);
209f4a2713aSLionel Sambuc delete BB;
210f4a2713aSLionel Sambuc }
211f4a2713aSLionel Sambuc
FinishFunction(SourceLocation EndLoc)212f4a2713aSLionel Sambuc void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
213f4a2713aSLionel Sambuc assert(BreakContinueStack.empty() &&
214f4a2713aSLionel Sambuc "mismatched push/pop in break/continue stack!");
215f4a2713aSLionel Sambuc
216f4a2713aSLionel Sambuc bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
217f4a2713aSLionel Sambuc && NumSimpleReturnExprs == NumReturnExprs
218f4a2713aSLionel Sambuc && ReturnBlock.getBlock()->use_empty();
219f4a2713aSLionel Sambuc // Usually the return expression is evaluated before the cleanup
220f4a2713aSLionel Sambuc // code. If the function contains only a simple return statement,
221f4a2713aSLionel Sambuc // such as a constant, the location before the cleanup code becomes
222f4a2713aSLionel Sambuc // the last useful breakpoint in the function, because the simple
223f4a2713aSLionel Sambuc // return expression will be evaluated after the cleanup code. To be
224f4a2713aSLionel Sambuc // safe, set the debug location for cleanup code to the location of
225f4a2713aSLionel Sambuc // the return statement. Otherwise the cleanup code should be at the
226f4a2713aSLionel Sambuc // end of the function's lexical scope.
227f4a2713aSLionel Sambuc //
228f4a2713aSLionel Sambuc // If there are multiple branches to the return block, the branch
229f4a2713aSLionel Sambuc // instructions will get the location of the return statements and
230f4a2713aSLionel Sambuc // all will be fine.
231f4a2713aSLionel Sambuc if (CGDebugInfo *DI = getDebugInfo()) {
232f4a2713aSLionel Sambuc if (OnlySimpleReturnStmts)
233f4a2713aSLionel Sambuc DI->EmitLocation(Builder, LastStopPoint);
234f4a2713aSLionel Sambuc else
235f4a2713aSLionel Sambuc DI->EmitLocation(Builder, EndLoc);
236f4a2713aSLionel Sambuc }
237f4a2713aSLionel Sambuc
238f4a2713aSLionel Sambuc // Pop any cleanups that might have been associated with the
239f4a2713aSLionel Sambuc // parameters. Do this in whatever block we're currently in; it's
240f4a2713aSLionel Sambuc // important to do this before we enter the return block or return
241f4a2713aSLionel Sambuc // edges will be *really* confused.
242f4a2713aSLionel Sambuc bool EmitRetDbgLoc = true;
243f4a2713aSLionel Sambuc if (EHStack.stable_begin() != PrologueCleanupDepth) {
244f4a2713aSLionel Sambuc PopCleanupBlocks(PrologueCleanupDepth);
245f4a2713aSLionel Sambuc
246f4a2713aSLionel Sambuc // Make sure the line table doesn't jump back into the body for
247f4a2713aSLionel Sambuc // the ret after it's been at EndLoc.
248f4a2713aSLionel Sambuc EmitRetDbgLoc = false;
249f4a2713aSLionel Sambuc
250f4a2713aSLionel Sambuc if (CGDebugInfo *DI = getDebugInfo())
251f4a2713aSLionel Sambuc if (OnlySimpleReturnStmts)
252f4a2713aSLionel Sambuc DI->EmitLocation(Builder, EndLoc);
253f4a2713aSLionel Sambuc }
254f4a2713aSLionel Sambuc
255f4a2713aSLionel Sambuc // Emit function epilog (to return).
256*0a6a1f1dSLionel Sambuc llvm::DebugLoc Loc = EmitReturnBlock();
257f4a2713aSLionel Sambuc
258f4a2713aSLionel Sambuc if (ShouldInstrumentFunction())
259f4a2713aSLionel Sambuc EmitFunctionInstrumentation("__cyg_profile_func_exit");
260f4a2713aSLionel Sambuc
261f4a2713aSLionel Sambuc // Emit debug descriptor for function end.
262*0a6a1f1dSLionel Sambuc if (CGDebugInfo *DI = getDebugInfo())
263f4a2713aSLionel Sambuc DI->EmitFunctionEnd(Builder);
264f4a2713aSLionel Sambuc
265*0a6a1f1dSLionel Sambuc // Reset the debug location to that of the simple 'return' expression, if any
266*0a6a1f1dSLionel Sambuc // rather than that of the end of the function's scope '}'.
267*0a6a1f1dSLionel Sambuc ApplyDebugLocation AL(*this, Loc);
268f4a2713aSLionel Sambuc EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
269f4a2713aSLionel Sambuc EmitEndEHSpec(CurCodeDecl);
270f4a2713aSLionel Sambuc
271f4a2713aSLionel Sambuc assert(EHStack.empty() &&
272f4a2713aSLionel Sambuc "did not remove all scopes from cleanup stack!");
273f4a2713aSLionel Sambuc
274f4a2713aSLionel Sambuc // If someone did an indirect goto, emit the indirect goto block at the end of
275f4a2713aSLionel Sambuc // the function.
276f4a2713aSLionel Sambuc if (IndirectBranch) {
277f4a2713aSLionel Sambuc EmitBlock(IndirectBranch->getParent());
278f4a2713aSLionel Sambuc Builder.ClearInsertionPoint();
279f4a2713aSLionel Sambuc }
280f4a2713aSLionel Sambuc
281f4a2713aSLionel Sambuc // Remove the AllocaInsertPt instruction, which is just a convenience for us.
282f4a2713aSLionel Sambuc llvm::Instruction *Ptr = AllocaInsertPt;
283*0a6a1f1dSLionel Sambuc AllocaInsertPt = nullptr;
284f4a2713aSLionel Sambuc Ptr->eraseFromParent();
285f4a2713aSLionel Sambuc
286f4a2713aSLionel Sambuc // If someone took the address of a label but never did an indirect goto, we
287f4a2713aSLionel Sambuc // made a zero entry PHI node, which is illegal, zap it now.
288f4a2713aSLionel Sambuc if (IndirectBranch) {
289f4a2713aSLionel Sambuc llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
290f4a2713aSLionel Sambuc if (PN->getNumIncomingValues() == 0) {
291f4a2713aSLionel Sambuc PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
292f4a2713aSLionel Sambuc PN->eraseFromParent();
293f4a2713aSLionel Sambuc }
294f4a2713aSLionel Sambuc }
295f4a2713aSLionel Sambuc
296f4a2713aSLionel Sambuc EmitIfUsed(*this, EHResumeBlock);
297f4a2713aSLionel Sambuc EmitIfUsed(*this, TerminateLandingPad);
298f4a2713aSLionel Sambuc EmitIfUsed(*this, TerminateHandler);
299f4a2713aSLionel Sambuc EmitIfUsed(*this, UnreachableBlock);
300f4a2713aSLionel Sambuc
301f4a2713aSLionel Sambuc if (CGM.getCodeGenOpts().EmitDeclMetadata)
302f4a2713aSLionel Sambuc EmitDeclMetadata();
303*0a6a1f1dSLionel Sambuc
304*0a6a1f1dSLionel Sambuc for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
305*0a6a1f1dSLionel Sambuc I = DeferredReplacements.begin(),
306*0a6a1f1dSLionel Sambuc E = DeferredReplacements.end();
307*0a6a1f1dSLionel Sambuc I != E; ++I) {
308*0a6a1f1dSLionel Sambuc I->first->replaceAllUsesWith(I->second);
309*0a6a1f1dSLionel Sambuc I->first->eraseFromParent();
310*0a6a1f1dSLionel Sambuc }
311f4a2713aSLionel Sambuc }
312f4a2713aSLionel Sambuc
313f4a2713aSLionel Sambuc /// ShouldInstrumentFunction - Return true if the current function should be
314f4a2713aSLionel Sambuc /// instrumented with __cyg_profile_func_* calls
ShouldInstrumentFunction()315f4a2713aSLionel Sambuc bool CodeGenFunction::ShouldInstrumentFunction() {
316f4a2713aSLionel Sambuc if (!CGM.getCodeGenOpts().InstrumentFunctions)
317f4a2713aSLionel Sambuc return false;
318f4a2713aSLionel Sambuc if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
319f4a2713aSLionel Sambuc return false;
320f4a2713aSLionel Sambuc return true;
321f4a2713aSLionel Sambuc }
322f4a2713aSLionel Sambuc
323f4a2713aSLionel Sambuc /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
324f4a2713aSLionel Sambuc /// instrumentation function with the current function and the call site, if
325f4a2713aSLionel Sambuc /// function instrumentation is enabled.
EmitFunctionInstrumentation(const char * Fn)326f4a2713aSLionel Sambuc void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
327f4a2713aSLionel Sambuc // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
328f4a2713aSLionel Sambuc llvm::PointerType *PointerTy = Int8PtrTy;
329f4a2713aSLionel Sambuc llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
330f4a2713aSLionel Sambuc llvm::FunctionType *FunctionTy =
331f4a2713aSLionel Sambuc llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
332f4a2713aSLionel Sambuc
333f4a2713aSLionel Sambuc llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
334f4a2713aSLionel Sambuc llvm::CallInst *CallSite = Builder.CreateCall(
335f4a2713aSLionel Sambuc CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
336f4a2713aSLionel Sambuc llvm::ConstantInt::get(Int32Ty, 0),
337f4a2713aSLionel Sambuc "callsite");
338f4a2713aSLionel Sambuc
339f4a2713aSLionel Sambuc llvm::Value *args[] = {
340f4a2713aSLionel Sambuc llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
341f4a2713aSLionel Sambuc CallSite
342f4a2713aSLionel Sambuc };
343f4a2713aSLionel Sambuc
344f4a2713aSLionel Sambuc EmitNounwindRuntimeCall(F, args);
345f4a2713aSLionel Sambuc }
346f4a2713aSLionel Sambuc
EmitMCountInstrumentation()347f4a2713aSLionel Sambuc void CodeGenFunction::EmitMCountInstrumentation() {
348f4a2713aSLionel Sambuc llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
349f4a2713aSLionel Sambuc
350f4a2713aSLionel Sambuc llvm::Constant *MCountFn =
351f4a2713aSLionel Sambuc CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName());
352f4a2713aSLionel Sambuc EmitNounwindRuntimeCall(MCountFn);
353f4a2713aSLionel Sambuc }
354f4a2713aSLionel Sambuc
355f4a2713aSLionel Sambuc // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
356f4a2713aSLionel Sambuc // information in the program executable. The argument information stored
357f4a2713aSLionel Sambuc // includes the argument name, its type, the address and access qualifiers used.
GenOpenCLArgMetadata(const FunctionDecl * FD,llvm::Function * Fn,CodeGenModule & CGM,llvm::LLVMContext & Context,SmallVector<llvm::Metadata *,5> & kernelMDArgs,CGBuilderTy & Builder,ASTContext & ASTCtx)358f4a2713aSLionel Sambuc static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
359f4a2713aSLionel Sambuc CodeGenModule &CGM, llvm::LLVMContext &Context,
360*0a6a1f1dSLionel Sambuc SmallVector<llvm::Metadata *, 5> &kernelMDArgs,
361f4a2713aSLionel Sambuc CGBuilderTy &Builder, ASTContext &ASTCtx) {
362f4a2713aSLionel Sambuc // Create MDNodes that represent the kernel arg metadata.
363f4a2713aSLionel Sambuc // Each MDNode is a list in the form of "key", N number of values which is
364f4a2713aSLionel Sambuc // the same number of values as their are kernel arguments.
365f4a2713aSLionel Sambuc
366*0a6a1f1dSLionel Sambuc const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
367*0a6a1f1dSLionel Sambuc
368f4a2713aSLionel Sambuc // MDNode for the kernel argument address space qualifiers.
369*0a6a1f1dSLionel Sambuc SmallVector<llvm::Metadata *, 8> addressQuals;
370f4a2713aSLionel Sambuc addressQuals.push_back(llvm::MDString::get(Context, "kernel_arg_addr_space"));
371f4a2713aSLionel Sambuc
372f4a2713aSLionel Sambuc // MDNode for the kernel argument access qualifiers (images only).
373*0a6a1f1dSLionel Sambuc SmallVector<llvm::Metadata *, 8> accessQuals;
374f4a2713aSLionel Sambuc accessQuals.push_back(llvm::MDString::get(Context, "kernel_arg_access_qual"));
375f4a2713aSLionel Sambuc
376f4a2713aSLionel Sambuc // MDNode for the kernel argument type names.
377*0a6a1f1dSLionel Sambuc SmallVector<llvm::Metadata *, 8> argTypeNames;
378f4a2713aSLionel Sambuc argTypeNames.push_back(llvm::MDString::get(Context, "kernel_arg_type"));
379f4a2713aSLionel Sambuc
380*0a6a1f1dSLionel Sambuc // MDNode for the kernel argument base type names.
381*0a6a1f1dSLionel Sambuc SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
382*0a6a1f1dSLionel Sambuc argBaseTypeNames.push_back(
383*0a6a1f1dSLionel Sambuc llvm::MDString::get(Context, "kernel_arg_base_type"));
384*0a6a1f1dSLionel Sambuc
385f4a2713aSLionel Sambuc // MDNode for the kernel argument type qualifiers.
386*0a6a1f1dSLionel Sambuc SmallVector<llvm::Metadata *, 8> argTypeQuals;
387f4a2713aSLionel Sambuc argTypeQuals.push_back(llvm::MDString::get(Context, "kernel_arg_type_qual"));
388f4a2713aSLionel Sambuc
389f4a2713aSLionel Sambuc // MDNode for the kernel argument names.
390*0a6a1f1dSLionel Sambuc SmallVector<llvm::Metadata *, 8> argNames;
391f4a2713aSLionel Sambuc argNames.push_back(llvm::MDString::get(Context, "kernel_arg_name"));
392f4a2713aSLionel Sambuc
393f4a2713aSLionel Sambuc for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
394f4a2713aSLionel Sambuc const ParmVarDecl *parm = FD->getParamDecl(i);
395f4a2713aSLionel Sambuc QualType ty = parm->getType();
396f4a2713aSLionel Sambuc std::string typeQuals;
397f4a2713aSLionel Sambuc
398f4a2713aSLionel Sambuc if (ty->isPointerType()) {
399f4a2713aSLionel Sambuc QualType pointeeTy = ty->getPointeeType();
400f4a2713aSLionel Sambuc
401f4a2713aSLionel Sambuc // Get address qualifier.
402*0a6a1f1dSLionel Sambuc addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
403*0a6a1f1dSLionel Sambuc ASTCtx.getTargetAddressSpace(pointeeTy.getAddressSpace()))));
404f4a2713aSLionel Sambuc
405f4a2713aSLionel Sambuc // Get argument type name.
406*0a6a1f1dSLionel Sambuc std::string typeName =
407*0a6a1f1dSLionel Sambuc pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
408f4a2713aSLionel Sambuc
409f4a2713aSLionel Sambuc // Turn "unsigned type" to "utype"
410f4a2713aSLionel Sambuc std::string::size_type pos = typeName.find("unsigned");
411*0a6a1f1dSLionel Sambuc if (pointeeTy.isCanonical() && pos != std::string::npos)
412f4a2713aSLionel Sambuc typeName.erase(pos+1, 8);
413f4a2713aSLionel Sambuc
414f4a2713aSLionel Sambuc argTypeNames.push_back(llvm::MDString::get(Context, typeName));
415f4a2713aSLionel Sambuc
416*0a6a1f1dSLionel Sambuc std::string baseTypeName =
417*0a6a1f1dSLionel Sambuc pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
418*0a6a1f1dSLionel Sambuc Policy) +
419*0a6a1f1dSLionel Sambuc "*";
420*0a6a1f1dSLionel Sambuc
421*0a6a1f1dSLionel Sambuc // Turn "unsigned type" to "utype"
422*0a6a1f1dSLionel Sambuc pos = baseTypeName.find("unsigned");
423*0a6a1f1dSLionel Sambuc if (pos != std::string::npos)
424*0a6a1f1dSLionel Sambuc baseTypeName.erase(pos+1, 8);
425*0a6a1f1dSLionel Sambuc
426*0a6a1f1dSLionel Sambuc argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
427*0a6a1f1dSLionel Sambuc
428f4a2713aSLionel Sambuc // Get argument type qualifiers:
429f4a2713aSLionel Sambuc if (ty.isRestrictQualified())
430f4a2713aSLionel Sambuc typeQuals = "restrict";
431f4a2713aSLionel Sambuc if (pointeeTy.isConstQualified() ||
432f4a2713aSLionel Sambuc (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
433f4a2713aSLionel Sambuc typeQuals += typeQuals.empty() ? "const" : " const";
434f4a2713aSLionel Sambuc if (pointeeTy.isVolatileQualified())
435f4a2713aSLionel Sambuc typeQuals += typeQuals.empty() ? "volatile" : " volatile";
436f4a2713aSLionel Sambuc } else {
437*0a6a1f1dSLionel Sambuc uint32_t AddrSpc = 0;
438*0a6a1f1dSLionel Sambuc if (ty->isImageType())
439*0a6a1f1dSLionel Sambuc AddrSpc =
440*0a6a1f1dSLionel Sambuc CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
441*0a6a1f1dSLionel Sambuc
442*0a6a1f1dSLionel Sambuc addressQuals.push_back(
443*0a6a1f1dSLionel Sambuc llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
444f4a2713aSLionel Sambuc
445f4a2713aSLionel Sambuc // Get argument type name.
446*0a6a1f1dSLionel Sambuc std::string typeName = ty.getUnqualifiedType().getAsString(Policy);
447f4a2713aSLionel Sambuc
448f4a2713aSLionel Sambuc // Turn "unsigned type" to "utype"
449f4a2713aSLionel Sambuc std::string::size_type pos = typeName.find("unsigned");
450*0a6a1f1dSLionel Sambuc if (ty.isCanonical() && pos != std::string::npos)
451f4a2713aSLionel Sambuc typeName.erase(pos+1, 8);
452f4a2713aSLionel Sambuc
453f4a2713aSLionel Sambuc argTypeNames.push_back(llvm::MDString::get(Context, typeName));
454f4a2713aSLionel Sambuc
455*0a6a1f1dSLionel Sambuc std::string baseTypeName =
456*0a6a1f1dSLionel Sambuc ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
457*0a6a1f1dSLionel Sambuc
458*0a6a1f1dSLionel Sambuc // Turn "unsigned type" to "utype"
459*0a6a1f1dSLionel Sambuc pos = baseTypeName.find("unsigned");
460*0a6a1f1dSLionel Sambuc if (pos != std::string::npos)
461*0a6a1f1dSLionel Sambuc baseTypeName.erase(pos+1, 8);
462*0a6a1f1dSLionel Sambuc
463*0a6a1f1dSLionel Sambuc argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
464*0a6a1f1dSLionel Sambuc
465f4a2713aSLionel Sambuc // Get argument type qualifiers:
466f4a2713aSLionel Sambuc if (ty.isConstQualified())
467f4a2713aSLionel Sambuc typeQuals = "const";
468f4a2713aSLionel Sambuc if (ty.isVolatileQualified())
469f4a2713aSLionel Sambuc typeQuals += typeQuals.empty() ? "volatile" : " volatile";
470f4a2713aSLionel Sambuc }
471f4a2713aSLionel Sambuc
472f4a2713aSLionel Sambuc argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
473f4a2713aSLionel Sambuc
474f4a2713aSLionel Sambuc // Get image access qualifier:
475f4a2713aSLionel Sambuc if (ty->isImageType()) {
476*0a6a1f1dSLionel Sambuc const OpenCLImageAccessAttr *A = parm->getAttr<OpenCLImageAccessAttr>();
477*0a6a1f1dSLionel Sambuc if (A && A->isWriteOnly())
478f4a2713aSLionel Sambuc accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
479f4a2713aSLionel Sambuc else
480f4a2713aSLionel Sambuc accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
481*0a6a1f1dSLionel Sambuc // FIXME: what about read_write?
482f4a2713aSLionel Sambuc } else
483f4a2713aSLionel Sambuc accessQuals.push_back(llvm::MDString::get(Context, "none"));
484f4a2713aSLionel Sambuc
485f4a2713aSLionel Sambuc // Get argument name.
486f4a2713aSLionel Sambuc argNames.push_back(llvm::MDString::get(Context, parm->getName()));
487f4a2713aSLionel Sambuc }
488f4a2713aSLionel Sambuc
489f4a2713aSLionel Sambuc kernelMDArgs.push_back(llvm::MDNode::get(Context, addressQuals));
490f4a2713aSLionel Sambuc kernelMDArgs.push_back(llvm::MDNode::get(Context, accessQuals));
491f4a2713aSLionel Sambuc kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames));
492*0a6a1f1dSLionel Sambuc kernelMDArgs.push_back(llvm::MDNode::get(Context, argBaseTypeNames));
493f4a2713aSLionel Sambuc kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals));
494*0a6a1f1dSLionel Sambuc if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
495f4a2713aSLionel Sambuc kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames));
496f4a2713aSLionel Sambuc }
497f4a2713aSLionel Sambuc
EmitOpenCLKernelMetadata(const FunctionDecl * FD,llvm::Function * Fn)498f4a2713aSLionel Sambuc void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
499f4a2713aSLionel Sambuc llvm::Function *Fn)
500f4a2713aSLionel Sambuc {
501f4a2713aSLionel Sambuc if (!FD->hasAttr<OpenCLKernelAttr>())
502f4a2713aSLionel Sambuc return;
503f4a2713aSLionel Sambuc
504f4a2713aSLionel Sambuc llvm::LLVMContext &Context = getLLVMContext();
505f4a2713aSLionel Sambuc
506*0a6a1f1dSLionel Sambuc SmallVector<llvm::Metadata *, 5> kernelMDArgs;
507*0a6a1f1dSLionel Sambuc kernelMDArgs.push_back(llvm::ConstantAsMetadata::get(Fn));
508f4a2713aSLionel Sambuc
509*0a6a1f1dSLionel Sambuc GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs, Builder,
510*0a6a1f1dSLionel Sambuc getContext());
511f4a2713aSLionel Sambuc
512*0a6a1f1dSLionel Sambuc if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
513*0a6a1f1dSLionel Sambuc QualType hintQTy = A->getTypeHint();
514f4a2713aSLionel Sambuc const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
515f4a2713aSLionel Sambuc bool isSignedInteger =
516f4a2713aSLionel Sambuc hintQTy->isSignedIntegerType() ||
517f4a2713aSLionel Sambuc (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
518*0a6a1f1dSLionel Sambuc llvm::Metadata *attrMDArgs[] = {
519f4a2713aSLionel Sambuc llvm::MDString::get(Context, "vec_type_hint"),
520*0a6a1f1dSLionel Sambuc llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
521*0a6a1f1dSLionel Sambuc CGM.getTypes().ConvertType(A->getTypeHint()))),
522*0a6a1f1dSLionel Sambuc llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
523f4a2713aSLionel Sambuc llvm::IntegerType::get(Context, 32),
524*0a6a1f1dSLionel Sambuc llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))};
525f4a2713aSLionel Sambuc kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
526f4a2713aSLionel Sambuc }
527f4a2713aSLionel Sambuc
528*0a6a1f1dSLionel Sambuc if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
529*0a6a1f1dSLionel Sambuc llvm::Metadata *attrMDArgs[] = {
530f4a2713aSLionel Sambuc llvm::MDString::get(Context, "work_group_size_hint"),
531*0a6a1f1dSLionel Sambuc llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
532*0a6a1f1dSLionel Sambuc llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
533*0a6a1f1dSLionel Sambuc llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
534f4a2713aSLionel Sambuc kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
535f4a2713aSLionel Sambuc }
536f4a2713aSLionel Sambuc
537*0a6a1f1dSLionel Sambuc if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
538*0a6a1f1dSLionel Sambuc llvm::Metadata *attrMDArgs[] = {
539f4a2713aSLionel Sambuc llvm::MDString::get(Context, "reqd_work_group_size"),
540*0a6a1f1dSLionel Sambuc llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
541*0a6a1f1dSLionel Sambuc llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
542*0a6a1f1dSLionel Sambuc llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
543f4a2713aSLionel Sambuc kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
544f4a2713aSLionel Sambuc }
545f4a2713aSLionel Sambuc
546f4a2713aSLionel Sambuc llvm::MDNode *kernelMDNode = llvm::MDNode::get(Context, kernelMDArgs);
547f4a2713aSLionel Sambuc llvm::NamedMDNode *OpenCLKernelMetadata =
548f4a2713aSLionel Sambuc CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
549f4a2713aSLionel Sambuc OpenCLKernelMetadata->addOperand(kernelMDNode);
550f4a2713aSLionel Sambuc }
551f4a2713aSLionel Sambuc
552*0a6a1f1dSLionel Sambuc /// Determine whether the function F ends with a return stmt.
endsWithReturn(const Decl * F)553*0a6a1f1dSLionel Sambuc static bool endsWithReturn(const Decl* F) {
554*0a6a1f1dSLionel Sambuc const Stmt *Body = nullptr;
555*0a6a1f1dSLionel Sambuc if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
556*0a6a1f1dSLionel Sambuc Body = FD->getBody();
557*0a6a1f1dSLionel Sambuc else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
558*0a6a1f1dSLionel Sambuc Body = OMD->getBody();
559*0a6a1f1dSLionel Sambuc
560*0a6a1f1dSLionel Sambuc if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
561*0a6a1f1dSLionel Sambuc auto LastStmt = CS->body_rbegin();
562*0a6a1f1dSLionel Sambuc if (LastStmt != CS->body_rend())
563*0a6a1f1dSLionel Sambuc return isa<ReturnStmt>(*LastStmt);
564*0a6a1f1dSLionel Sambuc }
565*0a6a1f1dSLionel Sambuc return false;
566*0a6a1f1dSLionel Sambuc }
567*0a6a1f1dSLionel Sambuc
StartFunction(GlobalDecl GD,QualType RetTy,llvm::Function * Fn,const CGFunctionInfo & FnInfo,const FunctionArgList & Args,SourceLocation Loc,SourceLocation StartLoc)568f4a2713aSLionel Sambuc void CodeGenFunction::StartFunction(GlobalDecl GD,
569f4a2713aSLionel Sambuc QualType RetTy,
570f4a2713aSLionel Sambuc llvm::Function *Fn,
571f4a2713aSLionel Sambuc const CGFunctionInfo &FnInfo,
572f4a2713aSLionel Sambuc const FunctionArgList &Args,
573*0a6a1f1dSLionel Sambuc SourceLocation Loc,
574f4a2713aSLionel Sambuc SourceLocation StartLoc) {
575*0a6a1f1dSLionel Sambuc assert(!CurFn &&
576*0a6a1f1dSLionel Sambuc "Do not use a CodeGenFunction object for more than one function");
577*0a6a1f1dSLionel Sambuc
578f4a2713aSLionel Sambuc const Decl *D = GD.getDecl();
579f4a2713aSLionel Sambuc
580f4a2713aSLionel Sambuc DidCallStackSave = false;
581f4a2713aSLionel Sambuc CurCodeDecl = D;
582*0a6a1f1dSLionel Sambuc CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
583f4a2713aSLionel Sambuc FnRetTy = RetTy;
584f4a2713aSLionel Sambuc CurFn = Fn;
585f4a2713aSLionel Sambuc CurFnInfo = &FnInfo;
586f4a2713aSLionel Sambuc assert(CurFn->isDeclaration() && "Function already has body?");
587f4a2713aSLionel Sambuc
588*0a6a1f1dSLionel Sambuc if (CGM.isInSanitizerBlacklist(Fn, Loc))
589*0a6a1f1dSLionel Sambuc SanOpts.clear();
590f4a2713aSLionel Sambuc
591f4a2713aSLionel Sambuc // Pass inline keyword to optimizer if it appears explicitly on any
592*0a6a1f1dSLionel Sambuc // declaration. Also, in the case of -fno-inline attach NoInline
593*0a6a1f1dSLionel Sambuc // attribute to all function that are not marked AlwaysInline.
594*0a6a1f1dSLionel Sambuc if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
595*0a6a1f1dSLionel Sambuc if (!CGM.getCodeGenOpts().NoInline) {
596*0a6a1f1dSLionel Sambuc for (auto RI : FD->redecls())
597f4a2713aSLionel Sambuc if (RI->isInlineSpecified()) {
598f4a2713aSLionel Sambuc Fn->addFnAttr(llvm::Attribute::InlineHint);
599f4a2713aSLionel Sambuc break;
600f4a2713aSLionel Sambuc }
601*0a6a1f1dSLionel Sambuc } else if (!FD->hasAttr<AlwaysInlineAttr>())
602*0a6a1f1dSLionel Sambuc Fn->addFnAttr(llvm::Attribute::NoInline);
603*0a6a1f1dSLionel Sambuc }
604f4a2713aSLionel Sambuc
605f4a2713aSLionel Sambuc if (getLangOpts().OpenCL) {
606f4a2713aSLionel Sambuc // Add metadata for a kernel function.
607f4a2713aSLionel Sambuc if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
608f4a2713aSLionel Sambuc EmitOpenCLKernelMetadata(FD, Fn);
609f4a2713aSLionel Sambuc }
610f4a2713aSLionel Sambuc
611f4a2713aSLionel Sambuc // If we are checking function types, emit a function type signature as
612*0a6a1f1dSLionel Sambuc // prologue data.
613*0a6a1f1dSLionel Sambuc if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
614f4a2713aSLionel Sambuc if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
615*0a6a1f1dSLionel Sambuc if (llvm::Constant *PrologueSig =
616f4a2713aSLionel Sambuc CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
617f4a2713aSLionel Sambuc llvm::Constant *FTRTTIConst =
618f4a2713aSLionel Sambuc CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
619*0a6a1f1dSLionel Sambuc llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst };
620*0a6a1f1dSLionel Sambuc llvm::Constant *PrologueStructConst =
621*0a6a1f1dSLionel Sambuc llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
622*0a6a1f1dSLionel Sambuc Fn->setPrologueData(PrologueStructConst);
623f4a2713aSLionel Sambuc }
624f4a2713aSLionel Sambuc }
625f4a2713aSLionel Sambuc }
626f4a2713aSLionel Sambuc
627f4a2713aSLionel Sambuc llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
628f4a2713aSLionel Sambuc
629f4a2713aSLionel Sambuc // Create a marker to make it easy to insert allocas into the entryblock
630f4a2713aSLionel Sambuc // later. Don't create this with the builder, because we don't want it
631f4a2713aSLionel Sambuc // folded.
632f4a2713aSLionel Sambuc llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
633f4a2713aSLionel Sambuc AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
634f4a2713aSLionel Sambuc if (Builder.isNamePreserving())
635f4a2713aSLionel Sambuc AllocaInsertPt->setName("allocapt");
636f4a2713aSLionel Sambuc
637f4a2713aSLionel Sambuc ReturnBlock = getJumpDestInCurrentScope("return");
638f4a2713aSLionel Sambuc
639f4a2713aSLionel Sambuc Builder.SetInsertPoint(EntryBB);
640f4a2713aSLionel Sambuc
641f4a2713aSLionel Sambuc // Emit subprogram debug descriptor.
642f4a2713aSLionel Sambuc if (CGDebugInfo *DI = getDebugInfo()) {
643f4a2713aSLionel Sambuc SmallVector<QualType, 16> ArgTypes;
644f4a2713aSLionel Sambuc for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
645f4a2713aSLionel Sambuc i != e; ++i) {
646f4a2713aSLionel Sambuc ArgTypes.push_back((*i)->getType());
647f4a2713aSLionel Sambuc }
648f4a2713aSLionel Sambuc
649f4a2713aSLionel Sambuc QualType FnType =
650f4a2713aSLionel Sambuc getContext().getFunctionType(RetTy, ArgTypes,
651f4a2713aSLionel Sambuc FunctionProtoType::ExtProtoInfo());
652*0a6a1f1dSLionel Sambuc DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder);
653f4a2713aSLionel Sambuc }
654f4a2713aSLionel Sambuc
655f4a2713aSLionel Sambuc if (ShouldInstrumentFunction())
656f4a2713aSLionel Sambuc EmitFunctionInstrumentation("__cyg_profile_func_enter");
657f4a2713aSLionel Sambuc
658f4a2713aSLionel Sambuc if (CGM.getCodeGenOpts().InstrumentForProfiling)
659f4a2713aSLionel Sambuc EmitMCountInstrumentation();
660f4a2713aSLionel Sambuc
661f4a2713aSLionel Sambuc if (RetTy->isVoidType()) {
662f4a2713aSLionel Sambuc // Void type; nothing to return.
663*0a6a1f1dSLionel Sambuc ReturnValue = nullptr;
664*0a6a1f1dSLionel Sambuc
665*0a6a1f1dSLionel Sambuc // Count the implicit return.
666*0a6a1f1dSLionel Sambuc if (!endsWithReturn(D))
667*0a6a1f1dSLionel Sambuc ++NumReturnExprs;
668f4a2713aSLionel Sambuc } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
669f4a2713aSLionel Sambuc !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
670f4a2713aSLionel Sambuc // Indirect aggregate return; emit returned value directly into sret slot.
671f4a2713aSLionel Sambuc // This reduces code size, and affects correctness in C++.
672*0a6a1f1dSLionel Sambuc auto AI = CurFn->arg_begin();
673*0a6a1f1dSLionel Sambuc if (CurFnInfo->getReturnInfo().isSRetAfterThis())
674*0a6a1f1dSLionel Sambuc ++AI;
675*0a6a1f1dSLionel Sambuc ReturnValue = AI;
676*0a6a1f1dSLionel Sambuc } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
677*0a6a1f1dSLionel Sambuc !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
678*0a6a1f1dSLionel Sambuc // Load the sret pointer from the argument struct and return into that.
679*0a6a1f1dSLionel Sambuc unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
680*0a6a1f1dSLionel Sambuc llvm::Function::arg_iterator EI = CurFn->arg_end();
681*0a6a1f1dSLionel Sambuc --EI;
682*0a6a1f1dSLionel Sambuc llvm::Value *Addr = Builder.CreateStructGEP(EI, Idx);
683*0a6a1f1dSLionel Sambuc ReturnValue = Builder.CreateLoad(Addr, "agg.result");
684f4a2713aSLionel Sambuc } else {
685f4a2713aSLionel Sambuc ReturnValue = CreateIRTemp(RetTy, "retval");
686f4a2713aSLionel Sambuc
687f4a2713aSLionel Sambuc // Tell the epilog emitter to autorelease the result. We do this
688f4a2713aSLionel Sambuc // now so that various specialized functions can suppress it
689f4a2713aSLionel Sambuc // during their IR-generation.
690f4a2713aSLionel Sambuc if (getLangOpts().ObjCAutoRefCount &&
691f4a2713aSLionel Sambuc !CurFnInfo->isReturnsRetained() &&
692f4a2713aSLionel Sambuc RetTy->isObjCRetainableType())
693f4a2713aSLionel Sambuc AutoreleaseResult = true;
694f4a2713aSLionel Sambuc }
695f4a2713aSLionel Sambuc
696f4a2713aSLionel Sambuc EmitStartEHSpec(CurCodeDecl);
697f4a2713aSLionel Sambuc
698f4a2713aSLionel Sambuc PrologueCleanupDepth = EHStack.stable_begin();
699f4a2713aSLionel Sambuc EmitFunctionProlog(*CurFnInfo, CurFn, Args);
700f4a2713aSLionel Sambuc
701f4a2713aSLionel Sambuc if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
702f4a2713aSLionel Sambuc CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
703f4a2713aSLionel Sambuc const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
704f4a2713aSLionel Sambuc if (MD->getParent()->isLambda() &&
705f4a2713aSLionel Sambuc MD->getOverloadedOperator() == OO_Call) {
706f4a2713aSLionel Sambuc // We're in a lambda; figure out the captures.
707f4a2713aSLionel Sambuc MD->getParent()->getCaptureFields(LambdaCaptureFields,
708f4a2713aSLionel Sambuc LambdaThisCaptureField);
709f4a2713aSLionel Sambuc if (LambdaThisCaptureField) {
710f4a2713aSLionel Sambuc // If this lambda captures this, load it.
711f4a2713aSLionel Sambuc LValue ThisLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
712f4a2713aSLionel Sambuc CXXThisValue = EmitLoadOfLValue(ThisLValue,
713f4a2713aSLionel Sambuc SourceLocation()).getScalarVal();
714f4a2713aSLionel Sambuc }
715*0a6a1f1dSLionel Sambuc for (auto *FD : MD->getParent()->fields()) {
716*0a6a1f1dSLionel Sambuc if (FD->hasCapturedVLAType()) {
717*0a6a1f1dSLionel Sambuc auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
718*0a6a1f1dSLionel Sambuc SourceLocation()).getScalarVal();
719*0a6a1f1dSLionel Sambuc auto VAT = FD->getCapturedVLAType();
720*0a6a1f1dSLionel Sambuc VLASizeMap[VAT->getSizeExpr()] = ExprArg;
721*0a6a1f1dSLionel Sambuc }
722*0a6a1f1dSLionel Sambuc }
723f4a2713aSLionel Sambuc } else {
724f4a2713aSLionel Sambuc // Not in a lambda; just use 'this' from the method.
725f4a2713aSLionel Sambuc // FIXME: Should we generate a new load for each use of 'this'? The
726f4a2713aSLionel Sambuc // fast register allocator would be happier...
727f4a2713aSLionel Sambuc CXXThisValue = CXXABIThisValue;
728f4a2713aSLionel Sambuc }
729f4a2713aSLionel Sambuc }
730f4a2713aSLionel Sambuc
731f4a2713aSLionel Sambuc // If any of the arguments have a variably modified type, make sure to
732f4a2713aSLionel Sambuc // emit the type size.
733f4a2713aSLionel Sambuc for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
734f4a2713aSLionel Sambuc i != e; ++i) {
735f4a2713aSLionel Sambuc const VarDecl *VD = *i;
736f4a2713aSLionel Sambuc
737f4a2713aSLionel Sambuc // Dig out the type as written from ParmVarDecls; it's unclear whether
738f4a2713aSLionel Sambuc // the standard (C99 6.9.1p10) requires this, but we're following the
739f4a2713aSLionel Sambuc // precedent set by gcc.
740f4a2713aSLionel Sambuc QualType Ty;
741f4a2713aSLionel Sambuc if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
742f4a2713aSLionel Sambuc Ty = PVD->getOriginalType();
743f4a2713aSLionel Sambuc else
744f4a2713aSLionel Sambuc Ty = VD->getType();
745f4a2713aSLionel Sambuc
746f4a2713aSLionel Sambuc if (Ty->isVariablyModifiedType())
747f4a2713aSLionel Sambuc EmitVariablyModifiedType(Ty);
748f4a2713aSLionel Sambuc }
749f4a2713aSLionel Sambuc // Emit a location at the end of the prologue.
750f4a2713aSLionel Sambuc if (CGDebugInfo *DI = getDebugInfo())
751f4a2713aSLionel Sambuc DI->EmitLocation(Builder, StartLoc);
752f4a2713aSLionel Sambuc }
753f4a2713aSLionel Sambuc
EmitFunctionBody(FunctionArgList & Args,const Stmt * Body)754f4a2713aSLionel Sambuc void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
755f4a2713aSLionel Sambuc const Stmt *Body) {
756*0a6a1f1dSLionel Sambuc RegionCounter Cnt = getPGORegionCounter(Body);
757*0a6a1f1dSLionel Sambuc Cnt.beginRegion(Builder);
758f4a2713aSLionel Sambuc if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
759f4a2713aSLionel Sambuc EmitCompoundStmtWithoutScope(*S);
760f4a2713aSLionel Sambuc else
761f4a2713aSLionel Sambuc EmitStmt(Body);
762f4a2713aSLionel Sambuc }
763f4a2713aSLionel Sambuc
764*0a6a1f1dSLionel Sambuc /// When instrumenting to collect profile data, the counts for some blocks
765*0a6a1f1dSLionel Sambuc /// such as switch cases need to not include the fall-through counts, so
766*0a6a1f1dSLionel Sambuc /// emit a branch around the instrumentation code. When not instrumenting,
767*0a6a1f1dSLionel Sambuc /// this just calls EmitBlock().
EmitBlockWithFallThrough(llvm::BasicBlock * BB,RegionCounter & Cnt)768*0a6a1f1dSLionel Sambuc void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
769*0a6a1f1dSLionel Sambuc RegionCounter &Cnt) {
770*0a6a1f1dSLionel Sambuc llvm::BasicBlock *SkipCountBB = nullptr;
771*0a6a1f1dSLionel Sambuc if (HaveInsertPoint() && CGM.getCodeGenOpts().ProfileInstrGenerate) {
772*0a6a1f1dSLionel Sambuc // When instrumenting for profiling, the fallthrough to certain
773*0a6a1f1dSLionel Sambuc // statements needs to skip over the instrumentation code so that we
774*0a6a1f1dSLionel Sambuc // get an accurate count.
775*0a6a1f1dSLionel Sambuc SkipCountBB = createBasicBlock("skipcount");
776*0a6a1f1dSLionel Sambuc EmitBranch(SkipCountBB);
777*0a6a1f1dSLionel Sambuc }
778*0a6a1f1dSLionel Sambuc EmitBlock(BB);
779*0a6a1f1dSLionel Sambuc Cnt.beginRegion(Builder, /*AddIncomingFallThrough=*/true);
780*0a6a1f1dSLionel Sambuc if (SkipCountBB)
781*0a6a1f1dSLionel Sambuc EmitBlock(SkipCountBB);
782*0a6a1f1dSLionel Sambuc }
783*0a6a1f1dSLionel Sambuc
784f4a2713aSLionel Sambuc /// Tries to mark the given function nounwind based on the
785f4a2713aSLionel Sambuc /// non-existence of any throwing calls within it. We believe this is
786f4a2713aSLionel Sambuc /// lightweight enough to do at -O0.
TryMarkNoThrow(llvm::Function * F)787f4a2713aSLionel Sambuc static void TryMarkNoThrow(llvm::Function *F) {
788f4a2713aSLionel Sambuc // LLVM treats 'nounwind' on a function as part of the type, so we
789f4a2713aSLionel Sambuc // can't do this on functions that can be overwritten.
790f4a2713aSLionel Sambuc if (F->mayBeOverridden()) return;
791f4a2713aSLionel Sambuc
792f4a2713aSLionel Sambuc for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
793f4a2713aSLionel Sambuc for (llvm::BasicBlock::iterator
794f4a2713aSLionel Sambuc BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
795f4a2713aSLionel Sambuc if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) {
796f4a2713aSLionel Sambuc if (!Call->doesNotThrow())
797f4a2713aSLionel Sambuc return;
798f4a2713aSLionel Sambuc } else if (isa<llvm::ResumeInst>(&*BI)) {
799f4a2713aSLionel Sambuc return;
800f4a2713aSLionel Sambuc }
801f4a2713aSLionel Sambuc F->setDoesNotThrow();
802f4a2713aSLionel Sambuc }
803f4a2713aSLionel Sambuc
EmitSizedDeallocationFunction(CodeGenFunction & CGF,const FunctionDecl * UnsizedDealloc)804f4a2713aSLionel Sambuc static void EmitSizedDeallocationFunction(CodeGenFunction &CGF,
805f4a2713aSLionel Sambuc const FunctionDecl *UnsizedDealloc) {
806f4a2713aSLionel Sambuc // This is a weak discardable definition of the sized deallocation function.
807f4a2713aSLionel Sambuc CGF.CurFn->setLinkage(llvm::Function::LinkOnceAnyLinkage);
808f4a2713aSLionel Sambuc
809f4a2713aSLionel Sambuc // Call the unsized deallocation function and forward the first argument
810f4a2713aSLionel Sambuc // unchanged.
811f4a2713aSLionel Sambuc llvm::Constant *Unsized = CGF.CGM.GetAddrOfFunction(UnsizedDealloc);
812f4a2713aSLionel Sambuc CGF.Builder.CreateCall(Unsized, &*CGF.CurFn->arg_begin());
813f4a2713aSLionel Sambuc }
814f4a2713aSLionel Sambuc
GenerateCode(GlobalDecl GD,llvm::Function * Fn,const CGFunctionInfo & FnInfo)815f4a2713aSLionel Sambuc void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
816f4a2713aSLionel Sambuc const CGFunctionInfo &FnInfo) {
817f4a2713aSLionel Sambuc const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
818f4a2713aSLionel Sambuc
819f4a2713aSLionel Sambuc // Check if we should generate debug info for this function.
820f4a2713aSLionel Sambuc if (FD->hasAttr<NoDebugAttr>())
821*0a6a1f1dSLionel Sambuc DebugInfo = nullptr; // disable debug info indefinitely for this function
822f4a2713aSLionel Sambuc
823f4a2713aSLionel Sambuc FunctionArgList Args;
824*0a6a1f1dSLionel Sambuc QualType ResTy = FD->getReturnType();
825f4a2713aSLionel Sambuc
826f4a2713aSLionel Sambuc CurGD = GD;
827*0a6a1f1dSLionel Sambuc const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
828*0a6a1f1dSLionel Sambuc if (MD && MD->isInstance()) {
829f4a2713aSLionel Sambuc if (CGM.getCXXABI().HasThisReturn(GD))
830f4a2713aSLionel Sambuc ResTy = MD->getThisType(getContext());
831*0a6a1f1dSLionel Sambuc else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
832*0a6a1f1dSLionel Sambuc ResTy = CGM.getContext().VoidPtrTy;
833*0a6a1f1dSLionel Sambuc CGM.getCXXABI().buildThisParam(*this, Args);
834f4a2713aSLionel Sambuc }
835f4a2713aSLionel Sambuc
836*0a6a1f1dSLionel Sambuc Args.append(FD->param_begin(), FD->param_end());
837*0a6a1f1dSLionel Sambuc
838*0a6a1f1dSLionel Sambuc if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
839*0a6a1f1dSLionel Sambuc CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
840f4a2713aSLionel Sambuc
841f4a2713aSLionel Sambuc SourceRange BodyRange;
842f4a2713aSLionel Sambuc if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
843f4a2713aSLionel Sambuc CurEHLocation = BodyRange.getEnd();
844f4a2713aSLionel Sambuc
845*0a6a1f1dSLionel Sambuc // Use the location of the start of the function to determine where
846*0a6a1f1dSLionel Sambuc // the function definition is located. By default use the location
847*0a6a1f1dSLionel Sambuc // of the declaration as the location for the subprogram. A function
848*0a6a1f1dSLionel Sambuc // may lack a declaration in the source code if it is created by code
849*0a6a1f1dSLionel Sambuc // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
850*0a6a1f1dSLionel Sambuc SourceLocation Loc = FD->getLocation();
851*0a6a1f1dSLionel Sambuc
852*0a6a1f1dSLionel Sambuc // If this is a function specialization then use the pattern body
853*0a6a1f1dSLionel Sambuc // as the location for the function.
854*0a6a1f1dSLionel Sambuc if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
855*0a6a1f1dSLionel Sambuc if (SpecDecl->hasBody(SpecDecl))
856*0a6a1f1dSLionel Sambuc Loc = SpecDecl->getLocation();
857*0a6a1f1dSLionel Sambuc
858f4a2713aSLionel Sambuc // Emit the standard function prologue.
859*0a6a1f1dSLionel Sambuc StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
860f4a2713aSLionel Sambuc
861f4a2713aSLionel Sambuc // Generate the body of the function.
862*0a6a1f1dSLionel Sambuc PGO.checkGlobalDecl(GD);
863*0a6a1f1dSLionel Sambuc PGO.assignRegionCounters(GD.getDecl(), CurFn);
864f4a2713aSLionel Sambuc if (isa<CXXDestructorDecl>(FD))
865f4a2713aSLionel Sambuc EmitDestructorBody(Args);
866f4a2713aSLionel Sambuc else if (isa<CXXConstructorDecl>(FD))
867f4a2713aSLionel Sambuc EmitConstructorBody(Args);
868f4a2713aSLionel Sambuc else if (getLangOpts().CUDA &&
869f4a2713aSLionel Sambuc !CGM.getCodeGenOpts().CUDAIsDevice &&
870f4a2713aSLionel Sambuc FD->hasAttr<CUDAGlobalAttr>())
871f4a2713aSLionel Sambuc CGM.getCUDARuntime().EmitDeviceStubBody(*this, Args);
872f4a2713aSLionel Sambuc else if (isa<CXXConversionDecl>(FD) &&
873f4a2713aSLionel Sambuc cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
874f4a2713aSLionel Sambuc // The lambda conversion to block pointer is special; the semantics can't be
875f4a2713aSLionel Sambuc // expressed in the AST, so IRGen needs to special-case it.
876f4a2713aSLionel Sambuc EmitLambdaToBlockPointerBody(Args);
877f4a2713aSLionel Sambuc } else if (isa<CXXMethodDecl>(FD) &&
878f4a2713aSLionel Sambuc cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
879f4a2713aSLionel Sambuc // The lambda static invoker function is special, because it forwards or
880f4a2713aSLionel Sambuc // clones the body of the function call operator (but is actually static).
881f4a2713aSLionel Sambuc EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
882f4a2713aSLionel Sambuc } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
883f4a2713aSLionel Sambuc (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
884f4a2713aSLionel Sambuc cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
885f4a2713aSLionel Sambuc // Implicit copy-assignment gets the same special treatment as implicit
886f4a2713aSLionel Sambuc // copy-constructors.
887f4a2713aSLionel Sambuc emitImplicitAssignmentOperatorBody(Args);
888f4a2713aSLionel Sambuc } else if (Stmt *Body = FD->getBody()) {
889f4a2713aSLionel Sambuc EmitFunctionBody(Args, Body);
890f4a2713aSLionel Sambuc } else if (FunctionDecl *UnsizedDealloc =
891f4a2713aSLionel Sambuc FD->getCorrespondingUnsizedGlobalDeallocationFunction()) {
892f4a2713aSLionel Sambuc // Global sized deallocation functions get an implicit weak definition if
893f4a2713aSLionel Sambuc // they don't have an explicit definition.
894f4a2713aSLionel Sambuc EmitSizedDeallocationFunction(*this, UnsizedDealloc);
895f4a2713aSLionel Sambuc } else
896f4a2713aSLionel Sambuc llvm_unreachable("no definition for emitted function");
897f4a2713aSLionel Sambuc
898f4a2713aSLionel Sambuc // C++11 [stmt.return]p2:
899f4a2713aSLionel Sambuc // Flowing off the end of a function [...] results in undefined behavior in
900f4a2713aSLionel Sambuc // a value-returning function.
901f4a2713aSLionel Sambuc // C11 6.9.1p12:
902f4a2713aSLionel Sambuc // If the '}' that terminates a function is reached, and the value of the
903f4a2713aSLionel Sambuc // function call is used by the caller, the behavior is undefined.
904*0a6a1f1dSLionel Sambuc if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
905*0a6a1f1dSLionel Sambuc !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
906*0a6a1f1dSLionel Sambuc if (SanOpts.has(SanitizerKind::Return)) {
907*0a6a1f1dSLionel Sambuc SanitizerScope SanScope(this);
908*0a6a1f1dSLionel Sambuc llvm::Value *IsFalse = Builder.getFalse();
909*0a6a1f1dSLionel Sambuc EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
910*0a6a1f1dSLionel Sambuc "missing_return", EmitCheckSourceLocation(FD->getLocation()),
911*0a6a1f1dSLionel Sambuc None);
912*0a6a1f1dSLionel Sambuc } else if (CGM.getCodeGenOpts().OptimizationLevel == 0)
913f4a2713aSLionel Sambuc Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::trap));
914f4a2713aSLionel Sambuc Builder.CreateUnreachable();
915f4a2713aSLionel Sambuc Builder.ClearInsertionPoint();
916f4a2713aSLionel Sambuc }
917f4a2713aSLionel Sambuc
918f4a2713aSLionel Sambuc // Emit the standard function epilogue.
919f4a2713aSLionel Sambuc FinishFunction(BodyRange.getEnd());
920f4a2713aSLionel Sambuc
921f4a2713aSLionel Sambuc // If we haven't marked the function nothrow through other means, do
922f4a2713aSLionel Sambuc // a quick pass now to see if we can.
923f4a2713aSLionel Sambuc if (!CurFn->doesNotThrow())
924f4a2713aSLionel Sambuc TryMarkNoThrow(CurFn);
925f4a2713aSLionel Sambuc }
926f4a2713aSLionel Sambuc
927f4a2713aSLionel Sambuc /// ContainsLabel - Return true if the statement contains a label in it. If
928f4a2713aSLionel Sambuc /// this statement is not executed normally, it not containing a label means
929f4a2713aSLionel Sambuc /// that we can just remove the code.
ContainsLabel(const Stmt * S,bool IgnoreCaseStmts)930f4a2713aSLionel Sambuc bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
931f4a2713aSLionel Sambuc // Null statement, not a label!
932*0a6a1f1dSLionel Sambuc if (!S) return false;
933f4a2713aSLionel Sambuc
934f4a2713aSLionel Sambuc // If this is a label, we have to emit the code, consider something like:
935f4a2713aSLionel Sambuc // if (0) { ... foo: bar(); } goto foo;
936f4a2713aSLionel Sambuc //
937f4a2713aSLionel Sambuc // TODO: If anyone cared, we could track __label__'s, since we know that you
938f4a2713aSLionel Sambuc // can't jump to one from outside their declared region.
939f4a2713aSLionel Sambuc if (isa<LabelStmt>(S))
940f4a2713aSLionel Sambuc return true;
941f4a2713aSLionel Sambuc
942f4a2713aSLionel Sambuc // If this is a case/default statement, and we haven't seen a switch, we have
943f4a2713aSLionel Sambuc // to emit the code.
944f4a2713aSLionel Sambuc if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
945f4a2713aSLionel Sambuc return true;
946f4a2713aSLionel Sambuc
947f4a2713aSLionel Sambuc // If this is a switch statement, we want to ignore cases below it.
948f4a2713aSLionel Sambuc if (isa<SwitchStmt>(S))
949f4a2713aSLionel Sambuc IgnoreCaseStmts = true;
950f4a2713aSLionel Sambuc
951f4a2713aSLionel Sambuc // Scan subexpressions for verboten labels.
952f4a2713aSLionel Sambuc for (Stmt::const_child_range I = S->children(); I; ++I)
953f4a2713aSLionel Sambuc if (ContainsLabel(*I, IgnoreCaseStmts))
954f4a2713aSLionel Sambuc return true;
955f4a2713aSLionel Sambuc
956f4a2713aSLionel Sambuc return false;
957f4a2713aSLionel Sambuc }
958f4a2713aSLionel Sambuc
959f4a2713aSLionel Sambuc /// containsBreak - Return true if the statement contains a break out of it.
960f4a2713aSLionel Sambuc /// If the statement (recursively) contains a switch or loop with a break
961f4a2713aSLionel Sambuc /// inside of it, this is fine.
containsBreak(const Stmt * S)962f4a2713aSLionel Sambuc bool CodeGenFunction::containsBreak(const Stmt *S) {
963f4a2713aSLionel Sambuc // Null statement, not a label!
964*0a6a1f1dSLionel Sambuc if (!S) return false;
965f4a2713aSLionel Sambuc
966f4a2713aSLionel Sambuc // If this is a switch or loop that defines its own break scope, then we can
967f4a2713aSLionel Sambuc // include it and anything inside of it.
968f4a2713aSLionel Sambuc if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
969f4a2713aSLionel Sambuc isa<ForStmt>(S))
970f4a2713aSLionel Sambuc return false;
971f4a2713aSLionel Sambuc
972f4a2713aSLionel Sambuc if (isa<BreakStmt>(S))
973f4a2713aSLionel Sambuc return true;
974f4a2713aSLionel Sambuc
975f4a2713aSLionel Sambuc // Scan subexpressions for verboten breaks.
976f4a2713aSLionel Sambuc for (Stmt::const_child_range I = S->children(); I; ++I)
977f4a2713aSLionel Sambuc if (containsBreak(*I))
978f4a2713aSLionel Sambuc return true;
979f4a2713aSLionel Sambuc
980f4a2713aSLionel Sambuc return false;
981f4a2713aSLionel Sambuc }
982f4a2713aSLionel Sambuc
983f4a2713aSLionel Sambuc
984f4a2713aSLionel Sambuc /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
985f4a2713aSLionel Sambuc /// to a constant, or if it does but contains a label, return false. If it
986f4a2713aSLionel Sambuc /// constant folds return true and set the boolean result in Result.
ConstantFoldsToSimpleInteger(const Expr * Cond,bool & ResultBool)987f4a2713aSLionel Sambuc bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
988f4a2713aSLionel Sambuc bool &ResultBool) {
989f4a2713aSLionel Sambuc llvm::APSInt ResultInt;
990f4a2713aSLionel Sambuc if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
991f4a2713aSLionel Sambuc return false;
992f4a2713aSLionel Sambuc
993f4a2713aSLionel Sambuc ResultBool = ResultInt.getBoolValue();
994f4a2713aSLionel Sambuc return true;
995f4a2713aSLionel Sambuc }
996f4a2713aSLionel Sambuc
997f4a2713aSLionel Sambuc /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
998f4a2713aSLionel Sambuc /// to a constant, or if it does but contains a label, return false. If it
999f4a2713aSLionel Sambuc /// constant folds return true and set the folded value.
1000f4a2713aSLionel Sambuc bool CodeGenFunction::
ConstantFoldsToSimpleInteger(const Expr * Cond,llvm::APSInt & ResultInt)1001f4a2713aSLionel Sambuc ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &ResultInt) {
1002f4a2713aSLionel Sambuc // FIXME: Rename and handle conversion of other evaluatable things
1003f4a2713aSLionel Sambuc // to bool.
1004f4a2713aSLionel Sambuc llvm::APSInt Int;
1005f4a2713aSLionel Sambuc if (!Cond->EvaluateAsInt(Int, getContext()))
1006f4a2713aSLionel Sambuc return false; // Not foldable, not integer or not fully evaluatable.
1007f4a2713aSLionel Sambuc
1008f4a2713aSLionel Sambuc if (CodeGenFunction::ContainsLabel(Cond))
1009f4a2713aSLionel Sambuc return false; // Contains a label.
1010f4a2713aSLionel Sambuc
1011f4a2713aSLionel Sambuc ResultInt = Int;
1012f4a2713aSLionel Sambuc return true;
1013f4a2713aSLionel Sambuc }
1014f4a2713aSLionel Sambuc
1015f4a2713aSLionel Sambuc
1016f4a2713aSLionel Sambuc
1017f4a2713aSLionel Sambuc /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1018f4a2713aSLionel Sambuc /// statement) to the specified blocks. Based on the condition, this might try
1019f4a2713aSLionel Sambuc /// to simplify the codegen of the conditional based on the branch.
1020f4a2713aSLionel Sambuc ///
EmitBranchOnBoolExpr(const Expr * Cond,llvm::BasicBlock * TrueBlock,llvm::BasicBlock * FalseBlock,uint64_t TrueCount)1021f4a2713aSLionel Sambuc void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1022f4a2713aSLionel Sambuc llvm::BasicBlock *TrueBlock,
1023*0a6a1f1dSLionel Sambuc llvm::BasicBlock *FalseBlock,
1024*0a6a1f1dSLionel Sambuc uint64_t TrueCount) {
1025f4a2713aSLionel Sambuc Cond = Cond->IgnoreParens();
1026f4a2713aSLionel Sambuc
1027f4a2713aSLionel Sambuc if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1028*0a6a1f1dSLionel Sambuc
1029f4a2713aSLionel Sambuc // Handle X && Y in a condition.
1030f4a2713aSLionel Sambuc if (CondBOp->getOpcode() == BO_LAnd) {
1031*0a6a1f1dSLionel Sambuc RegionCounter Cnt = getPGORegionCounter(CondBOp);
1032*0a6a1f1dSLionel Sambuc
1033f4a2713aSLionel Sambuc // If we have "1 && X", simplify the code. "0 && X" would have constant
1034f4a2713aSLionel Sambuc // folded if the case was simple enough.
1035f4a2713aSLionel Sambuc bool ConstantBool = false;
1036f4a2713aSLionel Sambuc if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1037f4a2713aSLionel Sambuc ConstantBool) {
1038f4a2713aSLionel Sambuc // br(1 && X) -> br(X).
1039*0a6a1f1dSLionel Sambuc Cnt.beginRegion(Builder);
1040*0a6a1f1dSLionel Sambuc return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1041*0a6a1f1dSLionel Sambuc TrueCount);
1042f4a2713aSLionel Sambuc }
1043f4a2713aSLionel Sambuc
1044f4a2713aSLionel Sambuc // If we have "X && 1", simplify the code to use an uncond branch.
1045f4a2713aSLionel Sambuc // "X && 0" would have been constant folded to 0.
1046f4a2713aSLionel Sambuc if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1047f4a2713aSLionel Sambuc ConstantBool) {
1048f4a2713aSLionel Sambuc // br(X && 1) -> br(X).
1049*0a6a1f1dSLionel Sambuc return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1050*0a6a1f1dSLionel Sambuc TrueCount);
1051f4a2713aSLionel Sambuc }
1052f4a2713aSLionel Sambuc
1053f4a2713aSLionel Sambuc // Emit the LHS as a conditional. If the LHS conditional is false, we
1054f4a2713aSLionel Sambuc // want to jump to the FalseBlock.
1055f4a2713aSLionel Sambuc llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1056*0a6a1f1dSLionel Sambuc // The counter tells us how often we evaluate RHS, and all of TrueCount
1057*0a6a1f1dSLionel Sambuc // can be propagated to that branch.
1058*0a6a1f1dSLionel Sambuc uint64_t RHSCount = Cnt.getCount();
1059f4a2713aSLionel Sambuc
1060f4a2713aSLionel Sambuc ConditionalEvaluation eval(*this);
1061*0a6a1f1dSLionel Sambuc EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
1062f4a2713aSLionel Sambuc EmitBlock(LHSTrue);
1063f4a2713aSLionel Sambuc
1064f4a2713aSLionel Sambuc // Any temporaries created here are conditional.
1065*0a6a1f1dSLionel Sambuc Cnt.beginRegion(Builder);
1066f4a2713aSLionel Sambuc eval.begin(*this);
1067*0a6a1f1dSLionel Sambuc EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
1068f4a2713aSLionel Sambuc eval.end(*this);
1069f4a2713aSLionel Sambuc
1070f4a2713aSLionel Sambuc return;
1071f4a2713aSLionel Sambuc }
1072f4a2713aSLionel Sambuc
1073f4a2713aSLionel Sambuc if (CondBOp->getOpcode() == BO_LOr) {
1074*0a6a1f1dSLionel Sambuc RegionCounter Cnt = getPGORegionCounter(CondBOp);
1075*0a6a1f1dSLionel Sambuc
1076f4a2713aSLionel Sambuc // If we have "0 || X", simplify the code. "1 || X" would have constant
1077f4a2713aSLionel Sambuc // folded if the case was simple enough.
1078f4a2713aSLionel Sambuc bool ConstantBool = false;
1079f4a2713aSLionel Sambuc if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1080f4a2713aSLionel Sambuc !ConstantBool) {
1081f4a2713aSLionel Sambuc // br(0 || X) -> br(X).
1082*0a6a1f1dSLionel Sambuc Cnt.beginRegion(Builder);
1083*0a6a1f1dSLionel Sambuc return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1084*0a6a1f1dSLionel Sambuc TrueCount);
1085f4a2713aSLionel Sambuc }
1086f4a2713aSLionel Sambuc
1087f4a2713aSLionel Sambuc // If we have "X || 0", simplify the code to use an uncond branch.
1088f4a2713aSLionel Sambuc // "X || 1" would have been constant folded to 1.
1089f4a2713aSLionel Sambuc if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1090f4a2713aSLionel Sambuc !ConstantBool) {
1091f4a2713aSLionel Sambuc // br(X || 0) -> br(X).
1092*0a6a1f1dSLionel Sambuc return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1093*0a6a1f1dSLionel Sambuc TrueCount);
1094f4a2713aSLionel Sambuc }
1095f4a2713aSLionel Sambuc
1096f4a2713aSLionel Sambuc // Emit the LHS as a conditional. If the LHS conditional is true, we
1097f4a2713aSLionel Sambuc // want to jump to the TrueBlock.
1098f4a2713aSLionel Sambuc llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
1099*0a6a1f1dSLionel Sambuc // We have the count for entry to the RHS and for the whole expression
1100*0a6a1f1dSLionel Sambuc // being true, so we can divy up True count between the short circuit and
1101*0a6a1f1dSLionel Sambuc // the RHS.
1102*0a6a1f1dSLionel Sambuc uint64_t LHSCount = Cnt.getParentCount() - Cnt.getCount();
1103*0a6a1f1dSLionel Sambuc uint64_t RHSCount = TrueCount - LHSCount;
1104f4a2713aSLionel Sambuc
1105f4a2713aSLionel Sambuc ConditionalEvaluation eval(*this);
1106*0a6a1f1dSLionel Sambuc EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
1107f4a2713aSLionel Sambuc EmitBlock(LHSFalse);
1108f4a2713aSLionel Sambuc
1109f4a2713aSLionel Sambuc // Any temporaries created here are conditional.
1110*0a6a1f1dSLionel Sambuc Cnt.beginRegion(Builder);
1111f4a2713aSLionel Sambuc eval.begin(*this);
1112*0a6a1f1dSLionel Sambuc EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
1113*0a6a1f1dSLionel Sambuc
1114f4a2713aSLionel Sambuc eval.end(*this);
1115f4a2713aSLionel Sambuc
1116f4a2713aSLionel Sambuc return;
1117f4a2713aSLionel Sambuc }
1118f4a2713aSLionel Sambuc }
1119f4a2713aSLionel Sambuc
1120f4a2713aSLionel Sambuc if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1121f4a2713aSLionel Sambuc // br(!x, t, f) -> br(x, f, t)
1122*0a6a1f1dSLionel Sambuc if (CondUOp->getOpcode() == UO_LNot) {
1123*0a6a1f1dSLionel Sambuc // Negate the count.
1124*0a6a1f1dSLionel Sambuc uint64_t FalseCount = PGO.getCurrentRegionCount() - TrueCount;
1125*0a6a1f1dSLionel Sambuc // Negate the condition and swap the destination blocks.
1126*0a6a1f1dSLionel Sambuc return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1127*0a6a1f1dSLionel Sambuc FalseCount);
1128*0a6a1f1dSLionel Sambuc }
1129f4a2713aSLionel Sambuc }
1130f4a2713aSLionel Sambuc
1131f4a2713aSLionel Sambuc if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1132f4a2713aSLionel Sambuc // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1133f4a2713aSLionel Sambuc llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1134f4a2713aSLionel Sambuc llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1135f4a2713aSLionel Sambuc
1136*0a6a1f1dSLionel Sambuc RegionCounter Cnt = getPGORegionCounter(CondOp);
1137f4a2713aSLionel Sambuc ConditionalEvaluation cond(*this);
1138*0a6a1f1dSLionel Sambuc EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock, Cnt.getCount());
1139*0a6a1f1dSLionel Sambuc
1140*0a6a1f1dSLionel Sambuc // When computing PGO branch weights, we only know the overall count for
1141*0a6a1f1dSLionel Sambuc // the true block. This code is essentially doing tail duplication of the
1142*0a6a1f1dSLionel Sambuc // naive code-gen, introducing new edges for which counts are not
1143*0a6a1f1dSLionel Sambuc // available. Divide the counts proportionally between the LHS and RHS of
1144*0a6a1f1dSLionel Sambuc // the conditional operator.
1145*0a6a1f1dSLionel Sambuc uint64_t LHSScaledTrueCount = 0;
1146*0a6a1f1dSLionel Sambuc if (TrueCount) {
1147*0a6a1f1dSLionel Sambuc double LHSRatio = Cnt.getCount() / (double) Cnt.getParentCount();
1148*0a6a1f1dSLionel Sambuc LHSScaledTrueCount = TrueCount * LHSRatio;
1149*0a6a1f1dSLionel Sambuc }
1150f4a2713aSLionel Sambuc
1151f4a2713aSLionel Sambuc cond.begin(*this);
1152f4a2713aSLionel Sambuc EmitBlock(LHSBlock);
1153*0a6a1f1dSLionel Sambuc Cnt.beginRegion(Builder);
1154*0a6a1f1dSLionel Sambuc EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
1155*0a6a1f1dSLionel Sambuc LHSScaledTrueCount);
1156f4a2713aSLionel Sambuc cond.end(*this);
1157f4a2713aSLionel Sambuc
1158f4a2713aSLionel Sambuc cond.begin(*this);
1159f4a2713aSLionel Sambuc EmitBlock(RHSBlock);
1160*0a6a1f1dSLionel Sambuc EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
1161*0a6a1f1dSLionel Sambuc TrueCount - LHSScaledTrueCount);
1162f4a2713aSLionel Sambuc cond.end(*this);
1163f4a2713aSLionel Sambuc
1164f4a2713aSLionel Sambuc return;
1165f4a2713aSLionel Sambuc }
1166f4a2713aSLionel Sambuc
1167f4a2713aSLionel Sambuc if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1168f4a2713aSLionel Sambuc // Conditional operator handling can give us a throw expression as a
1169f4a2713aSLionel Sambuc // condition for a case like:
1170f4a2713aSLionel Sambuc // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1171f4a2713aSLionel Sambuc // Fold this to:
1172f4a2713aSLionel Sambuc // br(c, throw x, br(y, t, f))
1173f4a2713aSLionel Sambuc EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1174f4a2713aSLionel Sambuc return;
1175f4a2713aSLionel Sambuc }
1176f4a2713aSLionel Sambuc
1177*0a6a1f1dSLionel Sambuc // Create branch weights based on the number of times we get here and the
1178*0a6a1f1dSLionel Sambuc // number of times the condition should be true.
1179*0a6a1f1dSLionel Sambuc uint64_t CurrentCount = std::max(PGO.getCurrentRegionCount(), TrueCount);
1180*0a6a1f1dSLionel Sambuc llvm::MDNode *Weights = PGO.createBranchWeights(TrueCount,
1181*0a6a1f1dSLionel Sambuc CurrentCount - TrueCount);
1182*0a6a1f1dSLionel Sambuc
1183f4a2713aSLionel Sambuc // Emit the code with the fully general case.
1184f4a2713aSLionel Sambuc llvm::Value *CondV = EvaluateExprAsBool(Cond);
1185*0a6a1f1dSLionel Sambuc Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights);
1186f4a2713aSLionel Sambuc }
1187f4a2713aSLionel Sambuc
1188f4a2713aSLionel Sambuc /// ErrorUnsupported - Print out an error that codegen doesn't support the
1189f4a2713aSLionel Sambuc /// specified stmt yet.
ErrorUnsupported(const Stmt * S,const char * Type)1190f4a2713aSLionel Sambuc void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1191f4a2713aSLionel Sambuc CGM.ErrorUnsupported(S, Type);
1192f4a2713aSLionel Sambuc }
1193f4a2713aSLionel Sambuc
1194f4a2713aSLionel Sambuc /// emitNonZeroVLAInit - Emit the "zero" initialization of a
1195f4a2713aSLionel Sambuc /// variable-length array whose elements have a non-zero bit-pattern.
1196f4a2713aSLionel Sambuc ///
1197f4a2713aSLionel Sambuc /// \param baseType the inner-most element type of the array
1198f4a2713aSLionel Sambuc /// \param src - a char* pointing to the bit-pattern for a single
1199f4a2713aSLionel Sambuc /// base element of the array
1200f4a2713aSLionel Sambuc /// \param sizeInChars - the total size of the VLA, in chars
emitNonZeroVLAInit(CodeGenFunction & CGF,QualType baseType,llvm::Value * dest,llvm::Value * src,llvm::Value * sizeInChars)1201f4a2713aSLionel Sambuc static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
1202f4a2713aSLionel Sambuc llvm::Value *dest, llvm::Value *src,
1203f4a2713aSLionel Sambuc llvm::Value *sizeInChars) {
1204f4a2713aSLionel Sambuc std::pair<CharUnits,CharUnits> baseSizeAndAlign
1205f4a2713aSLionel Sambuc = CGF.getContext().getTypeInfoInChars(baseType);
1206f4a2713aSLionel Sambuc
1207f4a2713aSLionel Sambuc CGBuilderTy &Builder = CGF.Builder;
1208f4a2713aSLionel Sambuc
1209f4a2713aSLionel Sambuc llvm::Value *baseSizeInChars
1210f4a2713aSLionel Sambuc = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
1211f4a2713aSLionel Sambuc
1212f4a2713aSLionel Sambuc llvm::Type *i8p = Builder.getInt8PtrTy();
1213f4a2713aSLionel Sambuc
1214f4a2713aSLionel Sambuc llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
1215f4a2713aSLionel Sambuc llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
1216f4a2713aSLionel Sambuc
1217f4a2713aSLionel Sambuc llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
1218f4a2713aSLionel Sambuc llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
1219f4a2713aSLionel Sambuc llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
1220f4a2713aSLionel Sambuc
1221f4a2713aSLionel Sambuc // Make a loop over the VLA. C99 guarantees that the VLA element
1222f4a2713aSLionel Sambuc // count must be nonzero.
1223f4a2713aSLionel Sambuc CGF.EmitBlock(loopBB);
1224f4a2713aSLionel Sambuc
1225f4a2713aSLionel Sambuc llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur");
1226f4a2713aSLionel Sambuc cur->addIncoming(begin, originBB);
1227f4a2713aSLionel Sambuc
1228f4a2713aSLionel Sambuc // memcpy the individual element bit-pattern.
1229f4a2713aSLionel Sambuc Builder.CreateMemCpy(cur, src, baseSizeInChars,
1230f4a2713aSLionel Sambuc baseSizeAndAlign.second.getQuantity(),
1231f4a2713aSLionel Sambuc /*volatile*/ false);
1232f4a2713aSLionel Sambuc
1233f4a2713aSLionel Sambuc // Go to the next element.
1234f4a2713aSLionel Sambuc llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next");
1235f4a2713aSLionel Sambuc
1236f4a2713aSLionel Sambuc // Leave if that's the end of the VLA.
1237f4a2713aSLionel Sambuc llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
1238f4a2713aSLionel Sambuc Builder.CreateCondBr(done, contBB, loopBB);
1239f4a2713aSLionel Sambuc cur->addIncoming(next, loopBB);
1240f4a2713aSLionel Sambuc
1241f4a2713aSLionel Sambuc CGF.EmitBlock(contBB);
1242f4a2713aSLionel Sambuc }
1243f4a2713aSLionel Sambuc
1244f4a2713aSLionel Sambuc void
EmitNullInitialization(llvm::Value * DestPtr,QualType Ty)1245f4a2713aSLionel Sambuc CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
1246f4a2713aSLionel Sambuc // Ignore empty classes in C++.
1247f4a2713aSLionel Sambuc if (getLangOpts().CPlusPlus) {
1248f4a2713aSLionel Sambuc if (const RecordType *RT = Ty->getAs<RecordType>()) {
1249f4a2713aSLionel Sambuc if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1250f4a2713aSLionel Sambuc return;
1251f4a2713aSLionel Sambuc }
1252f4a2713aSLionel Sambuc }
1253f4a2713aSLionel Sambuc
1254f4a2713aSLionel Sambuc // Cast the dest ptr to the appropriate i8 pointer type.
1255f4a2713aSLionel Sambuc unsigned DestAS =
1256f4a2713aSLionel Sambuc cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
1257f4a2713aSLionel Sambuc llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
1258f4a2713aSLionel Sambuc if (DestPtr->getType() != BP)
1259f4a2713aSLionel Sambuc DestPtr = Builder.CreateBitCast(DestPtr, BP);
1260f4a2713aSLionel Sambuc
1261f4a2713aSLionel Sambuc // Get size and alignment info for this aggregate.
1262f4a2713aSLionel Sambuc std::pair<CharUnits, CharUnits> TypeInfo =
1263f4a2713aSLionel Sambuc getContext().getTypeInfoInChars(Ty);
1264f4a2713aSLionel Sambuc CharUnits Size = TypeInfo.first;
1265f4a2713aSLionel Sambuc CharUnits Align = TypeInfo.second;
1266f4a2713aSLionel Sambuc
1267f4a2713aSLionel Sambuc llvm::Value *SizeVal;
1268f4a2713aSLionel Sambuc const VariableArrayType *vla;
1269f4a2713aSLionel Sambuc
1270f4a2713aSLionel Sambuc // Don't bother emitting a zero-byte memset.
1271f4a2713aSLionel Sambuc if (Size.isZero()) {
1272f4a2713aSLionel Sambuc // But note that getTypeInfo returns 0 for a VLA.
1273f4a2713aSLionel Sambuc if (const VariableArrayType *vlaType =
1274f4a2713aSLionel Sambuc dyn_cast_or_null<VariableArrayType>(
1275f4a2713aSLionel Sambuc getContext().getAsArrayType(Ty))) {
1276f4a2713aSLionel Sambuc QualType eltType;
1277f4a2713aSLionel Sambuc llvm::Value *numElts;
1278*0a6a1f1dSLionel Sambuc std::tie(numElts, eltType) = getVLASize(vlaType);
1279f4a2713aSLionel Sambuc
1280f4a2713aSLionel Sambuc SizeVal = numElts;
1281f4a2713aSLionel Sambuc CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
1282f4a2713aSLionel Sambuc if (!eltSize.isOne())
1283f4a2713aSLionel Sambuc SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
1284f4a2713aSLionel Sambuc vla = vlaType;
1285f4a2713aSLionel Sambuc } else {
1286f4a2713aSLionel Sambuc return;
1287f4a2713aSLionel Sambuc }
1288f4a2713aSLionel Sambuc } else {
1289f4a2713aSLionel Sambuc SizeVal = CGM.getSize(Size);
1290*0a6a1f1dSLionel Sambuc vla = nullptr;
1291f4a2713aSLionel Sambuc }
1292f4a2713aSLionel Sambuc
1293f4a2713aSLionel Sambuc // If the type contains a pointer to data member we can't memset it to zero.
1294f4a2713aSLionel Sambuc // Instead, create a null constant and copy it to the destination.
1295f4a2713aSLionel Sambuc // TODO: there are other patterns besides zero that we can usefully memset,
1296f4a2713aSLionel Sambuc // like -1, which happens to be the pattern used by member-pointers.
1297f4a2713aSLionel Sambuc if (!CGM.getTypes().isZeroInitializable(Ty)) {
1298f4a2713aSLionel Sambuc // For a VLA, emit a single element, then splat that over the VLA.
1299f4a2713aSLionel Sambuc if (vla) Ty = getContext().getBaseElementType(vla);
1300f4a2713aSLionel Sambuc
1301f4a2713aSLionel Sambuc llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1302f4a2713aSLionel Sambuc
1303f4a2713aSLionel Sambuc llvm::GlobalVariable *NullVariable =
1304f4a2713aSLionel Sambuc new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1305f4a2713aSLionel Sambuc /*isConstant=*/true,
1306f4a2713aSLionel Sambuc llvm::GlobalVariable::PrivateLinkage,
1307f4a2713aSLionel Sambuc NullConstant, Twine());
1308f4a2713aSLionel Sambuc llvm::Value *SrcPtr =
1309f4a2713aSLionel Sambuc Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
1310f4a2713aSLionel Sambuc
1311f4a2713aSLionel Sambuc if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1312f4a2713aSLionel Sambuc
1313f4a2713aSLionel Sambuc // Get and call the appropriate llvm.memcpy overload.
1314f4a2713aSLionel Sambuc Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false);
1315f4a2713aSLionel Sambuc return;
1316f4a2713aSLionel Sambuc }
1317f4a2713aSLionel Sambuc
1318f4a2713aSLionel Sambuc // Otherwise, just memset the whole thing to zero. This is legal
1319f4a2713aSLionel Sambuc // because in LLVM, all default initializers (other than the ones we just
1320f4a2713aSLionel Sambuc // handled above) are guaranteed to have a bit pattern of all zeros.
1321f4a2713aSLionel Sambuc Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal,
1322f4a2713aSLionel Sambuc Align.getQuantity(), false);
1323f4a2713aSLionel Sambuc }
1324f4a2713aSLionel Sambuc
GetAddrOfLabel(const LabelDecl * L)1325f4a2713aSLionel Sambuc llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
1326f4a2713aSLionel Sambuc // Make sure that there is a block for the indirect goto.
1327*0a6a1f1dSLionel Sambuc if (!IndirectBranch)
1328f4a2713aSLionel Sambuc GetIndirectGotoBlock();
1329f4a2713aSLionel Sambuc
1330f4a2713aSLionel Sambuc llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
1331f4a2713aSLionel Sambuc
1332f4a2713aSLionel Sambuc // Make sure the indirect branch includes all of the address-taken blocks.
1333f4a2713aSLionel Sambuc IndirectBranch->addDestination(BB);
1334f4a2713aSLionel Sambuc return llvm::BlockAddress::get(CurFn, BB);
1335f4a2713aSLionel Sambuc }
1336f4a2713aSLionel Sambuc
GetIndirectGotoBlock()1337f4a2713aSLionel Sambuc llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
1338f4a2713aSLionel Sambuc // If we already made the indirect branch for indirect goto, return its block.
1339f4a2713aSLionel Sambuc if (IndirectBranch) return IndirectBranch->getParent();
1340f4a2713aSLionel Sambuc
1341f4a2713aSLionel Sambuc CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
1342f4a2713aSLionel Sambuc
1343f4a2713aSLionel Sambuc // Create the PHI node that indirect gotos will add entries to.
1344f4a2713aSLionel Sambuc llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
1345f4a2713aSLionel Sambuc "indirect.goto.dest");
1346f4a2713aSLionel Sambuc
1347f4a2713aSLionel Sambuc // Create the indirect branch instruction.
1348f4a2713aSLionel Sambuc IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1349f4a2713aSLionel Sambuc return IndirectBranch->getParent();
1350f4a2713aSLionel Sambuc }
1351f4a2713aSLionel Sambuc
1352f4a2713aSLionel Sambuc /// Computes the length of an array in elements, as well as the base
1353f4a2713aSLionel Sambuc /// element type and a properly-typed first element pointer.
emitArrayLength(const ArrayType * origArrayType,QualType & baseType,llvm::Value * & addr)1354f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
1355f4a2713aSLionel Sambuc QualType &baseType,
1356f4a2713aSLionel Sambuc llvm::Value *&addr) {
1357f4a2713aSLionel Sambuc const ArrayType *arrayType = origArrayType;
1358f4a2713aSLionel Sambuc
1359f4a2713aSLionel Sambuc // If it's a VLA, we have to load the stored size. Note that
1360f4a2713aSLionel Sambuc // this is the size of the VLA in bytes, not its size in elements.
1361*0a6a1f1dSLionel Sambuc llvm::Value *numVLAElements = nullptr;
1362f4a2713aSLionel Sambuc if (isa<VariableArrayType>(arrayType)) {
1363f4a2713aSLionel Sambuc numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
1364f4a2713aSLionel Sambuc
1365f4a2713aSLionel Sambuc // Walk into all VLAs. This doesn't require changes to addr,
1366f4a2713aSLionel Sambuc // which has type T* where T is the first non-VLA element type.
1367f4a2713aSLionel Sambuc do {
1368f4a2713aSLionel Sambuc QualType elementType = arrayType->getElementType();
1369f4a2713aSLionel Sambuc arrayType = getContext().getAsArrayType(elementType);
1370f4a2713aSLionel Sambuc
1371f4a2713aSLionel Sambuc // If we only have VLA components, 'addr' requires no adjustment.
1372f4a2713aSLionel Sambuc if (!arrayType) {
1373f4a2713aSLionel Sambuc baseType = elementType;
1374f4a2713aSLionel Sambuc return numVLAElements;
1375f4a2713aSLionel Sambuc }
1376f4a2713aSLionel Sambuc } while (isa<VariableArrayType>(arrayType));
1377f4a2713aSLionel Sambuc
1378f4a2713aSLionel Sambuc // We get out here only if we find a constant array type
1379f4a2713aSLionel Sambuc // inside the VLA.
1380f4a2713aSLionel Sambuc }
1381f4a2713aSLionel Sambuc
1382f4a2713aSLionel Sambuc // We have some number of constant-length arrays, so addr should
1383f4a2713aSLionel Sambuc // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
1384f4a2713aSLionel Sambuc // down to the first element of addr.
1385f4a2713aSLionel Sambuc SmallVector<llvm::Value*, 8> gepIndices;
1386f4a2713aSLionel Sambuc
1387f4a2713aSLionel Sambuc // GEP down to the array type.
1388f4a2713aSLionel Sambuc llvm::ConstantInt *zero = Builder.getInt32(0);
1389f4a2713aSLionel Sambuc gepIndices.push_back(zero);
1390f4a2713aSLionel Sambuc
1391f4a2713aSLionel Sambuc uint64_t countFromCLAs = 1;
1392f4a2713aSLionel Sambuc QualType eltType;
1393f4a2713aSLionel Sambuc
1394f4a2713aSLionel Sambuc llvm::ArrayType *llvmArrayType =
1395f4a2713aSLionel Sambuc dyn_cast<llvm::ArrayType>(
1396f4a2713aSLionel Sambuc cast<llvm::PointerType>(addr->getType())->getElementType());
1397f4a2713aSLionel Sambuc while (llvmArrayType) {
1398f4a2713aSLionel Sambuc assert(isa<ConstantArrayType>(arrayType));
1399f4a2713aSLionel Sambuc assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
1400f4a2713aSLionel Sambuc == llvmArrayType->getNumElements());
1401f4a2713aSLionel Sambuc
1402f4a2713aSLionel Sambuc gepIndices.push_back(zero);
1403f4a2713aSLionel Sambuc countFromCLAs *= llvmArrayType->getNumElements();
1404f4a2713aSLionel Sambuc eltType = arrayType->getElementType();
1405f4a2713aSLionel Sambuc
1406f4a2713aSLionel Sambuc llvmArrayType =
1407f4a2713aSLionel Sambuc dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
1408f4a2713aSLionel Sambuc arrayType = getContext().getAsArrayType(arrayType->getElementType());
1409f4a2713aSLionel Sambuc assert((!llvmArrayType || arrayType) &&
1410f4a2713aSLionel Sambuc "LLVM and Clang types are out-of-synch");
1411f4a2713aSLionel Sambuc }
1412f4a2713aSLionel Sambuc
1413f4a2713aSLionel Sambuc if (arrayType) {
1414f4a2713aSLionel Sambuc // From this point onwards, the Clang array type has been emitted
1415f4a2713aSLionel Sambuc // as some other type (probably a packed struct). Compute the array
1416f4a2713aSLionel Sambuc // size, and just emit the 'begin' expression as a bitcast.
1417f4a2713aSLionel Sambuc while (arrayType) {
1418f4a2713aSLionel Sambuc countFromCLAs *=
1419f4a2713aSLionel Sambuc cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
1420f4a2713aSLionel Sambuc eltType = arrayType->getElementType();
1421f4a2713aSLionel Sambuc arrayType = getContext().getAsArrayType(eltType);
1422f4a2713aSLionel Sambuc }
1423f4a2713aSLionel Sambuc
1424f4a2713aSLionel Sambuc unsigned AddressSpace = addr->getType()->getPointerAddressSpace();
1425f4a2713aSLionel Sambuc llvm::Type *BaseType = ConvertType(eltType)->getPointerTo(AddressSpace);
1426f4a2713aSLionel Sambuc addr = Builder.CreateBitCast(addr, BaseType, "array.begin");
1427f4a2713aSLionel Sambuc } else {
1428f4a2713aSLionel Sambuc // Create the actual GEP.
1429f4a2713aSLionel Sambuc addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin");
1430f4a2713aSLionel Sambuc }
1431f4a2713aSLionel Sambuc
1432f4a2713aSLionel Sambuc baseType = eltType;
1433f4a2713aSLionel Sambuc
1434f4a2713aSLionel Sambuc llvm::Value *numElements
1435f4a2713aSLionel Sambuc = llvm::ConstantInt::get(SizeTy, countFromCLAs);
1436f4a2713aSLionel Sambuc
1437f4a2713aSLionel Sambuc // If we had any VLA dimensions, factor them in.
1438f4a2713aSLionel Sambuc if (numVLAElements)
1439f4a2713aSLionel Sambuc numElements = Builder.CreateNUWMul(numVLAElements, numElements);
1440f4a2713aSLionel Sambuc
1441f4a2713aSLionel Sambuc return numElements;
1442f4a2713aSLionel Sambuc }
1443f4a2713aSLionel Sambuc
1444f4a2713aSLionel Sambuc std::pair<llvm::Value*, QualType>
getVLASize(QualType type)1445f4a2713aSLionel Sambuc CodeGenFunction::getVLASize(QualType type) {
1446f4a2713aSLionel Sambuc const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
1447f4a2713aSLionel Sambuc assert(vla && "type was not a variable array type!");
1448f4a2713aSLionel Sambuc return getVLASize(vla);
1449f4a2713aSLionel Sambuc }
1450f4a2713aSLionel Sambuc
1451f4a2713aSLionel Sambuc std::pair<llvm::Value*, QualType>
getVLASize(const VariableArrayType * type)1452f4a2713aSLionel Sambuc CodeGenFunction::getVLASize(const VariableArrayType *type) {
1453f4a2713aSLionel Sambuc // The number of elements so far; always size_t.
1454*0a6a1f1dSLionel Sambuc llvm::Value *numElements = nullptr;
1455f4a2713aSLionel Sambuc
1456f4a2713aSLionel Sambuc QualType elementType;
1457f4a2713aSLionel Sambuc do {
1458f4a2713aSLionel Sambuc elementType = type->getElementType();
1459f4a2713aSLionel Sambuc llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
1460f4a2713aSLionel Sambuc assert(vlaSize && "no size for VLA!");
1461f4a2713aSLionel Sambuc assert(vlaSize->getType() == SizeTy);
1462f4a2713aSLionel Sambuc
1463f4a2713aSLionel Sambuc if (!numElements) {
1464f4a2713aSLionel Sambuc numElements = vlaSize;
1465f4a2713aSLionel Sambuc } else {
1466f4a2713aSLionel Sambuc // It's undefined behavior if this wraps around, so mark it that way.
1467*0a6a1f1dSLionel Sambuc // FIXME: Teach -fsanitize=undefined to trap this.
1468f4a2713aSLionel Sambuc numElements = Builder.CreateNUWMul(numElements, vlaSize);
1469f4a2713aSLionel Sambuc }
1470f4a2713aSLionel Sambuc } while ((type = getContext().getAsVariableArrayType(elementType)));
1471f4a2713aSLionel Sambuc
1472f4a2713aSLionel Sambuc return std::pair<llvm::Value*,QualType>(numElements, elementType);
1473f4a2713aSLionel Sambuc }
1474f4a2713aSLionel Sambuc
EmitVariablyModifiedType(QualType type)1475f4a2713aSLionel Sambuc void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
1476f4a2713aSLionel Sambuc assert(type->isVariablyModifiedType() &&
1477f4a2713aSLionel Sambuc "Must pass variably modified type to EmitVLASizes!");
1478f4a2713aSLionel Sambuc
1479f4a2713aSLionel Sambuc EnsureInsertPoint();
1480f4a2713aSLionel Sambuc
1481f4a2713aSLionel Sambuc // We're going to walk down into the type and look for VLA
1482f4a2713aSLionel Sambuc // expressions.
1483f4a2713aSLionel Sambuc do {
1484f4a2713aSLionel Sambuc assert(type->isVariablyModifiedType());
1485f4a2713aSLionel Sambuc
1486f4a2713aSLionel Sambuc const Type *ty = type.getTypePtr();
1487f4a2713aSLionel Sambuc switch (ty->getTypeClass()) {
1488f4a2713aSLionel Sambuc
1489f4a2713aSLionel Sambuc #define TYPE(Class, Base)
1490f4a2713aSLionel Sambuc #define ABSTRACT_TYPE(Class, Base)
1491f4a2713aSLionel Sambuc #define NON_CANONICAL_TYPE(Class, Base)
1492f4a2713aSLionel Sambuc #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1493f4a2713aSLionel Sambuc #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
1494f4a2713aSLionel Sambuc #include "clang/AST/TypeNodes.def"
1495f4a2713aSLionel Sambuc llvm_unreachable("unexpected dependent type!");
1496f4a2713aSLionel Sambuc
1497f4a2713aSLionel Sambuc // These types are never variably-modified.
1498f4a2713aSLionel Sambuc case Type::Builtin:
1499f4a2713aSLionel Sambuc case Type::Complex:
1500f4a2713aSLionel Sambuc case Type::Vector:
1501f4a2713aSLionel Sambuc case Type::ExtVector:
1502f4a2713aSLionel Sambuc case Type::Record:
1503f4a2713aSLionel Sambuc case Type::Enum:
1504f4a2713aSLionel Sambuc case Type::Elaborated:
1505f4a2713aSLionel Sambuc case Type::TemplateSpecialization:
1506f4a2713aSLionel Sambuc case Type::ObjCObject:
1507f4a2713aSLionel Sambuc case Type::ObjCInterface:
1508f4a2713aSLionel Sambuc case Type::ObjCObjectPointer:
1509f4a2713aSLionel Sambuc llvm_unreachable("type class is never variably-modified!");
1510f4a2713aSLionel Sambuc
1511*0a6a1f1dSLionel Sambuc case Type::Adjusted:
1512*0a6a1f1dSLionel Sambuc type = cast<AdjustedType>(ty)->getAdjustedType();
1513*0a6a1f1dSLionel Sambuc break;
1514*0a6a1f1dSLionel Sambuc
1515f4a2713aSLionel Sambuc case Type::Decayed:
1516f4a2713aSLionel Sambuc type = cast<DecayedType>(ty)->getPointeeType();
1517f4a2713aSLionel Sambuc break;
1518f4a2713aSLionel Sambuc
1519f4a2713aSLionel Sambuc case Type::Pointer:
1520f4a2713aSLionel Sambuc type = cast<PointerType>(ty)->getPointeeType();
1521f4a2713aSLionel Sambuc break;
1522f4a2713aSLionel Sambuc
1523f4a2713aSLionel Sambuc case Type::BlockPointer:
1524f4a2713aSLionel Sambuc type = cast<BlockPointerType>(ty)->getPointeeType();
1525f4a2713aSLionel Sambuc break;
1526f4a2713aSLionel Sambuc
1527f4a2713aSLionel Sambuc case Type::LValueReference:
1528f4a2713aSLionel Sambuc case Type::RValueReference:
1529f4a2713aSLionel Sambuc type = cast<ReferenceType>(ty)->getPointeeType();
1530f4a2713aSLionel Sambuc break;
1531f4a2713aSLionel Sambuc
1532f4a2713aSLionel Sambuc case Type::MemberPointer:
1533f4a2713aSLionel Sambuc type = cast<MemberPointerType>(ty)->getPointeeType();
1534f4a2713aSLionel Sambuc break;
1535f4a2713aSLionel Sambuc
1536f4a2713aSLionel Sambuc case Type::ConstantArray:
1537f4a2713aSLionel Sambuc case Type::IncompleteArray:
1538f4a2713aSLionel Sambuc // Losing element qualification here is fine.
1539f4a2713aSLionel Sambuc type = cast<ArrayType>(ty)->getElementType();
1540f4a2713aSLionel Sambuc break;
1541f4a2713aSLionel Sambuc
1542f4a2713aSLionel Sambuc case Type::VariableArray: {
1543f4a2713aSLionel Sambuc // Losing element qualification here is fine.
1544f4a2713aSLionel Sambuc const VariableArrayType *vat = cast<VariableArrayType>(ty);
1545f4a2713aSLionel Sambuc
1546f4a2713aSLionel Sambuc // Unknown size indication requires no size computation.
1547f4a2713aSLionel Sambuc // Otherwise, evaluate and record it.
1548f4a2713aSLionel Sambuc if (const Expr *size = vat->getSizeExpr()) {
1549f4a2713aSLionel Sambuc // It's possible that we might have emitted this already,
1550f4a2713aSLionel Sambuc // e.g. with a typedef and a pointer to it.
1551f4a2713aSLionel Sambuc llvm::Value *&entry = VLASizeMap[size];
1552f4a2713aSLionel Sambuc if (!entry) {
1553f4a2713aSLionel Sambuc llvm::Value *Size = EmitScalarExpr(size);
1554f4a2713aSLionel Sambuc
1555f4a2713aSLionel Sambuc // C11 6.7.6.2p5:
1556f4a2713aSLionel Sambuc // If the size is an expression that is not an integer constant
1557f4a2713aSLionel Sambuc // expression [...] each time it is evaluated it shall have a value
1558f4a2713aSLionel Sambuc // greater than zero.
1559*0a6a1f1dSLionel Sambuc if (SanOpts.has(SanitizerKind::VLABound) &&
1560f4a2713aSLionel Sambuc size->getType()->isSignedIntegerType()) {
1561*0a6a1f1dSLionel Sambuc SanitizerScope SanScope(this);
1562f4a2713aSLionel Sambuc llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
1563f4a2713aSLionel Sambuc llvm::Constant *StaticArgs[] = {
1564f4a2713aSLionel Sambuc EmitCheckSourceLocation(size->getLocStart()),
1565f4a2713aSLionel Sambuc EmitCheckTypeDescriptor(size->getType())
1566f4a2713aSLionel Sambuc };
1567*0a6a1f1dSLionel Sambuc EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
1568*0a6a1f1dSLionel Sambuc SanitizerKind::VLABound),
1569*0a6a1f1dSLionel Sambuc "vla_bound_not_positive", StaticArgs, Size);
1570f4a2713aSLionel Sambuc }
1571f4a2713aSLionel Sambuc
1572f4a2713aSLionel Sambuc // Always zexting here would be wrong if it weren't
1573f4a2713aSLionel Sambuc // undefined behavior to have a negative bound.
1574f4a2713aSLionel Sambuc entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
1575f4a2713aSLionel Sambuc }
1576f4a2713aSLionel Sambuc }
1577f4a2713aSLionel Sambuc type = vat->getElementType();
1578f4a2713aSLionel Sambuc break;
1579f4a2713aSLionel Sambuc }
1580f4a2713aSLionel Sambuc
1581f4a2713aSLionel Sambuc case Type::FunctionProto:
1582f4a2713aSLionel Sambuc case Type::FunctionNoProto:
1583*0a6a1f1dSLionel Sambuc type = cast<FunctionType>(ty)->getReturnType();
1584f4a2713aSLionel Sambuc break;
1585f4a2713aSLionel Sambuc
1586f4a2713aSLionel Sambuc case Type::Paren:
1587f4a2713aSLionel Sambuc case Type::TypeOf:
1588f4a2713aSLionel Sambuc case Type::UnaryTransform:
1589f4a2713aSLionel Sambuc case Type::Attributed:
1590f4a2713aSLionel Sambuc case Type::SubstTemplateTypeParm:
1591f4a2713aSLionel Sambuc case Type::PackExpansion:
1592f4a2713aSLionel Sambuc // Keep walking after single level desugaring.
1593f4a2713aSLionel Sambuc type = type.getSingleStepDesugaredType(getContext());
1594f4a2713aSLionel Sambuc break;
1595f4a2713aSLionel Sambuc
1596f4a2713aSLionel Sambuc case Type::Typedef:
1597f4a2713aSLionel Sambuc case Type::Decltype:
1598f4a2713aSLionel Sambuc case Type::Auto:
1599f4a2713aSLionel Sambuc // Stop walking: nothing to do.
1600f4a2713aSLionel Sambuc return;
1601f4a2713aSLionel Sambuc
1602f4a2713aSLionel Sambuc case Type::TypeOfExpr:
1603f4a2713aSLionel Sambuc // Stop walking: emit typeof expression.
1604f4a2713aSLionel Sambuc EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
1605f4a2713aSLionel Sambuc return;
1606f4a2713aSLionel Sambuc
1607f4a2713aSLionel Sambuc case Type::Atomic:
1608f4a2713aSLionel Sambuc type = cast<AtomicType>(ty)->getValueType();
1609f4a2713aSLionel Sambuc break;
1610f4a2713aSLionel Sambuc }
1611f4a2713aSLionel Sambuc } while (type->isVariablyModifiedType());
1612f4a2713aSLionel Sambuc }
1613f4a2713aSLionel Sambuc
EmitVAListRef(const Expr * E)1614f4a2713aSLionel Sambuc llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
1615f4a2713aSLionel Sambuc if (getContext().getBuiltinVaListType()->isArrayType())
1616f4a2713aSLionel Sambuc return EmitScalarExpr(E);
1617f4a2713aSLionel Sambuc return EmitLValue(E).getAddress();
1618f4a2713aSLionel Sambuc }
1619f4a2713aSLionel Sambuc
EmitDeclRefExprDbgValue(const DeclRefExpr * E,llvm::Constant * Init)1620f4a2713aSLionel Sambuc void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
1621f4a2713aSLionel Sambuc llvm::Constant *Init) {
1622f4a2713aSLionel Sambuc assert (Init && "Invalid DeclRefExpr initializer!");
1623f4a2713aSLionel Sambuc if (CGDebugInfo *Dbg = getDebugInfo())
1624f4a2713aSLionel Sambuc if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1625f4a2713aSLionel Sambuc Dbg->EmitGlobalVariable(E->getDecl(), Init);
1626f4a2713aSLionel Sambuc }
1627f4a2713aSLionel Sambuc
1628f4a2713aSLionel Sambuc CodeGenFunction::PeepholeProtection
protectFromPeepholes(RValue rvalue)1629f4a2713aSLionel Sambuc CodeGenFunction::protectFromPeepholes(RValue rvalue) {
1630f4a2713aSLionel Sambuc // At the moment, the only aggressive peephole we do in IR gen
1631f4a2713aSLionel Sambuc // is trunc(zext) folding, but if we add more, we can easily
1632f4a2713aSLionel Sambuc // extend this protection.
1633f4a2713aSLionel Sambuc
1634f4a2713aSLionel Sambuc if (!rvalue.isScalar()) return PeepholeProtection();
1635f4a2713aSLionel Sambuc llvm::Value *value = rvalue.getScalarVal();
1636f4a2713aSLionel Sambuc if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
1637f4a2713aSLionel Sambuc
1638f4a2713aSLionel Sambuc // Just make an extra bitcast.
1639f4a2713aSLionel Sambuc assert(HaveInsertPoint());
1640f4a2713aSLionel Sambuc llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
1641f4a2713aSLionel Sambuc Builder.GetInsertBlock());
1642f4a2713aSLionel Sambuc
1643f4a2713aSLionel Sambuc PeepholeProtection protection;
1644f4a2713aSLionel Sambuc protection.Inst = inst;
1645f4a2713aSLionel Sambuc return protection;
1646f4a2713aSLionel Sambuc }
1647f4a2713aSLionel Sambuc
unprotectFromPeepholes(PeepholeProtection protection)1648f4a2713aSLionel Sambuc void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
1649f4a2713aSLionel Sambuc if (!protection.Inst) return;
1650f4a2713aSLionel Sambuc
1651f4a2713aSLionel Sambuc // In theory, we could try to duplicate the peepholes now, but whatever.
1652f4a2713aSLionel Sambuc protection.Inst->eraseFromParent();
1653f4a2713aSLionel Sambuc }
1654f4a2713aSLionel Sambuc
EmitAnnotationCall(llvm::Value * AnnotationFn,llvm::Value * AnnotatedVal,StringRef AnnotationStr,SourceLocation Location)1655f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
1656f4a2713aSLionel Sambuc llvm::Value *AnnotatedVal,
1657f4a2713aSLionel Sambuc StringRef AnnotationStr,
1658f4a2713aSLionel Sambuc SourceLocation Location) {
1659f4a2713aSLionel Sambuc llvm::Value *Args[4] = {
1660f4a2713aSLionel Sambuc AnnotatedVal,
1661f4a2713aSLionel Sambuc Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
1662f4a2713aSLionel Sambuc Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
1663f4a2713aSLionel Sambuc CGM.EmitAnnotationLineNo(Location)
1664f4a2713aSLionel Sambuc };
1665f4a2713aSLionel Sambuc return Builder.CreateCall(AnnotationFn, Args);
1666f4a2713aSLionel Sambuc }
1667f4a2713aSLionel Sambuc
EmitVarAnnotations(const VarDecl * D,llvm::Value * V)1668f4a2713aSLionel Sambuc void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
1669f4a2713aSLionel Sambuc assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1670f4a2713aSLionel Sambuc // FIXME We create a new bitcast for every annotation because that's what
1671f4a2713aSLionel Sambuc // llvm-gcc was doing.
1672*0a6a1f1dSLionel Sambuc for (const auto *I : D->specific_attrs<AnnotateAttr>())
1673f4a2713aSLionel Sambuc EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
1674f4a2713aSLionel Sambuc Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
1675*0a6a1f1dSLionel Sambuc I->getAnnotation(), D->getLocation());
1676f4a2713aSLionel Sambuc }
1677f4a2713aSLionel Sambuc
EmitFieldAnnotations(const FieldDecl * D,llvm::Value * V)1678f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
1679f4a2713aSLionel Sambuc llvm::Value *V) {
1680f4a2713aSLionel Sambuc assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1681f4a2713aSLionel Sambuc llvm::Type *VTy = V->getType();
1682f4a2713aSLionel Sambuc llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
1683f4a2713aSLionel Sambuc CGM.Int8PtrTy);
1684f4a2713aSLionel Sambuc
1685*0a6a1f1dSLionel Sambuc for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
1686f4a2713aSLionel Sambuc // FIXME Always emit the cast inst so we can differentiate between
1687f4a2713aSLionel Sambuc // annotation on the first field of a struct and annotation on the struct
1688f4a2713aSLionel Sambuc // itself.
1689f4a2713aSLionel Sambuc if (VTy != CGM.Int8PtrTy)
1690f4a2713aSLionel Sambuc V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
1691*0a6a1f1dSLionel Sambuc V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
1692f4a2713aSLionel Sambuc V = Builder.CreateBitCast(V, VTy);
1693f4a2713aSLionel Sambuc }
1694f4a2713aSLionel Sambuc
1695f4a2713aSLionel Sambuc return V;
1696f4a2713aSLionel Sambuc }
1697f4a2713aSLionel Sambuc
~CGCapturedStmtInfo()1698f4a2713aSLionel Sambuc CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
1699*0a6a1f1dSLionel Sambuc
SanitizerScope(CodeGenFunction * CGF)1700*0a6a1f1dSLionel Sambuc CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
1701*0a6a1f1dSLionel Sambuc : CGF(CGF) {
1702*0a6a1f1dSLionel Sambuc assert(!CGF->IsSanitizerScope);
1703*0a6a1f1dSLionel Sambuc CGF->IsSanitizerScope = true;
1704*0a6a1f1dSLionel Sambuc }
1705*0a6a1f1dSLionel Sambuc
~SanitizerScope()1706*0a6a1f1dSLionel Sambuc CodeGenFunction::SanitizerScope::~SanitizerScope() {
1707*0a6a1f1dSLionel Sambuc CGF->IsSanitizerScope = false;
1708*0a6a1f1dSLionel Sambuc }
1709*0a6a1f1dSLionel Sambuc
InsertHelper(llvm::Instruction * I,const llvm::Twine & Name,llvm::BasicBlock * BB,llvm::BasicBlock::iterator InsertPt) const1710*0a6a1f1dSLionel Sambuc void CodeGenFunction::InsertHelper(llvm::Instruction *I,
1711*0a6a1f1dSLionel Sambuc const llvm::Twine &Name,
1712*0a6a1f1dSLionel Sambuc llvm::BasicBlock *BB,
1713*0a6a1f1dSLionel Sambuc llvm::BasicBlock::iterator InsertPt) const {
1714*0a6a1f1dSLionel Sambuc LoopStack.InsertHelper(I);
1715*0a6a1f1dSLionel Sambuc if (IsSanitizerScope)
1716*0a6a1f1dSLionel Sambuc CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
1717*0a6a1f1dSLionel Sambuc }
1718*0a6a1f1dSLionel Sambuc
1719*0a6a1f1dSLionel Sambuc template <bool PreserveNames>
InsertHelper(llvm::Instruction * I,const llvm::Twine & Name,llvm::BasicBlock * BB,llvm::BasicBlock::iterator InsertPt) const1720*0a6a1f1dSLionel Sambuc void CGBuilderInserter<PreserveNames>::InsertHelper(
1721*0a6a1f1dSLionel Sambuc llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
1722*0a6a1f1dSLionel Sambuc llvm::BasicBlock::iterator InsertPt) const {
1723*0a6a1f1dSLionel Sambuc llvm::IRBuilderDefaultInserter<PreserveNames>::InsertHelper(I, Name, BB,
1724*0a6a1f1dSLionel Sambuc InsertPt);
1725*0a6a1f1dSLionel Sambuc if (CGF)
1726*0a6a1f1dSLionel Sambuc CGF->InsertHelper(I, Name, BB, InsertPt);
1727*0a6a1f1dSLionel Sambuc }
1728*0a6a1f1dSLionel Sambuc
1729*0a6a1f1dSLionel Sambuc #ifdef NDEBUG
1730*0a6a1f1dSLionel Sambuc #define PreserveNames false
1731*0a6a1f1dSLionel Sambuc #else
1732*0a6a1f1dSLionel Sambuc #define PreserveNames true
1733*0a6a1f1dSLionel Sambuc #endif
1734*0a6a1f1dSLionel Sambuc template void CGBuilderInserter<PreserveNames>::InsertHelper(
1735*0a6a1f1dSLionel Sambuc llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
1736*0a6a1f1dSLionel Sambuc llvm::BasicBlock::iterator InsertPt) const;
1737*0a6a1f1dSLionel Sambuc #undef PreserveNames
1738