1f22ef01cSRoman Divacky //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This coordinates the per-function state used while generating code.
11f22ef01cSRoman Divacky //
12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
13f22ef01cSRoman Divacky 
14f22ef01cSRoman Divacky #include "CodeGenFunction.h"
150623d748SDimitry Andric #include "CGBlocks.h"
1633956c43SDimitry Andric #include "CGCleanup.h"
176122f3e6SDimitry Andric #include "CGCUDARuntime.h"
18e580952dSDimitry Andric #include "CGCXXABI.h"
19f22ef01cSRoman Divacky #include "CGDebugInfo.h"
2059d1ed5bSDimitry Andric #include "CGOpenMPRuntime.h"
21139f7f9bSDimitry Andric #include "CodeGenModule.h"
2259d1ed5bSDimitry Andric #include "CodeGenPGO.h"
23f785676fSDimitry Andric #include "TargetInfo.h"
24f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h"
25f22ef01cSRoman Divacky #include "clang/AST/Decl.h"
26f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h"
27f22ef01cSRoman Divacky #include "clang/AST/StmtCXX.h"
28f41fbc90SDimitry Andric #include "clang/AST/StmtObjC.h"
290623d748SDimitry Andric #include "clang/Basic/Builtins.h"
30139f7f9bSDimitry Andric #include "clang/Basic/TargetInfo.h"
31f785676fSDimitry Andric #include "clang/CodeGen/CGFunctionInfo.h"
32ffd1746dSEd Schouten #include "clang/Frontend/CodeGenOptions.h"
330623d748SDimitry Andric #include "clang/Sema/SemaDiagnostic.h"
34139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
35139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
36139f7f9bSDimitry Andric #include "llvm/IR/MDBuilder.h"
37139f7f9bSDimitry Andric #include "llvm/IR/Operator.h"
38f22ef01cSRoman Divacky using namespace clang;
39f22ef01cSRoman Divacky using namespace CodeGen;
40f22ef01cSRoman Divacky 
4144290647SDimitry Andric /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
4244290647SDimitry Andric /// markers.
4344290647SDimitry Andric static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
4444290647SDimitry Andric                                       const LangOptions &LangOpts) {
4524e2fe98SDimitry Andric   if (CGOpts.DisableLifetimeMarkers)
4624e2fe98SDimitry Andric     return false;
4724e2fe98SDimitry Andric 
4844290647SDimitry Andric   // Asan uses markers for use-after-scope checks.
4944290647SDimitry Andric   if (CGOpts.SanitizeAddressUseAfterScope)
5044290647SDimitry Andric     return true;
5144290647SDimitry Andric 
5244290647SDimitry Andric   // Disable lifetime markers in msan builds.
5344290647SDimitry Andric   // FIXME: Remove this when msan works with lifetime markers.
5444290647SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Memory))
5544290647SDimitry Andric     return false;
5644290647SDimitry Andric 
5744290647SDimitry Andric   // For now, only in optimized builds.
5844290647SDimitry Andric   return CGOpts.OptimizationLevel != 0;
5944290647SDimitry Andric }
6044290647SDimitry Andric 
617ae0e2c9SDimitry Andric CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
62284c1978SDimitry Andric     : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
630623d748SDimitry Andric       Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
6459d1ed5bSDimitry Andric               CGBuilderInserterTy(this)),
650623d748SDimitry Andric       CurFn(nullptr), ReturnValue(Address::invalid()),
6644290647SDimitry Andric       CapturedStmtInfo(nullptr), SanOpts(CGM.getLangOpts().Sanitize),
6744290647SDimitry Andric       IsSanitizerScope(false), CurFuncIsThunk(false), AutoreleaseResult(false),
6844290647SDimitry Andric       SawAsmBlock(false), IsOutlinedSEHHelper(false), BlockInfo(nullptr),
6944290647SDimitry Andric       BlockPointer(nullptr), LambdaThisCaptureField(nullptr),
7044290647SDimitry Andric       NormalCleanupDest(nullptr), NextCleanupDestIndex(1),
7144290647SDimitry Andric       FirstBlockInfo(nullptr), EHResumeBlock(nullptr), ExceptionSlot(nullptr),
7244290647SDimitry Andric       EHSelectorSlot(nullptr), DebugInfo(CGM.getModuleDebugInfo()),
73875ed548SDimitry Andric       DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(nullptr),
74875ed548SDimitry Andric       PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr),
75875ed548SDimitry Andric       CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0),
76875ed548SDimitry Andric       NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr),
77875ed548SDimitry Andric       CXXABIThisValue(nullptr), CXXThisValue(nullptr),
780623d748SDimitry Andric       CXXStructorImplicitParamDecl(nullptr),
7959d1ed5bSDimitry Andric       CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
8059d1ed5bSDimitry Andric       CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
8144290647SDimitry Andric       TerminateHandler(nullptr), TrapBB(nullptr),
8244290647SDimitry Andric       ShouldEmitLifetimeMarkers(
8344290647SDimitry Andric           shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) {
847ae0e2c9SDimitry Andric   if (!suppressNewContext)
85e580952dSDimitry Andric     CGM.getCXXABI().getMangleContext().startNewFunction();
86139f7f9bSDimitry Andric 
87139f7f9bSDimitry Andric   llvm::FastMathFlags FMF;
88139f7f9bSDimitry Andric   if (CGM.getLangOpts().FastMath)
89139f7f9bSDimitry Andric     FMF.setUnsafeAlgebra();
90139f7f9bSDimitry Andric   if (CGM.getLangOpts().FiniteMathOnly) {
91139f7f9bSDimitry Andric     FMF.setNoNaNs();
92139f7f9bSDimitry Andric     FMF.setNoInfs();
93139f7f9bSDimitry Andric   }
9439d628a0SDimitry Andric   if (CGM.getCodeGenOpts().NoNaNsFPMath) {
9539d628a0SDimitry Andric     FMF.setNoNaNs();
9639d628a0SDimitry Andric   }
9739d628a0SDimitry Andric   if (CGM.getCodeGenOpts().NoSignedZeros) {
9839d628a0SDimitry Andric     FMF.setNoSignedZeros();
9939d628a0SDimitry Andric   }
10033956c43SDimitry Andric   if (CGM.getCodeGenOpts().ReciprocalMath) {
10133956c43SDimitry Andric     FMF.setAllowReciprocal();
10233956c43SDimitry Andric   }
103444ed5c5SDimitry Andric   Builder.setFastMathFlags(FMF);
104f22ef01cSRoman Divacky }
105f22ef01cSRoman Divacky 
106dff0c46cSDimitry Andric CodeGenFunction::~CodeGenFunction() {
107f785676fSDimitry Andric   assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
108f785676fSDimitry Andric 
109dff0c46cSDimitry Andric   // If there are any unclaimed block infos, go ahead and destroy them
110dff0c46cSDimitry Andric   // now.  This can happen if IR-gen gets clever and skips evaluating
111dff0c46cSDimitry Andric   // something.
112dff0c46cSDimitry Andric   if (FirstBlockInfo)
113dff0c46cSDimitry Andric     destroyBlockInfos(FirstBlockInfo);
11459d1ed5bSDimitry Andric 
11559d1ed5bSDimitry Andric   if (getLangOpts().OpenMP) {
11633956c43SDimitry Andric     CGM.getOpenMPRuntime().functionFinished(*this);
11759d1ed5bSDimitry Andric   }
118dff0c46cSDimitry Andric }
119dff0c46cSDimitry Andric 
1200623d748SDimitry Andric CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T,
1210623d748SDimitry Andric                                                      AlignmentSource *Source) {
1220623d748SDimitry Andric   return getNaturalTypeAlignment(T->getPointeeType(), Source,
1230623d748SDimitry Andric                                  /*forPointee*/ true);
1240623d748SDimitry Andric }
1250623d748SDimitry Andric 
1260623d748SDimitry Andric CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T,
1270623d748SDimitry Andric                                                    AlignmentSource *Source,
1280623d748SDimitry Andric                                                    bool forPointeeType) {
1290623d748SDimitry Andric   // Honor alignment typedef attributes even on incomplete types.
1300623d748SDimitry Andric   // We also honor them straight for C++ class types, even as pointees;
1310623d748SDimitry Andric   // there's an expressivity gap here.
1320623d748SDimitry Andric   if (auto TT = T->getAs<TypedefType>()) {
1330623d748SDimitry Andric     if (auto Align = TT->getDecl()->getMaxAlignment()) {
1340623d748SDimitry Andric       if (Source) *Source = AlignmentSource::AttributedType;
1350623d748SDimitry Andric       return getContext().toCharUnitsFromBits(Align);
1360623d748SDimitry Andric     }
1370623d748SDimitry Andric   }
1380623d748SDimitry Andric 
1390623d748SDimitry Andric   if (Source) *Source = AlignmentSource::Type;
1400623d748SDimitry Andric 
14139d628a0SDimitry Andric   CharUnits Alignment;
1420623d748SDimitry Andric   if (T->isIncompleteType()) {
1430623d748SDimitry Andric     Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best.
1440623d748SDimitry Andric   } else {
1450623d748SDimitry Andric     // For C++ class pointees, we don't know whether we're pointing at a
1460623d748SDimitry Andric     // base or a complete object, so we generally need to use the
1470623d748SDimitry Andric     // non-virtual alignment.
1480623d748SDimitry Andric     const CXXRecordDecl *RD;
1490623d748SDimitry Andric     if (forPointeeType && (RD = T->getAsCXXRecordDecl())) {
1500623d748SDimitry Andric       Alignment = CGM.getClassPointerAlignment(RD);
1510623d748SDimitry Andric     } else {
15239d628a0SDimitry Andric       Alignment = getContext().getTypeAlignInChars(T);
1530623d748SDimitry Andric     }
1540623d748SDimitry Andric 
1550623d748SDimitry Andric     // Cap to the global maximum type alignment unless the alignment
1560623d748SDimitry Andric     // was somehow explicit on the type.
1570623d748SDimitry Andric     if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
1580623d748SDimitry Andric       if (Alignment.getQuantity() > MaxAlign &&
15939d628a0SDimitry Andric           !getContext().isAlignmentRequired(T))
16039d628a0SDimitry Andric         Alignment = CharUnits::fromQuantity(MaxAlign);
16139d628a0SDimitry Andric     }
16239d628a0SDimitry Andric   }
1630623d748SDimitry Andric   return Alignment;
1640623d748SDimitry Andric }
1650623d748SDimitry Andric 
1660623d748SDimitry Andric LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
1670623d748SDimitry Andric   AlignmentSource AlignSource;
1680623d748SDimitry Andric   CharUnits Alignment = getNaturalTypeAlignment(T, &AlignSource);
1690623d748SDimitry Andric   return LValue::MakeAddr(Address(V, Alignment), T, getContext(), AlignSource,
1700623d748SDimitry Andric                           CGM.getTBAAInfo(T));
1710623d748SDimitry Andric }
1720623d748SDimitry Andric 
1730623d748SDimitry Andric /// Given a value of type T* that may not be to a complete object,
1740623d748SDimitry Andric /// construct an l-value with the natural pointee alignment of T.
1750623d748SDimitry Andric LValue
1760623d748SDimitry Andric CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
1770623d748SDimitry Andric   AlignmentSource AlignSource;
1780623d748SDimitry Andric   CharUnits Align = getNaturalTypeAlignment(T, &AlignSource, /*pointee*/ true);
1790623d748SDimitry Andric   return MakeAddrLValue(Address(V, Align), T, AlignSource);
1800623d748SDimitry Andric }
1810623d748SDimitry Andric 
182f22ef01cSRoman Divacky 
18317a519f9SDimitry Andric llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
184f22ef01cSRoman Divacky   return CGM.getTypes().ConvertTypeForMem(T);
185f22ef01cSRoman Divacky }
186f22ef01cSRoman Divacky 
18717a519f9SDimitry Andric llvm::Type *CodeGenFunction::ConvertType(QualType T) {
188f22ef01cSRoman Divacky   return CGM.getTypes().ConvertType(T);
189f22ef01cSRoman Divacky }
190f22ef01cSRoman Divacky 
191139f7f9bSDimitry Andric TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
192139f7f9bSDimitry Andric   type = type.getCanonicalType();
193139f7f9bSDimitry Andric   while (true) {
194139f7f9bSDimitry Andric     switch (type->getTypeClass()) {
195bd5abe19SDimitry Andric #define TYPE(name, parent)
196bd5abe19SDimitry Andric #define ABSTRACT_TYPE(name, parent)
197bd5abe19SDimitry Andric #define NON_CANONICAL_TYPE(name, parent) case Type::name:
198bd5abe19SDimitry Andric #define DEPENDENT_TYPE(name, parent) case Type::name:
199bd5abe19SDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
200bd5abe19SDimitry Andric #include "clang/AST/TypeNodes.def"
201bd5abe19SDimitry Andric       llvm_unreachable("non-canonical or dependent type in IR-generation");
202bd5abe19SDimitry Andric 
203284c1978SDimitry Andric     case Type::Auto:
204284c1978SDimitry Andric       llvm_unreachable("undeduced auto type in IR-generation");
205284c1978SDimitry Andric 
206139f7f9bSDimitry Andric     // Various scalar types.
207bd5abe19SDimitry Andric     case Type::Builtin:
208bd5abe19SDimitry Andric     case Type::Pointer:
209bd5abe19SDimitry Andric     case Type::BlockPointer:
210bd5abe19SDimitry Andric     case Type::LValueReference:
211bd5abe19SDimitry Andric     case Type::RValueReference:
212bd5abe19SDimitry Andric     case Type::MemberPointer:
213bd5abe19SDimitry Andric     case Type::Vector:
214bd5abe19SDimitry Andric     case Type::ExtVector:
215bd5abe19SDimitry Andric     case Type::FunctionProto:
216bd5abe19SDimitry Andric     case Type::FunctionNoProto:
217bd5abe19SDimitry Andric     case Type::Enum:
218bd5abe19SDimitry Andric     case Type::ObjCObjectPointer:
219444ed5c5SDimitry Andric     case Type::Pipe:
220139f7f9bSDimitry Andric       return TEK_Scalar;
221bd5abe19SDimitry Andric 
222139f7f9bSDimitry Andric     // Complexes.
223bd5abe19SDimitry Andric     case Type::Complex:
224139f7f9bSDimitry Andric       return TEK_Complex;
225139f7f9bSDimitry Andric 
226139f7f9bSDimitry Andric     // Arrays, records, and Objective-C objects.
227bd5abe19SDimitry Andric     case Type::ConstantArray:
228bd5abe19SDimitry Andric     case Type::IncompleteArray:
229bd5abe19SDimitry Andric     case Type::VariableArray:
230bd5abe19SDimitry Andric     case Type::Record:
231bd5abe19SDimitry Andric     case Type::ObjCObject:
232bd5abe19SDimitry Andric     case Type::ObjCInterface:
233139f7f9bSDimitry Andric       return TEK_Aggregate;
2346122f3e6SDimitry Andric 
235139f7f9bSDimitry Andric     // We operate on atomic values according to their underlying type.
2366122f3e6SDimitry Andric     case Type::Atomic:
237139f7f9bSDimitry Andric       type = cast<AtomicType>(type)->getValueType();
238139f7f9bSDimitry Andric       continue;
239bd5abe19SDimitry Andric     }
240bd5abe19SDimitry Andric     llvm_unreachable("unknown type kind!");
241f22ef01cSRoman Divacky   }
242139f7f9bSDimitry Andric }
243f22ef01cSRoman Divacky 
24439d628a0SDimitry Andric llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
245f22ef01cSRoman Divacky   // For cleanliness, we try to avoid emitting the return block for
246f22ef01cSRoman Divacky   // simple cases.
247f22ef01cSRoman Divacky   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
248f22ef01cSRoman Divacky 
249f22ef01cSRoman Divacky   if (CurBB) {
250f22ef01cSRoman Divacky     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
251f22ef01cSRoman Divacky 
252f22ef01cSRoman Divacky     // We have a valid insert point, reuse it if it is empty or there are no
253f22ef01cSRoman Divacky     // explicit jumps to the return block.
254e580952dSDimitry Andric     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
255e580952dSDimitry Andric       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
256e580952dSDimitry Andric       delete ReturnBlock.getBlock();
257f22ef01cSRoman Divacky     } else
258e580952dSDimitry Andric       EmitBlock(ReturnBlock.getBlock());
25939d628a0SDimitry Andric     return llvm::DebugLoc();
260f22ef01cSRoman Divacky   }
261f22ef01cSRoman Divacky 
262f22ef01cSRoman Divacky   // Otherwise, if the return block is the target of a single direct
263f22ef01cSRoman Divacky   // branch then we can just put the code in that block instead. This
264f22ef01cSRoman Divacky   // cleans up functions which started with a unified return block.
265e580952dSDimitry Andric   if (ReturnBlock.getBlock()->hasOneUse()) {
266f22ef01cSRoman Divacky     llvm::BranchInst *BI =
26759d1ed5bSDimitry Andric       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
268ffd1746dSEd Schouten     if (BI && BI->isUnconditional() &&
269e580952dSDimitry Andric         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
27039d628a0SDimitry Andric       // Record/return the DebugLoc of the simple 'return' expression to be used
27139d628a0SDimitry Andric       // later by the actual 'ret' instruction.
27239d628a0SDimitry Andric       llvm::DebugLoc Loc = BI->getDebugLoc();
273f22ef01cSRoman Divacky       Builder.SetInsertPoint(BI->getParent());
274f22ef01cSRoman Divacky       BI->eraseFromParent();
275e580952dSDimitry Andric       delete ReturnBlock.getBlock();
27639d628a0SDimitry Andric       return Loc;
277f22ef01cSRoman Divacky     }
278f22ef01cSRoman Divacky   }
279f22ef01cSRoman Divacky 
280f22ef01cSRoman Divacky   // FIXME: We are at an unreachable point, there is no reason to emit the block
281f22ef01cSRoman Divacky   // unless it has uses. However, we still need a place to put the debug
282f22ef01cSRoman Divacky   // region.end for now.
283f22ef01cSRoman Divacky 
284e580952dSDimitry Andric   EmitBlock(ReturnBlock.getBlock());
28539d628a0SDimitry Andric   return llvm::DebugLoc();
286ffd1746dSEd Schouten }
287ffd1746dSEd Schouten 
288ffd1746dSEd Schouten static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
289ffd1746dSEd Schouten   if (!BB) return;
290ffd1746dSEd Schouten   if (!BB->use_empty())
291ffd1746dSEd Schouten     return CGF.CurFn->getBasicBlockList().push_back(BB);
292ffd1746dSEd Schouten   delete BB;
293f22ef01cSRoman Divacky }
294f22ef01cSRoman Divacky 
295f22ef01cSRoman Divacky void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
296f22ef01cSRoman Divacky   assert(BreakContinueStack.empty() &&
297f22ef01cSRoman Divacky          "mismatched push/pop in break/continue stack!");
298f22ef01cSRoman Divacky 
299284c1978SDimitry Andric   bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
300f785676fSDimitry Andric     && NumSimpleReturnExprs == NumReturnExprs
301f785676fSDimitry Andric     && ReturnBlock.getBlock()->use_empty();
302f785676fSDimitry Andric   // Usually the return expression is evaluated before the cleanup
303f785676fSDimitry Andric   // code.  If the function contains only a simple return statement,
304f785676fSDimitry Andric   // such as a constant, the location before the cleanup code becomes
305f785676fSDimitry Andric   // the last useful breakpoint in the function, because the simple
306f785676fSDimitry Andric   // return expression will be evaluated after the cleanup code. To be
307f785676fSDimitry Andric   // safe, set the debug location for cleanup code to the location of
308f785676fSDimitry Andric   // the return statement.  Otherwise the cleanup code should be at the
309f785676fSDimitry Andric   // end of the function's lexical scope.
310f785676fSDimitry Andric   //
311f785676fSDimitry Andric   // If there are multiple branches to the return block, the branch
312f785676fSDimitry Andric   // instructions will get the location of the return statements and
313f785676fSDimitry Andric   // all will be fine.
314284c1978SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo()) {
315284c1978SDimitry Andric     if (OnlySimpleReturnStmts)
316284c1978SDimitry Andric       DI->EmitLocation(Builder, LastStopPoint);
317284c1978SDimitry Andric     else
318139f7f9bSDimitry Andric       DI->EmitLocation(Builder, EndLoc);
319284c1978SDimitry Andric   }
320139f7f9bSDimitry Andric 
32117a519f9SDimitry Andric   // Pop any cleanups that might have been associated with the
32217a519f9SDimitry Andric   // parameters.  Do this in whatever block we're currently in; it's
32317a519f9SDimitry Andric   // important to do this before we enter the return block or return
32417a519f9SDimitry Andric   // edges will be *really* confused.
32533956c43SDimitry Andric   bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
32633956c43SDimitry Andric   bool HasOnlyLifetimeMarkers =
32733956c43SDimitry Andric       HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
32833956c43SDimitry Andric   bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
32933956c43SDimitry Andric   if (HasCleanups) {
330284c1978SDimitry Andric     // Make sure the line table doesn't jump back into the body for
331284c1978SDimitry Andric     // the ret after it's been at EndLoc.
332284c1978SDimitry Andric     if (CGDebugInfo *DI = getDebugInfo())
333284c1978SDimitry Andric       if (OnlySimpleReturnStmts)
334284c1978SDimitry Andric         DI->EmitLocation(Builder, EndLoc);
33533956c43SDimitry Andric 
33633956c43SDimitry Andric     PopCleanupBlocks(PrologueCleanupDepth);
337284c1978SDimitry Andric   }
33817a519f9SDimitry Andric 
339f22ef01cSRoman Divacky   // Emit function epilog (to return).
34039d628a0SDimitry Andric   llvm::DebugLoc Loc = EmitReturnBlock();
341f22ef01cSRoman Divacky 
3422754fe60SDimitry Andric   if (ShouldInstrumentFunction())
343ffd1746dSEd Schouten     EmitFunctionInstrumentation("__cyg_profile_func_exit");
344ffd1746dSEd Schouten 
345f22ef01cSRoman Divacky   // Emit debug descriptor for function end.
34639d628a0SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
347e580952dSDimitry Andric     DI->EmitFunctionEnd(Builder);
348f22ef01cSRoman Divacky 
34939d628a0SDimitry Andric   // Reset the debug location to that of the simple 'return' expression, if any
35039d628a0SDimitry Andric   // rather than that of the end of the function's scope '}'.
35139d628a0SDimitry Andric   ApplyDebugLocation AL(*this, Loc);
352f785676fSDimitry Andric   EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
353f22ef01cSRoman Divacky   EmitEndEHSpec(CurCodeDecl);
354f22ef01cSRoman Divacky 
355ffd1746dSEd Schouten   assert(EHStack.empty() &&
356ffd1746dSEd Schouten          "did not remove all scopes from cleanup stack!");
357ffd1746dSEd Schouten 
358f22ef01cSRoman Divacky   // If someone did an indirect goto, emit the indirect goto block at the end of
359f22ef01cSRoman Divacky   // the function.
360f22ef01cSRoman Divacky   if (IndirectBranch) {
361f22ef01cSRoman Divacky     EmitBlock(IndirectBranch->getParent());
362f22ef01cSRoman Divacky     Builder.ClearInsertionPoint();
363f22ef01cSRoman Divacky   }
364f22ef01cSRoman Divacky 
365875ed548SDimitry Andric   // If some of our locals escaped, insert a call to llvm.localescape in the
36633956c43SDimitry Andric   // entry block.
36733956c43SDimitry Andric   if (!EscapedLocals.empty()) {
36833956c43SDimitry Andric     // Invert the map from local to index into a simple vector. There should be
36933956c43SDimitry Andric     // no holes.
37033956c43SDimitry Andric     SmallVector<llvm::Value *, 4> EscapeArgs;
37133956c43SDimitry Andric     EscapeArgs.resize(EscapedLocals.size());
37233956c43SDimitry Andric     for (auto &Pair : EscapedLocals)
37333956c43SDimitry Andric       EscapeArgs[Pair.second] = Pair.first;
37433956c43SDimitry Andric     llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
375875ed548SDimitry Andric         &CGM.getModule(), llvm::Intrinsic::localescape);
3760623d748SDimitry Andric     CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
37733956c43SDimitry Andric   }
37833956c43SDimitry Andric 
379f22ef01cSRoman Divacky   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
380f22ef01cSRoman Divacky   llvm::Instruction *Ptr = AllocaInsertPt;
38159d1ed5bSDimitry Andric   AllocaInsertPt = nullptr;
382f22ef01cSRoman Divacky   Ptr->eraseFromParent();
383f22ef01cSRoman Divacky 
384f22ef01cSRoman Divacky   // If someone took the address of a label but never did an indirect goto, we
385f22ef01cSRoman Divacky   // made a zero entry PHI node, which is illegal, zap it now.
386f22ef01cSRoman Divacky   if (IndirectBranch) {
387f22ef01cSRoman Divacky     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
388f22ef01cSRoman Divacky     if (PN->getNumIncomingValues() == 0) {
389f22ef01cSRoman Divacky       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
390f22ef01cSRoman Divacky       PN->eraseFromParent();
391f22ef01cSRoman Divacky     }
392f22ef01cSRoman Divacky   }
393ffd1746dSEd Schouten 
3946122f3e6SDimitry Andric   EmitIfUsed(*this, EHResumeBlock);
395ffd1746dSEd Schouten   EmitIfUsed(*this, TerminateLandingPad);
396ffd1746dSEd Schouten   EmitIfUsed(*this, TerminateHandler);
397ffd1746dSEd Schouten   EmitIfUsed(*this, UnreachableBlock);
398ffd1746dSEd Schouten 
399ffd1746dSEd Schouten   if (CGM.getCodeGenOpts().EmitDeclMetadata)
400ffd1746dSEd Schouten     EmitDeclMetadata();
40159d1ed5bSDimitry Andric 
40259d1ed5bSDimitry Andric   for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
40359d1ed5bSDimitry Andric            I = DeferredReplacements.begin(),
40459d1ed5bSDimitry Andric            E = DeferredReplacements.end();
40559d1ed5bSDimitry Andric        I != E; ++I) {
40659d1ed5bSDimitry Andric     I->first->replaceAllUsesWith(I->second);
40759d1ed5bSDimitry Andric     I->first->eraseFromParent();
40859d1ed5bSDimitry Andric   }
409ffd1746dSEd Schouten }
410ffd1746dSEd Schouten 
411ffd1746dSEd Schouten /// ShouldInstrumentFunction - Return true if the current function should be
412ffd1746dSEd Schouten /// instrumented with __cyg_profile_func_* calls
413ffd1746dSEd Schouten bool CodeGenFunction::ShouldInstrumentFunction() {
414ffd1746dSEd Schouten   if (!CGM.getCodeGenOpts().InstrumentFunctions)
415ffd1746dSEd Schouten     return false;
416bd5abe19SDimitry Andric   if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
417ffd1746dSEd Schouten     return false;
418ffd1746dSEd Schouten   return true;
419ffd1746dSEd Schouten }
420ffd1746dSEd Schouten 
421e7145dcbSDimitry Andric /// ShouldXRayInstrument - Return true if the current function should be
422e7145dcbSDimitry Andric /// instrumented with XRay nop sleds.
423e7145dcbSDimitry Andric bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
424e7145dcbSDimitry Andric   return CGM.getCodeGenOpts().XRayInstrumentFunctions;
425e7145dcbSDimitry Andric }
426e7145dcbSDimitry Andric 
427ffd1746dSEd Schouten /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
428ffd1746dSEd Schouten /// instrumentation function with the current function and the call site, if
429ffd1746dSEd Schouten /// function instrumentation is enabled.
430ffd1746dSEd Schouten void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
431e7145dcbSDimitry Andric   auto NL = ApplyDebugLocation::CreateArtificial(*this);
432ffd1746dSEd Schouten   // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
43317a519f9SDimitry Andric   llvm::PointerType *PointerTy = Int8PtrTy;
43417a519f9SDimitry Andric   llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
4356122f3e6SDimitry Andric   llvm::FunctionType *FunctionTy =
436dff0c46cSDimitry Andric     llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
437ffd1746dSEd Schouten 
438ffd1746dSEd Schouten   llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
439ffd1746dSEd Schouten   llvm::CallInst *CallSite = Builder.CreateCall(
44017a519f9SDimitry Andric     CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
441ffd1746dSEd Schouten     llvm::ConstantInt::get(Int32Ty, 0),
442ffd1746dSEd Schouten     "callsite");
443ffd1746dSEd Schouten 
444139f7f9bSDimitry Andric   llvm::Value *args[] = {
445ffd1746dSEd Schouten     llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
446139f7f9bSDimitry Andric     CallSite
447139f7f9bSDimitry Andric   };
448139f7f9bSDimitry Andric 
449139f7f9bSDimitry Andric   EmitNounwindRuntimeCall(F, args);
450f22ef01cSRoman Divacky }
451f22ef01cSRoman Divacky 
45244290647SDimitry Andric static void removeImageAccessQualifier(std::string& TyName) {
45344290647SDimitry Andric   std::string ReadOnlyQual("__read_only");
45444290647SDimitry Andric   std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
45544290647SDimitry Andric   if (ReadOnlyPos != std::string::npos)
45644290647SDimitry Andric     // "+ 1" for the space after access qualifier.
45744290647SDimitry Andric     TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
45844290647SDimitry Andric   else {
45944290647SDimitry Andric     std::string WriteOnlyQual("__write_only");
46044290647SDimitry Andric     std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
46144290647SDimitry Andric     if (WriteOnlyPos != std::string::npos)
46244290647SDimitry Andric       TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
46344290647SDimitry Andric     else {
46444290647SDimitry Andric       std::string ReadWriteQual("__read_write");
46544290647SDimitry Andric       std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
46644290647SDimitry Andric       if (ReadWritePos != std::string::npos)
46744290647SDimitry Andric         TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
46844290647SDimitry Andric     }
46944290647SDimitry Andric   }
4702754fe60SDimitry Andric }
4712754fe60SDimitry Andric 
472f41fbc90SDimitry Andric // Returns the address space id that should be produced to the
473f41fbc90SDimitry Andric // kernel_arg_addr_space metadata. This is always fixed to the ids
474f41fbc90SDimitry Andric // as specified in the SPIR 2.0 specification in order to differentiate
475f41fbc90SDimitry Andric // for example in clGetKernelArgInfo() implementation between the address
476f41fbc90SDimitry Andric // spaces with targets without unique mapping to the OpenCL address spaces
477f41fbc90SDimitry Andric // (basically all single AS CPUs).
478f41fbc90SDimitry Andric static unsigned ArgInfoAddressSpace(unsigned LangAS) {
479f41fbc90SDimitry Andric   switch (LangAS) {
480f41fbc90SDimitry Andric   case LangAS::opencl_global:   return 1;
481f41fbc90SDimitry Andric   case LangAS::opencl_constant: return 2;
482f41fbc90SDimitry Andric   case LangAS::opencl_local:    return 3;
483f41fbc90SDimitry Andric   case LangAS::opencl_generic:  return 4; // Not in SPIR 2.0 specs.
484f41fbc90SDimitry Andric   default:
485f41fbc90SDimitry Andric     return 0; // Assume private.
486f41fbc90SDimitry Andric   }
487f41fbc90SDimitry Andric }
488f41fbc90SDimitry Andric 
4897ae0e2c9SDimitry Andric // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
4907ae0e2c9SDimitry Andric // information in the program executable. The argument information stored
4917ae0e2c9SDimitry Andric // includes the argument name, its type, the address and access qualifiers used.
4927ae0e2c9SDimitry Andric static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
4937ae0e2c9SDimitry Andric                                  CodeGenModule &CGM, llvm::LLVMContext &Context,
494139f7f9bSDimitry Andric                                  CGBuilderTy &Builder, ASTContext &ASTCtx) {
495139f7f9bSDimitry Andric   // Create MDNodes that represent the kernel arg metadata.
4967ae0e2c9SDimitry Andric   // Each MDNode is a list in the form of "key", N number of values which is
4977ae0e2c9SDimitry Andric   // the same number of values as their are kernel arguments.
4987ae0e2c9SDimitry Andric 
49959d1ed5bSDimitry Andric   const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
50059d1ed5bSDimitry Andric 
501139f7f9bSDimitry Andric   // MDNode for the kernel argument address space qualifiers.
50239d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> addressQuals;
503139f7f9bSDimitry Andric 
504139f7f9bSDimitry Andric   // MDNode for the kernel argument access qualifiers (images only).
50539d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> accessQuals;
506139f7f9bSDimitry Andric 
507139f7f9bSDimitry Andric   // MDNode for the kernel argument type names.
50839d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeNames;
509139f7f9bSDimitry Andric 
51039d628a0SDimitry Andric   // MDNode for the kernel argument base type names.
51139d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
51239d628a0SDimitry Andric 
513139f7f9bSDimitry Andric   // MDNode for the kernel argument type qualifiers.
51439d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeQuals;
515139f7f9bSDimitry Andric 
5167ae0e2c9SDimitry Andric   // MDNode for the kernel argument names.
51739d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argNames;
5187ae0e2c9SDimitry Andric 
5197ae0e2c9SDimitry Andric   for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
5207ae0e2c9SDimitry Andric     const ParmVarDecl *parm = FD->getParamDecl(i);
521139f7f9bSDimitry Andric     QualType ty = parm->getType();
522139f7f9bSDimitry Andric     std::string typeQuals;
523139f7f9bSDimitry Andric 
524139f7f9bSDimitry Andric     if (ty->isPointerType()) {
525139f7f9bSDimitry Andric       QualType pointeeTy = ty->getPointeeType();
526139f7f9bSDimitry Andric 
527139f7f9bSDimitry Andric       // Get address qualifier.
52839d628a0SDimitry Andric       addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
529f41fbc90SDimitry Andric         ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
530139f7f9bSDimitry Andric 
531139f7f9bSDimitry Andric       // Get argument type name.
53259d1ed5bSDimitry Andric       std::string typeName =
53359d1ed5bSDimitry Andric           pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
534139f7f9bSDimitry Andric 
535139f7f9bSDimitry Andric       // Turn "unsigned type" to "utype"
536139f7f9bSDimitry Andric       std::string::size_type pos = typeName.find("unsigned");
53739d628a0SDimitry Andric       if (pointeeTy.isCanonical() && pos != std::string::npos)
538139f7f9bSDimitry Andric         typeName.erase(pos+1, 8);
539139f7f9bSDimitry Andric 
540139f7f9bSDimitry Andric       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
541139f7f9bSDimitry Andric 
54239d628a0SDimitry Andric       std::string baseTypeName =
54339d628a0SDimitry Andric           pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
54439d628a0SDimitry Andric               Policy) +
54539d628a0SDimitry Andric           "*";
54639d628a0SDimitry Andric 
54739d628a0SDimitry Andric       // Turn "unsigned type" to "utype"
54839d628a0SDimitry Andric       pos = baseTypeName.find("unsigned");
54939d628a0SDimitry Andric       if (pos != std::string::npos)
55039d628a0SDimitry Andric         baseTypeName.erase(pos+1, 8);
55139d628a0SDimitry Andric 
55239d628a0SDimitry Andric       argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
55339d628a0SDimitry Andric 
554139f7f9bSDimitry Andric       // Get argument type qualifiers:
555139f7f9bSDimitry Andric       if (ty.isRestrictQualified())
556139f7f9bSDimitry Andric         typeQuals = "restrict";
557139f7f9bSDimitry Andric       if (pointeeTy.isConstQualified() ||
558139f7f9bSDimitry Andric           (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
559139f7f9bSDimitry Andric         typeQuals += typeQuals.empty() ? "const" : " const";
560139f7f9bSDimitry Andric       if (pointeeTy.isVolatileQualified())
561139f7f9bSDimitry Andric         typeQuals += typeQuals.empty() ? "volatile" : " volatile";
562139f7f9bSDimitry Andric     } else {
56359d1ed5bSDimitry Andric       uint32_t AddrSpc = 0;
564444ed5c5SDimitry Andric       bool isPipe = ty->isPipeType();
565444ed5c5SDimitry Andric       if (ty->isImageType() || isPipe)
566f41fbc90SDimitry Andric         AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
56759d1ed5bSDimitry Andric 
56839d628a0SDimitry Andric       addressQuals.push_back(
56939d628a0SDimitry Andric           llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
570139f7f9bSDimitry Andric 
571139f7f9bSDimitry Andric       // Get argument type name.
572444ed5c5SDimitry Andric       std::string typeName;
573444ed5c5SDimitry Andric       if (isPipe)
574e7145dcbSDimitry Andric         typeName = ty.getCanonicalType()->getAs<PipeType>()->getElementType()
575e7145dcbSDimitry Andric                      .getAsString(Policy);
576444ed5c5SDimitry Andric       else
577444ed5c5SDimitry Andric         typeName = ty.getUnqualifiedType().getAsString(Policy);
578139f7f9bSDimitry Andric 
579139f7f9bSDimitry Andric       // Turn "unsigned type" to "utype"
580139f7f9bSDimitry Andric       std::string::size_type pos = typeName.find("unsigned");
58139d628a0SDimitry Andric       if (ty.isCanonical() && pos != std::string::npos)
582139f7f9bSDimitry Andric         typeName.erase(pos+1, 8);
583139f7f9bSDimitry Andric 
584444ed5c5SDimitry Andric       std::string baseTypeName;
585444ed5c5SDimitry Andric       if (isPipe)
586e7145dcbSDimitry Andric         baseTypeName = ty.getCanonicalType()->getAs<PipeType>()
587e7145dcbSDimitry Andric                           ->getElementType().getCanonicalType()
588e7145dcbSDimitry Andric                           .getAsString(Policy);
589444ed5c5SDimitry Andric       else
590444ed5c5SDimitry Andric         baseTypeName =
59139d628a0SDimitry Andric           ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
59239d628a0SDimitry Andric 
59344290647SDimitry Andric       // Remove access qualifiers on images
59444290647SDimitry Andric       // (as they are inseparable from type in clang implementation,
59544290647SDimitry Andric       // but OpenCL spec provides a special query to get access qualifier
59644290647SDimitry Andric       // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
59744290647SDimitry Andric       if (ty->isImageType()) {
59844290647SDimitry Andric         removeImageAccessQualifier(typeName);
59944290647SDimitry Andric         removeImageAccessQualifier(baseTypeName);
60044290647SDimitry Andric       }
60144290647SDimitry Andric 
60244290647SDimitry Andric       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
60344290647SDimitry Andric 
60439d628a0SDimitry Andric       // Turn "unsigned type" to "utype"
60539d628a0SDimitry Andric       pos = baseTypeName.find("unsigned");
60639d628a0SDimitry Andric       if (pos != std::string::npos)
60739d628a0SDimitry Andric         baseTypeName.erase(pos+1, 8);
60839d628a0SDimitry Andric 
60939d628a0SDimitry Andric       argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
61039d628a0SDimitry Andric 
611139f7f9bSDimitry Andric       // Get argument type qualifiers:
612139f7f9bSDimitry Andric       if (ty.isConstQualified())
613139f7f9bSDimitry Andric         typeQuals = "const";
614139f7f9bSDimitry Andric       if (ty.isVolatileQualified())
615139f7f9bSDimitry Andric         typeQuals += typeQuals.empty() ? "volatile" : " volatile";
616444ed5c5SDimitry Andric       if (isPipe)
617444ed5c5SDimitry Andric         typeQuals = "pipe";
618139f7f9bSDimitry Andric     }
619139f7f9bSDimitry Andric 
620139f7f9bSDimitry Andric     argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
621139f7f9bSDimitry Andric 
622444ed5c5SDimitry Andric     // Get image and pipe access qualifier:
623444ed5c5SDimitry Andric     if (ty->isImageType()|| ty->isPipeType()) {
624e7145dcbSDimitry Andric       const OpenCLAccessAttr *A = parm->getAttr<OpenCLAccessAttr>();
62559d1ed5bSDimitry Andric       if (A && A->isWriteOnly())
626139f7f9bSDimitry Andric         accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
627e7145dcbSDimitry Andric       else if (A && A->isReadWrite())
628e7145dcbSDimitry Andric         accessQuals.push_back(llvm::MDString::get(Context, "read_write"));
629139f7f9bSDimitry Andric       else
630139f7f9bSDimitry Andric         accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
631139f7f9bSDimitry Andric     } else
632139f7f9bSDimitry Andric       accessQuals.push_back(llvm::MDString::get(Context, "none"));
6337ae0e2c9SDimitry Andric 
6347ae0e2c9SDimitry Andric     // Get argument name.
6357ae0e2c9SDimitry Andric     argNames.push_back(llvm::MDString::get(Context, parm->getName()));
6367ae0e2c9SDimitry Andric   }
637139f7f9bSDimitry Andric 
638e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_addr_space",
639e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, addressQuals));
640e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_access_qual",
641e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, accessQuals));
642e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_type",
643e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, argTypeNames));
644e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_base_type",
645e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, argBaseTypeNames));
646e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_type_qual",
647e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, argTypeQuals));
64839d628a0SDimitry Andric   if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
649e7145dcbSDimitry Andric     Fn->setMetadata("kernel_arg_name",
650e7145dcbSDimitry Andric                     llvm::MDNode::get(Context, argNames));
6517ae0e2c9SDimitry Andric }
6527ae0e2c9SDimitry Andric 
6537ae0e2c9SDimitry Andric void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
6547ae0e2c9SDimitry Andric                                                llvm::Function *Fn)
6557ae0e2c9SDimitry Andric {
6567ae0e2c9SDimitry Andric   if (!FD->hasAttr<OpenCLKernelAttr>())
6577ae0e2c9SDimitry Andric     return;
6587ae0e2c9SDimitry Andric 
6597ae0e2c9SDimitry Andric   llvm::LLVMContext &Context = getLLVMContext();
6607ae0e2c9SDimitry Andric 
661e7145dcbSDimitry Andric   GenOpenCLArgMetadata(FD, Fn, CGM, Context, Builder, getContext());
662139f7f9bSDimitry Andric 
66359d1ed5bSDimitry Andric   if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
66459d1ed5bSDimitry Andric     QualType hintQTy = A->getTypeHint();
665139f7f9bSDimitry Andric     const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
666139f7f9bSDimitry Andric     bool isSignedInteger =
667139f7f9bSDimitry Andric         hintQTy->isSignedIntegerType() ||
668139f7f9bSDimitry Andric         (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
66939d628a0SDimitry Andric     llvm::Metadata *attrMDArgs[] = {
67039d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
67139d628a0SDimitry Andric             CGM.getTypes().ConvertType(A->getTypeHint()))),
67239d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
673139f7f9bSDimitry Andric             llvm::IntegerType::get(Context, 32),
67439d628a0SDimitry Andric             llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))};
675e7145dcbSDimitry Andric     Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, attrMDArgs));
676139f7f9bSDimitry Andric   }
6777ae0e2c9SDimitry Andric 
67859d1ed5bSDimitry Andric   if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
67939d628a0SDimitry Andric     llvm::Metadata *attrMDArgs[] = {
68039d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
68139d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
68239d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
683e7145dcbSDimitry Andric     Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, attrMDArgs));
6847ae0e2c9SDimitry Andric   }
6857ae0e2c9SDimitry Andric 
68659d1ed5bSDimitry Andric   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
68739d628a0SDimitry Andric     llvm::Metadata *attrMDArgs[] = {
68839d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
68939d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
69039d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
691e7145dcbSDimitry Andric     Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, attrMDArgs));
6927ae0e2c9SDimitry Andric   }
6937ae0e2c9SDimitry Andric }
6947ae0e2c9SDimitry Andric 
69559d1ed5bSDimitry Andric /// Determine whether the function F ends with a return stmt.
69659d1ed5bSDimitry Andric static bool endsWithReturn(const Decl* F) {
69759d1ed5bSDimitry Andric   const Stmt *Body = nullptr;
69859d1ed5bSDimitry Andric   if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
69959d1ed5bSDimitry Andric     Body = FD->getBody();
70059d1ed5bSDimitry Andric   else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
70159d1ed5bSDimitry Andric     Body = OMD->getBody();
70259d1ed5bSDimitry Andric 
70359d1ed5bSDimitry Andric   if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
70459d1ed5bSDimitry Andric     auto LastStmt = CS->body_rbegin();
70559d1ed5bSDimitry Andric     if (LastStmt != CS->body_rend())
70659d1ed5bSDimitry Andric       return isa<ReturnStmt>(*LastStmt);
70759d1ed5bSDimitry Andric   }
70859d1ed5bSDimitry Andric   return false;
70959d1ed5bSDimitry Andric }
71059d1ed5bSDimitry Andric 
711284c1978SDimitry Andric void CodeGenFunction::StartFunction(GlobalDecl GD,
712284c1978SDimitry Andric                                     QualType RetTy,
713f22ef01cSRoman Divacky                                     llvm::Function *Fn,
7143b0f4066SDimitry Andric                                     const CGFunctionInfo &FnInfo,
715f22ef01cSRoman Divacky                                     const FunctionArgList &Args,
71659d1ed5bSDimitry Andric                                     SourceLocation Loc,
717f22ef01cSRoman Divacky                                     SourceLocation StartLoc) {
71839d628a0SDimitry Andric   assert(!CurFn &&
71939d628a0SDimitry Andric          "Do not use a CodeGenFunction object for more than one function");
72039d628a0SDimitry Andric 
721f22ef01cSRoman Divacky   const Decl *D = GD.getDecl();
722f22ef01cSRoman Divacky 
723f22ef01cSRoman Divacky   DidCallStackSave = false;
724284c1978SDimitry Andric   CurCodeDecl = D;
725e7145dcbSDimitry Andric   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
726e7145dcbSDimitry Andric     if (FD->usesSEHTry())
727e7145dcbSDimitry Andric       CurSEHParent = FD;
72859d1ed5bSDimitry Andric   CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
729f22ef01cSRoman Divacky   FnRetTy = RetTy;
730f22ef01cSRoman Divacky   CurFn = Fn;
7313b0f4066SDimitry Andric   CurFnInfo = &FnInfo;
732f22ef01cSRoman Divacky   assert(CurFn->isDeclaration() && "Function already has body?");
733f22ef01cSRoman Divacky 
73439d628a0SDimitry Andric   if (CGM.isInSanitizerBlacklist(Fn, Loc))
73539d628a0SDimitry Andric     SanOpts.clear();
736139f7f9bSDimitry Andric 
73733956c43SDimitry Andric   if (D) {
73833956c43SDimitry Andric     // Apply the no_sanitize* attributes to SanOpts.
73933956c43SDimitry Andric     for (auto Attr : D->specific_attrs<NoSanitizeAttr>())
74033956c43SDimitry Andric       SanOpts.Mask &= ~Attr->getMask();
74133956c43SDimitry Andric   }
74233956c43SDimitry Andric 
74333956c43SDimitry Andric   // Apply sanitizer attributes to the function.
7448f0fd8f6SDimitry Andric   if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
74533956c43SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
74633956c43SDimitry Andric   if (SanOpts.has(SanitizerKind::Thread))
74733956c43SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeThread);
74833956c43SDimitry Andric   if (SanOpts.has(SanitizerKind::Memory))
74933956c43SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
7508f0fd8f6SDimitry Andric   if (SanOpts.has(SanitizerKind::SafeStack))
7518f0fd8f6SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SafeStack);
75233956c43SDimitry Andric 
75344290647SDimitry Andric   // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
75444290647SDimitry Andric   // .cxx_destruct and all of their calees at run time.
75544290647SDimitry Andric   if (SanOpts.has(SanitizerKind::Thread)) {
75644290647SDimitry Andric     if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
75744290647SDimitry Andric       IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
75844290647SDimitry Andric       if (OMD->getMethodFamily() == OMF_dealloc ||
75944290647SDimitry Andric           OMD->getMethodFamily() == OMF_initialize ||
76044290647SDimitry Andric           (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
76144290647SDimitry Andric         Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
76244290647SDimitry Andric         Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
76344290647SDimitry Andric       }
76444290647SDimitry Andric     }
76544290647SDimitry Andric   }
76644290647SDimitry Andric 
767e7145dcbSDimitry Andric   // Apply xray attributes to the function (as a string, for now)
768e7145dcbSDimitry Andric   if (D && ShouldXRayInstrumentFunction()) {
769e7145dcbSDimitry Andric     if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) {
770e7145dcbSDimitry Andric       if (XRayAttr->alwaysXRayInstrument())
771e7145dcbSDimitry Andric         Fn->addFnAttr("function-instrument", "xray-always");
772e7145dcbSDimitry Andric       if (XRayAttr->neverXRayInstrument())
773e7145dcbSDimitry Andric         Fn->addFnAttr("function-instrument", "xray-never");
774e7145dcbSDimitry Andric     } else {
775e7145dcbSDimitry Andric       Fn->addFnAttr(
776e7145dcbSDimitry Andric           "xray-instruction-threshold",
777e7145dcbSDimitry Andric           llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
778e7145dcbSDimitry Andric     }
779e7145dcbSDimitry Andric   }
780e7145dcbSDimitry Andric 
78144290647SDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
782e7145dcbSDimitry Andric     if (CGM.getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
783e7145dcbSDimitry Andric       CGM.getOpenMPRuntime().emitDeclareSimdFunction(FD, Fn);
784f22ef01cSRoman Divacky 
785e7145dcbSDimitry Andric   // Add no-jump-tables value.
786e7145dcbSDimitry Andric   Fn->addFnAttr("no-jump-tables",
787e7145dcbSDimitry Andric                 llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
788e7145dcbSDimitry Andric 
7893861d79fSDimitry Andric   if (getLangOpts().OpenCL) {
7902754fe60SDimitry Andric     // Add metadata for a kernel function.
7912754fe60SDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
7927ae0e2c9SDimitry Andric       EmitOpenCLKernelMetadata(FD, Fn);
7932754fe60SDimitry Andric   }
7942754fe60SDimitry Andric 
795f785676fSDimitry Andric   // If we are checking function types, emit a function type signature as
79639d628a0SDimitry Andric   // prologue data.
79739d628a0SDimitry Andric   if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
798f785676fSDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
79939d628a0SDimitry Andric       if (llvm::Constant *PrologueSig =
800f785676fSDimitry Andric               CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
801f785676fSDimitry Andric         llvm::Constant *FTRTTIConst =
802f785676fSDimitry Andric             CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
80339d628a0SDimitry Andric         llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst };
80439d628a0SDimitry Andric         llvm::Constant *PrologueStructConst =
80539d628a0SDimitry Andric             llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
80639d628a0SDimitry Andric         Fn->setPrologueData(PrologueStructConst);
807f785676fSDimitry Andric       }
808f785676fSDimitry Andric     }
809f785676fSDimitry Andric   }
810f785676fSDimitry Andric 
8110623d748SDimitry Andric   // If we're in C++ mode and the function name is "main", it is guaranteed
8120623d748SDimitry Andric   // to be norecurse by the standard (3.6.1.3 "The function main shall not be
8130623d748SDimitry Andric   // used within a program").
8140623d748SDimitry Andric   if (getLangOpts().CPlusPlus)
8150623d748SDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
8160623d748SDimitry Andric       if (FD->isMain())
8170623d748SDimitry Andric         Fn->addFnAttr(llvm::Attribute::NoRecurse);
8180623d748SDimitry Andric 
819f22ef01cSRoman Divacky   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
820f22ef01cSRoman Divacky 
821f22ef01cSRoman Divacky   // Create a marker to make it easy to insert allocas into the entryblock
822f22ef01cSRoman Divacky   // later.  Don't create this with the builder, because we don't want it
823f22ef01cSRoman Divacky   // folded.
824ffd1746dSEd Schouten   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
825e7145dcbSDimitry Andric   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
826f22ef01cSRoman Divacky 
827ffd1746dSEd Schouten   ReturnBlock = getJumpDestInCurrentScope("return");
828f22ef01cSRoman Divacky 
829f22ef01cSRoman Divacky   Builder.SetInsertPoint(EntryBB);
830f22ef01cSRoman Divacky 
831f22ef01cSRoman Divacky   // Emit subprogram debug descriptor.
832f22ef01cSRoman Divacky   if (CGDebugInfo *DI = getDebugInfo()) {
833e7145dcbSDimitry Andric     // Reconstruct the type from the argument list so that implicit parameters,
834e7145dcbSDimitry Andric     // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
835e7145dcbSDimitry Andric     // convention.
836e7145dcbSDimitry Andric     CallingConv CC = CallingConv::CC_C;
837e7145dcbSDimitry Andric     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D))
838e7145dcbSDimitry Andric       if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
839e7145dcbSDimitry Andric         CC = SrcFnTy->getCallConv();
840139f7f9bSDimitry Andric     SmallVector<QualType, 16> ArgTypes;
841e7145dcbSDimitry Andric     for (const VarDecl *VD : Args)
842e7145dcbSDimitry Andric       ArgTypes.push_back(VD->getType());
843e7145dcbSDimitry Andric     QualType FnType = getContext().getFunctionType(
844e7145dcbSDimitry Andric         RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
84559d1ed5bSDimitry Andric     DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder);
846f22ef01cSRoman Divacky   }
847f22ef01cSRoman Divacky 
8482754fe60SDimitry Andric   if (ShouldInstrumentFunction())
849ffd1746dSEd Schouten     EmitFunctionInstrumentation("__cyg_profile_func_enter");
850ffd1746dSEd Schouten 
85144290647SDimitry Andric   // Since emitting the mcount call here impacts optimizations such as function
85244290647SDimitry Andric   // inlining, we just add an attribute to insert a mcount call in backend.
85344290647SDimitry Andric   // The attribute "counting-function" is set to mcount function name which is
85444290647SDimitry Andric   // architecture dependent.
8552754fe60SDimitry Andric   if (CGM.getCodeGenOpts().InstrumentForProfiling)
85644290647SDimitry Andric     Fn->addFnAttr("counting-function", getTarget().getMCountName());
8572754fe60SDimitry Andric 
858f22ef01cSRoman Divacky   if (RetTy->isVoidType()) {
859f22ef01cSRoman Divacky     // Void type; nothing to return.
8600623d748SDimitry Andric     ReturnValue = Address::invalid();
86159d1ed5bSDimitry Andric 
86259d1ed5bSDimitry Andric     // Count the implicit return.
86359d1ed5bSDimitry Andric     if (!endsWithReturn(D))
86459d1ed5bSDimitry Andric       ++NumReturnExprs;
865f22ef01cSRoman Divacky   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
866139f7f9bSDimitry Andric              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
867f22ef01cSRoman Divacky     // Indirect aggregate return; emit returned value directly into sret slot.
868f22ef01cSRoman Divacky     // This reduces code size, and affects correctness in C++.
86959d1ed5bSDimitry Andric     auto AI = CurFn->arg_begin();
87059d1ed5bSDimitry Andric     if (CurFnInfo->getReturnInfo().isSRetAfterThis())
87159d1ed5bSDimitry Andric       ++AI;
8720623d748SDimitry Andric     ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
87359d1ed5bSDimitry Andric   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
87459d1ed5bSDimitry Andric              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
87559d1ed5bSDimitry Andric     // Load the sret pointer from the argument struct and return into that.
87659d1ed5bSDimitry Andric     unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
87759d1ed5bSDimitry Andric     llvm::Function::arg_iterator EI = CurFn->arg_end();
87859d1ed5bSDimitry Andric     --EI;
8790623d748SDimitry Andric     llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
8800623d748SDimitry Andric     Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
8810623d748SDimitry Andric     ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
882f22ef01cSRoman Divacky   } else {
883f22ef01cSRoman Divacky     ReturnValue = CreateIRTemp(RetTy, "retval");
88417a519f9SDimitry Andric 
88517a519f9SDimitry Andric     // Tell the epilog emitter to autorelease the result.  We do this
88617a519f9SDimitry Andric     // now so that various specialized functions can suppress it
88717a519f9SDimitry Andric     // during their IR-generation.
888dff0c46cSDimitry Andric     if (getLangOpts().ObjCAutoRefCount &&
88917a519f9SDimitry Andric         !CurFnInfo->isReturnsRetained() &&
89017a519f9SDimitry Andric         RetTy->isObjCRetainableType())
89117a519f9SDimitry Andric       AutoreleaseResult = true;
892f22ef01cSRoman Divacky   }
893f22ef01cSRoman Divacky 
894f22ef01cSRoman Divacky   EmitStartEHSpec(CurCodeDecl);
89517a519f9SDimitry Andric 
89617a519f9SDimitry Andric   PrologueCleanupDepth = EHStack.stable_begin();
897f22ef01cSRoman Divacky   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
898f22ef01cSRoman Divacky 
899dff0c46cSDimitry Andric   if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
900e580952dSDimitry Andric     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
901dff0c46cSDimitry Andric     const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
902dff0c46cSDimitry Andric     if (MD->getParent()->isLambda() &&
903dff0c46cSDimitry Andric         MD->getOverloadedOperator() == OO_Call) {
904dff0c46cSDimitry Andric       // We're in a lambda; figure out the captures.
905dff0c46cSDimitry Andric       MD->getParent()->getCaptureFields(LambdaCaptureFields,
906dff0c46cSDimitry Andric                                         LambdaThisCaptureField);
907dff0c46cSDimitry Andric       if (LambdaThisCaptureField) {
908e7145dcbSDimitry Andric         // If the lambda captures the object referred to by '*this' - either by
909e7145dcbSDimitry Andric         // value or by reference, make sure CXXThisValue points to the correct
910e7145dcbSDimitry Andric         // object.
911e7145dcbSDimitry Andric 
912e7145dcbSDimitry Andric         // Get the lvalue for the field (which is a copy of the enclosing object
913e7145dcbSDimitry Andric         // or contains the address of the enclosing object).
914e7145dcbSDimitry Andric         LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
915e7145dcbSDimitry Andric         if (!LambdaThisCaptureField->getType()->isPointerType()) {
916e7145dcbSDimitry Andric           // If the enclosing object was captured by value, just use its address.
917e7145dcbSDimitry Andric           CXXThisValue = ThisFieldLValue.getAddress().getPointer();
918e7145dcbSDimitry Andric         } else {
919e7145dcbSDimitry Andric           // Load the lvalue pointed to by the field, since '*this' was captured
920e7145dcbSDimitry Andric           // by reference.
921e7145dcbSDimitry Andric           CXXThisValue =
922e7145dcbSDimitry Andric               EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
923e7145dcbSDimitry Andric         }
924dff0c46cSDimitry Andric       }
92539d628a0SDimitry Andric       for (auto *FD : MD->getParent()->fields()) {
92639d628a0SDimitry Andric         if (FD->hasCapturedVLAType()) {
92739d628a0SDimitry Andric           auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
92839d628a0SDimitry Andric                                            SourceLocation()).getScalarVal();
92939d628a0SDimitry Andric           auto VAT = FD->getCapturedVLAType();
93039d628a0SDimitry Andric           VLASizeMap[VAT->getSizeExpr()] = ExprArg;
93139d628a0SDimitry Andric         }
93239d628a0SDimitry Andric       }
933dff0c46cSDimitry Andric     } else {
934dff0c46cSDimitry Andric       // Not in a lambda; just use 'this' from the method.
935dff0c46cSDimitry Andric       // FIXME: Should we generate a new load for each use of 'this'?  The
936dff0c46cSDimitry Andric       // fast register allocator would be happier...
937dff0c46cSDimitry Andric       CXXThisValue = CXXABIThisValue;
938dff0c46cSDimitry Andric     }
939dff0c46cSDimitry Andric   }
940f22ef01cSRoman Divacky 
941f22ef01cSRoman Divacky   // If any of the arguments have a variably modified type, make sure to
942f22ef01cSRoman Divacky   // emit the type size.
943f22ef01cSRoman Divacky   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
944f22ef01cSRoman Divacky        i != e; ++i) {
945139f7f9bSDimitry Andric     const VarDecl *VD = *i;
946139f7f9bSDimitry Andric 
947139f7f9bSDimitry Andric     // Dig out the type as written from ParmVarDecls; it's unclear whether
948139f7f9bSDimitry Andric     // the standard (C99 6.9.1p10) requires this, but we're following the
949139f7f9bSDimitry Andric     // precedent set by gcc.
950139f7f9bSDimitry Andric     QualType Ty;
951139f7f9bSDimitry Andric     if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
952139f7f9bSDimitry Andric       Ty = PVD->getOriginalType();
953139f7f9bSDimitry Andric     else
954139f7f9bSDimitry Andric       Ty = VD->getType();
955f22ef01cSRoman Divacky 
956f22ef01cSRoman Divacky     if (Ty->isVariablyModifiedType())
95717a519f9SDimitry Andric       EmitVariablyModifiedType(Ty);
958f22ef01cSRoman Divacky   }
9596122f3e6SDimitry Andric   // Emit a location at the end of the prologue.
9606122f3e6SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
9616122f3e6SDimitry Andric     DI->EmitLocation(Builder, StartLoc);
962f22ef01cSRoman Divacky }
963f22ef01cSRoman Divacky 
964f785676fSDimitry Andric void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
965f785676fSDimitry Andric                                        const Stmt *Body) {
96633956c43SDimitry Andric   incrementProfileCounter(Body);
967f785676fSDimitry Andric   if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
968139f7f9bSDimitry Andric     EmitCompoundStmtWithoutScope(*S);
969139f7f9bSDimitry Andric   else
970f785676fSDimitry Andric     EmitStmt(Body);
971f22ef01cSRoman Divacky }
972f22ef01cSRoman Divacky 
97359d1ed5bSDimitry Andric /// When instrumenting to collect profile data, the counts for some blocks
97459d1ed5bSDimitry Andric /// such as switch cases need to not include the fall-through counts, so
97559d1ed5bSDimitry Andric /// emit a branch around the instrumentation code. When not instrumenting,
97659d1ed5bSDimitry Andric /// this just calls EmitBlock().
97759d1ed5bSDimitry Andric void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
97833956c43SDimitry Andric                                                const Stmt *S) {
97959d1ed5bSDimitry Andric   llvm::BasicBlock *SkipCountBB = nullptr;
980e7145dcbSDimitry Andric   if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
98159d1ed5bSDimitry Andric     // When instrumenting for profiling, the fallthrough to certain
98259d1ed5bSDimitry Andric     // statements needs to skip over the instrumentation code so that we
98359d1ed5bSDimitry Andric     // get an accurate count.
98459d1ed5bSDimitry Andric     SkipCountBB = createBasicBlock("skipcount");
98559d1ed5bSDimitry Andric     EmitBranch(SkipCountBB);
98659d1ed5bSDimitry Andric   }
98759d1ed5bSDimitry Andric   EmitBlock(BB);
98833956c43SDimitry Andric   uint64_t CurrentCount = getCurrentProfileCount();
98933956c43SDimitry Andric   incrementProfileCounter(S);
99033956c43SDimitry Andric   setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
99159d1ed5bSDimitry Andric   if (SkipCountBB)
99259d1ed5bSDimitry Andric     EmitBlock(SkipCountBB);
99359d1ed5bSDimitry Andric }
99459d1ed5bSDimitry Andric 
995e580952dSDimitry Andric /// Tries to mark the given function nounwind based on the
996e580952dSDimitry Andric /// non-existence of any throwing calls within it.  We believe this is
997e580952dSDimitry Andric /// lightweight enough to do at -O0.
998e580952dSDimitry Andric static void TryMarkNoThrow(llvm::Function *F) {
999e580952dSDimitry Andric   // LLVM treats 'nounwind' on a function as part of the type, so we
1000e580952dSDimitry Andric   // can't do this on functions that can be overwritten.
1001e7145dcbSDimitry Andric   if (F->isInterposable()) return;
1002e580952dSDimitry Andric 
10030623d748SDimitry Andric   for (llvm::BasicBlock &BB : *F)
10040623d748SDimitry Andric     for (llvm::Instruction &I : BB)
10050623d748SDimitry Andric       if (I.mayThrow())
1006e580952dSDimitry Andric         return;
10070623d748SDimitry Andric 
10083861d79fSDimitry Andric   F->setDoesNotThrow();
1009e580952dSDimitry Andric }
1010e580952dSDimitry Andric 
1011e7145dcbSDimitry Andric QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
1012e7145dcbSDimitry Andric                                                FunctionArgList &Args) {
1013f22ef01cSRoman Divacky   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
101459d1ed5bSDimitry Andric   QualType ResTy = FD->getReturnType();
1015f22ef01cSRoman Divacky 
101659d1ed5bSDimitry Andric   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
101759d1ed5bSDimitry Andric   if (MD && MD->isInstance()) {
1018f785676fSDimitry Andric     if (CGM.getCXXABI().HasThisReturn(GD))
1019f785676fSDimitry Andric       ResTy = MD->getThisType(getContext());
102039d628a0SDimitry Andric     else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
102139d628a0SDimitry Andric       ResTy = CGM.getContext().VoidPtrTy;
102259d1ed5bSDimitry Andric     CGM.getCXXABI().buildThisParam(*this, Args);
1023f785676fSDimitry Andric   }
1024f22ef01cSRoman Divacky 
1025e7145dcbSDimitry Andric   // The base version of an inheriting constructor whose constructed base is a
1026e7145dcbSDimitry Andric   // virtual base is not passed any arguments (because it doesn't actually call
1027e7145dcbSDimitry Andric   // the inherited constructor).
1028e7145dcbSDimitry Andric   bool PassedParams = true;
1029e7145dcbSDimitry Andric   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
1030e7145dcbSDimitry Andric     if (auto Inherited = CD->getInheritedConstructor())
1031e7145dcbSDimitry Andric       PassedParams =
1032e7145dcbSDimitry Andric           getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
1033e7145dcbSDimitry Andric 
1034e7145dcbSDimitry Andric   if (PassedParams) {
1035e7145dcbSDimitry Andric     for (auto *Param : FD->parameters()) {
10360623d748SDimitry Andric       Args.push_back(Param);
10370623d748SDimitry Andric       if (!Param->hasAttr<PassObjectSizeAttr>())
10380623d748SDimitry Andric         continue;
10390623d748SDimitry Andric 
10400623d748SDimitry Andric       IdentifierInfo *NoID = nullptr;
10410623d748SDimitry Andric       auto *Implicit = ImplicitParamDecl::Create(
10420623d748SDimitry Andric           getContext(), Param->getDeclContext(), Param->getLocation(), NoID,
10430623d748SDimitry Andric           getContext().getSizeType());
10440623d748SDimitry Andric       SizeArguments[Param] = Implicit;
10450623d748SDimitry Andric       Args.push_back(Implicit);
10460623d748SDimitry Andric     }
1047e7145dcbSDimitry Andric   }
1048f22ef01cSRoman Divacky 
104959d1ed5bSDimitry Andric   if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
105059d1ed5bSDimitry Andric     CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
105159d1ed5bSDimitry Andric 
1052e7145dcbSDimitry Andric   return ResTy;
1053e7145dcbSDimitry Andric }
1054e7145dcbSDimitry Andric 
10558e0f8b8cSDimitry Andric static bool
10568e0f8b8cSDimitry Andric shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD,
10578e0f8b8cSDimitry Andric                                              const ASTContext &Context) {
10588e0f8b8cSDimitry Andric   QualType T = FD->getReturnType();
10598e0f8b8cSDimitry Andric   // Avoid the optimization for functions that return a record type with a
10608e0f8b8cSDimitry Andric   // trivial destructor or another trivially copyable type.
10618e0f8b8cSDimitry Andric   if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) {
10628e0f8b8cSDimitry Andric     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
10638e0f8b8cSDimitry Andric       return !ClassDecl->hasTrivialDestructor();
10648e0f8b8cSDimitry Andric   }
10658e0f8b8cSDimitry Andric   return !T.isTriviallyCopyableType(Context);
10668e0f8b8cSDimitry Andric }
10678e0f8b8cSDimitry Andric 
1068e7145dcbSDimitry Andric void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1069e7145dcbSDimitry Andric                                    const CGFunctionInfo &FnInfo) {
1070e7145dcbSDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1071e7145dcbSDimitry Andric   CurGD = GD;
1072e7145dcbSDimitry Andric 
1073e7145dcbSDimitry Andric   FunctionArgList Args;
1074e7145dcbSDimitry Andric   QualType ResTy = BuildFunctionArgList(GD, Args);
1075e7145dcbSDimitry Andric 
1076e7145dcbSDimitry Andric   // Check if we should generate debug info for this function.
1077e7145dcbSDimitry Andric   if (FD->hasAttr<NoDebugAttr>())
1078e7145dcbSDimitry Andric     DebugInfo = nullptr; // disable debug info indefinitely for this function
1079e7145dcbSDimitry Andric 
1080f22ef01cSRoman Divacky   SourceRange BodyRange;
1081f22ef01cSRoman Divacky   if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
1082f785676fSDimitry Andric   CurEHLocation = BodyRange.getEnd();
1083139f7f9bSDimitry Andric 
108459d1ed5bSDimitry Andric   // Use the location of the start of the function to determine where
108559d1ed5bSDimitry Andric   // the function definition is located. By default use the location
108659d1ed5bSDimitry Andric   // of the declaration as the location for the subprogram. A function
108759d1ed5bSDimitry Andric   // may lack a declaration in the source code if it is created by code
108859d1ed5bSDimitry Andric   // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
108959d1ed5bSDimitry Andric   SourceLocation Loc = FD->getLocation();
109059d1ed5bSDimitry Andric 
109159d1ed5bSDimitry Andric   // If this is a function specialization then use the pattern body
109259d1ed5bSDimitry Andric   // as the location for the function.
109359d1ed5bSDimitry Andric   if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
109459d1ed5bSDimitry Andric     if (SpecDecl->hasBody(SpecDecl))
109559d1ed5bSDimitry Andric       Loc = SpecDecl->getLocation();
109659d1ed5bSDimitry Andric 
109744290647SDimitry Andric   Stmt *Body = FD->getBody();
109844290647SDimitry Andric 
109944290647SDimitry Andric   // Initialize helper which will detect jumps which can cause invalid lifetime
110044290647SDimitry Andric   // markers.
110144290647SDimitry Andric   if (Body && ShouldEmitLifetimeMarkers)
110244290647SDimitry Andric     Bypasses.Init(Body);
110344290647SDimitry Andric 
1104f22ef01cSRoman Divacky   // Emit the standard function prologue.
110559d1ed5bSDimitry Andric   StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1106f22ef01cSRoman Divacky 
1107f22ef01cSRoman Divacky   // Generate the body of the function.
11080623d748SDimitry Andric   PGO.assignRegionCounters(GD, CurFn);
1109f22ef01cSRoman Divacky   if (isa<CXXDestructorDecl>(FD))
1110f22ef01cSRoman Divacky     EmitDestructorBody(Args);
1111f22ef01cSRoman Divacky   else if (isa<CXXConstructorDecl>(FD))
1112f22ef01cSRoman Divacky     EmitConstructorBody(Args);
11133861d79fSDimitry Andric   else if (getLangOpts().CUDA &&
111433956c43SDimitry Andric            !getLangOpts().CUDAIsDevice &&
11156122f3e6SDimitry Andric            FD->hasAttr<CUDAGlobalAttr>())
111633956c43SDimitry Andric     CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1117dff0c46cSDimitry Andric   else if (isa<CXXConversionDecl>(FD) &&
1118dff0c46cSDimitry Andric            cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
1119dff0c46cSDimitry Andric     // The lambda conversion to block pointer is special; the semantics can't be
1120dff0c46cSDimitry Andric     // expressed in the AST, so IRGen needs to special-case it.
1121dff0c46cSDimitry Andric     EmitLambdaToBlockPointerBody(Args);
1122dff0c46cSDimitry Andric   } else if (isa<CXXMethodDecl>(FD) &&
1123dff0c46cSDimitry Andric              cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1124f785676fSDimitry Andric     // The lambda static invoker function is special, because it forwards or
1125dff0c46cSDimitry Andric     // clones the body of the function call operator (but is actually static).
1126dff0c46cSDimitry Andric     EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
1127139f7f9bSDimitry Andric   } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
1128f785676fSDimitry Andric              (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1129f785676fSDimitry Andric               cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1130139f7f9bSDimitry Andric     // Implicit copy-assignment gets the same special treatment as implicit
1131139f7f9bSDimitry Andric     // copy-constructors.
1132139f7f9bSDimitry Andric     emitImplicitAssignmentOperatorBody(Args);
113344290647SDimitry Andric   } else if (Body) {
1134f785676fSDimitry Andric     EmitFunctionBody(Args, Body);
1135f785676fSDimitry Andric   } else
1136f785676fSDimitry Andric     llvm_unreachable("no definition for emitted function");
1137f22ef01cSRoman Divacky 
11383861d79fSDimitry Andric   // C++11 [stmt.return]p2:
11393861d79fSDimitry Andric   //   Flowing off the end of a function [...] results in undefined behavior in
11403861d79fSDimitry Andric   //   a value-returning function.
11413861d79fSDimitry Andric   // C11 6.9.1p12:
11423861d79fSDimitry Andric   //   If the '}' that terminates a function is reached, and the value of the
11433861d79fSDimitry Andric   //   function call is used by the caller, the behavior is undefined.
114439d628a0SDimitry Andric   if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
114559d1ed5bSDimitry Andric       !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
11468e0f8b8cSDimitry Andric     bool ShouldEmitUnreachable =
11478e0f8b8cSDimitry Andric         CGM.getCodeGenOpts().StrictReturn ||
11488e0f8b8cSDimitry Andric         shouldUseUndefinedBehaviorReturnOptimization(FD, getContext());
114939d628a0SDimitry Andric     if (SanOpts.has(SanitizerKind::Return)) {
115059d1ed5bSDimitry Andric       SanitizerScope SanScope(this);
115139d628a0SDimitry Andric       llvm::Value *IsFalse = Builder.getFalse();
115239d628a0SDimitry Andric       EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
115344290647SDimitry Andric                 SanitizerHandler::MissingReturn,
115444290647SDimitry Andric                 EmitCheckSourceLocation(FD->getLocation()), None);
11558e0f8b8cSDimitry Andric     } else if (ShouldEmitUnreachable) {
11568e0f8b8cSDimitry Andric       if (CGM.getCodeGenOpts().OptimizationLevel == 0)
11573dac3a9bSDimitry Andric         EmitTrapCall(llvm::Intrinsic::trap);
11583dac3a9bSDimitry Andric     }
11598e0f8b8cSDimitry Andric     if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
11603861d79fSDimitry Andric       Builder.CreateUnreachable();
11613861d79fSDimitry Andric       Builder.ClearInsertionPoint();
11623861d79fSDimitry Andric     }
11638e0f8b8cSDimitry Andric   }
11643861d79fSDimitry Andric 
1165f22ef01cSRoman Divacky   // Emit the standard function epilogue.
1166f22ef01cSRoman Divacky   FinishFunction(BodyRange.getEnd());
1167f22ef01cSRoman Divacky 
1168e580952dSDimitry Andric   // If we haven't marked the function nothrow through other means, do
1169e580952dSDimitry Andric   // a quick pass now to see if we can.
1170e580952dSDimitry Andric   if (!CurFn->doesNotThrow())
1171e580952dSDimitry Andric     TryMarkNoThrow(CurFn);
1172f22ef01cSRoman Divacky }
1173f22ef01cSRoman Divacky 
1174f22ef01cSRoman Divacky /// ContainsLabel - Return true if the statement contains a label in it.  If
1175f22ef01cSRoman Divacky /// this statement is not executed normally, it not containing a label means
1176f22ef01cSRoman Divacky /// that we can just remove the code.
1177f22ef01cSRoman Divacky bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1178f22ef01cSRoman Divacky   // Null statement, not a label!
117959d1ed5bSDimitry Andric   if (!S) return false;
1180f22ef01cSRoman Divacky 
1181f22ef01cSRoman Divacky   // If this is a label, we have to emit the code, consider something like:
1182f22ef01cSRoman Divacky   // if (0) {  ...  foo:  bar(); }  goto foo;
11833b0f4066SDimitry Andric   //
11843b0f4066SDimitry Andric   // TODO: If anyone cared, we could track __label__'s, since we know that you
11853b0f4066SDimitry Andric   // can't jump to one from outside their declared region.
1186f22ef01cSRoman Divacky   if (isa<LabelStmt>(S))
1187f22ef01cSRoman Divacky     return true;
1188f22ef01cSRoman Divacky 
1189f22ef01cSRoman Divacky   // If this is a case/default statement, and we haven't seen a switch, we have
1190f22ef01cSRoman Divacky   // to emit the code.
1191f22ef01cSRoman Divacky   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1192f22ef01cSRoman Divacky     return true;
1193f22ef01cSRoman Divacky 
1194f22ef01cSRoman Divacky   // If this is a switch statement, we want to ignore cases below it.
1195f22ef01cSRoman Divacky   if (isa<SwitchStmt>(S))
1196f22ef01cSRoman Divacky     IgnoreCaseStmts = true;
1197f22ef01cSRoman Divacky 
1198f22ef01cSRoman Divacky   // Scan subexpressions for verboten labels.
11993dac3a9bSDimitry Andric   for (const Stmt *SubStmt : S->children())
12003dac3a9bSDimitry Andric     if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1201f22ef01cSRoman Divacky       return true;
1202f22ef01cSRoman Divacky 
1203f22ef01cSRoman Divacky   return false;
1204f22ef01cSRoman Divacky }
1205f22ef01cSRoman Divacky 
12063b0f4066SDimitry Andric /// containsBreak - Return true if the statement contains a break out of it.
12073b0f4066SDimitry Andric /// If the statement (recursively) contains a switch or loop with a break
12083b0f4066SDimitry Andric /// inside of it, this is fine.
12093b0f4066SDimitry Andric bool CodeGenFunction::containsBreak(const Stmt *S) {
12103b0f4066SDimitry Andric   // Null statement, not a label!
121159d1ed5bSDimitry Andric   if (!S) return false;
1212f22ef01cSRoman Divacky 
12133b0f4066SDimitry Andric   // If this is a switch or loop that defines its own break scope, then we can
12143b0f4066SDimitry Andric   // include it and anything inside of it.
12153b0f4066SDimitry Andric   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
12163b0f4066SDimitry Andric       isa<ForStmt>(S))
12173b0f4066SDimitry Andric     return false;
12183b0f4066SDimitry Andric 
12193b0f4066SDimitry Andric   if (isa<BreakStmt>(S))
12203b0f4066SDimitry Andric     return true;
12213b0f4066SDimitry Andric 
12223b0f4066SDimitry Andric   // Scan subexpressions for verboten breaks.
12233dac3a9bSDimitry Andric   for (const Stmt *SubStmt : S->children())
12243dac3a9bSDimitry Andric     if (containsBreak(SubStmt))
12253b0f4066SDimitry Andric       return true;
12263b0f4066SDimitry Andric 
12273b0f4066SDimitry Andric   return false;
12283b0f4066SDimitry Andric }
12293b0f4066SDimitry Andric 
1230f41fbc90SDimitry Andric bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
1231f41fbc90SDimitry Andric   if (!S) return false;
1232f41fbc90SDimitry Andric 
1233f41fbc90SDimitry Andric   // Some statement kinds add a scope and thus never add a decl to the current
1234f41fbc90SDimitry Andric   // scope. Note, this list is longer than the list of statements that might
1235f41fbc90SDimitry Andric   // have an unscoped decl nested within them, but this way is conservatively
1236f41fbc90SDimitry Andric   // correct even if more statement kinds are added.
1237f41fbc90SDimitry Andric   if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1238f41fbc90SDimitry Andric       isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
1239f41fbc90SDimitry Andric       isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
1240f41fbc90SDimitry Andric       isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
1241f41fbc90SDimitry Andric     return false;
1242f41fbc90SDimitry Andric 
1243f41fbc90SDimitry Andric   if (isa<DeclStmt>(S))
1244f41fbc90SDimitry Andric     return true;
1245f41fbc90SDimitry Andric 
1246f41fbc90SDimitry Andric   for (const Stmt *SubStmt : S->children())
1247f41fbc90SDimitry Andric     if (mightAddDeclToScope(SubStmt))
1248f41fbc90SDimitry Andric       return true;
1249f41fbc90SDimitry Andric 
1250f41fbc90SDimitry Andric   return false;
1251f41fbc90SDimitry Andric }
12523b0f4066SDimitry Andric 
12533b0f4066SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
12543b0f4066SDimitry Andric /// to a constant, or if it does but contains a label, return false.  If it
12553b0f4066SDimitry Andric /// constant folds return true and set the boolean result in Result.
12563b0f4066SDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1257e7145dcbSDimitry Andric                                                    bool &ResultBool,
1258e7145dcbSDimitry Andric                                                    bool AllowLabels) {
12597ae0e2c9SDimitry Andric   llvm::APSInt ResultInt;
1260e7145dcbSDimitry Andric   if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
12613b0f4066SDimitry Andric     return false;
12623b0f4066SDimitry Andric 
12633b0f4066SDimitry Andric   ResultBool = ResultInt.getBoolValue();
12643b0f4066SDimitry Andric   return true;
12653b0f4066SDimitry Andric }
12663b0f4066SDimitry Andric 
12673b0f4066SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
12683b0f4066SDimitry Andric /// to a constant, or if it does but contains a label, return false.  If it
12693b0f4066SDimitry Andric /// constant folds return true and set the folded value.
1270e7145dcbSDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1271e7145dcbSDimitry Andric                                                    llvm::APSInt &ResultInt,
1272e7145dcbSDimitry Andric                                                    bool AllowLabels) {
1273f22ef01cSRoman Divacky   // FIXME: Rename and handle conversion of other evaluatable things
1274f22ef01cSRoman Divacky   // to bool.
1275dff0c46cSDimitry Andric   llvm::APSInt Int;
1276dff0c46cSDimitry Andric   if (!Cond->EvaluateAsInt(Int, getContext()))
12773b0f4066SDimitry Andric     return false;  // Not foldable, not integer or not fully evaluatable.
1278f22ef01cSRoman Divacky 
1279e7145dcbSDimitry Andric   if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
12803b0f4066SDimitry Andric     return false;  // Contains a label.
1281f22ef01cSRoman Divacky 
1282dff0c46cSDimitry Andric   ResultInt = Int;
12833b0f4066SDimitry Andric   return true;
1284f22ef01cSRoman Divacky }
1285f22ef01cSRoman Divacky 
1286f22ef01cSRoman Divacky 
12873b0f4066SDimitry Andric 
1288f22ef01cSRoman Divacky /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1289f22ef01cSRoman Divacky /// statement) to the specified blocks.  Based on the condition, this might try
1290f22ef01cSRoman Divacky /// to simplify the codegen of the conditional based on the branch.
1291f22ef01cSRoman Divacky ///
1292f22ef01cSRoman Divacky void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1293f22ef01cSRoman Divacky                                            llvm::BasicBlock *TrueBlock,
129459d1ed5bSDimitry Andric                                            llvm::BasicBlock *FalseBlock,
129559d1ed5bSDimitry Andric                                            uint64_t TrueCount) {
12963b0f4066SDimitry Andric   Cond = Cond->IgnoreParens();
1297f22ef01cSRoman Divacky 
1298f22ef01cSRoman Divacky   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
129959d1ed5bSDimitry Andric 
1300f22ef01cSRoman Divacky     // Handle X && Y in a condition.
1301e580952dSDimitry Andric     if (CondBOp->getOpcode() == BO_LAnd) {
1302f22ef01cSRoman Divacky       // If we have "1 && X", simplify the code.  "0 && X" would have constant
1303f22ef01cSRoman Divacky       // folded if the case was simple enough.
13043b0f4066SDimitry Andric       bool ConstantBool = false;
13053b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
13063b0f4066SDimitry Andric           ConstantBool) {
1307f22ef01cSRoman Divacky         // br(1 && X) -> br(X).
130833956c43SDimitry Andric         incrementProfileCounter(CondBOp);
130959d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
131059d1ed5bSDimitry Andric                                     TrueCount);
1311f22ef01cSRoman Divacky       }
1312f22ef01cSRoman Divacky 
1313f22ef01cSRoman Divacky       // If we have "X && 1", simplify the code to use an uncond branch.
1314f22ef01cSRoman Divacky       // "X && 0" would have been constant folded to 0.
13153b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
13163b0f4066SDimitry Andric           ConstantBool) {
1317f22ef01cSRoman Divacky         // br(X && 1) -> br(X).
131859d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
131959d1ed5bSDimitry Andric                                     TrueCount);
1320f22ef01cSRoman Divacky       }
1321f22ef01cSRoman Divacky 
1322f22ef01cSRoman Divacky       // Emit the LHS as a conditional.  If the LHS conditional is false, we
1323f22ef01cSRoman Divacky       // want to jump to the FalseBlock.
1324f22ef01cSRoman Divacky       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
132559d1ed5bSDimitry Andric       // The counter tells us how often we evaluate RHS, and all of TrueCount
132659d1ed5bSDimitry Andric       // can be propagated to that branch.
132733956c43SDimitry Andric       uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
13282754fe60SDimitry Andric 
13292754fe60SDimitry Andric       ConditionalEvaluation eval(*this);
133033956c43SDimitry Andric       {
133133956c43SDimitry Andric         ApplyDebugLocation DL(*this, Cond);
133259d1ed5bSDimitry Andric         EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
1333f22ef01cSRoman Divacky         EmitBlock(LHSTrue);
133433956c43SDimitry Andric       }
133533956c43SDimitry Andric 
133633956c43SDimitry Andric       incrementProfileCounter(CondBOp);
133733956c43SDimitry Andric       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1338f22ef01cSRoman Divacky 
1339f22ef01cSRoman Divacky       // Any temporaries created here are conditional.
13402754fe60SDimitry Andric       eval.begin(*this);
134159d1ed5bSDimitry Andric       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
13422754fe60SDimitry Andric       eval.end(*this);
1343f22ef01cSRoman Divacky 
1344f22ef01cSRoman Divacky       return;
13453b0f4066SDimitry Andric     }
13463b0f4066SDimitry Andric 
13473b0f4066SDimitry Andric     if (CondBOp->getOpcode() == BO_LOr) {
1348f22ef01cSRoman Divacky       // If we have "0 || X", simplify the code.  "1 || X" would have constant
1349f22ef01cSRoman Divacky       // folded if the case was simple enough.
13503b0f4066SDimitry Andric       bool ConstantBool = false;
13513b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
13523b0f4066SDimitry Andric           !ConstantBool) {
1353f22ef01cSRoman Divacky         // br(0 || X) -> br(X).
135433956c43SDimitry Andric         incrementProfileCounter(CondBOp);
135559d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
135659d1ed5bSDimitry Andric                                     TrueCount);
1357f22ef01cSRoman Divacky       }
1358f22ef01cSRoman Divacky 
1359f22ef01cSRoman Divacky       // If we have "X || 0", simplify the code to use an uncond branch.
1360f22ef01cSRoman Divacky       // "X || 1" would have been constant folded to 1.
13613b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
13623b0f4066SDimitry Andric           !ConstantBool) {
1363f22ef01cSRoman Divacky         // br(X || 0) -> br(X).
136459d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
136559d1ed5bSDimitry Andric                                     TrueCount);
1366f22ef01cSRoman Divacky       }
1367f22ef01cSRoman Divacky 
1368f22ef01cSRoman Divacky       // Emit the LHS as a conditional.  If the LHS conditional is true, we
1369f22ef01cSRoman Divacky       // want to jump to the TrueBlock.
1370f22ef01cSRoman Divacky       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
137159d1ed5bSDimitry Andric       // We have the count for entry to the RHS and for the whole expression
137259d1ed5bSDimitry Andric       // being true, so we can divy up True count between the short circuit and
137359d1ed5bSDimitry Andric       // the RHS.
137433956c43SDimitry Andric       uint64_t LHSCount =
137533956c43SDimitry Andric           getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
137659d1ed5bSDimitry Andric       uint64_t RHSCount = TrueCount - LHSCount;
13772754fe60SDimitry Andric 
13782754fe60SDimitry Andric       ConditionalEvaluation eval(*this);
137933956c43SDimitry Andric       {
138033956c43SDimitry Andric         ApplyDebugLocation DL(*this, Cond);
138159d1ed5bSDimitry Andric         EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
1382f22ef01cSRoman Divacky         EmitBlock(LHSFalse);
138333956c43SDimitry Andric       }
138433956c43SDimitry Andric 
138533956c43SDimitry Andric       incrementProfileCounter(CondBOp);
138633956c43SDimitry Andric       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1387f22ef01cSRoman Divacky 
1388f22ef01cSRoman Divacky       // Any temporaries created here are conditional.
13892754fe60SDimitry Andric       eval.begin(*this);
139059d1ed5bSDimitry Andric       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
139159d1ed5bSDimitry Andric 
13922754fe60SDimitry Andric       eval.end(*this);
1393f22ef01cSRoman Divacky 
1394f22ef01cSRoman Divacky       return;
1395f22ef01cSRoman Divacky     }
1396f22ef01cSRoman Divacky   }
1397f22ef01cSRoman Divacky 
1398f22ef01cSRoman Divacky   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1399f22ef01cSRoman Divacky     // br(!x, t, f) -> br(x, f, t)
140059d1ed5bSDimitry Andric     if (CondUOp->getOpcode() == UO_LNot) {
140159d1ed5bSDimitry Andric       // Negate the count.
140233956c43SDimitry Andric       uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
140359d1ed5bSDimitry Andric       // Negate the condition and swap the destination blocks.
140459d1ed5bSDimitry Andric       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
140559d1ed5bSDimitry Andric                                   FalseCount);
140659d1ed5bSDimitry Andric     }
1407f22ef01cSRoman Divacky   }
1408f22ef01cSRoman Divacky 
1409f22ef01cSRoman Divacky   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1410f22ef01cSRoman Divacky     // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1411f22ef01cSRoman Divacky     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1412f22ef01cSRoman Divacky     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
14132754fe60SDimitry Andric 
14142754fe60SDimitry Andric     ConditionalEvaluation cond(*this);
141533956c43SDimitry Andric     EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
141633956c43SDimitry Andric                          getProfileCount(CondOp));
141759d1ed5bSDimitry Andric 
141859d1ed5bSDimitry Andric     // When computing PGO branch weights, we only know the overall count for
141959d1ed5bSDimitry Andric     // the true block. This code is essentially doing tail duplication of the
142059d1ed5bSDimitry Andric     // naive code-gen, introducing new edges for which counts are not
142159d1ed5bSDimitry Andric     // available. Divide the counts proportionally between the LHS and RHS of
142259d1ed5bSDimitry Andric     // the conditional operator.
142359d1ed5bSDimitry Andric     uint64_t LHSScaledTrueCount = 0;
142459d1ed5bSDimitry Andric     if (TrueCount) {
142533956c43SDimitry Andric       double LHSRatio =
142633956c43SDimitry Andric           getProfileCount(CondOp) / (double)getCurrentProfileCount();
142759d1ed5bSDimitry Andric       LHSScaledTrueCount = TrueCount * LHSRatio;
142859d1ed5bSDimitry Andric     }
14292754fe60SDimitry Andric 
14302754fe60SDimitry Andric     cond.begin(*this);
1431f22ef01cSRoman Divacky     EmitBlock(LHSBlock);
143233956c43SDimitry Andric     incrementProfileCounter(CondOp);
143333956c43SDimitry Andric     {
143433956c43SDimitry Andric       ApplyDebugLocation DL(*this, Cond);
143559d1ed5bSDimitry Andric       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
143659d1ed5bSDimitry Andric                            LHSScaledTrueCount);
143733956c43SDimitry Andric     }
14382754fe60SDimitry Andric     cond.end(*this);
14392754fe60SDimitry Andric 
14402754fe60SDimitry Andric     cond.begin(*this);
1441f22ef01cSRoman Divacky     EmitBlock(RHSBlock);
144259d1ed5bSDimitry Andric     EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
144359d1ed5bSDimitry Andric                          TrueCount - LHSScaledTrueCount);
14442754fe60SDimitry Andric     cond.end(*this);
14452754fe60SDimitry Andric 
1446f22ef01cSRoman Divacky     return;
1447f22ef01cSRoman Divacky   }
1448f22ef01cSRoman Divacky 
1449284c1978SDimitry Andric   if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1450284c1978SDimitry Andric     // Conditional operator handling can give us a throw expression as a
1451284c1978SDimitry Andric     // condition for a case like:
1452284c1978SDimitry Andric     //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1453284c1978SDimitry Andric     // Fold this to:
1454284c1978SDimitry Andric     //   br(c, throw x, br(y, t, f))
1455284c1978SDimitry Andric     EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1456284c1978SDimitry Andric     return;
1457284c1978SDimitry Andric   }
1458284c1978SDimitry Andric 
14590623d748SDimitry Andric   // If the branch has a condition wrapped by __builtin_unpredictable,
14600623d748SDimitry Andric   // create metadata that specifies that the branch is unpredictable.
14610623d748SDimitry Andric   // Don't bother if not optimizing because that metadata would not be used.
14620623d748SDimitry Andric   llvm::MDNode *Unpredictable = nullptr;
1463e7145dcbSDimitry Andric   auto *Call = dyn_cast<CallExpr>(Cond);
1464e7145dcbSDimitry Andric   if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1465e7145dcbSDimitry Andric     auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1466e7145dcbSDimitry Andric     if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
14670623d748SDimitry Andric       llvm::MDBuilder MDHelper(getLLVMContext());
14680623d748SDimitry Andric       Unpredictable = MDHelper.createUnpredictable();
14690623d748SDimitry Andric     }
14700623d748SDimitry Andric   }
14710623d748SDimitry Andric 
147259d1ed5bSDimitry Andric   // Create branch weights based on the number of times we get here and the
147359d1ed5bSDimitry Andric   // number of times the condition should be true.
147433956c43SDimitry Andric   uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
147533956c43SDimitry Andric   llvm::MDNode *Weights =
147633956c43SDimitry Andric       createProfileWeights(TrueCount, CurrentCount - TrueCount);
147759d1ed5bSDimitry Andric 
1478f22ef01cSRoman Divacky   // Emit the code with the fully general case.
147933956c43SDimitry Andric   llvm::Value *CondV;
148033956c43SDimitry Andric   {
148133956c43SDimitry Andric     ApplyDebugLocation DL(*this, Cond);
148233956c43SDimitry Andric     CondV = EvaluateExprAsBool(Cond);
148333956c43SDimitry Andric   }
14840623d748SDimitry Andric   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
1485f22ef01cSRoman Divacky }
1486f22ef01cSRoman Divacky 
1487f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
1488f22ef01cSRoman Divacky /// specified stmt yet.
1489f785676fSDimitry Andric void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1490f785676fSDimitry Andric   CGM.ErrorUnsupported(S, Type);
1491f22ef01cSRoman Divacky }
1492f22ef01cSRoman Divacky 
14932754fe60SDimitry Andric /// emitNonZeroVLAInit - Emit the "zero" initialization of a
14942754fe60SDimitry Andric /// variable-length array whose elements have a non-zero bit-pattern.
14952754fe60SDimitry Andric ///
14967ae0e2c9SDimitry Andric /// \param baseType the inner-most element type of the array
14972754fe60SDimitry Andric /// \param src - a char* pointing to the bit-pattern for a single
14982754fe60SDimitry Andric /// base element of the array
14992754fe60SDimitry Andric /// \param sizeInChars - the total size of the VLA, in chars
15002754fe60SDimitry Andric static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
15010623d748SDimitry Andric                                Address dest, Address src,
15022754fe60SDimitry Andric                                llvm::Value *sizeInChars) {
15032754fe60SDimitry Andric   CGBuilderTy &Builder = CGF.Builder;
15042754fe60SDimitry Andric 
15050623d748SDimitry Andric   CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
15062754fe60SDimitry Andric   llvm::Value *baseSizeInChars
15070623d748SDimitry Andric     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
15082754fe60SDimitry Andric 
15090623d748SDimitry Andric   Address begin =
15100623d748SDimitry Andric     Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
15110623d748SDimitry Andric   llvm::Value *end =
15120623d748SDimitry Andric     Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
15132754fe60SDimitry Andric 
15142754fe60SDimitry Andric   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
15152754fe60SDimitry Andric   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
15162754fe60SDimitry Andric   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
15172754fe60SDimitry Andric 
15182754fe60SDimitry Andric   // Make a loop over the VLA.  C99 guarantees that the VLA element
15192754fe60SDimitry Andric   // count must be nonzero.
15202754fe60SDimitry Andric   CGF.EmitBlock(loopBB);
15212754fe60SDimitry Andric 
15220623d748SDimitry Andric   llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
15230623d748SDimitry Andric   cur->addIncoming(begin.getPointer(), originBB);
15240623d748SDimitry Andric 
15250623d748SDimitry Andric   CharUnits curAlign =
15260623d748SDimitry Andric     dest.getAlignment().alignmentOfArrayElement(baseSize);
15272754fe60SDimitry Andric 
15282754fe60SDimitry Andric   // memcpy the individual element bit-pattern.
15290623d748SDimitry Andric   Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
15302754fe60SDimitry Andric                        /*volatile*/ false);
15312754fe60SDimitry Andric 
15322754fe60SDimitry Andric   // Go to the next element.
15330623d748SDimitry Andric   llvm::Value *next =
15340623d748SDimitry Andric     Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
15352754fe60SDimitry Andric 
15362754fe60SDimitry Andric   // Leave if that's the end of the VLA.
15372754fe60SDimitry Andric   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
15382754fe60SDimitry Andric   Builder.CreateCondBr(done, contBB, loopBB);
15392754fe60SDimitry Andric   cur->addIncoming(next, loopBB);
15402754fe60SDimitry Andric 
15412754fe60SDimitry Andric   CGF.EmitBlock(contBB);
15422754fe60SDimitry Andric }
15432754fe60SDimitry Andric 
1544f22ef01cSRoman Divacky void
15450623d748SDimitry Andric CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
1546f22ef01cSRoman Divacky   // Ignore empty classes in C++.
15473861d79fSDimitry Andric   if (getLangOpts().CPlusPlus) {
1548f22ef01cSRoman Divacky     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1549f22ef01cSRoman Divacky       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1550f22ef01cSRoman Divacky         return;
1551f22ef01cSRoman Divacky     }
1552f22ef01cSRoman Divacky   }
1553f22ef01cSRoman Divacky 
1554e580952dSDimitry Andric   // Cast the dest ptr to the appropriate i8 pointer type.
15550623d748SDimitry Andric   if (DestPtr.getElementType() != Int8Ty)
15560623d748SDimitry Andric     DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
1557f22ef01cSRoman Divacky 
1558f22ef01cSRoman Divacky   // Get size and alignment info for this aggregate.
15590623d748SDimitry Andric   CharUnits size = getContext().getTypeSizeInChars(Ty);
15602754fe60SDimitry Andric 
15612754fe60SDimitry Andric   llvm::Value *SizeVal;
15622754fe60SDimitry Andric   const VariableArrayType *vla;
1563f22ef01cSRoman Divacky 
1564f22ef01cSRoman Divacky   // Don't bother emitting a zero-byte memset.
15650623d748SDimitry Andric   if (size.isZero()) {
15662754fe60SDimitry Andric     // But note that getTypeInfo returns 0 for a VLA.
15672754fe60SDimitry Andric     if (const VariableArrayType *vlaType =
15682754fe60SDimitry Andric           dyn_cast_or_null<VariableArrayType>(
15692754fe60SDimitry Andric                                           getContext().getAsArrayType(Ty))) {
157017a519f9SDimitry Andric       QualType eltType;
157117a519f9SDimitry Andric       llvm::Value *numElts;
157259d1ed5bSDimitry Andric       std::tie(numElts, eltType) = getVLASize(vlaType);
157317a519f9SDimitry Andric 
157417a519f9SDimitry Andric       SizeVal = numElts;
157517a519f9SDimitry Andric       CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
157617a519f9SDimitry Andric       if (!eltSize.isOne())
157717a519f9SDimitry Andric         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
15782754fe60SDimitry Andric       vla = vlaType;
15792754fe60SDimitry Andric     } else {
1580f22ef01cSRoman Divacky       return;
15812754fe60SDimitry Andric     }
15822754fe60SDimitry Andric   } else {
15830623d748SDimitry Andric     SizeVal = CGM.getSize(size);
158459d1ed5bSDimitry Andric     vla = nullptr;
15852754fe60SDimitry Andric   }
1586e580952dSDimitry Andric 
1587e580952dSDimitry Andric   // If the type contains a pointer to data member we can't memset it to zero.
1588e580952dSDimitry Andric   // Instead, create a null constant and copy it to the destination.
15892754fe60SDimitry Andric   // TODO: there are other patterns besides zero that we can usefully memset,
15902754fe60SDimitry Andric   // like -1, which happens to be the pattern used by member-pointers.
1591e580952dSDimitry Andric   if (!CGM.getTypes().isZeroInitializable(Ty)) {
15922754fe60SDimitry Andric     // For a VLA, emit a single element, then splat that over the VLA.
15932754fe60SDimitry Andric     if (vla) Ty = getContext().getBaseElementType(vla);
15942754fe60SDimitry Andric 
1595e580952dSDimitry Andric     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1596e580952dSDimitry Andric 
1597e580952dSDimitry Andric     llvm::GlobalVariable *NullVariable =
1598e580952dSDimitry Andric       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1599e580952dSDimitry Andric                                /*isConstant=*/true,
1600e580952dSDimitry Andric                                llvm::GlobalVariable::PrivateLinkage,
16016122f3e6SDimitry Andric                                NullConstant, Twine());
16020623d748SDimitry Andric     CharUnits NullAlign = DestPtr.getAlignment();
16030623d748SDimitry Andric     NullVariable->setAlignment(NullAlign.getQuantity());
16040623d748SDimitry Andric     Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
16050623d748SDimitry Andric                    NullAlign);
1606e580952dSDimitry Andric 
16072754fe60SDimitry Andric     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1608e580952dSDimitry Andric 
1609e580952dSDimitry Andric     // Get and call the appropriate llvm.memcpy overload.
16100623d748SDimitry Andric     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
1611e580952dSDimitry Andric     return;
1612e580952dSDimitry Andric   }
1613e580952dSDimitry Andric 
1614e580952dSDimitry Andric   // Otherwise, just memset the whole thing to zero.  This is legal
1615e580952dSDimitry Andric   // because in LLVM, all default initializers (other than the ones we just
1616e580952dSDimitry Andric   // handled above) are guaranteed to have a bit pattern of all zeros.
16170623d748SDimitry Andric   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
1618f22ef01cSRoman Divacky }
1619f22ef01cSRoman Divacky 
16202754fe60SDimitry Andric llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
1621f22ef01cSRoman Divacky   // Make sure that there is a block for the indirect goto.
162259d1ed5bSDimitry Andric   if (!IndirectBranch)
1623f22ef01cSRoman Divacky     GetIndirectGotoBlock();
1624f22ef01cSRoman Divacky 
1625e580952dSDimitry Andric   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
1626f22ef01cSRoman Divacky 
1627f22ef01cSRoman Divacky   // Make sure the indirect branch includes all of the address-taken blocks.
1628f22ef01cSRoman Divacky   IndirectBranch->addDestination(BB);
1629f22ef01cSRoman Divacky   return llvm::BlockAddress::get(CurFn, BB);
1630f22ef01cSRoman Divacky }
1631f22ef01cSRoman Divacky 
1632f22ef01cSRoman Divacky llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
1633f22ef01cSRoman Divacky   // If we already made the indirect branch for indirect goto, return its block.
1634f22ef01cSRoman Divacky   if (IndirectBranch) return IndirectBranch->getParent();
1635f22ef01cSRoman Divacky 
16360623d748SDimitry Andric   CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
1637f22ef01cSRoman Divacky 
1638f22ef01cSRoman Divacky   // Create the PHI node that indirect gotos will add entries to.
16393b0f4066SDimitry Andric   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
16403b0f4066SDimitry Andric                                               "indirect.goto.dest");
1641f22ef01cSRoman Divacky 
1642f22ef01cSRoman Divacky   // Create the indirect branch instruction.
1643f22ef01cSRoman Divacky   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1644f22ef01cSRoman Divacky   return IndirectBranch->getParent();
1645f22ef01cSRoman Divacky }
1646f22ef01cSRoman Divacky 
164717a519f9SDimitry Andric /// Computes the length of an array in elements, as well as the base
164817a519f9SDimitry Andric /// element type and a properly-typed first element pointer.
164917a519f9SDimitry Andric llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
165017a519f9SDimitry Andric                                               QualType &baseType,
16510623d748SDimitry Andric                                               Address &addr) {
165217a519f9SDimitry Andric   const ArrayType *arrayType = origArrayType;
1653f22ef01cSRoman Divacky 
165417a519f9SDimitry Andric   // If it's a VLA, we have to load the stored size.  Note that
165517a519f9SDimitry Andric   // this is the size of the VLA in bytes, not its size in elements.
165659d1ed5bSDimitry Andric   llvm::Value *numVLAElements = nullptr;
165717a519f9SDimitry Andric   if (isa<VariableArrayType>(arrayType)) {
165817a519f9SDimitry Andric     numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
165917a519f9SDimitry Andric 
166017a519f9SDimitry Andric     // Walk into all VLAs.  This doesn't require changes to addr,
166117a519f9SDimitry Andric     // which has type T* where T is the first non-VLA element type.
166217a519f9SDimitry Andric     do {
166317a519f9SDimitry Andric       QualType elementType = arrayType->getElementType();
166417a519f9SDimitry Andric       arrayType = getContext().getAsArrayType(elementType);
166517a519f9SDimitry Andric 
166617a519f9SDimitry Andric       // If we only have VLA components, 'addr' requires no adjustment.
166717a519f9SDimitry Andric       if (!arrayType) {
166817a519f9SDimitry Andric         baseType = elementType;
166917a519f9SDimitry Andric         return numVLAElements;
167017a519f9SDimitry Andric       }
167117a519f9SDimitry Andric     } while (isa<VariableArrayType>(arrayType));
167217a519f9SDimitry Andric 
167317a519f9SDimitry Andric     // We get out here only if we find a constant array type
167417a519f9SDimitry Andric     // inside the VLA.
1675f22ef01cSRoman Divacky   }
1676f22ef01cSRoman Divacky 
167717a519f9SDimitry Andric   // We have some number of constant-length arrays, so addr should
167817a519f9SDimitry Andric   // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
167917a519f9SDimitry Andric   // down to the first element of addr.
16806122f3e6SDimitry Andric   SmallVector<llvm::Value*, 8> gepIndices;
168117a519f9SDimitry Andric 
168217a519f9SDimitry Andric   // GEP down to the array type.
168317a519f9SDimitry Andric   llvm::ConstantInt *zero = Builder.getInt32(0);
168417a519f9SDimitry Andric   gepIndices.push_back(zero);
168517a519f9SDimitry Andric 
168617a519f9SDimitry Andric   uint64_t countFromCLAs = 1;
16877ae0e2c9SDimitry Andric   QualType eltType;
168817a519f9SDimitry Andric 
16896122f3e6SDimitry Andric   llvm::ArrayType *llvmArrayType =
16900623d748SDimitry Andric     dyn_cast<llvm::ArrayType>(addr.getElementType());
16917ae0e2c9SDimitry Andric   while (llvmArrayType) {
169217a519f9SDimitry Andric     assert(isa<ConstantArrayType>(arrayType));
169317a519f9SDimitry Andric     assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
169417a519f9SDimitry Andric              == llvmArrayType->getNumElements());
169517a519f9SDimitry Andric 
169617a519f9SDimitry Andric     gepIndices.push_back(zero);
169717a519f9SDimitry Andric     countFromCLAs *= llvmArrayType->getNumElements();
16987ae0e2c9SDimitry Andric     eltType = arrayType->getElementType();
169917a519f9SDimitry Andric 
170017a519f9SDimitry Andric     llvmArrayType =
170117a519f9SDimitry Andric       dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
170217a519f9SDimitry Andric     arrayType = getContext().getAsArrayType(arrayType->getElementType());
17037ae0e2c9SDimitry Andric     assert((!llvmArrayType || arrayType) &&
17047ae0e2c9SDimitry Andric            "LLVM and Clang types are out-of-synch");
170517a519f9SDimitry Andric   }
170617a519f9SDimitry Andric 
17077ae0e2c9SDimitry Andric   if (arrayType) {
17087ae0e2c9SDimitry Andric     // From this point onwards, the Clang array type has been emitted
17097ae0e2c9SDimitry Andric     // as some other type (probably a packed struct). Compute the array
17107ae0e2c9SDimitry Andric     // size, and just emit the 'begin' expression as a bitcast.
17117ae0e2c9SDimitry Andric     while (arrayType) {
17127ae0e2c9SDimitry Andric       countFromCLAs *=
17137ae0e2c9SDimitry Andric           cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
17147ae0e2c9SDimitry Andric       eltType = arrayType->getElementType();
17157ae0e2c9SDimitry Andric       arrayType = getContext().getAsArrayType(eltType);
17167ae0e2c9SDimitry Andric     }
171717a519f9SDimitry Andric 
17180623d748SDimitry Andric     llvm::Type *baseType = ConvertType(eltType);
17190623d748SDimitry Andric     addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
17207ae0e2c9SDimitry Andric   } else {
172117a519f9SDimitry Andric     // Create the actual GEP.
17220623d748SDimitry Andric     addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
17230623d748SDimitry Andric                                              gepIndices, "array.begin"),
17240623d748SDimitry Andric                    addr.getAlignment());
17257ae0e2c9SDimitry Andric   }
17267ae0e2c9SDimitry Andric 
17277ae0e2c9SDimitry Andric   baseType = eltType;
172817a519f9SDimitry Andric 
172917a519f9SDimitry Andric   llvm::Value *numElements
173017a519f9SDimitry Andric     = llvm::ConstantInt::get(SizeTy, countFromCLAs);
173117a519f9SDimitry Andric 
173217a519f9SDimitry Andric   // If we had any VLA dimensions, factor them in.
173317a519f9SDimitry Andric   if (numVLAElements)
173417a519f9SDimitry Andric     numElements = Builder.CreateNUWMul(numVLAElements, numElements);
173517a519f9SDimitry Andric 
173617a519f9SDimitry Andric   return numElements;
173717a519f9SDimitry Andric }
173817a519f9SDimitry Andric 
173917a519f9SDimitry Andric std::pair<llvm::Value*, QualType>
174017a519f9SDimitry Andric CodeGenFunction::getVLASize(QualType type) {
174117a519f9SDimitry Andric   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
174217a519f9SDimitry Andric   assert(vla && "type was not a variable array type!");
174317a519f9SDimitry Andric   return getVLASize(vla);
174417a519f9SDimitry Andric }
174517a519f9SDimitry Andric 
174617a519f9SDimitry Andric std::pair<llvm::Value*, QualType>
174717a519f9SDimitry Andric CodeGenFunction::getVLASize(const VariableArrayType *type) {
174817a519f9SDimitry Andric   // The number of elements so far; always size_t.
174959d1ed5bSDimitry Andric   llvm::Value *numElements = nullptr;
175017a519f9SDimitry Andric 
175117a519f9SDimitry Andric   QualType elementType;
175217a519f9SDimitry Andric   do {
175317a519f9SDimitry Andric     elementType = type->getElementType();
175417a519f9SDimitry Andric     llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
175517a519f9SDimitry Andric     assert(vlaSize && "no size for VLA!");
175617a519f9SDimitry Andric     assert(vlaSize->getType() == SizeTy);
175717a519f9SDimitry Andric 
175817a519f9SDimitry Andric     if (!numElements) {
175917a519f9SDimitry Andric       numElements = vlaSize;
176017a519f9SDimitry Andric     } else {
176117a519f9SDimitry Andric       // It's undefined behavior if this wraps around, so mark it that way.
176259d1ed5bSDimitry Andric       // FIXME: Teach -fsanitize=undefined to trap this.
176317a519f9SDimitry Andric       numElements = Builder.CreateNUWMul(numElements, vlaSize);
176417a519f9SDimitry Andric     }
176517a519f9SDimitry Andric   } while ((type = getContext().getAsVariableArrayType(elementType)));
176617a519f9SDimitry Andric 
176717a519f9SDimitry Andric   return std::pair<llvm::Value*,QualType>(numElements, elementType);
176817a519f9SDimitry Andric }
176917a519f9SDimitry Andric 
177017a519f9SDimitry Andric void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
177117a519f9SDimitry Andric   assert(type->isVariablyModifiedType() &&
1772f22ef01cSRoman Divacky          "Must pass variably modified type to EmitVLASizes!");
1773f22ef01cSRoman Divacky 
1774f22ef01cSRoman Divacky   EnsureInsertPoint();
1775f22ef01cSRoman Divacky 
177617a519f9SDimitry Andric   // We're going to walk down into the type and look for VLA
177717a519f9SDimitry Andric   // expressions.
177817a519f9SDimitry Andric   do {
177917a519f9SDimitry Andric     assert(type->isVariablyModifiedType());
1780f22ef01cSRoman Divacky 
178117a519f9SDimitry Andric     const Type *ty = type.getTypePtr();
178217a519f9SDimitry Andric     switch (ty->getTypeClass()) {
1783dff0c46cSDimitry Andric 
178417a519f9SDimitry Andric #define TYPE(Class, Base)
178517a519f9SDimitry Andric #define ABSTRACT_TYPE(Class, Base)
1786dff0c46cSDimitry Andric #define NON_CANONICAL_TYPE(Class, Base)
178717a519f9SDimitry Andric #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1788dff0c46cSDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
178917a519f9SDimitry Andric #include "clang/AST/TypeNodes.def"
1790dff0c46cSDimitry Andric       llvm_unreachable("unexpected dependent type!");
1791f22ef01cSRoman Divacky 
179217a519f9SDimitry Andric     // These types are never variably-modified.
179317a519f9SDimitry Andric     case Type::Builtin:
179417a519f9SDimitry Andric     case Type::Complex:
179517a519f9SDimitry Andric     case Type::Vector:
179617a519f9SDimitry Andric     case Type::ExtVector:
179717a519f9SDimitry Andric     case Type::Record:
179817a519f9SDimitry Andric     case Type::Enum:
1799dff0c46cSDimitry Andric     case Type::Elaborated:
1800dff0c46cSDimitry Andric     case Type::TemplateSpecialization:
180144290647SDimitry Andric     case Type::ObjCTypeParam:
180217a519f9SDimitry Andric     case Type::ObjCObject:
180317a519f9SDimitry Andric     case Type::ObjCInterface:
180417a519f9SDimitry Andric     case Type::ObjCObjectPointer:
180517a519f9SDimitry Andric       llvm_unreachable("type class is never variably-modified!");
1806f22ef01cSRoman Divacky 
180759d1ed5bSDimitry Andric     case Type::Adjusted:
180859d1ed5bSDimitry Andric       type = cast<AdjustedType>(ty)->getAdjustedType();
180959d1ed5bSDimitry Andric       break;
181059d1ed5bSDimitry Andric 
1811f785676fSDimitry Andric     case Type::Decayed:
1812f785676fSDimitry Andric       type = cast<DecayedType>(ty)->getPointeeType();
1813f785676fSDimitry Andric       break;
1814f785676fSDimitry Andric 
181517a519f9SDimitry Andric     case Type::Pointer:
181617a519f9SDimitry Andric       type = cast<PointerType>(ty)->getPointeeType();
181717a519f9SDimitry Andric       break;
1818f22ef01cSRoman Divacky 
181917a519f9SDimitry Andric     case Type::BlockPointer:
182017a519f9SDimitry Andric       type = cast<BlockPointerType>(ty)->getPointeeType();
182117a519f9SDimitry Andric       break;
182217a519f9SDimitry Andric 
182317a519f9SDimitry Andric     case Type::LValueReference:
182417a519f9SDimitry Andric     case Type::RValueReference:
182517a519f9SDimitry Andric       type = cast<ReferenceType>(ty)->getPointeeType();
182617a519f9SDimitry Andric       break;
182717a519f9SDimitry Andric 
182817a519f9SDimitry Andric     case Type::MemberPointer:
182917a519f9SDimitry Andric       type = cast<MemberPointerType>(ty)->getPointeeType();
183017a519f9SDimitry Andric       break;
183117a519f9SDimitry Andric 
183217a519f9SDimitry Andric     case Type::ConstantArray:
183317a519f9SDimitry Andric     case Type::IncompleteArray:
183417a519f9SDimitry Andric       // Losing element qualification here is fine.
183517a519f9SDimitry Andric       type = cast<ArrayType>(ty)->getElementType();
183617a519f9SDimitry Andric       break;
183717a519f9SDimitry Andric 
183817a519f9SDimitry Andric     case Type::VariableArray: {
183917a519f9SDimitry Andric       // Losing element qualification here is fine.
184017a519f9SDimitry Andric       const VariableArrayType *vat = cast<VariableArrayType>(ty);
184117a519f9SDimitry Andric 
184217a519f9SDimitry Andric       // Unknown size indication requires no size computation.
184317a519f9SDimitry Andric       // Otherwise, evaluate and record it.
184417a519f9SDimitry Andric       if (const Expr *size = vat->getSizeExpr()) {
184517a519f9SDimitry Andric         // It's possible that we might have emitted this already,
184617a519f9SDimitry Andric         // e.g. with a typedef and a pointer to it.
184717a519f9SDimitry Andric         llvm::Value *&entry = VLASizeMap[size];
184817a519f9SDimitry Andric         if (!entry) {
18493861d79fSDimitry Andric           llvm::Value *Size = EmitScalarExpr(size);
18503861d79fSDimitry Andric 
18513861d79fSDimitry Andric           // C11 6.7.6.2p5:
18523861d79fSDimitry Andric           //   If the size is an expression that is not an integer constant
18533861d79fSDimitry Andric           //   expression [...] each time it is evaluated it shall have a value
18543861d79fSDimitry Andric           //   greater than zero.
185539d628a0SDimitry Andric           if (SanOpts.has(SanitizerKind::VLABound) &&
18563861d79fSDimitry Andric               size->getType()->isSignedIntegerType()) {
185759d1ed5bSDimitry Andric             SanitizerScope SanScope(this);
18583861d79fSDimitry Andric             llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
18593861d79fSDimitry Andric             llvm::Constant *StaticArgs[] = {
18603861d79fSDimitry Andric               EmitCheckSourceLocation(size->getLocStart()),
18613861d79fSDimitry Andric               EmitCheckTypeDescriptor(size->getType())
18623861d79fSDimitry Andric             };
186339d628a0SDimitry Andric             EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
186439d628a0SDimitry Andric                                      SanitizerKind::VLABound),
186544290647SDimitry Andric                       SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
18663861d79fSDimitry Andric           }
18673861d79fSDimitry Andric 
186817a519f9SDimitry Andric           // Always zexting here would be wrong if it weren't
186917a519f9SDimitry Andric           // undefined behavior to have a negative bound.
18703861d79fSDimitry Andric           entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
187117a519f9SDimitry Andric         }
187217a519f9SDimitry Andric       }
187317a519f9SDimitry Andric       type = vat->getElementType();
187417a519f9SDimitry Andric       break;
1875f22ef01cSRoman Divacky     }
1876f22ef01cSRoman Divacky 
187717a519f9SDimitry Andric     case Type::FunctionProto:
187817a519f9SDimitry Andric     case Type::FunctionNoProto:
187959d1ed5bSDimitry Andric       type = cast<FunctionType>(ty)->getReturnType();
188017a519f9SDimitry Andric       break;
18816122f3e6SDimitry Andric 
1882dff0c46cSDimitry Andric     case Type::Paren:
1883dff0c46cSDimitry Andric     case Type::TypeOf:
1884dff0c46cSDimitry Andric     case Type::UnaryTransform:
1885dff0c46cSDimitry Andric     case Type::Attributed:
1886dff0c46cSDimitry Andric     case Type::SubstTemplateTypeParm:
1887f785676fSDimitry Andric     case Type::PackExpansion:
1888dff0c46cSDimitry Andric       // Keep walking after single level desugaring.
1889dff0c46cSDimitry Andric       type = type.getSingleStepDesugaredType(getContext());
1890dff0c46cSDimitry Andric       break;
1891dff0c46cSDimitry Andric 
1892dff0c46cSDimitry Andric     case Type::Typedef:
1893dff0c46cSDimitry Andric     case Type::Decltype:
1894dff0c46cSDimitry Andric     case Type::Auto:
1895dff0c46cSDimitry Andric       // Stop walking: nothing to do.
1896dff0c46cSDimitry Andric       return;
1897dff0c46cSDimitry Andric 
1898dff0c46cSDimitry Andric     case Type::TypeOfExpr:
1899dff0c46cSDimitry Andric       // Stop walking: emit typeof expression.
1900dff0c46cSDimitry Andric       EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
1901dff0c46cSDimitry Andric       return;
1902dff0c46cSDimitry Andric 
19036122f3e6SDimitry Andric     case Type::Atomic:
19046122f3e6SDimitry Andric       type = cast<AtomicType>(ty)->getValueType();
19056122f3e6SDimitry Andric       break;
1906444ed5c5SDimitry Andric 
1907444ed5c5SDimitry Andric     case Type::Pipe:
1908444ed5c5SDimitry Andric       type = cast<PipeType>(ty)->getElementType();
1909444ed5c5SDimitry Andric       break;
1910f22ef01cSRoman Divacky     }
191117a519f9SDimitry Andric   } while (type->isVariablyModifiedType());
1912f22ef01cSRoman Divacky }
1913f22ef01cSRoman Divacky 
19140623d748SDimitry Andric Address CodeGenFunction::EmitVAListRef(const Expr* E) {
19152754fe60SDimitry Andric   if (getContext().getBuiltinVaListType()->isArrayType())
19160623d748SDimitry Andric     return EmitPointerWithAlignment(E);
19170623d748SDimitry Andric   return EmitLValue(E).getAddress();
19180623d748SDimitry Andric }
19190623d748SDimitry Andric 
19200623d748SDimitry Andric Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
1921f22ef01cSRoman Divacky   return EmitLValue(E).getAddress();
1922f22ef01cSRoman Divacky }
1923f22ef01cSRoman Divacky 
1924e580952dSDimitry Andric void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
192544290647SDimitry Andric                                               const APValue &Init) {
192644290647SDimitry Andric   assert(!Init.isUninit() && "Invalid DeclRefExpr initializer!");
1927e580952dSDimitry Andric   if (CGDebugInfo *Dbg = getDebugInfo())
1928e7145dcbSDimitry Andric     if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
19292754fe60SDimitry Andric       Dbg->EmitGlobalVariable(E->getDecl(), Init);
19302754fe60SDimitry Andric }
19312754fe60SDimitry Andric 
19322754fe60SDimitry Andric CodeGenFunction::PeepholeProtection
19332754fe60SDimitry Andric CodeGenFunction::protectFromPeepholes(RValue rvalue) {
19342754fe60SDimitry Andric   // At the moment, the only aggressive peephole we do in IR gen
19352754fe60SDimitry Andric   // is trunc(zext) folding, but if we add more, we can easily
19362754fe60SDimitry Andric   // extend this protection.
19372754fe60SDimitry Andric 
19382754fe60SDimitry Andric   if (!rvalue.isScalar()) return PeepholeProtection();
19392754fe60SDimitry Andric   llvm::Value *value = rvalue.getScalarVal();
19402754fe60SDimitry Andric   if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
19412754fe60SDimitry Andric 
19422754fe60SDimitry Andric   // Just make an extra bitcast.
19432754fe60SDimitry Andric   assert(HaveInsertPoint());
19442754fe60SDimitry Andric   llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
19452754fe60SDimitry Andric                                                   Builder.GetInsertBlock());
19462754fe60SDimitry Andric 
19472754fe60SDimitry Andric   PeepholeProtection protection;
19482754fe60SDimitry Andric   protection.Inst = inst;
19492754fe60SDimitry Andric   return protection;
19502754fe60SDimitry Andric }
19512754fe60SDimitry Andric 
19522754fe60SDimitry Andric void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
19532754fe60SDimitry Andric   if (!protection.Inst) return;
19542754fe60SDimitry Andric 
19552754fe60SDimitry Andric   // In theory, we could try to duplicate the peepholes now, but whatever.
19562754fe60SDimitry Andric   protection.Inst->eraseFromParent();
1957e580952dSDimitry Andric }
19586122f3e6SDimitry Andric 
19596122f3e6SDimitry Andric llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
19606122f3e6SDimitry Andric                                                  llvm::Value *AnnotatedVal,
1961139f7f9bSDimitry Andric                                                  StringRef AnnotationStr,
19626122f3e6SDimitry Andric                                                  SourceLocation Location) {
19636122f3e6SDimitry Andric   llvm::Value *Args[4] = {
19646122f3e6SDimitry Andric     AnnotatedVal,
19656122f3e6SDimitry Andric     Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
19666122f3e6SDimitry Andric     Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
19676122f3e6SDimitry Andric     CGM.EmitAnnotationLineNo(Location)
19686122f3e6SDimitry Andric   };
19696122f3e6SDimitry Andric   return Builder.CreateCall(AnnotationFn, Args);
19706122f3e6SDimitry Andric }
19716122f3e6SDimitry Andric 
19726122f3e6SDimitry Andric void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
19736122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
19746122f3e6SDimitry Andric   // FIXME We create a new bitcast for every annotation because that's what
19756122f3e6SDimitry Andric   // llvm-gcc was doing.
197659d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
19776122f3e6SDimitry Andric     EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
19786122f3e6SDimitry Andric                        Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
197959d1ed5bSDimitry Andric                        I->getAnnotation(), D->getLocation());
19806122f3e6SDimitry Andric }
19816122f3e6SDimitry Andric 
19820623d748SDimitry Andric Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
19830623d748SDimitry Andric                                               Address Addr) {
19846122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
19850623d748SDimitry Andric   llvm::Value *V = Addr.getPointer();
19866122f3e6SDimitry Andric   llvm::Type *VTy = V->getType();
19876122f3e6SDimitry Andric   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
19886122f3e6SDimitry Andric                                     CGM.Int8PtrTy);
19896122f3e6SDimitry Andric 
199059d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
19916122f3e6SDimitry Andric     // FIXME Always emit the cast inst so we can differentiate between
19926122f3e6SDimitry Andric     // annotation on the first field of a struct and annotation on the struct
19936122f3e6SDimitry Andric     // itself.
19946122f3e6SDimitry Andric     if (VTy != CGM.Int8PtrTy)
19956122f3e6SDimitry Andric       V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
199659d1ed5bSDimitry Andric     V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
19976122f3e6SDimitry Andric     V = Builder.CreateBitCast(V, VTy);
19986122f3e6SDimitry Andric   }
19996122f3e6SDimitry Andric 
20000623d748SDimitry Andric   return Address(V, Addr.getAlignment());
20016122f3e6SDimitry Andric }
2002f785676fSDimitry Andric 
2003f785676fSDimitry Andric CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
200459d1ed5bSDimitry Andric 
200559d1ed5bSDimitry Andric CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
200659d1ed5bSDimitry Andric     : CGF(CGF) {
200759d1ed5bSDimitry Andric   assert(!CGF->IsSanitizerScope);
200859d1ed5bSDimitry Andric   CGF->IsSanitizerScope = true;
200959d1ed5bSDimitry Andric }
201059d1ed5bSDimitry Andric 
201159d1ed5bSDimitry Andric CodeGenFunction::SanitizerScope::~SanitizerScope() {
201259d1ed5bSDimitry Andric   CGF->IsSanitizerScope = false;
201359d1ed5bSDimitry Andric }
201459d1ed5bSDimitry Andric 
201559d1ed5bSDimitry Andric void CodeGenFunction::InsertHelper(llvm::Instruction *I,
201659d1ed5bSDimitry Andric                                    const llvm::Twine &Name,
201759d1ed5bSDimitry Andric                                    llvm::BasicBlock *BB,
201859d1ed5bSDimitry Andric                                    llvm::BasicBlock::iterator InsertPt) const {
201959d1ed5bSDimitry Andric   LoopStack.InsertHelper(I);
202039d628a0SDimitry Andric   if (IsSanitizerScope)
202139d628a0SDimitry Andric     CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
202259d1ed5bSDimitry Andric }
202359d1ed5bSDimitry Andric 
2024e7145dcbSDimitry Andric void CGBuilderInserter::InsertHelper(
202559d1ed5bSDimitry Andric     llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
202659d1ed5bSDimitry Andric     llvm::BasicBlock::iterator InsertPt) const {
2027e7145dcbSDimitry Andric   llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
202859d1ed5bSDimitry Andric   if (CGF)
202959d1ed5bSDimitry Andric     CGF->InsertHelper(I, Name, BB, InsertPt);
203059d1ed5bSDimitry Andric }
203159d1ed5bSDimitry Andric 
20320623d748SDimitry Andric static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
20330623d748SDimitry Andric                                 CodeGenModule &CGM, const FunctionDecl *FD,
20340623d748SDimitry Andric                                 std::string &FirstMissing) {
20350623d748SDimitry Andric   // If there aren't any required features listed then go ahead and return.
20360623d748SDimitry Andric   if (ReqFeatures.empty())
20370623d748SDimitry Andric     return false;
20380623d748SDimitry Andric 
20390623d748SDimitry Andric   // Now build up the set of caller features and verify that all the required
20400623d748SDimitry Andric   // features are there.
20410623d748SDimitry Andric   llvm::StringMap<bool> CallerFeatureMap;
20420623d748SDimitry Andric   CGM.getFunctionFeatureMap(CallerFeatureMap, FD);
20430623d748SDimitry Andric 
20440623d748SDimitry Andric   // If we have at least one of the features in the feature list return
20450623d748SDimitry Andric   // true, otherwise return false.
20460623d748SDimitry Andric   return std::all_of(
20470623d748SDimitry Andric       ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
20480623d748SDimitry Andric         SmallVector<StringRef, 1> OrFeatures;
20490623d748SDimitry Andric         Feature.split(OrFeatures, "|");
20500623d748SDimitry Andric         return std::any_of(OrFeatures.begin(), OrFeatures.end(),
20510623d748SDimitry Andric                            [&](StringRef Feature) {
20520623d748SDimitry Andric                              if (!CallerFeatureMap.lookup(Feature)) {
20530623d748SDimitry Andric                                FirstMissing = Feature.str();
20540623d748SDimitry Andric                                return false;
20550623d748SDimitry Andric                              }
20560623d748SDimitry Andric                              return true;
20570623d748SDimitry Andric                            });
20580623d748SDimitry Andric       });
20590623d748SDimitry Andric }
20600623d748SDimitry Andric 
20610623d748SDimitry Andric // Emits an error if we don't have a valid set of target features for the
20620623d748SDimitry Andric // called function.
20630623d748SDimitry Andric void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
20640623d748SDimitry Andric                                           const FunctionDecl *TargetDecl) {
20650623d748SDimitry Andric   // Early exit if this is an indirect call.
20660623d748SDimitry Andric   if (!TargetDecl)
20670623d748SDimitry Andric     return;
20680623d748SDimitry Andric 
20690623d748SDimitry Andric   // Get the current enclosing function if it exists. If it doesn't
20700623d748SDimitry Andric   // we can't check the target features anyhow.
20710623d748SDimitry Andric   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl);
20720623d748SDimitry Andric   if (!FD)
20730623d748SDimitry Andric     return;
20740623d748SDimitry Andric 
20750623d748SDimitry Andric   // Grab the required features for the call. For a builtin this is listed in
20760623d748SDimitry Andric   // the td file with the default cpu, for an always_inline function this is any
20770623d748SDimitry Andric   // listed cpu and any listed features.
20780623d748SDimitry Andric   unsigned BuiltinID = TargetDecl->getBuiltinID();
20790623d748SDimitry Andric   std::string MissingFeature;
20800623d748SDimitry Andric   if (BuiltinID) {
20810623d748SDimitry Andric     SmallVector<StringRef, 1> ReqFeatures;
20820623d748SDimitry Andric     const char *FeatureList =
20830623d748SDimitry Andric         CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
20840623d748SDimitry Andric     // Return if the builtin doesn't have any required features.
20850623d748SDimitry Andric     if (!FeatureList || StringRef(FeatureList) == "")
20860623d748SDimitry Andric       return;
20870623d748SDimitry Andric     StringRef(FeatureList).split(ReqFeatures, ",");
20880623d748SDimitry Andric     if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
20890623d748SDimitry Andric       CGM.getDiags().Report(E->getLocStart(), diag::err_builtin_needs_feature)
20900623d748SDimitry Andric           << TargetDecl->getDeclName()
20910623d748SDimitry Andric           << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
20920623d748SDimitry Andric 
20930623d748SDimitry Andric   } else if (TargetDecl->hasAttr<TargetAttr>()) {
20940623d748SDimitry Andric     // Get the required features for the callee.
20950623d748SDimitry Andric     SmallVector<StringRef, 1> ReqFeatures;
20960623d748SDimitry Andric     llvm::StringMap<bool> CalleeFeatureMap;
20970623d748SDimitry Andric     CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
20980623d748SDimitry Andric     for (const auto &F : CalleeFeatureMap) {
20990623d748SDimitry Andric       // Only positive features are "required".
21000623d748SDimitry Andric       if (F.getValue())
21010623d748SDimitry Andric         ReqFeatures.push_back(F.getKey());
21020623d748SDimitry Andric     }
21030623d748SDimitry Andric     if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
21040623d748SDimitry Andric       CGM.getDiags().Report(E->getLocStart(), diag::err_function_needs_feature)
21050623d748SDimitry Andric           << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
21060623d748SDimitry Andric   }
21070623d748SDimitry Andric }
2108e7145dcbSDimitry Andric 
2109e7145dcbSDimitry Andric void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2110e7145dcbSDimitry Andric   if (!CGM.getCodeGenOpts().SanitizeStats)
2111e7145dcbSDimitry Andric     return;
2112e7145dcbSDimitry Andric 
2113e7145dcbSDimitry Andric   llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2114e7145dcbSDimitry Andric   IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2115e7145dcbSDimitry Andric   CGM.getSanStats().create(IRB, SSK);
2116e7145dcbSDimitry Andric }
211744290647SDimitry Andric 
211844290647SDimitry Andric llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
211944290647SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
212044290647SDimitry Andric     return DI->SourceLocToDebugLoc(Location);
212144290647SDimitry Andric 
212244290647SDimitry Andric   return llvm::DebugLoc();
212344290647SDimitry Andric }
2124