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"
253ea909ccSDimitry Andric #include "clang/AST/ASTLambda.h"
26f22ef01cSRoman Divacky #include "clang/AST/Decl.h"
27f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h"
28f22ef01cSRoman Divacky #include "clang/AST/StmtCXX.h"
29f41fbc90SDimitry Andric #include "clang/AST/StmtObjC.h"
300623d748SDimitry Andric #include "clang/Basic/Builtins.h"
31*b5893f02SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
32139f7f9bSDimitry Andric #include "clang/Basic/TargetInfo.h"
33f785676fSDimitry Andric #include "clang/CodeGen/CGFunctionInfo.h"
34*b5893f02SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h"
35139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
369a199699SDimitry Andric #include "llvm/IR/Dominators.h"
37139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
38139f7f9bSDimitry Andric #include "llvm/IR/MDBuilder.h"
39139f7f9bSDimitry Andric #include "llvm/IR/Operator.h"
409a199699SDimitry Andric #include "llvm/Transforms/Utils/PromoteMemToReg.h"
41f22ef01cSRoman Divacky using namespace clang;
42f22ef01cSRoman Divacky using namespace CodeGen;
43f22ef01cSRoman Divacky 
4444290647SDimitry Andric /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
4544290647SDimitry Andric /// markers.
shouldEmitLifetimeMarkers(const CodeGenOptions & CGOpts,const LangOptions & LangOpts)4644290647SDimitry Andric static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
4744290647SDimitry Andric                                       const LangOptions &LangOpts) {
4824e2fe98SDimitry Andric   if (CGOpts.DisableLifetimeMarkers)
4924e2fe98SDimitry Andric     return false;
5024e2fe98SDimitry Andric 
5144290647SDimitry Andric   // Disable lifetime markers in msan builds.
5244290647SDimitry Andric   // FIXME: Remove this when msan works with lifetime markers.
5344290647SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Memory))
5444290647SDimitry Andric     return false;
5544290647SDimitry Andric 
5620e90f04SDimitry Andric   // Asan uses markers for use-after-scope checks.
5720e90f04SDimitry Andric   if (CGOpts.SanitizeAddressUseAfterScope)
5820e90f04SDimitry Andric     return true;
5920e90f04SDimitry Andric 
6044290647SDimitry Andric   // For now, only in optimized builds.
6144290647SDimitry Andric   return CGOpts.OptimizationLevel != 0;
6244290647SDimitry Andric }
6344290647SDimitry Andric 
CodeGenFunction(CodeGenModule & cgm,bool suppressNewContext)647ae0e2c9SDimitry Andric CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
65284c1978SDimitry Andric     : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
660623d748SDimitry Andric       Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
6759d1ed5bSDimitry Andric               CGBuilderInserterTy(this)),
684ba319b5SDimitry Andric       SanOpts(CGM.getLangOpts().Sanitize), DebugInfo(CGM.getModuleDebugInfo()),
694ba319b5SDimitry Andric       PGO(cgm), ShouldEmitLifetimeMarkers(shouldEmitLifetimeMarkers(
704ba319b5SDimitry Andric                     CGM.getCodeGenOpts(), CGM.getLangOpts())) {
717ae0e2c9SDimitry Andric   if (!suppressNewContext)
72e580952dSDimitry Andric     CGM.getCXXABI().getMangleContext().startNewFunction();
73139f7f9bSDimitry Andric 
74139f7f9bSDimitry Andric   llvm::FastMathFlags FMF;
75139f7f9bSDimitry Andric   if (CGM.getLangOpts().FastMath)
769a199699SDimitry Andric     FMF.setFast();
77139f7f9bSDimitry Andric   if (CGM.getLangOpts().FiniteMathOnly) {
78139f7f9bSDimitry Andric     FMF.setNoNaNs();
79139f7f9bSDimitry Andric     FMF.setNoInfs();
80139f7f9bSDimitry Andric   }
8139d628a0SDimitry Andric   if (CGM.getCodeGenOpts().NoNaNsFPMath) {
8239d628a0SDimitry Andric     FMF.setNoNaNs();
8339d628a0SDimitry Andric   }
8439d628a0SDimitry Andric   if (CGM.getCodeGenOpts().NoSignedZeros) {
8539d628a0SDimitry Andric     FMF.setNoSignedZeros();
8639d628a0SDimitry Andric   }
8733956c43SDimitry Andric   if (CGM.getCodeGenOpts().ReciprocalMath) {
8833956c43SDimitry Andric     FMF.setAllowReciprocal();
8933956c43SDimitry Andric   }
909a199699SDimitry Andric   if (CGM.getCodeGenOpts().Reassociate) {
919a199699SDimitry Andric     FMF.setAllowReassoc();
929a199699SDimitry Andric   }
93444ed5c5SDimitry Andric   Builder.setFastMathFlags(FMF);
94f22ef01cSRoman Divacky }
95f22ef01cSRoman Divacky 
~CodeGenFunction()96dff0c46cSDimitry Andric CodeGenFunction::~CodeGenFunction() {
97f785676fSDimitry Andric   assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
98f785676fSDimitry Andric 
99dff0c46cSDimitry Andric   // If there are any unclaimed block infos, go ahead and destroy them
100dff0c46cSDimitry Andric   // now.  This can happen if IR-gen gets clever and skips evaluating
101dff0c46cSDimitry Andric   // something.
102dff0c46cSDimitry Andric   if (FirstBlockInfo)
103dff0c46cSDimitry Andric     destroyBlockInfos(FirstBlockInfo);
10459d1ed5bSDimitry Andric 
10598221d2eSDimitry Andric   if (getLangOpts().OpenMP && CurFn)
10633956c43SDimitry Andric     CGM.getOpenMPRuntime().functionFinished(*this);
10759d1ed5bSDimitry Andric }
108dff0c46cSDimitry Andric 
getNaturalPointeeTypeAlignment(QualType T,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo)1090623d748SDimitry Andric CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T,
1109a199699SDimitry Andric                                                     LValueBaseInfo *BaseInfo,
1119a199699SDimitry Andric                                                     TBAAAccessInfo *TBAAInfo) {
1129a199699SDimitry Andric   return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
1139a199699SDimitry Andric                                  /* forPointeeType= */ true);
1140623d748SDimitry Andric }
1150623d748SDimitry Andric 
getNaturalTypeAlignment(QualType T,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo,bool forPointeeType)1160623d748SDimitry Andric CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T,
117d8866befSDimitry Andric                                                    LValueBaseInfo *BaseInfo,
1189a199699SDimitry Andric                                                    TBAAAccessInfo *TBAAInfo,
1190623d748SDimitry Andric                                                    bool forPointeeType) {
1209a199699SDimitry Andric   if (TBAAInfo)
1219a199699SDimitry Andric     *TBAAInfo = CGM.getTBAAAccessInfo(T);
1229a199699SDimitry Andric 
1230623d748SDimitry Andric   // Honor alignment typedef attributes even on incomplete types.
1240623d748SDimitry Andric   // We also honor them straight for C++ class types, even as pointees;
1250623d748SDimitry Andric   // there's an expressivity gap here.
1260623d748SDimitry Andric   if (auto TT = T->getAs<TypedefType>()) {
1270623d748SDimitry Andric     if (auto Align = TT->getDecl()->getMaxAlignment()) {
128d8866befSDimitry Andric       if (BaseInfo)
1299a199699SDimitry Andric         *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
1300623d748SDimitry Andric       return getContext().toCharUnitsFromBits(Align);
1310623d748SDimitry Andric     }
1320623d748SDimitry Andric   }
1330623d748SDimitry Andric 
134d8866befSDimitry Andric   if (BaseInfo)
1359a199699SDimitry Andric     *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
1360623d748SDimitry Andric 
13739d628a0SDimitry Andric   CharUnits Alignment;
1380623d748SDimitry Andric   if (T->isIncompleteType()) {
1390623d748SDimitry Andric     Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best.
1400623d748SDimitry Andric   } else {
1410623d748SDimitry Andric     // For C++ class pointees, we don't know whether we're pointing at a
1420623d748SDimitry Andric     // base or a complete object, so we generally need to use the
1430623d748SDimitry Andric     // non-virtual alignment.
1440623d748SDimitry Andric     const CXXRecordDecl *RD;
1450623d748SDimitry Andric     if (forPointeeType && (RD = T->getAsCXXRecordDecl())) {
1460623d748SDimitry Andric       Alignment = CGM.getClassPointerAlignment(RD);
1470623d748SDimitry Andric     } else {
14839d628a0SDimitry Andric       Alignment = getContext().getTypeAlignInChars(T);
14920e90f04SDimitry Andric       if (T.getQualifiers().hasUnaligned())
15020e90f04SDimitry Andric         Alignment = CharUnits::One();
1510623d748SDimitry Andric     }
1520623d748SDimitry Andric 
1530623d748SDimitry Andric     // Cap to the global maximum type alignment unless the alignment
1540623d748SDimitry Andric     // was somehow explicit on the type.
1550623d748SDimitry Andric     if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
1560623d748SDimitry Andric       if (Alignment.getQuantity() > MaxAlign &&
15739d628a0SDimitry Andric           !getContext().isAlignmentRequired(T))
15839d628a0SDimitry Andric         Alignment = CharUnits::fromQuantity(MaxAlign);
15939d628a0SDimitry Andric     }
16039d628a0SDimitry Andric   }
1610623d748SDimitry Andric   return Alignment;
1620623d748SDimitry Andric }
1630623d748SDimitry Andric 
MakeNaturalAlignAddrLValue(llvm::Value * V,QualType T)1640623d748SDimitry Andric LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
165d8866befSDimitry Andric   LValueBaseInfo BaseInfo;
1669a199699SDimitry Andric   TBAAAccessInfo TBAAInfo;
1679a199699SDimitry Andric   CharUnits Alignment = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo);
168d8866befSDimitry Andric   return LValue::MakeAddr(Address(V, Alignment), T, getContext(), BaseInfo,
1699a199699SDimitry Andric                           TBAAInfo);
1700623d748SDimitry Andric }
1710623d748SDimitry Andric 
1720623d748SDimitry Andric /// Given a value of type T* that may not be to a complete object,
1730623d748SDimitry Andric /// construct an l-value with the natural pointee alignment of T.
1740623d748SDimitry Andric LValue
MakeNaturalAlignPointeeAddrLValue(llvm::Value * V,QualType T)1750623d748SDimitry Andric CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
176d8866befSDimitry Andric   LValueBaseInfo BaseInfo;
1779a199699SDimitry Andric   TBAAAccessInfo TBAAInfo;
1789a199699SDimitry Andric   CharUnits Align = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo,
1799a199699SDimitry Andric                                             /* forPointeeType= */ true);
1809a199699SDimitry Andric   return MakeAddrLValue(Address(V, Align), T, BaseInfo, TBAAInfo);
1810623d748SDimitry Andric }
1820623d748SDimitry Andric 
183f22ef01cSRoman Divacky 
ConvertTypeForMem(QualType T)18417a519f9SDimitry Andric llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
185f22ef01cSRoman Divacky   return CGM.getTypes().ConvertTypeForMem(T);
186f22ef01cSRoman Divacky }
187f22ef01cSRoman Divacky 
ConvertType(QualType T)18817a519f9SDimitry Andric llvm::Type *CodeGenFunction::ConvertType(QualType T) {
189f22ef01cSRoman Divacky   return CGM.getTypes().ConvertType(T);
190f22ef01cSRoman Divacky }
191f22ef01cSRoman Divacky 
getEvaluationKind(QualType type)192139f7f9bSDimitry Andric TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
193139f7f9bSDimitry Andric   type = type.getCanonicalType();
194139f7f9bSDimitry Andric   while (true) {
195139f7f9bSDimitry Andric     switch (type->getTypeClass()) {
196bd5abe19SDimitry Andric #define TYPE(name, parent)
197bd5abe19SDimitry Andric #define ABSTRACT_TYPE(name, parent)
198bd5abe19SDimitry Andric #define NON_CANONICAL_TYPE(name, parent) case Type::name:
199bd5abe19SDimitry Andric #define DEPENDENT_TYPE(name, parent) case Type::name:
200bd5abe19SDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
201bd5abe19SDimitry Andric #include "clang/AST/TypeNodes.def"
202bd5abe19SDimitry Andric       llvm_unreachable("non-canonical or dependent type in IR-generation");
203bd5abe19SDimitry Andric 
204284c1978SDimitry Andric     case Type::Auto:
20520e90f04SDimitry Andric     case Type::DeducedTemplateSpecialization:
20620e90f04SDimitry Andric       llvm_unreachable("undeduced type in IR-generation");
207284c1978SDimitry Andric 
208139f7f9bSDimitry Andric     // Various scalar types.
209bd5abe19SDimitry Andric     case Type::Builtin:
210bd5abe19SDimitry Andric     case Type::Pointer:
211bd5abe19SDimitry Andric     case Type::BlockPointer:
212bd5abe19SDimitry Andric     case Type::LValueReference:
213bd5abe19SDimitry Andric     case Type::RValueReference:
214bd5abe19SDimitry Andric     case Type::MemberPointer:
215bd5abe19SDimitry Andric     case Type::Vector:
216bd5abe19SDimitry Andric     case Type::ExtVector:
217bd5abe19SDimitry Andric     case Type::FunctionProto:
218bd5abe19SDimitry Andric     case Type::FunctionNoProto:
219bd5abe19SDimitry Andric     case Type::Enum:
220bd5abe19SDimitry Andric     case Type::ObjCObjectPointer:
221444ed5c5SDimitry Andric     case Type::Pipe:
222139f7f9bSDimitry Andric       return TEK_Scalar;
223bd5abe19SDimitry Andric 
224139f7f9bSDimitry Andric     // Complexes.
225bd5abe19SDimitry Andric     case Type::Complex:
226139f7f9bSDimitry Andric       return TEK_Complex;
227139f7f9bSDimitry Andric 
228139f7f9bSDimitry Andric     // Arrays, records, and Objective-C objects.
229bd5abe19SDimitry Andric     case Type::ConstantArray:
230bd5abe19SDimitry Andric     case Type::IncompleteArray:
231bd5abe19SDimitry Andric     case Type::VariableArray:
232bd5abe19SDimitry Andric     case Type::Record:
233bd5abe19SDimitry Andric     case Type::ObjCObject:
234bd5abe19SDimitry Andric     case Type::ObjCInterface:
235139f7f9bSDimitry Andric       return TEK_Aggregate;
2366122f3e6SDimitry Andric 
237139f7f9bSDimitry Andric     // We operate on atomic values according to their underlying type.
2386122f3e6SDimitry Andric     case Type::Atomic:
239139f7f9bSDimitry Andric       type = cast<AtomicType>(type)->getValueType();
240139f7f9bSDimitry Andric       continue;
241bd5abe19SDimitry Andric     }
242bd5abe19SDimitry Andric     llvm_unreachable("unknown type kind!");
243f22ef01cSRoman Divacky   }
244139f7f9bSDimitry Andric }
245f22ef01cSRoman Divacky 
EmitReturnBlock()24639d628a0SDimitry Andric llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
247f22ef01cSRoman Divacky   // For cleanliness, we try to avoid emitting the return block for
248f22ef01cSRoman Divacky   // simple cases.
249f22ef01cSRoman Divacky   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
250f22ef01cSRoman Divacky 
251f22ef01cSRoman Divacky   if (CurBB) {
252f22ef01cSRoman Divacky     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
253f22ef01cSRoman Divacky 
254f22ef01cSRoman Divacky     // We have a valid insert point, reuse it if it is empty or there are no
255f22ef01cSRoman Divacky     // explicit jumps to the return block.
256e580952dSDimitry Andric     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
257e580952dSDimitry Andric       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
258e580952dSDimitry Andric       delete ReturnBlock.getBlock();
259f22ef01cSRoman Divacky     } else
260e580952dSDimitry Andric       EmitBlock(ReturnBlock.getBlock());
26139d628a0SDimitry Andric     return llvm::DebugLoc();
262f22ef01cSRoman Divacky   }
263f22ef01cSRoman Divacky 
264f22ef01cSRoman Divacky   // Otherwise, if the return block is the target of a single direct
265f22ef01cSRoman Divacky   // branch then we can just put the code in that block instead. This
266f22ef01cSRoman Divacky   // cleans up functions which started with a unified return block.
267e580952dSDimitry Andric   if (ReturnBlock.getBlock()->hasOneUse()) {
268f22ef01cSRoman Divacky     llvm::BranchInst *BI =
26959d1ed5bSDimitry Andric       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
270ffd1746dSEd Schouten     if (BI && BI->isUnconditional() &&
271e580952dSDimitry Andric         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
27239d628a0SDimitry Andric       // Record/return the DebugLoc of the simple 'return' expression to be used
27339d628a0SDimitry Andric       // later by the actual 'ret' instruction.
27439d628a0SDimitry Andric       llvm::DebugLoc Loc = BI->getDebugLoc();
275f22ef01cSRoman Divacky       Builder.SetInsertPoint(BI->getParent());
276f22ef01cSRoman Divacky       BI->eraseFromParent();
277e580952dSDimitry Andric       delete ReturnBlock.getBlock();
27839d628a0SDimitry Andric       return Loc;
279f22ef01cSRoman Divacky     }
280f22ef01cSRoman Divacky   }
281f22ef01cSRoman Divacky 
282f22ef01cSRoman Divacky   // FIXME: We are at an unreachable point, there is no reason to emit the block
283f22ef01cSRoman Divacky   // unless it has uses. However, we still need a place to put the debug
284f22ef01cSRoman Divacky   // region.end for now.
285f22ef01cSRoman Divacky 
286e580952dSDimitry Andric   EmitBlock(ReturnBlock.getBlock());
28739d628a0SDimitry Andric   return llvm::DebugLoc();
288ffd1746dSEd Schouten }
289ffd1746dSEd Schouten 
EmitIfUsed(CodeGenFunction & CGF,llvm::BasicBlock * BB)290ffd1746dSEd Schouten static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
291ffd1746dSEd Schouten   if (!BB) return;
292ffd1746dSEd Schouten   if (!BB->use_empty())
293ffd1746dSEd Schouten     return CGF.CurFn->getBasicBlockList().push_back(BB);
294ffd1746dSEd Schouten   delete BB;
295f22ef01cSRoman Divacky }
296f22ef01cSRoman Divacky 
FinishFunction(SourceLocation EndLoc)297f22ef01cSRoman Divacky void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
298f22ef01cSRoman Divacky   assert(BreakContinueStack.empty() &&
299f22ef01cSRoman Divacky          "mismatched push/pop in break/continue stack!");
300f22ef01cSRoman Divacky 
301284c1978SDimitry Andric   bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
302f785676fSDimitry Andric     && NumSimpleReturnExprs == NumReturnExprs
303f785676fSDimitry Andric     && ReturnBlock.getBlock()->use_empty();
304f785676fSDimitry Andric   // Usually the return expression is evaluated before the cleanup
305f785676fSDimitry Andric   // code.  If the function contains only a simple return statement,
306f785676fSDimitry Andric   // such as a constant, the location before the cleanup code becomes
307f785676fSDimitry Andric   // the last useful breakpoint in the function, because the simple
308f785676fSDimitry Andric   // return expression will be evaluated after the cleanup code. To be
309f785676fSDimitry Andric   // safe, set the debug location for cleanup code to the location of
310f785676fSDimitry Andric   // the return statement.  Otherwise the cleanup code should be at the
311f785676fSDimitry Andric   // end of the function's lexical scope.
312f785676fSDimitry Andric   //
313f785676fSDimitry Andric   // If there are multiple branches to the return block, the branch
314f785676fSDimitry Andric   // instructions will get the location of the return statements and
315f785676fSDimitry Andric   // all will be fine.
316284c1978SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo()) {
317284c1978SDimitry Andric     if (OnlySimpleReturnStmts)
318284c1978SDimitry Andric       DI->EmitLocation(Builder, LastStopPoint);
319284c1978SDimitry Andric     else
320139f7f9bSDimitry Andric       DI->EmitLocation(Builder, EndLoc);
321284c1978SDimitry Andric   }
322139f7f9bSDimitry Andric 
32317a519f9SDimitry Andric   // Pop any cleanups that might have been associated with the
32417a519f9SDimitry Andric   // parameters.  Do this in whatever block we're currently in; it's
32517a519f9SDimitry Andric   // important to do this before we enter the return block or return
32617a519f9SDimitry Andric   // edges will be *really* confused.
32733956c43SDimitry Andric   bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
32833956c43SDimitry Andric   bool HasOnlyLifetimeMarkers =
32933956c43SDimitry Andric       HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
33033956c43SDimitry Andric   bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
33133956c43SDimitry Andric   if (HasCleanups) {
332284c1978SDimitry Andric     // Make sure the line table doesn't jump back into the body for
333284c1978SDimitry Andric     // the ret after it's been at EndLoc.
334284c1978SDimitry Andric     if (CGDebugInfo *DI = getDebugInfo())
335284c1978SDimitry Andric       if (OnlySimpleReturnStmts)
336284c1978SDimitry Andric         DI->EmitLocation(Builder, EndLoc);
33733956c43SDimitry Andric 
33833956c43SDimitry Andric     PopCleanupBlocks(PrologueCleanupDepth);
339284c1978SDimitry Andric   }
34017a519f9SDimitry Andric 
341f22ef01cSRoman Divacky   // Emit function epilog (to return).
34239d628a0SDimitry Andric   llvm::DebugLoc Loc = EmitReturnBlock();
343f22ef01cSRoman Divacky 
3449a199699SDimitry Andric   if (ShouldInstrumentFunction()) {
3459a199699SDimitry Andric     if (CGM.getCodeGenOpts().InstrumentFunctions)
3469a199699SDimitry Andric       CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
3479a199699SDimitry Andric     if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
3489a199699SDimitry Andric       CurFn->addFnAttr("instrument-function-exit-inlined",
3499a199699SDimitry Andric                        "__cyg_profile_func_exit");
3509a199699SDimitry Andric   }
351ffd1746dSEd Schouten 
352f22ef01cSRoman Divacky   // Emit debug descriptor for function end.
35339d628a0SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
3546d97bb29SDimitry Andric     DI->EmitFunctionEnd(Builder, CurFn);
355f22ef01cSRoman Divacky 
35639d628a0SDimitry Andric   // Reset the debug location to that of the simple 'return' expression, if any
35739d628a0SDimitry Andric   // rather than that of the end of the function's scope '}'.
35839d628a0SDimitry Andric   ApplyDebugLocation AL(*this, Loc);
359f785676fSDimitry Andric   EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
360f22ef01cSRoman Divacky   EmitEndEHSpec(CurCodeDecl);
361f22ef01cSRoman Divacky 
362ffd1746dSEd Schouten   assert(EHStack.empty() &&
363ffd1746dSEd Schouten          "did not remove all scopes from cleanup stack!");
364ffd1746dSEd Schouten 
365f22ef01cSRoman Divacky   // If someone did an indirect goto, emit the indirect goto block at the end of
366f22ef01cSRoman Divacky   // the function.
367f22ef01cSRoman Divacky   if (IndirectBranch) {
368f22ef01cSRoman Divacky     EmitBlock(IndirectBranch->getParent());
369f22ef01cSRoman Divacky     Builder.ClearInsertionPoint();
370f22ef01cSRoman Divacky   }
371f22ef01cSRoman Divacky 
372875ed548SDimitry Andric   // If some of our locals escaped, insert a call to llvm.localescape in the
37333956c43SDimitry Andric   // entry block.
37433956c43SDimitry Andric   if (!EscapedLocals.empty()) {
37533956c43SDimitry Andric     // Invert the map from local to index into a simple vector. There should be
37633956c43SDimitry Andric     // no holes.
37733956c43SDimitry Andric     SmallVector<llvm::Value *, 4> EscapeArgs;
37833956c43SDimitry Andric     EscapeArgs.resize(EscapedLocals.size());
37933956c43SDimitry Andric     for (auto &Pair : EscapedLocals)
38033956c43SDimitry Andric       EscapeArgs[Pair.second] = Pair.first;
38133956c43SDimitry Andric     llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
382875ed548SDimitry Andric         &CGM.getModule(), llvm::Intrinsic::localescape);
3830623d748SDimitry Andric     CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
38433956c43SDimitry Andric   }
38533956c43SDimitry Andric 
386f22ef01cSRoman Divacky   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
387f22ef01cSRoman Divacky   llvm::Instruction *Ptr = AllocaInsertPt;
38859d1ed5bSDimitry Andric   AllocaInsertPt = nullptr;
389f22ef01cSRoman Divacky   Ptr->eraseFromParent();
390f22ef01cSRoman Divacky 
391f22ef01cSRoman Divacky   // If someone took the address of a label but never did an indirect goto, we
392f22ef01cSRoman Divacky   // made a zero entry PHI node, which is illegal, zap it now.
393f22ef01cSRoman Divacky   if (IndirectBranch) {
394f22ef01cSRoman Divacky     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
395f22ef01cSRoman Divacky     if (PN->getNumIncomingValues() == 0) {
396f22ef01cSRoman Divacky       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
397f22ef01cSRoman Divacky       PN->eraseFromParent();
398f22ef01cSRoman Divacky     }
399f22ef01cSRoman Divacky   }
400ffd1746dSEd Schouten 
4016122f3e6SDimitry Andric   EmitIfUsed(*this, EHResumeBlock);
402ffd1746dSEd Schouten   EmitIfUsed(*this, TerminateLandingPad);
403ffd1746dSEd Schouten   EmitIfUsed(*this, TerminateHandler);
404ffd1746dSEd Schouten   EmitIfUsed(*this, UnreachableBlock);
405ffd1746dSEd Schouten 
40630785c0eSDimitry Andric   for (const auto &FuncletAndParent : TerminateFunclets)
40730785c0eSDimitry Andric     EmitIfUsed(*this, FuncletAndParent.second);
40830785c0eSDimitry Andric 
409ffd1746dSEd Schouten   if (CGM.getCodeGenOpts().EmitDeclMetadata)
410ffd1746dSEd Schouten     EmitDeclMetadata();
41159d1ed5bSDimitry Andric 
41259d1ed5bSDimitry Andric   for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
41359d1ed5bSDimitry Andric            I = DeferredReplacements.begin(),
41459d1ed5bSDimitry Andric            E = DeferredReplacements.end();
41559d1ed5bSDimitry Andric        I != E; ++I) {
41659d1ed5bSDimitry Andric     I->first->replaceAllUsesWith(I->second);
41759d1ed5bSDimitry Andric     I->first->eraseFromParent();
41859d1ed5bSDimitry Andric   }
4199a199699SDimitry Andric 
4209a199699SDimitry Andric   // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
4219a199699SDimitry Andric   // PHIs if the current function is a coroutine. We don't do it for all
4229a199699SDimitry Andric   // functions as it may result in slight increase in numbers of instructions
4239a199699SDimitry Andric   // if compiled with no optimizations. We do it for coroutine as the lifetime
4249a199699SDimitry Andric   // of CleanupDestSlot alloca make correct coroutine frame building very
4259a199699SDimitry Andric   // difficult.
4264ba319b5SDimitry Andric   if (NormalCleanupDest.isValid() && isCoroutine()) {
4279a199699SDimitry Andric     llvm::DominatorTree DT(*CurFn);
4284ba319b5SDimitry Andric     llvm::PromoteMemToReg(
4294ba319b5SDimitry Andric         cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
4304ba319b5SDimitry Andric     NormalCleanupDest = Address::invalid();
4319a199699SDimitry Andric   }
4324ba319b5SDimitry Andric 
433*b5893f02SDimitry Andric   // Scan function arguments for vector width.
434*b5893f02SDimitry Andric   for (llvm::Argument &A : CurFn->args())
435*b5893f02SDimitry Andric     if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
436*b5893f02SDimitry Andric       LargestVectorWidth = std::max(LargestVectorWidth,
437*b5893f02SDimitry Andric                                     VT->getPrimitiveSizeInBits());
438*b5893f02SDimitry Andric 
439*b5893f02SDimitry Andric   // Update vector width based on return type.
440*b5893f02SDimitry Andric   if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
441*b5893f02SDimitry Andric     LargestVectorWidth = std::max(LargestVectorWidth,
442*b5893f02SDimitry Andric                                   VT->getPrimitiveSizeInBits());
443*b5893f02SDimitry Andric 
444*b5893f02SDimitry Andric   // Add the required-vector-width attribute. This contains the max width from:
445*b5893f02SDimitry Andric   // 1. min-vector-width attribute used in the source program.
446*b5893f02SDimitry Andric   // 2. Any builtins used that have a vector width specified.
447*b5893f02SDimitry Andric   // 3. Values passed in and out of inline assembly.
448*b5893f02SDimitry Andric   // 4. Width of vector arguments and return types for this function.
449*b5893f02SDimitry Andric   // 5. Width of vector aguments and return types for functions called by this
450*b5893f02SDimitry Andric   //    function.
451*b5893f02SDimitry Andric   CurFn->addFnAttr("min-legal-vector-width", llvm::utostr(LargestVectorWidth));
452ffd1746dSEd Schouten }
453ffd1746dSEd Schouten 
454ffd1746dSEd Schouten /// ShouldInstrumentFunction - Return true if the current function should be
455ffd1746dSEd Schouten /// instrumented with __cyg_profile_func_* calls
ShouldInstrumentFunction()456ffd1746dSEd Schouten bool CodeGenFunction::ShouldInstrumentFunction() {
4579a199699SDimitry Andric   if (!CGM.getCodeGenOpts().InstrumentFunctions &&
4589a199699SDimitry Andric       !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining &&
4599a199699SDimitry Andric       !CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
460ffd1746dSEd Schouten     return false;
461bd5abe19SDimitry Andric   if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
462ffd1746dSEd Schouten     return false;
463ffd1746dSEd Schouten   return true;
464ffd1746dSEd Schouten }
465ffd1746dSEd Schouten 
466e7145dcbSDimitry Andric /// ShouldXRayInstrument - Return true if the current function should be
467e7145dcbSDimitry Andric /// instrumented with XRay nop sleds.
ShouldXRayInstrumentFunction() const468e7145dcbSDimitry Andric bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
469e7145dcbSDimitry Andric   return CGM.getCodeGenOpts().XRayInstrumentFunctions;
470e7145dcbSDimitry Andric }
471e7145dcbSDimitry Andric 
4729a199699SDimitry Andric /// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
4734ba319b5SDimitry Andric /// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
AlwaysEmitXRayCustomEvents() const4749a199699SDimitry Andric bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
4754ba319b5SDimitry Andric   return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
4764ba319b5SDimitry Andric          (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
4774ba319b5SDimitry Andric           CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
4784ba319b5SDimitry Andric               XRayInstrKind::Custom);
4794ba319b5SDimitry Andric }
4804ba319b5SDimitry Andric 
AlwaysEmitXRayTypedEvents() const4814ba319b5SDimitry Andric bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
4824ba319b5SDimitry Andric   return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
4834ba319b5SDimitry Andric          (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
4844ba319b5SDimitry Andric           CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
4854ba319b5SDimitry Andric               XRayInstrKind::Typed);
4869a199699SDimitry Andric }
487ffd1746dSEd Schouten 
4889a199699SDimitry Andric llvm::Constant *
EncodeAddrForUseInPrologue(llvm::Function * F,llvm::Constant * Addr)4899a199699SDimitry Andric CodeGenFunction::EncodeAddrForUseInPrologue(llvm::Function *F,
4909a199699SDimitry Andric                                             llvm::Constant *Addr) {
4919a199699SDimitry Andric   // Addresses stored in prologue data can't require run-time fixups and must
4929a199699SDimitry Andric   // be PC-relative. Run-time fixups are undesirable because they necessitate
4939a199699SDimitry Andric   // writable text segments, which are unsafe. And absolute addresses are
4949a199699SDimitry Andric   // undesirable because they break PIE mode.
495ffd1746dSEd Schouten 
4969a199699SDimitry Andric   // Add a layer of indirection through a private global. Taking its address
4979a199699SDimitry Andric   // won't result in a run-time fixup, even if Addr has linkonce_odr linkage.
4989a199699SDimitry Andric   auto *GV = new llvm::GlobalVariable(CGM.getModule(), Addr->getType(),
4999a199699SDimitry Andric                                       /*isConstant=*/true,
5009a199699SDimitry Andric                                       llvm::GlobalValue::PrivateLinkage, Addr);
501139f7f9bSDimitry Andric 
5029a199699SDimitry Andric   // Create a PC-relative address.
5039a199699SDimitry Andric   auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV, IntPtrTy);
5049a199699SDimitry Andric   auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F, IntPtrTy);
5059a199699SDimitry Andric   auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt);
5069a199699SDimitry Andric   return (IntPtrTy == Int32Ty)
5079a199699SDimitry Andric              ? PCRelAsInt
5089a199699SDimitry Andric              : llvm::ConstantExpr::getTrunc(PCRelAsInt, Int32Ty);
5099a199699SDimitry Andric }
5109a199699SDimitry Andric 
5119a199699SDimitry Andric llvm::Value *
DecodeAddrUsedInPrologue(llvm::Value * F,llvm::Value * EncodedAddr)5129a199699SDimitry Andric CodeGenFunction::DecodeAddrUsedInPrologue(llvm::Value *F,
5139a199699SDimitry Andric                                           llvm::Value *EncodedAddr) {
5149a199699SDimitry Andric   // Reconstruct the address of the global.
5159a199699SDimitry Andric   auto *PCRelAsInt = Builder.CreateSExt(EncodedAddr, IntPtrTy);
5169a199699SDimitry Andric   auto *FuncAsInt = Builder.CreatePtrToInt(F, IntPtrTy, "func_addr.int");
5179a199699SDimitry Andric   auto *GOTAsInt = Builder.CreateAdd(PCRelAsInt, FuncAsInt, "global_addr.int");
5189a199699SDimitry Andric   auto *GOTAddr = Builder.CreateIntToPtr(GOTAsInt, Int8PtrPtrTy, "global_addr");
5199a199699SDimitry Andric 
5209a199699SDimitry Andric   // Load the original pointer through the global.
5219a199699SDimitry Andric   return Builder.CreateLoad(Address(GOTAddr, getPointerAlign()),
5229a199699SDimitry Andric                             "decoded_addr");
523f22ef01cSRoman Divacky }
524f22ef01cSRoman Divacky 
removeImageAccessQualifier(std::string & TyName)52544290647SDimitry Andric static void removeImageAccessQualifier(std::string& TyName) {
52644290647SDimitry Andric   std::string ReadOnlyQual("__read_only");
52744290647SDimitry Andric   std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
52844290647SDimitry Andric   if (ReadOnlyPos != std::string::npos)
52944290647SDimitry Andric     // "+ 1" for the space after access qualifier.
53044290647SDimitry Andric     TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
53144290647SDimitry Andric   else {
53244290647SDimitry Andric     std::string WriteOnlyQual("__write_only");
53344290647SDimitry Andric     std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
53444290647SDimitry Andric     if (WriteOnlyPos != std::string::npos)
53544290647SDimitry Andric       TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
53644290647SDimitry Andric     else {
53744290647SDimitry Andric       std::string ReadWriteQual("__read_write");
53844290647SDimitry Andric       std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
53944290647SDimitry Andric       if (ReadWritePos != std::string::npos)
54044290647SDimitry Andric         TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
54144290647SDimitry Andric     }
54244290647SDimitry Andric   }
5432754fe60SDimitry Andric }
5442754fe60SDimitry Andric 
545f41fbc90SDimitry Andric // Returns the address space id that should be produced to the
546f41fbc90SDimitry Andric // kernel_arg_addr_space metadata. This is always fixed to the ids
547f41fbc90SDimitry Andric // as specified in the SPIR 2.0 specification in order to differentiate
548f41fbc90SDimitry Andric // for example in clGetKernelArgInfo() implementation between the address
549f41fbc90SDimitry Andric // spaces with targets without unique mapping to the OpenCL address spaces
550f41fbc90SDimitry Andric // (basically all single AS CPUs).
ArgInfoAddressSpace(LangAS AS)5519a199699SDimitry Andric static unsigned ArgInfoAddressSpace(LangAS AS) {
5529a199699SDimitry Andric   switch (AS) {
553f41fbc90SDimitry Andric   case LangAS::opencl_global:   return 1;
554f41fbc90SDimitry Andric   case LangAS::opencl_constant: return 2;
555f41fbc90SDimitry Andric   case LangAS::opencl_local:    return 3;
556f41fbc90SDimitry Andric   case LangAS::opencl_generic:  return 4; // Not in SPIR 2.0 specs.
557f41fbc90SDimitry Andric   default:
558f41fbc90SDimitry Andric     return 0; // Assume private.
559f41fbc90SDimitry Andric   }
560f41fbc90SDimitry Andric }
561f41fbc90SDimitry Andric 
5627ae0e2c9SDimitry Andric // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
5637ae0e2c9SDimitry Andric // information in the program executable. The argument information stored
5647ae0e2c9SDimitry Andric // includes the argument name, its type, the address and access qualifiers used.
GenOpenCLArgMetadata(const FunctionDecl * FD,llvm::Function * Fn,CodeGenModule & CGM,llvm::LLVMContext & Context,CGBuilderTy & Builder,ASTContext & ASTCtx)5657ae0e2c9SDimitry Andric static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
5667ae0e2c9SDimitry Andric                                  CodeGenModule &CGM, llvm::LLVMContext &Context,
567139f7f9bSDimitry Andric                                  CGBuilderTy &Builder, ASTContext &ASTCtx) {
568139f7f9bSDimitry Andric   // Create MDNodes that represent the kernel arg metadata.
5697ae0e2c9SDimitry Andric   // Each MDNode is a list in the form of "key", N number of values which is
5707ae0e2c9SDimitry Andric   // the same number of values as their are kernel arguments.
5717ae0e2c9SDimitry Andric 
57259d1ed5bSDimitry Andric   const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
57359d1ed5bSDimitry Andric 
574139f7f9bSDimitry Andric   // MDNode for the kernel argument address space qualifiers.
57539d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> addressQuals;
576139f7f9bSDimitry Andric 
577139f7f9bSDimitry Andric   // MDNode for the kernel argument access qualifiers (images only).
57839d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> accessQuals;
579139f7f9bSDimitry Andric 
580139f7f9bSDimitry Andric   // MDNode for the kernel argument type names.
58139d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeNames;
582139f7f9bSDimitry Andric 
58339d628a0SDimitry Andric   // MDNode for the kernel argument base type names.
58439d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
58539d628a0SDimitry Andric 
586139f7f9bSDimitry Andric   // MDNode for the kernel argument type qualifiers.
58739d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeQuals;
588139f7f9bSDimitry Andric 
5897ae0e2c9SDimitry Andric   // MDNode for the kernel argument names.
59039d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argNames;
5917ae0e2c9SDimitry Andric 
5927ae0e2c9SDimitry Andric   for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
5937ae0e2c9SDimitry Andric     const ParmVarDecl *parm = FD->getParamDecl(i);
594139f7f9bSDimitry Andric     QualType ty = parm->getType();
595139f7f9bSDimitry Andric     std::string typeQuals;
596139f7f9bSDimitry Andric 
597139f7f9bSDimitry Andric     if (ty->isPointerType()) {
598139f7f9bSDimitry Andric       QualType pointeeTy = ty->getPointeeType();
599139f7f9bSDimitry Andric 
600139f7f9bSDimitry Andric       // Get address qualifier.
60139d628a0SDimitry Andric       addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
602f41fbc90SDimitry Andric         ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
603139f7f9bSDimitry Andric 
604139f7f9bSDimitry Andric       // Get argument type name.
60559d1ed5bSDimitry Andric       std::string typeName =
60659d1ed5bSDimitry Andric           pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
607139f7f9bSDimitry Andric 
608139f7f9bSDimitry Andric       // Turn "unsigned type" to "utype"
609139f7f9bSDimitry Andric       std::string::size_type pos = typeName.find("unsigned");
61039d628a0SDimitry Andric       if (pointeeTy.isCanonical() && pos != std::string::npos)
611139f7f9bSDimitry Andric         typeName.erase(pos+1, 8);
612139f7f9bSDimitry Andric 
613139f7f9bSDimitry Andric       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
614139f7f9bSDimitry Andric 
61539d628a0SDimitry Andric       std::string baseTypeName =
61639d628a0SDimitry Andric           pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
61739d628a0SDimitry Andric               Policy) +
61839d628a0SDimitry Andric           "*";
61939d628a0SDimitry Andric 
62039d628a0SDimitry Andric       // Turn "unsigned type" to "utype"
62139d628a0SDimitry Andric       pos = baseTypeName.find("unsigned");
62239d628a0SDimitry Andric       if (pos != std::string::npos)
62339d628a0SDimitry Andric         baseTypeName.erase(pos+1, 8);
62439d628a0SDimitry Andric 
62539d628a0SDimitry Andric       argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
62639d628a0SDimitry Andric 
627139f7f9bSDimitry Andric       // Get argument type qualifiers:
628139f7f9bSDimitry Andric       if (ty.isRestrictQualified())
629139f7f9bSDimitry Andric         typeQuals = "restrict";
630139f7f9bSDimitry Andric       if (pointeeTy.isConstQualified() ||
631139f7f9bSDimitry Andric           (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
632139f7f9bSDimitry Andric         typeQuals += typeQuals.empty() ? "const" : " const";
633139f7f9bSDimitry Andric       if (pointeeTy.isVolatileQualified())
634139f7f9bSDimitry Andric         typeQuals += typeQuals.empty() ? "volatile" : " volatile";
635139f7f9bSDimitry Andric     } else {
63659d1ed5bSDimitry Andric       uint32_t AddrSpc = 0;
637444ed5c5SDimitry Andric       bool isPipe = ty->isPipeType();
638444ed5c5SDimitry Andric       if (ty->isImageType() || isPipe)
639f41fbc90SDimitry Andric         AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
64059d1ed5bSDimitry Andric 
64139d628a0SDimitry Andric       addressQuals.push_back(
64239d628a0SDimitry Andric           llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
643139f7f9bSDimitry Andric 
644139f7f9bSDimitry Andric       // Get argument type name.
645444ed5c5SDimitry Andric       std::string typeName;
646444ed5c5SDimitry Andric       if (isPipe)
647e7145dcbSDimitry Andric         typeName = ty.getCanonicalType()->getAs<PipeType>()->getElementType()
648e7145dcbSDimitry Andric                      .getAsString(Policy);
649444ed5c5SDimitry Andric       else
650444ed5c5SDimitry Andric         typeName = ty.getUnqualifiedType().getAsString(Policy);
651139f7f9bSDimitry Andric 
652139f7f9bSDimitry Andric       // Turn "unsigned type" to "utype"
653139f7f9bSDimitry Andric       std::string::size_type pos = typeName.find("unsigned");
65439d628a0SDimitry Andric       if (ty.isCanonical() && pos != std::string::npos)
655139f7f9bSDimitry Andric         typeName.erase(pos+1, 8);
656139f7f9bSDimitry Andric 
657444ed5c5SDimitry Andric       std::string baseTypeName;
658444ed5c5SDimitry Andric       if (isPipe)
659e7145dcbSDimitry Andric         baseTypeName = ty.getCanonicalType()->getAs<PipeType>()
660e7145dcbSDimitry Andric                           ->getElementType().getCanonicalType()
661e7145dcbSDimitry Andric                           .getAsString(Policy);
662444ed5c5SDimitry Andric       else
663444ed5c5SDimitry Andric         baseTypeName =
66439d628a0SDimitry Andric           ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
66539d628a0SDimitry Andric 
66644290647SDimitry Andric       // Remove access qualifiers on images
66744290647SDimitry Andric       // (as they are inseparable from type in clang implementation,
66844290647SDimitry Andric       // but OpenCL spec provides a special query to get access qualifier
66944290647SDimitry Andric       // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
67044290647SDimitry Andric       if (ty->isImageType()) {
67144290647SDimitry Andric         removeImageAccessQualifier(typeName);
67244290647SDimitry Andric         removeImageAccessQualifier(baseTypeName);
67344290647SDimitry Andric       }
67444290647SDimitry Andric 
67544290647SDimitry Andric       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
67644290647SDimitry Andric 
67739d628a0SDimitry Andric       // Turn "unsigned type" to "utype"
67839d628a0SDimitry Andric       pos = baseTypeName.find("unsigned");
67939d628a0SDimitry Andric       if (pos != std::string::npos)
68039d628a0SDimitry Andric         baseTypeName.erase(pos+1, 8);
68139d628a0SDimitry Andric 
68239d628a0SDimitry Andric       argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
68339d628a0SDimitry Andric 
684444ed5c5SDimitry Andric       if (isPipe)
685444ed5c5SDimitry Andric         typeQuals = "pipe";
686139f7f9bSDimitry Andric     }
687139f7f9bSDimitry Andric 
688139f7f9bSDimitry Andric     argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
689139f7f9bSDimitry Andric 
690444ed5c5SDimitry Andric     // Get image and pipe access qualifier:
691444ed5c5SDimitry Andric     if (ty->isImageType()|| ty->isPipeType()) {
6929a199699SDimitry Andric       const Decl *PDecl = parm;
6939a199699SDimitry Andric       if (auto *TD = dyn_cast<TypedefType>(ty))
6949a199699SDimitry Andric         PDecl = TD->getDecl();
6959a199699SDimitry Andric       const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
69659d1ed5bSDimitry Andric       if (A && A->isWriteOnly())
697139f7f9bSDimitry Andric         accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
698e7145dcbSDimitry Andric       else if (A && A->isReadWrite())
699e7145dcbSDimitry Andric         accessQuals.push_back(llvm::MDString::get(Context, "read_write"));
700139f7f9bSDimitry Andric       else
701139f7f9bSDimitry Andric         accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
702139f7f9bSDimitry Andric     } else
703139f7f9bSDimitry Andric       accessQuals.push_back(llvm::MDString::get(Context, "none"));
7047ae0e2c9SDimitry Andric 
7057ae0e2c9SDimitry Andric     // Get argument name.
7067ae0e2c9SDimitry Andric     argNames.push_back(llvm::MDString::get(Context, parm->getName()));
7077ae0e2c9SDimitry Andric   }
708139f7f9bSDimitry Andric 
709e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_addr_space",
710e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, addressQuals));
711e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_access_qual",
712e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, accessQuals));
713e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_type",
714e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, argTypeNames));
715e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_base_type",
716e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, argBaseTypeNames));
717e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_type_qual",
718e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, argTypeQuals));
71939d628a0SDimitry Andric   if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
720e7145dcbSDimitry Andric     Fn->setMetadata("kernel_arg_name",
721e7145dcbSDimitry Andric                     llvm::MDNode::get(Context, argNames));
7227ae0e2c9SDimitry Andric }
7237ae0e2c9SDimitry Andric 
EmitOpenCLKernelMetadata(const FunctionDecl * FD,llvm::Function * Fn)7247ae0e2c9SDimitry Andric void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
7257ae0e2c9SDimitry Andric                                                llvm::Function *Fn)
7267ae0e2c9SDimitry Andric {
7277ae0e2c9SDimitry Andric   if (!FD->hasAttr<OpenCLKernelAttr>())
7287ae0e2c9SDimitry Andric     return;
7297ae0e2c9SDimitry Andric 
7307ae0e2c9SDimitry Andric   llvm::LLVMContext &Context = getLLVMContext();
7317ae0e2c9SDimitry Andric 
732e7145dcbSDimitry Andric   GenOpenCLArgMetadata(FD, Fn, CGM, Context, Builder, getContext());
733139f7f9bSDimitry Andric 
73459d1ed5bSDimitry Andric   if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
7350f5676f4SDimitry Andric     QualType HintQTy = A->getTypeHint();
7360f5676f4SDimitry Andric     const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
7370f5676f4SDimitry Andric     bool IsSignedInteger =
7380f5676f4SDimitry Andric         HintQTy->isSignedIntegerType() ||
7390f5676f4SDimitry Andric         (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType());
7400f5676f4SDimitry Andric     llvm::Metadata *AttrMDArgs[] = {
74139d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
74239d628a0SDimitry Andric             CGM.getTypes().ConvertType(A->getTypeHint()))),
74339d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
744139f7f9bSDimitry Andric             llvm::IntegerType::get(Context, 32),
7450f5676f4SDimitry Andric             llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
7460f5676f4SDimitry Andric     Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
747139f7f9bSDimitry Andric   }
7487ae0e2c9SDimitry Andric 
74959d1ed5bSDimitry Andric   if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
7500f5676f4SDimitry Andric     llvm::Metadata *AttrMDArgs[] = {
75139d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
75239d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
75339d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
7540f5676f4SDimitry Andric     Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
7557ae0e2c9SDimitry Andric   }
7567ae0e2c9SDimitry Andric 
75759d1ed5bSDimitry Andric   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
7580f5676f4SDimitry Andric     llvm::Metadata *AttrMDArgs[] = {
75939d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
76039d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
76139d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
7620f5676f4SDimitry Andric     Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
7630f5676f4SDimitry Andric   }
7640f5676f4SDimitry Andric 
7650f5676f4SDimitry Andric   if (const OpenCLIntelReqdSubGroupSizeAttr *A =
7660f5676f4SDimitry Andric           FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
7670f5676f4SDimitry Andric     llvm::Metadata *AttrMDArgs[] = {
7680f5676f4SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
7690f5676f4SDimitry Andric     Fn->setMetadata("intel_reqd_sub_group_size",
7700f5676f4SDimitry Andric                     llvm::MDNode::get(Context, AttrMDArgs));
7717ae0e2c9SDimitry Andric   }
7727ae0e2c9SDimitry Andric }
7737ae0e2c9SDimitry Andric 
77459d1ed5bSDimitry Andric /// Determine whether the function F ends with a return stmt.
endsWithReturn(const Decl * F)77559d1ed5bSDimitry Andric static bool endsWithReturn(const Decl* F) {
77659d1ed5bSDimitry Andric   const Stmt *Body = nullptr;
77759d1ed5bSDimitry Andric   if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
77859d1ed5bSDimitry Andric     Body = FD->getBody();
77959d1ed5bSDimitry Andric   else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
78059d1ed5bSDimitry Andric     Body = OMD->getBody();
78159d1ed5bSDimitry Andric 
78259d1ed5bSDimitry Andric   if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
78359d1ed5bSDimitry Andric     auto LastStmt = CS->body_rbegin();
78459d1ed5bSDimitry Andric     if (LastStmt != CS->body_rend())
78559d1ed5bSDimitry Andric       return isa<ReturnStmt>(*LastStmt);
78659d1ed5bSDimitry Andric   }
78759d1ed5bSDimitry Andric   return false;
78859d1ed5bSDimitry Andric }
78959d1ed5bSDimitry Andric 
markAsIgnoreThreadCheckingAtRuntime(llvm::Function * Fn)790*b5893f02SDimitry Andric void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
791*b5893f02SDimitry Andric   if (SanOpts.has(SanitizerKind::Thread)) {
79220e90f04SDimitry Andric     Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
79320e90f04SDimitry Andric     Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
79420e90f04SDimitry Andric   }
795*b5893f02SDimitry Andric }
79620e90f04SDimitry Andric 
matchesStlAllocatorFn(const Decl * D,const ASTContext & Ctx)7979a199699SDimitry Andric static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
7989a199699SDimitry Andric   auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
7999a199699SDimitry Andric   if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
8009a199699SDimitry Andric       !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") ||
8019a199699SDimitry Andric       (MD->getNumParams() != 1 && MD->getNumParams() != 2))
8029a199699SDimitry Andric     return false;
8039a199699SDimitry Andric 
8049a199699SDimitry Andric   if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
8059a199699SDimitry Andric     return false;
8069a199699SDimitry Andric 
8079a199699SDimitry Andric   if (MD->getNumParams() == 2) {
8089a199699SDimitry Andric     auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
8099a199699SDimitry Andric     if (!PT || !PT->isVoidPointerType() ||
8109a199699SDimitry Andric         !PT->getPointeeType().isConstQualified())
8119a199699SDimitry Andric       return false;
8129a199699SDimitry Andric   }
8139a199699SDimitry Andric 
8149a199699SDimitry Andric   return true;
8159a199699SDimitry Andric }
8169a199699SDimitry Andric 
8179a199699SDimitry Andric /// Return the UBSan prologue signature for \p FD if one is available.
getPrologueSignature(CodeGenModule & CGM,const FunctionDecl * FD)8189a199699SDimitry Andric static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
8199a199699SDimitry Andric                                             const FunctionDecl *FD) {
8209a199699SDimitry Andric   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8219a199699SDimitry Andric     if (!MD->isStatic())
8229a199699SDimitry Andric       return nullptr;
8239a199699SDimitry Andric   return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
8249a199699SDimitry Andric }
8259a199699SDimitry Andric 
StartFunction(GlobalDecl GD,QualType RetTy,llvm::Function * Fn,const CGFunctionInfo & FnInfo,const FunctionArgList & Args,SourceLocation Loc,SourceLocation StartLoc)826284c1978SDimitry Andric void CodeGenFunction::StartFunction(GlobalDecl GD,
827284c1978SDimitry Andric                                     QualType RetTy,
828f22ef01cSRoman Divacky                                     llvm::Function *Fn,
8293b0f4066SDimitry Andric                                     const CGFunctionInfo &FnInfo,
830f22ef01cSRoman Divacky                                     const FunctionArgList &Args,
83159d1ed5bSDimitry Andric                                     SourceLocation Loc,
832f22ef01cSRoman Divacky                                     SourceLocation StartLoc) {
83339d628a0SDimitry Andric   assert(!CurFn &&
83439d628a0SDimitry Andric          "Do not use a CodeGenFunction object for more than one function");
83539d628a0SDimitry Andric 
836f22ef01cSRoman Divacky   const Decl *D = GD.getDecl();
837f22ef01cSRoman Divacky 
838f22ef01cSRoman Divacky   DidCallStackSave = false;
839284c1978SDimitry Andric   CurCodeDecl = D;
840e7145dcbSDimitry Andric   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
841e7145dcbSDimitry Andric     if (FD->usesSEHTry())
842e7145dcbSDimitry Andric       CurSEHParent = FD;
84359d1ed5bSDimitry Andric   CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
844f22ef01cSRoman Divacky   FnRetTy = RetTy;
845f22ef01cSRoman Divacky   CurFn = Fn;
8463b0f4066SDimitry Andric   CurFnInfo = &FnInfo;
847f22ef01cSRoman Divacky   assert(CurFn->isDeclaration() && "Function already has body?");
848f22ef01cSRoman Divacky 
8499a199699SDimitry Andric   // If this function has been blacklisted for any of the enabled sanitizers,
8509a199699SDimitry Andric   // disable the sanitizer for the function.
8519a199699SDimitry Andric   do {
8529a199699SDimitry Andric #define SANITIZER(NAME, ID)                                                    \
8539a199699SDimitry Andric   if (SanOpts.empty())                                                         \
8549a199699SDimitry Andric     break;                                                                     \
8559a199699SDimitry Andric   if (SanOpts.has(SanitizerKind::ID))                                          \
8569a199699SDimitry Andric     if (CGM.isInSanitizerBlacklist(SanitizerKind::ID, Fn, Loc))                \
8579a199699SDimitry Andric       SanOpts.set(SanitizerKind::ID, false);
8589a199699SDimitry Andric 
8599a199699SDimitry Andric #include "clang/Basic/Sanitizers.def"
8609a199699SDimitry Andric #undef SANITIZER
8619a199699SDimitry Andric   } while (0);
862139f7f9bSDimitry Andric 
86333956c43SDimitry Andric   if (D) {
86433956c43SDimitry Andric     // Apply the no_sanitize* attributes to SanOpts.
8654ba319b5SDimitry Andric     for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) {
8664ba319b5SDimitry Andric       SanitizerMask mask = Attr->getMask();
8674ba319b5SDimitry Andric       SanOpts.Mask &= ~mask;
8684ba319b5SDimitry Andric       if (mask & SanitizerKind::Address)
8694ba319b5SDimitry Andric         SanOpts.set(SanitizerKind::KernelAddress, false);
8704ba319b5SDimitry Andric       if (mask & SanitizerKind::KernelAddress)
8714ba319b5SDimitry Andric         SanOpts.set(SanitizerKind::Address, false);
8724ba319b5SDimitry Andric       if (mask & SanitizerKind::HWAddress)
8734ba319b5SDimitry Andric         SanOpts.set(SanitizerKind::KernelHWAddress, false);
8744ba319b5SDimitry Andric       if (mask & SanitizerKind::KernelHWAddress)
8754ba319b5SDimitry Andric         SanOpts.set(SanitizerKind::HWAddress, false);
8764ba319b5SDimitry Andric     }
87733956c43SDimitry Andric   }
87833956c43SDimitry Andric 
87933956c43SDimitry Andric   // Apply sanitizer attributes to the function.
8808f0fd8f6SDimitry Andric   if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
88133956c43SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
8824ba319b5SDimitry Andric   if (SanOpts.hasOneOf(SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress))
8839a199699SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
88433956c43SDimitry Andric   if (SanOpts.has(SanitizerKind::Thread))
88533956c43SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeThread);
886*b5893f02SDimitry Andric   if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
88733956c43SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
8888f0fd8f6SDimitry Andric   if (SanOpts.has(SanitizerKind::SafeStack))
8898f0fd8f6SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SafeStack);
8904ba319b5SDimitry Andric   if (SanOpts.has(SanitizerKind::ShadowCallStack))
8914ba319b5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
8924ba319b5SDimitry Andric 
8934ba319b5SDimitry Andric   // Apply fuzzing attribute to the function.
8944ba319b5SDimitry Andric   if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
8954ba319b5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
89633956c43SDimitry Andric 
89744290647SDimitry Andric   // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
89820e90f04SDimitry Andric   // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
89944290647SDimitry Andric   if (SanOpts.has(SanitizerKind::Thread)) {
90044290647SDimitry Andric     if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
90144290647SDimitry Andric       IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
90244290647SDimitry Andric       if (OMD->getMethodFamily() == OMF_dealloc ||
90344290647SDimitry Andric           OMD->getMethodFamily() == OMF_initialize ||
90444290647SDimitry Andric           (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
90520e90f04SDimitry Andric         markAsIgnoreThreadCheckingAtRuntime(Fn);
90644290647SDimitry Andric       }
90744290647SDimitry Andric     }
90844290647SDimitry Andric   }
90944290647SDimitry Andric 
9109a199699SDimitry Andric   // Ignore unrelated casts in STL allocate() since the allocator must cast
9119a199699SDimitry Andric   // from void* to T* before object initialization completes. Don't match on the
9129a199699SDimitry Andric   // namespace because not all allocators are in std::
9139a199699SDimitry Andric   if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
9149a199699SDimitry Andric     if (matchesStlAllocatorFn(D, getContext()))
9159a199699SDimitry Andric       SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
9169a199699SDimitry Andric   }
9179a199699SDimitry Andric 
918e7145dcbSDimitry Andric   // Apply xray attributes to the function (as a string, for now)
919*b5893f02SDimitry Andric   if (D) {
920e7145dcbSDimitry Andric     if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) {
921*b5893f02SDimitry Andric       if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
922*b5893f02SDimitry Andric               XRayInstrKind::Function)) {
923*b5893f02SDimitry Andric         if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction())
924e7145dcbSDimitry Andric           Fn->addFnAttr("function-instrument", "xray-always");
925e7145dcbSDimitry Andric         if (XRayAttr->neverXRayInstrument())
926e7145dcbSDimitry Andric           Fn->addFnAttr("function-instrument", "xray-never");
927*b5893f02SDimitry Andric         if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
928*b5893f02SDimitry Andric           if (ShouldXRayInstrumentFunction())
92920e90f04SDimitry Andric             Fn->addFnAttr("xray-log-args",
93020e90f04SDimitry Andric                           llvm::utostr(LogArgs->getArgumentCount()));
93120e90f04SDimitry Andric       }
932e7145dcbSDimitry Andric     } else {
933*b5893f02SDimitry Andric       if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc))
934e7145dcbSDimitry Andric         Fn->addFnAttr(
935e7145dcbSDimitry Andric             "xray-instruction-threshold",
936e7145dcbSDimitry Andric             llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
937e7145dcbSDimitry Andric     }
938e7145dcbSDimitry Andric   }
939e7145dcbSDimitry Andric 
940e7145dcbSDimitry Andric   // Add no-jump-tables value.
941e7145dcbSDimitry Andric   Fn->addFnAttr("no-jump-tables",
942e7145dcbSDimitry Andric                 llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
943e7145dcbSDimitry Andric 
9449a199699SDimitry Andric   // Add profile-sample-accurate value.
9459a199699SDimitry Andric   if (CGM.getCodeGenOpts().ProfileSampleAccurate)
9469a199699SDimitry Andric     Fn->addFnAttr("profile-sample-accurate");
9479a199699SDimitry Andric 
9483861d79fSDimitry Andric   if (getLangOpts().OpenCL) {
9492754fe60SDimitry Andric     // Add metadata for a kernel function.
9502754fe60SDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
9517ae0e2c9SDimitry Andric       EmitOpenCLKernelMetadata(FD, Fn);
9522754fe60SDimitry Andric   }
9532754fe60SDimitry Andric 
954f785676fSDimitry Andric   // If we are checking function types, emit a function type signature as
95539d628a0SDimitry Andric   // prologue data.
95639d628a0SDimitry Andric   if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
957f785676fSDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
9589a199699SDimitry Andric       if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
9594ba319b5SDimitry Andric         // Remove any (C++17) exception specifications, to allow calling e.g. a
9604ba319b5SDimitry Andric         // noexcept function through a non-noexcept pointer.
9614ba319b5SDimitry Andric         auto ProtoTy =
9624ba319b5SDimitry Andric           getContext().getFunctionTypeWithExceptionSpec(FD->getType(),
9634ba319b5SDimitry Andric                                                         EST_None);
964f785676fSDimitry Andric         llvm::Constant *FTRTTIConst =
9654ba319b5SDimitry Andric             CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
9669a199699SDimitry Andric         llvm::Constant *FTRTTIConstEncoded =
9679a199699SDimitry Andric             EncodeAddrForUseInPrologue(Fn, FTRTTIConst);
9689a199699SDimitry Andric         llvm::Constant *PrologueStructElems[] = {PrologueSig,
9699a199699SDimitry Andric                                                  FTRTTIConstEncoded};
97039d628a0SDimitry Andric         llvm::Constant *PrologueStructConst =
97139d628a0SDimitry Andric             llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
97239d628a0SDimitry Andric         Fn->setPrologueData(PrologueStructConst);
973f785676fSDimitry Andric       }
974f785676fSDimitry Andric     }
975f785676fSDimitry Andric   }
976f785676fSDimitry Andric 
97720e90f04SDimitry Andric   // If we're checking nullability, we need to know whether we can check the
97820e90f04SDimitry Andric   // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
97920e90f04SDimitry Andric   if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
98020e90f04SDimitry Andric     auto Nullability = FnRetTy->getNullability(getContext());
98120e90f04SDimitry Andric     if (Nullability && *Nullability == NullabilityKind::NonNull) {
98220e90f04SDimitry Andric       if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
98320e90f04SDimitry Andric             CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
98420e90f04SDimitry Andric         RetValNullabilityPrecondition =
98520e90f04SDimitry Andric             llvm::ConstantInt::getTrue(getLLVMContext());
98620e90f04SDimitry Andric     }
98720e90f04SDimitry Andric   }
98820e90f04SDimitry Andric 
9890623d748SDimitry Andric   // If we're in C++ mode and the function name is "main", it is guaranteed
9900623d748SDimitry Andric   // to be norecurse by the standard (3.6.1.3 "The function main shall not be
9910623d748SDimitry Andric   // used within a program").
9920623d748SDimitry Andric   if (getLangOpts().CPlusPlus)
9930623d748SDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
9940623d748SDimitry Andric       if (FD->isMain())
9950623d748SDimitry Andric         Fn->addFnAttr(llvm::Attribute::NoRecurse);
9960623d748SDimitry Andric 
997*b5893f02SDimitry Andric   // If a custom alignment is used, force realigning to this alignment on
998*b5893f02SDimitry Andric   // any main function which certainly will need it.
999*b5893f02SDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
1000*b5893f02SDimitry Andric     if ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
1001*b5893f02SDimitry Andric         CGM.getCodeGenOpts().StackAlignment)
1002*b5893f02SDimitry Andric       Fn->addFnAttr("stackrealign");
1003*b5893f02SDimitry Andric 
1004f22ef01cSRoman Divacky   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
1005f22ef01cSRoman Divacky 
1006f22ef01cSRoman Divacky   // Create a marker to make it easy to insert allocas into the entryblock
1007f22ef01cSRoman Divacky   // later.  Don't create this with the builder, because we don't want it
1008f22ef01cSRoman Divacky   // folded.
1009ffd1746dSEd Schouten   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
1010e7145dcbSDimitry Andric   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
1011f22ef01cSRoman Divacky 
1012ffd1746dSEd Schouten   ReturnBlock = getJumpDestInCurrentScope("return");
1013f22ef01cSRoman Divacky 
1014f22ef01cSRoman Divacky   Builder.SetInsertPoint(EntryBB);
1015f22ef01cSRoman Divacky 
1016edd7eaddSDimitry Andric   // If we're checking the return value, allocate space for a pointer to a
1017edd7eaddSDimitry Andric   // precise source location of the checked return statement.
1018edd7eaddSDimitry Andric   if (requiresReturnValueCheck()) {
1019edd7eaddSDimitry Andric     ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
1020edd7eaddSDimitry Andric     InitTempAlloca(ReturnLocation, llvm::ConstantPointerNull::get(Int8PtrTy));
1021edd7eaddSDimitry Andric   }
1022edd7eaddSDimitry Andric 
1023f22ef01cSRoman Divacky   // Emit subprogram debug descriptor.
1024f22ef01cSRoman Divacky   if (CGDebugInfo *DI = getDebugInfo()) {
1025e7145dcbSDimitry Andric     // Reconstruct the type from the argument list so that implicit parameters,
1026e7145dcbSDimitry Andric     // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
1027e7145dcbSDimitry Andric     // convention.
1028e7145dcbSDimitry Andric     CallingConv CC = CallingConv::CC_C;
1029e7145dcbSDimitry Andric     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D))
1030e7145dcbSDimitry Andric       if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
1031e7145dcbSDimitry Andric         CC = SrcFnTy->getCallConv();
1032139f7f9bSDimitry Andric     SmallVector<QualType, 16> ArgTypes;
1033e7145dcbSDimitry Andric     for (const VarDecl *VD : Args)
1034e7145dcbSDimitry Andric       ArgTypes.push_back(VD->getType());
1035e7145dcbSDimitry Andric     QualType FnType = getContext().getFunctionType(
1036e7145dcbSDimitry Andric         RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
10374ba319b5SDimitry Andric     DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, CurFuncIsThunk,
10384ba319b5SDimitry Andric                           Builder);
1039f22ef01cSRoman Divacky   }
1040f22ef01cSRoman Divacky 
10419a199699SDimitry Andric   if (ShouldInstrumentFunction()) {
10429a199699SDimitry Andric     if (CGM.getCodeGenOpts().InstrumentFunctions)
10439a199699SDimitry Andric       CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
10449a199699SDimitry Andric     if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
10459a199699SDimitry Andric       CurFn->addFnAttr("instrument-function-entry-inlined",
10469a199699SDimitry Andric                        "__cyg_profile_func_enter");
10479a199699SDimitry Andric     if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
10489a199699SDimitry Andric       CurFn->addFnAttr("instrument-function-entry-inlined",
10499a199699SDimitry Andric                        "__cyg_profile_func_enter_bare");
10509a199699SDimitry Andric   }
1051ffd1746dSEd Schouten 
105244290647SDimitry Andric   // Since emitting the mcount call here impacts optimizations such as function
105344290647SDimitry Andric   // inlining, we just add an attribute to insert a mcount call in backend.
105444290647SDimitry Andric   // The attribute "counting-function" is set to mcount function name which is
105544290647SDimitry Andric   // architecture dependent.
105620e90f04SDimitry Andric   if (CGM.getCodeGenOpts().InstrumentForProfiling) {
10574ba319b5SDimitry Andric     // Calls to fentry/mcount should not be generated if function has
10584ba319b5SDimitry Andric     // the no_instrument_function attribute.
10594ba319b5SDimitry Andric     if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
106020e90f04SDimitry Andric       if (CGM.getCodeGenOpts().CallFEntry)
106120e90f04SDimitry Andric         Fn->addFnAttr("fentry-call", "true");
1062edd7eaddSDimitry Andric       else {
10639a199699SDimitry Andric         Fn->addFnAttr("instrument-function-entry-inlined",
10649a199699SDimitry Andric                       getTarget().getMCountName());
10659a199699SDimitry Andric       }
106620e90f04SDimitry Andric     }
1067edd7eaddSDimitry Andric   }
10682754fe60SDimitry Andric 
1069f22ef01cSRoman Divacky   if (RetTy->isVoidType()) {
1070f22ef01cSRoman Divacky     // Void type; nothing to return.
10710623d748SDimitry Andric     ReturnValue = Address::invalid();
107259d1ed5bSDimitry Andric 
107359d1ed5bSDimitry Andric     // Count the implicit return.
107459d1ed5bSDimitry Andric     if (!endsWithReturn(D))
107559d1ed5bSDimitry Andric       ++NumReturnExprs;
1076*b5893f02SDimitry Andric   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
1077*b5893f02SDimitry Andric     // Indirect return; emit returned value directly into sret slot.
1078f22ef01cSRoman Divacky     // This reduces code size, and affects correctness in C++.
107959d1ed5bSDimitry Andric     auto AI = CurFn->arg_begin();
108059d1ed5bSDimitry Andric     if (CurFnInfo->getReturnInfo().isSRetAfterThis())
108159d1ed5bSDimitry Andric       ++AI;
10820623d748SDimitry Andric     ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
108359d1ed5bSDimitry Andric   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
108459d1ed5bSDimitry Andric              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
108559d1ed5bSDimitry Andric     // Load the sret pointer from the argument struct and return into that.
108659d1ed5bSDimitry Andric     unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
108759d1ed5bSDimitry Andric     llvm::Function::arg_iterator EI = CurFn->arg_end();
108859d1ed5bSDimitry Andric     --EI;
10890623d748SDimitry Andric     llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
10900623d748SDimitry Andric     Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
10910623d748SDimitry Andric     ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
1092f22ef01cSRoman Divacky   } else {
1093f22ef01cSRoman Divacky     ReturnValue = CreateIRTemp(RetTy, "retval");
109417a519f9SDimitry Andric 
109517a519f9SDimitry Andric     // Tell the epilog emitter to autorelease the result.  We do this
109617a519f9SDimitry Andric     // now so that various specialized functions can suppress it
109717a519f9SDimitry Andric     // during their IR-generation.
1098dff0c46cSDimitry Andric     if (getLangOpts().ObjCAutoRefCount &&
109917a519f9SDimitry Andric         !CurFnInfo->isReturnsRetained() &&
110017a519f9SDimitry Andric         RetTy->isObjCRetainableType())
110117a519f9SDimitry Andric       AutoreleaseResult = true;
1102f22ef01cSRoman Divacky   }
1103f22ef01cSRoman Divacky 
1104f22ef01cSRoman Divacky   EmitStartEHSpec(CurCodeDecl);
110517a519f9SDimitry Andric 
110617a519f9SDimitry Andric   PrologueCleanupDepth = EHStack.stable_begin();
11074ba319b5SDimitry Andric 
11084ba319b5SDimitry Andric   // Emit OpenMP specific initialization of the device functions.
11094ba319b5SDimitry Andric   if (getLangOpts().OpenMP && CurCodeDecl)
11104ba319b5SDimitry Andric     CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
11114ba319b5SDimitry Andric 
1112f22ef01cSRoman Divacky   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
1113f22ef01cSRoman Divacky 
1114dff0c46cSDimitry Andric   if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
1115e580952dSDimitry Andric     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
1116dff0c46cSDimitry Andric     const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
1117dff0c46cSDimitry Andric     if (MD->getParent()->isLambda() &&
1118dff0c46cSDimitry Andric         MD->getOverloadedOperator() == OO_Call) {
1119dff0c46cSDimitry Andric       // We're in a lambda; figure out the captures.
1120dff0c46cSDimitry Andric       MD->getParent()->getCaptureFields(LambdaCaptureFields,
1121dff0c46cSDimitry Andric                                         LambdaThisCaptureField);
1122dff0c46cSDimitry Andric       if (LambdaThisCaptureField) {
1123e7145dcbSDimitry Andric         // If the lambda captures the object referred to by '*this' - either by
1124e7145dcbSDimitry Andric         // value or by reference, make sure CXXThisValue points to the correct
1125e7145dcbSDimitry Andric         // object.
1126e7145dcbSDimitry Andric 
1127e7145dcbSDimitry Andric         // Get the lvalue for the field (which is a copy of the enclosing object
1128e7145dcbSDimitry Andric         // or contains the address of the enclosing object).
1129e7145dcbSDimitry Andric         LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
1130e7145dcbSDimitry Andric         if (!LambdaThisCaptureField->getType()->isPointerType()) {
1131e7145dcbSDimitry Andric           // If the enclosing object was captured by value, just use its address.
1132e7145dcbSDimitry Andric           CXXThisValue = ThisFieldLValue.getAddress().getPointer();
1133e7145dcbSDimitry Andric         } else {
1134e7145dcbSDimitry Andric           // Load the lvalue pointed to by the field, since '*this' was captured
1135e7145dcbSDimitry Andric           // by reference.
1136e7145dcbSDimitry Andric           CXXThisValue =
1137e7145dcbSDimitry Andric               EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
1138e7145dcbSDimitry Andric         }
1139dff0c46cSDimitry Andric       }
114039d628a0SDimitry Andric       for (auto *FD : MD->getParent()->fields()) {
114139d628a0SDimitry Andric         if (FD->hasCapturedVLAType()) {
114239d628a0SDimitry Andric           auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
114339d628a0SDimitry Andric                                            SourceLocation()).getScalarVal();
114439d628a0SDimitry Andric           auto VAT = FD->getCapturedVLAType();
114539d628a0SDimitry Andric           VLASizeMap[VAT->getSizeExpr()] = ExprArg;
114639d628a0SDimitry Andric         }
114739d628a0SDimitry Andric       }
1148dff0c46cSDimitry Andric     } else {
1149dff0c46cSDimitry Andric       // Not in a lambda; just use 'this' from the method.
1150dff0c46cSDimitry Andric       // FIXME: Should we generate a new load for each use of 'this'?  The
1151dff0c46cSDimitry Andric       // fast register allocator would be happier...
1152dff0c46cSDimitry Andric       CXXThisValue = CXXABIThisValue;
1153dff0c46cSDimitry Andric     }
115420e90f04SDimitry Andric 
115520e90f04SDimitry Andric     // Check the 'this' pointer once per function, if it's available.
11563ea909ccSDimitry Andric     if (CXXABIThisValue) {
115720e90f04SDimitry Andric       SanitizerSet SkippedChecks;
115820e90f04SDimitry Andric       SkippedChecks.set(SanitizerKind::ObjectSize, true);
1159*b5893f02SDimitry Andric       QualType ThisTy = MD->getThisType();
11603ea909ccSDimitry Andric 
11613ea909ccSDimitry Andric       // If this is the call operator of a lambda with no capture-default, it
11623ea909ccSDimitry Andric       // may have a static invoker function, which may call this operator with
11633ea909ccSDimitry Andric       // a null 'this' pointer.
11643ea909ccSDimitry Andric       if (isLambdaCallOperator(MD) &&
11654ba319b5SDimitry Andric           MD->getParent()->getLambdaCaptureDefault() == LCD_None)
11663ea909ccSDimitry Andric         SkippedChecks.set(SanitizerKind::Null, true);
11673ea909ccSDimitry Andric 
11683ea909ccSDimitry Andric       EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall
11693ea909ccSDimitry Andric                                                 : TCK_MemberCall,
11703ea909ccSDimitry Andric                     Loc, CXXABIThisValue, ThisTy,
117120e90f04SDimitry Andric                     getContext().getTypeAlignInChars(ThisTy->getPointeeType()),
117220e90f04SDimitry Andric                     SkippedChecks);
117320e90f04SDimitry Andric     }
1174dff0c46cSDimitry Andric   }
1175f22ef01cSRoman Divacky 
1176f22ef01cSRoman Divacky   // If any of the arguments have a variably modified type, make sure to
1177f22ef01cSRoman Divacky   // emit the type size.
1178f22ef01cSRoman Divacky   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1179f22ef01cSRoman Divacky        i != e; ++i) {
1180139f7f9bSDimitry Andric     const VarDecl *VD = *i;
1181139f7f9bSDimitry Andric 
1182139f7f9bSDimitry Andric     // Dig out the type as written from ParmVarDecls; it's unclear whether
1183139f7f9bSDimitry Andric     // the standard (C99 6.9.1p10) requires this, but we're following the
1184139f7f9bSDimitry Andric     // precedent set by gcc.
1185139f7f9bSDimitry Andric     QualType Ty;
1186139f7f9bSDimitry Andric     if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1187139f7f9bSDimitry Andric       Ty = PVD->getOriginalType();
1188139f7f9bSDimitry Andric     else
1189139f7f9bSDimitry Andric       Ty = VD->getType();
1190f22ef01cSRoman Divacky 
1191f22ef01cSRoman Divacky     if (Ty->isVariablyModifiedType())
119217a519f9SDimitry Andric       EmitVariablyModifiedType(Ty);
1193f22ef01cSRoman Divacky   }
11946122f3e6SDimitry Andric   // Emit a location at the end of the prologue.
11956122f3e6SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
11966122f3e6SDimitry Andric     DI->EmitLocation(Builder, StartLoc);
11974ba319b5SDimitry Andric 
11984ba319b5SDimitry Andric   // TODO: Do we need to handle this in two places like we do with
11994ba319b5SDimitry Andric   // target-features/target-cpu?
12004ba319b5SDimitry Andric   if (CurFuncDecl)
12014ba319b5SDimitry Andric     if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
12024ba319b5SDimitry Andric       LargestVectorWidth = VecWidth->getVectorWidth();
1203f22ef01cSRoman Divacky }
1204f22ef01cSRoman Divacky 
EmitFunctionBody(const Stmt * Body)1205*b5893f02SDimitry Andric void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
120633956c43SDimitry Andric   incrementProfileCounter(Body);
1207f785676fSDimitry Andric   if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1208139f7f9bSDimitry Andric     EmitCompoundStmtWithoutScope(*S);
1209139f7f9bSDimitry Andric   else
1210f785676fSDimitry Andric     EmitStmt(Body);
1211f22ef01cSRoman Divacky }
1212f22ef01cSRoman Divacky 
121359d1ed5bSDimitry Andric /// When instrumenting to collect profile data, the counts for some blocks
121459d1ed5bSDimitry Andric /// such as switch cases need to not include the fall-through counts, so
121559d1ed5bSDimitry Andric /// emit a branch around the instrumentation code. When not instrumenting,
121659d1ed5bSDimitry Andric /// this just calls EmitBlock().
EmitBlockWithFallThrough(llvm::BasicBlock * BB,const Stmt * S)121759d1ed5bSDimitry Andric void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
121833956c43SDimitry Andric                                                const Stmt *S) {
121959d1ed5bSDimitry Andric   llvm::BasicBlock *SkipCountBB = nullptr;
1220e7145dcbSDimitry Andric   if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
122159d1ed5bSDimitry Andric     // When instrumenting for profiling, the fallthrough to certain
122259d1ed5bSDimitry Andric     // statements needs to skip over the instrumentation code so that we
122359d1ed5bSDimitry Andric     // get an accurate count.
122459d1ed5bSDimitry Andric     SkipCountBB = createBasicBlock("skipcount");
122559d1ed5bSDimitry Andric     EmitBranch(SkipCountBB);
122659d1ed5bSDimitry Andric   }
122759d1ed5bSDimitry Andric   EmitBlock(BB);
122833956c43SDimitry Andric   uint64_t CurrentCount = getCurrentProfileCount();
122933956c43SDimitry Andric   incrementProfileCounter(S);
123033956c43SDimitry Andric   setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
123159d1ed5bSDimitry Andric   if (SkipCountBB)
123259d1ed5bSDimitry Andric     EmitBlock(SkipCountBB);
123359d1ed5bSDimitry Andric }
123459d1ed5bSDimitry Andric 
1235e580952dSDimitry Andric /// Tries to mark the given function nounwind based on the
1236e580952dSDimitry Andric /// non-existence of any throwing calls within it.  We believe this is
1237e580952dSDimitry Andric /// lightweight enough to do at -O0.
TryMarkNoThrow(llvm::Function * F)1238e580952dSDimitry Andric static void TryMarkNoThrow(llvm::Function *F) {
1239e580952dSDimitry Andric   // LLVM treats 'nounwind' on a function as part of the type, so we
1240e580952dSDimitry Andric   // can't do this on functions that can be overwritten.
1241e7145dcbSDimitry Andric   if (F->isInterposable()) return;
1242e580952dSDimitry Andric 
12430623d748SDimitry Andric   for (llvm::BasicBlock &BB : *F)
12440623d748SDimitry Andric     for (llvm::Instruction &I : BB)
12450623d748SDimitry Andric       if (I.mayThrow())
1246e580952dSDimitry Andric         return;
12470623d748SDimitry Andric 
12483861d79fSDimitry Andric   F->setDoesNotThrow();
1249e580952dSDimitry Andric }
1250e580952dSDimitry Andric 
BuildFunctionArgList(GlobalDecl GD,FunctionArgList & Args)1251e7145dcbSDimitry Andric QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
1252e7145dcbSDimitry Andric                                                FunctionArgList &Args) {
1253f22ef01cSRoman Divacky   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
125459d1ed5bSDimitry Andric   QualType ResTy = FD->getReturnType();
1255f22ef01cSRoman Divacky 
125659d1ed5bSDimitry Andric   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
125759d1ed5bSDimitry Andric   if (MD && MD->isInstance()) {
1258f785676fSDimitry Andric     if (CGM.getCXXABI().HasThisReturn(GD))
1259*b5893f02SDimitry Andric       ResTy = MD->getThisType();
126039d628a0SDimitry Andric     else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
126139d628a0SDimitry Andric       ResTy = CGM.getContext().VoidPtrTy;
126259d1ed5bSDimitry Andric     CGM.getCXXABI().buildThisParam(*this, Args);
1263f785676fSDimitry Andric   }
1264f22ef01cSRoman Divacky 
1265e7145dcbSDimitry Andric   // The base version of an inheriting constructor whose constructed base is a
1266e7145dcbSDimitry Andric   // virtual base is not passed any arguments (because it doesn't actually call
1267e7145dcbSDimitry Andric   // the inherited constructor).
1268e7145dcbSDimitry Andric   bool PassedParams = true;
1269e7145dcbSDimitry Andric   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
1270e7145dcbSDimitry Andric     if (auto Inherited = CD->getInheritedConstructor())
1271e7145dcbSDimitry Andric       PassedParams =
1272e7145dcbSDimitry Andric           getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
1273e7145dcbSDimitry Andric 
1274e7145dcbSDimitry Andric   if (PassedParams) {
1275e7145dcbSDimitry Andric     for (auto *Param : FD->parameters()) {
12760623d748SDimitry Andric       Args.push_back(Param);
12770623d748SDimitry Andric       if (!Param->hasAttr<PassObjectSizeAttr>())
12780623d748SDimitry Andric         continue;
12790623d748SDimitry Andric 
12800623d748SDimitry Andric       auto *Implicit = ImplicitParamDecl::Create(
1281db17bf38SDimitry Andric           getContext(), Param->getDeclContext(), Param->getLocation(),
1282db17bf38SDimitry Andric           /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other);
12830623d748SDimitry Andric       SizeArguments[Param] = Implicit;
12840623d748SDimitry Andric       Args.push_back(Implicit);
12850623d748SDimitry Andric     }
1286e7145dcbSDimitry Andric   }
1287f22ef01cSRoman Divacky 
128859d1ed5bSDimitry Andric   if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
128959d1ed5bSDimitry Andric     CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
129059d1ed5bSDimitry Andric 
1291e7145dcbSDimitry Andric   return ResTy;
1292e7145dcbSDimitry Andric }
1293e7145dcbSDimitry Andric 
12948e0f8b8cSDimitry Andric static bool
shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl * FD,const ASTContext & Context)12958e0f8b8cSDimitry Andric shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD,
12968e0f8b8cSDimitry Andric                                              const ASTContext &Context) {
12978e0f8b8cSDimitry Andric   QualType T = FD->getReturnType();
12988e0f8b8cSDimitry Andric   // Avoid the optimization for functions that return a record type with a
12998e0f8b8cSDimitry Andric   // trivial destructor or another trivially copyable type.
13008e0f8b8cSDimitry Andric   if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) {
13018e0f8b8cSDimitry Andric     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
13028e0f8b8cSDimitry Andric       return !ClassDecl->hasTrivialDestructor();
13038e0f8b8cSDimitry Andric   }
13048e0f8b8cSDimitry Andric   return !T.isTriviallyCopyableType(Context);
13058e0f8b8cSDimitry Andric }
13068e0f8b8cSDimitry Andric 
GenerateCode(GlobalDecl GD,llvm::Function * Fn,const CGFunctionInfo & FnInfo)1307e7145dcbSDimitry Andric void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1308e7145dcbSDimitry Andric                                    const CGFunctionInfo &FnInfo) {
1309e7145dcbSDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1310e7145dcbSDimitry Andric   CurGD = GD;
1311e7145dcbSDimitry Andric 
1312e7145dcbSDimitry Andric   FunctionArgList Args;
1313e7145dcbSDimitry Andric   QualType ResTy = BuildFunctionArgList(GD, Args);
1314e7145dcbSDimitry Andric 
1315e7145dcbSDimitry Andric   // Check if we should generate debug info for this function.
1316e7145dcbSDimitry Andric   if (FD->hasAttr<NoDebugAttr>())
1317e7145dcbSDimitry Andric     DebugInfo = nullptr; // disable debug info indefinitely for this function
1318e7145dcbSDimitry Andric 
131920e90f04SDimitry Andric   // The function might not have a body if we're generating thunks for a
132020e90f04SDimitry Andric   // function declaration.
1321f22ef01cSRoman Divacky   SourceRange BodyRange;
132220e90f04SDimitry Andric   if (Stmt *Body = FD->getBody())
132320e90f04SDimitry Andric     BodyRange = Body->getSourceRange();
132420e90f04SDimitry Andric   else
132520e90f04SDimitry Andric     BodyRange = FD->getLocation();
1326f785676fSDimitry Andric   CurEHLocation = BodyRange.getEnd();
1327139f7f9bSDimitry Andric 
132859d1ed5bSDimitry Andric   // Use the location of the start of the function to determine where
132959d1ed5bSDimitry Andric   // the function definition is located. By default use the location
133059d1ed5bSDimitry Andric   // of the declaration as the location for the subprogram. A function
133159d1ed5bSDimitry Andric   // may lack a declaration in the source code if it is created by code
133259d1ed5bSDimitry Andric   // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
133359d1ed5bSDimitry Andric   SourceLocation Loc = FD->getLocation();
133459d1ed5bSDimitry Andric 
133559d1ed5bSDimitry Andric   // If this is a function specialization then use the pattern body
133659d1ed5bSDimitry Andric   // as the location for the function.
133759d1ed5bSDimitry Andric   if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
133859d1ed5bSDimitry Andric     if (SpecDecl->hasBody(SpecDecl))
133959d1ed5bSDimitry Andric       Loc = SpecDecl->getLocation();
134059d1ed5bSDimitry Andric 
134144290647SDimitry Andric   Stmt *Body = FD->getBody();
134244290647SDimitry Andric 
134344290647SDimitry Andric   // Initialize helper which will detect jumps which can cause invalid lifetime
134444290647SDimitry Andric   // markers.
134544290647SDimitry Andric   if (Body && ShouldEmitLifetimeMarkers)
134644290647SDimitry Andric     Bypasses.Init(Body);
134744290647SDimitry Andric 
1348f22ef01cSRoman Divacky   // Emit the standard function prologue.
134959d1ed5bSDimitry Andric   StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1350f22ef01cSRoman Divacky 
1351f22ef01cSRoman Divacky   // Generate the body of the function.
13520623d748SDimitry Andric   PGO.assignRegionCounters(GD, CurFn);
1353f22ef01cSRoman Divacky   if (isa<CXXDestructorDecl>(FD))
1354f22ef01cSRoman Divacky     EmitDestructorBody(Args);
1355f22ef01cSRoman Divacky   else if (isa<CXXConstructorDecl>(FD))
1356f22ef01cSRoman Divacky     EmitConstructorBody(Args);
13573861d79fSDimitry Andric   else if (getLangOpts().CUDA &&
135833956c43SDimitry Andric            !getLangOpts().CUDAIsDevice &&
13596122f3e6SDimitry Andric            FD->hasAttr<CUDAGlobalAttr>())
136033956c43SDimitry Andric     CGM.getCUDARuntime().emitDeviceStub(*this, Args);
13619a199699SDimitry Andric   else if (isa<CXXMethodDecl>(FD) &&
1362dff0c46cSDimitry Andric            cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1363f785676fSDimitry Andric     // The lambda static invoker function is special, because it forwards or
1364dff0c46cSDimitry Andric     // clones the body of the function call operator (but is actually static).
13659a199699SDimitry Andric     EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
1366139f7f9bSDimitry Andric   } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
1367f785676fSDimitry Andric              (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1368f785676fSDimitry Andric               cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1369139f7f9bSDimitry Andric     // Implicit copy-assignment gets the same special treatment as implicit
1370139f7f9bSDimitry Andric     // copy-constructors.
1371139f7f9bSDimitry Andric     emitImplicitAssignmentOperatorBody(Args);
137244290647SDimitry Andric   } else if (Body) {
1373*b5893f02SDimitry Andric     EmitFunctionBody(Body);
1374f785676fSDimitry Andric   } else
1375f785676fSDimitry Andric     llvm_unreachable("no definition for emitted function");
1376f22ef01cSRoman Divacky 
13773861d79fSDimitry Andric   // C++11 [stmt.return]p2:
13783861d79fSDimitry Andric   //   Flowing off the end of a function [...] results in undefined behavior in
13793861d79fSDimitry Andric   //   a value-returning function.
13803861d79fSDimitry Andric   // C11 6.9.1p12:
13813861d79fSDimitry Andric   //   If the '}' that terminates a function is reached, and the value of the
13823861d79fSDimitry Andric   //   function call is used by the caller, the behavior is undefined.
138339d628a0SDimitry Andric   if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
138459d1ed5bSDimitry Andric       !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
13858e0f8b8cSDimitry Andric     bool ShouldEmitUnreachable =
13868e0f8b8cSDimitry Andric         CGM.getCodeGenOpts().StrictReturn ||
13878e0f8b8cSDimitry Andric         shouldUseUndefinedBehaviorReturnOptimization(FD, getContext());
138839d628a0SDimitry Andric     if (SanOpts.has(SanitizerKind::Return)) {
138959d1ed5bSDimitry Andric       SanitizerScope SanScope(this);
139039d628a0SDimitry Andric       llvm::Value *IsFalse = Builder.getFalse();
139139d628a0SDimitry Andric       EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
139244290647SDimitry Andric                 SanitizerHandler::MissingReturn,
139344290647SDimitry Andric                 EmitCheckSourceLocation(FD->getLocation()), None);
13948e0f8b8cSDimitry Andric     } else if (ShouldEmitUnreachable) {
13958e0f8b8cSDimitry Andric       if (CGM.getCodeGenOpts().OptimizationLevel == 0)
13963dac3a9bSDimitry Andric         EmitTrapCall(llvm::Intrinsic::trap);
13973dac3a9bSDimitry Andric     }
13988e0f8b8cSDimitry Andric     if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
13993861d79fSDimitry Andric       Builder.CreateUnreachable();
14003861d79fSDimitry Andric       Builder.ClearInsertionPoint();
14013861d79fSDimitry Andric     }
14028e0f8b8cSDimitry Andric   }
14033861d79fSDimitry Andric 
1404f22ef01cSRoman Divacky   // Emit the standard function epilogue.
1405f22ef01cSRoman Divacky   FinishFunction(BodyRange.getEnd());
1406f22ef01cSRoman Divacky 
1407e580952dSDimitry Andric   // If we haven't marked the function nothrow through other means, do
1408e580952dSDimitry Andric   // a quick pass now to see if we can.
1409e580952dSDimitry Andric   if (!CurFn->doesNotThrow())
1410e580952dSDimitry Andric     TryMarkNoThrow(CurFn);
1411f22ef01cSRoman Divacky }
1412f22ef01cSRoman Divacky 
1413f22ef01cSRoman Divacky /// ContainsLabel - Return true if the statement contains a label in it.  If
1414f22ef01cSRoman Divacky /// this statement is not executed normally, it not containing a label means
1415f22ef01cSRoman Divacky /// that we can just remove the code.
ContainsLabel(const Stmt * S,bool IgnoreCaseStmts)1416f22ef01cSRoman Divacky bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1417f22ef01cSRoman Divacky   // Null statement, not a label!
141859d1ed5bSDimitry Andric   if (!S) return false;
1419f22ef01cSRoman Divacky 
1420f22ef01cSRoman Divacky   // If this is a label, we have to emit the code, consider something like:
1421f22ef01cSRoman Divacky   // if (0) {  ...  foo:  bar(); }  goto foo;
14223b0f4066SDimitry Andric   //
14233b0f4066SDimitry Andric   // TODO: If anyone cared, we could track __label__'s, since we know that you
14243b0f4066SDimitry Andric   // can't jump to one from outside their declared region.
1425f22ef01cSRoman Divacky   if (isa<LabelStmt>(S))
1426f22ef01cSRoman Divacky     return true;
1427f22ef01cSRoman Divacky 
1428f22ef01cSRoman Divacky   // If this is a case/default statement, and we haven't seen a switch, we have
1429f22ef01cSRoman Divacky   // to emit the code.
1430f22ef01cSRoman Divacky   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1431f22ef01cSRoman Divacky     return true;
1432f22ef01cSRoman Divacky 
1433f22ef01cSRoman Divacky   // If this is a switch statement, we want to ignore cases below it.
1434f22ef01cSRoman Divacky   if (isa<SwitchStmt>(S))
1435f22ef01cSRoman Divacky     IgnoreCaseStmts = true;
1436f22ef01cSRoman Divacky 
1437f22ef01cSRoman Divacky   // Scan subexpressions for verboten labels.
14383dac3a9bSDimitry Andric   for (const Stmt *SubStmt : S->children())
14393dac3a9bSDimitry Andric     if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1440f22ef01cSRoman Divacky       return true;
1441f22ef01cSRoman Divacky 
1442f22ef01cSRoman Divacky   return false;
1443f22ef01cSRoman Divacky }
1444f22ef01cSRoman Divacky 
14453b0f4066SDimitry Andric /// containsBreak - Return true if the statement contains a break out of it.
14463b0f4066SDimitry Andric /// If the statement (recursively) contains a switch or loop with a break
14473b0f4066SDimitry Andric /// inside of it, this is fine.
containsBreak(const Stmt * S)14483b0f4066SDimitry Andric bool CodeGenFunction::containsBreak(const Stmt *S) {
14493b0f4066SDimitry Andric   // Null statement, not a label!
145059d1ed5bSDimitry Andric   if (!S) return false;
1451f22ef01cSRoman Divacky 
14523b0f4066SDimitry Andric   // If this is a switch or loop that defines its own break scope, then we can
14533b0f4066SDimitry Andric   // include it and anything inside of it.
14543b0f4066SDimitry Andric   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
14553b0f4066SDimitry Andric       isa<ForStmt>(S))
14563b0f4066SDimitry Andric     return false;
14573b0f4066SDimitry Andric 
14583b0f4066SDimitry Andric   if (isa<BreakStmt>(S))
14593b0f4066SDimitry Andric     return true;
14603b0f4066SDimitry Andric 
14613b0f4066SDimitry Andric   // Scan subexpressions for verboten breaks.
14623dac3a9bSDimitry Andric   for (const Stmt *SubStmt : S->children())
14633dac3a9bSDimitry Andric     if (containsBreak(SubStmt))
14643b0f4066SDimitry Andric       return true;
14653b0f4066SDimitry Andric 
14663b0f4066SDimitry Andric   return false;
14673b0f4066SDimitry Andric }
14683b0f4066SDimitry Andric 
mightAddDeclToScope(const Stmt * S)1469f41fbc90SDimitry Andric bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
1470f41fbc90SDimitry Andric   if (!S) return false;
1471f41fbc90SDimitry Andric 
1472f41fbc90SDimitry Andric   // Some statement kinds add a scope and thus never add a decl to the current
1473f41fbc90SDimitry Andric   // scope. Note, this list is longer than the list of statements that might
1474f41fbc90SDimitry Andric   // have an unscoped decl nested within them, but this way is conservatively
1475f41fbc90SDimitry Andric   // correct even if more statement kinds are added.
1476f41fbc90SDimitry Andric   if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1477f41fbc90SDimitry Andric       isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
1478f41fbc90SDimitry Andric       isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
1479f41fbc90SDimitry Andric       isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
1480f41fbc90SDimitry Andric     return false;
1481f41fbc90SDimitry Andric 
1482f41fbc90SDimitry Andric   if (isa<DeclStmt>(S))
1483f41fbc90SDimitry Andric     return true;
1484f41fbc90SDimitry Andric 
1485f41fbc90SDimitry Andric   for (const Stmt *SubStmt : S->children())
1486f41fbc90SDimitry Andric     if (mightAddDeclToScope(SubStmt))
1487f41fbc90SDimitry Andric       return true;
1488f41fbc90SDimitry Andric 
1489f41fbc90SDimitry Andric   return false;
1490f41fbc90SDimitry Andric }
14913b0f4066SDimitry Andric 
14923b0f4066SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
14933b0f4066SDimitry Andric /// to a constant, or if it does but contains a label, return false.  If it
14943b0f4066SDimitry Andric /// constant folds return true and set the boolean result in Result.
ConstantFoldsToSimpleInteger(const Expr * Cond,bool & ResultBool,bool AllowLabels)14953b0f4066SDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1496e7145dcbSDimitry Andric                                                    bool &ResultBool,
1497e7145dcbSDimitry Andric                                                    bool AllowLabels) {
14987ae0e2c9SDimitry Andric   llvm::APSInt ResultInt;
1499e7145dcbSDimitry Andric   if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
15003b0f4066SDimitry Andric     return false;
15013b0f4066SDimitry Andric 
15023b0f4066SDimitry Andric   ResultBool = ResultInt.getBoolValue();
15033b0f4066SDimitry Andric   return true;
15043b0f4066SDimitry Andric }
15053b0f4066SDimitry Andric 
15063b0f4066SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
15073b0f4066SDimitry Andric /// to a constant, or if it does but contains a label, return false.  If it
15083b0f4066SDimitry Andric /// constant folds return true and set the folded value.
ConstantFoldsToSimpleInteger(const Expr * Cond,llvm::APSInt & ResultInt,bool AllowLabels)1509e7145dcbSDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1510e7145dcbSDimitry Andric                                                    llvm::APSInt &ResultInt,
1511e7145dcbSDimitry Andric                                                    bool AllowLabels) {
1512f22ef01cSRoman Divacky   // FIXME: Rename and handle conversion of other evaluatable things
1513f22ef01cSRoman Divacky   // to bool.
1514*b5893f02SDimitry Andric   Expr::EvalResult Result;
1515*b5893f02SDimitry Andric   if (!Cond->EvaluateAsInt(Result, getContext()))
15163b0f4066SDimitry Andric     return false;  // Not foldable, not integer or not fully evaluatable.
1517f22ef01cSRoman Divacky 
1518*b5893f02SDimitry Andric   llvm::APSInt Int = Result.Val.getInt();
1519e7145dcbSDimitry Andric   if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
15203b0f4066SDimitry Andric     return false;  // Contains a label.
1521f22ef01cSRoman Divacky 
1522dff0c46cSDimitry Andric   ResultInt = Int;
15233b0f4066SDimitry Andric   return true;
1524f22ef01cSRoman Divacky }
1525f22ef01cSRoman Divacky 
1526f22ef01cSRoman Divacky 
15273b0f4066SDimitry Andric 
1528f22ef01cSRoman Divacky /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1529f22ef01cSRoman Divacky /// statement) to the specified blocks.  Based on the condition, this might try
1530f22ef01cSRoman Divacky /// to simplify the codegen of the conditional based on the branch.
1531f22ef01cSRoman Divacky ///
EmitBranchOnBoolExpr(const Expr * Cond,llvm::BasicBlock * TrueBlock,llvm::BasicBlock * FalseBlock,uint64_t TrueCount)1532f22ef01cSRoman Divacky void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1533f22ef01cSRoman Divacky                                            llvm::BasicBlock *TrueBlock,
153459d1ed5bSDimitry Andric                                            llvm::BasicBlock *FalseBlock,
153559d1ed5bSDimitry Andric                                            uint64_t TrueCount) {
15363b0f4066SDimitry Andric   Cond = Cond->IgnoreParens();
1537f22ef01cSRoman Divacky 
1538f22ef01cSRoman Divacky   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
153959d1ed5bSDimitry Andric 
1540f22ef01cSRoman Divacky     // Handle X && Y in a condition.
1541e580952dSDimitry Andric     if (CondBOp->getOpcode() == BO_LAnd) {
1542f22ef01cSRoman Divacky       // If we have "1 && X", simplify the code.  "0 && X" would have constant
1543f22ef01cSRoman Divacky       // folded if the case was simple enough.
15443b0f4066SDimitry Andric       bool ConstantBool = false;
15453b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
15463b0f4066SDimitry Andric           ConstantBool) {
1547f22ef01cSRoman Divacky         // br(1 && X) -> br(X).
154833956c43SDimitry Andric         incrementProfileCounter(CondBOp);
154959d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
155059d1ed5bSDimitry Andric                                     TrueCount);
1551f22ef01cSRoman Divacky       }
1552f22ef01cSRoman Divacky 
1553f22ef01cSRoman Divacky       // If we have "X && 1", simplify the code to use an uncond branch.
1554f22ef01cSRoman Divacky       // "X && 0" would have been constant folded to 0.
15553b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
15563b0f4066SDimitry Andric           ConstantBool) {
1557f22ef01cSRoman Divacky         // br(X && 1) -> br(X).
155859d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
155959d1ed5bSDimitry Andric                                     TrueCount);
1560f22ef01cSRoman Divacky       }
1561f22ef01cSRoman Divacky 
1562f22ef01cSRoman Divacky       // Emit the LHS as a conditional.  If the LHS conditional is false, we
1563f22ef01cSRoman Divacky       // want to jump to the FalseBlock.
1564f22ef01cSRoman Divacky       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
156559d1ed5bSDimitry Andric       // The counter tells us how often we evaluate RHS, and all of TrueCount
156659d1ed5bSDimitry Andric       // can be propagated to that branch.
156733956c43SDimitry Andric       uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
15682754fe60SDimitry Andric 
15692754fe60SDimitry Andric       ConditionalEvaluation eval(*this);
157033956c43SDimitry Andric       {
157133956c43SDimitry Andric         ApplyDebugLocation DL(*this, Cond);
157259d1ed5bSDimitry Andric         EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
1573f22ef01cSRoman Divacky         EmitBlock(LHSTrue);
157433956c43SDimitry Andric       }
157533956c43SDimitry Andric 
157633956c43SDimitry Andric       incrementProfileCounter(CondBOp);
157733956c43SDimitry Andric       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1578f22ef01cSRoman Divacky 
1579f22ef01cSRoman Divacky       // Any temporaries created here are conditional.
15802754fe60SDimitry Andric       eval.begin(*this);
158159d1ed5bSDimitry Andric       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
15822754fe60SDimitry Andric       eval.end(*this);
1583f22ef01cSRoman Divacky 
1584f22ef01cSRoman Divacky       return;
15853b0f4066SDimitry Andric     }
15863b0f4066SDimitry Andric 
15873b0f4066SDimitry Andric     if (CondBOp->getOpcode() == BO_LOr) {
1588f22ef01cSRoman Divacky       // If we have "0 || X", simplify the code.  "1 || X" would have constant
1589f22ef01cSRoman Divacky       // folded if the case was simple enough.
15903b0f4066SDimitry Andric       bool ConstantBool = false;
15913b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
15923b0f4066SDimitry Andric           !ConstantBool) {
1593f22ef01cSRoman Divacky         // br(0 || X) -> br(X).
159433956c43SDimitry Andric         incrementProfileCounter(CondBOp);
159559d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
159659d1ed5bSDimitry Andric                                     TrueCount);
1597f22ef01cSRoman Divacky       }
1598f22ef01cSRoman Divacky 
1599f22ef01cSRoman Divacky       // If we have "X || 0", simplify the code to use an uncond branch.
1600f22ef01cSRoman Divacky       // "X || 1" would have been constant folded to 1.
16013b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
16023b0f4066SDimitry Andric           !ConstantBool) {
1603f22ef01cSRoman Divacky         // br(X || 0) -> br(X).
160459d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
160559d1ed5bSDimitry Andric                                     TrueCount);
1606f22ef01cSRoman Divacky       }
1607f22ef01cSRoman Divacky 
1608f22ef01cSRoman Divacky       // Emit the LHS as a conditional.  If the LHS conditional is true, we
1609f22ef01cSRoman Divacky       // want to jump to the TrueBlock.
1610f22ef01cSRoman Divacky       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
161159d1ed5bSDimitry Andric       // We have the count for entry to the RHS and for the whole expression
161259d1ed5bSDimitry Andric       // being true, so we can divy up True count between the short circuit and
161359d1ed5bSDimitry Andric       // the RHS.
161433956c43SDimitry Andric       uint64_t LHSCount =
161533956c43SDimitry Andric           getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
161659d1ed5bSDimitry Andric       uint64_t RHSCount = TrueCount - LHSCount;
16172754fe60SDimitry Andric 
16182754fe60SDimitry Andric       ConditionalEvaluation eval(*this);
161933956c43SDimitry Andric       {
162033956c43SDimitry Andric         ApplyDebugLocation DL(*this, Cond);
162159d1ed5bSDimitry Andric         EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
1622f22ef01cSRoman Divacky         EmitBlock(LHSFalse);
162333956c43SDimitry Andric       }
162433956c43SDimitry Andric 
162533956c43SDimitry Andric       incrementProfileCounter(CondBOp);
162633956c43SDimitry Andric       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1627f22ef01cSRoman Divacky 
1628f22ef01cSRoman Divacky       // Any temporaries created here are conditional.
16292754fe60SDimitry Andric       eval.begin(*this);
163059d1ed5bSDimitry Andric       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
163159d1ed5bSDimitry Andric 
16322754fe60SDimitry Andric       eval.end(*this);
1633f22ef01cSRoman Divacky 
1634f22ef01cSRoman Divacky       return;
1635f22ef01cSRoman Divacky     }
1636f22ef01cSRoman Divacky   }
1637f22ef01cSRoman Divacky 
1638f22ef01cSRoman Divacky   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1639f22ef01cSRoman Divacky     // br(!x, t, f) -> br(x, f, t)
164059d1ed5bSDimitry Andric     if (CondUOp->getOpcode() == UO_LNot) {
164159d1ed5bSDimitry Andric       // Negate the count.
164233956c43SDimitry Andric       uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
164359d1ed5bSDimitry Andric       // Negate the condition and swap the destination blocks.
164459d1ed5bSDimitry Andric       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
164559d1ed5bSDimitry Andric                                   FalseCount);
164659d1ed5bSDimitry Andric     }
1647f22ef01cSRoman Divacky   }
1648f22ef01cSRoman Divacky 
1649f22ef01cSRoman Divacky   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1650f22ef01cSRoman Divacky     // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1651f22ef01cSRoman Divacky     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1652f22ef01cSRoman Divacky     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
16532754fe60SDimitry Andric 
16542754fe60SDimitry Andric     ConditionalEvaluation cond(*this);
165533956c43SDimitry Andric     EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
165633956c43SDimitry Andric                          getProfileCount(CondOp));
165759d1ed5bSDimitry Andric 
165859d1ed5bSDimitry Andric     // When computing PGO branch weights, we only know the overall count for
165959d1ed5bSDimitry Andric     // the true block. This code is essentially doing tail duplication of the
166059d1ed5bSDimitry Andric     // naive code-gen, introducing new edges for which counts are not
166159d1ed5bSDimitry Andric     // available. Divide the counts proportionally between the LHS and RHS of
166259d1ed5bSDimitry Andric     // the conditional operator.
166359d1ed5bSDimitry Andric     uint64_t LHSScaledTrueCount = 0;
166459d1ed5bSDimitry Andric     if (TrueCount) {
166533956c43SDimitry Andric       double LHSRatio =
166633956c43SDimitry Andric           getProfileCount(CondOp) / (double)getCurrentProfileCount();
166759d1ed5bSDimitry Andric       LHSScaledTrueCount = TrueCount * LHSRatio;
166859d1ed5bSDimitry Andric     }
16692754fe60SDimitry Andric 
16702754fe60SDimitry Andric     cond.begin(*this);
1671f22ef01cSRoman Divacky     EmitBlock(LHSBlock);
167233956c43SDimitry Andric     incrementProfileCounter(CondOp);
167333956c43SDimitry Andric     {
167433956c43SDimitry Andric       ApplyDebugLocation DL(*this, Cond);
167559d1ed5bSDimitry Andric       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
167659d1ed5bSDimitry Andric                            LHSScaledTrueCount);
167733956c43SDimitry Andric     }
16782754fe60SDimitry Andric     cond.end(*this);
16792754fe60SDimitry Andric 
16802754fe60SDimitry Andric     cond.begin(*this);
1681f22ef01cSRoman Divacky     EmitBlock(RHSBlock);
168259d1ed5bSDimitry Andric     EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
168359d1ed5bSDimitry Andric                          TrueCount - LHSScaledTrueCount);
16842754fe60SDimitry Andric     cond.end(*this);
16852754fe60SDimitry Andric 
1686f22ef01cSRoman Divacky     return;
1687f22ef01cSRoman Divacky   }
1688f22ef01cSRoman Divacky 
1689284c1978SDimitry Andric   if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1690284c1978SDimitry Andric     // Conditional operator handling can give us a throw expression as a
1691284c1978SDimitry Andric     // condition for a case like:
1692284c1978SDimitry Andric     //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1693284c1978SDimitry Andric     // Fold this to:
1694284c1978SDimitry Andric     //   br(c, throw x, br(y, t, f))
1695284c1978SDimitry Andric     EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1696284c1978SDimitry Andric     return;
1697284c1978SDimitry Andric   }
1698284c1978SDimitry Andric 
16990623d748SDimitry Andric   // If the branch has a condition wrapped by __builtin_unpredictable,
17000623d748SDimitry Andric   // create metadata that specifies that the branch is unpredictable.
17010623d748SDimitry Andric   // Don't bother if not optimizing because that metadata would not be used.
17020623d748SDimitry Andric   llvm::MDNode *Unpredictable = nullptr;
1703*b5893f02SDimitry Andric   auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
1704e7145dcbSDimitry Andric   if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1705e7145dcbSDimitry Andric     auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1706e7145dcbSDimitry Andric     if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
17070623d748SDimitry Andric       llvm::MDBuilder MDHelper(getLLVMContext());
17080623d748SDimitry Andric       Unpredictable = MDHelper.createUnpredictable();
17090623d748SDimitry Andric     }
17100623d748SDimitry Andric   }
17110623d748SDimitry Andric 
171259d1ed5bSDimitry Andric   // Create branch weights based on the number of times we get here and the
171359d1ed5bSDimitry Andric   // number of times the condition should be true.
171433956c43SDimitry Andric   uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
171533956c43SDimitry Andric   llvm::MDNode *Weights =
171633956c43SDimitry Andric       createProfileWeights(TrueCount, CurrentCount - TrueCount);
171759d1ed5bSDimitry Andric 
1718f22ef01cSRoman Divacky   // Emit the code with the fully general case.
171933956c43SDimitry Andric   llvm::Value *CondV;
172033956c43SDimitry Andric   {
172133956c43SDimitry Andric     ApplyDebugLocation DL(*this, Cond);
172233956c43SDimitry Andric     CondV = EvaluateExprAsBool(Cond);
172333956c43SDimitry Andric   }
17240623d748SDimitry Andric   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
1725f22ef01cSRoman Divacky }
1726f22ef01cSRoman Divacky 
1727f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
1728f22ef01cSRoman Divacky /// specified stmt yet.
ErrorUnsupported(const Stmt * S,const char * Type)1729f785676fSDimitry Andric void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1730f785676fSDimitry Andric   CGM.ErrorUnsupported(S, Type);
1731f22ef01cSRoman Divacky }
1732f22ef01cSRoman Divacky 
17332754fe60SDimitry Andric /// emitNonZeroVLAInit - Emit the "zero" initialization of a
17342754fe60SDimitry Andric /// variable-length array whose elements have a non-zero bit-pattern.
17352754fe60SDimitry Andric ///
17367ae0e2c9SDimitry Andric /// \param baseType the inner-most element type of the array
17372754fe60SDimitry Andric /// \param src - a char* pointing to the bit-pattern for a single
17382754fe60SDimitry Andric /// base element of the array
17392754fe60SDimitry Andric /// \param sizeInChars - the total size of the VLA, in chars
emitNonZeroVLAInit(CodeGenFunction & CGF,QualType baseType,Address dest,Address src,llvm::Value * sizeInChars)17402754fe60SDimitry Andric static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
17410623d748SDimitry Andric                                Address dest, Address src,
17422754fe60SDimitry Andric                                llvm::Value *sizeInChars) {
17432754fe60SDimitry Andric   CGBuilderTy &Builder = CGF.Builder;
17442754fe60SDimitry Andric 
17450623d748SDimitry Andric   CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
17462754fe60SDimitry Andric   llvm::Value *baseSizeInChars
17470623d748SDimitry Andric     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
17482754fe60SDimitry Andric 
17490623d748SDimitry Andric   Address begin =
17500623d748SDimitry Andric     Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
17510623d748SDimitry Andric   llvm::Value *end =
17520623d748SDimitry Andric     Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
17532754fe60SDimitry Andric 
17542754fe60SDimitry Andric   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
17552754fe60SDimitry Andric   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
17562754fe60SDimitry Andric   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
17572754fe60SDimitry Andric 
17582754fe60SDimitry Andric   // Make a loop over the VLA.  C99 guarantees that the VLA element
17592754fe60SDimitry Andric   // count must be nonzero.
17602754fe60SDimitry Andric   CGF.EmitBlock(loopBB);
17612754fe60SDimitry Andric 
17620623d748SDimitry Andric   llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
17630623d748SDimitry Andric   cur->addIncoming(begin.getPointer(), originBB);
17640623d748SDimitry Andric 
17650623d748SDimitry Andric   CharUnits curAlign =
17660623d748SDimitry Andric     dest.getAlignment().alignmentOfArrayElement(baseSize);
17672754fe60SDimitry Andric 
17682754fe60SDimitry Andric   // memcpy the individual element bit-pattern.
17690623d748SDimitry Andric   Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
17702754fe60SDimitry Andric                        /*volatile*/ false);
17712754fe60SDimitry Andric 
17722754fe60SDimitry Andric   // Go to the next element.
17730623d748SDimitry Andric   llvm::Value *next =
17740623d748SDimitry Andric     Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
17752754fe60SDimitry Andric 
17762754fe60SDimitry Andric   // Leave if that's the end of the VLA.
17772754fe60SDimitry Andric   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
17782754fe60SDimitry Andric   Builder.CreateCondBr(done, contBB, loopBB);
17792754fe60SDimitry Andric   cur->addIncoming(next, loopBB);
17802754fe60SDimitry Andric 
17812754fe60SDimitry Andric   CGF.EmitBlock(contBB);
17822754fe60SDimitry Andric }
17832754fe60SDimitry Andric 
1784f22ef01cSRoman Divacky void
EmitNullInitialization(Address DestPtr,QualType Ty)17850623d748SDimitry Andric CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
1786f22ef01cSRoman Divacky   // Ignore empty classes in C++.
17873861d79fSDimitry Andric   if (getLangOpts().CPlusPlus) {
1788f22ef01cSRoman Divacky     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1789f22ef01cSRoman Divacky       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1790f22ef01cSRoman Divacky         return;
1791f22ef01cSRoman Divacky     }
1792f22ef01cSRoman Divacky   }
1793f22ef01cSRoman Divacky 
1794e580952dSDimitry Andric   // Cast the dest ptr to the appropriate i8 pointer type.
17950623d748SDimitry Andric   if (DestPtr.getElementType() != Int8Ty)
17960623d748SDimitry Andric     DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
1797f22ef01cSRoman Divacky 
1798f22ef01cSRoman Divacky   // Get size and alignment info for this aggregate.
17990623d748SDimitry Andric   CharUnits size = getContext().getTypeSizeInChars(Ty);
18002754fe60SDimitry Andric 
18012754fe60SDimitry Andric   llvm::Value *SizeVal;
18022754fe60SDimitry Andric   const VariableArrayType *vla;
1803f22ef01cSRoman Divacky 
1804f22ef01cSRoman Divacky   // Don't bother emitting a zero-byte memset.
18050623d748SDimitry Andric   if (size.isZero()) {
18062754fe60SDimitry Andric     // But note that getTypeInfo returns 0 for a VLA.
18072754fe60SDimitry Andric     if (const VariableArrayType *vlaType =
18082754fe60SDimitry Andric           dyn_cast_or_null<VariableArrayType>(
18092754fe60SDimitry Andric                                           getContext().getAsArrayType(Ty))) {
18104ba319b5SDimitry Andric       auto VlaSize = getVLASize(vlaType);
18114ba319b5SDimitry Andric       SizeVal = VlaSize.NumElts;
18124ba319b5SDimitry Andric       CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
181317a519f9SDimitry Andric       if (!eltSize.isOne())
181417a519f9SDimitry Andric         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
18152754fe60SDimitry Andric       vla = vlaType;
18162754fe60SDimitry Andric     } else {
1817f22ef01cSRoman Divacky       return;
18182754fe60SDimitry Andric     }
18192754fe60SDimitry Andric   } else {
18200623d748SDimitry Andric     SizeVal = CGM.getSize(size);
182159d1ed5bSDimitry Andric     vla = nullptr;
18222754fe60SDimitry Andric   }
1823e580952dSDimitry Andric 
1824e580952dSDimitry Andric   // If the type contains a pointer to data member we can't memset it to zero.
1825e580952dSDimitry Andric   // Instead, create a null constant and copy it to the destination.
18262754fe60SDimitry Andric   // TODO: there are other patterns besides zero that we can usefully memset,
18272754fe60SDimitry Andric   // like -1, which happens to be the pattern used by member-pointers.
1828e580952dSDimitry Andric   if (!CGM.getTypes().isZeroInitializable(Ty)) {
18292754fe60SDimitry Andric     // For a VLA, emit a single element, then splat that over the VLA.
18302754fe60SDimitry Andric     if (vla) Ty = getContext().getBaseElementType(vla);
18312754fe60SDimitry Andric 
1832e580952dSDimitry Andric     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1833e580952dSDimitry Andric 
1834e580952dSDimitry Andric     llvm::GlobalVariable *NullVariable =
1835e580952dSDimitry Andric       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1836e580952dSDimitry Andric                                /*isConstant=*/true,
1837e580952dSDimitry Andric                                llvm::GlobalVariable::PrivateLinkage,
18386122f3e6SDimitry Andric                                NullConstant, Twine());
18390623d748SDimitry Andric     CharUnits NullAlign = DestPtr.getAlignment();
18400623d748SDimitry Andric     NullVariable->setAlignment(NullAlign.getQuantity());
18410623d748SDimitry Andric     Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
18420623d748SDimitry Andric                    NullAlign);
1843e580952dSDimitry Andric 
18442754fe60SDimitry Andric     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1845e580952dSDimitry Andric 
1846e580952dSDimitry Andric     // Get and call the appropriate llvm.memcpy overload.
18470623d748SDimitry Andric     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
1848e580952dSDimitry Andric     return;
1849e580952dSDimitry Andric   }
1850e580952dSDimitry Andric 
1851e580952dSDimitry Andric   // Otherwise, just memset the whole thing to zero.  This is legal
1852e580952dSDimitry Andric   // because in LLVM, all default initializers (other than the ones we just
1853e580952dSDimitry Andric   // handled above) are guaranteed to have a bit pattern of all zeros.
18540623d748SDimitry Andric   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
1855f22ef01cSRoman Divacky }
1856f22ef01cSRoman Divacky 
GetAddrOfLabel(const LabelDecl * L)18572754fe60SDimitry Andric llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
1858f22ef01cSRoman Divacky   // Make sure that there is a block for the indirect goto.
185959d1ed5bSDimitry Andric   if (!IndirectBranch)
1860f22ef01cSRoman Divacky     GetIndirectGotoBlock();
1861f22ef01cSRoman Divacky 
1862e580952dSDimitry Andric   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
1863f22ef01cSRoman Divacky 
1864f22ef01cSRoman Divacky   // Make sure the indirect branch includes all of the address-taken blocks.
1865f22ef01cSRoman Divacky   IndirectBranch->addDestination(BB);
1866f22ef01cSRoman Divacky   return llvm::BlockAddress::get(CurFn, BB);
1867f22ef01cSRoman Divacky }
1868f22ef01cSRoman Divacky 
GetIndirectGotoBlock()1869f22ef01cSRoman Divacky llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
1870f22ef01cSRoman Divacky   // If we already made the indirect branch for indirect goto, return its block.
1871f22ef01cSRoman Divacky   if (IndirectBranch) return IndirectBranch->getParent();
1872f22ef01cSRoman Divacky 
18730623d748SDimitry Andric   CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
1874f22ef01cSRoman Divacky 
1875f22ef01cSRoman Divacky   // Create the PHI node that indirect gotos will add entries to.
18763b0f4066SDimitry Andric   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
18773b0f4066SDimitry Andric                                               "indirect.goto.dest");
1878f22ef01cSRoman Divacky 
1879f22ef01cSRoman Divacky   // Create the indirect branch instruction.
1880f22ef01cSRoman Divacky   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1881f22ef01cSRoman Divacky   return IndirectBranch->getParent();
1882f22ef01cSRoman Divacky }
1883f22ef01cSRoman Divacky 
188417a519f9SDimitry Andric /// Computes the length of an array in elements, as well as the base
188517a519f9SDimitry Andric /// element type and a properly-typed first element pointer.
emitArrayLength(const ArrayType * origArrayType,QualType & baseType,Address & addr)188617a519f9SDimitry Andric llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
188717a519f9SDimitry Andric                                               QualType &baseType,
18880623d748SDimitry Andric                                               Address &addr) {
188917a519f9SDimitry Andric   const ArrayType *arrayType = origArrayType;
1890f22ef01cSRoman Divacky 
189117a519f9SDimitry Andric   // If it's a VLA, we have to load the stored size.  Note that
189217a519f9SDimitry Andric   // this is the size of the VLA in bytes, not its size in elements.
189359d1ed5bSDimitry Andric   llvm::Value *numVLAElements = nullptr;
189417a519f9SDimitry Andric   if (isa<VariableArrayType>(arrayType)) {
18954ba319b5SDimitry Andric     numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
189617a519f9SDimitry Andric 
189717a519f9SDimitry Andric     // Walk into all VLAs.  This doesn't require changes to addr,
189817a519f9SDimitry Andric     // which has type T* where T is the first non-VLA element type.
189917a519f9SDimitry Andric     do {
190017a519f9SDimitry Andric       QualType elementType = arrayType->getElementType();
190117a519f9SDimitry Andric       arrayType = getContext().getAsArrayType(elementType);
190217a519f9SDimitry Andric 
190317a519f9SDimitry Andric       // If we only have VLA components, 'addr' requires no adjustment.
190417a519f9SDimitry Andric       if (!arrayType) {
190517a519f9SDimitry Andric         baseType = elementType;
190617a519f9SDimitry Andric         return numVLAElements;
190717a519f9SDimitry Andric       }
190817a519f9SDimitry Andric     } while (isa<VariableArrayType>(arrayType));
190917a519f9SDimitry Andric 
191017a519f9SDimitry Andric     // We get out here only if we find a constant array type
191117a519f9SDimitry Andric     // inside the VLA.
1912f22ef01cSRoman Divacky   }
1913f22ef01cSRoman Divacky 
191417a519f9SDimitry Andric   // We have some number of constant-length arrays, so addr should
191517a519f9SDimitry Andric   // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
191617a519f9SDimitry Andric   // down to the first element of addr.
19176122f3e6SDimitry Andric   SmallVector<llvm::Value*, 8> gepIndices;
191817a519f9SDimitry Andric 
191917a519f9SDimitry Andric   // GEP down to the array type.
192017a519f9SDimitry Andric   llvm::ConstantInt *zero = Builder.getInt32(0);
192117a519f9SDimitry Andric   gepIndices.push_back(zero);
192217a519f9SDimitry Andric 
192317a519f9SDimitry Andric   uint64_t countFromCLAs = 1;
19247ae0e2c9SDimitry Andric   QualType eltType;
192517a519f9SDimitry Andric 
19266122f3e6SDimitry Andric   llvm::ArrayType *llvmArrayType =
19270623d748SDimitry Andric     dyn_cast<llvm::ArrayType>(addr.getElementType());
19287ae0e2c9SDimitry Andric   while (llvmArrayType) {
192917a519f9SDimitry Andric     assert(isa<ConstantArrayType>(arrayType));
193017a519f9SDimitry Andric     assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
193117a519f9SDimitry Andric              == llvmArrayType->getNumElements());
193217a519f9SDimitry Andric 
193317a519f9SDimitry Andric     gepIndices.push_back(zero);
193417a519f9SDimitry Andric     countFromCLAs *= llvmArrayType->getNumElements();
19357ae0e2c9SDimitry Andric     eltType = arrayType->getElementType();
193617a519f9SDimitry Andric 
193717a519f9SDimitry Andric     llvmArrayType =
193817a519f9SDimitry Andric       dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
193917a519f9SDimitry Andric     arrayType = getContext().getAsArrayType(arrayType->getElementType());
19407ae0e2c9SDimitry Andric     assert((!llvmArrayType || arrayType) &&
19417ae0e2c9SDimitry Andric            "LLVM and Clang types are out-of-synch");
194217a519f9SDimitry Andric   }
194317a519f9SDimitry Andric 
19447ae0e2c9SDimitry Andric   if (arrayType) {
19457ae0e2c9SDimitry Andric     // From this point onwards, the Clang array type has been emitted
19467ae0e2c9SDimitry Andric     // as some other type (probably a packed struct). Compute the array
19477ae0e2c9SDimitry Andric     // size, and just emit the 'begin' expression as a bitcast.
19487ae0e2c9SDimitry Andric     while (arrayType) {
19497ae0e2c9SDimitry Andric       countFromCLAs *=
19507ae0e2c9SDimitry Andric           cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
19517ae0e2c9SDimitry Andric       eltType = arrayType->getElementType();
19527ae0e2c9SDimitry Andric       arrayType = getContext().getAsArrayType(eltType);
19537ae0e2c9SDimitry Andric     }
195417a519f9SDimitry Andric 
19550623d748SDimitry Andric     llvm::Type *baseType = ConvertType(eltType);
19560623d748SDimitry Andric     addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
19577ae0e2c9SDimitry Andric   } else {
195817a519f9SDimitry Andric     // Create the actual GEP.
19590623d748SDimitry Andric     addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
19600623d748SDimitry Andric                                              gepIndices, "array.begin"),
19610623d748SDimitry Andric                    addr.getAlignment());
19627ae0e2c9SDimitry Andric   }
19637ae0e2c9SDimitry Andric 
19647ae0e2c9SDimitry Andric   baseType = eltType;
196517a519f9SDimitry Andric 
196617a519f9SDimitry Andric   llvm::Value *numElements
196717a519f9SDimitry Andric     = llvm::ConstantInt::get(SizeTy, countFromCLAs);
196817a519f9SDimitry Andric 
196917a519f9SDimitry Andric   // If we had any VLA dimensions, factor them in.
197017a519f9SDimitry Andric   if (numVLAElements)
197117a519f9SDimitry Andric     numElements = Builder.CreateNUWMul(numVLAElements, numElements);
197217a519f9SDimitry Andric 
197317a519f9SDimitry Andric   return numElements;
197417a519f9SDimitry Andric }
197517a519f9SDimitry Andric 
getVLASize(QualType type)19764ba319b5SDimitry Andric CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
197717a519f9SDimitry Andric   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
197817a519f9SDimitry Andric   assert(vla && "type was not a variable array type!");
197917a519f9SDimitry Andric   return getVLASize(vla);
198017a519f9SDimitry Andric }
198117a519f9SDimitry Andric 
19824ba319b5SDimitry Andric CodeGenFunction::VlaSizePair
getVLASize(const VariableArrayType * type)198317a519f9SDimitry Andric CodeGenFunction::getVLASize(const VariableArrayType *type) {
198417a519f9SDimitry Andric   // The number of elements so far; always size_t.
198559d1ed5bSDimitry Andric   llvm::Value *numElements = nullptr;
198617a519f9SDimitry Andric 
198717a519f9SDimitry Andric   QualType elementType;
198817a519f9SDimitry Andric   do {
198917a519f9SDimitry Andric     elementType = type->getElementType();
199017a519f9SDimitry Andric     llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
199117a519f9SDimitry Andric     assert(vlaSize && "no size for VLA!");
199217a519f9SDimitry Andric     assert(vlaSize->getType() == SizeTy);
199317a519f9SDimitry Andric 
199417a519f9SDimitry Andric     if (!numElements) {
199517a519f9SDimitry Andric       numElements = vlaSize;
199617a519f9SDimitry Andric     } else {
199717a519f9SDimitry Andric       // It's undefined behavior if this wraps around, so mark it that way.
199859d1ed5bSDimitry Andric       // FIXME: Teach -fsanitize=undefined to trap this.
199917a519f9SDimitry Andric       numElements = Builder.CreateNUWMul(numElements, vlaSize);
200017a519f9SDimitry Andric     }
200117a519f9SDimitry Andric   } while ((type = getContext().getAsVariableArrayType(elementType)));
200217a519f9SDimitry Andric 
20034ba319b5SDimitry Andric   return { numElements, elementType };
20044ba319b5SDimitry Andric }
20054ba319b5SDimitry Andric 
20064ba319b5SDimitry Andric CodeGenFunction::VlaSizePair
getVLAElements1D(QualType type)20074ba319b5SDimitry Andric CodeGenFunction::getVLAElements1D(QualType type) {
20084ba319b5SDimitry Andric   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
20094ba319b5SDimitry Andric   assert(vla && "type was not a variable array type!");
20104ba319b5SDimitry Andric   return getVLAElements1D(vla);
20114ba319b5SDimitry Andric }
20124ba319b5SDimitry Andric 
20134ba319b5SDimitry Andric CodeGenFunction::VlaSizePair
getVLAElements1D(const VariableArrayType * Vla)20144ba319b5SDimitry Andric CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
20154ba319b5SDimitry Andric   llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
20164ba319b5SDimitry Andric   assert(VlaSize && "no size for VLA!");
20174ba319b5SDimitry Andric   assert(VlaSize->getType() == SizeTy);
20184ba319b5SDimitry Andric   return { VlaSize, Vla->getElementType() };
201917a519f9SDimitry Andric }
202017a519f9SDimitry Andric 
EmitVariablyModifiedType(QualType type)202117a519f9SDimitry Andric void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
202217a519f9SDimitry Andric   assert(type->isVariablyModifiedType() &&
2023f22ef01cSRoman Divacky          "Must pass variably modified type to EmitVLASizes!");
2024f22ef01cSRoman Divacky 
2025f22ef01cSRoman Divacky   EnsureInsertPoint();
2026f22ef01cSRoman Divacky 
202717a519f9SDimitry Andric   // We're going to walk down into the type and look for VLA
202817a519f9SDimitry Andric   // expressions.
202917a519f9SDimitry Andric   do {
203017a519f9SDimitry Andric     assert(type->isVariablyModifiedType());
2031f22ef01cSRoman Divacky 
203217a519f9SDimitry Andric     const Type *ty = type.getTypePtr();
203317a519f9SDimitry Andric     switch (ty->getTypeClass()) {
2034dff0c46cSDimitry Andric 
203517a519f9SDimitry Andric #define TYPE(Class, Base)
203617a519f9SDimitry Andric #define ABSTRACT_TYPE(Class, Base)
2037dff0c46cSDimitry Andric #define NON_CANONICAL_TYPE(Class, Base)
203817a519f9SDimitry Andric #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2039dff0c46cSDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
204017a519f9SDimitry Andric #include "clang/AST/TypeNodes.def"
2041dff0c46cSDimitry Andric       llvm_unreachable("unexpected dependent type!");
2042f22ef01cSRoman Divacky 
204317a519f9SDimitry Andric     // These types are never variably-modified.
204417a519f9SDimitry Andric     case Type::Builtin:
204517a519f9SDimitry Andric     case Type::Complex:
204617a519f9SDimitry Andric     case Type::Vector:
204717a519f9SDimitry Andric     case Type::ExtVector:
204817a519f9SDimitry Andric     case Type::Record:
204917a519f9SDimitry Andric     case Type::Enum:
2050dff0c46cSDimitry Andric     case Type::Elaborated:
2051dff0c46cSDimitry Andric     case Type::TemplateSpecialization:
205244290647SDimitry Andric     case Type::ObjCTypeParam:
205317a519f9SDimitry Andric     case Type::ObjCObject:
205417a519f9SDimitry Andric     case Type::ObjCInterface:
205517a519f9SDimitry Andric     case Type::ObjCObjectPointer:
205617a519f9SDimitry Andric       llvm_unreachable("type class is never variably-modified!");
2057f22ef01cSRoman Divacky 
205859d1ed5bSDimitry Andric     case Type::Adjusted:
205959d1ed5bSDimitry Andric       type = cast<AdjustedType>(ty)->getAdjustedType();
206059d1ed5bSDimitry Andric       break;
206159d1ed5bSDimitry Andric 
2062f785676fSDimitry Andric     case Type::Decayed:
2063f785676fSDimitry Andric       type = cast<DecayedType>(ty)->getPointeeType();
2064f785676fSDimitry Andric       break;
2065f785676fSDimitry Andric 
206617a519f9SDimitry Andric     case Type::Pointer:
206717a519f9SDimitry Andric       type = cast<PointerType>(ty)->getPointeeType();
206817a519f9SDimitry Andric       break;
2069f22ef01cSRoman Divacky 
207017a519f9SDimitry Andric     case Type::BlockPointer:
207117a519f9SDimitry Andric       type = cast<BlockPointerType>(ty)->getPointeeType();
207217a519f9SDimitry Andric       break;
207317a519f9SDimitry Andric 
207417a519f9SDimitry Andric     case Type::LValueReference:
207517a519f9SDimitry Andric     case Type::RValueReference:
207617a519f9SDimitry Andric       type = cast<ReferenceType>(ty)->getPointeeType();
207717a519f9SDimitry Andric       break;
207817a519f9SDimitry Andric 
207917a519f9SDimitry Andric     case Type::MemberPointer:
208017a519f9SDimitry Andric       type = cast<MemberPointerType>(ty)->getPointeeType();
208117a519f9SDimitry Andric       break;
208217a519f9SDimitry Andric 
208317a519f9SDimitry Andric     case Type::ConstantArray:
208417a519f9SDimitry Andric     case Type::IncompleteArray:
208517a519f9SDimitry Andric       // Losing element qualification here is fine.
208617a519f9SDimitry Andric       type = cast<ArrayType>(ty)->getElementType();
208717a519f9SDimitry Andric       break;
208817a519f9SDimitry Andric 
208917a519f9SDimitry Andric     case Type::VariableArray: {
209017a519f9SDimitry Andric       // Losing element qualification here is fine.
209117a519f9SDimitry Andric       const VariableArrayType *vat = cast<VariableArrayType>(ty);
209217a519f9SDimitry Andric 
209317a519f9SDimitry Andric       // Unknown size indication requires no size computation.
209417a519f9SDimitry Andric       // Otherwise, evaluate and record it.
209517a519f9SDimitry Andric       if (const Expr *size = vat->getSizeExpr()) {
209617a519f9SDimitry Andric         // It's possible that we might have emitted this already,
209717a519f9SDimitry Andric         // e.g. with a typedef and a pointer to it.
209817a519f9SDimitry Andric         llvm::Value *&entry = VLASizeMap[size];
209917a519f9SDimitry Andric         if (!entry) {
21003861d79fSDimitry Andric           llvm::Value *Size = EmitScalarExpr(size);
21013861d79fSDimitry Andric 
21023861d79fSDimitry Andric           // C11 6.7.6.2p5:
21033861d79fSDimitry Andric           //   If the size is an expression that is not an integer constant
21043861d79fSDimitry Andric           //   expression [...] each time it is evaluated it shall have a value
21053861d79fSDimitry Andric           //   greater than zero.
210639d628a0SDimitry Andric           if (SanOpts.has(SanitizerKind::VLABound) &&
21073861d79fSDimitry Andric               size->getType()->isSignedIntegerType()) {
210859d1ed5bSDimitry Andric             SanitizerScope SanScope(this);
21093861d79fSDimitry Andric             llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
21103861d79fSDimitry Andric             llvm::Constant *StaticArgs[] = {
2111*b5893f02SDimitry Andric                 EmitCheckSourceLocation(size->getBeginLoc()),
2112*b5893f02SDimitry Andric                 EmitCheckTypeDescriptor(size->getType())};
211339d628a0SDimitry Andric             EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
211439d628a0SDimitry Andric                                      SanitizerKind::VLABound),
211544290647SDimitry Andric                       SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
21163861d79fSDimitry Andric           }
21173861d79fSDimitry Andric 
211817a519f9SDimitry Andric           // Always zexting here would be wrong if it weren't
211917a519f9SDimitry Andric           // undefined behavior to have a negative bound.
21203861d79fSDimitry Andric           entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
212117a519f9SDimitry Andric         }
212217a519f9SDimitry Andric       }
212317a519f9SDimitry Andric       type = vat->getElementType();
212417a519f9SDimitry Andric       break;
2125f22ef01cSRoman Divacky     }
2126f22ef01cSRoman Divacky 
212717a519f9SDimitry Andric     case Type::FunctionProto:
212817a519f9SDimitry Andric     case Type::FunctionNoProto:
212959d1ed5bSDimitry Andric       type = cast<FunctionType>(ty)->getReturnType();
213017a519f9SDimitry Andric       break;
21316122f3e6SDimitry Andric 
2132dff0c46cSDimitry Andric     case Type::Paren:
2133dff0c46cSDimitry Andric     case Type::TypeOf:
2134dff0c46cSDimitry Andric     case Type::UnaryTransform:
2135dff0c46cSDimitry Andric     case Type::Attributed:
2136dff0c46cSDimitry Andric     case Type::SubstTemplateTypeParm:
2137f785676fSDimitry Andric     case Type::PackExpansion:
2138dff0c46cSDimitry Andric       // Keep walking after single level desugaring.
2139dff0c46cSDimitry Andric       type = type.getSingleStepDesugaredType(getContext());
2140dff0c46cSDimitry Andric       break;
2141dff0c46cSDimitry Andric 
2142dff0c46cSDimitry Andric     case Type::Typedef:
2143dff0c46cSDimitry Andric     case Type::Decltype:
2144dff0c46cSDimitry Andric     case Type::Auto:
214520e90f04SDimitry Andric     case Type::DeducedTemplateSpecialization:
2146dff0c46cSDimitry Andric       // Stop walking: nothing to do.
2147dff0c46cSDimitry Andric       return;
2148dff0c46cSDimitry Andric 
2149dff0c46cSDimitry Andric     case Type::TypeOfExpr:
2150dff0c46cSDimitry Andric       // Stop walking: emit typeof expression.
2151dff0c46cSDimitry Andric       EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
2152dff0c46cSDimitry Andric       return;
2153dff0c46cSDimitry Andric 
21546122f3e6SDimitry Andric     case Type::Atomic:
21556122f3e6SDimitry Andric       type = cast<AtomicType>(ty)->getValueType();
21566122f3e6SDimitry Andric       break;
2157444ed5c5SDimitry Andric 
2158444ed5c5SDimitry Andric     case Type::Pipe:
2159444ed5c5SDimitry Andric       type = cast<PipeType>(ty)->getElementType();
2160444ed5c5SDimitry Andric       break;
2161f22ef01cSRoman Divacky     }
216217a519f9SDimitry Andric   } while (type->isVariablyModifiedType());
2163f22ef01cSRoman Divacky }
2164f22ef01cSRoman Divacky 
EmitVAListRef(const Expr * E)21650623d748SDimitry Andric Address CodeGenFunction::EmitVAListRef(const Expr* E) {
21662754fe60SDimitry Andric   if (getContext().getBuiltinVaListType()->isArrayType())
21670623d748SDimitry Andric     return EmitPointerWithAlignment(E);
21680623d748SDimitry Andric   return EmitLValue(E).getAddress();
21690623d748SDimitry Andric }
21700623d748SDimitry Andric 
EmitMSVAListRef(const Expr * E)21710623d748SDimitry Andric Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
2172f22ef01cSRoman Divacky   return EmitLValue(E).getAddress();
2173f22ef01cSRoman Divacky }
2174f22ef01cSRoman Divacky 
EmitDeclRefExprDbgValue(const DeclRefExpr * E,const APValue & Init)2175e580952dSDimitry Andric void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
217644290647SDimitry Andric                                               const APValue &Init) {
217744290647SDimitry Andric   assert(!Init.isUninit() && "Invalid DeclRefExpr initializer!");
2178e580952dSDimitry Andric   if (CGDebugInfo *Dbg = getDebugInfo())
2179e7145dcbSDimitry Andric     if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
21802754fe60SDimitry Andric       Dbg->EmitGlobalVariable(E->getDecl(), Init);
21812754fe60SDimitry Andric }
21822754fe60SDimitry Andric 
21832754fe60SDimitry Andric CodeGenFunction::PeepholeProtection
protectFromPeepholes(RValue rvalue)21842754fe60SDimitry Andric CodeGenFunction::protectFromPeepholes(RValue rvalue) {
21852754fe60SDimitry Andric   // At the moment, the only aggressive peephole we do in IR gen
21862754fe60SDimitry Andric   // is trunc(zext) folding, but if we add more, we can easily
21872754fe60SDimitry Andric   // extend this protection.
21882754fe60SDimitry Andric 
21892754fe60SDimitry Andric   if (!rvalue.isScalar()) return PeepholeProtection();
21902754fe60SDimitry Andric   llvm::Value *value = rvalue.getScalarVal();
21912754fe60SDimitry Andric   if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
21922754fe60SDimitry Andric 
21932754fe60SDimitry Andric   // Just make an extra bitcast.
21942754fe60SDimitry Andric   assert(HaveInsertPoint());
21952754fe60SDimitry Andric   llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
21962754fe60SDimitry Andric                                                   Builder.GetInsertBlock());
21972754fe60SDimitry Andric 
21982754fe60SDimitry Andric   PeepholeProtection protection;
21992754fe60SDimitry Andric   protection.Inst = inst;
22002754fe60SDimitry Andric   return protection;
22012754fe60SDimitry Andric }
22022754fe60SDimitry Andric 
unprotectFromPeepholes(PeepholeProtection protection)22032754fe60SDimitry Andric void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
22042754fe60SDimitry Andric   if (!protection.Inst) return;
22052754fe60SDimitry Andric 
22062754fe60SDimitry Andric   // In theory, we could try to duplicate the peepholes now, but whatever.
22072754fe60SDimitry Andric   protection.Inst->eraseFromParent();
2208e580952dSDimitry Andric }
22096122f3e6SDimitry Andric 
EmitAlignmentAssumption(llvm::Value * PtrValue,QualType Ty,SourceLocation Loc,SourceLocation AssumptionLoc,llvm::Value * Alignment,llvm::Value * OffsetValue)2210*b5893f02SDimitry Andric void CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue,
2211*b5893f02SDimitry Andric                                               QualType Ty, SourceLocation Loc,
2212*b5893f02SDimitry Andric                                               SourceLocation AssumptionLoc,
2213*b5893f02SDimitry Andric                                               llvm::Value *Alignment,
2214*b5893f02SDimitry Andric                                               llvm::Value *OffsetValue) {
2215*b5893f02SDimitry Andric   llvm::Value *TheCheck;
2216*b5893f02SDimitry Andric   llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
2217*b5893f02SDimitry Andric       CGM.getDataLayout(), PtrValue, Alignment, OffsetValue, &TheCheck);
2218*b5893f02SDimitry Andric   if (SanOpts.has(SanitizerKind::Alignment)) {
2219*b5893f02SDimitry Andric     EmitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2220*b5893f02SDimitry Andric                                  OffsetValue, TheCheck, Assumption);
2221*b5893f02SDimitry Andric   }
2222*b5893f02SDimitry Andric }
2223*b5893f02SDimitry Andric 
EmitAlignmentAssumption(llvm::Value * PtrValue,QualType Ty,SourceLocation Loc,SourceLocation AssumptionLoc,unsigned Alignment,llvm::Value * OffsetValue)2224*b5893f02SDimitry Andric void CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue,
2225*b5893f02SDimitry Andric                                               QualType Ty, SourceLocation Loc,
2226*b5893f02SDimitry Andric                                               SourceLocation AssumptionLoc,
2227*b5893f02SDimitry Andric                                               unsigned Alignment,
2228*b5893f02SDimitry Andric                                               llvm::Value *OffsetValue) {
2229*b5893f02SDimitry Andric   llvm::Value *TheCheck;
2230*b5893f02SDimitry Andric   llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
2231*b5893f02SDimitry Andric       CGM.getDataLayout(), PtrValue, Alignment, OffsetValue, &TheCheck);
2232*b5893f02SDimitry Andric   if (SanOpts.has(SanitizerKind::Alignment)) {
2233*b5893f02SDimitry Andric     llvm::Value *AlignmentVal = llvm::ConstantInt::get(IntPtrTy, Alignment);
2234*b5893f02SDimitry Andric     EmitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, AlignmentVal,
2235*b5893f02SDimitry Andric                                  OffsetValue, TheCheck, Assumption);
2236*b5893f02SDimitry Andric   }
2237*b5893f02SDimitry Andric }
2238*b5893f02SDimitry Andric 
EmitAlignmentAssumption(llvm::Value * PtrValue,const Expr * E,SourceLocation AssumptionLoc,unsigned Alignment,llvm::Value * OffsetValue)2239*b5893f02SDimitry Andric void CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue,
2240*b5893f02SDimitry Andric                                               const Expr *E,
2241*b5893f02SDimitry Andric                                               SourceLocation AssumptionLoc,
2242*b5893f02SDimitry Andric                                               unsigned Alignment,
2243*b5893f02SDimitry Andric                                               llvm::Value *OffsetValue) {
2244*b5893f02SDimitry Andric   if (auto *CE = dyn_cast<CastExpr>(E))
2245*b5893f02SDimitry Andric     E = CE->getSubExprAsWritten();
2246*b5893f02SDimitry Andric   QualType Ty = E->getType();
2247*b5893f02SDimitry Andric   SourceLocation Loc = E->getExprLoc();
2248*b5893f02SDimitry Andric 
2249*b5893f02SDimitry Andric   EmitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2250*b5893f02SDimitry Andric                           OffsetValue);
2251*b5893f02SDimitry Andric }
2252*b5893f02SDimitry Andric 
EmitAnnotationCall(llvm::Value * AnnotationFn,llvm::Value * AnnotatedVal,StringRef AnnotationStr,SourceLocation Location)22536122f3e6SDimitry Andric llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
22546122f3e6SDimitry Andric                                                  llvm::Value *AnnotatedVal,
2255139f7f9bSDimitry Andric                                                  StringRef AnnotationStr,
22566122f3e6SDimitry Andric                                                  SourceLocation Location) {
22576122f3e6SDimitry Andric   llvm::Value *Args[4] = {
22586122f3e6SDimitry Andric     AnnotatedVal,
22596122f3e6SDimitry Andric     Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
22606122f3e6SDimitry Andric     Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
22616122f3e6SDimitry Andric     CGM.EmitAnnotationLineNo(Location)
22626122f3e6SDimitry Andric   };
22636122f3e6SDimitry Andric   return Builder.CreateCall(AnnotationFn, Args);
22646122f3e6SDimitry Andric }
22656122f3e6SDimitry Andric 
EmitVarAnnotations(const VarDecl * D,llvm::Value * V)22666122f3e6SDimitry Andric void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
22676122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
22686122f3e6SDimitry Andric   // FIXME We create a new bitcast for every annotation because that's what
22696122f3e6SDimitry Andric   // llvm-gcc was doing.
227059d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
22716122f3e6SDimitry Andric     EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
22726122f3e6SDimitry Andric                        Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
227359d1ed5bSDimitry Andric                        I->getAnnotation(), D->getLocation());
22746122f3e6SDimitry Andric }
22756122f3e6SDimitry Andric 
EmitFieldAnnotations(const FieldDecl * D,Address Addr)22760623d748SDimitry Andric Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
22770623d748SDimitry Andric                                               Address Addr) {
22786122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
22790623d748SDimitry Andric   llvm::Value *V = Addr.getPointer();
22806122f3e6SDimitry Andric   llvm::Type *VTy = V->getType();
22816122f3e6SDimitry Andric   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
22826122f3e6SDimitry Andric                                     CGM.Int8PtrTy);
22836122f3e6SDimitry Andric 
228459d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
22856122f3e6SDimitry Andric     // FIXME Always emit the cast inst so we can differentiate between
22866122f3e6SDimitry Andric     // annotation on the first field of a struct and annotation on the struct
22876122f3e6SDimitry Andric     // itself.
22886122f3e6SDimitry Andric     if (VTy != CGM.Int8PtrTy)
2289*b5893f02SDimitry Andric       V = Builder.CreateBitCast(V, CGM.Int8PtrTy);
229059d1ed5bSDimitry Andric     V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
22916122f3e6SDimitry Andric     V = Builder.CreateBitCast(V, VTy);
22926122f3e6SDimitry Andric   }
22936122f3e6SDimitry Andric 
22940623d748SDimitry Andric   return Address(V, Addr.getAlignment());
22956122f3e6SDimitry Andric }
2296f785676fSDimitry Andric 
~CGCapturedStmtInfo()2297f785676fSDimitry Andric CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
229859d1ed5bSDimitry Andric 
SanitizerScope(CodeGenFunction * CGF)229959d1ed5bSDimitry Andric CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
230059d1ed5bSDimitry Andric     : CGF(CGF) {
230159d1ed5bSDimitry Andric   assert(!CGF->IsSanitizerScope);
230259d1ed5bSDimitry Andric   CGF->IsSanitizerScope = true;
230359d1ed5bSDimitry Andric }
230459d1ed5bSDimitry Andric 
~SanitizerScope()230559d1ed5bSDimitry Andric CodeGenFunction::SanitizerScope::~SanitizerScope() {
230659d1ed5bSDimitry Andric   CGF->IsSanitizerScope = false;
230759d1ed5bSDimitry Andric }
230859d1ed5bSDimitry Andric 
InsertHelper(llvm::Instruction * I,const llvm::Twine & Name,llvm::BasicBlock * BB,llvm::BasicBlock::iterator InsertPt) const230959d1ed5bSDimitry Andric void CodeGenFunction::InsertHelper(llvm::Instruction *I,
231059d1ed5bSDimitry Andric                                    const llvm::Twine &Name,
231159d1ed5bSDimitry Andric                                    llvm::BasicBlock *BB,
231259d1ed5bSDimitry Andric                                    llvm::BasicBlock::iterator InsertPt) const {
231359d1ed5bSDimitry Andric   LoopStack.InsertHelper(I);
231439d628a0SDimitry Andric   if (IsSanitizerScope)
231539d628a0SDimitry Andric     CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
231659d1ed5bSDimitry Andric }
231759d1ed5bSDimitry Andric 
InsertHelper(llvm::Instruction * I,const llvm::Twine & Name,llvm::BasicBlock * BB,llvm::BasicBlock::iterator InsertPt) const2318e7145dcbSDimitry Andric void CGBuilderInserter::InsertHelper(
231959d1ed5bSDimitry Andric     llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
232059d1ed5bSDimitry Andric     llvm::BasicBlock::iterator InsertPt) const {
2321e7145dcbSDimitry Andric   llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
232259d1ed5bSDimitry Andric   if (CGF)
232359d1ed5bSDimitry Andric     CGF->InsertHelper(I, Name, BB, InsertPt);
232459d1ed5bSDimitry Andric }
232559d1ed5bSDimitry Andric 
hasRequiredFeatures(const SmallVectorImpl<StringRef> & ReqFeatures,CodeGenModule & CGM,const FunctionDecl * FD,std::string & FirstMissing)23260623d748SDimitry Andric static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
23270623d748SDimitry Andric                                 CodeGenModule &CGM, const FunctionDecl *FD,
23280623d748SDimitry Andric                                 std::string &FirstMissing) {
23290623d748SDimitry Andric   // If there aren't any required features listed then go ahead and return.
23300623d748SDimitry Andric   if (ReqFeatures.empty())
23310623d748SDimitry Andric     return false;
23320623d748SDimitry Andric 
23330623d748SDimitry Andric   // Now build up the set of caller features and verify that all the required
23340623d748SDimitry Andric   // features are there.
23350623d748SDimitry Andric   llvm::StringMap<bool> CallerFeatureMap;
2336*b5893f02SDimitry Andric   CGM.getFunctionFeatureMap(CallerFeatureMap, GlobalDecl().getWithDecl(FD));
23370623d748SDimitry Andric 
23380623d748SDimitry Andric   // If we have at least one of the features in the feature list return
23390623d748SDimitry Andric   // true, otherwise return false.
23400623d748SDimitry Andric   return std::all_of(
23410623d748SDimitry Andric       ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
23420623d748SDimitry Andric         SmallVector<StringRef, 1> OrFeatures;
23434ba319b5SDimitry Andric         Feature.split(OrFeatures, '|');
2344*b5893f02SDimitry Andric         return llvm::any_of(OrFeatures, [&](StringRef Feature) {
23450623d748SDimitry Andric           if (!CallerFeatureMap.lookup(Feature)) {
23460623d748SDimitry Andric             FirstMissing = Feature.str();
23470623d748SDimitry Andric             return false;
23480623d748SDimitry Andric           }
23490623d748SDimitry Andric           return true;
23500623d748SDimitry Andric         });
23510623d748SDimitry Andric       });
23520623d748SDimitry Andric }
23530623d748SDimitry Andric 
23540623d748SDimitry Andric // Emits an error if we don't have a valid set of target features for the
23550623d748SDimitry Andric // called function.
checkTargetFeatures(const CallExpr * E,const FunctionDecl * TargetDecl)23560623d748SDimitry Andric void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
23570623d748SDimitry Andric                                           const FunctionDecl *TargetDecl) {
23580623d748SDimitry Andric   // Early exit if this is an indirect call.
23590623d748SDimitry Andric   if (!TargetDecl)
23600623d748SDimitry Andric     return;
23610623d748SDimitry Andric 
23620623d748SDimitry Andric   // Get the current enclosing function if it exists. If it doesn't
23630623d748SDimitry Andric   // we can't check the target features anyhow.
23640623d748SDimitry Andric   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl);
23650623d748SDimitry Andric   if (!FD)
23660623d748SDimitry Andric     return;
23670623d748SDimitry Andric 
23680623d748SDimitry Andric   // Grab the required features for the call. For a builtin this is listed in
23690623d748SDimitry Andric   // the td file with the default cpu, for an always_inline function this is any
23700623d748SDimitry Andric   // listed cpu and any listed features.
23710623d748SDimitry Andric   unsigned BuiltinID = TargetDecl->getBuiltinID();
23720623d748SDimitry Andric   std::string MissingFeature;
23730623d748SDimitry Andric   if (BuiltinID) {
23740623d748SDimitry Andric     SmallVector<StringRef, 1> ReqFeatures;
23750623d748SDimitry Andric     const char *FeatureList =
23760623d748SDimitry Andric         CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
23770623d748SDimitry Andric     // Return if the builtin doesn't have any required features.
23780623d748SDimitry Andric     if (!FeatureList || StringRef(FeatureList) == "")
23790623d748SDimitry Andric       return;
23804ba319b5SDimitry Andric     StringRef(FeatureList).split(ReqFeatures, ',');
23810623d748SDimitry Andric     if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
2382*b5893f02SDimitry Andric       CGM.getDiags().Report(E->getBeginLoc(), diag::err_builtin_needs_feature)
23830623d748SDimitry Andric           << TargetDecl->getDeclName()
23840623d748SDimitry Andric           << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
23850623d748SDimitry Andric 
23864ba319b5SDimitry Andric   } else if (TargetDecl->hasAttr<TargetAttr>() ||
23874ba319b5SDimitry Andric              TargetDecl->hasAttr<CPUSpecificAttr>()) {
23880623d748SDimitry Andric     // Get the required features for the callee.
23894ba319b5SDimitry Andric 
23904ba319b5SDimitry Andric     const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
23914ba319b5SDimitry Andric     TargetAttr::ParsedTargetAttr ParsedAttr = CGM.filterFunctionTargetAttrs(TD);
23924ba319b5SDimitry Andric 
23930623d748SDimitry Andric     SmallVector<StringRef, 1> ReqFeatures;
23940623d748SDimitry Andric     llvm::StringMap<bool> CalleeFeatureMap;
23950623d748SDimitry Andric     CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
23964ba319b5SDimitry Andric 
23974ba319b5SDimitry Andric     for (const auto &F : ParsedAttr.Features) {
23984ba319b5SDimitry Andric       if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
23994ba319b5SDimitry Andric         ReqFeatures.push_back(StringRef(F).substr(1));
24004ba319b5SDimitry Andric     }
24014ba319b5SDimitry Andric 
24020623d748SDimitry Andric     for (const auto &F : CalleeFeatureMap) {
24030623d748SDimitry Andric       // Only positive features are "required".
24040623d748SDimitry Andric       if (F.getValue())
24050623d748SDimitry Andric         ReqFeatures.push_back(F.getKey());
24060623d748SDimitry Andric     }
24070623d748SDimitry Andric     if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
2408*b5893f02SDimitry Andric       CGM.getDiags().Report(E->getBeginLoc(), diag::err_function_needs_feature)
24090623d748SDimitry Andric           << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
24100623d748SDimitry Andric   }
24110623d748SDimitry Andric }
2412e7145dcbSDimitry Andric 
EmitSanitizerStatReport(llvm::SanitizerStatKind SSK)2413e7145dcbSDimitry Andric void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2414e7145dcbSDimitry Andric   if (!CGM.getCodeGenOpts().SanitizeStats)
2415e7145dcbSDimitry Andric     return;
2416e7145dcbSDimitry Andric 
2417e7145dcbSDimitry Andric   llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2418e7145dcbSDimitry Andric   IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2419e7145dcbSDimitry Andric   CGM.getSanStats().create(IRB, SSK);
2420e7145dcbSDimitry Andric }
242144290647SDimitry Andric 
24224ba319b5SDimitry Andric llvm::Value *
FormResolverCondition(const MultiVersionResolverOption & RO)24234ba319b5SDimitry Andric CodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) {
24244ba319b5SDimitry Andric   llvm::Value *Condition = nullptr;
24254ba319b5SDimitry Andric 
24264ba319b5SDimitry Andric   if (!RO.Conditions.Architecture.empty())
24274ba319b5SDimitry Andric     Condition = EmitX86CpuIs(RO.Conditions.Architecture);
24284ba319b5SDimitry Andric 
24294ba319b5SDimitry Andric   if (!RO.Conditions.Features.empty()) {
24304ba319b5SDimitry Andric     llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features);
24314ba319b5SDimitry Andric     Condition =
24324ba319b5SDimitry Andric         Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
24334ba319b5SDimitry Andric   }
24344ba319b5SDimitry Andric   return Condition;
24354ba319b5SDimitry Andric }
24364ba319b5SDimitry Andric 
CreateMultiVersionResolverReturn(CodeGenModule & CGM,llvm::Function * Resolver,CGBuilderTy & Builder,llvm::Function * FuncToReturn,bool SupportsIFunc)2437*b5893f02SDimitry Andric static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
2438*b5893f02SDimitry Andric                                              llvm::Function *Resolver,
2439*b5893f02SDimitry Andric                                              CGBuilderTy &Builder,
2440*b5893f02SDimitry Andric                                              llvm::Function *FuncToReturn,
2441*b5893f02SDimitry Andric                                              bool SupportsIFunc) {
2442*b5893f02SDimitry Andric   if (SupportsIFunc) {
2443*b5893f02SDimitry Andric     Builder.CreateRet(FuncToReturn);
2444*b5893f02SDimitry Andric     return;
2445*b5893f02SDimitry Andric   }
2446*b5893f02SDimitry Andric 
2447*b5893f02SDimitry Andric   llvm::SmallVector<llvm::Value *, 10> Args;
2448*b5893f02SDimitry Andric   llvm::for_each(Resolver->args(),
2449*b5893f02SDimitry Andric                  [&](llvm::Argument &Arg) { Args.push_back(&Arg); });
2450*b5893f02SDimitry Andric 
2451*b5893f02SDimitry Andric   llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
2452*b5893f02SDimitry Andric   Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2453*b5893f02SDimitry Andric 
2454*b5893f02SDimitry Andric   if (Resolver->getReturnType()->isVoidTy())
2455*b5893f02SDimitry Andric     Builder.CreateRetVoid();
2456*b5893f02SDimitry Andric   else
2457*b5893f02SDimitry Andric     Builder.CreateRet(Result);
2458*b5893f02SDimitry Andric }
2459*b5893f02SDimitry Andric 
EmitMultiVersionResolver(llvm::Function * Resolver,ArrayRef<MultiVersionResolverOption> Options)24604ba319b5SDimitry Andric void CodeGenFunction::EmitMultiVersionResolver(
24614ba319b5SDimitry Andric     llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
24624ba319b5SDimitry Andric   assert((getContext().getTargetInfo().getTriple().getArch() ==
24634ba319b5SDimitry Andric               llvm::Triple::x86 ||
24644ba319b5SDimitry Andric           getContext().getTargetInfo().getTriple().getArch() ==
24654ba319b5SDimitry Andric               llvm::Triple::x86_64) &&
24664ba319b5SDimitry Andric          "Only implemented for x86 targets");
2467*b5893f02SDimitry Andric 
2468*b5893f02SDimitry Andric   bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
2469*b5893f02SDimitry Andric 
24704ba319b5SDimitry Andric   // Main function's basic block.
24714ba319b5SDimitry Andric   llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
24724ba319b5SDimitry Andric   Builder.SetInsertPoint(CurBlock);
24734ba319b5SDimitry Andric   EmitX86CpuInit();
24744ba319b5SDimitry Andric 
24754ba319b5SDimitry Andric   for (const MultiVersionResolverOption &RO : Options) {
24764ba319b5SDimitry Andric     Builder.SetInsertPoint(CurBlock);
24774ba319b5SDimitry Andric     llvm::Value *Condition = FormResolverCondition(RO);
24784ba319b5SDimitry Andric 
24794ba319b5SDimitry Andric     // The 'default' or 'generic' case.
24804ba319b5SDimitry Andric     if (!Condition) {
24814ba319b5SDimitry Andric       assert(&RO == Options.end() - 1 &&
24824ba319b5SDimitry Andric              "Default or Generic case must be last");
2483*b5893f02SDimitry Andric       CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
2484*b5893f02SDimitry Andric                                        SupportsIFunc);
24854ba319b5SDimitry Andric       return;
24864ba319b5SDimitry Andric     }
24874ba319b5SDimitry Andric 
24884ba319b5SDimitry Andric     llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
2489*b5893f02SDimitry Andric     CGBuilderTy RetBuilder(*this, RetBlock);
2490*b5893f02SDimitry Andric     CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
2491*b5893f02SDimitry Andric                                      SupportsIFunc);
24924ba319b5SDimitry Andric     CurBlock = createBasicBlock("resolver_else", Resolver);
24934ba319b5SDimitry Andric     Builder.CreateCondBr(Condition, RetBlock, CurBlock);
24944ba319b5SDimitry Andric   }
24954ba319b5SDimitry Andric 
24964ba319b5SDimitry Andric   // If no generic/default, emit an unreachable.
24974ba319b5SDimitry Andric   Builder.SetInsertPoint(CurBlock);
24984ba319b5SDimitry Andric   llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
24994ba319b5SDimitry Andric   TrapCall->setDoesNotReturn();
25004ba319b5SDimitry Andric   TrapCall->setDoesNotThrow();
25014ba319b5SDimitry Andric   Builder.CreateUnreachable();
25024ba319b5SDimitry Andric   Builder.ClearInsertionPoint();
25034ba319b5SDimitry Andric }
25044ba319b5SDimitry Andric 
2505*b5893f02SDimitry Andric // Loc - where the diagnostic will point, where in the source code this
2506*b5893f02SDimitry Andric //  alignment has failed.
2507*b5893f02SDimitry Andric // SecondaryLoc - if present (will be present if sufficiently different from
2508*b5893f02SDimitry Andric //  Loc), the diagnostic will additionally point a "Note:" to this location.
2509*b5893f02SDimitry Andric //  It should be the location where the __attribute__((assume_aligned))
2510*b5893f02SDimitry Andric //  was written e.g.
EmitAlignmentAssumptionCheck(llvm::Value * Ptr,QualType Ty,SourceLocation Loc,SourceLocation SecondaryLoc,llvm::Value * Alignment,llvm::Value * OffsetValue,llvm::Value * TheCheck,llvm::Instruction * Assumption)2511*b5893f02SDimitry Andric void CodeGenFunction::EmitAlignmentAssumptionCheck(
2512*b5893f02SDimitry Andric     llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
2513*b5893f02SDimitry Andric     SourceLocation SecondaryLoc, llvm::Value *Alignment,
2514*b5893f02SDimitry Andric     llvm::Value *OffsetValue, llvm::Value *TheCheck,
2515*b5893f02SDimitry Andric     llvm::Instruction *Assumption) {
2516*b5893f02SDimitry Andric   assert(Assumption && isa<llvm::CallInst>(Assumption) &&
2517*b5893f02SDimitry Andric          cast<llvm::CallInst>(Assumption)->getCalledValue() ==
2518*b5893f02SDimitry Andric              llvm::Intrinsic::getDeclaration(
2519*b5893f02SDimitry Andric                  Builder.GetInsertBlock()->getParent()->getParent(),
2520*b5893f02SDimitry Andric                  llvm::Intrinsic::assume) &&
2521*b5893f02SDimitry Andric          "Assumption should be a call to llvm.assume().");
2522*b5893f02SDimitry Andric   assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
2523*b5893f02SDimitry Andric          "Assumption should be the last instruction of the basic block, "
2524*b5893f02SDimitry Andric          "since the basic block is still being generated.");
2525*b5893f02SDimitry Andric 
2526*b5893f02SDimitry Andric   if (!SanOpts.has(SanitizerKind::Alignment))
2527*b5893f02SDimitry Andric     return;
2528*b5893f02SDimitry Andric 
2529*b5893f02SDimitry Andric   // Don't check pointers to volatile data. The behavior here is implementation-
2530*b5893f02SDimitry Andric   // defined.
2531*b5893f02SDimitry Andric   if (Ty->getPointeeType().isVolatileQualified())
2532*b5893f02SDimitry Andric     return;
2533*b5893f02SDimitry Andric 
2534*b5893f02SDimitry Andric   // We need to temorairly remove the assumption so we can insert the
2535*b5893f02SDimitry Andric   // sanitizer check before it, else the check will be dropped by optimizations.
2536*b5893f02SDimitry Andric   Assumption->removeFromParent();
2537*b5893f02SDimitry Andric 
2538*b5893f02SDimitry Andric   {
2539*b5893f02SDimitry Andric     SanitizerScope SanScope(this);
2540*b5893f02SDimitry Andric 
2541*b5893f02SDimitry Andric     if (!OffsetValue)
2542*b5893f02SDimitry Andric       OffsetValue = Builder.getInt1(0); // no offset.
2543*b5893f02SDimitry Andric 
2544*b5893f02SDimitry Andric     llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
2545*b5893f02SDimitry Andric                                     EmitCheckSourceLocation(SecondaryLoc),
2546*b5893f02SDimitry Andric                                     EmitCheckTypeDescriptor(Ty)};
2547*b5893f02SDimitry Andric     llvm::Value *DynamicData[] = {EmitCheckValue(Ptr),
2548*b5893f02SDimitry Andric                                   EmitCheckValue(Alignment),
2549*b5893f02SDimitry Andric                                   EmitCheckValue(OffsetValue)};
2550*b5893f02SDimitry Andric     EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
2551*b5893f02SDimitry Andric               SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
2552*b5893f02SDimitry Andric   }
2553*b5893f02SDimitry Andric 
2554*b5893f02SDimitry Andric   // We are now in the (new, empty) "cont" basic block.
2555*b5893f02SDimitry Andric   // Reintroduce the assumption.
2556*b5893f02SDimitry Andric   Builder.Insert(Assumption);
2557*b5893f02SDimitry Andric   // FIXME: Assumption still has it's original basic block as it's Parent.
2558*b5893f02SDimitry Andric }
2559*b5893f02SDimitry Andric 
SourceLocToDebugLoc(SourceLocation Location)256044290647SDimitry Andric llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
256144290647SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
256244290647SDimitry Andric     return DI->SourceLocToDebugLoc(Location);
256344290647SDimitry Andric 
256444290647SDimitry Andric   return llvm::DebugLoc();
256544290647SDimitry Andric }
2566