1f22ef01cSRoman Divacky //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===// 2f22ef01cSRoman Divacky // 3f22ef01cSRoman Divacky // The LLVM Compiler Infrastructure 4f22ef01cSRoman Divacky // 5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source 6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details. 7f22ef01cSRoman Divacky // 8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 9f22ef01cSRoman Divacky // 10f22ef01cSRoman Divacky // This coordinates the per-function state used while generating code. 11f22ef01cSRoman Divacky // 12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 13f22ef01cSRoman Divacky 14f22ef01cSRoman Divacky #include "CodeGenFunction.h" 150623d748SDimitry Andric #include "CGBlocks.h" 1633956c43SDimitry Andric #include "CGCleanup.h" 176122f3e6SDimitry Andric #include "CGCUDARuntime.h" 18e580952dSDimitry Andric #include "CGCXXABI.h" 19f22ef01cSRoman Divacky #include "CGDebugInfo.h" 2059d1ed5bSDimitry Andric #include "CGOpenMPRuntime.h" 21139f7f9bSDimitry Andric #include "CodeGenModule.h" 2259d1ed5bSDimitry Andric #include "CodeGenPGO.h" 23f785676fSDimitry Andric #include "TargetInfo.h" 24f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h" 25f22ef01cSRoman Divacky #include "clang/AST/Decl.h" 26f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h" 27f22ef01cSRoman Divacky #include "clang/AST/StmtCXX.h" 28f41fbc90SDimitry Andric #include "clang/AST/StmtObjC.h" 290623d748SDimitry Andric #include "clang/Basic/Builtins.h" 30139f7f9bSDimitry Andric #include "clang/Basic/TargetInfo.h" 31f785676fSDimitry Andric #include "clang/CodeGen/CGFunctionInfo.h" 32ffd1746dSEd Schouten #include "clang/Frontend/CodeGenOptions.h" 330623d748SDimitry Andric #include "clang/Sema/SemaDiagnostic.h" 34139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h" 35139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h" 36139f7f9bSDimitry Andric #include "llvm/IR/MDBuilder.h" 37139f7f9bSDimitry Andric #include "llvm/IR/Operator.h" 38f22ef01cSRoman Divacky using namespace clang; 39f22ef01cSRoman Divacky using namespace CodeGen; 40f22ef01cSRoman Divacky 4144290647SDimitry Andric /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time 4244290647SDimitry Andric /// markers. 4344290647SDimitry Andric static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts, 4444290647SDimitry Andric const LangOptions &LangOpts) { 4524e2fe98SDimitry Andric if (CGOpts.DisableLifetimeMarkers) 4624e2fe98SDimitry Andric return false; 4724e2fe98SDimitry Andric 4844290647SDimitry Andric // Asan uses markers for use-after-scope checks. 4944290647SDimitry Andric if (CGOpts.SanitizeAddressUseAfterScope) 5044290647SDimitry Andric return true; 5144290647SDimitry Andric 5244290647SDimitry Andric // Disable lifetime markers in msan builds. 5344290647SDimitry Andric // FIXME: Remove this when msan works with lifetime markers. 5444290647SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Memory)) 5544290647SDimitry Andric return false; 5644290647SDimitry Andric 5744290647SDimitry Andric // For now, only in optimized builds. 5844290647SDimitry Andric return CGOpts.OptimizationLevel != 0; 5944290647SDimitry Andric } 6044290647SDimitry Andric 617ae0e2c9SDimitry Andric CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext) 62284c1978SDimitry Andric : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()), 630623d748SDimitry Andric Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(), 6459d1ed5bSDimitry Andric CGBuilderInserterTy(this)), 650623d748SDimitry Andric CurFn(nullptr), ReturnValue(Address::invalid()), 6644290647SDimitry Andric CapturedStmtInfo(nullptr), SanOpts(CGM.getLangOpts().Sanitize), 6744290647SDimitry Andric IsSanitizerScope(false), CurFuncIsThunk(false), AutoreleaseResult(false), 6844290647SDimitry Andric SawAsmBlock(false), IsOutlinedSEHHelper(false), BlockInfo(nullptr), 6944290647SDimitry Andric BlockPointer(nullptr), LambdaThisCaptureField(nullptr), 7044290647SDimitry Andric NormalCleanupDest(nullptr), NextCleanupDestIndex(1), 7144290647SDimitry Andric FirstBlockInfo(nullptr), EHResumeBlock(nullptr), ExceptionSlot(nullptr), 7244290647SDimitry Andric EHSelectorSlot(nullptr), DebugInfo(CGM.getModuleDebugInfo()), 73875ed548SDimitry Andric DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(nullptr), 74875ed548SDimitry Andric PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr), 75875ed548SDimitry Andric CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0), 76875ed548SDimitry Andric NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr), 77875ed548SDimitry Andric CXXABIThisValue(nullptr), CXXThisValue(nullptr), 780623d748SDimitry Andric CXXStructorImplicitParamDecl(nullptr), 7959d1ed5bSDimitry Andric CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr), 8059d1ed5bSDimitry Andric CurLexicalScope(nullptr), TerminateLandingPad(nullptr), 8144290647SDimitry Andric TerminateHandler(nullptr), TrapBB(nullptr), 8244290647SDimitry Andric ShouldEmitLifetimeMarkers( 8344290647SDimitry Andric shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) { 847ae0e2c9SDimitry Andric if (!suppressNewContext) 85e580952dSDimitry Andric CGM.getCXXABI().getMangleContext().startNewFunction(); 86139f7f9bSDimitry Andric 87139f7f9bSDimitry Andric llvm::FastMathFlags FMF; 88139f7f9bSDimitry Andric if (CGM.getLangOpts().FastMath) 89139f7f9bSDimitry Andric FMF.setUnsafeAlgebra(); 90139f7f9bSDimitry Andric if (CGM.getLangOpts().FiniteMathOnly) { 91139f7f9bSDimitry Andric FMF.setNoNaNs(); 92139f7f9bSDimitry Andric FMF.setNoInfs(); 93139f7f9bSDimitry Andric } 9439d628a0SDimitry Andric if (CGM.getCodeGenOpts().NoNaNsFPMath) { 9539d628a0SDimitry Andric FMF.setNoNaNs(); 9639d628a0SDimitry Andric } 9739d628a0SDimitry Andric if (CGM.getCodeGenOpts().NoSignedZeros) { 9839d628a0SDimitry Andric FMF.setNoSignedZeros(); 9939d628a0SDimitry Andric } 10033956c43SDimitry Andric if (CGM.getCodeGenOpts().ReciprocalMath) { 10133956c43SDimitry Andric FMF.setAllowReciprocal(); 10233956c43SDimitry Andric } 103444ed5c5SDimitry Andric Builder.setFastMathFlags(FMF); 104f22ef01cSRoman Divacky } 105f22ef01cSRoman Divacky 106dff0c46cSDimitry Andric CodeGenFunction::~CodeGenFunction() { 107f785676fSDimitry Andric assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup"); 108f785676fSDimitry Andric 109dff0c46cSDimitry Andric // If there are any unclaimed block infos, go ahead and destroy them 110dff0c46cSDimitry Andric // now. This can happen if IR-gen gets clever and skips evaluating 111dff0c46cSDimitry Andric // something. 112dff0c46cSDimitry Andric if (FirstBlockInfo) 113dff0c46cSDimitry Andric destroyBlockInfos(FirstBlockInfo); 11459d1ed5bSDimitry Andric 11598221d2eSDimitry Andric if (getLangOpts().OpenMP && CurFn) 11633956c43SDimitry Andric CGM.getOpenMPRuntime().functionFinished(*this); 11759d1ed5bSDimitry Andric } 118dff0c46cSDimitry Andric 1190623d748SDimitry Andric CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T, 1200623d748SDimitry Andric AlignmentSource *Source) { 1210623d748SDimitry Andric return getNaturalTypeAlignment(T->getPointeeType(), Source, 1220623d748SDimitry Andric /*forPointee*/ true); 1230623d748SDimitry Andric } 1240623d748SDimitry Andric 1250623d748SDimitry Andric CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T, 1260623d748SDimitry Andric AlignmentSource *Source, 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()) { 1330623d748SDimitry Andric if (Source) *Source = AlignmentSource::AttributedType; 1340623d748SDimitry Andric return getContext().toCharUnitsFromBits(Align); 1350623d748SDimitry Andric } 1360623d748SDimitry Andric } 1370623d748SDimitry Andric 1380623d748SDimitry Andric if (Source) *Source = AlignmentSource::Type; 1390623d748SDimitry Andric 14039d628a0SDimitry Andric CharUnits Alignment; 1410623d748SDimitry Andric if (T->isIncompleteType()) { 1420623d748SDimitry Andric Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best. 1430623d748SDimitry Andric } else { 1440623d748SDimitry Andric // For C++ class pointees, we don't know whether we're pointing at a 1450623d748SDimitry Andric // base or a complete object, so we generally need to use the 1460623d748SDimitry Andric // non-virtual alignment. 1470623d748SDimitry Andric const CXXRecordDecl *RD; 1480623d748SDimitry Andric if (forPointeeType && (RD = T->getAsCXXRecordDecl())) { 1490623d748SDimitry Andric Alignment = CGM.getClassPointerAlignment(RD); 1500623d748SDimitry Andric } else { 15139d628a0SDimitry Andric Alignment = getContext().getTypeAlignInChars(T); 1520623d748SDimitry Andric } 1530623d748SDimitry Andric 1540623d748SDimitry Andric // Cap to the global maximum type alignment unless the alignment 1550623d748SDimitry Andric // was somehow explicit on the type. 1560623d748SDimitry Andric if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 1570623d748SDimitry Andric if (Alignment.getQuantity() > MaxAlign && 15839d628a0SDimitry Andric !getContext().isAlignmentRequired(T)) 15939d628a0SDimitry Andric Alignment = CharUnits::fromQuantity(MaxAlign); 16039d628a0SDimitry Andric } 16139d628a0SDimitry Andric } 1620623d748SDimitry Andric return Alignment; 1630623d748SDimitry Andric } 1640623d748SDimitry Andric 1650623d748SDimitry Andric LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) { 1660623d748SDimitry Andric AlignmentSource AlignSource; 1670623d748SDimitry Andric CharUnits Alignment = getNaturalTypeAlignment(T, &AlignSource); 1680623d748SDimitry Andric return LValue::MakeAddr(Address(V, Alignment), T, getContext(), AlignSource, 1690623d748SDimitry Andric CGM.getTBAAInfo(T)); 1700623d748SDimitry Andric } 1710623d748SDimitry Andric 1720623d748SDimitry Andric /// Given a value of type T* that may not be to a complete object, 1730623d748SDimitry Andric /// construct an l-value with the natural pointee alignment of T. 1740623d748SDimitry Andric LValue 1750623d748SDimitry Andric CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) { 1760623d748SDimitry Andric AlignmentSource AlignSource; 1770623d748SDimitry Andric CharUnits Align = getNaturalTypeAlignment(T, &AlignSource, /*pointee*/ true); 1780623d748SDimitry Andric return MakeAddrLValue(Address(V, Align), T, AlignSource); 1790623d748SDimitry Andric } 1800623d748SDimitry Andric 181f22ef01cSRoman Divacky 18217a519f9SDimitry Andric llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 183f22ef01cSRoman Divacky return CGM.getTypes().ConvertTypeForMem(T); 184f22ef01cSRoman Divacky } 185f22ef01cSRoman Divacky 18617a519f9SDimitry Andric llvm::Type *CodeGenFunction::ConvertType(QualType T) { 187f22ef01cSRoman Divacky return CGM.getTypes().ConvertType(T); 188f22ef01cSRoman Divacky } 189f22ef01cSRoman Divacky 190139f7f9bSDimitry Andric TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) { 191139f7f9bSDimitry Andric type = type.getCanonicalType(); 192139f7f9bSDimitry Andric while (true) { 193139f7f9bSDimitry Andric switch (type->getTypeClass()) { 194bd5abe19SDimitry Andric #define TYPE(name, parent) 195bd5abe19SDimitry Andric #define ABSTRACT_TYPE(name, parent) 196bd5abe19SDimitry Andric #define NON_CANONICAL_TYPE(name, parent) case Type::name: 197bd5abe19SDimitry Andric #define DEPENDENT_TYPE(name, parent) case Type::name: 198bd5abe19SDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name: 199bd5abe19SDimitry Andric #include "clang/AST/TypeNodes.def" 200bd5abe19SDimitry Andric llvm_unreachable("non-canonical or dependent type in IR-generation"); 201bd5abe19SDimitry Andric 202284c1978SDimitry Andric case Type::Auto: 203284c1978SDimitry Andric llvm_unreachable("undeduced auto type in IR-generation"); 204284c1978SDimitry Andric 205139f7f9bSDimitry Andric // Various scalar types. 206bd5abe19SDimitry Andric case Type::Builtin: 207bd5abe19SDimitry Andric case Type::Pointer: 208bd5abe19SDimitry Andric case Type::BlockPointer: 209bd5abe19SDimitry Andric case Type::LValueReference: 210bd5abe19SDimitry Andric case Type::RValueReference: 211bd5abe19SDimitry Andric case Type::MemberPointer: 212bd5abe19SDimitry Andric case Type::Vector: 213bd5abe19SDimitry Andric case Type::ExtVector: 214bd5abe19SDimitry Andric case Type::FunctionProto: 215bd5abe19SDimitry Andric case Type::FunctionNoProto: 216bd5abe19SDimitry Andric case Type::Enum: 217bd5abe19SDimitry Andric case Type::ObjCObjectPointer: 218444ed5c5SDimitry Andric case Type::Pipe: 219139f7f9bSDimitry Andric return TEK_Scalar; 220bd5abe19SDimitry Andric 221139f7f9bSDimitry Andric // Complexes. 222bd5abe19SDimitry Andric case Type::Complex: 223139f7f9bSDimitry Andric return TEK_Complex; 224139f7f9bSDimitry Andric 225139f7f9bSDimitry Andric // Arrays, records, and Objective-C objects. 226bd5abe19SDimitry Andric case Type::ConstantArray: 227bd5abe19SDimitry Andric case Type::IncompleteArray: 228bd5abe19SDimitry Andric case Type::VariableArray: 229bd5abe19SDimitry Andric case Type::Record: 230bd5abe19SDimitry Andric case Type::ObjCObject: 231bd5abe19SDimitry Andric case Type::ObjCInterface: 232139f7f9bSDimitry Andric return TEK_Aggregate; 2336122f3e6SDimitry Andric 234139f7f9bSDimitry Andric // We operate on atomic values according to their underlying type. 2356122f3e6SDimitry Andric case Type::Atomic: 236139f7f9bSDimitry Andric type = cast<AtomicType>(type)->getValueType(); 237139f7f9bSDimitry Andric continue; 238bd5abe19SDimitry Andric } 239bd5abe19SDimitry Andric llvm_unreachable("unknown type kind!"); 240f22ef01cSRoman Divacky } 241139f7f9bSDimitry Andric } 242f22ef01cSRoman Divacky 24339d628a0SDimitry Andric llvm::DebugLoc CodeGenFunction::EmitReturnBlock() { 244f22ef01cSRoman Divacky // For cleanliness, we try to avoid emitting the return block for 245f22ef01cSRoman Divacky // simple cases. 246f22ef01cSRoman Divacky llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 247f22ef01cSRoman Divacky 248f22ef01cSRoman Divacky if (CurBB) { 249f22ef01cSRoman Divacky assert(!CurBB->getTerminator() && "Unexpected terminated block."); 250f22ef01cSRoman Divacky 251f22ef01cSRoman Divacky // We have a valid insert point, reuse it if it is empty or there are no 252f22ef01cSRoman Divacky // explicit jumps to the return block. 253e580952dSDimitry Andric if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) { 254e580952dSDimitry Andric ReturnBlock.getBlock()->replaceAllUsesWith(CurBB); 255e580952dSDimitry Andric delete ReturnBlock.getBlock(); 256f22ef01cSRoman Divacky } else 257e580952dSDimitry Andric EmitBlock(ReturnBlock.getBlock()); 25839d628a0SDimitry Andric return llvm::DebugLoc(); 259f22ef01cSRoman Divacky } 260f22ef01cSRoman Divacky 261f22ef01cSRoman Divacky // Otherwise, if the return block is the target of a single direct 262f22ef01cSRoman Divacky // branch then we can just put the code in that block instead. This 263f22ef01cSRoman Divacky // cleans up functions which started with a unified return block. 264e580952dSDimitry Andric if (ReturnBlock.getBlock()->hasOneUse()) { 265f22ef01cSRoman Divacky llvm::BranchInst *BI = 26659d1ed5bSDimitry Andric dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin()); 267ffd1746dSEd Schouten if (BI && BI->isUnconditional() && 268e580952dSDimitry Andric BI->getSuccessor(0) == ReturnBlock.getBlock()) { 26939d628a0SDimitry Andric // Record/return the DebugLoc of the simple 'return' expression to be used 27039d628a0SDimitry Andric // later by the actual 'ret' instruction. 27139d628a0SDimitry Andric llvm::DebugLoc Loc = BI->getDebugLoc(); 272f22ef01cSRoman Divacky Builder.SetInsertPoint(BI->getParent()); 273f22ef01cSRoman Divacky BI->eraseFromParent(); 274e580952dSDimitry Andric delete ReturnBlock.getBlock(); 27539d628a0SDimitry Andric return Loc; 276f22ef01cSRoman Divacky } 277f22ef01cSRoman Divacky } 278f22ef01cSRoman Divacky 279f22ef01cSRoman Divacky // FIXME: We are at an unreachable point, there is no reason to emit the block 280f22ef01cSRoman Divacky // unless it has uses. However, we still need a place to put the debug 281f22ef01cSRoman Divacky // region.end for now. 282f22ef01cSRoman Divacky 283e580952dSDimitry Andric EmitBlock(ReturnBlock.getBlock()); 28439d628a0SDimitry Andric return llvm::DebugLoc(); 285ffd1746dSEd Schouten } 286ffd1746dSEd Schouten 287ffd1746dSEd Schouten static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) { 288ffd1746dSEd Schouten if (!BB) return; 289ffd1746dSEd Schouten if (!BB->use_empty()) 290ffd1746dSEd Schouten return CGF.CurFn->getBasicBlockList().push_back(BB); 291ffd1746dSEd Schouten delete BB; 292f22ef01cSRoman Divacky } 293f22ef01cSRoman Divacky 294f22ef01cSRoman Divacky void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 295f22ef01cSRoman Divacky assert(BreakContinueStack.empty() && 296f22ef01cSRoman Divacky "mismatched push/pop in break/continue stack!"); 297f22ef01cSRoman Divacky 298284c1978SDimitry Andric bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0 299f785676fSDimitry Andric && NumSimpleReturnExprs == NumReturnExprs 300f785676fSDimitry Andric && ReturnBlock.getBlock()->use_empty(); 301f785676fSDimitry Andric // Usually the return expression is evaluated before the cleanup 302f785676fSDimitry Andric // code. If the function contains only a simple return statement, 303f785676fSDimitry Andric // such as a constant, the location before the cleanup code becomes 304f785676fSDimitry Andric // the last useful breakpoint in the function, because the simple 305f785676fSDimitry Andric // return expression will be evaluated after the cleanup code. To be 306f785676fSDimitry Andric // safe, set the debug location for cleanup code to the location of 307f785676fSDimitry Andric // the return statement. Otherwise the cleanup code should be at the 308f785676fSDimitry Andric // end of the function's lexical scope. 309f785676fSDimitry Andric // 310f785676fSDimitry Andric // If there are multiple branches to the return block, the branch 311f785676fSDimitry Andric // instructions will get the location of the return statements and 312f785676fSDimitry Andric // all will be fine. 313284c1978SDimitry Andric if (CGDebugInfo *DI = getDebugInfo()) { 314284c1978SDimitry Andric if (OnlySimpleReturnStmts) 315284c1978SDimitry Andric DI->EmitLocation(Builder, LastStopPoint); 316284c1978SDimitry Andric else 317139f7f9bSDimitry Andric DI->EmitLocation(Builder, EndLoc); 318284c1978SDimitry Andric } 319139f7f9bSDimitry Andric 32017a519f9SDimitry Andric // Pop any cleanups that might have been associated with the 32117a519f9SDimitry Andric // parameters. Do this in whatever block we're currently in; it's 32217a519f9SDimitry Andric // important to do this before we enter the return block or return 32317a519f9SDimitry Andric // edges will be *really* confused. 32433956c43SDimitry Andric bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth; 32533956c43SDimitry Andric bool HasOnlyLifetimeMarkers = 32633956c43SDimitry Andric HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth); 32733956c43SDimitry Andric bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers; 32833956c43SDimitry Andric if (HasCleanups) { 329284c1978SDimitry Andric // Make sure the line table doesn't jump back into the body for 330284c1978SDimitry Andric // the ret after it's been at EndLoc. 331284c1978SDimitry Andric if (CGDebugInfo *DI = getDebugInfo()) 332284c1978SDimitry Andric if (OnlySimpleReturnStmts) 333284c1978SDimitry Andric DI->EmitLocation(Builder, EndLoc); 33433956c43SDimitry Andric 33533956c43SDimitry Andric PopCleanupBlocks(PrologueCleanupDepth); 336284c1978SDimitry Andric } 33717a519f9SDimitry Andric 338f22ef01cSRoman Divacky // Emit function epilog (to return). 33939d628a0SDimitry Andric llvm::DebugLoc Loc = EmitReturnBlock(); 340f22ef01cSRoman Divacky 3412754fe60SDimitry Andric if (ShouldInstrumentFunction()) 342ffd1746dSEd Schouten EmitFunctionInstrumentation("__cyg_profile_func_exit"); 343ffd1746dSEd Schouten 344f22ef01cSRoman Divacky // Emit debug descriptor for function end. 34539d628a0SDimitry Andric if (CGDebugInfo *DI = getDebugInfo()) 346e580952dSDimitry Andric DI->EmitFunctionEnd(Builder); 347f22ef01cSRoman Divacky 34839d628a0SDimitry Andric // Reset the debug location to that of the simple 'return' expression, if any 34939d628a0SDimitry Andric // rather than that of the end of the function's scope '}'. 35039d628a0SDimitry Andric ApplyDebugLocation AL(*this, Loc); 351f785676fSDimitry Andric EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc); 352f22ef01cSRoman Divacky EmitEndEHSpec(CurCodeDecl); 353f22ef01cSRoman Divacky 354ffd1746dSEd Schouten assert(EHStack.empty() && 355ffd1746dSEd Schouten "did not remove all scopes from cleanup stack!"); 356ffd1746dSEd Schouten 357f22ef01cSRoman Divacky // If someone did an indirect goto, emit the indirect goto block at the end of 358f22ef01cSRoman Divacky // the function. 359f22ef01cSRoman Divacky if (IndirectBranch) { 360f22ef01cSRoman Divacky EmitBlock(IndirectBranch->getParent()); 361f22ef01cSRoman Divacky Builder.ClearInsertionPoint(); 362f22ef01cSRoman Divacky } 363f22ef01cSRoman Divacky 364875ed548SDimitry Andric // If some of our locals escaped, insert a call to llvm.localescape in the 36533956c43SDimitry Andric // entry block. 36633956c43SDimitry Andric if (!EscapedLocals.empty()) { 36733956c43SDimitry Andric // Invert the map from local to index into a simple vector. There should be 36833956c43SDimitry Andric // no holes. 36933956c43SDimitry Andric SmallVector<llvm::Value *, 4> EscapeArgs; 37033956c43SDimitry Andric EscapeArgs.resize(EscapedLocals.size()); 37133956c43SDimitry Andric for (auto &Pair : EscapedLocals) 37233956c43SDimitry Andric EscapeArgs[Pair.second] = Pair.first; 37333956c43SDimitry Andric llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration( 374875ed548SDimitry Andric &CGM.getModule(), llvm::Intrinsic::localescape); 3750623d748SDimitry Andric CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs); 37633956c43SDimitry Andric } 37733956c43SDimitry Andric 378f22ef01cSRoman Divacky // Remove the AllocaInsertPt instruction, which is just a convenience for us. 379f22ef01cSRoman Divacky llvm::Instruction *Ptr = AllocaInsertPt; 38059d1ed5bSDimitry Andric AllocaInsertPt = nullptr; 381f22ef01cSRoman Divacky Ptr->eraseFromParent(); 382f22ef01cSRoman Divacky 383f22ef01cSRoman Divacky // If someone took the address of a label but never did an indirect goto, we 384f22ef01cSRoman Divacky // made a zero entry PHI node, which is illegal, zap it now. 385f22ef01cSRoman Divacky if (IndirectBranch) { 386f22ef01cSRoman Divacky llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress()); 387f22ef01cSRoman Divacky if (PN->getNumIncomingValues() == 0) { 388f22ef01cSRoman Divacky PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType())); 389f22ef01cSRoman Divacky PN->eraseFromParent(); 390f22ef01cSRoman Divacky } 391f22ef01cSRoman Divacky } 392ffd1746dSEd Schouten 3936122f3e6SDimitry Andric EmitIfUsed(*this, EHResumeBlock); 394ffd1746dSEd Schouten EmitIfUsed(*this, TerminateLandingPad); 395ffd1746dSEd Schouten EmitIfUsed(*this, TerminateHandler); 396ffd1746dSEd Schouten EmitIfUsed(*this, UnreachableBlock); 397ffd1746dSEd Schouten 398ffd1746dSEd Schouten if (CGM.getCodeGenOpts().EmitDeclMetadata) 399ffd1746dSEd Schouten EmitDeclMetadata(); 40059d1ed5bSDimitry Andric 40159d1ed5bSDimitry Andric for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator 40259d1ed5bSDimitry Andric I = DeferredReplacements.begin(), 40359d1ed5bSDimitry Andric E = DeferredReplacements.end(); 40459d1ed5bSDimitry Andric I != E; ++I) { 40559d1ed5bSDimitry Andric I->first->replaceAllUsesWith(I->second); 40659d1ed5bSDimitry Andric I->first->eraseFromParent(); 40759d1ed5bSDimitry Andric } 408ffd1746dSEd Schouten } 409ffd1746dSEd Schouten 410ffd1746dSEd Schouten /// ShouldInstrumentFunction - Return true if the current function should be 411ffd1746dSEd Schouten /// instrumented with __cyg_profile_func_* calls 412ffd1746dSEd Schouten bool CodeGenFunction::ShouldInstrumentFunction() { 413ffd1746dSEd Schouten if (!CGM.getCodeGenOpts().InstrumentFunctions) 414ffd1746dSEd Schouten return false; 415bd5abe19SDimitry Andric if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) 416ffd1746dSEd Schouten return false; 417ffd1746dSEd Schouten return true; 418ffd1746dSEd Schouten } 419ffd1746dSEd Schouten 420e7145dcbSDimitry Andric /// ShouldXRayInstrument - Return true if the current function should be 421e7145dcbSDimitry Andric /// instrumented with XRay nop sleds. 422e7145dcbSDimitry Andric bool CodeGenFunction::ShouldXRayInstrumentFunction() const { 423e7145dcbSDimitry Andric return CGM.getCodeGenOpts().XRayInstrumentFunctions; 424e7145dcbSDimitry Andric } 425e7145dcbSDimitry Andric 426ffd1746dSEd Schouten /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 427ffd1746dSEd Schouten /// instrumentation function with the current function and the call site, if 428ffd1746dSEd Schouten /// function instrumentation is enabled. 429ffd1746dSEd Schouten void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) { 430e7145dcbSDimitry Andric auto NL = ApplyDebugLocation::CreateArtificial(*this); 431ffd1746dSEd Schouten // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site); 43217a519f9SDimitry Andric llvm::PointerType *PointerTy = Int8PtrTy; 43317a519f9SDimitry Andric llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy }; 4346122f3e6SDimitry Andric llvm::FunctionType *FunctionTy = 435dff0c46cSDimitry Andric llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false); 436ffd1746dSEd Schouten 437ffd1746dSEd Schouten llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn); 438ffd1746dSEd Schouten llvm::CallInst *CallSite = Builder.CreateCall( 43917a519f9SDimitry Andric CGM.getIntrinsic(llvm::Intrinsic::returnaddress), 440ffd1746dSEd Schouten llvm::ConstantInt::get(Int32Ty, 0), 441ffd1746dSEd Schouten "callsite"); 442ffd1746dSEd Schouten 443139f7f9bSDimitry Andric llvm::Value *args[] = { 444ffd1746dSEd Schouten llvm::ConstantExpr::getBitCast(CurFn, PointerTy), 445139f7f9bSDimitry Andric CallSite 446139f7f9bSDimitry Andric }; 447139f7f9bSDimitry Andric 448139f7f9bSDimitry Andric EmitNounwindRuntimeCall(F, args); 449f22ef01cSRoman Divacky } 450f22ef01cSRoman Divacky 45144290647SDimitry Andric static void removeImageAccessQualifier(std::string& TyName) { 45244290647SDimitry Andric std::string ReadOnlyQual("__read_only"); 45344290647SDimitry Andric std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual); 45444290647SDimitry Andric if (ReadOnlyPos != std::string::npos) 45544290647SDimitry Andric // "+ 1" for the space after access qualifier. 45644290647SDimitry Andric TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1); 45744290647SDimitry Andric else { 45844290647SDimitry Andric std::string WriteOnlyQual("__write_only"); 45944290647SDimitry Andric std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual); 46044290647SDimitry Andric if (WriteOnlyPos != std::string::npos) 46144290647SDimitry Andric TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1); 46244290647SDimitry Andric else { 46344290647SDimitry Andric std::string ReadWriteQual("__read_write"); 46444290647SDimitry Andric std::string::size_type ReadWritePos = TyName.find(ReadWriteQual); 46544290647SDimitry Andric if (ReadWritePos != std::string::npos) 46644290647SDimitry Andric TyName.erase(ReadWritePos, ReadWriteQual.size() + 1); 46744290647SDimitry Andric } 46844290647SDimitry Andric } 4692754fe60SDimitry Andric } 4702754fe60SDimitry Andric 471f41fbc90SDimitry Andric // Returns the address space id that should be produced to the 472f41fbc90SDimitry Andric // kernel_arg_addr_space metadata. This is always fixed to the ids 473f41fbc90SDimitry Andric // as specified in the SPIR 2.0 specification in order to differentiate 474f41fbc90SDimitry Andric // for example in clGetKernelArgInfo() implementation between the address 475f41fbc90SDimitry Andric // spaces with targets without unique mapping to the OpenCL address spaces 476f41fbc90SDimitry Andric // (basically all single AS CPUs). 477f41fbc90SDimitry Andric static unsigned ArgInfoAddressSpace(unsigned LangAS) { 478f41fbc90SDimitry Andric switch (LangAS) { 479f41fbc90SDimitry Andric case LangAS::opencl_global: return 1; 480f41fbc90SDimitry Andric case LangAS::opencl_constant: return 2; 481f41fbc90SDimitry Andric case LangAS::opencl_local: return 3; 482f41fbc90SDimitry Andric case LangAS::opencl_generic: return 4; // Not in SPIR 2.0 specs. 483f41fbc90SDimitry Andric default: 484f41fbc90SDimitry Andric return 0; // Assume private. 485f41fbc90SDimitry Andric } 486f41fbc90SDimitry Andric } 487f41fbc90SDimitry Andric 4887ae0e2c9SDimitry Andric // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument 4897ae0e2c9SDimitry Andric // information in the program executable. The argument information stored 4907ae0e2c9SDimitry Andric // includes the argument name, its type, the address and access qualifiers used. 4917ae0e2c9SDimitry Andric static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn, 4927ae0e2c9SDimitry Andric CodeGenModule &CGM, llvm::LLVMContext &Context, 493139f7f9bSDimitry Andric CGBuilderTy &Builder, ASTContext &ASTCtx) { 494139f7f9bSDimitry Andric // Create MDNodes that represent the kernel arg metadata. 4957ae0e2c9SDimitry Andric // Each MDNode is a list in the form of "key", N number of values which is 4967ae0e2c9SDimitry Andric // the same number of values as their are kernel arguments. 4977ae0e2c9SDimitry Andric 49859d1ed5bSDimitry Andric const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy(); 49959d1ed5bSDimitry Andric 500139f7f9bSDimitry Andric // MDNode for the kernel argument address space qualifiers. 50139d628a0SDimitry Andric SmallVector<llvm::Metadata *, 8> addressQuals; 502139f7f9bSDimitry Andric 503139f7f9bSDimitry Andric // MDNode for the kernel argument access qualifiers (images only). 50439d628a0SDimitry Andric SmallVector<llvm::Metadata *, 8> accessQuals; 505139f7f9bSDimitry Andric 506139f7f9bSDimitry Andric // MDNode for the kernel argument type names. 50739d628a0SDimitry Andric SmallVector<llvm::Metadata *, 8> argTypeNames; 508139f7f9bSDimitry Andric 50939d628a0SDimitry Andric // MDNode for the kernel argument base type names. 51039d628a0SDimitry Andric SmallVector<llvm::Metadata *, 8> argBaseTypeNames; 51139d628a0SDimitry Andric 512139f7f9bSDimitry Andric // MDNode for the kernel argument type qualifiers. 51339d628a0SDimitry Andric SmallVector<llvm::Metadata *, 8> argTypeQuals; 514139f7f9bSDimitry Andric 5157ae0e2c9SDimitry Andric // MDNode for the kernel argument names. 51639d628a0SDimitry Andric SmallVector<llvm::Metadata *, 8> argNames; 5177ae0e2c9SDimitry Andric 5187ae0e2c9SDimitry Andric for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 5197ae0e2c9SDimitry Andric const ParmVarDecl *parm = FD->getParamDecl(i); 520139f7f9bSDimitry Andric QualType ty = parm->getType(); 521139f7f9bSDimitry Andric std::string typeQuals; 522139f7f9bSDimitry Andric 523139f7f9bSDimitry Andric if (ty->isPointerType()) { 524139f7f9bSDimitry Andric QualType pointeeTy = ty->getPointeeType(); 525139f7f9bSDimitry Andric 526139f7f9bSDimitry Andric // Get address qualifier. 52739d628a0SDimitry Andric addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32( 528f41fbc90SDimitry Andric ArgInfoAddressSpace(pointeeTy.getAddressSpace())))); 529139f7f9bSDimitry Andric 530139f7f9bSDimitry Andric // Get argument type name. 53159d1ed5bSDimitry Andric std::string typeName = 53259d1ed5bSDimitry Andric pointeeTy.getUnqualifiedType().getAsString(Policy) + "*"; 533139f7f9bSDimitry Andric 534139f7f9bSDimitry Andric // Turn "unsigned type" to "utype" 535139f7f9bSDimitry Andric std::string::size_type pos = typeName.find("unsigned"); 53639d628a0SDimitry Andric if (pointeeTy.isCanonical() && pos != std::string::npos) 537139f7f9bSDimitry Andric typeName.erase(pos+1, 8); 538139f7f9bSDimitry Andric 539139f7f9bSDimitry Andric argTypeNames.push_back(llvm::MDString::get(Context, typeName)); 540139f7f9bSDimitry Andric 54139d628a0SDimitry Andric std::string baseTypeName = 54239d628a0SDimitry Andric pointeeTy.getUnqualifiedType().getCanonicalType().getAsString( 54339d628a0SDimitry Andric Policy) + 54439d628a0SDimitry Andric "*"; 54539d628a0SDimitry Andric 54639d628a0SDimitry Andric // Turn "unsigned type" to "utype" 54739d628a0SDimitry Andric pos = baseTypeName.find("unsigned"); 54839d628a0SDimitry Andric if (pos != std::string::npos) 54939d628a0SDimitry Andric baseTypeName.erase(pos+1, 8); 55039d628a0SDimitry Andric 55139d628a0SDimitry Andric argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName)); 55239d628a0SDimitry Andric 553139f7f9bSDimitry Andric // Get argument type qualifiers: 554139f7f9bSDimitry Andric if (ty.isRestrictQualified()) 555139f7f9bSDimitry Andric typeQuals = "restrict"; 556139f7f9bSDimitry Andric if (pointeeTy.isConstQualified() || 557139f7f9bSDimitry Andric (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) 558139f7f9bSDimitry Andric typeQuals += typeQuals.empty() ? "const" : " const"; 559139f7f9bSDimitry Andric if (pointeeTy.isVolatileQualified()) 560139f7f9bSDimitry Andric typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 561139f7f9bSDimitry Andric } else { 56259d1ed5bSDimitry Andric uint32_t AddrSpc = 0; 563444ed5c5SDimitry Andric bool isPipe = ty->isPipeType(); 564444ed5c5SDimitry Andric if (ty->isImageType() || isPipe) 565f41fbc90SDimitry Andric AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global); 56659d1ed5bSDimitry Andric 56739d628a0SDimitry Andric addressQuals.push_back( 56839d628a0SDimitry Andric llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc))); 569139f7f9bSDimitry Andric 570139f7f9bSDimitry Andric // Get argument type name. 571444ed5c5SDimitry Andric std::string typeName; 572444ed5c5SDimitry Andric if (isPipe) 573e7145dcbSDimitry Andric typeName = ty.getCanonicalType()->getAs<PipeType>()->getElementType() 574e7145dcbSDimitry Andric .getAsString(Policy); 575444ed5c5SDimitry Andric else 576444ed5c5SDimitry Andric typeName = ty.getUnqualifiedType().getAsString(Policy); 577139f7f9bSDimitry Andric 578139f7f9bSDimitry Andric // Turn "unsigned type" to "utype" 579139f7f9bSDimitry Andric std::string::size_type pos = typeName.find("unsigned"); 58039d628a0SDimitry Andric if (ty.isCanonical() && pos != std::string::npos) 581139f7f9bSDimitry Andric typeName.erase(pos+1, 8); 582139f7f9bSDimitry Andric 583444ed5c5SDimitry Andric std::string baseTypeName; 584444ed5c5SDimitry Andric if (isPipe) 585e7145dcbSDimitry Andric baseTypeName = ty.getCanonicalType()->getAs<PipeType>() 586e7145dcbSDimitry Andric ->getElementType().getCanonicalType() 587e7145dcbSDimitry Andric .getAsString(Policy); 588444ed5c5SDimitry Andric else 589444ed5c5SDimitry Andric baseTypeName = 59039d628a0SDimitry Andric ty.getUnqualifiedType().getCanonicalType().getAsString(Policy); 59139d628a0SDimitry Andric 59244290647SDimitry Andric // Remove access qualifiers on images 59344290647SDimitry Andric // (as they are inseparable from type in clang implementation, 59444290647SDimitry Andric // but OpenCL spec provides a special query to get access qualifier 59544290647SDimitry Andric // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER): 59644290647SDimitry Andric if (ty->isImageType()) { 59744290647SDimitry Andric removeImageAccessQualifier(typeName); 59844290647SDimitry Andric removeImageAccessQualifier(baseTypeName); 59944290647SDimitry Andric } 60044290647SDimitry Andric 60144290647SDimitry Andric argTypeNames.push_back(llvm::MDString::get(Context, typeName)); 60244290647SDimitry Andric 60339d628a0SDimitry Andric // Turn "unsigned type" to "utype" 60439d628a0SDimitry Andric pos = baseTypeName.find("unsigned"); 60539d628a0SDimitry Andric if (pos != std::string::npos) 60639d628a0SDimitry Andric baseTypeName.erase(pos+1, 8); 60739d628a0SDimitry Andric 60839d628a0SDimitry Andric argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName)); 60939d628a0SDimitry Andric 610139f7f9bSDimitry Andric // Get argument type qualifiers: 611139f7f9bSDimitry Andric if (ty.isConstQualified()) 612139f7f9bSDimitry Andric typeQuals = "const"; 613139f7f9bSDimitry Andric if (ty.isVolatileQualified()) 614139f7f9bSDimitry Andric typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 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>()) { 66359d1ed5bSDimitry Andric QualType hintQTy = A->getTypeHint(); 664139f7f9bSDimitry Andric const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>(); 665139f7f9bSDimitry Andric bool isSignedInteger = 666139f7f9bSDimitry Andric hintQTy->isSignedIntegerType() || 667139f7f9bSDimitry Andric (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType()); 66839d628a0SDimitry 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), 67339d628a0SDimitry Andric llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))}; 674e7145dcbSDimitry Andric Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, attrMDArgs)); 675139f7f9bSDimitry Andric } 6767ae0e2c9SDimitry Andric 67759d1ed5bSDimitry Andric if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) { 67839d628a0SDimitry 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()))}; 682e7145dcbSDimitry 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>()) { 68639d628a0SDimitry 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()))}; 690e7145dcbSDimitry Andric Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, attrMDArgs)); 6917ae0e2c9SDimitry Andric } 6927ae0e2c9SDimitry Andric } 6937ae0e2c9SDimitry Andric 69459d1ed5bSDimitry Andric /// Determine whether the function F ends with a return stmt. 69559d1ed5bSDimitry Andric static bool endsWithReturn(const Decl* F) { 69659d1ed5bSDimitry Andric const Stmt *Body = nullptr; 69759d1ed5bSDimitry Andric if (auto *FD = dyn_cast_or_null<FunctionDecl>(F)) 69859d1ed5bSDimitry Andric Body = FD->getBody(); 69959d1ed5bSDimitry Andric else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F)) 70059d1ed5bSDimitry Andric Body = OMD->getBody(); 70159d1ed5bSDimitry Andric 70259d1ed5bSDimitry Andric if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) { 70359d1ed5bSDimitry Andric auto LastStmt = CS->body_rbegin(); 70459d1ed5bSDimitry Andric if (LastStmt != CS->body_rend()) 70559d1ed5bSDimitry Andric return isa<ReturnStmt>(*LastStmt); 70659d1ed5bSDimitry Andric } 70759d1ed5bSDimitry Andric return false; 70859d1ed5bSDimitry Andric } 70959d1ed5bSDimitry Andric 710284c1978SDimitry Andric void CodeGenFunction::StartFunction(GlobalDecl GD, 711284c1978SDimitry Andric QualType RetTy, 712f22ef01cSRoman Divacky llvm::Function *Fn, 7133b0f4066SDimitry Andric const CGFunctionInfo &FnInfo, 714f22ef01cSRoman Divacky const FunctionArgList &Args, 71559d1ed5bSDimitry Andric SourceLocation Loc, 716f22ef01cSRoman Divacky SourceLocation StartLoc) { 71739d628a0SDimitry Andric assert(!CurFn && 71839d628a0SDimitry Andric "Do not use a CodeGenFunction object for more than one function"); 71939d628a0SDimitry Andric 720f22ef01cSRoman Divacky const Decl *D = GD.getDecl(); 721f22ef01cSRoman Divacky 722f22ef01cSRoman Divacky DidCallStackSave = false; 723284c1978SDimitry Andric CurCodeDecl = D; 724e7145dcbSDimitry Andric if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) 725e7145dcbSDimitry Andric if (FD->usesSEHTry()) 726e7145dcbSDimitry Andric CurSEHParent = FD; 72759d1ed5bSDimitry Andric CurFuncDecl = (D ? D->getNonClosureContext() : nullptr); 728f22ef01cSRoman Divacky FnRetTy = RetTy; 729f22ef01cSRoman Divacky CurFn = Fn; 7303b0f4066SDimitry Andric CurFnInfo = &FnInfo; 731f22ef01cSRoman Divacky assert(CurFn->isDeclaration() && "Function already has body?"); 732f22ef01cSRoman Divacky 73339d628a0SDimitry Andric if (CGM.isInSanitizerBlacklist(Fn, Loc)) 73439d628a0SDimitry Andric SanOpts.clear(); 735139f7f9bSDimitry Andric 73633956c43SDimitry Andric if (D) { 73733956c43SDimitry Andric // Apply the no_sanitize* attributes to SanOpts. 73833956c43SDimitry Andric for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) 73933956c43SDimitry Andric SanOpts.Mask &= ~Attr->getMask(); 74033956c43SDimitry Andric } 74133956c43SDimitry Andric 74233956c43SDimitry Andric // Apply sanitizer attributes to the function. 7438f0fd8f6SDimitry Andric if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress)) 74433956c43SDimitry Andric Fn->addFnAttr(llvm::Attribute::SanitizeAddress); 74533956c43SDimitry Andric if (SanOpts.has(SanitizerKind::Thread)) 74633956c43SDimitry Andric Fn->addFnAttr(llvm::Attribute::SanitizeThread); 74733956c43SDimitry Andric if (SanOpts.has(SanitizerKind::Memory)) 74833956c43SDimitry Andric Fn->addFnAttr(llvm::Attribute::SanitizeMemory); 7498f0fd8f6SDimitry Andric if (SanOpts.has(SanitizerKind::SafeStack)) 7508f0fd8f6SDimitry Andric Fn->addFnAttr(llvm::Attribute::SafeStack); 75133956c43SDimitry Andric 75244290647SDimitry Andric // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize, 75344290647SDimitry Andric // .cxx_destruct and all of their calees at run time. 75444290647SDimitry Andric if (SanOpts.has(SanitizerKind::Thread)) { 75544290647SDimitry Andric if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) { 75644290647SDimitry Andric IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0); 75744290647SDimitry Andric if (OMD->getMethodFamily() == OMF_dealloc || 75844290647SDimitry Andric OMD->getMethodFamily() == OMF_initialize || 75944290647SDimitry Andric (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) { 76044290647SDimitry Andric Fn->addFnAttr("sanitize_thread_no_checking_at_run_time"); 76144290647SDimitry Andric Fn->removeFnAttr(llvm::Attribute::SanitizeThread); 76244290647SDimitry Andric } 76344290647SDimitry Andric } 76444290647SDimitry Andric } 76544290647SDimitry Andric 766e7145dcbSDimitry Andric // Apply xray attributes to the function (as a string, for now) 767e7145dcbSDimitry Andric if (D && ShouldXRayInstrumentFunction()) { 768e7145dcbSDimitry Andric if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) { 769e7145dcbSDimitry Andric if (XRayAttr->alwaysXRayInstrument()) 770e7145dcbSDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 771e7145dcbSDimitry Andric if (XRayAttr->neverXRayInstrument()) 772e7145dcbSDimitry Andric Fn->addFnAttr("function-instrument", "xray-never"); 773e7145dcbSDimitry Andric } else { 774e7145dcbSDimitry Andric Fn->addFnAttr( 775e7145dcbSDimitry Andric "xray-instruction-threshold", 776e7145dcbSDimitry Andric llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold)); 777e7145dcbSDimitry Andric } 778e7145dcbSDimitry Andric } 779e7145dcbSDimitry Andric 78044290647SDimitry Andric if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 781e7145dcbSDimitry Andric if (CGM.getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) 782e7145dcbSDimitry Andric CGM.getOpenMPRuntime().emitDeclareSimdFunction(FD, Fn); 783f22ef01cSRoman Divacky 784e7145dcbSDimitry Andric // Add no-jump-tables value. 785e7145dcbSDimitry Andric Fn->addFnAttr("no-jump-tables", 786e7145dcbSDimitry Andric llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables)); 787e7145dcbSDimitry Andric 7883861d79fSDimitry Andric if (getLangOpts().OpenCL) { 7892754fe60SDimitry Andric // Add metadata for a kernel function. 7902754fe60SDimitry Andric if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 7917ae0e2c9SDimitry Andric EmitOpenCLKernelMetadata(FD, Fn); 7922754fe60SDimitry Andric } 7932754fe60SDimitry Andric 794f785676fSDimitry Andric // If we are checking function types, emit a function type signature as 79539d628a0SDimitry Andric // prologue data. 79639d628a0SDimitry Andric if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) { 797f785676fSDimitry Andric if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 79839d628a0SDimitry Andric if (llvm::Constant *PrologueSig = 799f785676fSDimitry Andric CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) { 800f785676fSDimitry Andric llvm::Constant *FTRTTIConst = 801f785676fSDimitry Andric CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true); 80239d628a0SDimitry Andric llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst }; 80339d628a0SDimitry Andric llvm::Constant *PrologueStructConst = 80439d628a0SDimitry Andric llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true); 80539d628a0SDimitry Andric Fn->setPrologueData(PrologueStructConst); 806f785676fSDimitry Andric } 807f785676fSDimitry Andric } 808f785676fSDimitry Andric } 809f785676fSDimitry Andric 8100623d748SDimitry Andric // If we're in C++ mode and the function name is "main", it is guaranteed 8110623d748SDimitry Andric // to be norecurse by the standard (3.6.1.3 "The function main shall not be 8120623d748SDimitry Andric // used within a program"). 8130623d748SDimitry Andric if (getLangOpts().CPlusPlus) 8140623d748SDimitry Andric if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 8150623d748SDimitry Andric if (FD->isMain()) 8160623d748SDimitry Andric Fn->addFnAttr(llvm::Attribute::NoRecurse); 8170623d748SDimitry Andric 818f22ef01cSRoman Divacky llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 819f22ef01cSRoman Divacky 820f22ef01cSRoman Divacky // Create a marker to make it easy to insert allocas into the entryblock 821f22ef01cSRoman Divacky // later. Don't create this with the builder, because we don't want it 822f22ef01cSRoman Divacky // folded. 823ffd1746dSEd Schouten llvm::Value *Undef = llvm::UndefValue::get(Int32Ty); 824e7145dcbSDimitry Andric AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB); 825f22ef01cSRoman Divacky 826ffd1746dSEd Schouten ReturnBlock = getJumpDestInCurrentScope("return"); 827f22ef01cSRoman Divacky 828f22ef01cSRoman Divacky Builder.SetInsertPoint(EntryBB); 829f22ef01cSRoman Divacky 830f22ef01cSRoman Divacky // Emit subprogram debug descriptor. 831f22ef01cSRoman Divacky if (CGDebugInfo *DI = getDebugInfo()) { 832e7145dcbSDimitry Andric // Reconstruct the type from the argument list so that implicit parameters, 833e7145dcbSDimitry Andric // such as 'this' and 'vtt', show up in the debug info. Preserve the calling 834e7145dcbSDimitry Andric // convention. 835e7145dcbSDimitry Andric CallingConv CC = CallingConv::CC_C; 836e7145dcbSDimitry Andric if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) 837e7145dcbSDimitry Andric if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>()) 838e7145dcbSDimitry Andric CC = SrcFnTy->getCallConv(); 839139f7f9bSDimitry Andric SmallVector<QualType, 16> ArgTypes; 840e7145dcbSDimitry Andric for (const VarDecl *VD : Args) 841e7145dcbSDimitry Andric ArgTypes.push_back(VD->getType()); 842e7145dcbSDimitry Andric QualType FnType = getContext().getFunctionType( 843e7145dcbSDimitry Andric RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC)); 84459d1ed5bSDimitry Andric DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder); 845f22ef01cSRoman Divacky } 846f22ef01cSRoman Divacky 8472754fe60SDimitry Andric if (ShouldInstrumentFunction()) 848ffd1746dSEd Schouten EmitFunctionInstrumentation("__cyg_profile_func_enter"); 849ffd1746dSEd Schouten 85044290647SDimitry Andric // Since emitting the mcount call here impacts optimizations such as function 85144290647SDimitry Andric // inlining, we just add an attribute to insert a mcount call in backend. 85244290647SDimitry Andric // The attribute "counting-function" is set to mcount function name which is 85344290647SDimitry Andric // architecture dependent. 8542754fe60SDimitry Andric if (CGM.getCodeGenOpts().InstrumentForProfiling) 85544290647SDimitry Andric Fn->addFnAttr("counting-function", getTarget().getMCountName()); 8562754fe60SDimitry Andric 857f22ef01cSRoman Divacky if (RetTy->isVoidType()) { 858f22ef01cSRoman Divacky // Void type; nothing to return. 8590623d748SDimitry Andric ReturnValue = Address::invalid(); 86059d1ed5bSDimitry Andric 86159d1ed5bSDimitry Andric // Count the implicit return. 86259d1ed5bSDimitry Andric if (!endsWithReturn(D)) 86359d1ed5bSDimitry Andric ++NumReturnExprs; 864f22ef01cSRoman Divacky } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect && 865139f7f9bSDimitry Andric !hasScalarEvaluationKind(CurFnInfo->getReturnType())) { 866f22ef01cSRoman Divacky // Indirect aggregate return; emit returned value directly into sret slot. 867f22ef01cSRoman Divacky // This reduces code size, and affects correctness in C++. 86859d1ed5bSDimitry Andric auto AI = CurFn->arg_begin(); 86959d1ed5bSDimitry Andric if (CurFnInfo->getReturnInfo().isSRetAfterThis()) 87059d1ed5bSDimitry Andric ++AI; 8710623d748SDimitry Andric ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign()); 87259d1ed5bSDimitry Andric } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca && 87359d1ed5bSDimitry Andric !hasScalarEvaluationKind(CurFnInfo->getReturnType())) { 87459d1ed5bSDimitry Andric // Load the sret pointer from the argument struct and return into that. 87559d1ed5bSDimitry Andric unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex(); 87659d1ed5bSDimitry Andric llvm::Function::arg_iterator EI = CurFn->arg_end(); 87759d1ed5bSDimitry Andric --EI; 8780623d748SDimitry Andric llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx); 8790623d748SDimitry Andric Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result"); 8800623d748SDimitry Andric ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy)); 881f22ef01cSRoman Divacky } else { 882f22ef01cSRoman Divacky ReturnValue = CreateIRTemp(RetTy, "retval"); 88317a519f9SDimitry Andric 88417a519f9SDimitry Andric // Tell the epilog emitter to autorelease the result. We do this 88517a519f9SDimitry Andric // now so that various specialized functions can suppress it 88617a519f9SDimitry Andric // during their IR-generation. 887dff0c46cSDimitry Andric if (getLangOpts().ObjCAutoRefCount && 88817a519f9SDimitry Andric !CurFnInfo->isReturnsRetained() && 88917a519f9SDimitry Andric RetTy->isObjCRetainableType()) 89017a519f9SDimitry Andric AutoreleaseResult = true; 891f22ef01cSRoman Divacky } 892f22ef01cSRoman Divacky 893f22ef01cSRoman Divacky EmitStartEHSpec(CurCodeDecl); 89417a519f9SDimitry Andric 89517a519f9SDimitry Andric PrologueCleanupDepth = EHStack.stable_begin(); 896f22ef01cSRoman Divacky EmitFunctionProlog(*CurFnInfo, CurFn, Args); 897f22ef01cSRoman Divacky 898dff0c46cSDimitry Andric if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) { 899e580952dSDimitry Andric CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 900dff0c46cSDimitry Andric const CXXMethodDecl *MD = cast<CXXMethodDecl>(D); 901dff0c46cSDimitry Andric if (MD->getParent()->isLambda() && 902dff0c46cSDimitry Andric MD->getOverloadedOperator() == OO_Call) { 903dff0c46cSDimitry Andric // We're in a lambda; figure out the captures. 904dff0c46cSDimitry Andric MD->getParent()->getCaptureFields(LambdaCaptureFields, 905dff0c46cSDimitry Andric LambdaThisCaptureField); 906dff0c46cSDimitry Andric if (LambdaThisCaptureField) { 907e7145dcbSDimitry Andric // If the lambda captures the object referred to by '*this' - either by 908e7145dcbSDimitry Andric // value or by reference, make sure CXXThisValue points to the correct 909e7145dcbSDimitry Andric // object. 910e7145dcbSDimitry Andric 911e7145dcbSDimitry Andric // Get the lvalue for the field (which is a copy of the enclosing object 912e7145dcbSDimitry Andric // or contains the address of the enclosing object). 913e7145dcbSDimitry Andric LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField); 914e7145dcbSDimitry Andric if (!LambdaThisCaptureField->getType()->isPointerType()) { 915e7145dcbSDimitry Andric // If the enclosing object was captured by value, just use its address. 916e7145dcbSDimitry Andric CXXThisValue = ThisFieldLValue.getAddress().getPointer(); 917e7145dcbSDimitry Andric } else { 918e7145dcbSDimitry Andric // Load the lvalue pointed to by the field, since '*this' was captured 919e7145dcbSDimitry Andric // by reference. 920e7145dcbSDimitry Andric CXXThisValue = 921e7145dcbSDimitry Andric EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal(); 922e7145dcbSDimitry Andric } 923dff0c46cSDimitry Andric } 92439d628a0SDimitry Andric for (auto *FD : MD->getParent()->fields()) { 92539d628a0SDimitry Andric if (FD->hasCapturedVLAType()) { 92639d628a0SDimitry Andric auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD), 92739d628a0SDimitry Andric SourceLocation()).getScalarVal(); 92839d628a0SDimitry Andric auto VAT = FD->getCapturedVLAType(); 92939d628a0SDimitry Andric VLASizeMap[VAT->getSizeExpr()] = ExprArg; 93039d628a0SDimitry Andric } 93139d628a0SDimitry Andric } 932dff0c46cSDimitry Andric } else { 933dff0c46cSDimitry Andric // Not in a lambda; just use 'this' from the method. 934dff0c46cSDimitry Andric // FIXME: Should we generate a new load for each use of 'this'? The 935dff0c46cSDimitry Andric // fast register allocator would be happier... 936dff0c46cSDimitry Andric CXXThisValue = CXXABIThisValue; 937dff0c46cSDimitry Andric } 938dff0c46cSDimitry Andric } 939f22ef01cSRoman Divacky 940f22ef01cSRoman Divacky // If any of the arguments have a variably modified type, make sure to 941f22ef01cSRoman Divacky // emit the type size. 942f22ef01cSRoman Divacky for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 943f22ef01cSRoman Divacky i != e; ++i) { 944139f7f9bSDimitry Andric const VarDecl *VD = *i; 945139f7f9bSDimitry Andric 946139f7f9bSDimitry Andric // Dig out the type as written from ParmVarDecls; it's unclear whether 947139f7f9bSDimitry Andric // the standard (C99 6.9.1p10) requires this, but we're following the 948139f7f9bSDimitry Andric // precedent set by gcc. 949139f7f9bSDimitry Andric QualType Ty; 950139f7f9bSDimitry Andric if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) 951139f7f9bSDimitry Andric Ty = PVD->getOriginalType(); 952139f7f9bSDimitry Andric else 953139f7f9bSDimitry Andric Ty = VD->getType(); 954f22ef01cSRoman Divacky 955f22ef01cSRoman Divacky if (Ty->isVariablyModifiedType()) 95617a519f9SDimitry Andric EmitVariablyModifiedType(Ty); 957f22ef01cSRoman Divacky } 9586122f3e6SDimitry Andric // Emit a location at the end of the prologue. 9596122f3e6SDimitry Andric if (CGDebugInfo *DI = getDebugInfo()) 9606122f3e6SDimitry Andric DI->EmitLocation(Builder, StartLoc); 961f22ef01cSRoman Divacky } 962f22ef01cSRoman Divacky 963f785676fSDimitry Andric void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args, 964f785676fSDimitry Andric const Stmt *Body) { 96533956c43SDimitry Andric incrementProfileCounter(Body); 966f785676fSDimitry Andric if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body)) 967139f7f9bSDimitry Andric EmitCompoundStmtWithoutScope(*S); 968139f7f9bSDimitry Andric else 969f785676fSDimitry Andric EmitStmt(Body); 970f22ef01cSRoman Divacky } 971f22ef01cSRoman Divacky 97259d1ed5bSDimitry Andric /// When instrumenting to collect profile data, the counts for some blocks 97359d1ed5bSDimitry Andric /// such as switch cases need to not include the fall-through counts, so 97459d1ed5bSDimitry Andric /// emit a branch around the instrumentation code. When not instrumenting, 97559d1ed5bSDimitry Andric /// this just calls EmitBlock(). 97659d1ed5bSDimitry Andric void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB, 97733956c43SDimitry Andric const Stmt *S) { 97859d1ed5bSDimitry Andric llvm::BasicBlock *SkipCountBB = nullptr; 979e7145dcbSDimitry Andric if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) { 98059d1ed5bSDimitry Andric // When instrumenting for profiling, the fallthrough to certain 98159d1ed5bSDimitry Andric // statements needs to skip over the instrumentation code so that we 98259d1ed5bSDimitry Andric // get an accurate count. 98359d1ed5bSDimitry Andric SkipCountBB = createBasicBlock("skipcount"); 98459d1ed5bSDimitry Andric EmitBranch(SkipCountBB); 98559d1ed5bSDimitry Andric } 98659d1ed5bSDimitry Andric EmitBlock(BB); 98733956c43SDimitry Andric uint64_t CurrentCount = getCurrentProfileCount(); 98833956c43SDimitry Andric incrementProfileCounter(S); 98933956c43SDimitry Andric setCurrentProfileCount(getCurrentProfileCount() + CurrentCount); 99059d1ed5bSDimitry Andric if (SkipCountBB) 99159d1ed5bSDimitry Andric EmitBlock(SkipCountBB); 99259d1ed5bSDimitry Andric } 99359d1ed5bSDimitry Andric 994e580952dSDimitry Andric /// Tries to mark the given function nounwind based on the 995e580952dSDimitry Andric /// non-existence of any throwing calls within it. We believe this is 996e580952dSDimitry Andric /// lightweight enough to do at -O0. 997e580952dSDimitry Andric static void TryMarkNoThrow(llvm::Function *F) { 998e580952dSDimitry Andric // LLVM treats 'nounwind' on a function as part of the type, so we 999e580952dSDimitry Andric // can't do this on functions that can be overwritten. 1000e7145dcbSDimitry Andric if (F->isInterposable()) return; 1001e580952dSDimitry Andric 10020623d748SDimitry Andric for (llvm::BasicBlock &BB : *F) 10030623d748SDimitry Andric for (llvm::Instruction &I : BB) 10040623d748SDimitry Andric if (I.mayThrow()) 1005e580952dSDimitry Andric return; 10060623d748SDimitry Andric 10073861d79fSDimitry Andric F->setDoesNotThrow(); 1008e580952dSDimitry Andric } 1009e580952dSDimitry Andric 1010e7145dcbSDimitry Andric QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD, 1011e7145dcbSDimitry Andric FunctionArgList &Args) { 1012f22ef01cSRoman Divacky const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 101359d1ed5bSDimitry Andric QualType ResTy = FD->getReturnType(); 1014f22ef01cSRoman Divacky 101559d1ed5bSDimitry Andric const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 101659d1ed5bSDimitry Andric if (MD && MD->isInstance()) { 1017f785676fSDimitry Andric if (CGM.getCXXABI().HasThisReturn(GD)) 1018f785676fSDimitry Andric ResTy = MD->getThisType(getContext()); 101939d628a0SDimitry Andric else if (CGM.getCXXABI().hasMostDerivedReturn(GD)) 102039d628a0SDimitry Andric ResTy = CGM.getContext().VoidPtrTy; 102159d1ed5bSDimitry Andric CGM.getCXXABI().buildThisParam(*this, Args); 1022f785676fSDimitry Andric } 1023f22ef01cSRoman Divacky 1024e7145dcbSDimitry Andric // The base version of an inheriting constructor whose constructed base is a 1025e7145dcbSDimitry Andric // virtual base is not passed any arguments (because it doesn't actually call 1026e7145dcbSDimitry Andric // the inherited constructor). 1027e7145dcbSDimitry Andric bool PassedParams = true; 1028e7145dcbSDimitry Andric if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 1029e7145dcbSDimitry Andric if (auto Inherited = CD->getInheritedConstructor()) 1030e7145dcbSDimitry Andric PassedParams = 1031e7145dcbSDimitry Andric getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType()); 1032e7145dcbSDimitry Andric 1033e7145dcbSDimitry Andric if (PassedParams) { 1034e7145dcbSDimitry Andric for (auto *Param : FD->parameters()) { 10350623d748SDimitry Andric Args.push_back(Param); 10360623d748SDimitry Andric if (!Param->hasAttr<PassObjectSizeAttr>()) 10370623d748SDimitry Andric continue; 10380623d748SDimitry Andric 10390623d748SDimitry Andric IdentifierInfo *NoID = nullptr; 10400623d748SDimitry Andric auto *Implicit = ImplicitParamDecl::Create( 10410623d748SDimitry Andric getContext(), Param->getDeclContext(), Param->getLocation(), NoID, 10420623d748SDimitry Andric getContext().getSizeType()); 10430623d748SDimitry Andric SizeArguments[Param] = Implicit; 10440623d748SDimitry Andric Args.push_back(Implicit); 10450623d748SDimitry Andric } 1046e7145dcbSDimitry Andric } 1047f22ef01cSRoman Divacky 104859d1ed5bSDimitry Andric if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))) 104959d1ed5bSDimitry Andric CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args); 105059d1ed5bSDimitry Andric 1051e7145dcbSDimitry Andric return ResTy; 1052e7145dcbSDimitry Andric } 1053e7145dcbSDimitry Andric 10548e0f8b8cSDimitry Andric static bool 10558e0f8b8cSDimitry Andric shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD, 10568e0f8b8cSDimitry Andric const ASTContext &Context) { 10578e0f8b8cSDimitry Andric QualType T = FD->getReturnType(); 10588e0f8b8cSDimitry Andric // Avoid the optimization for functions that return a record type with a 10598e0f8b8cSDimitry Andric // trivial destructor or another trivially copyable type. 10608e0f8b8cSDimitry Andric if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) { 10618e0f8b8cSDimitry Andric if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) 10628e0f8b8cSDimitry Andric return !ClassDecl->hasTrivialDestructor(); 10638e0f8b8cSDimitry Andric } 10648e0f8b8cSDimitry Andric return !T.isTriviallyCopyableType(Context); 10658e0f8b8cSDimitry Andric } 10668e0f8b8cSDimitry Andric 1067e7145dcbSDimitry Andric void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn, 1068e7145dcbSDimitry Andric const CGFunctionInfo &FnInfo) { 1069e7145dcbSDimitry Andric const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 1070e7145dcbSDimitry Andric CurGD = GD; 1071e7145dcbSDimitry Andric 1072e7145dcbSDimitry Andric FunctionArgList Args; 1073e7145dcbSDimitry Andric QualType ResTy = BuildFunctionArgList(GD, Args); 1074e7145dcbSDimitry Andric 1075e7145dcbSDimitry Andric // Check if we should generate debug info for this function. 1076e7145dcbSDimitry Andric if (FD->hasAttr<NoDebugAttr>()) 1077e7145dcbSDimitry Andric DebugInfo = nullptr; // disable debug info indefinitely for this function 1078e7145dcbSDimitry Andric 1079f22ef01cSRoman Divacky SourceRange BodyRange; 1080f22ef01cSRoman Divacky if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange(); 1081f785676fSDimitry Andric CurEHLocation = BodyRange.getEnd(); 1082139f7f9bSDimitry Andric 108359d1ed5bSDimitry Andric // Use the location of the start of the function to determine where 108459d1ed5bSDimitry Andric // the function definition is located. By default use the location 108559d1ed5bSDimitry Andric // of the declaration as the location for the subprogram. A function 108659d1ed5bSDimitry Andric // may lack a declaration in the source code if it is created by code 108759d1ed5bSDimitry Andric // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk). 108859d1ed5bSDimitry Andric SourceLocation Loc = FD->getLocation(); 108959d1ed5bSDimitry Andric 109059d1ed5bSDimitry Andric // If this is a function specialization then use the pattern body 109159d1ed5bSDimitry Andric // as the location for the function. 109259d1ed5bSDimitry Andric if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern()) 109359d1ed5bSDimitry Andric if (SpecDecl->hasBody(SpecDecl)) 109459d1ed5bSDimitry Andric Loc = SpecDecl->getLocation(); 109559d1ed5bSDimitry Andric 109644290647SDimitry Andric Stmt *Body = FD->getBody(); 109744290647SDimitry Andric 109844290647SDimitry Andric // Initialize helper which will detect jumps which can cause invalid lifetime 109944290647SDimitry Andric // markers. 110044290647SDimitry Andric if (Body && ShouldEmitLifetimeMarkers) 110144290647SDimitry Andric Bypasses.Init(Body); 110244290647SDimitry Andric 1103f22ef01cSRoman Divacky // Emit the standard function prologue. 110459d1ed5bSDimitry Andric StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin()); 1105f22ef01cSRoman Divacky 1106f22ef01cSRoman Divacky // Generate the body of the function. 11070623d748SDimitry Andric PGO.assignRegionCounters(GD, CurFn); 1108f22ef01cSRoman Divacky if (isa<CXXDestructorDecl>(FD)) 1109f22ef01cSRoman Divacky EmitDestructorBody(Args); 1110f22ef01cSRoman Divacky else if (isa<CXXConstructorDecl>(FD)) 1111f22ef01cSRoman Divacky EmitConstructorBody(Args); 11123861d79fSDimitry Andric else if (getLangOpts().CUDA && 111333956c43SDimitry Andric !getLangOpts().CUDAIsDevice && 11146122f3e6SDimitry Andric FD->hasAttr<CUDAGlobalAttr>()) 111533956c43SDimitry Andric CGM.getCUDARuntime().emitDeviceStub(*this, Args); 1116dff0c46cSDimitry Andric else if (isa<CXXConversionDecl>(FD) && 1117dff0c46cSDimitry Andric cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) { 1118dff0c46cSDimitry Andric // The lambda conversion to block pointer is special; the semantics can't be 1119dff0c46cSDimitry Andric // expressed in the AST, so IRGen needs to special-case it. 1120dff0c46cSDimitry Andric EmitLambdaToBlockPointerBody(Args); 1121dff0c46cSDimitry Andric } else if (isa<CXXMethodDecl>(FD) && 1122dff0c46cSDimitry Andric cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) { 1123f785676fSDimitry Andric // The lambda static invoker function is special, because it forwards or 1124dff0c46cSDimitry Andric // clones the body of the function call operator (but is actually static). 1125dff0c46cSDimitry Andric EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD)); 1126139f7f9bSDimitry Andric } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) && 1127f785676fSDimitry Andric (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() || 1128f785676fSDimitry Andric cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) { 1129139f7f9bSDimitry Andric // Implicit copy-assignment gets the same special treatment as implicit 1130139f7f9bSDimitry Andric // copy-constructors. 1131139f7f9bSDimitry Andric emitImplicitAssignmentOperatorBody(Args); 113244290647SDimitry Andric } else if (Body) { 1133f785676fSDimitry Andric EmitFunctionBody(Args, Body); 1134f785676fSDimitry Andric } else 1135f785676fSDimitry Andric llvm_unreachable("no definition for emitted function"); 1136f22ef01cSRoman Divacky 11373861d79fSDimitry Andric // C++11 [stmt.return]p2: 11383861d79fSDimitry Andric // Flowing off the end of a function [...] results in undefined behavior in 11393861d79fSDimitry Andric // a value-returning function. 11403861d79fSDimitry Andric // C11 6.9.1p12: 11413861d79fSDimitry Andric // If the '}' that terminates a function is reached, and the value of the 11423861d79fSDimitry Andric // function call is used by the caller, the behavior is undefined. 114339d628a0SDimitry Andric if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock && 114459d1ed5bSDimitry Andric !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) { 11458e0f8b8cSDimitry Andric bool ShouldEmitUnreachable = 11468e0f8b8cSDimitry Andric CGM.getCodeGenOpts().StrictReturn || 11478e0f8b8cSDimitry Andric shouldUseUndefinedBehaviorReturnOptimization(FD, getContext()); 114839d628a0SDimitry Andric if (SanOpts.has(SanitizerKind::Return)) { 114959d1ed5bSDimitry Andric SanitizerScope SanScope(this); 115039d628a0SDimitry Andric llvm::Value *IsFalse = Builder.getFalse(); 115139d628a0SDimitry Andric EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return), 115244290647SDimitry Andric SanitizerHandler::MissingReturn, 115344290647SDimitry Andric EmitCheckSourceLocation(FD->getLocation()), None); 11548e0f8b8cSDimitry Andric } else if (ShouldEmitUnreachable) { 11558e0f8b8cSDimitry Andric if (CGM.getCodeGenOpts().OptimizationLevel == 0) 11563dac3a9bSDimitry Andric EmitTrapCall(llvm::Intrinsic::trap); 11573dac3a9bSDimitry Andric } 11588e0f8b8cSDimitry Andric if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) { 11593861d79fSDimitry Andric Builder.CreateUnreachable(); 11603861d79fSDimitry Andric Builder.ClearInsertionPoint(); 11613861d79fSDimitry Andric } 11628e0f8b8cSDimitry Andric } 11633861d79fSDimitry Andric 1164f22ef01cSRoman Divacky // Emit the standard function epilogue. 1165f22ef01cSRoman Divacky FinishFunction(BodyRange.getEnd()); 1166f22ef01cSRoman Divacky 1167e580952dSDimitry Andric // If we haven't marked the function nothrow through other means, do 1168e580952dSDimitry Andric // a quick pass now to see if we can. 1169e580952dSDimitry Andric if (!CurFn->doesNotThrow()) 1170e580952dSDimitry Andric TryMarkNoThrow(CurFn); 1171f22ef01cSRoman Divacky } 1172f22ef01cSRoman Divacky 1173f22ef01cSRoman Divacky /// ContainsLabel - Return true if the statement contains a label in it. If 1174f22ef01cSRoman Divacky /// this statement is not executed normally, it not containing a label means 1175f22ef01cSRoman Divacky /// that we can just remove the code. 1176f22ef01cSRoman Divacky bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 1177f22ef01cSRoman Divacky // Null statement, not a label! 117859d1ed5bSDimitry Andric if (!S) return false; 1179f22ef01cSRoman Divacky 1180f22ef01cSRoman Divacky // If this is a label, we have to emit the code, consider something like: 1181f22ef01cSRoman Divacky // if (0) { ... foo: bar(); } goto foo; 11823b0f4066SDimitry Andric // 11833b0f4066SDimitry Andric // TODO: If anyone cared, we could track __label__'s, since we know that you 11843b0f4066SDimitry Andric // can't jump to one from outside their declared region. 1185f22ef01cSRoman Divacky if (isa<LabelStmt>(S)) 1186f22ef01cSRoman Divacky return true; 1187f22ef01cSRoman Divacky 1188f22ef01cSRoman Divacky // If this is a case/default statement, and we haven't seen a switch, we have 1189f22ef01cSRoman Divacky // to emit the code. 1190f22ef01cSRoman Divacky if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 1191f22ef01cSRoman Divacky return true; 1192f22ef01cSRoman Divacky 1193f22ef01cSRoman Divacky // If this is a switch statement, we want to ignore cases below it. 1194f22ef01cSRoman Divacky if (isa<SwitchStmt>(S)) 1195f22ef01cSRoman Divacky IgnoreCaseStmts = true; 1196f22ef01cSRoman Divacky 1197f22ef01cSRoman Divacky // Scan subexpressions for verboten labels. 11983dac3a9bSDimitry Andric for (const Stmt *SubStmt : S->children()) 11993dac3a9bSDimitry Andric if (ContainsLabel(SubStmt, IgnoreCaseStmts)) 1200f22ef01cSRoman Divacky return true; 1201f22ef01cSRoman Divacky 1202f22ef01cSRoman Divacky return false; 1203f22ef01cSRoman Divacky } 1204f22ef01cSRoman Divacky 12053b0f4066SDimitry Andric /// containsBreak - Return true if the statement contains a break out of it. 12063b0f4066SDimitry Andric /// If the statement (recursively) contains a switch or loop with a break 12073b0f4066SDimitry Andric /// inside of it, this is fine. 12083b0f4066SDimitry Andric bool CodeGenFunction::containsBreak(const Stmt *S) { 12093b0f4066SDimitry Andric // Null statement, not a label! 121059d1ed5bSDimitry Andric if (!S) return false; 1211f22ef01cSRoman Divacky 12123b0f4066SDimitry Andric // If this is a switch or loop that defines its own break scope, then we can 12133b0f4066SDimitry Andric // include it and anything inside of it. 12143b0f4066SDimitry Andric if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) || 12153b0f4066SDimitry Andric isa<ForStmt>(S)) 12163b0f4066SDimitry Andric return false; 12173b0f4066SDimitry Andric 12183b0f4066SDimitry Andric if (isa<BreakStmt>(S)) 12193b0f4066SDimitry Andric return true; 12203b0f4066SDimitry Andric 12213b0f4066SDimitry Andric // Scan subexpressions for verboten breaks. 12223dac3a9bSDimitry Andric for (const Stmt *SubStmt : S->children()) 12233dac3a9bSDimitry Andric if (containsBreak(SubStmt)) 12243b0f4066SDimitry Andric return true; 12253b0f4066SDimitry Andric 12263b0f4066SDimitry Andric return false; 12273b0f4066SDimitry Andric } 12283b0f4066SDimitry Andric 1229f41fbc90SDimitry Andric bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) { 1230f41fbc90SDimitry Andric if (!S) return false; 1231f41fbc90SDimitry Andric 1232f41fbc90SDimitry Andric // Some statement kinds add a scope and thus never add a decl to the current 1233f41fbc90SDimitry Andric // scope. Note, this list is longer than the list of statements that might 1234f41fbc90SDimitry Andric // have an unscoped decl nested within them, but this way is conservatively 1235f41fbc90SDimitry Andric // correct even if more statement kinds are added. 1236f41fbc90SDimitry Andric if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) || 1237f41fbc90SDimitry Andric isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) || 1238f41fbc90SDimitry Andric isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) || 1239f41fbc90SDimitry Andric isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S)) 1240f41fbc90SDimitry Andric return false; 1241f41fbc90SDimitry Andric 1242f41fbc90SDimitry Andric if (isa<DeclStmt>(S)) 1243f41fbc90SDimitry Andric return true; 1244f41fbc90SDimitry Andric 1245f41fbc90SDimitry Andric for (const Stmt *SubStmt : S->children()) 1246f41fbc90SDimitry Andric if (mightAddDeclToScope(SubStmt)) 1247f41fbc90SDimitry Andric return true; 1248f41fbc90SDimitry Andric 1249f41fbc90SDimitry Andric return false; 1250f41fbc90SDimitry Andric } 12513b0f4066SDimitry Andric 12523b0f4066SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 12533b0f4066SDimitry Andric /// to a constant, or if it does but contains a label, return false. If it 12543b0f4066SDimitry Andric /// constant folds return true and set the boolean result in Result. 12553b0f4066SDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 1256e7145dcbSDimitry Andric bool &ResultBool, 1257e7145dcbSDimitry Andric bool AllowLabels) { 12587ae0e2c9SDimitry Andric llvm::APSInt ResultInt; 1259e7145dcbSDimitry Andric if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels)) 12603b0f4066SDimitry Andric return false; 12613b0f4066SDimitry Andric 12623b0f4066SDimitry Andric ResultBool = ResultInt.getBoolValue(); 12633b0f4066SDimitry Andric return true; 12643b0f4066SDimitry Andric } 12653b0f4066SDimitry Andric 12663b0f4066SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 12673b0f4066SDimitry Andric /// to a constant, or if it does but contains a label, return false. If it 12683b0f4066SDimitry Andric /// constant folds return true and set the folded value. 1269e7145dcbSDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 1270e7145dcbSDimitry Andric llvm::APSInt &ResultInt, 1271e7145dcbSDimitry Andric bool AllowLabels) { 1272f22ef01cSRoman Divacky // FIXME: Rename and handle conversion of other evaluatable things 1273f22ef01cSRoman Divacky // to bool. 1274dff0c46cSDimitry Andric llvm::APSInt Int; 1275dff0c46cSDimitry Andric if (!Cond->EvaluateAsInt(Int, getContext())) 12763b0f4066SDimitry Andric return false; // Not foldable, not integer or not fully evaluatable. 1277f22ef01cSRoman Divacky 1278e7145dcbSDimitry Andric if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond)) 12793b0f4066SDimitry Andric return false; // Contains a label. 1280f22ef01cSRoman Divacky 1281dff0c46cSDimitry Andric ResultInt = Int; 12823b0f4066SDimitry Andric return true; 1283f22ef01cSRoman Divacky } 1284f22ef01cSRoman Divacky 1285f22ef01cSRoman Divacky 12863b0f4066SDimitry Andric 1287f22ef01cSRoman Divacky /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 1288f22ef01cSRoman Divacky /// statement) to the specified blocks. Based on the condition, this might try 1289f22ef01cSRoman Divacky /// to simplify the codegen of the conditional based on the branch. 1290f22ef01cSRoman Divacky /// 1291f22ef01cSRoman Divacky void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 1292f22ef01cSRoman Divacky llvm::BasicBlock *TrueBlock, 129359d1ed5bSDimitry Andric llvm::BasicBlock *FalseBlock, 129459d1ed5bSDimitry Andric uint64_t TrueCount) { 12953b0f4066SDimitry Andric Cond = Cond->IgnoreParens(); 1296f22ef01cSRoman Divacky 1297f22ef01cSRoman Divacky if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 129859d1ed5bSDimitry Andric 1299f22ef01cSRoman Divacky // Handle X && Y in a condition. 1300e580952dSDimitry Andric if (CondBOp->getOpcode() == BO_LAnd) { 1301f22ef01cSRoman Divacky // If we have "1 && X", simplify the code. "0 && X" would have constant 1302f22ef01cSRoman Divacky // folded if the case was simple enough. 13033b0f4066SDimitry Andric bool ConstantBool = false; 13043b0f4066SDimitry Andric if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 13053b0f4066SDimitry Andric ConstantBool) { 1306f22ef01cSRoman Divacky // br(1 && X) -> br(X). 130733956c43SDimitry Andric incrementProfileCounter(CondBOp); 130859d1ed5bSDimitry Andric return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, 130959d1ed5bSDimitry Andric TrueCount); 1310f22ef01cSRoman Divacky } 1311f22ef01cSRoman Divacky 1312f22ef01cSRoman Divacky // If we have "X && 1", simplify the code to use an uncond branch. 1313f22ef01cSRoman Divacky // "X && 0" would have been constant folded to 0. 13143b0f4066SDimitry Andric if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 13153b0f4066SDimitry Andric ConstantBool) { 1316f22ef01cSRoman Divacky // br(X && 1) -> br(X). 131759d1ed5bSDimitry Andric return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock, 131859d1ed5bSDimitry Andric TrueCount); 1319f22ef01cSRoman Divacky } 1320f22ef01cSRoman Divacky 1321f22ef01cSRoman Divacky // Emit the LHS as a conditional. If the LHS conditional is false, we 1322f22ef01cSRoman Divacky // want to jump to the FalseBlock. 1323f22ef01cSRoman Divacky llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 132459d1ed5bSDimitry Andric // The counter tells us how often we evaluate RHS, and all of TrueCount 132559d1ed5bSDimitry Andric // can be propagated to that branch. 132633956c43SDimitry Andric uint64_t RHSCount = getProfileCount(CondBOp->getRHS()); 13272754fe60SDimitry Andric 13282754fe60SDimitry Andric ConditionalEvaluation eval(*this); 132933956c43SDimitry Andric { 133033956c43SDimitry Andric ApplyDebugLocation DL(*this, Cond); 133159d1ed5bSDimitry Andric EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount); 1332f22ef01cSRoman Divacky EmitBlock(LHSTrue); 133333956c43SDimitry Andric } 133433956c43SDimitry Andric 133533956c43SDimitry Andric incrementProfileCounter(CondBOp); 133633956c43SDimitry Andric setCurrentProfileCount(getProfileCount(CondBOp->getRHS())); 1337f22ef01cSRoman Divacky 1338f22ef01cSRoman Divacky // Any temporaries created here are conditional. 13392754fe60SDimitry Andric eval.begin(*this); 134059d1ed5bSDimitry Andric EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount); 13412754fe60SDimitry Andric eval.end(*this); 1342f22ef01cSRoman Divacky 1343f22ef01cSRoman Divacky return; 13443b0f4066SDimitry Andric } 13453b0f4066SDimitry Andric 13463b0f4066SDimitry Andric if (CondBOp->getOpcode() == BO_LOr) { 1347f22ef01cSRoman Divacky // If we have "0 || X", simplify the code. "1 || X" would have constant 1348f22ef01cSRoman Divacky // folded if the case was simple enough. 13493b0f4066SDimitry Andric bool ConstantBool = false; 13503b0f4066SDimitry Andric if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 13513b0f4066SDimitry Andric !ConstantBool) { 1352f22ef01cSRoman Divacky // br(0 || X) -> br(X). 135333956c43SDimitry Andric incrementProfileCounter(CondBOp); 135459d1ed5bSDimitry Andric return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, 135559d1ed5bSDimitry Andric TrueCount); 1356f22ef01cSRoman Divacky } 1357f22ef01cSRoman Divacky 1358f22ef01cSRoman Divacky // If we have "X || 0", simplify the code to use an uncond branch. 1359f22ef01cSRoman Divacky // "X || 1" would have been constant folded to 1. 13603b0f4066SDimitry Andric if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 13613b0f4066SDimitry Andric !ConstantBool) { 1362f22ef01cSRoman Divacky // br(X || 0) -> br(X). 136359d1ed5bSDimitry Andric return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock, 136459d1ed5bSDimitry Andric TrueCount); 1365f22ef01cSRoman Divacky } 1366f22ef01cSRoman Divacky 1367f22ef01cSRoman Divacky // Emit the LHS as a conditional. If the LHS conditional is true, we 1368f22ef01cSRoman Divacky // want to jump to the TrueBlock. 1369f22ef01cSRoman Divacky llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 137059d1ed5bSDimitry Andric // We have the count for entry to the RHS and for the whole expression 137159d1ed5bSDimitry Andric // being true, so we can divy up True count between the short circuit and 137259d1ed5bSDimitry Andric // the RHS. 137333956c43SDimitry Andric uint64_t LHSCount = 137433956c43SDimitry Andric getCurrentProfileCount() - getProfileCount(CondBOp->getRHS()); 137559d1ed5bSDimitry Andric uint64_t RHSCount = TrueCount - LHSCount; 13762754fe60SDimitry Andric 13772754fe60SDimitry Andric ConditionalEvaluation eval(*this); 137833956c43SDimitry Andric { 137933956c43SDimitry Andric ApplyDebugLocation DL(*this, Cond); 138059d1ed5bSDimitry Andric EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount); 1381f22ef01cSRoman Divacky EmitBlock(LHSFalse); 138233956c43SDimitry Andric } 138333956c43SDimitry Andric 138433956c43SDimitry Andric incrementProfileCounter(CondBOp); 138533956c43SDimitry Andric setCurrentProfileCount(getProfileCount(CondBOp->getRHS())); 1386f22ef01cSRoman Divacky 1387f22ef01cSRoman Divacky // Any temporaries created here are conditional. 13882754fe60SDimitry Andric eval.begin(*this); 138959d1ed5bSDimitry Andric EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount); 139059d1ed5bSDimitry Andric 13912754fe60SDimitry Andric eval.end(*this); 1392f22ef01cSRoman Divacky 1393f22ef01cSRoman Divacky return; 1394f22ef01cSRoman Divacky } 1395f22ef01cSRoman Divacky } 1396f22ef01cSRoman Divacky 1397f22ef01cSRoman Divacky if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 1398f22ef01cSRoman Divacky // br(!x, t, f) -> br(x, f, t) 139959d1ed5bSDimitry Andric if (CondUOp->getOpcode() == UO_LNot) { 140059d1ed5bSDimitry Andric // Negate the count. 140133956c43SDimitry Andric uint64_t FalseCount = getCurrentProfileCount() - TrueCount; 140259d1ed5bSDimitry Andric // Negate the condition and swap the destination blocks. 140359d1ed5bSDimitry Andric return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock, 140459d1ed5bSDimitry Andric FalseCount); 140559d1ed5bSDimitry Andric } 1406f22ef01cSRoman Divacky } 1407f22ef01cSRoman Divacky 1408f22ef01cSRoman Divacky if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 1409f22ef01cSRoman Divacky // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 1410f22ef01cSRoman Divacky llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 1411f22ef01cSRoman Divacky llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 14122754fe60SDimitry Andric 14132754fe60SDimitry Andric ConditionalEvaluation cond(*this); 141433956c43SDimitry Andric EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock, 141533956c43SDimitry Andric getProfileCount(CondOp)); 141659d1ed5bSDimitry Andric 141759d1ed5bSDimitry Andric // When computing PGO branch weights, we only know the overall count for 141859d1ed5bSDimitry Andric // the true block. This code is essentially doing tail duplication of the 141959d1ed5bSDimitry Andric // naive code-gen, introducing new edges for which counts are not 142059d1ed5bSDimitry Andric // available. Divide the counts proportionally between the LHS and RHS of 142159d1ed5bSDimitry Andric // the conditional operator. 142259d1ed5bSDimitry Andric uint64_t LHSScaledTrueCount = 0; 142359d1ed5bSDimitry Andric if (TrueCount) { 142433956c43SDimitry Andric double LHSRatio = 142533956c43SDimitry Andric getProfileCount(CondOp) / (double)getCurrentProfileCount(); 142659d1ed5bSDimitry Andric LHSScaledTrueCount = TrueCount * LHSRatio; 142759d1ed5bSDimitry Andric } 14282754fe60SDimitry Andric 14292754fe60SDimitry Andric cond.begin(*this); 1430f22ef01cSRoman Divacky EmitBlock(LHSBlock); 143133956c43SDimitry Andric incrementProfileCounter(CondOp); 143233956c43SDimitry Andric { 143333956c43SDimitry Andric ApplyDebugLocation DL(*this, Cond); 143459d1ed5bSDimitry Andric EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock, 143559d1ed5bSDimitry Andric LHSScaledTrueCount); 143633956c43SDimitry Andric } 14372754fe60SDimitry Andric cond.end(*this); 14382754fe60SDimitry Andric 14392754fe60SDimitry Andric cond.begin(*this); 1440f22ef01cSRoman Divacky EmitBlock(RHSBlock); 144159d1ed5bSDimitry Andric EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock, 144259d1ed5bSDimitry Andric TrueCount - LHSScaledTrueCount); 14432754fe60SDimitry Andric cond.end(*this); 14442754fe60SDimitry Andric 1445f22ef01cSRoman Divacky return; 1446f22ef01cSRoman Divacky } 1447f22ef01cSRoman Divacky 1448284c1978SDimitry Andric if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) { 1449284c1978SDimitry Andric // Conditional operator handling can give us a throw expression as a 1450284c1978SDimitry Andric // condition for a case like: 1451284c1978SDimitry Andric // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f) 1452284c1978SDimitry Andric // Fold this to: 1453284c1978SDimitry Andric // br(c, throw x, br(y, t, f)) 1454284c1978SDimitry Andric EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false); 1455284c1978SDimitry Andric return; 1456284c1978SDimitry Andric } 1457284c1978SDimitry Andric 14580623d748SDimitry Andric // If the branch has a condition wrapped by __builtin_unpredictable, 14590623d748SDimitry Andric // create metadata that specifies that the branch is unpredictable. 14600623d748SDimitry Andric // Don't bother if not optimizing because that metadata would not be used. 14610623d748SDimitry Andric llvm::MDNode *Unpredictable = nullptr; 1462e7145dcbSDimitry Andric auto *Call = dyn_cast<CallExpr>(Cond); 1463e7145dcbSDimitry Andric if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) { 1464e7145dcbSDimitry Andric auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl()); 1465e7145dcbSDimitry Andric if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) { 14660623d748SDimitry Andric llvm::MDBuilder MDHelper(getLLVMContext()); 14670623d748SDimitry Andric Unpredictable = MDHelper.createUnpredictable(); 14680623d748SDimitry Andric } 14690623d748SDimitry Andric } 14700623d748SDimitry Andric 147159d1ed5bSDimitry Andric // Create branch weights based on the number of times we get here and the 147259d1ed5bSDimitry Andric // number of times the condition should be true. 147333956c43SDimitry Andric uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount); 147433956c43SDimitry Andric llvm::MDNode *Weights = 147533956c43SDimitry Andric createProfileWeights(TrueCount, CurrentCount - TrueCount); 147659d1ed5bSDimitry Andric 1477f22ef01cSRoman Divacky // Emit the code with the fully general case. 147833956c43SDimitry Andric llvm::Value *CondV; 147933956c43SDimitry Andric { 148033956c43SDimitry Andric ApplyDebugLocation DL(*this, Cond); 148133956c43SDimitry Andric CondV = EvaluateExprAsBool(Cond); 148233956c43SDimitry Andric } 14830623d748SDimitry Andric Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable); 1484f22ef01cSRoman Divacky } 1485f22ef01cSRoman Divacky 1486f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 1487f22ef01cSRoman Divacky /// specified stmt yet. 1488f785676fSDimitry Andric void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) { 1489f785676fSDimitry Andric CGM.ErrorUnsupported(S, Type); 1490f22ef01cSRoman Divacky } 1491f22ef01cSRoman Divacky 14922754fe60SDimitry Andric /// emitNonZeroVLAInit - Emit the "zero" initialization of a 14932754fe60SDimitry Andric /// variable-length array whose elements have a non-zero bit-pattern. 14942754fe60SDimitry Andric /// 14957ae0e2c9SDimitry Andric /// \param baseType the inner-most element type of the array 14962754fe60SDimitry Andric /// \param src - a char* pointing to the bit-pattern for a single 14972754fe60SDimitry Andric /// base element of the array 14982754fe60SDimitry Andric /// \param sizeInChars - the total size of the VLA, in chars 14992754fe60SDimitry Andric static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, 15000623d748SDimitry Andric Address dest, Address src, 15012754fe60SDimitry Andric llvm::Value *sizeInChars) { 15022754fe60SDimitry Andric CGBuilderTy &Builder = CGF.Builder; 15032754fe60SDimitry Andric 15040623d748SDimitry Andric CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType); 15052754fe60SDimitry Andric llvm::Value *baseSizeInChars 15060623d748SDimitry Andric = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity()); 15072754fe60SDimitry Andric 15080623d748SDimitry Andric Address begin = 15090623d748SDimitry Andric Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin"); 15100623d748SDimitry Andric llvm::Value *end = 15110623d748SDimitry Andric Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end"); 15122754fe60SDimitry Andric 15132754fe60SDimitry Andric llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock(); 15142754fe60SDimitry Andric llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop"); 15152754fe60SDimitry Andric llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont"); 15162754fe60SDimitry Andric 15172754fe60SDimitry Andric // Make a loop over the VLA. C99 guarantees that the VLA element 15182754fe60SDimitry Andric // count must be nonzero. 15192754fe60SDimitry Andric CGF.EmitBlock(loopBB); 15202754fe60SDimitry Andric 15210623d748SDimitry Andric llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur"); 15220623d748SDimitry Andric cur->addIncoming(begin.getPointer(), originBB); 15230623d748SDimitry Andric 15240623d748SDimitry Andric CharUnits curAlign = 15250623d748SDimitry Andric dest.getAlignment().alignmentOfArrayElement(baseSize); 15262754fe60SDimitry Andric 15272754fe60SDimitry Andric // memcpy the individual element bit-pattern. 15280623d748SDimitry Andric Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars, 15292754fe60SDimitry Andric /*volatile*/ false); 15302754fe60SDimitry Andric 15312754fe60SDimitry Andric // Go to the next element. 15320623d748SDimitry Andric llvm::Value *next = 15330623d748SDimitry Andric Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next"); 15342754fe60SDimitry Andric 15352754fe60SDimitry Andric // Leave if that's the end of the VLA. 15362754fe60SDimitry Andric llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone"); 15372754fe60SDimitry Andric Builder.CreateCondBr(done, contBB, loopBB); 15382754fe60SDimitry Andric cur->addIncoming(next, loopBB); 15392754fe60SDimitry Andric 15402754fe60SDimitry Andric CGF.EmitBlock(contBB); 15412754fe60SDimitry Andric } 15422754fe60SDimitry Andric 1543f22ef01cSRoman Divacky void 15440623d748SDimitry Andric CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) { 1545f22ef01cSRoman Divacky // Ignore empty classes in C++. 15463861d79fSDimitry Andric if (getLangOpts().CPlusPlus) { 1547f22ef01cSRoman Divacky if (const RecordType *RT = Ty->getAs<RecordType>()) { 1548f22ef01cSRoman Divacky if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty()) 1549f22ef01cSRoman Divacky return; 1550f22ef01cSRoman Divacky } 1551f22ef01cSRoman Divacky } 1552f22ef01cSRoman Divacky 1553e580952dSDimitry Andric // Cast the dest ptr to the appropriate i8 pointer type. 15540623d748SDimitry Andric if (DestPtr.getElementType() != Int8Ty) 15550623d748SDimitry Andric DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty); 1556f22ef01cSRoman Divacky 1557f22ef01cSRoman Divacky // Get size and alignment info for this aggregate. 15580623d748SDimitry Andric CharUnits size = getContext().getTypeSizeInChars(Ty); 15592754fe60SDimitry Andric 15602754fe60SDimitry Andric llvm::Value *SizeVal; 15612754fe60SDimitry Andric const VariableArrayType *vla; 1562f22ef01cSRoman Divacky 1563f22ef01cSRoman Divacky // Don't bother emitting a zero-byte memset. 15640623d748SDimitry Andric if (size.isZero()) { 15652754fe60SDimitry Andric // But note that getTypeInfo returns 0 for a VLA. 15662754fe60SDimitry Andric if (const VariableArrayType *vlaType = 15672754fe60SDimitry Andric dyn_cast_or_null<VariableArrayType>( 15682754fe60SDimitry Andric getContext().getAsArrayType(Ty))) { 156917a519f9SDimitry Andric QualType eltType; 157017a519f9SDimitry Andric llvm::Value *numElts; 157159d1ed5bSDimitry Andric std::tie(numElts, eltType) = getVLASize(vlaType); 157217a519f9SDimitry Andric 157317a519f9SDimitry Andric SizeVal = numElts; 157417a519f9SDimitry Andric CharUnits eltSize = getContext().getTypeSizeInChars(eltType); 157517a519f9SDimitry Andric if (!eltSize.isOne()) 157617a519f9SDimitry Andric SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize)); 15772754fe60SDimitry Andric vla = vlaType; 15782754fe60SDimitry Andric } else { 1579f22ef01cSRoman Divacky return; 15802754fe60SDimitry Andric } 15812754fe60SDimitry Andric } else { 15820623d748SDimitry Andric SizeVal = CGM.getSize(size); 158359d1ed5bSDimitry Andric vla = nullptr; 15842754fe60SDimitry Andric } 1585e580952dSDimitry Andric 1586e580952dSDimitry Andric // If the type contains a pointer to data member we can't memset it to zero. 1587e580952dSDimitry Andric // Instead, create a null constant and copy it to the destination. 15882754fe60SDimitry Andric // TODO: there are other patterns besides zero that we can usefully memset, 15892754fe60SDimitry Andric // like -1, which happens to be the pattern used by member-pointers. 1590e580952dSDimitry Andric if (!CGM.getTypes().isZeroInitializable(Ty)) { 15912754fe60SDimitry Andric // For a VLA, emit a single element, then splat that over the VLA. 15922754fe60SDimitry Andric if (vla) Ty = getContext().getBaseElementType(vla); 15932754fe60SDimitry Andric 1594e580952dSDimitry Andric llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty); 1595e580952dSDimitry Andric 1596e580952dSDimitry Andric llvm::GlobalVariable *NullVariable = 1597e580952dSDimitry Andric new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(), 1598e580952dSDimitry Andric /*isConstant=*/true, 1599e580952dSDimitry Andric llvm::GlobalVariable::PrivateLinkage, 16006122f3e6SDimitry Andric NullConstant, Twine()); 16010623d748SDimitry Andric CharUnits NullAlign = DestPtr.getAlignment(); 16020623d748SDimitry Andric NullVariable->setAlignment(NullAlign.getQuantity()); 16030623d748SDimitry Andric Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()), 16040623d748SDimitry Andric NullAlign); 1605e580952dSDimitry Andric 16062754fe60SDimitry Andric if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal); 1607e580952dSDimitry Andric 1608e580952dSDimitry Andric // Get and call the appropriate llvm.memcpy overload. 16090623d748SDimitry Andric Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false); 1610e580952dSDimitry Andric return; 1611e580952dSDimitry Andric } 1612e580952dSDimitry Andric 1613e580952dSDimitry Andric // Otherwise, just memset the whole thing to zero. This is legal 1614e580952dSDimitry Andric // because in LLVM, all default initializers (other than the ones we just 1615e580952dSDimitry Andric // handled above) are guaranteed to have a bit pattern of all zeros. 16160623d748SDimitry Andric Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false); 1617f22ef01cSRoman Divacky } 1618f22ef01cSRoman Divacky 16192754fe60SDimitry Andric llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) { 1620f22ef01cSRoman Divacky // Make sure that there is a block for the indirect goto. 162159d1ed5bSDimitry Andric if (!IndirectBranch) 1622f22ef01cSRoman Divacky GetIndirectGotoBlock(); 1623f22ef01cSRoman Divacky 1624e580952dSDimitry Andric llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock(); 1625f22ef01cSRoman Divacky 1626f22ef01cSRoman Divacky // Make sure the indirect branch includes all of the address-taken blocks. 1627f22ef01cSRoman Divacky IndirectBranch->addDestination(BB); 1628f22ef01cSRoman Divacky return llvm::BlockAddress::get(CurFn, BB); 1629f22ef01cSRoman Divacky } 1630f22ef01cSRoman Divacky 1631f22ef01cSRoman Divacky llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() { 1632f22ef01cSRoman Divacky // If we already made the indirect branch for indirect goto, return its block. 1633f22ef01cSRoman Divacky if (IndirectBranch) return IndirectBranch->getParent(); 1634f22ef01cSRoman Divacky 16350623d748SDimitry Andric CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto")); 1636f22ef01cSRoman Divacky 1637f22ef01cSRoman Divacky // Create the PHI node that indirect gotos will add entries to. 16383b0f4066SDimitry Andric llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0, 16393b0f4066SDimitry Andric "indirect.goto.dest"); 1640f22ef01cSRoman Divacky 1641f22ef01cSRoman Divacky // Create the indirect branch instruction. 1642f22ef01cSRoman Divacky IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal); 1643f22ef01cSRoman Divacky return IndirectBranch->getParent(); 1644f22ef01cSRoman Divacky } 1645f22ef01cSRoman Divacky 164617a519f9SDimitry Andric /// Computes the length of an array in elements, as well as the base 164717a519f9SDimitry Andric /// element type and a properly-typed first element pointer. 164817a519f9SDimitry Andric llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType, 164917a519f9SDimitry Andric QualType &baseType, 16500623d748SDimitry Andric Address &addr) { 165117a519f9SDimitry Andric const ArrayType *arrayType = origArrayType; 1652f22ef01cSRoman Divacky 165317a519f9SDimitry Andric // If it's a VLA, we have to load the stored size. Note that 165417a519f9SDimitry Andric // this is the size of the VLA in bytes, not its size in elements. 165559d1ed5bSDimitry Andric llvm::Value *numVLAElements = nullptr; 165617a519f9SDimitry Andric if (isa<VariableArrayType>(arrayType)) { 165717a519f9SDimitry Andric numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first; 165817a519f9SDimitry Andric 165917a519f9SDimitry Andric // Walk into all VLAs. This doesn't require changes to addr, 166017a519f9SDimitry Andric // which has type T* where T is the first non-VLA element type. 166117a519f9SDimitry Andric do { 166217a519f9SDimitry Andric QualType elementType = arrayType->getElementType(); 166317a519f9SDimitry Andric arrayType = getContext().getAsArrayType(elementType); 166417a519f9SDimitry Andric 166517a519f9SDimitry Andric // If we only have VLA components, 'addr' requires no adjustment. 166617a519f9SDimitry Andric if (!arrayType) { 166717a519f9SDimitry Andric baseType = elementType; 166817a519f9SDimitry Andric return numVLAElements; 166917a519f9SDimitry Andric } 167017a519f9SDimitry Andric } while (isa<VariableArrayType>(arrayType)); 167117a519f9SDimitry Andric 167217a519f9SDimitry Andric // We get out here only if we find a constant array type 167317a519f9SDimitry Andric // inside the VLA. 1674f22ef01cSRoman Divacky } 1675f22ef01cSRoman Divacky 167617a519f9SDimitry Andric // We have some number of constant-length arrays, so addr should 167717a519f9SDimitry Andric // have LLVM type [M x [N x [...]]]*. Build a GEP that walks 167817a519f9SDimitry Andric // down to the first element of addr. 16796122f3e6SDimitry Andric SmallVector<llvm::Value*, 8> gepIndices; 168017a519f9SDimitry Andric 168117a519f9SDimitry Andric // GEP down to the array type. 168217a519f9SDimitry Andric llvm::ConstantInt *zero = Builder.getInt32(0); 168317a519f9SDimitry Andric gepIndices.push_back(zero); 168417a519f9SDimitry Andric 168517a519f9SDimitry Andric uint64_t countFromCLAs = 1; 16867ae0e2c9SDimitry Andric QualType eltType; 168717a519f9SDimitry Andric 16886122f3e6SDimitry Andric llvm::ArrayType *llvmArrayType = 16890623d748SDimitry Andric dyn_cast<llvm::ArrayType>(addr.getElementType()); 16907ae0e2c9SDimitry Andric while (llvmArrayType) { 169117a519f9SDimitry Andric assert(isa<ConstantArrayType>(arrayType)); 169217a519f9SDimitry Andric assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue() 169317a519f9SDimitry Andric == llvmArrayType->getNumElements()); 169417a519f9SDimitry Andric 169517a519f9SDimitry Andric gepIndices.push_back(zero); 169617a519f9SDimitry Andric countFromCLAs *= llvmArrayType->getNumElements(); 16977ae0e2c9SDimitry Andric eltType = arrayType->getElementType(); 169817a519f9SDimitry Andric 169917a519f9SDimitry Andric llvmArrayType = 170017a519f9SDimitry Andric dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType()); 170117a519f9SDimitry Andric arrayType = getContext().getAsArrayType(arrayType->getElementType()); 17027ae0e2c9SDimitry Andric assert((!llvmArrayType || arrayType) && 17037ae0e2c9SDimitry Andric "LLVM and Clang types are out-of-synch"); 170417a519f9SDimitry Andric } 170517a519f9SDimitry Andric 17067ae0e2c9SDimitry Andric if (arrayType) { 17077ae0e2c9SDimitry Andric // From this point onwards, the Clang array type has been emitted 17087ae0e2c9SDimitry Andric // as some other type (probably a packed struct). Compute the array 17097ae0e2c9SDimitry Andric // size, and just emit the 'begin' expression as a bitcast. 17107ae0e2c9SDimitry Andric while (arrayType) { 17117ae0e2c9SDimitry Andric countFromCLAs *= 17127ae0e2c9SDimitry Andric cast<ConstantArrayType>(arrayType)->getSize().getZExtValue(); 17137ae0e2c9SDimitry Andric eltType = arrayType->getElementType(); 17147ae0e2c9SDimitry Andric arrayType = getContext().getAsArrayType(eltType); 17157ae0e2c9SDimitry Andric } 171617a519f9SDimitry Andric 17170623d748SDimitry Andric llvm::Type *baseType = ConvertType(eltType); 17180623d748SDimitry Andric addr = Builder.CreateElementBitCast(addr, baseType, "array.begin"); 17197ae0e2c9SDimitry Andric } else { 172017a519f9SDimitry Andric // Create the actual GEP. 17210623d748SDimitry Andric addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(), 17220623d748SDimitry Andric gepIndices, "array.begin"), 17230623d748SDimitry Andric addr.getAlignment()); 17247ae0e2c9SDimitry Andric } 17257ae0e2c9SDimitry Andric 17267ae0e2c9SDimitry Andric baseType = eltType; 172717a519f9SDimitry Andric 172817a519f9SDimitry Andric llvm::Value *numElements 172917a519f9SDimitry Andric = llvm::ConstantInt::get(SizeTy, countFromCLAs); 173017a519f9SDimitry Andric 173117a519f9SDimitry Andric // If we had any VLA dimensions, factor them in. 173217a519f9SDimitry Andric if (numVLAElements) 173317a519f9SDimitry Andric numElements = Builder.CreateNUWMul(numVLAElements, numElements); 173417a519f9SDimitry Andric 173517a519f9SDimitry Andric return numElements; 173617a519f9SDimitry Andric } 173717a519f9SDimitry Andric 173817a519f9SDimitry Andric std::pair<llvm::Value*, QualType> 173917a519f9SDimitry Andric CodeGenFunction::getVLASize(QualType type) { 174017a519f9SDimitry Andric const VariableArrayType *vla = getContext().getAsVariableArrayType(type); 174117a519f9SDimitry Andric assert(vla && "type was not a variable array type!"); 174217a519f9SDimitry Andric return getVLASize(vla); 174317a519f9SDimitry Andric } 174417a519f9SDimitry Andric 174517a519f9SDimitry Andric std::pair<llvm::Value*, QualType> 174617a519f9SDimitry Andric CodeGenFunction::getVLASize(const VariableArrayType *type) { 174717a519f9SDimitry Andric // The number of elements so far; always size_t. 174859d1ed5bSDimitry Andric llvm::Value *numElements = nullptr; 174917a519f9SDimitry Andric 175017a519f9SDimitry Andric QualType elementType; 175117a519f9SDimitry Andric do { 175217a519f9SDimitry Andric elementType = type->getElementType(); 175317a519f9SDimitry Andric llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()]; 175417a519f9SDimitry Andric assert(vlaSize && "no size for VLA!"); 175517a519f9SDimitry Andric assert(vlaSize->getType() == SizeTy); 175617a519f9SDimitry Andric 175717a519f9SDimitry Andric if (!numElements) { 175817a519f9SDimitry Andric numElements = vlaSize; 175917a519f9SDimitry Andric } else { 176017a519f9SDimitry Andric // It's undefined behavior if this wraps around, so mark it that way. 176159d1ed5bSDimitry Andric // FIXME: Teach -fsanitize=undefined to trap this. 176217a519f9SDimitry Andric numElements = Builder.CreateNUWMul(numElements, vlaSize); 176317a519f9SDimitry Andric } 176417a519f9SDimitry Andric } while ((type = getContext().getAsVariableArrayType(elementType))); 176517a519f9SDimitry Andric 176617a519f9SDimitry Andric return std::pair<llvm::Value*,QualType>(numElements, elementType); 176717a519f9SDimitry Andric } 176817a519f9SDimitry Andric 176917a519f9SDimitry Andric void CodeGenFunction::EmitVariablyModifiedType(QualType type) { 177017a519f9SDimitry Andric assert(type->isVariablyModifiedType() && 1771f22ef01cSRoman Divacky "Must pass variably modified type to EmitVLASizes!"); 1772f22ef01cSRoman Divacky 1773f22ef01cSRoman Divacky EnsureInsertPoint(); 1774f22ef01cSRoman Divacky 177517a519f9SDimitry Andric // We're going to walk down into the type and look for VLA 177617a519f9SDimitry Andric // expressions. 177717a519f9SDimitry Andric do { 177817a519f9SDimitry Andric assert(type->isVariablyModifiedType()); 1779f22ef01cSRoman Divacky 178017a519f9SDimitry Andric const Type *ty = type.getTypePtr(); 178117a519f9SDimitry Andric switch (ty->getTypeClass()) { 1782dff0c46cSDimitry Andric 178317a519f9SDimitry Andric #define TYPE(Class, Base) 178417a519f9SDimitry Andric #define ABSTRACT_TYPE(Class, Base) 1785dff0c46cSDimitry Andric #define NON_CANONICAL_TYPE(Class, Base) 178617a519f9SDimitry Andric #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1787dff0c46cSDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 178817a519f9SDimitry Andric #include "clang/AST/TypeNodes.def" 1789dff0c46cSDimitry Andric llvm_unreachable("unexpected dependent type!"); 1790f22ef01cSRoman Divacky 179117a519f9SDimitry Andric // These types are never variably-modified. 179217a519f9SDimitry Andric case Type::Builtin: 179317a519f9SDimitry Andric case Type::Complex: 179417a519f9SDimitry Andric case Type::Vector: 179517a519f9SDimitry Andric case Type::ExtVector: 179617a519f9SDimitry Andric case Type::Record: 179717a519f9SDimitry Andric case Type::Enum: 1798dff0c46cSDimitry Andric case Type::Elaborated: 1799dff0c46cSDimitry Andric case Type::TemplateSpecialization: 180044290647SDimitry Andric case Type::ObjCTypeParam: 180117a519f9SDimitry Andric case Type::ObjCObject: 180217a519f9SDimitry Andric case Type::ObjCInterface: 180317a519f9SDimitry Andric case Type::ObjCObjectPointer: 180417a519f9SDimitry Andric llvm_unreachable("type class is never variably-modified!"); 1805f22ef01cSRoman Divacky 180659d1ed5bSDimitry Andric case Type::Adjusted: 180759d1ed5bSDimitry Andric type = cast<AdjustedType>(ty)->getAdjustedType(); 180859d1ed5bSDimitry Andric break; 180959d1ed5bSDimitry Andric 1810f785676fSDimitry Andric case Type::Decayed: 1811f785676fSDimitry Andric type = cast<DecayedType>(ty)->getPointeeType(); 1812f785676fSDimitry Andric break; 1813f785676fSDimitry Andric 181417a519f9SDimitry Andric case Type::Pointer: 181517a519f9SDimitry Andric type = cast<PointerType>(ty)->getPointeeType(); 181617a519f9SDimitry Andric break; 1817f22ef01cSRoman Divacky 181817a519f9SDimitry Andric case Type::BlockPointer: 181917a519f9SDimitry Andric type = cast<BlockPointerType>(ty)->getPointeeType(); 182017a519f9SDimitry Andric break; 182117a519f9SDimitry Andric 182217a519f9SDimitry Andric case Type::LValueReference: 182317a519f9SDimitry Andric case Type::RValueReference: 182417a519f9SDimitry Andric type = cast<ReferenceType>(ty)->getPointeeType(); 182517a519f9SDimitry Andric break; 182617a519f9SDimitry Andric 182717a519f9SDimitry Andric case Type::MemberPointer: 182817a519f9SDimitry Andric type = cast<MemberPointerType>(ty)->getPointeeType(); 182917a519f9SDimitry Andric break; 183017a519f9SDimitry Andric 183117a519f9SDimitry Andric case Type::ConstantArray: 183217a519f9SDimitry Andric case Type::IncompleteArray: 183317a519f9SDimitry Andric // Losing element qualification here is fine. 183417a519f9SDimitry Andric type = cast<ArrayType>(ty)->getElementType(); 183517a519f9SDimitry Andric break; 183617a519f9SDimitry Andric 183717a519f9SDimitry Andric case Type::VariableArray: { 183817a519f9SDimitry Andric // Losing element qualification here is fine. 183917a519f9SDimitry Andric const VariableArrayType *vat = cast<VariableArrayType>(ty); 184017a519f9SDimitry Andric 184117a519f9SDimitry Andric // Unknown size indication requires no size computation. 184217a519f9SDimitry Andric // Otherwise, evaluate and record it. 184317a519f9SDimitry Andric if (const Expr *size = vat->getSizeExpr()) { 184417a519f9SDimitry Andric // It's possible that we might have emitted this already, 184517a519f9SDimitry Andric // e.g. with a typedef and a pointer to it. 184617a519f9SDimitry Andric llvm::Value *&entry = VLASizeMap[size]; 184717a519f9SDimitry Andric if (!entry) { 18483861d79fSDimitry Andric llvm::Value *Size = EmitScalarExpr(size); 18493861d79fSDimitry Andric 18503861d79fSDimitry Andric // C11 6.7.6.2p5: 18513861d79fSDimitry Andric // If the size is an expression that is not an integer constant 18523861d79fSDimitry Andric // expression [...] each time it is evaluated it shall have a value 18533861d79fSDimitry Andric // greater than zero. 185439d628a0SDimitry Andric if (SanOpts.has(SanitizerKind::VLABound) && 18553861d79fSDimitry Andric size->getType()->isSignedIntegerType()) { 185659d1ed5bSDimitry Andric SanitizerScope SanScope(this); 18573861d79fSDimitry Andric llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType()); 18583861d79fSDimitry Andric llvm::Constant *StaticArgs[] = { 18593861d79fSDimitry Andric EmitCheckSourceLocation(size->getLocStart()), 18603861d79fSDimitry Andric EmitCheckTypeDescriptor(size->getType()) 18613861d79fSDimitry Andric }; 186239d628a0SDimitry Andric EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero), 186339d628a0SDimitry Andric SanitizerKind::VLABound), 186444290647SDimitry Andric SanitizerHandler::VLABoundNotPositive, StaticArgs, Size); 18653861d79fSDimitry Andric } 18663861d79fSDimitry Andric 186717a519f9SDimitry Andric // Always zexting here would be wrong if it weren't 186817a519f9SDimitry Andric // undefined behavior to have a negative bound. 18693861d79fSDimitry Andric entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false); 187017a519f9SDimitry Andric } 187117a519f9SDimitry Andric } 187217a519f9SDimitry Andric type = vat->getElementType(); 187317a519f9SDimitry Andric break; 1874f22ef01cSRoman Divacky } 1875f22ef01cSRoman Divacky 187617a519f9SDimitry Andric case Type::FunctionProto: 187717a519f9SDimitry Andric case Type::FunctionNoProto: 187859d1ed5bSDimitry Andric type = cast<FunctionType>(ty)->getReturnType(); 187917a519f9SDimitry Andric break; 18806122f3e6SDimitry Andric 1881dff0c46cSDimitry Andric case Type::Paren: 1882dff0c46cSDimitry Andric case Type::TypeOf: 1883dff0c46cSDimitry Andric case Type::UnaryTransform: 1884dff0c46cSDimitry Andric case Type::Attributed: 1885dff0c46cSDimitry Andric case Type::SubstTemplateTypeParm: 1886f785676fSDimitry Andric case Type::PackExpansion: 1887dff0c46cSDimitry Andric // Keep walking after single level desugaring. 1888dff0c46cSDimitry Andric type = type.getSingleStepDesugaredType(getContext()); 1889dff0c46cSDimitry Andric break; 1890dff0c46cSDimitry Andric 1891dff0c46cSDimitry Andric case Type::Typedef: 1892dff0c46cSDimitry Andric case Type::Decltype: 1893dff0c46cSDimitry Andric case Type::Auto: 1894dff0c46cSDimitry Andric // Stop walking: nothing to do. 1895dff0c46cSDimitry Andric return; 1896dff0c46cSDimitry Andric 1897dff0c46cSDimitry Andric case Type::TypeOfExpr: 1898dff0c46cSDimitry Andric // Stop walking: emit typeof expression. 1899dff0c46cSDimitry Andric EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr()); 1900dff0c46cSDimitry Andric return; 1901dff0c46cSDimitry Andric 19026122f3e6SDimitry Andric case Type::Atomic: 19036122f3e6SDimitry Andric type = cast<AtomicType>(ty)->getValueType(); 19046122f3e6SDimitry Andric break; 1905444ed5c5SDimitry Andric 1906444ed5c5SDimitry Andric case Type::Pipe: 1907444ed5c5SDimitry Andric type = cast<PipeType>(ty)->getElementType(); 1908444ed5c5SDimitry Andric break; 1909f22ef01cSRoman Divacky } 191017a519f9SDimitry Andric } while (type->isVariablyModifiedType()); 1911f22ef01cSRoman Divacky } 1912f22ef01cSRoman Divacky 19130623d748SDimitry Andric Address CodeGenFunction::EmitVAListRef(const Expr* E) { 19142754fe60SDimitry Andric if (getContext().getBuiltinVaListType()->isArrayType()) 19150623d748SDimitry Andric return EmitPointerWithAlignment(E); 19160623d748SDimitry Andric return EmitLValue(E).getAddress(); 19170623d748SDimitry Andric } 19180623d748SDimitry Andric 19190623d748SDimitry Andric Address CodeGenFunction::EmitMSVAListRef(const Expr *E) { 1920f22ef01cSRoman Divacky return EmitLValue(E).getAddress(); 1921f22ef01cSRoman Divacky } 1922f22ef01cSRoman Divacky 1923e580952dSDimitry Andric void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E, 192444290647SDimitry Andric const APValue &Init) { 192544290647SDimitry Andric assert(!Init.isUninit() && "Invalid DeclRefExpr initializer!"); 1926e580952dSDimitry Andric if (CGDebugInfo *Dbg = getDebugInfo()) 1927e7145dcbSDimitry Andric if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 19282754fe60SDimitry Andric Dbg->EmitGlobalVariable(E->getDecl(), Init); 19292754fe60SDimitry Andric } 19302754fe60SDimitry Andric 19312754fe60SDimitry Andric CodeGenFunction::PeepholeProtection 19322754fe60SDimitry Andric CodeGenFunction::protectFromPeepholes(RValue rvalue) { 19332754fe60SDimitry Andric // At the moment, the only aggressive peephole we do in IR gen 19342754fe60SDimitry Andric // is trunc(zext) folding, but if we add more, we can easily 19352754fe60SDimitry Andric // extend this protection. 19362754fe60SDimitry Andric 19372754fe60SDimitry Andric if (!rvalue.isScalar()) return PeepholeProtection(); 19382754fe60SDimitry Andric llvm::Value *value = rvalue.getScalarVal(); 19392754fe60SDimitry Andric if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection(); 19402754fe60SDimitry Andric 19412754fe60SDimitry Andric // Just make an extra bitcast. 19422754fe60SDimitry Andric assert(HaveInsertPoint()); 19432754fe60SDimitry Andric llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "", 19442754fe60SDimitry Andric Builder.GetInsertBlock()); 19452754fe60SDimitry Andric 19462754fe60SDimitry Andric PeepholeProtection protection; 19472754fe60SDimitry Andric protection.Inst = inst; 19482754fe60SDimitry Andric return protection; 19492754fe60SDimitry Andric } 19502754fe60SDimitry Andric 19512754fe60SDimitry Andric void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) { 19522754fe60SDimitry Andric if (!protection.Inst) return; 19532754fe60SDimitry Andric 19542754fe60SDimitry Andric // In theory, we could try to duplicate the peepholes now, but whatever. 19552754fe60SDimitry Andric protection.Inst->eraseFromParent(); 1956e580952dSDimitry Andric } 19576122f3e6SDimitry Andric 19586122f3e6SDimitry Andric llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn, 19596122f3e6SDimitry Andric llvm::Value *AnnotatedVal, 1960139f7f9bSDimitry Andric StringRef AnnotationStr, 19616122f3e6SDimitry Andric SourceLocation Location) { 19626122f3e6SDimitry Andric llvm::Value *Args[4] = { 19636122f3e6SDimitry Andric AnnotatedVal, 19646122f3e6SDimitry Andric Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy), 19656122f3e6SDimitry Andric Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy), 19666122f3e6SDimitry Andric CGM.EmitAnnotationLineNo(Location) 19676122f3e6SDimitry Andric }; 19686122f3e6SDimitry Andric return Builder.CreateCall(AnnotationFn, Args); 19696122f3e6SDimitry Andric } 19706122f3e6SDimitry Andric 19716122f3e6SDimitry Andric void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) { 19726122f3e6SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 19736122f3e6SDimitry Andric // FIXME We create a new bitcast for every annotation because that's what 19746122f3e6SDimitry Andric // llvm-gcc was doing. 197559d1ed5bSDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) 19766122f3e6SDimitry Andric EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation), 19776122f3e6SDimitry Andric Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()), 197859d1ed5bSDimitry Andric I->getAnnotation(), D->getLocation()); 19796122f3e6SDimitry Andric } 19806122f3e6SDimitry Andric 19810623d748SDimitry Andric Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D, 19820623d748SDimitry Andric Address Addr) { 19836122f3e6SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 19840623d748SDimitry Andric llvm::Value *V = Addr.getPointer(); 19856122f3e6SDimitry Andric llvm::Type *VTy = V->getType(); 19866122f3e6SDimitry Andric llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, 19876122f3e6SDimitry Andric CGM.Int8PtrTy); 19886122f3e6SDimitry Andric 198959d1ed5bSDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) { 19906122f3e6SDimitry Andric // FIXME Always emit the cast inst so we can differentiate between 19916122f3e6SDimitry Andric // annotation on the first field of a struct and annotation on the struct 19926122f3e6SDimitry Andric // itself. 19936122f3e6SDimitry Andric if (VTy != CGM.Int8PtrTy) 19946122f3e6SDimitry Andric V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy)); 199559d1ed5bSDimitry Andric V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation()); 19966122f3e6SDimitry Andric V = Builder.CreateBitCast(V, VTy); 19976122f3e6SDimitry Andric } 19986122f3e6SDimitry Andric 19990623d748SDimitry Andric return Address(V, Addr.getAlignment()); 20006122f3e6SDimitry Andric } 2001f785676fSDimitry Andric 2002f785676fSDimitry Andric CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { } 200359d1ed5bSDimitry Andric 200459d1ed5bSDimitry Andric CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF) 200559d1ed5bSDimitry Andric : CGF(CGF) { 200659d1ed5bSDimitry Andric assert(!CGF->IsSanitizerScope); 200759d1ed5bSDimitry Andric CGF->IsSanitizerScope = true; 200859d1ed5bSDimitry Andric } 200959d1ed5bSDimitry Andric 201059d1ed5bSDimitry Andric CodeGenFunction::SanitizerScope::~SanitizerScope() { 201159d1ed5bSDimitry Andric CGF->IsSanitizerScope = false; 201259d1ed5bSDimitry Andric } 201359d1ed5bSDimitry Andric 201459d1ed5bSDimitry Andric void CodeGenFunction::InsertHelper(llvm::Instruction *I, 201559d1ed5bSDimitry Andric const llvm::Twine &Name, 201659d1ed5bSDimitry Andric llvm::BasicBlock *BB, 201759d1ed5bSDimitry Andric llvm::BasicBlock::iterator InsertPt) const { 201859d1ed5bSDimitry Andric LoopStack.InsertHelper(I); 201939d628a0SDimitry Andric if (IsSanitizerScope) 202039d628a0SDimitry Andric CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I); 202159d1ed5bSDimitry Andric } 202259d1ed5bSDimitry Andric 2023e7145dcbSDimitry Andric void CGBuilderInserter::InsertHelper( 202459d1ed5bSDimitry Andric llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, 202559d1ed5bSDimitry Andric llvm::BasicBlock::iterator InsertPt) const { 2026e7145dcbSDimitry Andric llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt); 202759d1ed5bSDimitry Andric if (CGF) 202859d1ed5bSDimitry Andric CGF->InsertHelper(I, Name, BB, InsertPt); 202959d1ed5bSDimitry Andric } 203059d1ed5bSDimitry Andric 20310623d748SDimitry Andric static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures, 20320623d748SDimitry Andric CodeGenModule &CGM, const FunctionDecl *FD, 20330623d748SDimitry Andric std::string &FirstMissing) { 20340623d748SDimitry Andric // If there aren't any required features listed then go ahead and return. 20350623d748SDimitry Andric if (ReqFeatures.empty()) 20360623d748SDimitry Andric return false; 20370623d748SDimitry Andric 20380623d748SDimitry Andric // Now build up the set of caller features and verify that all the required 20390623d748SDimitry Andric // features are there. 20400623d748SDimitry Andric llvm::StringMap<bool> CallerFeatureMap; 20410623d748SDimitry Andric CGM.getFunctionFeatureMap(CallerFeatureMap, FD); 20420623d748SDimitry Andric 20430623d748SDimitry Andric // If we have at least one of the features in the feature list return 20440623d748SDimitry Andric // true, otherwise return false. 20450623d748SDimitry Andric return std::all_of( 20460623d748SDimitry Andric ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) { 20470623d748SDimitry Andric SmallVector<StringRef, 1> OrFeatures; 20480623d748SDimitry Andric Feature.split(OrFeatures, "|"); 20490623d748SDimitry Andric return std::any_of(OrFeatures.begin(), OrFeatures.end(), 20500623d748SDimitry Andric [&](StringRef Feature) { 20510623d748SDimitry Andric if (!CallerFeatureMap.lookup(Feature)) { 20520623d748SDimitry Andric FirstMissing = Feature.str(); 20530623d748SDimitry Andric return false; 20540623d748SDimitry Andric } 20550623d748SDimitry Andric return true; 20560623d748SDimitry Andric }); 20570623d748SDimitry Andric }); 20580623d748SDimitry Andric } 20590623d748SDimitry Andric 20600623d748SDimitry Andric // Emits an error if we don't have a valid set of target features for the 20610623d748SDimitry Andric // called function. 20620623d748SDimitry Andric void CodeGenFunction::checkTargetFeatures(const CallExpr *E, 20630623d748SDimitry Andric const FunctionDecl *TargetDecl) { 20640623d748SDimitry Andric // Early exit if this is an indirect call. 20650623d748SDimitry Andric if (!TargetDecl) 20660623d748SDimitry Andric return; 20670623d748SDimitry Andric 20680623d748SDimitry Andric // Get the current enclosing function if it exists. If it doesn't 20690623d748SDimitry Andric // we can't check the target features anyhow. 20700623d748SDimitry Andric const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl); 20710623d748SDimitry Andric if (!FD) 20720623d748SDimitry Andric return; 20730623d748SDimitry Andric 20740623d748SDimitry Andric // Grab the required features for the call. For a builtin this is listed in 20750623d748SDimitry Andric // the td file with the default cpu, for an always_inline function this is any 20760623d748SDimitry Andric // listed cpu and any listed features. 20770623d748SDimitry Andric unsigned BuiltinID = TargetDecl->getBuiltinID(); 20780623d748SDimitry Andric std::string MissingFeature; 20790623d748SDimitry Andric if (BuiltinID) { 20800623d748SDimitry Andric SmallVector<StringRef, 1> ReqFeatures; 20810623d748SDimitry Andric const char *FeatureList = 20820623d748SDimitry Andric CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID); 20830623d748SDimitry Andric // Return if the builtin doesn't have any required features. 20840623d748SDimitry Andric if (!FeatureList || StringRef(FeatureList) == "") 20850623d748SDimitry Andric return; 20860623d748SDimitry Andric StringRef(FeatureList).split(ReqFeatures, ","); 20870623d748SDimitry Andric if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature)) 20880623d748SDimitry Andric CGM.getDiags().Report(E->getLocStart(), diag::err_builtin_needs_feature) 20890623d748SDimitry Andric << TargetDecl->getDeclName() 20900623d748SDimitry Andric << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID); 20910623d748SDimitry Andric 20920623d748SDimitry Andric } else if (TargetDecl->hasAttr<TargetAttr>()) { 20930623d748SDimitry Andric // Get the required features for the callee. 20940623d748SDimitry Andric SmallVector<StringRef, 1> ReqFeatures; 20950623d748SDimitry Andric llvm::StringMap<bool> CalleeFeatureMap; 20960623d748SDimitry Andric CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl); 20970623d748SDimitry Andric for (const auto &F : CalleeFeatureMap) { 20980623d748SDimitry Andric // Only positive features are "required". 20990623d748SDimitry Andric if (F.getValue()) 21000623d748SDimitry Andric ReqFeatures.push_back(F.getKey()); 21010623d748SDimitry Andric } 21020623d748SDimitry Andric if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature)) 21030623d748SDimitry Andric CGM.getDiags().Report(E->getLocStart(), diag::err_function_needs_feature) 21040623d748SDimitry Andric << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature; 21050623d748SDimitry Andric } 21060623d748SDimitry Andric } 2107e7145dcbSDimitry Andric 2108e7145dcbSDimitry Andric void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) { 2109e7145dcbSDimitry Andric if (!CGM.getCodeGenOpts().SanitizeStats) 2110e7145dcbSDimitry Andric return; 2111e7145dcbSDimitry Andric 2112e7145dcbSDimitry Andric llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint()); 2113e7145dcbSDimitry Andric IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation()); 2114e7145dcbSDimitry Andric CGM.getSanStats().create(IRB, SSK); 2115e7145dcbSDimitry Andric } 211644290647SDimitry Andric 211744290647SDimitry Andric llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) { 211844290647SDimitry Andric if (CGDebugInfo *DI = getDebugInfo()) 211944290647SDimitry Andric return DI->SourceLocToDebugLoc(Location); 212044290647SDimitry Andric 212144290647SDimitry Andric return llvm::DebugLoc(); 212244290647SDimitry Andric } 2123