1f22ef01cSRoman Divacky //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===// 2f22ef01cSRoman Divacky // 3f22ef01cSRoman Divacky // The LLVM Compiler Infrastructure 4f22ef01cSRoman Divacky // 5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source 6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details. 7f22ef01cSRoman Divacky // 8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 9f22ef01cSRoman Divacky // 10f22ef01cSRoman Divacky // This coordinates the per-function state used while generating code. 11f22ef01cSRoman Divacky // 12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 13f22ef01cSRoman Divacky 14f22ef01cSRoman Divacky #include "CodeGenFunction.h" 150623d748SDimitry Andric #include "CGBlocks.h" 1633956c43SDimitry Andric #include "CGCleanup.h" 176122f3e6SDimitry Andric #include "CGCUDARuntime.h" 18e580952dSDimitry Andric #include "CGCXXABI.h" 19f22ef01cSRoman Divacky #include "CGDebugInfo.h" 2059d1ed5bSDimitry Andric #include "CGOpenMPRuntime.h" 21139f7f9bSDimitry Andric #include "CodeGenModule.h" 2259d1ed5bSDimitry Andric #include "CodeGenPGO.h" 23f785676fSDimitry Andric #include "TargetInfo.h" 24f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h" 25f22ef01cSRoman Divacky #include "clang/AST/Decl.h" 26f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h" 27f22ef01cSRoman Divacky #include "clang/AST/StmtCXX.h" 28f41fbc90SDimitry Andric #include "clang/AST/StmtObjC.h" 290623d748SDimitry Andric #include "clang/Basic/Builtins.h" 30139f7f9bSDimitry Andric #include "clang/Basic/TargetInfo.h" 31f785676fSDimitry Andric #include "clang/CodeGen/CGFunctionInfo.h" 32ffd1746dSEd Schouten #include "clang/Frontend/CodeGenOptions.h" 330623d748SDimitry Andric #include "clang/Sema/SemaDiagnostic.h" 34139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h" 35139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h" 36139f7f9bSDimitry Andric #include "llvm/IR/MDBuilder.h" 37139f7f9bSDimitry Andric #include "llvm/IR/Operator.h" 38f22ef01cSRoman Divacky using namespace clang; 39f22ef01cSRoman Divacky using namespace CodeGen; 40f22ef01cSRoman Divacky 4144290647SDimitry Andric /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time 4244290647SDimitry Andric /// markers. 4344290647SDimitry Andric static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts, 4444290647SDimitry Andric const LangOptions &LangOpts) { 4524e2fe98SDimitry Andric if (CGOpts.DisableLifetimeMarkers) 4624e2fe98SDimitry Andric return false; 4724e2fe98SDimitry Andric 4844290647SDimitry Andric // Disable lifetime markers in msan builds. 4944290647SDimitry Andric // FIXME: Remove this when msan works with lifetime markers. 5044290647SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Memory)) 5144290647SDimitry Andric return false; 5244290647SDimitry Andric 5320e90f04SDimitry Andric // Asan uses markers for use-after-scope checks. 5420e90f04SDimitry Andric if (CGOpts.SanitizeAddressUseAfterScope) 5520e90f04SDimitry Andric return true; 5620e90f04SDimitry Andric 5744290647SDimitry Andric // For now, only in optimized builds. 5844290647SDimitry Andric return CGOpts.OptimizationLevel != 0; 5944290647SDimitry Andric } 6044290647SDimitry Andric 617ae0e2c9SDimitry Andric CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext) 62284c1978SDimitry Andric : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()), 630623d748SDimitry Andric Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(), 6459d1ed5bSDimitry Andric CGBuilderInserterTy(this)), 650623d748SDimitry Andric CurFn(nullptr), ReturnValue(Address::invalid()), 6644290647SDimitry Andric CapturedStmtInfo(nullptr), SanOpts(CGM.getLangOpts().Sanitize), 6744290647SDimitry Andric IsSanitizerScope(false), CurFuncIsThunk(false), AutoreleaseResult(false), 6844290647SDimitry Andric SawAsmBlock(false), IsOutlinedSEHHelper(false), BlockInfo(nullptr), 6944290647SDimitry Andric BlockPointer(nullptr), LambdaThisCaptureField(nullptr), 7044290647SDimitry Andric NormalCleanupDest(nullptr), NextCleanupDestIndex(1), 7144290647SDimitry Andric FirstBlockInfo(nullptr), EHResumeBlock(nullptr), ExceptionSlot(nullptr), 7244290647SDimitry Andric EHSelectorSlot(nullptr), DebugInfo(CGM.getModuleDebugInfo()), 73875ed548SDimitry Andric DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(nullptr), 74875ed548SDimitry Andric PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr), 75875ed548SDimitry Andric CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0), 76875ed548SDimitry Andric NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr), 77875ed548SDimitry Andric CXXABIThisValue(nullptr), CXXThisValue(nullptr), 780623d748SDimitry Andric CXXStructorImplicitParamDecl(nullptr), 7959d1ed5bSDimitry Andric CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr), 8059d1ed5bSDimitry Andric CurLexicalScope(nullptr), TerminateLandingPad(nullptr), 8144290647SDimitry Andric TerminateHandler(nullptr), TrapBB(nullptr), 8244290647SDimitry Andric ShouldEmitLifetimeMarkers( 8344290647SDimitry Andric shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) { 847ae0e2c9SDimitry Andric if (!suppressNewContext) 85e580952dSDimitry Andric CGM.getCXXABI().getMangleContext().startNewFunction(); 86139f7f9bSDimitry Andric 87139f7f9bSDimitry Andric llvm::FastMathFlags FMF; 88139f7f9bSDimitry Andric if (CGM.getLangOpts().FastMath) 89139f7f9bSDimitry Andric FMF.setUnsafeAlgebra(); 90139f7f9bSDimitry Andric if (CGM.getLangOpts().FiniteMathOnly) { 91139f7f9bSDimitry Andric FMF.setNoNaNs(); 92139f7f9bSDimitry Andric FMF.setNoInfs(); 93139f7f9bSDimitry Andric } 9439d628a0SDimitry Andric if (CGM.getCodeGenOpts().NoNaNsFPMath) { 9539d628a0SDimitry Andric FMF.setNoNaNs(); 9639d628a0SDimitry Andric } 9739d628a0SDimitry Andric if (CGM.getCodeGenOpts().NoSignedZeros) { 9839d628a0SDimitry Andric FMF.setNoSignedZeros(); 9939d628a0SDimitry Andric } 10033956c43SDimitry Andric if (CGM.getCodeGenOpts().ReciprocalMath) { 10133956c43SDimitry Andric FMF.setAllowReciprocal(); 10233956c43SDimitry Andric } 103444ed5c5SDimitry Andric Builder.setFastMathFlags(FMF); 104f22ef01cSRoman Divacky } 105f22ef01cSRoman Divacky 106dff0c46cSDimitry Andric CodeGenFunction::~CodeGenFunction() { 107f785676fSDimitry Andric assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup"); 108f785676fSDimitry Andric 109dff0c46cSDimitry Andric // If there are any unclaimed block infos, go ahead and destroy them 110dff0c46cSDimitry Andric // now. This can happen if IR-gen gets clever and skips evaluating 111dff0c46cSDimitry Andric // something. 112dff0c46cSDimitry Andric if (FirstBlockInfo) 113dff0c46cSDimitry Andric destroyBlockInfos(FirstBlockInfo); 11459d1ed5bSDimitry Andric 11598221d2eSDimitry Andric if (getLangOpts().OpenMP && CurFn) 11633956c43SDimitry Andric CGM.getOpenMPRuntime().functionFinished(*this); 11759d1ed5bSDimitry Andric } 118dff0c46cSDimitry Andric 1190623d748SDimitry Andric CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T, 120d8866befSDimitry Andric LValueBaseInfo *BaseInfo) { 121d8866befSDimitry Andric return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, 1220623d748SDimitry Andric /*forPointee*/ true); 1230623d748SDimitry Andric } 1240623d748SDimitry Andric 1250623d748SDimitry Andric CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T, 126d8866befSDimitry Andric LValueBaseInfo *BaseInfo, 1270623d748SDimitry Andric bool forPointeeType) { 1280623d748SDimitry Andric // Honor alignment typedef attributes even on incomplete types. 1290623d748SDimitry Andric // We also honor them straight for C++ class types, even as pointees; 1300623d748SDimitry Andric // there's an expressivity gap here. 1310623d748SDimitry Andric if (auto TT = T->getAs<TypedefType>()) { 1320623d748SDimitry Andric if (auto Align = TT->getDecl()->getMaxAlignment()) { 133d8866befSDimitry Andric if (BaseInfo) 134d8866befSDimitry Andric *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType, false); 1350623d748SDimitry Andric return getContext().toCharUnitsFromBits(Align); 1360623d748SDimitry Andric } 1370623d748SDimitry Andric } 1380623d748SDimitry Andric 139d8866befSDimitry Andric if (BaseInfo) 140d8866befSDimitry Andric *BaseInfo = LValueBaseInfo(AlignmentSource::Type, false); 1410623d748SDimitry Andric 14239d628a0SDimitry Andric CharUnits Alignment; 1430623d748SDimitry Andric if (T->isIncompleteType()) { 1440623d748SDimitry Andric Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best. 1450623d748SDimitry Andric } else { 1460623d748SDimitry Andric // For C++ class pointees, we don't know whether we're pointing at a 1470623d748SDimitry Andric // base or a complete object, so we generally need to use the 1480623d748SDimitry Andric // non-virtual alignment. 1490623d748SDimitry Andric const CXXRecordDecl *RD; 1500623d748SDimitry Andric if (forPointeeType && (RD = T->getAsCXXRecordDecl())) { 1510623d748SDimitry Andric Alignment = CGM.getClassPointerAlignment(RD); 1520623d748SDimitry Andric } else { 15339d628a0SDimitry Andric Alignment = getContext().getTypeAlignInChars(T); 15420e90f04SDimitry Andric if (T.getQualifiers().hasUnaligned()) 15520e90f04SDimitry Andric Alignment = CharUnits::One(); 1560623d748SDimitry Andric } 1570623d748SDimitry Andric 1580623d748SDimitry Andric // Cap to the global maximum type alignment unless the alignment 1590623d748SDimitry Andric // was somehow explicit on the type. 1600623d748SDimitry Andric if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 1610623d748SDimitry Andric if (Alignment.getQuantity() > MaxAlign && 16239d628a0SDimitry Andric !getContext().isAlignmentRequired(T)) 16339d628a0SDimitry Andric Alignment = CharUnits::fromQuantity(MaxAlign); 16439d628a0SDimitry Andric } 16539d628a0SDimitry Andric } 1660623d748SDimitry Andric return Alignment; 1670623d748SDimitry Andric } 1680623d748SDimitry Andric 1690623d748SDimitry Andric LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) { 170d8866befSDimitry Andric LValueBaseInfo BaseInfo; 171d8866befSDimitry Andric CharUnits Alignment = getNaturalTypeAlignment(T, &BaseInfo); 172d8866befSDimitry Andric return LValue::MakeAddr(Address(V, Alignment), T, getContext(), BaseInfo, 1730623d748SDimitry Andric CGM.getTBAAInfo(T)); 1740623d748SDimitry Andric } 1750623d748SDimitry Andric 1760623d748SDimitry Andric /// Given a value of type T* that may not be to a complete object, 1770623d748SDimitry Andric /// construct an l-value with the natural pointee alignment of T. 1780623d748SDimitry Andric LValue 1790623d748SDimitry Andric CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) { 180d8866befSDimitry Andric LValueBaseInfo BaseInfo; 181d8866befSDimitry Andric CharUnits Align = getNaturalTypeAlignment(T, &BaseInfo, /*pointee*/ true); 182d8866befSDimitry Andric return MakeAddrLValue(Address(V, Align), T, BaseInfo); 1830623d748SDimitry Andric } 1840623d748SDimitry Andric 185f22ef01cSRoman Divacky 18617a519f9SDimitry Andric llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 187f22ef01cSRoman Divacky return CGM.getTypes().ConvertTypeForMem(T); 188f22ef01cSRoman Divacky } 189f22ef01cSRoman Divacky 19017a519f9SDimitry Andric llvm::Type *CodeGenFunction::ConvertType(QualType T) { 191f22ef01cSRoman Divacky return CGM.getTypes().ConvertType(T); 192f22ef01cSRoman Divacky } 193f22ef01cSRoman Divacky 194139f7f9bSDimitry Andric TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) { 195139f7f9bSDimitry Andric type = type.getCanonicalType(); 196139f7f9bSDimitry Andric while (true) { 197139f7f9bSDimitry Andric switch (type->getTypeClass()) { 198bd5abe19SDimitry Andric #define TYPE(name, parent) 199bd5abe19SDimitry Andric #define ABSTRACT_TYPE(name, parent) 200bd5abe19SDimitry Andric #define NON_CANONICAL_TYPE(name, parent) case Type::name: 201bd5abe19SDimitry Andric #define DEPENDENT_TYPE(name, parent) case Type::name: 202bd5abe19SDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name: 203bd5abe19SDimitry Andric #include "clang/AST/TypeNodes.def" 204bd5abe19SDimitry Andric llvm_unreachable("non-canonical or dependent type in IR-generation"); 205bd5abe19SDimitry Andric 206284c1978SDimitry Andric case Type::Auto: 20720e90f04SDimitry Andric case Type::DeducedTemplateSpecialization: 20820e90f04SDimitry Andric llvm_unreachable("undeduced type in IR-generation"); 209284c1978SDimitry Andric 210139f7f9bSDimitry Andric // Various scalar types. 211bd5abe19SDimitry Andric case Type::Builtin: 212bd5abe19SDimitry Andric case Type::Pointer: 213bd5abe19SDimitry Andric case Type::BlockPointer: 214bd5abe19SDimitry Andric case Type::LValueReference: 215bd5abe19SDimitry Andric case Type::RValueReference: 216bd5abe19SDimitry Andric case Type::MemberPointer: 217bd5abe19SDimitry Andric case Type::Vector: 218bd5abe19SDimitry Andric case Type::ExtVector: 219bd5abe19SDimitry Andric case Type::FunctionProto: 220bd5abe19SDimitry Andric case Type::FunctionNoProto: 221bd5abe19SDimitry Andric case Type::Enum: 222bd5abe19SDimitry Andric case Type::ObjCObjectPointer: 223444ed5c5SDimitry Andric case Type::Pipe: 224139f7f9bSDimitry Andric return TEK_Scalar; 225bd5abe19SDimitry Andric 226139f7f9bSDimitry Andric // Complexes. 227bd5abe19SDimitry Andric case Type::Complex: 228139f7f9bSDimitry Andric return TEK_Complex; 229139f7f9bSDimitry Andric 230139f7f9bSDimitry Andric // Arrays, records, and Objective-C objects. 231bd5abe19SDimitry Andric case Type::ConstantArray: 232bd5abe19SDimitry Andric case Type::IncompleteArray: 233bd5abe19SDimitry Andric case Type::VariableArray: 234bd5abe19SDimitry Andric case Type::Record: 235bd5abe19SDimitry Andric case Type::ObjCObject: 236bd5abe19SDimitry Andric case Type::ObjCInterface: 237139f7f9bSDimitry Andric return TEK_Aggregate; 2386122f3e6SDimitry Andric 239139f7f9bSDimitry Andric // We operate on atomic values according to their underlying type. 2406122f3e6SDimitry Andric case Type::Atomic: 241139f7f9bSDimitry Andric type = cast<AtomicType>(type)->getValueType(); 242139f7f9bSDimitry Andric continue; 243bd5abe19SDimitry Andric } 244bd5abe19SDimitry Andric llvm_unreachable("unknown type kind!"); 245f22ef01cSRoman Divacky } 246139f7f9bSDimitry Andric } 247f22ef01cSRoman Divacky 24839d628a0SDimitry Andric llvm::DebugLoc CodeGenFunction::EmitReturnBlock() { 249f22ef01cSRoman Divacky // For cleanliness, we try to avoid emitting the return block for 250f22ef01cSRoman Divacky // simple cases. 251f22ef01cSRoman Divacky llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 252f22ef01cSRoman Divacky 253f22ef01cSRoman Divacky if (CurBB) { 254f22ef01cSRoman Divacky assert(!CurBB->getTerminator() && "Unexpected terminated block."); 255f22ef01cSRoman Divacky 256f22ef01cSRoman Divacky // We have a valid insert point, reuse it if it is empty or there are no 257f22ef01cSRoman Divacky // explicit jumps to the return block. 258e580952dSDimitry Andric if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) { 259e580952dSDimitry Andric ReturnBlock.getBlock()->replaceAllUsesWith(CurBB); 260e580952dSDimitry Andric delete ReturnBlock.getBlock(); 261f22ef01cSRoman Divacky } else 262e580952dSDimitry Andric EmitBlock(ReturnBlock.getBlock()); 26339d628a0SDimitry Andric return llvm::DebugLoc(); 264f22ef01cSRoman Divacky } 265f22ef01cSRoman Divacky 266f22ef01cSRoman Divacky // Otherwise, if the return block is the target of a single direct 267f22ef01cSRoman Divacky // branch then we can just put the code in that block instead. This 268f22ef01cSRoman Divacky // cleans up functions which started with a unified return block. 269e580952dSDimitry Andric if (ReturnBlock.getBlock()->hasOneUse()) { 270f22ef01cSRoman Divacky llvm::BranchInst *BI = 27159d1ed5bSDimitry Andric dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin()); 272ffd1746dSEd Schouten if (BI && BI->isUnconditional() && 273e580952dSDimitry Andric BI->getSuccessor(0) == ReturnBlock.getBlock()) { 27439d628a0SDimitry Andric // Record/return the DebugLoc of the simple 'return' expression to be used 27539d628a0SDimitry Andric // later by the actual 'ret' instruction. 27639d628a0SDimitry Andric llvm::DebugLoc Loc = BI->getDebugLoc(); 277f22ef01cSRoman Divacky Builder.SetInsertPoint(BI->getParent()); 278f22ef01cSRoman Divacky BI->eraseFromParent(); 279e580952dSDimitry Andric delete ReturnBlock.getBlock(); 28039d628a0SDimitry Andric return Loc; 281f22ef01cSRoman Divacky } 282f22ef01cSRoman Divacky } 283f22ef01cSRoman Divacky 284f22ef01cSRoman Divacky // FIXME: We are at an unreachable point, there is no reason to emit the block 285f22ef01cSRoman Divacky // unless it has uses. However, we still need a place to put the debug 286f22ef01cSRoman Divacky // region.end for now. 287f22ef01cSRoman Divacky 288e580952dSDimitry Andric EmitBlock(ReturnBlock.getBlock()); 28939d628a0SDimitry Andric return llvm::DebugLoc(); 290ffd1746dSEd Schouten } 291ffd1746dSEd Schouten 292ffd1746dSEd Schouten static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) { 293ffd1746dSEd Schouten if (!BB) return; 294ffd1746dSEd Schouten if (!BB->use_empty()) 295ffd1746dSEd Schouten return CGF.CurFn->getBasicBlockList().push_back(BB); 296ffd1746dSEd Schouten delete BB; 297f22ef01cSRoman Divacky } 298f22ef01cSRoman Divacky 299f22ef01cSRoman Divacky void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 300f22ef01cSRoman Divacky assert(BreakContinueStack.empty() && 301f22ef01cSRoman Divacky "mismatched push/pop in break/continue stack!"); 302f22ef01cSRoman Divacky 303284c1978SDimitry Andric bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0 304f785676fSDimitry Andric && NumSimpleReturnExprs == NumReturnExprs 305f785676fSDimitry Andric && ReturnBlock.getBlock()->use_empty(); 306f785676fSDimitry Andric // Usually the return expression is evaluated before the cleanup 307f785676fSDimitry Andric // code. If the function contains only a simple return statement, 308f785676fSDimitry Andric // such as a constant, the location before the cleanup code becomes 309f785676fSDimitry Andric // the last useful breakpoint in the function, because the simple 310f785676fSDimitry Andric // return expression will be evaluated after the cleanup code. To be 311f785676fSDimitry Andric // safe, set the debug location for cleanup code to the location of 312f785676fSDimitry Andric // the return statement. Otherwise the cleanup code should be at the 313f785676fSDimitry Andric // end of the function's lexical scope. 314f785676fSDimitry Andric // 315f785676fSDimitry Andric // If there are multiple branches to the return block, the branch 316f785676fSDimitry Andric // instructions will get the location of the return statements and 317f785676fSDimitry Andric // all will be fine. 318284c1978SDimitry Andric if (CGDebugInfo *DI = getDebugInfo()) { 319284c1978SDimitry Andric if (OnlySimpleReturnStmts) 320284c1978SDimitry Andric DI->EmitLocation(Builder, LastStopPoint); 321284c1978SDimitry Andric else 322139f7f9bSDimitry Andric DI->EmitLocation(Builder, EndLoc); 323284c1978SDimitry Andric } 324139f7f9bSDimitry Andric 32517a519f9SDimitry Andric // Pop any cleanups that might have been associated with the 32617a519f9SDimitry Andric // parameters. Do this in whatever block we're currently in; it's 32717a519f9SDimitry Andric // important to do this before we enter the return block or return 32817a519f9SDimitry Andric // edges will be *really* confused. 32933956c43SDimitry Andric bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth; 33033956c43SDimitry Andric bool HasOnlyLifetimeMarkers = 33133956c43SDimitry Andric HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth); 33233956c43SDimitry Andric bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers; 33333956c43SDimitry Andric if (HasCleanups) { 334284c1978SDimitry Andric // Make sure the line table doesn't jump back into the body for 335284c1978SDimitry Andric // the ret after it's been at EndLoc. 336284c1978SDimitry Andric if (CGDebugInfo *DI = getDebugInfo()) 337284c1978SDimitry Andric if (OnlySimpleReturnStmts) 338284c1978SDimitry Andric DI->EmitLocation(Builder, EndLoc); 33933956c43SDimitry Andric 34033956c43SDimitry Andric PopCleanupBlocks(PrologueCleanupDepth); 341284c1978SDimitry Andric } 34217a519f9SDimitry Andric 343f22ef01cSRoman Divacky // Emit function epilog (to return). 34439d628a0SDimitry Andric llvm::DebugLoc Loc = EmitReturnBlock(); 345f22ef01cSRoman Divacky 3462754fe60SDimitry Andric if (ShouldInstrumentFunction()) 347ffd1746dSEd Schouten EmitFunctionInstrumentation("__cyg_profile_func_exit"); 348ffd1746dSEd Schouten 349f22ef01cSRoman Divacky // Emit debug descriptor for function end. 35039d628a0SDimitry Andric if (CGDebugInfo *DI = getDebugInfo()) 3516d97bb29SDimitry Andric DI->EmitFunctionEnd(Builder, CurFn); 352f22ef01cSRoman Divacky 35339d628a0SDimitry Andric // Reset the debug location to that of the simple 'return' expression, if any 35439d628a0SDimitry Andric // rather than that of the end of the function's scope '}'. 35539d628a0SDimitry Andric ApplyDebugLocation AL(*this, Loc); 356f785676fSDimitry Andric EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc); 357f22ef01cSRoman Divacky EmitEndEHSpec(CurCodeDecl); 358f22ef01cSRoman Divacky 359ffd1746dSEd Schouten assert(EHStack.empty() && 360ffd1746dSEd Schouten "did not remove all scopes from cleanup stack!"); 361ffd1746dSEd Schouten 362f22ef01cSRoman Divacky // If someone did an indirect goto, emit the indirect goto block at the end of 363f22ef01cSRoman Divacky // the function. 364f22ef01cSRoman Divacky if (IndirectBranch) { 365f22ef01cSRoman Divacky EmitBlock(IndirectBranch->getParent()); 366f22ef01cSRoman Divacky Builder.ClearInsertionPoint(); 367f22ef01cSRoman Divacky } 368f22ef01cSRoman Divacky 369875ed548SDimitry Andric // If some of our locals escaped, insert a call to llvm.localescape in the 37033956c43SDimitry Andric // entry block. 37133956c43SDimitry Andric if (!EscapedLocals.empty()) { 37233956c43SDimitry Andric // Invert the map from local to index into a simple vector. There should be 37333956c43SDimitry Andric // no holes. 37433956c43SDimitry Andric SmallVector<llvm::Value *, 4> EscapeArgs; 37533956c43SDimitry Andric EscapeArgs.resize(EscapedLocals.size()); 37633956c43SDimitry Andric for (auto &Pair : EscapedLocals) 37733956c43SDimitry Andric EscapeArgs[Pair.second] = Pair.first; 37833956c43SDimitry Andric llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration( 379875ed548SDimitry Andric &CGM.getModule(), llvm::Intrinsic::localescape); 3800623d748SDimitry Andric CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs); 38133956c43SDimitry Andric } 38233956c43SDimitry Andric 383f22ef01cSRoman Divacky // Remove the AllocaInsertPt instruction, which is just a convenience for us. 384f22ef01cSRoman Divacky llvm::Instruction *Ptr = AllocaInsertPt; 38559d1ed5bSDimitry Andric AllocaInsertPt = nullptr; 386f22ef01cSRoman Divacky Ptr->eraseFromParent(); 387f22ef01cSRoman Divacky 388f22ef01cSRoman Divacky // If someone took the address of a label but never did an indirect goto, we 389f22ef01cSRoman Divacky // made a zero entry PHI node, which is illegal, zap it now. 390f22ef01cSRoman Divacky if (IndirectBranch) { 391f22ef01cSRoman Divacky llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress()); 392f22ef01cSRoman Divacky if (PN->getNumIncomingValues() == 0) { 393f22ef01cSRoman Divacky PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType())); 394f22ef01cSRoman Divacky PN->eraseFromParent(); 395f22ef01cSRoman Divacky } 396f22ef01cSRoman Divacky } 397ffd1746dSEd Schouten 3986122f3e6SDimitry Andric EmitIfUsed(*this, EHResumeBlock); 399ffd1746dSEd Schouten EmitIfUsed(*this, TerminateLandingPad); 400ffd1746dSEd Schouten EmitIfUsed(*this, TerminateHandler); 401ffd1746dSEd Schouten EmitIfUsed(*this, UnreachableBlock); 402ffd1746dSEd Schouten 403ffd1746dSEd Schouten if (CGM.getCodeGenOpts().EmitDeclMetadata) 404ffd1746dSEd Schouten EmitDeclMetadata(); 40559d1ed5bSDimitry Andric 40659d1ed5bSDimitry Andric for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator 40759d1ed5bSDimitry Andric I = DeferredReplacements.begin(), 40859d1ed5bSDimitry Andric E = DeferredReplacements.end(); 40959d1ed5bSDimitry Andric I != E; ++I) { 41059d1ed5bSDimitry Andric I->first->replaceAllUsesWith(I->second); 41159d1ed5bSDimitry Andric I->first->eraseFromParent(); 41259d1ed5bSDimitry Andric } 413ffd1746dSEd Schouten } 414ffd1746dSEd Schouten 415ffd1746dSEd Schouten /// ShouldInstrumentFunction - Return true if the current function should be 416ffd1746dSEd Schouten /// instrumented with __cyg_profile_func_* calls 417ffd1746dSEd Schouten bool CodeGenFunction::ShouldInstrumentFunction() { 418ffd1746dSEd Schouten if (!CGM.getCodeGenOpts().InstrumentFunctions) 419ffd1746dSEd Schouten return false; 420bd5abe19SDimitry Andric if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) 421ffd1746dSEd Schouten return false; 422ffd1746dSEd Schouten return true; 423ffd1746dSEd Schouten } 424ffd1746dSEd Schouten 425e7145dcbSDimitry Andric /// ShouldXRayInstrument - Return true if the current function should be 426e7145dcbSDimitry Andric /// instrumented with XRay nop sleds. 427e7145dcbSDimitry Andric bool CodeGenFunction::ShouldXRayInstrumentFunction() const { 428e7145dcbSDimitry Andric return CGM.getCodeGenOpts().XRayInstrumentFunctions; 429e7145dcbSDimitry Andric } 430e7145dcbSDimitry Andric 431ffd1746dSEd Schouten /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 432ffd1746dSEd Schouten /// instrumentation function with the current function and the call site, if 433ffd1746dSEd Schouten /// function instrumentation is enabled. 434ffd1746dSEd Schouten void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) { 435e7145dcbSDimitry Andric auto NL = ApplyDebugLocation::CreateArtificial(*this); 436ffd1746dSEd Schouten // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site); 43717a519f9SDimitry Andric llvm::PointerType *PointerTy = Int8PtrTy; 43817a519f9SDimitry Andric llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy }; 4396122f3e6SDimitry Andric llvm::FunctionType *FunctionTy = 440dff0c46cSDimitry Andric llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false); 441ffd1746dSEd Schouten 442ffd1746dSEd Schouten llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn); 443ffd1746dSEd Schouten llvm::CallInst *CallSite = Builder.CreateCall( 44417a519f9SDimitry Andric CGM.getIntrinsic(llvm::Intrinsic::returnaddress), 445ffd1746dSEd Schouten llvm::ConstantInt::get(Int32Ty, 0), 446ffd1746dSEd Schouten "callsite"); 447ffd1746dSEd Schouten 448139f7f9bSDimitry Andric llvm::Value *args[] = { 449ffd1746dSEd Schouten llvm::ConstantExpr::getBitCast(CurFn, PointerTy), 450139f7f9bSDimitry Andric CallSite 451139f7f9bSDimitry Andric }; 452139f7f9bSDimitry Andric 453139f7f9bSDimitry Andric EmitNounwindRuntimeCall(F, args); 454f22ef01cSRoman Divacky } 455f22ef01cSRoman Divacky 45644290647SDimitry Andric static void removeImageAccessQualifier(std::string& TyName) { 45744290647SDimitry Andric std::string ReadOnlyQual("__read_only"); 45844290647SDimitry Andric std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual); 45944290647SDimitry Andric if (ReadOnlyPos != std::string::npos) 46044290647SDimitry Andric // "+ 1" for the space after access qualifier. 46144290647SDimitry Andric TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1); 46244290647SDimitry Andric else { 46344290647SDimitry Andric std::string WriteOnlyQual("__write_only"); 46444290647SDimitry Andric std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual); 46544290647SDimitry Andric if (WriteOnlyPos != std::string::npos) 46644290647SDimitry Andric TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1); 46744290647SDimitry Andric else { 46844290647SDimitry Andric std::string ReadWriteQual("__read_write"); 46944290647SDimitry Andric std::string::size_type ReadWritePos = TyName.find(ReadWriteQual); 47044290647SDimitry Andric if (ReadWritePos != std::string::npos) 47144290647SDimitry Andric TyName.erase(ReadWritePos, ReadWriteQual.size() + 1); 47244290647SDimitry Andric } 47344290647SDimitry Andric } 4742754fe60SDimitry Andric } 4752754fe60SDimitry Andric 476f41fbc90SDimitry Andric // Returns the address space id that should be produced to the 477f41fbc90SDimitry Andric // kernel_arg_addr_space metadata. This is always fixed to the ids 478f41fbc90SDimitry Andric // as specified in the SPIR 2.0 specification in order to differentiate 479f41fbc90SDimitry Andric // for example in clGetKernelArgInfo() implementation between the address 480f41fbc90SDimitry Andric // spaces with targets without unique mapping to the OpenCL address spaces 481f41fbc90SDimitry Andric // (basically all single AS CPUs). 482f41fbc90SDimitry Andric static unsigned ArgInfoAddressSpace(unsigned LangAS) { 483f41fbc90SDimitry Andric switch (LangAS) { 484f41fbc90SDimitry Andric case LangAS::opencl_global: return 1; 485f41fbc90SDimitry Andric case LangAS::opencl_constant: return 2; 486f41fbc90SDimitry Andric case LangAS::opencl_local: return 3; 487f41fbc90SDimitry Andric case LangAS::opencl_generic: return 4; // Not in SPIR 2.0 specs. 488f41fbc90SDimitry Andric default: 489f41fbc90SDimitry Andric return 0; // Assume private. 490f41fbc90SDimitry Andric } 491f41fbc90SDimitry Andric } 492f41fbc90SDimitry Andric 4937ae0e2c9SDimitry Andric // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument 4947ae0e2c9SDimitry Andric // information in the program executable. The argument information stored 4957ae0e2c9SDimitry Andric // includes the argument name, its type, the address and access qualifiers used. 4967ae0e2c9SDimitry Andric static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn, 4977ae0e2c9SDimitry Andric CodeGenModule &CGM, llvm::LLVMContext &Context, 498139f7f9bSDimitry Andric CGBuilderTy &Builder, ASTContext &ASTCtx) { 499139f7f9bSDimitry Andric // Create MDNodes that represent the kernel arg metadata. 5007ae0e2c9SDimitry Andric // Each MDNode is a list in the form of "key", N number of values which is 5017ae0e2c9SDimitry Andric // the same number of values as their are kernel arguments. 5027ae0e2c9SDimitry Andric 50359d1ed5bSDimitry Andric const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy(); 50459d1ed5bSDimitry Andric 505139f7f9bSDimitry Andric // MDNode for the kernel argument address space qualifiers. 50639d628a0SDimitry Andric SmallVector<llvm::Metadata *, 8> addressQuals; 507139f7f9bSDimitry Andric 508139f7f9bSDimitry Andric // MDNode for the kernel argument access qualifiers (images only). 50939d628a0SDimitry Andric SmallVector<llvm::Metadata *, 8> accessQuals; 510139f7f9bSDimitry Andric 511139f7f9bSDimitry Andric // MDNode for the kernel argument type names. 51239d628a0SDimitry Andric SmallVector<llvm::Metadata *, 8> argTypeNames; 513139f7f9bSDimitry Andric 51439d628a0SDimitry Andric // MDNode for the kernel argument base type names. 51539d628a0SDimitry Andric SmallVector<llvm::Metadata *, 8> argBaseTypeNames; 51639d628a0SDimitry Andric 517139f7f9bSDimitry Andric // MDNode for the kernel argument type qualifiers. 51839d628a0SDimitry Andric SmallVector<llvm::Metadata *, 8> argTypeQuals; 519139f7f9bSDimitry Andric 5207ae0e2c9SDimitry Andric // MDNode for the kernel argument names. 52139d628a0SDimitry Andric SmallVector<llvm::Metadata *, 8> argNames; 5227ae0e2c9SDimitry Andric 5237ae0e2c9SDimitry Andric for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 5247ae0e2c9SDimitry Andric const ParmVarDecl *parm = FD->getParamDecl(i); 525139f7f9bSDimitry Andric QualType ty = parm->getType(); 526139f7f9bSDimitry Andric std::string typeQuals; 527139f7f9bSDimitry Andric 528139f7f9bSDimitry Andric if (ty->isPointerType()) { 529139f7f9bSDimitry Andric QualType pointeeTy = ty->getPointeeType(); 530139f7f9bSDimitry Andric 531139f7f9bSDimitry Andric // Get address qualifier. 53239d628a0SDimitry Andric addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32( 533f41fbc90SDimitry Andric ArgInfoAddressSpace(pointeeTy.getAddressSpace())))); 534139f7f9bSDimitry Andric 535139f7f9bSDimitry Andric // Get argument type name. 53659d1ed5bSDimitry Andric std::string typeName = 53759d1ed5bSDimitry Andric pointeeTy.getUnqualifiedType().getAsString(Policy) + "*"; 538139f7f9bSDimitry Andric 539139f7f9bSDimitry Andric // Turn "unsigned type" to "utype" 540139f7f9bSDimitry Andric std::string::size_type pos = typeName.find("unsigned"); 54139d628a0SDimitry Andric if (pointeeTy.isCanonical() && pos != std::string::npos) 542139f7f9bSDimitry Andric typeName.erase(pos+1, 8); 543139f7f9bSDimitry Andric 544139f7f9bSDimitry Andric argTypeNames.push_back(llvm::MDString::get(Context, typeName)); 545139f7f9bSDimitry Andric 54639d628a0SDimitry Andric std::string baseTypeName = 54739d628a0SDimitry Andric pointeeTy.getUnqualifiedType().getCanonicalType().getAsString( 54839d628a0SDimitry Andric Policy) + 54939d628a0SDimitry Andric "*"; 55039d628a0SDimitry Andric 55139d628a0SDimitry Andric // Turn "unsigned type" to "utype" 55239d628a0SDimitry Andric pos = baseTypeName.find("unsigned"); 55339d628a0SDimitry Andric if (pos != std::string::npos) 55439d628a0SDimitry Andric baseTypeName.erase(pos+1, 8); 55539d628a0SDimitry Andric 55639d628a0SDimitry Andric argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName)); 55739d628a0SDimitry Andric 558139f7f9bSDimitry Andric // Get argument type qualifiers: 559139f7f9bSDimitry Andric if (ty.isRestrictQualified()) 560139f7f9bSDimitry Andric typeQuals = "restrict"; 561139f7f9bSDimitry Andric if (pointeeTy.isConstQualified() || 562139f7f9bSDimitry Andric (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) 563139f7f9bSDimitry Andric typeQuals += typeQuals.empty() ? "const" : " const"; 564139f7f9bSDimitry Andric if (pointeeTy.isVolatileQualified()) 565139f7f9bSDimitry Andric typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 566139f7f9bSDimitry Andric } else { 56759d1ed5bSDimitry Andric uint32_t AddrSpc = 0; 568444ed5c5SDimitry Andric bool isPipe = ty->isPipeType(); 569444ed5c5SDimitry Andric if (ty->isImageType() || isPipe) 570f41fbc90SDimitry Andric AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global); 57159d1ed5bSDimitry Andric 57239d628a0SDimitry Andric addressQuals.push_back( 57339d628a0SDimitry Andric llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc))); 574139f7f9bSDimitry Andric 575139f7f9bSDimitry Andric // Get argument type name. 576444ed5c5SDimitry Andric std::string typeName; 577444ed5c5SDimitry Andric if (isPipe) 578e7145dcbSDimitry Andric typeName = ty.getCanonicalType()->getAs<PipeType>()->getElementType() 579e7145dcbSDimitry Andric .getAsString(Policy); 580444ed5c5SDimitry Andric else 581444ed5c5SDimitry Andric typeName = ty.getUnqualifiedType().getAsString(Policy); 582139f7f9bSDimitry Andric 583139f7f9bSDimitry Andric // Turn "unsigned type" to "utype" 584139f7f9bSDimitry Andric std::string::size_type pos = typeName.find("unsigned"); 58539d628a0SDimitry Andric if (ty.isCanonical() && pos != std::string::npos) 586139f7f9bSDimitry Andric typeName.erase(pos+1, 8); 587139f7f9bSDimitry Andric 588444ed5c5SDimitry Andric std::string baseTypeName; 589444ed5c5SDimitry Andric if (isPipe) 590e7145dcbSDimitry Andric baseTypeName = ty.getCanonicalType()->getAs<PipeType>() 591e7145dcbSDimitry Andric ->getElementType().getCanonicalType() 592e7145dcbSDimitry Andric .getAsString(Policy); 593444ed5c5SDimitry Andric else 594444ed5c5SDimitry Andric baseTypeName = 59539d628a0SDimitry Andric ty.getUnqualifiedType().getCanonicalType().getAsString(Policy); 59639d628a0SDimitry Andric 59744290647SDimitry Andric // Remove access qualifiers on images 59844290647SDimitry Andric // (as they are inseparable from type in clang implementation, 59944290647SDimitry Andric // but OpenCL spec provides a special query to get access qualifier 60044290647SDimitry Andric // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER): 60144290647SDimitry Andric if (ty->isImageType()) { 60244290647SDimitry Andric removeImageAccessQualifier(typeName); 60344290647SDimitry Andric removeImageAccessQualifier(baseTypeName); 60444290647SDimitry Andric } 60544290647SDimitry Andric 60644290647SDimitry Andric argTypeNames.push_back(llvm::MDString::get(Context, typeName)); 60744290647SDimitry Andric 60839d628a0SDimitry Andric // Turn "unsigned type" to "utype" 60939d628a0SDimitry Andric pos = baseTypeName.find("unsigned"); 61039d628a0SDimitry Andric if (pos != std::string::npos) 61139d628a0SDimitry Andric baseTypeName.erase(pos+1, 8); 61239d628a0SDimitry Andric 61339d628a0SDimitry Andric argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName)); 61439d628a0SDimitry Andric 615444ed5c5SDimitry Andric if (isPipe) 616444ed5c5SDimitry Andric typeQuals = "pipe"; 617139f7f9bSDimitry Andric } 618139f7f9bSDimitry Andric 619139f7f9bSDimitry Andric argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals)); 620139f7f9bSDimitry Andric 621444ed5c5SDimitry Andric // Get image and pipe access qualifier: 622444ed5c5SDimitry Andric if (ty->isImageType()|| ty->isPipeType()) { 623e7145dcbSDimitry Andric const OpenCLAccessAttr *A = parm->getAttr<OpenCLAccessAttr>(); 62459d1ed5bSDimitry Andric if (A && A->isWriteOnly()) 625139f7f9bSDimitry Andric accessQuals.push_back(llvm::MDString::get(Context, "write_only")); 626e7145dcbSDimitry Andric else if (A && A->isReadWrite()) 627e7145dcbSDimitry Andric accessQuals.push_back(llvm::MDString::get(Context, "read_write")); 628139f7f9bSDimitry Andric else 629139f7f9bSDimitry Andric accessQuals.push_back(llvm::MDString::get(Context, "read_only")); 630139f7f9bSDimitry Andric } else 631139f7f9bSDimitry Andric accessQuals.push_back(llvm::MDString::get(Context, "none")); 6327ae0e2c9SDimitry Andric 6337ae0e2c9SDimitry Andric // Get argument name. 6347ae0e2c9SDimitry Andric argNames.push_back(llvm::MDString::get(Context, parm->getName())); 6357ae0e2c9SDimitry Andric } 636139f7f9bSDimitry Andric 637e7145dcbSDimitry Andric Fn->setMetadata("kernel_arg_addr_space", 638e7145dcbSDimitry Andric llvm::MDNode::get(Context, addressQuals)); 639e7145dcbSDimitry Andric Fn->setMetadata("kernel_arg_access_qual", 640e7145dcbSDimitry Andric llvm::MDNode::get(Context, accessQuals)); 641e7145dcbSDimitry Andric Fn->setMetadata("kernel_arg_type", 642e7145dcbSDimitry Andric llvm::MDNode::get(Context, argTypeNames)); 643e7145dcbSDimitry Andric Fn->setMetadata("kernel_arg_base_type", 644e7145dcbSDimitry Andric llvm::MDNode::get(Context, argBaseTypeNames)); 645e7145dcbSDimitry Andric Fn->setMetadata("kernel_arg_type_qual", 646e7145dcbSDimitry Andric llvm::MDNode::get(Context, argTypeQuals)); 64739d628a0SDimitry Andric if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata) 648e7145dcbSDimitry Andric Fn->setMetadata("kernel_arg_name", 649e7145dcbSDimitry Andric llvm::MDNode::get(Context, argNames)); 6507ae0e2c9SDimitry Andric } 6517ae0e2c9SDimitry Andric 6527ae0e2c9SDimitry Andric void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD, 6537ae0e2c9SDimitry Andric llvm::Function *Fn) 6547ae0e2c9SDimitry Andric { 6557ae0e2c9SDimitry Andric if (!FD->hasAttr<OpenCLKernelAttr>()) 6567ae0e2c9SDimitry Andric return; 6577ae0e2c9SDimitry Andric 6587ae0e2c9SDimitry Andric llvm::LLVMContext &Context = getLLVMContext(); 6597ae0e2c9SDimitry Andric 660e7145dcbSDimitry Andric GenOpenCLArgMetadata(FD, Fn, CGM, Context, Builder, getContext()); 661139f7f9bSDimitry Andric 66259d1ed5bSDimitry Andric if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) { 6630f5676f4SDimitry Andric QualType HintQTy = A->getTypeHint(); 6640f5676f4SDimitry Andric const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>(); 6650f5676f4SDimitry Andric bool IsSignedInteger = 6660f5676f4SDimitry Andric HintQTy->isSignedIntegerType() || 6670f5676f4SDimitry Andric (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType()); 6680f5676f4SDimitry Andric llvm::Metadata *AttrMDArgs[] = { 66939d628a0SDimitry Andric llvm::ConstantAsMetadata::get(llvm::UndefValue::get( 67039d628a0SDimitry Andric CGM.getTypes().ConvertType(A->getTypeHint()))), 67139d628a0SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 672139f7f9bSDimitry Andric llvm::IntegerType::get(Context, 32), 6730f5676f4SDimitry Andric llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))}; 6740f5676f4SDimitry Andric Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs)); 675139f7f9bSDimitry Andric } 6767ae0e2c9SDimitry Andric 67759d1ed5bSDimitry Andric if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) { 6780f5676f4SDimitry Andric llvm::Metadata *AttrMDArgs[] = { 67939d628a0SDimitry Andric llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())), 68039d628a0SDimitry Andric llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())), 68139d628a0SDimitry Andric llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))}; 6820f5676f4SDimitry Andric Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs)); 6837ae0e2c9SDimitry Andric } 6847ae0e2c9SDimitry Andric 68559d1ed5bSDimitry Andric if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) { 6860f5676f4SDimitry Andric llvm::Metadata *AttrMDArgs[] = { 68739d628a0SDimitry Andric llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())), 68839d628a0SDimitry Andric llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())), 68939d628a0SDimitry Andric llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))}; 6900f5676f4SDimitry Andric Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs)); 6910f5676f4SDimitry Andric } 6920f5676f4SDimitry Andric 6930f5676f4SDimitry Andric if (const OpenCLIntelReqdSubGroupSizeAttr *A = 6940f5676f4SDimitry Andric FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) { 6950f5676f4SDimitry Andric llvm::Metadata *AttrMDArgs[] = { 6960f5676f4SDimitry Andric llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))}; 6970f5676f4SDimitry Andric Fn->setMetadata("intel_reqd_sub_group_size", 6980f5676f4SDimitry Andric llvm::MDNode::get(Context, AttrMDArgs)); 6997ae0e2c9SDimitry Andric } 7007ae0e2c9SDimitry Andric } 7017ae0e2c9SDimitry Andric 70259d1ed5bSDimitry Andric /// Determine whether the function F ends with a return stmt. 70359d1ed5bSDimitry Andric static bool endsWithReturn(const Decl* F) { 70459d1ed5bSDimitry Andric const Stmt *Body = nullptr; 70559d1ed5bSDimitry Andric if (auto *FD = dyn_cast_or_null<FunctionDecl>(F)) 70659d1ed5bSDimitry Andric Body = FD->getBody(); 70759d1ed5bSDimitry Andric else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F)) 70859d1ed5bSDimitry Andric Body = OMD->getBody(); 70959d1ed5bSDimitry Andric 71059d1ed5bSDimitry Andric if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) { 71159d1ed5bSDimitry Andric auto LastStmt = CS->body_rbegin(); 71259d1ed5bSDimitry Andric if (LastStmt != CS->body_rend()) 71359d1ed5bSDimitry Andric return isa<ReturnStmt>(*LastStmt); 71459d1ed5bSDimitry Andric } 71559d1ed5bSDimitry Andric return false; 71659d1ed5bSDimitry Andric } 71759d1ed5bSDimitry Andric 71820e90f04SDimitry Andric static void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) { 71920e90f04SDimitry Andric Fn->addFnAttr("sanitize_thread_no_checking_at_run_time"); 72020e90f04SDimitry Andric Fn->removeFnAttr(llvm::Attribute::SanitizeThread); 72120e90f04SDimitry Andric } 72220e90f04SDimitry Andric 723284c1978SDimitry Andric void CodeGenFunction::StartFunction(GlobalDecl GD, 724284c1978SDimitry Andric QualType RetTy, 725f22ef01cSRoman Divacky llvm::Function *Fn, 7263b0f4066SDimitry Andric const CGFunctionInfo &FnInfo, 727f22ef01cSRoman Divacky const FunctionArgList &Args, 72859d1ed5bSDimitry Andric SourceLocation Loc, 729f22ef01cSRoman Divacky SourceLocation StartLoc) { 73039d628a0SDimitry Andric assert(!CurFn && 73139d628a0SDimitry Andric "Do not use a CodeGenFunction object for more than one function"); 73239d628a0SDimitry Andric 733f22ef01cSRoman Divacky const Decl *D = GD.getDecl(); 734f22ef01cSRoman Divacky 735f22ef01cSRoman Divacky DidCallStackSave = false; 736284c1978SDimitry Andric CurCodeDecl = D; 737e7145dcbSDimitry Andric if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) 738e7145dcbSDimitry Andric if (FD->usesSEHTry()) 739e7145dcbSDimitry Andric CurSEHParent = FD; 74059d1ed5bSDimitry Andric CurFuncDecl = (D ? D->getNonClosureContext() : nullptr); 741f22ef01cSRoman Divacky FnRetTy = RetTy; 742f22ef01cSRoman Divacky CurFn = Fn; 7433b0f4066SDimitry Andric CurFnInfo = &FnInfo; 744f22ef01cSRoman Divacky assert(CurFn->isDeclaration() && "Function already has body?"); 745f22ef01cSRoman Divacky 74639d628a0SDimitry Andric if (CGM.isInSanitizerBlacklist(Fn, Loc)) 74739d628a0SDimitry Andric SanOpts.clear(); 748139f7f9bSDimitry Andric 74933956c43SDimitry Andric if (D) { 75033956c43SDimitry Andric // Apply the no_sanitize* attributes to SanOpts. 75133956c43SDimitry Andric for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) 75233956c43SDimitry Andric SanOpts.Mask &= ~Attr->getMask(); 75333956c43SDimitry Andric } 75433956c43SDimitry Andric 75533956c43SDimitry Andric // Apply sanitizer attributes to the function. 7568f0fd8f6SDimitry Andric if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress)) 75733956c43SDimitry Andric Fn->addFnAttr(llvm::Attribute::SanitizeAddress); 75833956c43SDimitry Andric if (SanOpts.has(SanitizerKind::Thread)) 75933956c43SDimitry Andric Fn->addFnAttr(llvm::Attribute::SanitizeThread); 76033956c43SDimitry Andric if (SanOpts.has(SanitizerKind::Memory)) 76133956c43SDimitry Andric Fn->addFnAttr(llvm::Attribute::SanitizeMemory); 7628f0fd8f6SDimitry Andric if (SanOpts.has(SanitizerKind::SafeStack)) 7638f0fd8f6SDimitry Andric Fn->addFnAttr(llvm::Attribute::SafeStack); 76433956c43SDimitry Andric 76544290647SDimitry Andric // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize, 76620e90f04SDimitry Andric // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time. 76744290647SDimitry Andric if (SanOpts.has(SanitizerKind::Thread)) { 76844290647SDimitry Andric if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) { 76944290647SDimitry Andric IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0); 77044290647SDimitry Andric if (OMD->getMethodFamily() == OMF_dealloc || 77144290647SDimitry Andric OMD->getMethodFamily() == OMF_initialize || 77244290647SDimitry Andric (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) { 77320e90f04SDimitry Andric markAsIgnoreThreadCheckingAtRuntime(Fn); 77444290647SDimitry Andric } 77520e90f04SDimitry Andric } else if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 77620e90f04SDimitry Andric IdentifierInfo *II = FD->getIdentifier(); 77720e90f04SDimitry Andric if (II && II->isStr("__destroy_helper_block_")) 77820e90f04SDimitry Andric markAsIgnoreThreadCheckingAtRuntime(Fn); 77944290647SDimitry Andric } 78044290647SDimitry Andric } 78144290647SDimitry Andric 782e7145dcbSDimitry Andric // Apply xray attributes to the function (as a string, for now) 783e7145dcbSDimitry Andric if (D && ShouldXRayInstrumentFunction()) { 784e7145dcbSDimitry Andric if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) { 785e7145dcbSDimitry Andric if (XRayAttr->alwaysXRayInstrument()) 786e7145dcbSDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 787e7145dcbSDimitry Andric if (XRayAttr->neverXRayInstrument()) 788e7145dcbSDimitry Andric Fn->addFnAttr("function-instrument", "xray-never"); 78920e90f04SDimitry Andric if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>()) { 79020e90f04SDimitry Andric Fn->addFnAttr("xray-log-args", 79120e90f04SDimitry Andric llvm::utostr(LogArgs->getArgumentCount())); 79220e90f04SDimitry Andric } 793e7145dcbSDimitry Andric } else { 79420e90f04SDimitry Andric if (!CGM.imbueXRayAttrs(Fn, Loc)) 795e7145dcbSDimitry Andric Fn->addFnAttr( 796e7145dcbSDimitry Andric "xray-instruction-threshold", 797e7145dcbSDimitry Andric llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold)); 798e7145dcbSDimitry Andric } 799e7145dcbSDimitry Andric } 800e7145dcbSDimitry Andric 80144290647SDimitry Andric if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 802e7145dcbSDimitry Andric if (CGM.getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) 803e7145dcbSDimitry Andric CGM.getOpenMPRuntime().emitDeclareSimdFunction(FD, Fn); 804f22ef01cSRoman Divacky 805e7145dcbSDimitry Andric // Add no-jump-tables value. 806e7145dcbSDimitry Andric Fn->addFnAttr("no-jump-tables", 807e7145dcbSDimitry Andric llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables)); 808e7145dcbSDimitry Andric 8093861d79fSDimitry Andric if (getLangOpts().OpenCL) { 8102754fe60SDimitry Andric // Add metadata for a kernel function. 8112754fe60SDimitry Andric if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 8127ae0e2c9SDimitry Andric EmitOpenCLKernelMetadata(FD, Fn); 8132754fe60SDimitry Andric } 8142754fe60SDimitry Andric 815f785676fSDimitry Andric // If we are checking function types, emit a function type signature as 81639d628a0SDimitry Andric // prologue data. 81739d628a0SDimitry Andric if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) { 818f785676fSDimitry Andric if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 81939d628a0SDimitry Andric if (llvm::Constant *PrologueSig = 820f785676fSDimitry Andric CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) { 821f785676fSDimitry Andric llvm::Constant *FTRTTIConst = 822f785676fSDimitry Andric CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true); 82339d628a0SDimitry Andric llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst }; 82439d628a0SDimitry Andric llvm::Constant *PrologueStructConst = 82539d628a0SDimitry Andric llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true); 82639d628a0SDimitry Andric Fn->setPrologueData(PrologueStructConst); 827f785676fSDimitry Andric } 828f785676fSDimitry Andric } 829f785676fSDimitry Andric } 830f785676fSDimitry Andric 83120e90f04SDimitry Andric // If we're checking nullability, we need to know whether we can check the 83220e90f04SDimitry Andric // return value. Initialize the flag to 'true' and refine it in EmitParmDecl. 83320e90f04SDimitry Andric if (SanOpts.has(SanitizerKind::NullabilityReturn)) { 83420e90f04SDimitry Andric auto Nullability = FnRetTy->getNullability(getContext()); 83520e90f04SDimitry Andric if (Nullability && *Nullability == NullabilityKind::NonNull) { 83620e90f04SDimitry Andric if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && 83720e90f04SDimitry Andric CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>())) 83820e90f04SDimitry Andric RetValNullabilityPrecondition = 83920e90f04SDimitry Andric llvm::ConstantInt::getTrue(getLLVMContext()); 84020e90f04SDimitry Andric } 84120e90f04SDimitry Andric } 84220e90f04SDimitry Andric 8430623d748SDimitry Andric // If we're in C++ mode and the function name is "main", it is guaranteed 8440623d748SDimitry Andric // to be norecurse by the standard (3.6.1.3 "The function main shall not be 8450623d748SDimitry Andric // used within a program"). 8460623d748SDimitry Andric if (getLangOpts().CPlusPlus) 8470623d748SDimitry Andric if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 8480623d748SDimitry Andric if (FD->isMain()) 8490623d748SDimitry Andric Fn->addFnAttr(llvm::Attribute::NoRecurse); 8500623d748SDimitry Andric 851f22ef01cSRoman Divacky llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 852f22ef01cSRoman Divacky 853f22ef01cSRoman Divacky // Create a marker to make it easy to insert allocas into the entryblock 854f22ef01cSRoman Divacky // later. Don't create this with the builder, because we don't want it 855f22ef01cSRoman Divacky // folded. 856ffd1746dSEd Schouten llvm::Value *Undef = llvm::UndefValue::get(Int32Ty); 857e7145dcbSDimitry Andric AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB); 858f22ef01cSRoman Divacky 859ffd1746dSEd Schouten ReturnBlock = getJumpDestInCurrentScope("return"); 860f22ef01cSRoman Divacky 861f22ef01cSRoman Divacky Builder.SetInsertPoint(EntryBB); 862f22ef01cSRoman Divacky 863edd7eaddSDimitry Andric // If we're checking the return value, allocate space for a pointer to a 864edd7eaddSDimitry Andric // precise source location of the checked return statement. 865edd7eaddSDimitry Andric if (requiresReturnValueCheck()) { 866edd7eaddSDimitry Andric ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr"); 867edd7eaddSDimitry Andric InitTempAlloca(ReturnLocation, llvm::ConstantPointerNull::get(Int8PtrTy)); 868edd7eaddSDimitry Andric } 869edd7eaddSDimitry Andric 870f22ef01cSRoman Divacky // Emit subprogram debug descriptor. 871f22ef01cSRoman Divacky if (CGDebugInfo *DI = getDebugInfo()) { 872e7145dcbSDimitry Andric // Reconstruct the type from the argument list so that implicit parameters, 873e7145dcbSDimitry Andric // such as 'this' and 'vtt', show up in the debug info. Preserve the calling 874e7145dcbSDimitry Andric // convention. 875e7145dcbSDimitry Andric CallingConv CC = CallingConv::CC_C; 876e7145dcbSDimitry Andric if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) 877e7145dcbSDimitry Andric if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>()) 878e7145dcbSDimitry Andric CC = SrcFnTy->getCallConv(); 879139f7f9bSDimitry Andric SmallVector<QualType, 16> ArgTypes; 880e7145dcbSDimitry Andric for (const VarDecl *VD : Args) 881e7145dcbSDimitry Andric ArgTypes.push_back(VD->getType()); 882e7145dcbSDimitry Andric QualType FnType = getContext().getFunctionType( 883e7145dcbSDimitry Andric RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC)); 88459d1ed5bSDimitry Andric DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder); 885f22ef01cSRoman Divacky } 886f22ef01cSRoman Divacky 8872754fe60SDimitry Andric if (ShouldInstrumentFunction()) 888ffd1746dSEd Schouten EmitFunctionInstrumentation("__cyg_profile_func_enter"); 889ffd1746dSEd Schouten 89044290647SDimitry Andric // Since emitting the mcount call here impacts optimizations such as function 89144290647SDimitry Andric // inlining, we just add an attribute to insert a mcount call in backend. 89244290647SDimitry Andric // The attribute "counting-function" is set to mcount function name which is 89344290647SDimitry Andric // architecture dependent. 89420e90f04SDimitry Andric if (CGM.getCodeGenOpts().InstrumentForProfiling) { 89520e90f04SDimitry Andric if (CGM.getCodeGenOpts().CallFEntry) 89620e90f04SDimitry Andric Fn->addFnAttr("fentry-call", "true"); 897edd7eaddSDimitry Andric else { 898edd7eaddSDimitry Andric if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) 89944290647SDimitry Andric Fn->addFnAttr("counting-function", getTarget().getMCountName()); 90020e90f04SDimitry Andric } 901edd7eaddSDimitry Andric } 9022754fe60SDimitry Andric 903f22ef01cSRoman Divacky if (RetTy->isVoidType()) { 904f22ef01cSRoman Divacky // Void type; nothing to return. 9050623d748SDimitry Andric ReturnValue = Address::invalid(); 90659d1ed5bSDimitry Andric 90759d1ed5bSDimitry Andric // Count the implicit return. 90859d1ed5bSDimitry Andric if (!endsWithReturn(D)) 90959d1ed5bSDimitry Andric ++NumReturnExprs; 910f22ef01cSRoman Divacky } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect && 911139f7f9bSDimitry Andric !hasScalarEvaluationKind(CurFnInfo->getReturnType())) { 912f22ef01cSRoman Divacky // Indirect aggregate return; emit returned value directly into sret slot. 913f22ef01cSRoman Divacky // This reduces code size, and affects correctness in C++. 91459d1ed5bSDimitry Andric auto AI = CurFn->arg_begin(); 91559d1ed5bSDimitry Andric if (CurFnInfo->getReturnInfo().isSRetAfterThis()) 91659d1ed5bSDimitry Andric ++AI; 9170623d748SDimitry Andric ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign()); 91859d1ed5bSDimitry Andric } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca && 91959d1ed5bSDimitry Andric !hasScalarEvaluationKind(CurFnInfo->getReturnType())) { 92059d1ed5bSDimitry Andric // Load the sret pointer from the argument struct and return into that. 92159d1ed5bSDimitry Andric unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex(); 92259d1ed5bSDimitry Andric llvm::Function::arg_iterator EI = CurFn->arg_end(); 92359d1ed5bSDimitry Andric --EI; 9240623d748SDimitry Andric llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx); 9250623d748SDimitry Andric Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result"); 9260623d748SDimitry Andric ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy)); 927f22ef01cSRoman Divacky } else { 928f22ef01cSRoman Divacky ReturnValue = CreateIRTemp(RetTy, "retval"); 92917a519f9SDimitry Andric 93017a519f9SDimitry Andric // Tell the epilog emitter to autorelease the result. We do this 93117a519f9SDimitry Andric // now so that various specialized functions can suppress it 93217a519f9SDimitry Andric // during their IR-generation. 933dff0c46cSDimitry Andric if (getLangOpts().ObjCAutoRefCount && 93417a519f9SDimitry Andric !CurFnInfo->isReturnsRetained() && 93517a519f9SDimitry Andric RetTy->isObjCRetainableType()) 93617a519f9SDimitry Andric AutoreleaseResult = true; 937f22ef01cSRoman Divacky } 938f22ef01cSRoman Divacky 939f22ef01cSRoman Divacky EmitStartEHSpec(CurCodeDecl); 94017a519f9SDimitry Andric 94117a519f9SDimitry Andric PrologueCleanupDepth = EHStack.stable_begin(); 942f22ef01cSRoman Divacky EmitFunctionProlog(*CurFnInfo, CurFn, Args); 943f22ef01cSRoman Divacky 944dff0c46cSDimitry Andric if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) { 945e580952dSDimitry Andric CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 946dff0c46cSDimitry Andric const CXXMethodDecl *MD = cast<CXXMethodDecl>(D); 947dff0c46cSDimitry Andric if (MD->getParent()->isLambda() && 948dff0c46cSDimitry Andric MD->getOverloadedOperator() == OO_Call) { 949dff0c46cSDimitry Andric // We're in a lambda; figure out the captures. 950dff0c46cSDimitry Andric MD->getParent()->getCaptureFields(LambdaCaptureFields, 951dff0c46cSDimitry Andric LambdaThisCaptureField); 952dff0c46cSDimitry Andric if (LambdaThisCaptureField) { 953e7145dcbSDimitry Andric // If the lambda captures the object referred to by '*this' - either by 954e7145dcbSDimitry Andric // value or by reference, make sure CXXThisValue points to the correct 955e7145dcbSDimitry Andric // object. 956e7145dcbSDimitry Andric 957e7145dcbSDimitry Andric // Get the lvalue for the field (which is a copy of the enclosing object 958e7145dcbSDimitry Andric // or contains the address of the enclosing object). 959e7145dcbSDimitry Andric LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField); 960e7145dcbSDimitry Andric if (!LambdaThisCaptureField->getType()->isPointerType()) { 961e7145dcbSDimitry Andric // If the enclosing object was captured by value, just use its address. 962e7145dcbSDimitry Andric CXXThisValue = ThisFieldLValue.getAddress().getPointer(); 963e7145dcbSDimitry Andric } else { 964e7145dcbSDimitry Andric // Load the lvalue pointed to by the field, since '*this' was captured 965e7145dcbSDimitry Andric // by reference. 966e7145dcbSDimitry Andric CXXThisValue = 967e7145dcbSDimitry Andric EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal(); 968e7145dcbSDimitry Andric } 969dff0c46cSDimitry Andric } 97039d628a0SDimitry Andric for (auto *FD : MD->getParent()->fields()) { 97139d628a0SDimitry Andric if (FD->hasCapturedVLAType()) { 97239d628a0SDimitry Andric auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD), 97339d628a0SDimitry Andric SourceLocation()).getScalarVal(); 97439d628a0SDimitry Andric auto VAT = FD->getCapturedVLAType(); 97539d628a0SDimitry Andric VLASizeMap[VAT->getSizeExpr()] = ExprArg; 97639d628a0SDimitry Andric } 97739d628a0SDimitry Andric } 978dff0c46cSDimitry Andric } else { 979dff0c46cSDimitry Andric // Not in a lambda; just use 'this' from the method. 980dff0c46cSDimitry Andric // FIXME: Should we generate a new load for each use of 'this'? The 981dff0c46cSDimitry Andric // fast register allocator would be happier... 982dff0c46cSDimitry Andric CXXThisValue = CXXABIThisValue; 983dff0c46cSDimitry Andric } 98420e90f04SDimitry Andric 98520e90f04SDimitry Andric // Check the 'this' pointer once per function, if it's available. 98620e90f04SDimitry Andric if (CXXThisValue) { 98720e90f04SDimitry Andric SanitizerSet SkippedChecks; 98820e90f04SDimitry Andric SkippedChecks.set(SanitizerKind::ObjectSize, true); 98920e90f04SDimitry Andric QualType ThisTy = MD->getThisType(getContext()); 99020e90f04SDimitry Andric EmitTypeCheck(TCK_Load, Loc, CXXThisValue, ThisTy, 99120e90f04SDimitry Andric getContext().getTypeAlignInChars(ThisTy->getPointeeType()), 99220e90f04SDimitry Andric SkippedChecks); 99320e90f04SDimitry Andric } 994dff0c46cSDimitry Andric } 995f22ef01cSRoman Divacky 996f22ef01cSRoman Divacky // If any of the arguments have a variably modified type, make sure to 997f22ef01cSRoman Divacky // emit the type size. 998f22ef01cSRoman Divacky for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 999f22ef01cSRoman Divacky i != e; ++i) { 1000139f7f9bSDimitry Andric const VarDecl *VD = *i; 1001139f7f9bSDimitry Andric 1002139f7f9bSDimitry Andric // Dig out the type as written from ParmVarDecls; it's unclear whether 1003139f7f9bSDimitry Andric // the standard (C99 6.9.1p10) requires this, but we're following the 1004139f7f9bSDimitry Andric // precedent set by gcc. 1005139f7f9bSDimitry Andric QualType Ty; 1006139f7f9bSDimitry Andric if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) 1007139f7f9bSDimitry Andric Ty = PVD->getOriginalType(); 1008139f7f9bSDimitry Andric else 1009139f7f9bSDimitry Andric Ty = VD->getType(); 1010f22ef01cSRoman Divacky 1011f22ef01cSRoman Divacky if (Ty->isVariablyModifiedType()) 101217a519f9SDimitry Andric EmitVariablyModifiedType(Ty); 1013f22ef01cSRoman Divacky } 10146122f3e6SDimitry Andric // Emit a location at the end of the prologue. 10156122f3e6SDimitry Andric if (CGDebugInfo *DI = getDebugInfo()) 10166122f3e6SDimitry Andric DI->EmitLocation(Builder, StartLoc); 1017f22ef01cSRoman Divacky } 1018f22ef01cSRoman Divacky 1019f785676fSDimitry Andric void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args, 1020f785676fSDimitry Andric const Stmt *Body) { 102133956c43SDimitry Andric incrementProfileCounter(Body); 1022f785676fSDimitry Andric if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body)) 1023139f7f9bSDimitry Andric EmitCompoundStmtWithoutScope(*S); 1024139f7f9bSDimitry Andric else 1025f785676fSDimitry Andric EmitStmt(Body); 1026f22ef01cSRoman Divacky } 1027f22ef01cSRoman Divacky 102859d1ed5bSDimitry Andric /// When instrumenting to collect profile data, the counts for some blocks 102959d1ed5bSDimitry Andric /// such as switch cases need to not include the fall-through counts, so 103059d1ed5bSDimitry Andric /// emit a branch around the instrumentation code. When not instrumenting, 103159d1ed5bSDimitry Andric /// this just calls EmitBlock(). 103259d1ed5bSDimitry Andric void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB, 103333956c43SDimitry Andric const Stmt *S) { 103459d1ed5bSDimitry Andric llvm::BasicBlock *SkipCountBB = nullptr; 1035e7145dcbSDimitry Andric if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) { 103659d1ed5bSDimitry Andric // When instrumenting for profiling, the fallthrough to certain 103759d1ed5bSDimitry Andric // statements needs to skip over the instrumentation code so that we 103859d1ed5bSDimitry Andric // get an accurate count. 103959d1ed5bSDimitry Andric SkipCountBB = createBasicBlock("skipcount"); 104059d1ed5bSDimitry Andric EmitBranch(SkipCountBB); 104159d1ed5bSDimitry Andric } 104259d1ed5bSDimitry Andric EmitBlock(BB); 104333956c43SDimitry Andric uint64_t CurrentCount = getCurrentProfileCount(); 104433956c43SDimitry Andric incrementProfileCounter(S); 104533956c43SDimitry Andric setCurrentProfileCount(getCurrentProfileCount() + CurrentCount); 104659d1ed5bSDimitry Andric if (SkipCountBB) 104759d1ed5bSDimitry Andric EmitBlock(SkipCountBB); 104859d1ed5bSDimitry Andric } 104959d1ed5bSDimitry Andric 1050e580952dSDimitry Andric /// Tries to mark the given function nounwind based on the 1051e580952dSDimitry Andric /// non-existence of any throwing calls within it. We believe this is 1052e580952dSDimitry Andric /// lightweight enough to do at -O0. 1053e580952dSDimitry Andric static void TryMarkNoThrow(llvm::Function *F) { 1054e580952dSDimitry Andric // LLVM treats 'nounwind' on a function as part of the type, so we 1055e580952dSDimitry Andric // can't do this on functions that can be overwritten. 1056e7145dcbSDimitry Andric if (F->isInterposable()) return; 1057e580952dSDimitry Andric 10580623d748SDimitry Andric for (llvm::BasicBlock &BB : *F) 10590623d748SDimitry Andric for (llvm::Instruction &I : BB) 10600623d748SDimitry Andric if (I.mayThrow()) 1061e580952dSDimitry Andric return; 10620623d748SDimitry Andric 10633861d79fSDimitry Andric F->setDoesNotThrow(); 1064e580952dSDimitry Andric } 1065e580952dSDimitry Andric 1066e7145dcbSDimitry Andric QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD, 1067e7145dcbSDimitry Andric FunctionArgList &Args) { 1068f22ef01cSRoman Divacky const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 106959d1ed5bSDimitry Andric QualType ResTy = FD->getReturnType(); 1070f22ef01cSRoman Divacky 107159d1ed5bSDimitry Andric const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 107259d1ed5bSDimitry Andric if (MD && MD->isInstance()) { 1073f785676fSDimitry Andric if (CGM.getCXXABI().HasThisReturn(GD)) 1074f785676fSDimitry Andric ResTy = MD->getThisType(getContext()); 107539d628a0SDimitry Andric else if (CGM.getCXXABI().hasMostDerivedReturn(GD)) 107639d628a0SDimitry Andric ResTy = CGM.getContext().VoidPtrTy; 107759d1ed5bSDimitry Andric CGM.getCXXABI().buildThisParam(*this, Args); 1078f785676fSDimitry Andric } 1079f22ef01cSRoman Divacky 1080e7145dcbSDimitry Andric // The base version of an inheriting constructor whose constructed base is a 1081e7145dcbSDimitry Andric // virtual base is not passed any arguments (because it doesn't actually call 1082e7145dcbSDimitry Andric // the inherited constructor). 1083e7145dcbSDimitry Andric bool PassedParams = true; 1084e7145dcbSDimitry Andric if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 1085e7145dcbSDimitry Andric if (auto Inherited = CD->getInheritedConstructor()) 1086e7145dcbSDimitry Andric PassedParams = 1087e7145dcbSDimitry Andric getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType()); 1088e7145dcbSDimitry Andric 1089e7145dcbSDimitry Andric if (PassedParams) { 1090e7145dcbSDimitry Andric for (auto *Param : FD->parameters()) { 10910623d748SDimitry Andric Args.push_back(Param); 10920623d748SDimitry Andric if (!Param->hasAttr<PassObjectSizeAttr>()) 10930623d748SDimitry Andric continue; 10940623d748SDimitry Andric 10950623d748SDimitry Andric auto *Implicit = ImplicitParamDecl::Create( 1096db17bf38SDimitry Andric getContext(), Param->getDeclContext(), Param->getLocation(), 1097db17bf38SDimitry Andric /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other); 10980623d748SDimitry Andric SizeArguments[Param] = Implicit; 10990623d748SDimitry Andric Args.push_back(Implicit); 11000623d748SDimitry Andric } 1101e7145dcbSDimitry Andric } 1102f22ef01cSRoman Divacky 110359d1ed5bSDimitry Andric if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))) 110459d1ed5bSDimitry Andric CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args); 110559d1ed5bSDimitry Andric 1106e7145dcbSDimitry Andric return ResTy; 1107e7145dcbSDimitry Andric } 1108e7145dcbSDimitry Andric 11098e0f8b8cSDimitry Andric static bool 11108e0f8b8cSDimitry Andric shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD, 11118e0f8b8cSDimitry Andric const ASTContext &Context) { 11128e0f8b8cSDimitry Andric QualType T = FD->getReturnType(); 11138e0f8b8cSDimitry Andric // Avoid the optimization for functions that return a record type with a 11148e0f8b8cSDimitry Andric // trivial destructor or another trivially copyable type. 11158e0f8b8cSDimitry Andric if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) { 11168e0f8b8cSDimitry Andric if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) 11178e0f8b8cSDimitry Andric return !ClassDecl->hasTrivialDestructor(); 11188e0f8b8cSDimitry Andric } 11198e0f8b8cSDimitry Andric return !T.isTriviallyCopyableType(Context); 11208e0f8b8cSDimitry Andric } 11218e0f8b8cSDimitry Andric 1122e7145dcbSDimitry Andric void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn, 1123e7145dcbSDimitry Andric const CGFunctionInfo &FnInfo) { 1124e7145dcbSDimitry Andric const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 1125e7145dcbSDimitry Andric CurGD = GD; 1126e7145dcbSDimitry Andric 1127e7145dcbSDimitry Andric FunctionArgList Args; 1128e7145dcbSDimitry Andric QualType ResTy = BuildFunctionArgList(GD, Args); 1129e7145dcbSDimitry Andric 1130e7145dcbSDimitry Andric // Check if we should generate debug info for this function. 1131e7145dcbSDimitry Andric if (FD->hasAttr<NoDebugAttr>()) 1132e7145dcbSDimitry Andric DebugInfo = nullptr; // disable debug info indefinitely for this function 1133e7145dcbSDimitry Andric 113420e90f04SDimitry Andric // The function might not have a body if we're generating thunks for a 113520e90f04SDimitry Andric // function declaration. 1136f22ef01cSRoman Divacky SourceRange BodyRange; 113720e90f04SDimitry Andric if (Stmt *Body = FD->getBody()) 113820e90f04SDimitry Andric BodyRange = Body->getSourceRange(); 113920e90f04SDimitry Andric else 114020e90f04SDimitry Andric BodyRange = FD->getLocation(); 1141f785676fSDimitry Andric CurEHLocation = BodyRange.getEnd(); 1142139f7f9bSDimitry Andric 114359d1ed5bSDimitry Andric // Use the location of the start of the function to determine where 114459d1ed5bSDimitry Andric // the function definition is located. By default use the location 114559d1ed5bSDimitry Andric // of the declaration as the location for the subprogram. A function 114659d1ed5bSDimitry Andric // may lack a declaration in the source code if it is created by code 114759d1ed5bSDimitry Andric // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk). 114859d1ed5bSDimitry Andric SourceLocation Loc = FD->getLocation(); 114959d1ed5bSDimitry Andric 115059d1ed5bSDimitry Andric // If this is a function specialization then use the pattern body 115159d1ed5bSDimitry Andric // as the location for the function. 115259d1ed5bSDimitry Andric if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern()) 115359d1ed5bSDimitry Andric if (SpecDecl->hasBody(SpecDecl)) 115459d1ed5bSDimitry Andric Loc = SpecDecl->getLocation(); 115559d1ed5bSDimitry Andric 115644290647SDimitry Andric Stmt *Body = FD->getBody(); 115744290647SDimitry Andric 115844290647SDimitry Andric // Initialize helper which will detect jumps which can cause invalid lifetime 115944290647SDimitry Andric // markers. 116044290647SDimitry Andric if (Body && ShouldEmitLifetimeMarkers) 116144290647SDimitry Andric Bypasses.Init(Body); 116244290647SDimitry Andric 1163f22ef01cSRoman Divacky // Emit the standard function prologue. 116459d1ed5bSDimitry Andric StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin()); 1165f22ef01cSRoman Divacky 1166f22ef01cSRoman Divacky // Generate the body of the function. 11670623d748SDimitry Andric PGO.assignRegionCounters(GD, CurFn); 1168f22ef01cSRoman Divacky if (isa<CXXDestructorDecl>(FD)) 1169f22ef01cSRoman Divacky EmitDestructorBody(Args); 1170f22ef01cSRoman Divacky else if (isa<CXXConstructorDecl>(FD)) 1171f22ef01cSRoman Divacky EmitConstructorBody(Args); 11723861d79fSDimitry Andric else if (getLangOpts().CUDA && 117333956c43SDimitry Andric !getLangOpts().CUDAIsDevice && 11746122f3e6SDimitry Andric FD->hasAttr<CUDAGlobalAttr>()) 117533956c43SDimitry Andric CGM.getCUDARuntime().emitDeviceStub(*this, Args); 1176dff0c46cSDimitry Andric else if (isa<CXXConversionDecl>(FD) && 1177dff0c46cSDimitry Andric cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) { 1178dff0c46cSDimitry Andric // The lambda conversion to block pointer is special; the semantics can't be 1179dff0c46cSDimitry Andric // expressed in the AST, so IRGen needs to special-case it. 1180dff0c46cSDimitry Andric EmitLambdaToBlockPointerBody(Args); 1181dff0c46cSDimitry Andric } else if (isa<CXXMethodDecl>(FD) && 1182dff0c46cSDimitry Andric cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) { 1183f785676fSDimitry Andric // The lambda static invoker function is special, because it forwards or 1184dff0c46cSDimitry Andric // clones the body of the function call operator (but is actually static). 1185dff0c46cSDimitry Andric EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD)); 1186139f7f9bSDimitry Andric } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) && 1187f785676fSDimitry Andric (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() || 1188f785676fSDimitry Andric cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) { 1189139f7f9bSDimitry Andric // Implicit copy-assignment gets the same special treatment as implicit 1190139f7f9bSDimitry Andric // copy-constructors. 1191139f7f9bSDimitry Andric emitImplicitAssignmentOperatorBody(Args); 119244290647SDimitry Andric } else if (Body) { 1193f785676fSDimitry Andric EmitFunctionBody(Args, Body); 1194f785676fSDimitry Andric } else 1195f785676fSDimitry Andric llvm_unreachable("no definition for emitted function"); 1196f22ef01cSRoman Divacky 11973861d79fSDimitry Andric // C++11 [stmt.return]p2: 11983861d79fSDimitry Andric // Flowing off the end of a function [...] results in undefined behavior in 11993861d79fSDimitry Andric // a value-returning function. 12003861d79fSDimitry Andric // C11 6.9.1p12: 12013861d79fSDimitry Andric // If the '}' that terminates a function is reached, and the value of the 12023861d79fSDimitry Andric // function call is used by the caller, the behavior is undefined. 120339d628a0SDimitry Andric if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock && 120459d1ed5bSDimitry Andric !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) { 12058e0f8b8cSDimitry Andric bool ShouldEmitUnreachable = 12068e0f8b8cSDimitry Andric CGM.getCodeGenOpts().StrictReturn || 12078e0f8b8cSDimitry Andric shouldUseUndefinedBehaviorReturnOptimization(FD, getContext()); 120839d628a0SDimitry Andric if (SanOpts.has(SanitizerKind::Return)) { 120959d1ed5bSDimitry Andric SanitizerScope SanScope(this); 121039d628a0SDimitry Andric llvm::Value *IsFalse = Builder.getFalse(); 121139d628a0SDimitry Andric EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return), 121244290647SDimitry Andric SanitizerHandler::MissingReturn, 121344290647SDimitry Andric EmitCheckSourceLocation(FD->getLocation()), None); 12148e0f8b8cSDimitry Andric } else if (ShouldEmitUnreachable) { 12158e0f8b8cSDimitry Andric if (CGM.getCodeGenOpts().OptimizationLevel == 0) 12163dac3a9bSDimitry Andric EmitTrapCall(llvm::Intrinsic::trap); 12173dac3a9bSDimitry Andric } 12188e0f8b8cSDimitry Andric if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) { 12193861d79fSDimitry Andric Builder.CreateUnreachable(); 12203861d79fSDimitry Andric Builder.ClearInsertionPoint(); 12213861d79fSDimitry Andric } 12228e0f8b8cSDimitry Andric } 12233861d79fSDimitry Andric 1224f22ef01cSRoman Divacky // Emit the standard function epilogue. 1225f22ef01cSRoman Divacky FinishFunction(BodyRange.getEnd()); 1226f22ef01cSRoman Divacky 1227e580952dSDimitry Andric // If we haven't marked the function nothrow through other means, do 1228e580952dSDimitry Andric // a quick pass now to see if we can. 1229e580952dSDimitry Andric if (!CurFn->doesNotThrow()) 1230e580952dSDimitry Andric TryMarkNoThrow(CurFn); 1231f22ef01cSRoman Divacky } 1232f22ef01cSRoman Divacky 1233f22ef01cSRoman Divacky /// ContainsLabel - Return true if the statement contains a label in it. If 1234f22ef01cSRoman Divacky /// this statement is not executed normally, it not containing a label means 1235f22ef01cSRoman Divacky /// that we can just remove the code. 1236f22ef01cSRoman Divacky bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 1237f22ef01cSRoman Divacky // Null statement, not a label! 123859d1ed5bSDimitry Andric if (!S) return false; 1239f22ef01cSRoman Divacky 1240f22ef01cSRoman Divacky // If this is a label, we have to emit the code, consider something like: 1241f22ef01cSRoman Divacky // if (0) { ... foo: bar(); } goto foo; 12423b0f4066SDimitry Andric // 12433b0f4066SDimitry Andric // TODO: If anyone cared, we could track __label__'s, since we know that you 12443b0f4066SDimitry Andric // can't jump to one from outside their declared region. 1245f22ef01cSRoman Divacky if (isa<LabelStmt>(S)) 1246f22ef01cSRoman Divacky return true; 1247f22ef01cSRoman Divacky 1248f22ef01cSRoman Divacky // If this is a case/default statement, and we haven't seen a switch, we have 1249f22ef01cSRoman Divacky // to emit the code. 1250f22ef01cSRoman Divacky if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 1251f22ef01cSRoman Divacky return true; 1252f22ef01cSRoman Divacky 1253f22ef01cSRoman Divacky // If this is a switch statement, we want to ignore cases below it. 1254f22ef01cSRoman Divacky if (isa<SwitchStmt>(S)) 1255f22ef01cSRoman Divacky IgnoreCaseStmts = true; 1256f22ef01cSRoman Divacky 1257f22ef01cSRoman Divacky // Scan subexpressions for verboten labels. 12583dac3a9bSDimitry Andric for (const Stmt *SubStmt : S->children()) 12593dac3a9bSDimitry Andric if (ContainsLabel(SubStmt, IgnoreCaseStmts)) 1260f22ef01cSRoman Divacky return true; 1261f22ef01cSRoman Divacky 1262f22ef01cSRoman Divacky return false; 1263f22ef01cSRoman Divacky } 1264f22ef01cSRoman Divacky 12653b0f4066SDimitry Andric /// containsBreak - Return true if the statement contains a break out of it. 12663b0f4066SDimitry Andric /// If the statement (recursively) contains a switch or loop with a break 12673b0f4066SDimitry Andric /// inside of it, this is fine. 12683b0f4066SDimitry Andric bool CodeGenFunction::containsBreak(const Stmt *S) { 12693b0f4066SDimitry Andric // Null statement, not a label! 127059d1ed5bSDimitry Andric if (!S) return false; 1271f22ef01cSRoman Divacky 12723b0f4066SDimitry Andric // If this is a switch or loop that defines its own break scope, then we can 12733b0f4066SDimitry Andric // include it and anything inside of it. 12743b0f4066SDimitry Andric if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) || 12753b0f4066SDimitry Andric isa<ForStmt>(S)) 12763b0f4066SDimitry Andric return false; 12773b0f4066SDimitry Andric 12783b0f4066SDimitry Andric if (isa<BreakStmt>(S)) 12793b0f4066SDimitry Andric return true; 12803b0f4066SDimitry Andric 12813b0f4066SDimitry Andric // Scan subexpressions for verboten breaks. 12823dac3a9bSDimitry Andric for (const Stmt *SubStmt : S->children()) 12833dac3a9bSDimitry Andric if (containsBreak(SubStmt)) 12843b0f4066SDimitry Andric return true; 12853b0f4066SDimitry Andric 12863b0f4066SDimitry Andric return false; 12873b0f4066SDimitry Andric } 12883b0f4066SDimitry Andric 1289f41fbc90SDimitry Andric bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) { 1290f41fbc90SDimitry Andric if (!S) return false; 1291f41fbc90SDimitry Andric 1292f41fbc90SDimitry Andric // Some statement kinds add a scope and thus never add a decl to the current 1293f41fbc90SDimitry Andric // scope. Note, this list is longer than the list of statements that might 1294f41fbc90SDimitry Andric // have an unscoped decl nested within them, but this way is conservatively 1295f41fbc90SDimitry Andric // correct even if more statement kinds are added. 1296f41fbc90SDimitry Andric if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) || 1297f41fbc90SDimitry Andric isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) || 1298f41fbc90SDimitry Andric isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) || 1299f41fbc90SDimitry Andric isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S)) 1300f41fbc90SDimitry Andric return false; 1301f41fbc90SDimitry Andric 1302f41fbc90SDimitry Andric if (isa<DeclStmt>(S)) 1303f41fbc90SDimitry Andric return true; 1304f41fbc90SDimitry Andric 1305f41fbc90SDimitry Andric for (const Stmt *SubStmt : S->children()) 1306f41fbc90SDimitry Andric if (mightAddDeclToScope(SubStmt)) 1307f41fbc90SDimitry Andric return true; 1308f41fbc90SDimitry Andric 1309f41fbc90SDimitry Andric return false; 1310f41fbc90SDimitry Andric } 13113b0f4066SDimitry Andric 13123b0f4066SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 13133b0f4066SDimitry Andric /// to a constant, or if it does but contains a label, return false. If it 13143b0f4066SDimitry Andric /// constant folds return true and set the boolean result in Result. 13153b0f4066SDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 1316e7145dcbSDimitry Andric bool &ResultBool, 1317e7145dcbSDimitry Andric bool AllowLabels) { 13187ae0e2c9SDimitry Andric llvm::APSInt ResultInt; 1319e7145dcbSDimitry Andric if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels)) 13203b0f4066SDimitry Andric return false; 13213b0f4066SDimitry Andric 13223b0f4066SDimitry Andric ResultBool = ResultInt.getBoolValue(); 13233b0f4066SDimitry Andric return true; 13243b0f4066SDimitry Andric } 13253b0f4066SDimitry Andric 13263b0f4066SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 13273b0f4066SDimitry Andric /// to a constant, or if it does but contains a label, return false. If it 13283b0f4066SDimitry Andric /// constant folds return true and set the folded value. 1329e7145dcbSDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 1330e7145dcbSDimitry Andric llvm::APSInt &ResultInt, 1331e7145dcbSDimitry Andric bool AllowLabels) { 1332f22ef01cSRoman Divacky // FIXME: Rename and handle conversion of other evaluatable things 1333f22ef01cSRoman Divacky // to bool. 1334dff0c46cSDimitry Andric llvm::APSInt Int; 1335dff0c46cSDimitry Andric if (!Cond->EvaluateAsInt(Int, getContext())) 13363b0f4066SDimitry Andric return false; // Not foldable, not integer or not fully evaluatable. 1337f22ef01cSRoman Divacky 1338e7145dcbSDimitry Andric if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond)) 13393b0f4066SDimitry Andric return false; // Contains a label. 1340f22ef01cSRoman Divacky 1341dff0c46cSDimitry Andric ResultInt = Int; 13423b0f4066SDimitry Andric return true; 1343f22ef01cSRoman Divacky } 1344f22ef01cSRoman Divacky 1345f22ef01cSRoman Divacky 13463b0f4066SDimitry Andric 1347f22ef01cSRoman Divacky /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 1348f22ef01cSRoman Divacky /// statement) to the specified blocks. Based on the condition, this might try 1349f22ef01cSRoman Divacky /// to simplify the codegen of the conditional based on the branch. 1350f22ef01cSRoman Divacky /// 1351f22ef01cSRoman Divacky void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 1352f22ef01cSRoman Divacky llvm::BasicBlock *TrueBlock, 135359d1ed5bSDimitry Andric llvm::BasicBlock *FalseBlock, 135459d1ed5bSDimitry Andric uint64_t TrueCount) { 13553b0f4066SDimitry Andric Cond = Cond->IgnoreParens(); 1356f22ef01cSRoman Divacky 1357f22ef01cSRoman Divacky if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 135859d1ed5bSDimitry Andric 1359f22ef01cSRoman Divacky // Handle X && Y in a condition. 1360e580952dSDimitry Andric if (CondBOp->getOpcode() == BO_LAnd) { 1361f22ef01cSRoman Divacky // If we have "1 && X", simplify the code. "0 && X" would have constant 1362f22ef01cSRoman Divacky // folded if the case was simple enough. 13633b0f4066SDimitry Andric bool ConstantBool = false; 13643b0f4066SDimitry Andric if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 13653b0f4066SDimitry Andric ConstantBool) { 1366f22ef01cSRoman Divacky // br(1 && X) -> br(X). 136733956c43SDimitry Andric incrementProfileCounter(CondBOp); 136859d1ed5bSDimitry Andric return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, 136959d1ed5bSDimitry Andric TrueCount); 1370f22ef01cSRoman Divacky } 1371f22ef01cSRoman Divacky 1372f22ef01cSRoman Divacky // If we have "X && 1", simplify the code to use an uncond branch. 1373f22ef01cSRoman Divacky // "X && 0" would have been constant folded to 0. 13743b0f4066SDimitry Andric if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 13753b0f4066SDimitry Andric ConstantBool) { 1376f22ef01cSRoman Divacky // br(X && 1) -> br(X). 137759d1ed5bSDimitry Andric return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock, 137859d1ed5bSDimitry Andric TrueCount); 1379f22ef01cSRoman Divacky } 1380f22ef01cSRoman Divacky 1381f22ef01cSRoman Divacky // Emit the LHS as a conditional. If the LHS conditional is false, we 1382f22ef01cSRoman Divacky // want to jump to the FalseBlock. 1383f22ef01cSRoman Divacky llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 138459d1ed5bSDimitry Andric // The counter tells us how often we evaluate RHS, and all of TrueCount 138559d1ed5bSDimitry Andric // can be propagated to that branch. 138633956c43SDimitry Andric uint64_t RHSCount = getProfileCount(CondBOp->getRHS()); 13872754fe60SDimitry Andric 13882754fe60SDimitry Andric ConditionalEvaluation eval(*this); 138933956c43SDimitry Andric { 139033956c43SDimitry Andric ApplyDebugLocation DL(*this, Cond); 139159d1ed5bSDimitry Andric EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount); 1392f22ef01cSRoman Divacky EmitBlock(LHSTrue); 139333956c43SDimitry Andric } 139433956c43SDimitry Andric 139533956c43SDimitry Andric incrementProfileCounter(CondBOp); 139633956c43SDimitry Andric setCurrentProfileCount(getProfileCount(CondBOp->getRHS())); 1397f22ef01cSRoman Divacky 1398f22ef01cSRoman Divacky // Any temporaries created here are conditional. 13992754fe60SDimitry Andric eval.begin(*this); 140059d1ed5bSDimitry Andric EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount); 14012754fe60SDimitry Andric eval.end(*this); 1402f22ef01cSRoman Divacky 1403f22ef01cSRoman Divacky return; 14043b0f4066SDimitry Andric } 14053b0f4066SDimitry Andric 14063b0f4066SDimitry Andric if (CondBOp->getOpcode() == BO_LOr) { 1407f22ef01cSRoman Divacky // If we have "0 || X", simplify the code. "1 || X" would have constant 1408f22ef01cSRoman Divacky // folded if the case was simple enough. 14093b0f4066SDimitry Andric bool ConstantBool = false; 14103b0f4066SDimitry Andric if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 14113b0f4066SDimitry Andric !ConstantBool) { 1412f22ef01cSRoman Divacky // br(0 || X) -> br(X). 141333956c43SDimitry Andric incrementProfileCounter(CondBOp); 141459d1ed5bSDimitry Andric return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, 141559d1ed5bSDimitry Andric TrueCount); 1416f22ef01cSRoman Divacky } 1417f22ef01cSRoman Divacky 1418f22ef01cSRoman Divacky // If we have "X || 0", simplify the code to use an uncond branch. 1419f22ef01cSRoman Divacky // "X || 1" would have been constant folded to 1. 14203b0f4066SDimitry Andric if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 14213b0f4066SDimitry Andric !ConstantBool) { 1422f22ef01cSRoman Divacky // br(X || 0) -> br(X). 142359d1ed5bSDimitry Andric return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock, 142459d1ed5bSDimitry Andric TrueCount); 1425f22ef01cSRoman Divacky } 1426f22ef01cSRoman Divacky 1427f22ef01cSRoman Divacky // Emit the LHS as a conditional. If the LHS conditional is true, we 1428f22ef01cSRoman Divacky // want to jump to the TrueBlock. 1429f22ef01cSRoman Divacky llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 143059d1ed5bSDimitry Andric // We have the count for entry to the RHS and for the whole expression 143159d1ed5bSDimitry Andric // being true, so we can divy up True count between the short circuit and 143259d1ed5bSDimitry Andric // the RHS. 143333956c43SDimitry Andric uint64_t LHSCount = 143433956c43SDimitry Andric getCurrentProfileCount() - getProfileCount(CondBOp->getRHS()); 143559d1ed5bSDimitry Andric uint64_t RHSCount = TrueCount - LHSCount; 14362754fe60SDimitry Andric 14372754fe60SDimitry Andric ConditionalEvaluation eval(*this); 143833956c43SDimitry Andric { 143933956c43SDimitry Andric ApplyDebugLocation DL(*this, Cond); 144059d1ed5bSDimitry Andric EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount); 1441f22ef01cSRoman Divacky EmitBlock(LHSFalse); 144233956c43SDimitry Andric } 144333956c43SDimitry Andric 144433956c43SDimitry Andric incrementProfileCounter(CondBOp); 144533956c43SDimitry Andric setCurrentProfileCount(getProfileCount(CondBOp->getRHS())); 1446f22ef01cSRoman Divacky 1447f22ef01cSRoman Divacky // Any temporaries created here are conditional. 14482754fe60SDimitry Andric eval.begin(*this); 144959d1ed5bSDimitry Andric EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount); 145059d1ed5bSDimitry Andric 14512754fe60SDimitry Andric eval.end(*this); 1452f22ef01cSRoman Divacky 1453f22ef01cSRoman Divacky return; 1454f22ef01cSRoman Divacky } 1455f22ef01cSRoman Divacky } 1456f22ef01cSRoman Divacky 1457f22ef01cSRoman Divacky if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 1458f22ef01cSRoman Divacky // br(!x, t, f) -> br(x, f, t) 145959d1ed5bSDimitry Andric if (CondUOp->getOpcode() == UO_LNot) { 146059d1ed5bSDimitry Andric // Negate the count. 146133956c43SDimitry Andric uint64_t FalseCount = getCurrentProfileCount() - TrueCount; 146259d1ed5bSDimitry Andric // Negate the condition and swap the destination blocks. 146359d1ed5bSDimitry Andric return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock, 146459d1ed5bSDimitry Andric FalseCount); 146559d1ed5bSDimitry Andric } 1466f22ef01cSRoman Divacky } 1467f22ef01cSRoman Divacky 1468f22ef01cSRoman Divacky if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 1469f22ef01cSRoman Divacky // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 1470f22ef01cSRoman Divacky llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 1471f22ef01cSRoman Divacky llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 14722754fe60SDimitry Andric 14732754fe60SDimitry Andric ConditionalEvaluation cond(*this); 147433956c43SDimitry Andric EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock, 147533956c43SDimitry Andric getProfileCount(CondOp)); 147659d1ed5bSDimitry Andric 147759d1ed5bSDimitry Andric // When computing PGO branch weights, we only know the overall count for 147859d1ed5bSDimitry Andric // the true block. This code is essentially doing tail duplication of the 147959d1ed5bSDimitry Andric // naive code-gen, introducing new edges for which counts are not 148059d1ed5bSDimitry Andric // available. Divide the counts proportionally between the LHS and RHS of 148159d1ed5bSDimitry Andric // the conditional operator. 148259d1ed5bSDimitry Andric uint64_t LHSScaledTrueCount = 0; 148359d1ed5bSDimitry Andric if (TrueCount) { 148433956c43SDimitry Andric double LHSRatio = 148533956c43SDimitry Andric getProfileCount(CondOp) / (double)getCurrentProfileCount(); 148659d1ed5bSDimitry Andric LHSScaledTrueCount = TrueCount * LHSRatio; 148759d1ed5bSDimitry Andric } 14882754fe60SDimitry Andric 14892754fe60SDimitry Andric cond.begin(*this); 1490f22ef01cSRoman Divacky EmitBlock(LHSBlock); 149133956c43SDimitry Andric incrementProfileCounter(CondOp); 149233956c43SDimitry Andric { 149333956c43SDimitry Andric ApplyDebugLocation DL(*this, Cond); 149459d1ed5bSDimitry Andric EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock, 149559d1ed5bSDimitry Andric LHSScaledTrueCount); 149633956c43SDimitry Andric } 14972754fe60SDimitry Andric cond.end(*this); 14982754fe60SDimitry Andric 14992754fe60SDimitry Andric cond.begin(*this); 1500f22ef01cSRoman Divacky EmitBlock(RHSBlock); 150159d1ed5bSDimitry Andric EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock, 150259d1ed5bSDimitry Andric TrueCount - LHSScaledTrueCount); 15032754fe60SDimitry Andric cond.end(*this); 15042754fe60SDimitry Andric 1505f22ef01cSRoman Divacky return; 1506f22ef01cSRoman Divacky } 1507f22ef01cSRoman Divacky 1508284c1978SDimitry Andric if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) { 1509284c1978SDimitry Andric // Conditional operator handling can give us a throw expression as a 1510284c1978SDimitry Andric // condition for a case like: 1511284c1978SDimitry Andric // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f) 1512284c1978SDimitry Andric // Fold this to: 1513284c1978SDimitry Andric // br(c, throw x, br(y, t, f)) 1514284c1978SDimitry Andric EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false); 1515284c1978SDimitry Andric return; 1516284c1978SDimitry Andric } 1517284c1978SDimitry Andric 15180623d748SDimitry Andric // If the branch has a condition wrapped by __builtin_unpredictable, 15190623d748SDimitry Andric // create metadata that specifies that the branch is unpredictable. 15200623d748SDimitry Andric // Don't bother if not optimizing because that metadata would not be used. 15210623d748SDimitry Andric llvm::MDNode *Unpredictable = nullptr; 1522e7145dcbSDimitry Andric auto *Call = dyn_cast<CallExpr>(Cond); 1523e7145dcbSDimitry Andric if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) { 1524e7145dcbSDimitry Andric auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl()); 1525e7145dcbSDimitry Andric if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) { 15260623d748SDimitry Andric llvm::MDBuilder MDHelper(getLLVMContext()); 15270623d748SDimitry Andric Unpredictable = MDHelper.createUnpredictable(); 15280623d748SDimitry Andric } 15290623d748SDimitry Andric } 15300623d748SDimitry Andric 153159d1ed5bSDimitry Andric // Create branch weights based on the number of times we get here and the 153259d1ed5bSDimitry Andric // number of times the condition should be true. 153333956c43SDimitry Andric uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount); 153433956c43SDimitry Andric llvm::MDNode *Weights = 153533956c43SDimitry Andric createProfileWeights(TrueCount, CurrentCount - TrueCount); 153659d1ed5bSDimitry Andric 1537f22ef01cSRoman Divacky // Emit the code with the fully general case. 153833956c43SDimitry Andric llvm::Value *CondV; 153933956c43SDimitry Andric { 154033956c43SDimitry Andric ApplyDebugLocation DL(*this, Cond); 154133956c43SDimitry Andric CondV = EvaluateExprAsBool(Cond); 154233956c43SDimitry Andric } 15430623d748SDimitry Andric Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable); 1544f22ef01cSRoman Divacky } 1545f22ef01cSRoman Divacky 1546f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 1547f22ef01cSRoman Divacky /// specified stmt yet. 1548f785676fSDimitry Andric void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) { 1549f785676fSDimitry Andric CGM.ErrorUnsupported(S, Type); 1550f22ef01cSRoman Divacky } 1551f22ef01cSRoman Divacky 15522754fe60SDimitry Andric /// emitNonZeroVLAInit - Emit the "zero" initialization of a 15532754fe60SDimitry Andric /// variable-length array whose elements have a non-zero bit-pattern. 15542754fe60SDimitry Andric /// 15557ae0e2c9SDimitry Andric /// \param baseType the inner-most element type of the array 15562754fe60SDimitry Andric /// \param src - a char* pointing to the bit-pattern for a single 15572754fe60SDimitry Andric /// base element of the array 15582754fe60SDimitry Andric /// \param sizeInChars - the total size of the VLA, in chars 15592754fe60SDimitry Andric static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, 15600623d748SDimitry Andric Address dest, Address src, 15612754fe60SDimitry Andric llvm::Value *sizeInChars) { 15622754fe60SDimitry Andric CGBuilderTy &Builder = CGF.Builder; 15632754fe60SDimitry Andric 15640623d748SDimitry Andric CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType); 15652754fe60SDimitry Andric llvm::Value *baseSizeInChars 15660623d748SDimitry Andric = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity()); 15672754fe60SDimitry Andric 15680623d748SDimitry Andric Address begin = 15690623d748SDimitry Andric Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin"); 15700623d748SDimitry Andric llvm::Value *end = 15710623d748SDimitry Andric Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end"); 15722754fe60SDimitry Andric 15732754fe60SDimitry Andric llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock(); 15742754fe60SDimitry Andric llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop"); 15752754fe60SDimitry Andric llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont"); 15762754fe60SDimitry Andric 15772754fe60SDimitry Andric // Make a loop over the VLA. C99 guarantees that the VLA element 15782754fe60SDimitry Andric // count must be nonzero. 15792754fe60SDimitry Andric CGF.EmitBlock(loopBB); 15802754fe60SDimitry Andric 15810623d748SDimitry Andric llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur"); 15820623d748SDimitry Andric cur->addIncoming(begin.getPointer(), originBB); 15830623d748SDimitry Andric 15840623d748SDimitry Andric CharUnits curAlign = 15850623d748SDimitry Andric dest.getAlignment().alignmentOfArrayElement(baseSize); 15862754fe60SDimitry Andric 15872754fe60SDimitry Andric // memcpy the individual element bit-pattern. 15880623d748SDimitry Andric Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars, 15892754fe60SDimitry Andric /*volatile*/ false); 15902754fe60SDimitry Andric 15912754fe60SDimitry Andric // Go to the next element. 15920623d748SDimitry Andric llvm::Value *next = 15930623d748SDimitry Andric Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next"); 15942754fe60SDimitry Andric 15952754fe60SDimitry Andric // Leave if that's the end of the VLA. 15962754fe60SDimitry Andric llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone"); 15972754fe60SDimitry Andric Builder.CreateCondBr(done, contBB, loopBB); 15982754fe60SDimitry Andric cur->addIncoming(next, loopBB); 15992754fe60SDimitry Andric 16002754fe60SDimitry Andric CGF.EmitBlock(contBB); 16012754fe60SDimitry Andric } 16022754fe60SDimitry Andric 1603f22ef01cSRoman Divacky void 16040623d748SDimitry Andric CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) { 1605f22ef01cSRoman Divacky // Ignore empty classes in C++. 16063861d79fSDimitry Andric if (getLangOpts().CPlusPlus) { 1607f22ef01cSRoman Divacky if (const RecordType *RT = Ty->getAs<RecordType>()) { 1608f22ef01cSRoman Divacky if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty()) 1609f22ef01cSRoman Divacky return; 1610f22ef01cSRoman Divacky } 1611f22ef01cSRoman Divacky } 1612f22ef01cSRoman Divacky 1613e580952dSDimitry Andric // Cast the dest ptr to the appropriate i8 pointer type. 16140623d748SDimitry Andric if (DestPtr.getElementType() != Int8Ty) 16150623d748SDimitry Andric DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty); 1616f22ef01cSRoman Divacky 1617f22ef01cSRoman Divacky // Get size and alignment info for this aggregate. 16180623d748SDimitry Andric CharUnits size = getContext().getTypeSizeInChars(Ty); 16192754fe60SDimitry Andric 16202754fe60SDimitry Andric llvm::Value *SizeVal; 16212754fe60SDimitry Andric const VariableArrayType *vla; 1622f22ef01cSRoman Divacky 1623f22ef01cSRoman Divacky // Don't bother emitting a zero-byte memset. 16240623d748SDimitry Andric if (size.isZero()) { 16252754fe60SDimitry Andric // But note that getTypeInfo returns 0 for a VLA. 16262754fe60SDimitry Andric if (const VariableArrayType *vlaType = 16272754fe60SDimitry Andric dyn_cast_or_null<VariableArrayType>( 16282754fe60SDimitry Andric getContext().getAsArrayType(Ty))) { 162917a519f9SDimitry Andric QualType eltType; 163017a519f9SDimitry Andric llvm::Value *numElts; 163159d1ed5bSDimitry Andric std::tie(numElts, eltType) = getVLASize(vlaType); 163217a519f9SDimitry Andric 163317a519f9SDimitry Andric SizeVal = numElts; 163417a519f9SDimitry Andric CharUnits eltSize = getContext().getTypeSizeInChars(eltType); 163517a519f9SDimitry Andric if (!eltSize.isOne()) 163617a519f9SDimitry Andric SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize)); 16372754fe60SDimitry Andric vla = vlaType; 16382754fe60SDimitry Andric } else { 1639f22ef01cSRoman Divacky return; 16402754fe60SDimitry Andric } 16412754fe60SDimitry Andric } else { 16420623d748SDimitry Andric SizeVal = CGM.getSize(size); 164359d1ed5bSDimitry Andric vla = nullptr; 16442754fe60SDimitry Andric } 1645e580952dSDimitry Andric 1646e580952dSDimitry Andric // If the type contains a pointer to data member we can't memset it to zero. 1647e580952dSDimitry Andric // Instead, create a null constant and copy it to the destination. 16482754fe60SDimitry Andric // TODO: there are other patterns besides zero that we can usefully memset, 16492754fe60SDimitry Andric // like -1, which happens to be the pattern used by member-pointers. 1650e580952dSDimitry Andric if (!CGM.getTypes().isZeroInitializable(Ty)) { 16512754fe60SDimitry Andric // For a VLA, emit a single element, then splat that over the VLA. 16522754fe60SDimitry Andric if (vla) Ty = getContext().getBaseElementType(vla); 16532754fe60SDimitry Andric 1654e580952dSDimitry Andric llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty); 1655e580952dSDimitry Andric 1656e580952dSDimitry Andric llvm::GlobalVariable *NullVariable = 1657e580952dSDimitry Andric new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(), 1658e580952dSDimitry Andric /*isConstant=*/true, 1659e580952dSDimitry Andric llvm::GlobalVariable::PrivateLinkage, 16606122f3e6SDimitry Andric NullConstant, Twine()); 16610623d748SDimitry Andric CharUnits NullAlign = DestPtr.getAlignment(); 16620623d748SDimitry Andric NullVariable->setAlignment(NullAlign.getQuantity()); 16630623d748SDimitry Andric Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()), 16640623d748SDimitry Andric NullAlign); 1665e580952dSDimitry Andric 16662754fe60SDimitry Andric if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal); 1667e580952dSDimitry Andric 1668e580952dSDimitry Andric // Get and call the appropriate llvm.memcpy overload. 16690623d748SDimitry Andric Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false); 1670e580952dSDimitry Andric return; 1671e580952dSDimitry Andric } 1672e580952dSDimitry Andric 1673e580952dSDimitry Andric // Otherwise, just memset the whole thing to zero. This is legal 1674e580952dSDimitry Andric // because in LLVM, all default initializers (other than the ones we just 1675e580952dSDimitry Andric // handled above) are guaranteed to have a bit pattern of all zeros. 16760623d748SDimitry Andric Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false); 1677f22ef01cSRoman Divacky } 1678f22ef01cSRoman Divacky 16792754fe60SDimitry Andric llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) { 1680f22ef01cSRoman Divacky // Make sure that there is a block for the indirect goto. 168159d1ed5bSDimitry Andric if (!IndirectBranch) 1682f22ef01cSRoman Divacky GetIndirectGotoBlock(); 1683f22ef01cSRoman Divacky 1684e580952dSDimitry Andric llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock(); 1685f22ef01cSRoman Divacky 1686f22ef01cSRoman Divacky // Make sure the indirect branch includes all of the address-taken blocks. 1687f22ef01cSRoman Divacky IndirectBranch->addDestination(BB); 1688f22ef01cSRoman Divacky return llvm::BlockAddress::get(CurFn, BB); 1689f22ef01cSRoman Divacky } 1690f22ef01cSRoman Divacky 1691f22ef01cSRoman Divacky llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() { 1692f22ef01cSRoman Divacky // If we already made the indirect branch for indirect goto, return its block. 1693f22ef01cSRoman Divacky if (IndirectBranch) return IndirectBranch->getParent(); 1694f22ef01cSRoman Divacky 16950623d748SDimitry Andric CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto")); 1696f22ef01cSRoman Divacky 1697f22ef01cSRoman Divacky // Create the PHI node that indirect gotos will add entries to. 16983b0f4066SDimitry Andric llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0, 16993b0f4066SDimitry Andric "indirect.goto.dest"); 1700f22ef01cSRoman Divacky 1701f22ef01cSRoman Divacky // Create the indirect branch instruction. 1702f22ef01cSRoman Divacky IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal); 1703f22ef01cSRoman Divacky return IndirectBranch->getParent(); 1704f22ef01cSRoman Divacky } 1705f22ef01cSRoman Divacky 170617a519f9SDimitry Andric /// Computes the length of an array in elements, as well as the base 170717a519f9SDimitry Andric /// element type and a properly-typed first element pointer. 170817a519f9SDimitry Andric llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType, 170917a519f9SDimitry Andric QualType &baseType, 17100623d748SDimitry Andric Address &addr) { 171117a519f9SDimitry Andric const ArrayType *arrayType = origArrayType; 1712f22ef01cSRoman Divacky 171317a519f9SDimitry Andric // If it's a VLA, we have to load the stored size. Note that 171417a519f9SDimitry Andric // this is the size of the VLA in bytes, not its size in elements. 171559d1ed5bSDimitry Andric llvm::Value *numVLAElements = nullptr; 171617a519f9SDimitry Andric if (isa<VariableArrayType>(arrayType)) { 171717a519f9SDimitry Andric numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first; 171817a519f9SDimitry Andric 171917a519f9SDimitry Andric // Walk into all VLAs. This doesn't require changes to addr, 172017a519f9SDimitry Andric // which has type T* where T is the first non-VLA element type. 172117a519f9SDimitry Andric do { 172217a519f9SDimitry Andric QualType elementType = arrayType->getElementType(); 172317a519f9SDimitry Andric arrayType = getContext().getAsArrayType(elementType); 172417a519f9SDimitry Andric 172517a519f9SDimitry Andric // If we only have VLA components, 'addr' requires no adjustment. 172617a519f9SDimitry Andric if (!arrayType) { 172717a519f9SDimitry Andric baseType = elementType; 172817a519f9SDimitry Andric return numVLAElements; 172917a519f9SDimitry Andric } 173017a519f9SDimitry Andric } while (isa<VariableArrayType>(arrayType)); 173117a519f9SDimitry Andric 173217a519f9SDimitry Andric // We get out here only if we find a constant array type 173317a519f9SDimitry Andric // inside the VLA. 1734f22ef01cSRoman Divacky } 1735f22ef01cSRoman Divacky 173617a519f9SDimitry Andric // We have some number of constant-length arrays, so addr should 173717a519f9SDimitry Andric // have LLVM type [M x [N x [...]]]*. Build a GEP that walks 173817a519f9SDimitry Andric // down to the first element of addr. 17396122f3e6SDimitry Andric SmallVector<llvm::Value*, 8> gepIndices; 174017a519f9SDimitry Andric 174117a519f9SDimitry Andric // GEP down to the array type. 174217a519f9SDimitry Andric llvm::ConstantInt *zero = Builder.getInt32(0); 174317a519f9SDimitry Andric gepIndices.push_back(zero); 174417a519f9SDimitry Andric 174517a519f9SDimitry Andric uint64_t countFromCLAs = 1; 17467ae0e2c9SDimitry Andric QualType eltType; 174717a519f9SDimitry Andric 17486122f3e6SDimitry Andric llvm::ArrayType *llvmArrayType = 17490623d748SDimitry Andric dyn_cast<llvm::ArrayType>(addr.getElementType()); 17507ae0e2c9SDimitry Andric while (llvmArrayType) { 175117a519f9SDimitry Andric assert(isa<ConstantArrayType>(arrayType)); 175217a519f9SDimitry Andric assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue() 175317a519f9SDimitry Andric == llvmArrayType->getNumElements()); 175417a519f9SDimitry Andric 175517a519f9SDimitry Andric gepIndices.push_back(zero); 175617a519f9SDimitry Andric countFromCLAs *= llvmArrayType->getNumElements(); 17577ae0e2c9SDimitry Andric eltType = arrayType->getElementType(); 175817a519f9SDimitry Andric 175917a519f9SDimitry Andric llvmArrayType = 176017a519f9SDimitry Andric dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType()); 176117a519f9SDimitry Andric arrayType = getContext().getAsArrayType(arrayType->getElementType()); 17627ae0e2c9SDimitry Andric assert((!llvmArrayType || arrayType) && 17637ae0e2c9SDimitry Andric "LLVM and Clang types are out-of-synch"); 176417a519f9SDimitry Andric } 176517a519f9SDimitry Andric 17667ae0e2c9SDimitry Andric if (arrayType) { 17677ae0e2c9SDimitry Andric // From this point onwards, the Clang array type has been emitted 17687ae0e2c9SDimitry Andric // as some other type (probably a packed struct). Compute the array 17697ae0e2c9SDimitry Andric // size, and just emit the 'begin' expression as a bitcast. 17707ae0e2c9SDimitry Andric while (arrayType) { 17717ae0e2c9SDimitry Andric countFromCLAs *= 17727ae0e2c9SDimitry Andric cast<ConstantArrayType>(arrayType)->getSize().getZExtValue(); 17737ae0e2c9SDimitry Andric eltType = arrayType->getElementType(); 17747ae0e2c9SDimitry Andric arrayType = getContext().getAsArrayType(eltType); 17757ae0e2c9SDimitry Andric } 177617a519f9SDimitry Andric 17770623d748SDimitry Andric llvm::Type *baseType = ConvertType(eltType); 17780623d748SDimitry Andric addr = Builder.CreateElementBitCast(addr, baseType, "array.begin"); 17797ae0e2c9SDimitry Andric } else { 178017a519f9SDimitry Andric // Create the actual GEP. 17810623d748SDimitry Andric addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(), 17820623d748SDimitry Andric gepIndices, "array.begin"), 17830623d748SDimitry Andric addr.getAlignment()); 17847ae0e2c9SDimitry Andric } 17857ae0e2c9SDimitry Andric 17867ae0e2c9SDimitry Andric baseType = eltType; 178717a519f9SDimitry Andric 178817a519f9SDimitry Andric llvm::Value *numElements 178917a519f9SDimitry Andric = llvm::ConstantInt::get(SizeTy, countFromCLAs); 179017a519f9SDimitry Andric 179117a519f9SDimitry Andric // If we had any VLA dimensions, factor them in. 179217a519f9SDimitry Andric if (numVLAElements) 179317a519f9SDimitry Andric numElements = Builder.CreateNUWMul(numVLAElements, numElements); 179417a519f9SDimitry Andric 179517a519f9SDimitry Andric return numElements; 179617a519f9SDimitry Andric } 179717a519f9SDimitry Andric 179817a519f9SDimitry Andric std::pair<llvm::Value*, QualType> 179917a519f9SDimitry Andric CodeGenFunction::getVLASize(QualType type) { 180017a519f9SDimitry Andric const VariableArrayType *vla = getContext().getAsVariableArrayType(type); 180117a519f9SDimitry Andric assert(vla && "type was not a variable array type!"); 180217a519f9SDimitry Andric return getVLASize(vla); 180317a519f9SDimitry Andric } 180417a519f9SDimitry Andric 180517a519f9SDimitry Andric std::pair<llvm::Value*, QualType> 180617a519f9SDimitry Andric CodeGenFunction::getVLASize(const VariableArrayType *type) { 180717a519f9SDimitry Andric // The number of elements so far; always size_t. 180859d1ed5bSDimitry Andric llvm::Value *numElements = nullptr; 180917a519f9SDimitry Andric 181017a519f9SDimitry Andric QualType elementType; 181117a519f9SDimitry Andric do { 181217a519f9SDimitry Andric elementType = type->getElementType(); 181317a519f9SDimitry Andric llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()]; 181417a519f9SDimitry Andric assert(vlaSize && "no size for VLA!"); 181517a519f9SDimitry Andric assert(vlaSize->getType() == SizeTy); 181617a519f9SDimitry Andric 181717a519f9SDimitry Andric if (!numElements) { 181817a519f9SDimitry Andric numElements = vlaSize; 181917a519f9SDimitry Andric } else { 182017a519f9SDimitry Andric // It's undefined behavior if this wraps around, so mark it that way. 182159d1ed5bSDimitry Andric // FIXME: Teach -fsanitize=undefined to trap this. 182217a519f9SDimitry Andric numElements = Builder.CreateNUWMul(numElements, vlaSize); 182317a519f9SDimitry Andric } 182417a519f9SDimitry Andric } while ((type = getContext().getAsVariableArrayType(elementType))); 182517a519f9SDimitry Andric 182617a519f9SDimitry Andric return std::pair<llvm::Value*,QualType>(numElements, elementType); 182717a519f9SDimitry Andric } 182817a519f9SDimitry Andric 182917a519f9SDimitry Andric void CodeGenFunction::EmitVariablyModifiedType(QualType type) { 183017a519f9SDimitry Andric assert(type->isVariablyModifiedType() && 1831f22ef01cSRoman Divacky "Must pass variably modified type to EmitVLASizes!"); 1832f22ef01cSRoman Divacky 1833f22ef01cSRoman Divacky EnsureInsertPoint(); 1834f22ef01cSRoman Divacky 183517a519f9SDimitry Andric // We're going to walk down into the type and look for VLA 183617a519f9SDimitry Andric // expressions. 183717a519f9SDimitry Andric do { 183817a519f9SDimitry Andric assert(type->isVariablyModifiedType()); 1839f22ef01cSRoman Divacky 184017a519f9SDimitry Andric const Type *ty = type.getTypePtr(); 184117a519f9SDimitry Andric switch (ty->getTypeClass()) { 1842dff0c46cSDimitry Andric 184317a519f9SDimitry Andric #define TYPE(Class, Base) 184417a519f9SDimitry Andric #define ABSTRACT_TYPE(Class, Base) 1845dff0c46cSDimitry Andric #define NON_CANONICAL_TYPE(Class, Base) 184617a519f9SDimitry Andric #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1847dff0c46cSDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 184817a519f9SDimitry Andric #include "clang/AST/TypeNodes.def" 1849dff0c46cSDimitry Andric llvm_unreachable("unexpected dependent type!"); 1850f22ef01cSRoman Divacky 185117a519f9SDimitry Andric // These types are never variably-modified. 185217a519f9SDimitry Andric case Type::Builtin: 185317a519f9SDimitry Andric case Type::Complex: 185417a519f9SDimitry Andric case Type::Vector: 185517a519f9SDimitry Andric case Type::ExtVector: 185617a519f9SDimitry Andric case Type::Record: 185717a519f9SDimitry Andric case Type::Enum: 1858dff0c46cSDimitry Andric case Type::Elaborated: 1859dff0c46cSDimitry Andric case Type::TemplateSpecialization: 186044290647SDimitry Andric case Type::ObjCTypeParam: 186117a519f9SDimitry Andric case Type::ObjCObject: 186217a519f9SDimitry Andric case Type::ObjCInterface: 186317a519f9SDimitry Andric case Type::ObjCObjectPointer: 186417a519f9SDimitry Andric llvm_unreachable("type class is never variably-modified!"); 1865f22ef01cSRoman Divacky 186659d1ed5bSDimitry Andric case Type::Adjusted: 186759d1ed5bSDimitry Andric type = cast<AdjustedType>(ty)->getAdjustedType(); 186859d1ed5bSDimitry Andric break; 186959d1ed5bSDimitry Andric 1870f785676fSDimitry Andric case Type::Decayed: 1871f785676fSDimitry Andric type = cast<DecayedType>(ty)->getPointeeType(); 1872f785676fSDimitry Andric break; 1873f785676fSDimitry Andric 187417a519f9SDimitry Andric case Type::Pointer: 187517a519f9SDimitry Andric type = cast<PointerType>(ty)->getPointeeType(); 187617a519f9SDimitry Andric break; 1877f22ef01cSRoman Divacky 187817a519f9SDimitry Andric case Type::BlockPointer: 187917a519f9SDimitry Andric type = cast<BlockPointerType>(ty)->getPointeeType(); 188017a519f9SDimitry Andric break; 188117a519f9SDimitry Andric 188217a519f9SDimitry Andric case Type::LValueReference: 188317a519f9SDimitry Andric case Type::RValueReference: 188417a519f9SDimitry Andric type = cast<ReferenceType>(ty)->getPointeeType(); 188517a519f9SDimitry Andric break; 188617a519f9SDimitry Andric 188717a519f9SDimitry Andric case Type::MemberPointer: 188817a519f9SDimitry Andric type = cast<MemberPointerType>(ty)->getPointeeType(); 188917a519f9SDimitry Andric break; 189017a519f9SDimitry Andric 189117a519f9SDimitry Andric case Type::ConstantArray: 189217a519f9SDimitry Andric case Type::IncompleteArray: 189317a519f9SDimitry Andric // Losing element qualification here is fine. 189417a519f9SDimitry Andric type = cast<ArrayType>(ty)->getElementType(); 189517a519f9SDimitry Andric break; 189617a519f9SDimitry Andric 189717a519f9SDimitry Andric case Type::VariableArray: { 189817a519f9SDimitry Andric // Losing element qualification here is fine. 189917a519f9SDimitry Andric const VariableArrayType *vat = cast<VariableArrayType>(ty); 190017a519f9SDimitry Andric 190117a519f9SDimitry Andric // Unknown size indication requires no size computation. 190217a519f9SDimitry Andric // Otherwise, evaluate and record it. 190317a519f9SDimitry Andric if (const Expr *size = vat->getSizeExpr()) { 190417a519f9SDimitry Andric // It's possible that we might have emitted this already, 190517a519f9SDimitry Andric // e.g. with a typedef and a pointer to it. 190617a519f9SDimitry Andric llvm::Value *&entry = VLASizeMap[size]; 190717a519f9SDimitry Andric if (!entry) { 19083861d79fSDimitry Andric llvm::Value *Size = EmitScalarExpr(size); 19093861d79fSDimitry Andric 19103861d79fSDimitry Andric // C11 6.7.6.2p5: 19113861d79fSDimitry Andric // If the size is an expression that is not an integer constant 19123861d79fSDimitry Andric // expression [...] each time it is evaluated it shall have a value 19133861d79fSDimitry Andric // greater than zero. 191439d628a0SDimitry Andric if (SanOpts.has(SanitizerKind::VLABound) && 19153861d79fSDimitry Andric size->getType()->isSignedIntegerType()) { 191659d1ed5bSDimitry Andric SanitizerScope SanScope(this); 19173861d79fSDimitry Andric llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType()); 19183861d79fSDimitry Andric llvm::Constant *StaticArgs[] = { 19193861d79fSDimitry Andric EmitCheckSourceLocation(size->getLocStart()), 19203861d79fSDimitry Andric EmitCheckTypeDescriptor(size->getType()) 19213861d79fSDimitry Andric }; 192239d628a0SDimitry Andric EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero), 192339d628a0SDimitry Andric SanitizerKind::VLABound), 192444290647SDimitry Andric SanitizerHandler::VLABoundNotPositive, StaticArgs, Size); 19253861d79fSDimitry Andric } 19263861d79fSDimitry Andric 192717a519f9SDimitry Andric // Always zexting here would be wrong if it weren't 192817a519f9SDimitry Andric // undefined behavior to have a negative bound. 19293861d79fSDimitry Andric entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false); 193017a519f9SDimitry Andric } 193117a519f9SDimitry Andric } 193217a519f9SDimitry Andric type = vat->getElementType(); 193317a519f9SDimitry Andric break; 1934f22ef01cSRoman Divacky } 1935f22ef01cSRoman Divacky 193617a519f9SDimitry Andric case Type::FunctionProto: 193717a519f9SDimitry Andric case Type::FunctionNoProto: 193859d1ed5bSDimitry Andric type = cast<FunctionType>(ty)->getReturnType(); 193917a519f9SDimitry Andric break; 19406122f3e6SDimitry Andric 1941dff0c46cSDimitry Andric case Type::Paren: 1942dff0c46cSDimitry Andric case Type::TypeOf: 1943dff0c46cSDimitry Andric case Type::UnaryTransform: 1944dff0c46cSDimitry Andric case Type::Attributed: 1945dff0c46cSDimitry Andric case Type::SubstTemplateTypeParm: 1946f785676fSDimitry Andric case Type::PackExpansion: 1947dff0c46cSDimitry Andric // Keep walking after single level desugaring. 1948dff0c46cSDimitry Andric type = type.getSingleStepDesugaredType(getContext()); 1949dff0c46cSDimitry Andric break; 1950dff0c46cSDimitry Andric 1951dff0c46cSDimitry Andric case Type::Typedef: 1952dff0c46cSDimitry Andric case Type::Decltype: 1953dff0c46cSDimitry Andric case Type::Auto: 195420e90f04SDimitry Andric case Type::DeducedTemplateSpecialization: 1955dff0c46cSDimitry Andric // Stop walking: nothing to do. 1956dff0c46cSDimitry Andric return; 1957dff0c46cSDimitry Andric 1958dff0c46cSDimitry Andric case Type::TypeOfExpr: 1959dff0c46cSDimitry Andric // Stop walking: emit typeof expression. 1960dff0c46cSDimitry Andric EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr()); 1961dff0c46cSDimitry Andric return; 1962dff0c46cSDimitry Andric 19636122f3e6SDimitry Andric case Type::Atomic: 19646122f3e6SDimitry Andric type = cast<AtomicType>(ty)->getValueType(); 19656122f3e6SDimitry Andric break; 1966444ed5c5SDimitry Andric 1967444ed5c5SDimitry Andric case Type::Pipe: 1968444ed5c5SDimitry Andric type = cast<PipeType>(ty)->getElementType(); 1969444ed5c5SDimitry Andric break; 1970f22ef01cSRoman Divacky } 197117a519f9SDimitry Andric } while (type->isVariablyModifiedType()); 1972f22ef01cSRoman Divacky } 1973f22ef01cSRoman Divacky 19740623d748SDimitry Andric Address CodeGenFunction::EmitVAListRef(const Expr* E) { 19752754fe60SDimitry Andric if (getContext().getBuiltinVaListType()->isArrayType()) 19760623d748SDimitry Andric return EmitPointerWithAlignment(E); 19770623d748SDimitry Andric return EmitLValue(E).getAddress(); 19780623d748SDimitry Andric } 19790623d748SDimitry Andric 19800623d748SDimitry Andric Address CodeGenFunction::EmitMSVAListRef(const Expr *E) { 1981f22ef01cSRoman Divacky return EmitLValue(E).getAddress(); 1982f22ef01cSRoman Divacky } 1983f22ef01cSRoman Divacky 1984e580952dSDimitry Andric void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E, 198544290647SDimitry Andric const APValue &Init) { 198644290647SDimitry Andric assert(!Init.isUninit() && "Invalid DeclRefExpr initializer!"); 1987e580952dSDimitry Andric if (CGDebugInfo *Dbg = getDebugInfo()) 1988e7145dcbSDimitry Andric if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 19892754fe60SDimitry Andric Dbg->EmitGlobalVariable(E->getDecl(), Init); 19902754fe60SDimitry Andric } 19912754fe60SDimitry Andric 19922754fe60SDimitry Andric CodeGenFunction::PeepholeProtection 19932754fe60SDimitry Andric CodeGenFunction::protectFromPeepholes(RValue rvalue) { 19942754fe60SDimitry Andric // At the moment, the only aggressive peephole we do in IR gen 19952754fe60SDimitry Andric // is trunc(zext) folding, but if we add more, we can easily 19962754fe60SDimitry Andric // extend this protection. 19972754fe60SDimitry Andric 19982754fe60SDimitry Andric if (!rvalue.isScalar()) return PeepholeProtection(); 19992754fe60SDimitry Andric llvm::Value *value = rvalue.getScalarVal(); 20002754fe60SDimitry Andric if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection(); 20012754fe60SDimitry Andric 20022754fe60SDimitry Andric // Just make an extra bitcast. 20032754fe60SDimitry Andric assert(HaveInsertPoint()); 20042754fe60SDimitry Andric llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "", 20052754fe60SDimitry Andric Builder.GetInsertBlock()); 20062754fe60SDimitry Andric 20072754fe60SDimitry Andric PeepholeProtection protection; 20082754fe60SDimitry Andric protection.Inst = inst; 20092754fe60SDimitry Andric return protection; 20102754fe60SDimitry Andric } 20112754fe60SDimitry Andric 20122754fe60SDimitry Andric void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) { 20132754fe60SDimitry Andric if (!protection.Inst) return; 20142754fe60SDimitry Andric 20152754fe60SDimitry Andric // In theory, we could try to duplicate the peepholes now, but whatever. 20162754fe60SDimitry Andric protection.Inst->eraseFromParent(); 2017e580952dSDimitry Andric } 20186122f3e6SDimitry Andric 20196122f3e6SDimitry Andric llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn, 20206122f3e6SDimitry Andric llvm::Value *AnnotatedVal, 2021139f7f9bSDimitry Andric StringRef AnnotationStr, 20226122f3e6SDimitry Andric SourceLocation Location) { 20236122f3e6SDimitry Andric llvm::Value *Args[4] = { 20246122f3e6SDimitry Andric AnnotatedVal, 20256122f3e6SDimitry Andric Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy), 20266122f3e6SDimitry Andric Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy), 20276122f3e6SDimitry Andric CGM.EmitAnnotationLineNo(Location) 20286122f3e6SDimitry Andric }; 20296122f3e6SDimitry Andric return Builder.CreateCall(AnnotationFn, Args); 20306122f3e6SDimitry Andric } 20316122f3e6SDimitry Andric 20326122f3e6SDimitry Andric void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) { 20336122f3e6SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 20346122f3e6SDimitry Andric // FIXME We create a new bitcast for every annotation because that's what 20356122f3e6SDimitry Andric // llvm-gcc was doing. 203659d1ed5bSDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) 20376122f3e6SDimitry Andric EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation), 20386122f3e6SDimitry Andric Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()), 203959d1ed5bSDimitry Andric I->getAnnotation(), D->getLocation()); 20406122f3e6SDimitry Andric } 20416122f3e6SDimitry Andric 20420623d748SDimitry Andric Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D, 20430623d748SDimitry Andric Address Addr) { 20446122f3e6SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 20450623d748SDimitry Andric llvm::Value *V = Addr.getPointer(); 20466122f3e6SDimitry Andric llvm::Type *VTy = V->getType(); 20476122f3e6SDimitry Andric llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, 20486122f3e6SDimitry Andric CGM.Int8PtrTy); 20496122f3e6SDimitry Andric 205059d1ed5bSDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) { 20516122f3e6SDimitry Andric // FIXME Always emit the cast inst so we can differentiate between 20526122f3e6SDimitry Andric // annotation on the first field of a struct and annotation on the struct 20536122f3e6SDimitry Andric // itself. 20546122f3e6SDimitry Andric if (VTy != CGM.Int8PtrTy) 20556122f3e6SDimitry Andric V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy)); 205659d1ed5bSDimitry Andric V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation()); 20576122f3e6SDimitry Andric V = Builder.CreateBitCast(V, VTy); 20586122f3e6SDimitry Andric } 20596122f3e6SDimitry Andric 20600623d748SDimitry Andric return Address(V, Addr.getAlignment()); 20616122f3e6SDimitry Andric } 2062f785676fSDimitry Andric 2063f785676fSDimitry Andric CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { } 206459d1ed5bSDimitry Andric 206559d1ed5bSDimitry Andric CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF) 206659d1ed5bSDimitry Andric : CGF(CGF) { 206759d1ed5bSDimitry Andric assert(!CGF->IsSanitizerScope); 206859d1ed5bSDimitry Andric CGF->IsSanitizerScope = true; 206959d1ed5bSDimitry Andric } 207059d1ed5bSDimitry Andric 207159d1ed5bSDimitry Andric CodeGenFunction::SanitizerScope::~SanitizerScope() { 207259d1ed5bSDimitry Andric CGF->IsSanitizerScope = false; 207359d1ed5bSDimitry Andric } 207459d1ed5bSDimitry Andric 207559d1ed5bSDimitry Andric void CodeGenFunction::InsertHelper(llvm::Instruction *I, 207659d1ed5bSDimitry Andric const llvm::Twine &Name, 207759d1ed5bSDimitry Andric llvm::BasicBlock *BB, 207859d1ed5bSDimitry Andric llvm::BasicBlock::iterator InsertPt) const { 207959d1ed5bSDimitry Andric LoopStack.InsertHelper(I); 208039d628a0SDimitry Andric if (IsSanitizerScope) 208139d628a0SDimitry Andric CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I); 208259d1ed5bSDimitry Andric } 208359d1ed5bSDimitry Andric 2084e7145dcbSDimitry Andric void CGBuilderInserter::InsertHelper( 208559d1ed5bSDimitry Andric llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, 208659d1ed5bSDimitry Andric llvm::BasicBlock::iterator InsertPt) const { 2087e7145dcbSDimitry Andric llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt); 208859d1ed5bSDimitry Andric if (CGF) 208959d1ed5bSDimitry Andric CGF->InsertHelper(I, Name, BB, InsertPt); 209059d1ed5bSDimitry Andric } 209159d1ed5bSDimitry Andric 20920623d748SDimitry Andric static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures, 20930623d748SDimitry Andric CodeGenModule &CGM, const FunctionDecl *FD, 20940623d748SDimitry Andric std::string &FirstMissing) { 20950623d748SDimitry Andric // If there aren't any required features listed then go ahead and return. 20960623d748SDimitry Andric if (ReqFeatures.empty()) 20970623d748SDimitry Andric return false; 20980623d748SDimitry Andric 20990623d748SDimitry Andric // Now build up the set of caller features and verify that all the required 21000623d748SDimitry Andric // features are there. 21010623d748SDimitry Andric llvm::StringMap<bool> CallerFeatureMap; 21020623d748SDimitry Andric CGM.getFunctionFeatureMap(CallerFeatureMap, FD); 21030623d748SDimitry Andric 21040623d748SDimitry Andric // If we have at least one of the features in the feature list return 21050623d748SDimitry Andric // true, otherwise return false. 21060623d748SDimitry Andric return std::all_of( 21070623d748SDimitry Andric ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) { 21080623d748SDimitry Andric SmallVector<StringRef, 1> OrFeatures; 21090623d748SDimitry Andric Feature.split(OrFeatures, "|"); 21100623d748SDimitry Andric return std::any_of(OrFeatures.begin(), OrFeatures.end(), 21110623d748SDimitry Andric [&](StringRef Feature) { 21120623d748SDimitry Andric if (!CallerFeatureMap.lookup(Feature)) { 21130623d748SDimitry Andric FirstMissing = Feature.str(); 21140623d748SDimitry Andric return false; 21150623d748SDimitry Andric } 21160623d748SDimitry Andric return true; 21170623d748SDimitry Andric }); 21180623d748SDimitry Andric }); 21190623d748SDimitry Andric } 21200623d748SDimitry Andric 21210623d748SDimitry Andric // Emits an error if we don't have a valid set of target features for the 21220623d748SDimitry Andric // called function. 21230623d748SDimitry Andric void CodeGenFunction::checkTargetFeatures(const CallExpr *E, 21240623d748SDimitry Andric const FunctionDecl *TargetDecl) { 21250623d748SDimitry Andric // Early exit if this is an indirect call. 21260623d748SDimitry Andric if (!TargetDecl) 21270623d748SDimitry Andric return; 21280623d748SDimitry Andric 21290623d748SDimitry Andric // Get the current enclosing function if it exists. If it doesn't 21300623d748SDimitry Andric // we can't check the target features anyhow. 21310623d748SDimitry Andric const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl); 21320623d748SDimitry Andric if (!FD) 21330623d748SDimitry Andric return; 21340623d748SDimitry Andric 21350623d748SDimitry Andric // Grab the required features for the call. For a builtin this is listed in 21360623d748SDimitry Andric // the td file with the default cpu, for an always_inline function this is any 21370623d748SDimitry Andric // listed cpu and any listed features. 21380623d748SDimitry Andric unsigned BuiltinID = TargetDecl->getBuiltinID(); 21390623d748SDimitry Andric std::string MissingFeature; 21400623d748SDimitry Andric if (BuiltinID) { 21410623d748SDimitry Andric SmallVector<StringRef, 1> ReqFeatures; 21420623d748SDimitry Andric const char *FeatureList = 21430623d748SDimitry Andric CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID); 21440623d748SDimitry Andric // Return if the builtin doesn't have any required features. 21450623d748SDimitry Andric if (!FeatureList || StringRef(FeatureList) == "") 21460623d748SDimitry Andric return; 21470623d748SDimitry Andric StringRef(FeatureList).split(ReqFeatures, ","); 21480623d748SDimitry Andric if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature)) 21490623d748SDimitry Andric CGM.getDiags().Report(E->getLocStart(), diag::err_builtin_needs_feature) 21500623d748SDimitry Andric << TargetDecl->getDeclName() 21510623d748SDimitry Andric << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID); 21520623d748SDimitry Andric 21530623d748SDimitry Andric } else if (TargetDecl->hasAttr<TargetAttr>()) { 21540623d748SDimitry Andric // Get the required features for the callee. 21550623d748SDimitry Andric SmallVector<StringRef, 1> ReqFeatures; 21560623d748SDimitry Andric llvm::StringMap<bool> CalleeFeatureMap; 21570623d748SDimitry Andric CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl); 21580623d748SDimitry Andric for (const auto &F : CalleeFeatureMap) { 21590623d748SDimitry Andric // Only positive features are "required". 21600623d748SDimitry Andric if (F.getValue()) 21610623d748SDimitry Andric ReqFeatures.push_back(F.getKey()); 21620623d748SDimitry Andric } 21630623d748SDimitry Andric if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature)) 21640623d748SDimitry Andric CGM.getDiags().Report(E->getLocStart(), diag::err_function_needs_feature) 21650623d748SDimitry Andric << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature; 21660623d748SDimitry Andric } 21670623d748SDimitry Andric } 2168e7145dcbSDimitry Andric 2169e7145dcbSDimitry Andric void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) { 2170e7145dcbSDimitry Andric if (!CGM.getCodeGenOpts().SanitizeStats) 2171e7145dcbSDimitry Andric return; 2172e7145dcbSDimitry Andric 2173e7145dcbSDimitry Andric llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint()); 2174e7145dcbSDimitry Andric IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation()); 2175e7145dcbSDimitry Andric CGM.getSanStats().create(IRB, SSK); 2176e7145dcbSDimitry Andric } 217744290647SDimitry Andric 217844290647SDimitry Andric llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) { 217944290647SDimitry Andric if (CGDebugInfo *DI = getDebugInfo()) 218044290647SDimitry Andric return DI->SourceLocToDebugLoc(Location); 218144290647SDimitry Andric 218244290647SDimitry Andric return llvm::DebugLoc(); 218344290647SDimitry Andric } 2184