1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This coordinates the per-function state used while generating code.
11 //===----------------------------------------------------------------------===//
13 #include "CodeGenFunction.h"
15 #include "CGCUDARuntime.h"
17 #include "CGCleanup.h"
18 #include "CGDebugInfo.h"
19 #include "CGHLSLRuntime.h"
20 #include "CGOpenMPRuntime.h"
21 #include "CodeGenModule.h"
22 #include "CodeGenPGO.h"
23 #include "TargetInfo.h"
24 #include "clang/AST/ASTContext.h"
25 #include "clang/AST/ASTLambda.h"
26 #include "clang/AST/Attr.h"
27 #include "clang/AST/Decl.h"
28 #include "clang/AST/DeclCXX.h"
29 #include "clang/AST/Expr.h"
30 #include "clang/AST/StmtCXX.h"
31 #include "clang/AST/StmtObjC.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/CodeGenOptions.h"
34 #include "clang/Basic/TargetBuiltins.h"
35 #include "clang/Basic/TargetInfo.h"
36 #include "clang/CodeGen/CGFunctionInfo.h"
37 #include "clang/Frontend/FrontendDiagnostic.h"
38 #include "llvm/ADT/ArrayRef.h"
39 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/Dominators.h"
42 #include "llvm/IR/FPEnv.h"
43 #include "llvm/IR/IntrinsicInst.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/IR/MDBuilder.h"
46 #include "llvm/IR/Operator.h"
47 #include "llvm/Support/CRC.h"
48 #include "llvm/Support/xxhash.h"
49 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
50 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
53 using namespace clang
;
54 using namespace CodeGen
;
57 extern cl::opt
<bool> EnableSingleByteCoverage
;
60 /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
62 static bool shouldEmitLifetimeMarkers(const CodeGenOptions
&CGOpts
,
63 const LangOptions
&LangOpts
) {
64 if (CGOpts
.DisableLifetimeMarkers
)
67 // Sanitizers may use markers.
68 if (CGOpts
.SanitizeAddressUseAfterScope
||
69 LangOpts
.Sanitize
.has(SanitizerKind::HWAddress
) ||
70 LangOpts
.Sanitize
.has(SanitizerKind::Memory
))
73 // For now, only in optimized builds.
74 return CGOpts
.OptimizationLevel
!= 0;
77 CodeGenFunction::CodeGenFunction(CodeGenModule
&cgm
, bool suppressNewContext
)
78 : CodeGenTypeCache(cgm
), CGM(cgm
), Target(cgm
.getTarget()),
79 Builder(cgm
, cgm
.getModule().getContext(), llvm::ConstantFolder(),
80 CGBuilderInserterTy(this)),
81 SanOpts(CGM
.getLangOpts().Sanitize
), CurFPFeatures(CGM
.getLangOpts()),
82 DebugInfo(CGM
.getModuleDebugInfo()), PGO(cgm
),
83 ShouldEmitLifetimeMarkers(
84 shouldEmitLifetimeMarkers(CGM
.getCodeGenOpts(), CGM
.getLangOpts())) {
85 if (!suppressNewContext
)
86 CGM
.getCXXABI().getMangleContext().startNewFunction();
89 SetFastMathFlags(CurFPFeatures
);
92 CodeGenFunction::~CodeGenFunction() {
93 assert(LifetimeExtendedCleanupStack
.empty() && "failed to emit a cleanup");
94 assert(DeferredDeactivationCleanupStack
.empty() &&
95 "missed to deactivate a cleanup");
97 if (getLangOpts().OpenMP
&& CurFn
)
98 CGM
.getOpenMPRuntime().functionFinished(*this);
100 // If we have an OpenMPIRBuilder we want to finalize functions (incl.
101 // outlining etc) at some point. Doing it once the function codegen is done
102 // seems to be a reasonable spot. We do it here, as opposed to the deletion
103 // time of the CodeGenModule, because we have to ensure the IR has not yet
104 // been "emitted" to the outside, thus, modifications are still sensible.
105 if (CGM
.getLangOpts().OpenMPIRBuilder
&& CurFn
)
106 CGM
.getOpenMPRuntime().getOMPBuilder().finalize(CurFn
);
109 // Map the LangOption for exception behavior into
110 // the corresponding enum in the IR.
111 llvm::fp::ExceptionBehavior
112 clang::ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind
) {
115 case LangOptions::FPE_Ignore
: return llvm::fp::ebIgnore
;
116 case LangOptions::FPE_MayTrap
: return llvm::fp::ebMayTrap
;
117 case LangOptions::FPE_Strict
: return llvm::fp::ebStrict
;
119 llvm_unreachable("Unsupported FP Exception Behavior");
123 void CodeGenFunction::SetFastMathFlags(FPOptions FPFeatures
) {
124 llvm::FastMathFlags FMF
;
125 FMF
.setAllowReassoc(FPFeatures
.getAllowFPReassociate());
126 FMF
.setNoNaNs(FPFeatures
.getNoHonorNaNs());
127 FMF
.setNoInfs(FPFeatures
.getNoHonorInfs());
128 FMF
.setNoSignedZeros(FPFeatures
.getNoSignedZero());
129 FMF
.setAllowReciprocal(FPFeatures
.getAllowReciprocal());
130 FMF
.setApproxFunc(FPFeatures
.getAllowApproxFunc());
131 FMF
.setAllowContract(FPFeatures
.allowFPContractAcrossStatement());
132 Builder
.setFastMathFlags(FMF
);
135 CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction
&CGF
,
138 ConstructorHelper(E
->getFPFeaturesInEffect(CGF
.getLangOpts()));
141 CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction
&CGF
,
142 FPOptions FPFeatures
)
144 ConstructorHelper(FPFeatures
);
147 void CodeGenFunction::CGFPOptionsRAII::ConstructorHelper(FPOptions FPFeatures
) {
148 OldFPFeatures
= CGF
.CurFPFeatures
;
149 CGF
.CurFPFeatures
= FPFeatures
;
151 OldExcept
= CGF
.Builder
.getDefaultConstrainedExcept();
152 OldRounding
= CGF
.Builder
.getDefaultConstrainedRounding();
154 if (OldFPFeatures
== FPFeatures
)
157 FMFGuard
.emplace(CGF
.Builder
);
159 llvm::RoundingMode NewRoundingBehavior
= FPFeatures
.getRoundingMode();
160 CGF
.Builder
.setDefaultConstrainedRounding(NewRoundingBehavior
);
161 auto NewExceptionBehavior
=
162 ToConstrainedExceptMD(static_cast<LangOptions::FPExceptionModeKind
>(
163 FPFeatures
.getExceptionMode()));
164 CGF
.Builder
.setDefaultConstrainedExcept(NewExceptionBehavior
);
166 CGF
.SetFastMathFlags(FPFeatures
);
168 assert((CGF
.CurFuncDecl
== nullptr || CGF
.Builder
.getIsFPConstrained() ||
169 isa
<CXXConstructorDecl
>(CGF
.CurFuncDecl
) ||
170 isa
<CXXDestructorDecl
>(CGF
.CurFuncDecl
) ||
171 (NewExceptionBehavior
== llvm::fp::ebIgnore
&&
172 NewRoundingBehavior
== llvm::RoundingMode::NearestTiesToEven
)) &&
173 "FPConstrained should be enabled on entire function");
175 auto mergeFnAttrValue
= [&](StringRef Name
, bool Value
) {
177 CGF
.CurFn
->getFnAttribute(Name
).getValueAsBool();
178 auto NewValue
= OldValue
& Value
;
179 if (OldValue
!= NewValue
)
180 CGF
.CurFn
->addFnAttr(Name
, llvm::toStringRef(NewValue
));
182 mergeFnAttrValue("no-infs-fp-math", FPFeatures
.getNoHonorInfs());
183 mergeFnAttrValue("no-nans-fp-math", FPFeatures
.getNoHonorNaNs());
184 mergeFnAttrValue("no-signed-zeros-fp-math", FPFeatures
.getNoSignedZero());
187 FPFeatures
.getAllowFPReassociate() && FPFeatures
.getAllowReciprocal() &&
188 FPFeatures
.getAllowApproxFunc() && FPFeatures
.getNoSignedZero() &&
189 FPFeatures
.allowFPContractAcrossStatement());
192 CodeGenFunction::CGFPOptionsRAII::~CGFPOptionsRAII() {
193 CGF
.CurFPFeatures
= OldFPFeatures
;
194 CGF
.Builder
.setDefaultConstrainedExcept(OldExcept
);
195 CGF
.Builder
.setDefaultConstrainedRounding(OldRounding
);
199 makeNaturalAlignAddrLValue(llvm::Value
*V
, QualType T
, bool ForPointeeType
,
200 bool MightBeSigned
, CodeGenFunction
&CGF
,
201 KnownNonNull_t IsKnownNonNull
= NotKnownNonNull
) {
202 LValueBaseInfo BaseInfo
;
203 TBAAAccessInfo TBAAInfo
;
204 CharUnits Alignment
=
205 CGF
.CGM
.getNaturalTypeAlignment(T
, &BaseInfo
, &TBAAInfo
, ForPointeeType
);
208 ? CGF
.makeNaturalAddressForPointer(V
, T
, Alignment
, false, nullptr,
209 nullptr, IsKnownNonNull
)
210 : Address(V
, CGF
.ConvertTypeForMem(T
), Alignment
, IsKnownNonNull
);
211 return CGF
.MakeAddrLValue(Addr
, T
, BaseInfo
, TBAAInfo
);
215 CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value
*V
, QualType T
,
216 KnownNonNull_t IsKnownNonNull
) {
217 return ::makeNaturalAlignAddrLValue(V
, T
, /*ForPointeeType*/ false,
218 /*MightBeSigned*/ true, *this,
223 CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value
*V
, QualType T
) {
224 return ::makeNaturalAlignAddrLValue(V
, T
, /*ForPointeeType*/ true,
225 /*MightBeSigned*/ true, *this);
228 LValue
CodeGenFunction::MakeNaturalAlignRawAddrLValue(llvm::Value
*V
,
230 return ::makeNaturalAlignAddrLValue(V
, T
, /*ForPointeeType*/ false,
231 /*MightBeSigned*/ false, *this);
234 LValue
CodeGenFunction::MakeNaturalAlignPointeeRawAddrLValue(llvm::Value
*V
,
236 return ::makeNaturalAlignAddrLValue(V
, T
, /*ForPointeeType*/ true,
237 /*MightBeSigned*/ false, *this);
240 llvm::Type
*CodeGenFunction::ConvertTypeForMem(QualType T
) {
241 return CGM
.getTypes().ConvertTypeForMem(T
);
244 llvm::Type
*CodeGenFunction::ConvertType(QualType T
) {
245 return CGM
.getTypes().ConvertType(T
);
248 llvm::Type
*CodeGenFunction::convertTypeForLoadStore(QualType ASTTy
,
249 llvm::Type
*LLVMTy
) {
250 return CGM
.getTypes().convertTypeForLoadStore(ASTTy
, LLVMTy
);
253 TypeEvaluationKind
CodeGenFunction::getEvaluationKind(QualType type
) {
254 type
= type
.getCanonicalType();
256 switch (type
->getTypeClass()) {
257 #define TYPE(name, parent)
258 #define ABSTRACT_TYPE(name, parent)
259 #define NON_CANONICAL_TYPE(name, parent) case Type::name:
260 #define DEPENDENT_TYPE(name, parent) case Type::name:
261 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
262 #include "clang/AST/TypeNodes.inc"
263 llvm_unreachable("non-canonical or dependent type in IR-generation");
266 case Type::DeducedTemplateSpecialization
:
267 llvm_unreachable("undeduced type in IR-generation");
269 // Various scalar types.
272 case Type::BlockPointer
:
273 case Type::LValueReference
:
274 case Type::RValueReference
:
275 case Type::MemberPointer
:
277 case Type::ExtVector
:
278 case Type::ConstantMatrix
:
279 case Type::FunctionProto
:
280 case Type::FunctionNoProto
:
282 case Type::ObjCObjectPointer
:
291 // Arrays, records, and Objective-C objects.
292 case Type::ConstantArray
:
293 case Type::IncompleteArray
:
294 case Type::VariableArray
:
296 case Type::ObjCObject
:
297 case Type::ObjCInterface
:
298 case Type::ArrayParameter
:
299 return TEK_Aggregate
;
301 // We operate on atomic values according to their underlying type.
303 type
= cast
<AtomicType
>(type
)->getValueType();
306 llvm_unreachable("unknown type kind!");
310 llvm::DebugLoc
CodeGenFunction::EmitReturnBlock() {
311 // For cleanliness, we try to avoid emitting the return block for
313 llvm::BasicBlock
*CurBB
= Builder
.GetInsertBlock();
316 assert(!CurBB
->getTerminator() && "Unexpected terminated block.");
318 // We have a valid insert point, reuse it if it is empty or there are no
319 // explicit jumps to the return block.
320 if (CurBB
->empty() || ReturnBlock
.getBlock()->use_empty()) {
321 ReturnBlock
.getBlock()->replaceAllUsesWith(CurBB
);
322 delete ReturnBlock
.getBlock();
323 ReturnBlock
= JumpDest();
325 EmitBlock(ReturnBlock
.getBlock());
326 return llvm::DebugLoc();
329 // Otherwise, if the return block is the target of a single direct
330 // branch then we can just put the code in that block instead. This
331 // cleans up functions which started with a unified return block.
332 if (ReturnBlock
.getBlock()->hasOneUse()) {
333 llvm::BranchInst
*BI
=
334 dyn_cast
<llvm::BranchInst
>(*ReturnBlock
.getBlock()->user_begin());
335 if (BI
&& BI
->isUnconditional() &&
336 BI
->getSuccessor(0) == ReturnBlock
.getBlock()) {
337 // Record/return the DebugLoc of the simple 'return' expression to be used
338 // later by the actual 'ret' instruction.
339 llvm::DebugLoc Loc
= BI
->getDebugLoc();
340 Builder
.SetInsertPoint(BI
->getParent());
341 BI
->eraseFromParent();
342 delete ReturnBlock
.getBlock();
343 ReturnBlock
= JumpDest();
348 // FIXME: We are at an unreachable point, there is no reason to emit the block
349 // unless it has uses. However, we still need a place to put the debug
350 // region.end for now.
352 EmitBlock(ReturnBlock
.getBlock());
353 return llvm::DebugLoc();
356 static void EmitIfUsed(CodeGenFunction
&CGF
, llvm::BasicBlock
*BB
) {
358 if (!BB
->use_empty()) {
359 CGF
.CurFn
->insert(CGF
.CurFn
->end(), BB
);
365 void CodeGenFunction::FinishFunction(SourceLocation EndLoc
) {
366 assert(BreakContinueStack
.empty() &&
367 "mismatched push/pop in break/continue stack!");
368 assert(LifetimeExtendedCleanupStack
.empty() &&
369 "mismatched push/pop of cleanups in EHStack!");
370 assert(DeferredDeactivationCleanupStack
.empty() &&
371 "mismatched activate/deactivate of cleanups!");
373 if (CGM
.shouldEmitConvergenceTokens()) {
374 ConvergenceTokenStack
.pop_back();
375 assert(ConvergenceTokenStack
.empty() &&
376 "mismatched push/pop in convergence stack!");
379 bool OnlySimpleReturnStmts
= NumSimpleReturnExprs
> 0
380 && NumSimpleReturnExprs
== NumReturnExprs
381 && ReturnBlock
.getBlock()->use_empty();
382 // Usually the return expression is evaluated before the cleanup
383 // code. If the function contains only a simple return statement,
384 // such as a constant, the location before the cleanup code becomes
385 // the last useful breakpoint in the function, because the simple
386 // return expression will be evaluated after the cleanup code. To be
387 // safe, set the debug location for cleanup code to the location of
388 // the return statement. Otherwise the cleanup code should be at the
389 // end of the function's lexical scope.
391 // If there are multiple branches to the return block, the branch
392 // instructions will get the location of the return statements and
394 if (CGDebugInfo
*DI
= getDebugInfo()) {
395 if (OnlySimpleReturnStmts
)
396 DI
->EmitLocation(Builder
, LastStopPoint
);
398 DI
->EmitLocation(Builder
, EndLoc
);
401 // Pop any cleanups that might have been associated with the
402 // parameters. Do this in whatever block we're currently in; it's
403 // important to do this before we enter the return block or return
404 // edges will be *really* confused.
405 bool HasCleanups
= EHStack
.stable_begin() != PrologueCleanupDepth
;
406 bool HasOnlyLifetimeMarkers
=
407 HasCleanups
&& EHStack
.containsOnlyLifetimeMarkers(PrologueCleanupDepth
);
408 bool EmitRetDbgLoc
= !HasCleanups
|| HasOnlyLifetimeMarkers
;
410 std::optional
<ApplyDebugLocation
> OAL
;
412 // Make sure the line table doesn't jump back into the body for
413 // the ret after it's been at EndLoc.
414 if (CGDebugInfo
*DI
= getDebugInfo()) {
415 if (OnlySimpleReturnStmts
)
416 DI
->EmitLocation(Builder
, EndLoc
);
418 // We may not have a valid end location. Try to apply it anyway, and
419 // fall back to an artificial location if needed.
420 OAL
= ApplyDebugLocation::CreateDefaultArtificial(*this, EndLoc
);
423 PopCleanupBlocks(PrologueCleanupDepth
);
426 // Emit function epilog (to return).
427 llvm::DebugLoc Loc
= EmitReturnBlock();
429 if (ShouldInstrumentFunction()) {
430 if (CGM
.getCodeGenOpts().InstrumentFunctions
)
431 CurFn
->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
432 if (CGM
.getCodeGenOpts().InstrumentFunctionsAfterInlining
)
433 CurFn
->addFnAttr("instrument-function-exit-inlined",
434 "__cyg_profile_func_exit");
437 // Emit debug descriptor for function end.
438 if (CGDebugInfo
*DI
= getDebugInfo())
439 DI
->EmitFunctionEnd(Builder
, CurFn
);
441 // Reset the debug location to that of the simple 'return' expression, if any
442 // rather than that of the end of the function's scope '}'.
443 ApplyDebugLocation
AL(*this, Loc
);
444 EmitFunctionEpilog(*CurFnInfo
, EmitRetDbgLoc
, EndLoc
);
445 EmitEndEHSpec(CurCodeDecl
);
447 assert(EHStack
.empty() &&
448 "did not remove all scopes from cleanup stack!");
450 // If someone did an indirect goto, emit the indirect goto block at the end of
452 if (IndirectBranch
) {
453 EmitBlock(IndirectBranch
->getParent());
454 Builder
.ClearInsertionPoint();
457 // If some of our locals escaped, insert a call to llvm.localescape in the
459 if (!EscapedLocals
.empty()) {
460 // Invert the map from local to index into a simple vector. There should be
462 SmallVector
<llvm::Value
*, 4> EscapeArgs
;
463 EscapeArgs
.resize(EscapedLocals
.size());
464 for (auto &Pair
: EscapedLocals
)
465 EscapeArgs
[Pair
.second
] = Pair
.first
;
466 llvm::Function
*FrameEscapeFn
= llvm::Intrinsic::getDeclaration(
467 &CGM
.getModule(), llvm::Intrinsic::localescape
);
468 CGBuilderTy(*this, AllocaInsertPt
).CreateCall(FrameEscapeFn
, EscapeArgs
);
471 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
472 llvm::Instruction
*Ptr
= AllocaInsertPt
;
473 AllocaInsertPt
= nullptr;
474 Ptr
->eraseFromParent();
476 // PostAllocaInsertPt, if created, was lazily created when it was required,
477 // remove it now since it was just created for our own convenience.
478 if (PostAllocaInsertPt
) {
479 llvm::Instruction
*PostPtr
= PostAllocaInsertPt
;
480 PostAllocaInsertPt
= nullptr;
481 PostPtr
->eraseFromParent();
484 // If someone took the address of a label but never did an indirect goto, we
485 // made a zero entry PHI node, which is illegal, zap it now.
486 if (IndirectBranch
) {
487 llvm::PHINode
*PN
= cast
<llvm::PHINode
>(IndirectBranch
->getAddress());
488 if (PN
->getNumIncomingValues() == 0) {
489 PN
->replaceAllUsesWith(llvm::UndefValue::get(PN
->getType()));
490 PN
->eraseFromParent();
494 EmitIfUsed(*this, EHResumeBlock
);
495 EmitIfUsed(*this, TerminateLandingPad
);
496 EmitIfUsed(*this, TerminateHandler
);
497 EmitIfUsed(*this, UnreachableBlock
);
499 for (const auto &FuncletAndParent
: TerminateFunclets
)
500 EmitIfUsed(*this, FuncletAndParent
.second
);
502 if (CGM
.getCodeGenOpts().EmitDeclMetadata
)
505 for (const auto &R
: DeferredReplacements
) {
506 if (llvm::Value
*Old
= R
.first
) {
507 Old
->replaceAllUsesWith(R
.second
);
508 cast
<llvm::Instruction
>(Old
)->eraseFromParent();
511 DeferredReplacements
.clear();
513 // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
514 // PHIs if the current function is a coroutine. We don't do it for all
515 // functions as it may result in slight increase in numbers of instructions
516 // if compiled with no optimizations. We do it for coroutine as the lifetime
517 // of CleanupDestSlot alloca make correct coroutine frame building very
519 if (NormalCleanupDest
.isValid() && isCoroutine()) {
520 llvm::DominatorTree
DT(*CurFn
);
521 llvm::PromoteMemToReg(
522 cast
<llvm::AllocaInst
>(NormalCleanupDest
.getPointer()), DT
);
523 NormalCleanupDest
= Address::invalid();
526 // Scan function arguments for vector width.
527 for (llvm::Argument
&A
: CurFn
->args())
528 if (auto *VT
= dyn_cast
<llvm::VectorType
>(A
.getType()))
530 std::max((uint64_t)LargestVectorWidth
,
531 VT
->getPrimitiveSizeInBits().getKnownMinValue());
533 // Update vector width based on return type.
534 if (auto *VT
= dyn_cast
<llvm::VectorType
>(CurFn
->getReturnType()))
536 std::max((uint64_t)LargestVectorWidth
,
537 VT
->getPrimitiveSizeInBits().getKnownMinValue());
539 if (CurFnInfo
->getMaxVectorWidth() > LargestVectorWidth
)
540 LargestVectorWidth
= CurFnInfo
->getMaxVectorWidth();
542 // Add the min-legal-vector-width attribute. This contains the max width from:
543 // 1. min-vector-width attribute used in the source program.
544 // 2. Any builtins used that have a vector width specified.
545 // 3. Values passed in and out of inline assembly.
546 // 4. Width of vector arguments and return types for this function.
547 // 5. Width of vector arguments and return types for functions called by this
549 if (getContext().getTargetInfo().getTriple().isX86())
550 CurFn
->addFnAttr("min-legal-vector-width",
551 llvm::utostr(LargestVectorWidth
));
553 // Add vscale_range attribute if appropriate.
554 std::optional
<std::pair
<unsigned, unsigned>> VScaleRange
=
555 getContext().getTargetInfo().getVScaleRange(getLangOpts());
557 CurFn
->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(
558 getLLVMContext(), VScaleRange
->first
, VScaleRange
->second
));
561 // If we generated an unreachable return block, delete it now.
562 if (ReturnBlock
.isValid() && ReturnBlock
.getBlock()->use_empty()) {
563 Builder
.ClearInsertionPoint();
564 ReturnBlock
.getBlock()->eraseFromParent();
566 if (ReturnValue
.isValid()) {
568 dyn_cast
<llvm::AllocaInst
>(ReturnValue
.emitRawPointer(*this));
569 if (RetAlloca
&& RetAlloca
->use_empty()) {
570 RetAlloca
->eraseFromParent();
571 ReturnValue
= Address::invalid();
576 /// ShouldInstrumentFunction - Return true if the current function should be
577 /// instrumented with __cyg_profile_func_* calls
578 bool CodeGenFunction::ShouldInstrumentFunction() {
579 if (!CGM
.getCodeGenOpts().InstrumentFunctions
&&
580 !CGM
.getCodeGenOpts().InstrumentFunctionsAfterInlining
&&
581 !CGM
.getCodeGenOpts().InstrumentFunctionEntryBare
)
583 if (!CurFuncDecl
|| CurFuncDecl
->hasAttr
<NoInstrumentFunctionAttr
>())
588 bool CodeGenFunction::ShouldSkipSanitizerInstrumentation() {
591 return CurFuncDecl
->hasAttr
<DisableSanitizerInstrumentationAttr
>();
594 /// ShouldXRayInstrument - Return true if the current function should be
595 /// instrumented with XRay nop sleds.
596 bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
597 return CGM
.getCodeGenOpts().XRayInstrumentFunctions
;
600 /// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
601 /// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
602 bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
603 return CGM
.getCodeGenOpts().XRayInstrumentFunctions
&&
604 (CGM
.getCodeGenOpts().XRayAlwaysEmitCustomEvents
||
605 CGM
.getCodeGenOpts().XRayInstrumentationBundle
.Mask
==
606 XRayInstrKind::Custom
);
609 bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
610 return CGM
.getCodeGenOpts().XRayInstrumentFunctions
&&
611 (CGM
.getCodeGenOpts().XRayAlwaysEmitTypedEvents
||
612 CGM
.getCodeGenOpts().XRayInstrumentationBundle
.Mask
==
613 XRayInstrKind::Typed
);
617 CodeGenFunction::getUBSanFunctionTypeHash(QualType Ty
) const {
618 // Remove any (C++17) exception specifications, to allow calling e.g. a
619 // noexcept function through a non-noexcept pointer.
620 if (!Ty
->isFunctionNoProtoType())
621 Ty
= getContext().getFunctionTypeWithExceptionSpec(Ty
, EST_None
);
623 llvm::raw_string_ostream
Out(Mangled
);
624 CGM
.getCXXABI().getMangleContext().mangleCanonicalTypeName(Ty
, Out
, false);
625 return llvm::ConstantInt::get(
626 CGM
.Int32Ty
, static_cast<uint32_t>(llvm::xxh3_64bits(Mangled
)));
629 void CodeGenFunction::EmitKernelMetadata(const FunctionDecl
*FD
,
630 llvm::Function
*Fn
) {
631 if (!FD
->hasAttr
<OpenCLKernelAttr
>() && !FD
->hasAttr
<CUDAGlobalAttr
>())
634 llvm::LLVMContext
&Context
= getLLVMContext();
636 CGM
.GenKernelArgMetadata(Fn
, FD
, this);
638 if (!getLangOpts().OpenCL
)
641 if (const VecTypeHintAttr
*A
= FD
->getAttr
<VecTypeHintAttr
>()) {
642 QualType HintQTy
= A
->getTypeHint();
643 const ExtVectorType
*HintEltQTy
= HintQTy
->getAs
<ExtVectorType
>();
644 bool IsSignedInteger
=
645 HintQTy
->isSignedIntegerType() ||
646 (HintEltQTy
&& HintEltQTy
->getElementType()->isSignedIntegerType());
647 llvm::Metadata
*AttrMDArgs
[] = {
648 llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
649 CGM
.getTypes().ConvertType(A
->getTypeHint()))),
650 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
651 llvm::IntegerType::get(Context
, 32),
652 llvm::APInt(32, (uint64_t)(IsSignedInteger
? 1 : 0))))};
653 Fn
->setMetadata("vec_type_hint", llvm::MDNode::get(Context
, AttrMDArgs
));
656 if (const WorkGroupSizeHintAttr
*A
= FD
->getAttr
<WorkGroupSizeHintAttr
>()) {
657 llvm::Metadata
*AttrMDArgs
[] = {
658 llvm::ConstantAsMetadata::get(Builder
.getInt32(A
->getXDim())),
659 llvm::ConstantAsMetadata::get(Builder
.getInt32(A
->getYDim())),
660 llvm::ConstantAsMetadata::get(Builder
.getInt32(A
->getZDim()))};
661 Fn
->setMetadata("work_group_size_hint", llvm::MDNode::get(Context
, AttrMDArgs
));
664 if (const ReqdWorkGroupSizeAttr
*A
= FD
->getAttr
<ReqdWorkGroupSizeAttr
>()) {
665 llvm::Metadata
*AttrMDArgs
[] = {
666 llvm::ConstantAsMetadata::get(Builder
.getInt32(A
->getXDim())),
667 llvm::ConstantAsMetadata::get(Builder
.getInt32(A
->getYDim())),
668 llvm::ConstantAsMetadata::get(Builder
.getInt32(A
->getZDim()))};
669 Fn
->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context
, AttrMDArgs
));
672 if (const OpenCLIntelReqdSubGroupSizeAttr
*A
=
673 FD
->getAttr
<OpenCLIntelReqdSubGroupSizeAttr
>()) {
674 llvm::Metadata
*AttrMDArgs
[] = {
675 llvm::ConstantAsMetadata::get(Builder
.getInt32(A
->getSubGroupSize()))};
676 Fn
->setMetadata("intel_reqd_sub_group_size",
677 llvm::MDNode::get(Context
, AttrMDArgs
));
681 /// Determine whether the function F ends with a return stmt.
682 static bool endsWithReturn(const Decl
* F
) {
683 const Stmt
*Body
= nullptr;
684 if (auto *FD
= dyn_cast_or_null
<FunctionDecl
>(F
))
685 Body
= FD
->getBody();
686 else if (auto *OMD
= dyn_cast_or_null
<ObjCMethodDecl
>(F
))
687 Body
= OMD
->getBody();
689 if (auto *CS
= dyn_cast_or_null
<CompoundStmt
>(Body
)) {
690 auto LastStmt
= CS
->body_rbegin();
691 if (LastStmt
!= CS
->body_rend())
692 return isa
<ReturnStmt
>(*LastStmt
);
697 void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function
*Fn
) {
698 if (SanOpts
.has(SanitizerKind::Thread
)) {
699 Fn
->addFnAttr("sanitize_thread_no_checking_at_run_time");
700 Fn
->removeFnAttr(llvm::Attribute::SanitizeThread
);
704 /// Check if the return value of this function requires sanitization.
705 bool CodeGenFunction::requiresReturnValueCheck() const {
706 return requiresReturnValueNullabilityCheck() ||
707 (SanOpts
.has(SanitizerKind::ReturnsNonnullAttribute
) && CurCodeDecl
&&
708 CurCodeDecl
->getAttr
<ReturnsNonNullAttr
>());
711 static bool matchesStlAllocatorFn(const Decl
*D
, const ASTContext
&Ctx
) {
712 auto *MD
= dyn_cast_or_null
<CXXMethodDecl
>(D
);
713 if (!MD
|| !MD
->getDeclName().getAsIdentifierInfo() ||
714 !MD
->getDeclName().getAsIdentifierInfo()->isStr("allocate") ||
715 (MD
->getNumParams() != 1 && MD
->getNumParams() != 2))
718 if (MD
->parameters()[0]->getType().getCanonicalType() != Ctx
.getSizeType())
721 if (MD
->getNumParams() == 2) {
722 auto *PT
= MD
->parameters()[1]->getType()->getAs
<PointerType
>();
723 if (!PT
|| !PT
->isVoidPointerType() ||
724 !PT
->getPointeeType().isConstQualified())
731 bool CodeGenFunction::isInAllocaArgument(CGCXXABI
&ABI
, QualType Ty
) {
732 const CXXRecordDecl
*RD
= Ty
->getAsCXXRecordDecl();
733 return RD
&& ABI
.getRecordArgABI(RD
) == CGCXXABI::RAA_DirectInMemory
;
736 bool CodeGenFunction::hasInAllocaArg(const CXXMethodDecl
*MD
) {
737 return getTarget().getTriple().getArch() == llvm::Triple::x86
&&
738 getTarget().getCXXABI().isMicrosoft() &&
739 llvm::any_of(MD
->parameters(), [&](ParmVarDecl
*P
) {
740 return isInAllocaArgument(CGM
.getCXXABI(), P
->getType());
744 /// Return the UBSan prologue signature for \p FD if one is available.
745 static llvm::Constant
*getPrologueSignature(CodeGenModule
&CGM
,
746 const FunctionDecl
*FD
) {
747 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(FD
))
750 return CGM
.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM
);
753 void CodeGenFunction::StartFunction(GlobalDecl GD
, QualType RetTy
,
755 const CGFunctionInfo
&FnInfo
,
756 const FunctionArgList
&Args
,
758 SourceLocation StartLoc
) {
760 "Do not use a CodeGenFunction object for more than one function");
762 const Decl
*D
= GD
.getDecl();
764 DidCallStackSave
= false;
766 const FunctionDecl
*FD
= dyn_cast_or_null
<FunctionDecl
>(D
);
767 if (FD
&& FD
->usesSEHTry())
769 CurFuncDecl
= (D
? D
->getNonClosureContext() : nullptr);
773 assert(CurFn
->isDeclaration() && "Function already has body?");
775 // If this function is ignored for any of the enabled sanitizers,
776 // disable the sanitizer for the function.
778 #define SANITIZER(NAME, ID) \
779 if (SanOpts.empty()) \
781 if (SanOpts.has(SanitizerKind::ID)) \
782 if (CGM.isInNoSanitizeList(SanitizerKind::ID, Fn, Loc)) \
783 SanOpts.set(SanitizerKind::ID, false);
785 #include "clang/Basic/Sanitizers.def"
790 const bool SanitizeBounds
= SanOpts
.hasOneOf(SanitizerKind::Bounds
);
791 SanitizerMask no_sanitize_mask
;
792 bool NoSanitizeCoverage
= false;
794 for (auto *Attr
: D
->specific_attrs
<NoSanitizeAttr
>()) {
795 no_sanitize_mask
|= Attr
->getMask();
796 // SanitizeCoverage is not handled by SanOpts.
797 if (Attr
->hasCoverage())
798 NoSanitizeCoverage
= true;
801 // Apply the no_sanitize* attributes to SanOpts.
802 SanOpts
.Mask
&= ~no_sanitize_mask
;
803 if (no_sanitize_mask
& SanitizerKind::Address
)
804 SanOpts
.set(SanitizerKind::KernelAddress
, false);
805 if (no_sanitize_mask
& SanitizerKind::KernelAddress
)
806 SanOpts
.set(SanitizerKind::Address
, false);
807 if (no_sanitize_mask
& SanitizerKind::HWAddress
)
808 SanOpts
.set(SanitizerKind::KernelHWAddress
, false);
809 if (no_sanitize_mask
& SanitizerKind::KernelHWAddress
)
810 SanOpts
.set(SanitizerKind::HWAddress
, false);
812 if (SanitizeBounds
&& !SanOpts
.hasOneOf(SanitizerKind::Bounds
))
813 Fn
->addFnAttr(llvm::Attribute::NoSanitizeBounds
);
815 if (NoSanitizeCoverage
&& CGM
.getCodeGenOpts().hasSanitizeCoverage())
816 Fn
->addFnAttr(llvm::Attribute::NoSanitizeCoverage
);
818 // Some passes need the non-negated no_sanitize attribute. Pass them on.
819 if (CGM
.getCodeGenOpts().hasSanitizeBinaryMetadata()) {
820 if (no_sanitize_mask
& SanitizerKind::Thread
)
821 Fn
->addFnAttr("no_sanitize_thread");
825 if (ShouldSkipSanitizerInstrumentation()) {
826 CurFn
->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation
);
828 // Apply sanitizer attributes to the function.
829 if (SanOpts
.hasOneOf(SanitizerKind::Address
| SanitizerKind::KernelAddress
))
830 Fn
->addFnAttr(llvm::Attribute::SanitizeAddress
);
831 if (SanOpts
.hasOneOf(SanitizerKind::HWAddress
|
832 SanitizerKind::KernelHWAddress
))
833 Fn
->addFnAttr(llvm::Attribute::SanitizeHWAddress
);
834 if (SanOpts
.has(SanitizerKind::MemtagStack
))
835 Fn
->addFnAttr(llvm::Attribute::SanitizeMemTag
);
836 if (SanOpts
.has(SanitizerKind::Thread
))
837 Fn
->addFnAttr(llvm::Attribute::SanitizeThread
);
838 if (SanOpts
.has(SanitizerKind::NumericalStability
))
839 Fn
->addFnAttr(llvm::Attribute::SanitizeNumericalStability
);
840 if (SanOpts
.hasOneOf(SanitizerKind::Memory
| SanitizerKind::KernelMemory
))
841 Fn
->addFnAttr(llvm::Attribute::SanitizeMemory
);
843 if (SanOpts
.has(SanitizerKind::SafeStack
))
844 Fn
->addFnAttr(llvm::Attribute::SafeStack
);
845 if (SanOpts
.has(SanitizerKind::ShadowCallStack
))
846 Fn
->addFnAttr(llvm::Attribute::ShadowCallStack
);
848 if (SanOpts
.has(SanitizerKind::Realtime
))
849 if (FD
&& FD
->getASTContext().hasAnyFunctionEffects())
850 for (const FunctionEffectWithCondition
&Fe
: FD
->getFunctionEffects()) {
851 if (Fe
.Effect
.kind() == FunctionEffect::Kind::NonBlocking
)
852 Fn
->addFnAttr(llvm::Attribute::SanitizeRealtime
);
855 // Apply fuzzing attribute to the function.
856 if (SanOpts
.hasOneOf(SanitizerKind::Fuzzer
| SanitizerKind::FuzzerNoLink
))
857 Fn
->addFnAttr(llvm::Attribute::OptForFuzzing
);
859 // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
860 // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
861 if (SanOpts
.has(SanitizerKind::Thread
)) {
862 if (const auto *OMD
= dyn_cast_or_null
<ObjCMethodDecl
>(D
)) {
863 const IdentifierInfo
*II
= OMD
->getSelector().getIdentifierInfoForSlot(0);
864 if (OMD
->getMethodFamily() == OMF_dealloc
||
865 OMD
->getMethodFamily() == OMF_initialize
||
866 (OMD
->getSelector().isUnarySelector() && II
->isStr(".cxx_destruct"))) {
867 markAsIgnoreThreadCheckingAtRuntime(Fn
);
872 // Ignore unrelated casts in STL allocate() since the allocator must cast
873 // from void* to T* before object initialization completes. Don't match on the
874 // namespace because not all allocators are in std::
875 if (D
&& SanOpts
.has(SanitizerKind::CFIUnrelatedCast
)) {
876 if (matchesStlAllocatorFn(D
, getContext()))
877 SanOpts
.Mask
&= ~SanitizerKind::CFIUnrelatedCast
;
880 // Ignore null checks in coroutine functions since the coroutines passes
881 // are not aware of how to move the extra UBSan instructions across the split
882 // coroutine boundaries.
883 if (D
&& SanOpts
.has(SanitizerKind::Null
))
884 if (FD
&& FD
->getBody() &&
885 FD
->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass
)
886 SanOpts
.Mask
&= ~SanitizerKind::Null
;
888 // Add pointer authentication attributes.
889 const CodeGenOptions
&CodeGenOpts
= CGM
.getCodeGenOpts();
890 if (CodeGenOpts
.PointerAuth
.ReturnAddresses
)
891 Fn
->addFnAttr("ptrauth-returns");
892 if (CodeGenOpts
.PointerAuth
.FunctionPointers
)
893 Fn
->addFnAttr("ptrauth-calls");
894 if (CodeGenOpts
.PointerAuth
.AuthTraps
)
895 Fn
->addFnAttr("ptrauth-auth-traps");
896 if (CodeGenOpts
.PointerAuth
.IndirectGotos
)
897 Fn
->addFnAttr("ptrauth-indirect-gotos");
899 // Apply xray attributes to the function (as a string, for now)
900 bool AlwaysXRayAttr
= false;
901 if (const auto *XRayAttr
= D
? D
->getAttr
<XRayInstrumentAttr
>() : nullptr) {
902 if (CGM
.getCodeGenOpts().XRayInstrumentationBundle
.has(
903 XRayInstrKind::FunctionEntry
) ||
904 CGM
.getCodeGenOpts().XRayInstrumentationBundle
.has(
905 XRayInstrKind::FunctionExit
)) {
906 if (XRayAttr
->alwaysXRayInstrument() && ShouldXRayInstrumentFunction()) {
907 Fn
->addFnAttr("function-instrument", "xray-always");
908 AlwaysXRayAttr
= true;
910 if (XRayAttr
->neverXRayInstrument())
911 Fn
->addFnAttr("function-instrument", "xray-never");
912 if (const auto *LogArgs
= D
->getAttr
<XRayLogArgsAttr
>())
913 if (ShouldXRayInstrumentFunction())
914 Fn
->addFnAttr("xray-log-args",
915 llvm::utostr(LogArgs
->getArgumentCount()));
918 if (ShouldXRayInstrumentFunction() && !CGM
.imbueXRayAttrs(Fn
, Loc
))
920 "xray-instruction-threshold",
921 llvm::itostr(CGM
.getCodeGenOpts().XRayInstructionThreshold
));
924 if (ShouldXRayInstrumentFunction()) {
925 if (CGM
.getCodeGenOpts().XRayIgnoreLoops
)
926 Fn
->addFnAttr("xray-ignore-loops");
928 if (!CGM
.getCodeGenOpts().XRayInstrumentationBundle
.has(
929 XRayInstrKind::FunctionExit
))
930 Fn
->addFnAttr("xray-skip-exit");
932 if (!CGM
.getCodeGenOpts().XRayInstrumentationBundle
.has(
933 XRayInstrKind::FunctionEntry
))
934 Fn
->addFnAttr("xray-skip-entry");
936 auto FuncGroups
= CGM
.getCodeGenOpts().XRayTotalFunctionGroups
;
937 if (FuncGroups
> 1) {
938 auto FuncName
= llvm::ArrayRef
<uint8_t>(CurFn
->getName().bytes_begin(),
939 CurFn
->getName().bytes_end());
940 auto Group
= crc32(FuncName
) % FuncGroups
;
941 if (Group
!= CGM
.getCodeGenOpts().XRaySelectedFunctionGroup
&&
943 Fn
->addFnAttr("function-instrument", "xray-never");
947 if (CGM
.getCodeGenOpts().getProfileInstr() != CodeGenOptions::ProfileNone
) {
948 switch (CGM
.isFunctionBlockedFromProfileInstr(Fn
, Loc
)) {
949 case ProfileList::Skip
:
950 Fn
->addFnAttr(llvm::Attribute::SkipProfile
);
952 case ProfileList::Forbid
:
953 Fn
->addFnAttr(llvm::Attribute::NoProfile
);
955 case ProfileList::Allow
:
960 unsigned Count
, Offset
;
961 if (const auto *Attr
=
962 D
? D
->getAttr
<PatchableFunctionEntryAttr
>() : nullptr) {
963 Count
= Attr
->getCount();
964 Offset
= Attr
->getOffset();
966 Count
= CGM
.getCodeGenOpts().PatchableFunctionEntryCount
;
967 Offset
= CGM
.getCodeGenOpts().PatchableFunctionEntryOffset
;
969 if (Count
&& Offset
<= Count
) {
970 Fn
->addFnAttr("patchable-function-entry", std::to_string(Count
- Offset
));
972 Fn
->addFnAttr("patchable-function-prefix", std::to_string(Offset
));
974 // Instruct that functions for COFF/CodeView targets should start with a
975 // patchable instruction, but only on x86/x64. Don't forward this to ARM/ARM64
976 // backends as they don't need it -- instructions on these architectures are
977 // always atomically patchable at runtime.
978 if (CGM
.getCodeGenOpts().HotPatch
&&
979 getContext().getTargetInfo().getTriple().isX86() &&
980 getContext().getTargetInfo().getTriple().getEnvironment() !=
981 llvm::Triple::CODE16
)
982 Fn
->addFnAttr("patchable-function", "prologue-short-redirect");
984 // Add no-jump-tables value.
985 if (CGM
.getCodeGenOpts().NoUseJumpTables
)
986 Fn
->addFnAttr("no-jump-tables", "true");
988 // Add no-inline-line-tables value.
989 if (CGM
.getCodeGenOpts().NoInlineLineTables
)
990 Fn
->addFnAttr("no-inline-line-tables");
992 // Add profile-sample-accurate value.
993 if (CGM
.getCodeGenOpts().ProfileSampleAccurate
)
994 Fn
->addFnAttr("profile-sample-accurate");
996 if (!CGM
.getCodeGenOpts().SampleProfileFile
.empty())
997 Fn
->addFnAttr("use-sample-profile");
999 if (D
&& D
->hasAttr
<CFICanonicalJumpTableAttr
>())
1000 Fn
->addFnAttr("cfi-canonical-jump-table");
1002 if (D
&& D
->hasAttr
<NoProfileFunctionAttr
>())
1003 Fn
->addFnAttr(llvm::Attribute::NoProfile
);
1005 if (D
&& D
->hasAttr
<HybridPatchableAttr
>())
1006 Fn
->addFnAttr(llvm::Attribute::HybridPatchable
);
1009 // Function attributes take precedence over command line flags.
1010 if (auto *A
= D
->getAttr
<FunctionReturnThunksAttr
>()) {
1011 switch (A
->getThunkType()) {
1012 case FunctionReturnThunksAttr::Kind::Keep
:
1014 case FunctionReturnThunksAttr::Kind::Extern
:
1015 Fn
->addFnAttr(llvm::Attribute::FnRetThunkExtern
);
1018 } else if (CGM
.getCodeGenOpts().FunctionReturnThunks
)
1019 Fn
->addFnAttr(llvm::Attribute::FnRetThunkExtern
);
1022 if (FD
&& (getLangOpts().OpenCL
||
1023 ((getLangOpts().HIP
|| getLangOpts().OffloadViaLLVM
) &&
1024 getLangOpts().CUDAIsDevice
))) {
1025 // Add metadata for a kernel function.
1026 EmitKernelMetadata(FD
, Fn
);
1029 if (FD
&& FD
->hasAttr
<ClspvLibclcBuiltinAttr
>()) {
1030 Fn
->setMetadata("clspv_libclc_builtin",
1031 llvm::MDNode::get(getLLVMContext(), {}));
1034 // If we are checking function types, emit a function type signature as
1036 if (FD
&& SanOpts
.has(SanitizerKind::Function
)) {
1037 if (llvm::Constant
*PrologueSig
= getPrologueSignature(CGM
, FD
)) {
1038 llvm::LLVMContext
&Ctx
= Fn
->getContext();
1039 llvm::MDBuilder
MDB(Ctx
);
1041 llvm::LLVMContext::MD_func_sanitize
,
1042 MDB
.createRTTIPointerPrologue(
1043 PrologueSig
, getUBSanFunctionTypeHash(FD
->getType())));
1047 // If we're checking nullability, we need to know whether we can check the
1048 // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
1049 if (SanOpts
.has(SanitizerKind::NullabilityReturn
)) {
1050 auto Nullability
= FnRetTy
->getNullability();
1051 if (Nullability
&& *Nullability
== NullabilityKind::NonNull
&&
1052 !FnRetTy
->isRecordType()) {
1053 if (!(SanOpts
.has(SanitizerKind::ReturnsNonnullAttribute
) &&
1054 CurCodeDecl
&& CurCodeDecl
->getAttr
<ReturnsNonNullAttr
>()))
1055 RetValNullabilityPrecondition
=
1056 llvm::ConstantInt::getTrue(getLLVMContext());
1060 // If we're in C++ mode and the function name is "main", it is guaranteed
1061 // to be norecurse by the standard (3.6.1.3 "The function main shall not be
1062 // used within a program").
1064 // OpenCL C 2.0 v2.2-11 s6.9.i:
1065 // Recursion is not supported.
1068 // Recursion is not supported.
1070 // SYCL v1.2.1 s3.10:
1071 // kernels cannot include RTTI information, exception classes,
1072 // recursive code, virtual functions or make use of C++ libraries that
1073 // are not compiled for the device.
1075 ((getLangOpts().CPlusPlus
&& FD
->isMain()) || getLangOpts().OpenCL
||
1076 getLangOpts().HLSL
|| getLangOpts().SYCLIsDevice
||
1077 (getLangOpts().CUDA
&& FD
->hasAttr
<CUDAGlobalAttr
>())))
1078 Fn
->addFnAttr(llvm::Attribute::NoRecurse
);
1080 llvm::RoundingMode RM
= getLangOpts().getDefaultRoundingMode();
1081 llvm::fp::ExceptionBehavior FPExceptionBehavior
=
1082 ToConstrainedExceptMD(getLangOpts().getDefaultExceptionMode());
1083 Builder
.setDefaultConstrainedRounding(RM
);
1084 Builder
.setDefaultConstrainedExcept(FPExceptionBehavior
);
1085 if ((FD
&& (FD
->UsesFPIntrin() || FD
->hasAttr
<StrictFPAttr
>())) ||
1086 (!FD
&& (FPExceptionBehavior
!= llvm::fp::ebIgnore
||
1087 RM
!= llvm::RoundingMode::NearestTiesToEven
))) {
1088 Builder
.setIsFPConstrained(true);
1089 Fn
->addFnAttr(llvm::Attribute::StrictFP
);
1092 // If a custom alignment is used, force realigning to this alignment on
1093 // any main function which certainly will need it.
1094 if (FD
&& ((FD
->isMain() || FD
->isMSVCRTEntryPoint()) &&
1095 CGM
.getCodeGenOpts().StackAlignment
))
1096 Fn
->addFnAttr("stackrealign");
1098 // "main" doesn't need to zero out call-used registers.
1099 if (FD
&& FD
->isMain())
1100 Fn
->removeFnAttr("zero-call-used-regs");
1102 llvm::BasicBlock
*EntryBB
= createBasicBlock("entry", CurFn
);
1104 // Create a marker to make it easy to insert allocas into the entryblock
1105 // later. Don't create this with the builder, because we don't want it
1107 llvm::Value
*Undef
= llvm::UndefValue::get(Int32Ty
);
1108 AllocaInsertPt
= new llvm::BitCastInst(Undef
, Int32Ty
, "allocapt", EntryBB
);
1110 ReturnBlock
= getJumpDestInCurrentScope("return");
1112 Builder
.SetInsertPoint(EntryBB
);
1114 // If we're checking the return value, allocate space for a pointer to a
1115 // precise source location of the checked return statement.
1116 if (requiresReturnValueCheck()) {
1117 ReturnLocation
= CreateDefaultAlignTempAlloca(Int8PtrTy
, "return.sloc.ptr");
1118 Builder
.CreateStore(llvm::ConstantPointerNull::get(Int8PtrTy
),
1122 // Emit subprogram debug descriptor.
1123 if (CGDebugInfo
*DI
= getDebugInfo()) {
1124 // Reconstruct the type from the argument list so that implicit parameters,
1125 // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
1127 DI
->emitFunctionStart(GD
, Loc
, StartLoc
,
1128 DI
->getFunctionType(FD
, RetTy
, Args
), CurFn
,
1132 if (ShouldInstrumentFunction()) {
1133 if (CGM
.getCodeGenOpts().InstrumentFunctions
)
1134 CurFn
->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
1135 if (CGM
.getCodeGenOpts().InstrumentFunctionsAfterInlining
)
1136 CurFn
->addFnAttr("instrument-function-entry-inlined",
1137 "__cyg_profile_func_enter");
1138 if (CGM
.getCodeGenOpts().InstrumentFunctionEntryBare
)
1139 CurFn
->addFnAttr("instrument-function-entry-inlined",
1140 "__cyg_profile_func_enter_bare");
1143 // Since emitting the mcount call here impacts optimizations such as function
1144 // inlining, we just add an attribute to insert a mcount call in backend.
1145 // The attribute "counting-function" is set to mcount function name which is
1146 // architecture dependent.
1147 if (CGM
.getCodeGenOpts().InstrumentForProfiling
) {
1148 // Calls to fentry/mcount should not be generated if function has
1149 // the no_instrument_function attribute.
1150 if (!CurFuncDecl
|| !CurFuncDecl
->hasAttr
<NoInstrumentFunctionAttr
>()) {
1151 if (CGM
.getCodeGenOpts().CallFEntry
)
1152 Fn
->addFnAttr("fentry-call", "true");
1154 Fn
->addFnAttr("instrument-function-entry-inlined",
1155 getTarget().getMCountName());
1157 if (CGM
.getCodeGenOpts().MNopMCount
) {
1158 if (!CGM
.getCodeGenOpts().CallFEntry
)
1159 CGM
.getDiags().Report(diag::err_opt_not_valid_without_opt
)
1160 << "-mnop-mcount" << "-mfentry";
1161 Fn
->addFnAttr("mnop-mcount");
1164 if (CGM
.getCodeGenOpts().RecordMCount
) {
1165 if (!CGM
.getCodeGenOpts().CallFEntry
)
1166 CGM
.getDiags().Report(diag::err_opt_not_valid_without_opt
)
1167 << "-mrecord-mcount" << "-mfentry";
1168 Fn
->addFnAttr("mrecord-mcount");
1173 if (CGM
.getCodeGenOpts().PackedStack
) {
1174 if (getContext().getTargetInfo().getTriple().getArch() !=
1175 llvm::Triple::systemz
)
1176 CGM
.getDiags().Report(diag::err_opt_not_valid_on_target
)
1177 << "-mpacked-stack";
1178 Fn
->addFnAttr("packed-stack");
1181 if (CGM
.getCodeGenOpts().WarnStackSize
!= UINT_MAX
&&
1182 !CGM
.getDiags().isIgnored(diag::warn_fe_backend_frame_larger_than
, Loc
))
1183 Fn
->addFnAttr("warn-stack-size",
1184 std::to_string(CGM
.getCodeGenOpts().WarnStackSize
));
1186 if (RetTy
->isVoidType()) {
1187 // Void type; nothing to return.
1188 ReturnValue
= Address::invalid();
1190 // Count the implicit return.
1191 if (!endsWithReturn(D
))
1193 } else if (CurFnInfo
->getReturnInfo().getKind() == ABIArgInfo::Indirect
) {
1194 // Indirect return; emit returned value directly into sret slot.
1195 // This reduces code size, and affects correctness in C++.
1196 auto AI
= CurFn
->arg_begin();
1197 if (CurFnInfo
->getReturnInfo().isSRetAfterThis())
1199 ReturnValue
= makeNaturalAddressForPointer(
1200 &*AI
, RetTy
, CurFnInfo
->getReturnInfo().getIndirectAlign(), false,
1201 nullptr, nullptr, KnownNonNull
);
1202 if (!CurFnInfo
->getReturnInfo().getIndirectByVal()) {
1203 ReturnValuePointer
=
1204 CreateDefaultAlignTempAlloca(ReturnValue
.getType(), "result.ptr");
1205 Builder
.CreateStore(ReturnValue
.emitRawPointer(*this),
1206 ReturnValuePointer
);
1208 } else if (CurFnInfo
->getReturnInfo().getKind() == ABIArgInfo::InAlloca
&&
1209 !hasScalarEvaluationKind(CurFnInfo
->getReturnType())) {
1210 // Load the sret pointer from the argument struct and return into that.
1211 unsigned Idx
= CurFnInfo
->getReturnInfo().getInAllocaFieldIndex();
1212 llvm::Function::arg_iterator EI
= CurFn
->arg_end();
1214 llvm::Value
*Addr
= Builder
.CreateStructGEP(
1215 CurFnInfo
->getArgStruct(), &*EI
, Idx
);
1217 cast
<llvm::GetElementPtrInst
>(Addr
)->getResultElementType();
1218 ReturnValuePointer
= Address(Addr
, Ty
, getPointerAlign());
1219 Addr
= Builder
.CreateAlignedLoad(Ty
, Addr
, getPointerAlign(), "agg.result");
1220 ReturnValue
= Address(Addr
, ConvertType(RetTy
),
1221 CGM
.getNaturalTypeAlignment(RetTy
), KnownNonNull
);
1223 ReturnValue
= CreateIRTemp(RetTy
, "retval");
1225 // Tell the epilog emitter to autorelease the result. We do this
1226 // now so that various specialized functions can suppress it
1227 // during their IR-generation.
1228 if (getLangOpts().ObjCAutoRefCount
&&
1229 !CurFnInfo
->isReturnsRetained() &&
1230 RetTy
->isObjCRetainableType())
1231 AutoreleaseResult
= true;
1234 EmitStartEHSpec(CurCodeDecl
);
1236 PrologueCleanupDepth
= EHStack
.stable_begin();
1238 // Emit OpenMP specific initialization of the device functions.
1239 if (getLangOpts().OpenMP
&& CurCodeDecl
)
1240 CGM
.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl
);
1242 if (FD
&& getLangOpts().HLSL
) {
1243 // Handle emitting HLSL entry functions.
1244 if (FD
->hasAttr
<HLSLShaderAttr
>()) {
1245 CGM
.getHLSLRuntime().emitEntryFunction(FD
, Fn
);
1247 CGM
.getHLSLRuntime().setHLSLFunctionAttributes(FD
, Fn
);
1250 EmitFunctionProlog(*CurFnInfo
, CurFn
, Args
);
1252 if (const CXXMethodDecl
*MD
= dyn_cast_if_present
<CXXMethodDecl
>(D
);
1253 MD
&& !MD
->isStatic()) {
1255 MD
->getParent()->isLambda() && MD
->getOverloadedOperator() == OO_Call
;
1256 if (MD
->isImplicitObjectMemberFunction())
1257 CGM
.getCXXABI().EmitInstanceFunctionProlog(*this);
1259 // We're in a lambda; figure out the captures.
1260 MD
->getParent()->getCaptureFields(LambdaCaptureFields
,
1261 LambdaThisCaptureField
);
1262 if (LambdaThisCaptureField
) {
1263 // If the lambda captures the object referred to by '*this' - either by
1264 // value or by reference, make sure CXXThisValue points to the correct
1267 // Get the lvalue for the field (which is a copy of the enclosing object
1268 // or contains the address of the enclosing object).
1269 LValue ThisFieldLValue
= EmitLValueForLambdaField(LambdaThisCaptureField
);
1270 if (!LambdaThisCaptureField
->getType()->isPointerType()) {
1271 // If the enclosing object was captured by value, just use its
1272 // address. Sign this pointer.
1273 CXXThisValue
= ThisFieldLValue
.getPointer(*this);
1275 // Load the lvalue pointed to by the field, since '*this' was captured
1278 EmitLoadOfLValue(ThisFieldLValue
, SourceLocation()).getScalarVal();
1281 for (auto *FD
: MD
->getParent()->fields()) {
1282 if (FD
->hasCapturedVLAType()) {
1283 auto *ExprArg
= EmitLoadOfLValue(EmitLValueForLambdaField(FD
),
1284 SourceLocation()).getScalarVal();
1285 auto VAT
= FD
->getCapturedVLAType();
1286 VLASizeMap
[VAT
->getSizeExpr()] = ExprArg
;
1289 } else if (MD
->isImplicitObjectMemberFunction()) {
1290 // Not in a lambda; just use 'this' from the method.
1291 // FIXME: Should we generate a new load for each use of 'this'? The
1292 // fast register allocator would be happier...
1293 CXXThisValue
= CXXABIThisValue
;
1296 // Check the 'this' pointer once per function, if it's available.
1297 if (CXXABIThisValue
) {
1298 SanitizerSet SkippedChecks
;
1299 SkippedChecks
.set(SanitizerKind::ObjectSize
, true);
1300 QualType ThisTy
= MD
->getThisType();
1302 // If this is the call operator of a lambda with no captures, it
1303 // may have a static invoker function, which may call this operator with
1304 // a null 'this' pointer.
1305 if (isLambdaCallOperator(MD
) && MD
->getParent()->isCapturelessLambda())
1306 SkippedChecks
.set(SanitizerKind::Null
, true);
1309 isa
<CXXConstructorDecl
>(MD
) ? TCK_ConstructorCall
: TCK_MemberCall
,
1310 Loc
, CXXABIThisValue
, ThisTy
, CXXABIThisAlignment
, SkippedChecks
);
1314 // If any of the arguments have a variably modified type, make sure to
1315 // emit the type size, but only if the function is not naked. Naked functions
1316 // have no prolog to run this evaluation.
1317 if (!FD
|| !FD
->hasAttr
<NakedAttr
>()) {
1318 for (const VarDecl
*VD
: Args
) {
1319 // Dig out the type as written from ParmVarDecls; it's unclear whether
1320 // the standard (C99 6.9.1p10) requires this, but we're following the
1321 // precedent set by gcc.
1323 if (const ParmVarDecl
*PVD
= dyn_cast
<ParmVarDecl
>(VD
))
1324 Ty
= PVD
->getOriginalType();
1328 if (Ty
->isVariablyModifiedType())
1329 EmitVariablyModifiedType(Ty
);
1332 // Emit a location at the end of the prologue.
1333 if (CGDebugInfo
*DI
= getDebugInfo())
1334 DI
->EmitLocation(Builder
, StartLoc
);
1335 // TODO: Do we need to handle this in two places like we do with
1336 // target-features/target-cpu?
1338 if (const auto *VecWidth
= CurFuncDecl
->getAttr
<MinVectorWidthAttr
>())
1339 LargestVectorWidth
= VecWidth
->getVectorWidth();
1341 if (CGM
.shouldEmitConvergenceTokens())
1342 ConvergenceTokenStack
.push_back(getOrEmitConvergenceEntryToken(CurFn
));
1345 void CodeGenFunction::EmitFunctionBody(const Stmt
*Body
) {
1346 incrementProfileCounter(Body
);
1347 maybeCreateMCDCCondBitmap();
1348 if (const CompoundStmt
*S
= dyn_cast
<CompoundStmt
>(Body
))
1349 EmitCompoundStmtWithoutScope(*S
);
1354 /// When instrumenting to collect profile data, the counts for some blocks
1355 /// such as switch cases need to not include the fall-through counts, so
1356 /// emit a branch around the instrumentation code. When not instrumenting,
1357 /// this just calls EmitBlock().
1358 void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock
*BB
,
1360 llvm::BasicBlock
*SkipCountBB
= nullptr;
1361 // Do not skip over the instrumentation when single byte coverage mode is
1363 if (HaveInsertPoint() && CGM
.getCodeGenOpts().hasProfileClangInstr() &&
1364 !llvm::EnableSingleByteCoverage
) {
1365 // When instrumenting for profiling, the fallthrough to certain
1366 // statements needs to skip over the instrumentation code so that we
1367 // get an accurate count.
1368 SkipCountBB
= createBasicBlock("skipcount");
1369 EmitBranch(SkipCountBB
);
1372 uint64_t CurrentCount
= getCurrentProfileCount();
1373 incrementProfileCounter(S
);
1374 setCurrentProfileCount(getCurrentProfileCount() + CurrentCount
);
1376 EmitBlock(SkipCountBB
);
1379 /// Tries to mark the given function nounwind based on the
1380 /// non-existence of any throwing calls within it. We believe this is
1381 /// lightweight enough to do at -O0.
1382 static void TryMarkNoThrow(llvm::Function
*F
) {
1383 // LLVM treats 'nounwind' on a function as part of the type, so we
1384 // can't do this on functions that can be overwritten.
1385 if (F
->isInterposable()) return;
1387 for (llvm::BasicBlock
&BB
: *F
)
1388 for (llvm::Instruction
&I
: BB
)
1392 F
->setDoesNotThrow();
1395 QualType
CodeGenFunction::BuildFunctionArgList(GlobalDecl GD
,
1396 FunctionArgList
&Args
) {
1397 const FunctionDecl
*FD
= cast
<FunctionDecl
>(GD
.getDecl());
1398 QualType ResTy
= FD
->getReturnType();
1400 const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(FD
);
1401 if (MD
&& MD
->isImplicitObjectMemberFunction()) {
1402 if (CGM
.getCXXABI().HasThisReturn(GD
))
1403 ResTy
= MD
->getThisType();
1404 else if (CGM
.getCXXABI().hasMostDerivedReturn(GD
))
1405 ResTy
= CGM
.getContext().VoidPtrTy
;
1406 CGM
.getCXXABI().buildThisParam(*this, Args
);
1409 // The base version of an inheriting constructor whose constructed base is a
1410 // virtual base is not passed any arguments (because it doesn't actually call
1411 // the inherited constructor).
1412 bool PassedParams
= true;
1413 if (const CXXConstructorDecl
*CD
= dyn_cast
<CXXConstructorDecl
>(FD
))
1414 if (auto Inherited
= CD
->getInheritedConstructor())
1416 getTypes().inheritingCtorHasParams(Inherited
, GD
.getCtorType());
1419 for (auto *Param
: FD
->parameters()) {
1420 Args
.push_back(Param
);
1421 if (!Param
->hasAttr
<PassObjectSizeAttr
>())
1424 auto *Implicit
= ImplicitParamDecl::Create(
1425 getContext(), Param
->getDeclContext(), Param
->getLocation(),
1426 /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamKind::Other
);
1427 SizeArguments
[Param
] = Implicit
;
1428 Args
.push_back(Implicit
);
1432 if (MD
&& (isa
<CXXConstructorDecl
>(MD
) || isa
<CXXDestructorDecl
>(MD
)))
1433 CGM
.getCXXABI().addImplicitStructorParams(*this, ResTy
, Args
);
1438 void CodeGenFunction::GenerateCode(GlobalDecl GD
, llvm::Function
*Fn
,
1439 const CGFunctionInfo
&FnInfo
) {
1440 assert(Fn
&& "generating code for null Function");
1441 const FunctionDecl
*FD
= cast
<FunctionDecl
>(GD
.getDecl());
1444 FunctionArgList Args
;
1445 QualType ResTy
= BuildFunctionArgList(GD
, Args
);
1447 CGM
.getTargetCodeGenInfo().checkFunctionABI(CGM
, FD
);
1449 if (FD
->isInlineBuiltinDeclaration()) {
1450 // When generating code for a builtin with an inline declaration, use a
1451 // mangled name to hold the actual body, while keeping an external
1452 // definition in case the function pointer is referenced somewhere.
1453 std::string FDInlineName
= (Fn
->getName() + ".inline").str();
1454 llvm::Module
*M
= Fn
->getParent();
1455 llvm::Function
*Clone
= M
->getFunction(FDInlineName
);
1457 Clone
= llvm::Function::Create(Fn
->getFunctionType(),
1458 llvm::GlobalValue::InternalLinkage
,
1459 Fn
->getAddressSpace(), FDInlineName
, M
);
1460 Clone
->addFnAttr(llvm::Attribute::AlwaysInline
);
1462 Fn
->setLinkage(llvm::GlobalValue::ExternalLinkage
);
1465 // Detect the unusual situation where an inline version is shadowed by a
1466 // non-inline version. In that case we should pick the external one
1467 // everywhere. That's GCC behavior too. Unfortunately, I cannot find a way
1468 // to detect that situation before we reach codegen, so do some late
1470 for (const FunctionDecl
*PD
= FD
->getPreviousDecl(); PD
;
1471 PD
= PD
->getPreviousDecl()) {
1472 if (LLVM_UNLIKELY(PD
->isInlineBuiltinDeclaration())) {
1473 std::string FDInlineName
= (Fn
->getName() + ".inline").str();
1474 llvm::Module
*M
= Fn
->getParent();
1475 if (llvm::Function
*Clone
= M
->getFunction(FDInlineName
)) {
1476 Clone
->replaceAllUsesWith(Fn
);
1477 Clone
->eraseFromParent();
1484 // Check if we should generate debug info for this function.
1485 if (FD
->hasAttr
<NoDebugAttr
>()) {
1486 // Clear non-distinct debug info that was possibly attached to the function
1487 // due to an earlier declaration without the nodebug attribute
1488 Fn
->setSubprogram(nullptr);
1489 // Disable debug info indefinitely for this function
1490 DebugInfo
= nullptr;
1493 // The function might not have a body if we're generating thunks for a
1494 // function declaration.
1495 SourceRange BodyRange
;
1496 if (Stmt
*Body
= FD
->getBody())
1497 BodyRange
= Body
->getSourceRange();
1499 BodyRange
= FD
->getLocation();
1500 CurEHLocation
= BodyRange
.getEnd();
1502 // Use the location of the start of the function to determine where
1503 // the function definition is located. By default use the location
1504 // of the declaration as the location for the subprogram. A function
1505 // may lack a declaration in the source code if it is created by code
1506 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1507 SourceLocation Loc
= FD
->getLocation();
1509 // If this is a function specialization then use the pattern body
1510 // as the location for the function.
1511 if (const FunctionDecl
*SpecDecl
= FD
->getTemplateInstantiationPattern())
1512 if (SpecDecl
->hasBody(SpecDecl
))
1513 Loc
= SpecDecl
->getLocation();
1515 Stmt
*Body
= FD
->getBody();
1518 // Coroutines always emit lifetime markers.
1519 if (isa
<CoroutineBodyStmt
>(Body
))
1520 ShouldEmitLifetimeMarkers
= true;
1522 // Initialize helper which will detect jumps which can cause invalid
1523 // lifetime markers.
1524 if (ShouldEmitLifetimeMarkers
)
1525 Bypasses
.Init(Body
);
1528 // Emit the standard function prologue.
1529 StartFunction(GD
, ResTy
, Fn
, FnInfo
, Args
, Loc
, BodyRange
.getBegin());
1531 // Save parameters for coroutine function.
1532 if (Body
&& isa_and_nonnull
<CoroutineBodyStmt
>(Body
))
1533 llvm::append_range(FnArgs
, FD
->parameters());
1535 // Ensure that the function adheres to the forward progress guarantee, which
1536 // is required by certain optimizations.
1537 // In C++11 and up, the attribute will be removed if the body contains a
1538 // trivial empty loop.
1539 if (checkIfFunctionMustProgress())
1540 CurFn
->addFnAttr(llvm::Attribute::MustProgress
);
1542 // Generate the body of the function.
1543 PGO
.assignRegionCounters(GD
, CurFn
);
1544 if (isa
<CXXDestructorDecl
>(FD
))
1545 EmitDestructorBody(Args
);
1546 else if (isa
<CXXConstructorDecl
>(FD
))
1547 EmitConstructorBody(Args
);
1548 else if (getLangOpts().CUDA
&&
1549 !getLangOpts().CUDAIsDevice
&&
1550 FD
->hasAttr
<CUDAGlobalAttr
>())
1551 CGM
.getCUDARuntime().emitDeviceStub(*this, Args
);
1552 else if (isa
<CXXMethodDecl
>(FD
) &&
1553 cast
<CXXMethodDecl
>(FD
)->isLambdaStaticInvoker()) {
1554 // The lambda static invoker function is special, because it forwards or
1555 // clones the body of the function call operator (but is actually static).
1556 EmitLambdaStaticInvokeBody(cast
<CXXMethodDecl
>(FD
));
1557 } else if (isa
<CXXMethodDecl
>(FD
) &&
1558 isLambdaCallOperator(cast
<CXXMethodDecl
>(FD
)) &&
1559 !FnInfo
.isDelegateCall() &&
1560 cast
<CXXMethodDecl
>(FD
)->getParent()->getLambdaStaticInvoker() &&
1561 hasInAllocaArg(cast
<CXXMethodDecl
>(FD
))) {
1562 // If emitting a lambda with static invoker on X86 Windows, change
1563 // the call operator body.
1564 // Make sure that this is a call operator with an inalloca arg and check
1565 // for delegate call to make sure this is the original call op and not the
1566 // new forwarding function for the static invoker.
1567 EmitLambdaInAllocaCallOpBody(cast
<CXXMethodDecl
>(FD
));
1568 } else if (FD
->isDefaulted() && isa
<CXXMethodDecl
>(FD
) &&
1569 (cast
<CXXMethodDecl
>(FD
)->isCopyAssignmentOperator() ||
1570 cast
<CXXMethodDecl
>(FD
)->isMoveAssignmentOperator())) {
1571 // Implicit copy-assignment gets the same special treatment as implicit
1572 // copy-constructors.
1573 emitImplicitAssignmentOperatorBody(Args
);
1575 EmitFunctionBody(Body
);
1577 llvm_unreachable("no definition for emitted function");
1579 // C++11 [stmt.return]p2:
1580 // Flowing off the end of a function [...] results in undefined behavior in
1581 // a value-returning function.
1583 // If the '}' that terminates a function is reached, and the value of the
1584 // function call is used by the caller, the behavior is undefined.
1585 if (getLangOpts().CPlusPlus
&& !FD
->hasImplicitReturnZero() && !SawAsmBlock
&&
1586 !FD
->getReturnType()->isVoidType() && Builder
.GetInsertBlock()) {
1587 bool ShouldEmitUnreachable
=
1588 CGM
.getCodeGenOpts().StrictReturn
||
1589 !CGM
.MayDropFunctionReturn(FD
->getASTContext(), FD
->getReturnType());
1590 if (SanOpts
.has(SanitizerKind::Return
)) {
1591 SanitizerScope
SanScope(this);
1592 llvm::Value
*IsFalse
= Builder
.getFalse();
1593 EmitCheck(std::make_pair(IsFalse
, SanitizerKind::Return
),
1594 SanitizerHandler::MissingReturn
,
1595 EmitCheckSourceLocation(FD
->getLocation()), std::nullopt
);
1596 } else if (ShouldEmitUnreachable
) {
1597 if (CGM
.getCodeGenOpts().OptimizationLevel
== 0)
1598 EmitTrapCall(llvm::Intrinsic::trap
);
1600 if (SanOpts
.has(SanitizerKind::Return
) || ShouldEmitUnreachable
) {
1601 Builder
.CreateUnreachable();
1602 Builder
.ClearInsertionPoint();
1606 // Emit the standard function epilogue.
1607 FinishFunction(BodyRange
.getEnd());
1609 // If we haven't marked the function nothrow through other means, do
1610 // a quick pass now to see if we can.
1611 if (!CurFn
->doesNotThrow())
1612 TryMarkNoThrow(CurFn
);
1615 /// ContainsLabel - Return true if the statement contains a label in it. If
1616 /// this statement is not executed normally, it not containing a label means
1617 /// that we can just remove the code.
1618 bool CodeGenFunction::ContainsLabel(const Stmt
*S
, bool IgnoreCaseStmts
) {
1619 // Null statement, not a label!
1620 if (!S
) return false;
1622 // If this is a label, we have to emit the code, consider something like:
1623 // if (0) { ... foo: bar(); } goto foo;
1625 // TODO: If anyone cared, we could track __label__'s, since we know that you
1626 // can't jump to one from outside their declared region.
1627 if (isa
<LabelStmt
>(S
))
1630 // If this is a case/default statement, and we haven't seen a switch, we have
1631 // to emit the code.
1632 if (isa
<SwitchCase
>(S
) && !IgnoreCaseStmts
)
1635 // If this is a switch statement, we want to ignore cases below it.
1636 if (isa
<SwitchStmt
>(S
))
1637 IgnoreCaseStmts
= true;
1639 // Scan subexpressions for verboten labels.
1640 for (const Stmt
*SubStmt
: S
->children())
1641 if (ContainsLabel(SubStmt
, IgnoreCaseStmts
))
1647 /// containsBreak - Return true if the statement contains a break out of it.
1648 /// If the statement (recursively) contains a switch or loop with a break
1649 /// inside of it, this is fine.
1650 bool CodeGenFunction::containsBreak(const Stmt
*S
) {
1651 // Null statement, not a label!
1652 if (!S
) return false;
1654 // If this is a switch or loop that defines its own break scope, then we can
1655 // include it and anything inside of it.
1656 if (isa
<SwitchStmt
>(S
) || isa
<WhileStmt
>(S
) || isa
<DoStmt
>(S
) ||
1660 if (isa
<BreakStmt
>(S
))
1663 // Scan subexpressions for verboten breaks.
1664 for (const Stmt
*SubStmt
: S
->children())
1665 if (containsBreak(SubStmt
))
1671 bool CodeGenFunction::mightAddDeclToScope(const Stmt
*S
) {
1672 if (!S
) return false;
1674 // Some statement kinds add a scope and thus never add a decl to the current
1675 // scope. Note, this list is longer than the list of statements that might
1676 // have an unscoped decl nested within them, but this way is conservatively
1677 // correct even if more statement kinds are added.
1678 if (isa
<IfStmt
>(S
) || isa
<SwitchStmt
>(S
) || isa
<WhileStmt
>(S
) ||
1679 isa
<DoStmt
>(S
) || isa
<ForStmt
>(S
) || isa
<CompoundStmt
>(S
) ||
1680 isa
<CXXForRangeStmt
>(S
) || isa
<CXXTryStmt
>(S
) ||
1681 isa
<ObjCForCollectionStmt
>(S
) || isa
<ObjCAtTryStmt
>(S
))
1684 if (isa
<DeclStmt
>(S
))
1687 for (const Stmt
*SubStmt
: S
->children())
1688 if (mightAddDeclToScope(SubStmt
))
1694 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1695 /// to a constant, or if it does but contains a label, return false. If it
1696 /// constant folds return true and set the boolean result in Result.
1697 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr
*Cond
,
1700 // If MC/DC is enabled, disable folding so that we can instrument all
1701 // conditions to yield complete test vectors. We still keep track of
1702 // folded conditions during region mapping and visualization.
1703 if (!AllowLabels
&& CGM
.getCodeGenOpts().hasProfileClangInstr() &&
1704 CGM
.getCodeGenOpts().MCDCCoverage
)
1707 llvm::APSInt ResultInt
;
1708 if (!ConstantFoldsToSimpleInteger(Cond
, ResultInt
, AllowLabels
))
1711 ResultBool
= ResultInt
.getBoolValue();
1715 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1716 /// to a constant, or if it does but contains a label, return false. If it
1717 /// constant folds return true and set the folded value.
1718 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr
*Cond
,
1719 llvm::APSInt
&ResultInt
,
1721 // FIXME: Rename and handle conversion of other evaluatable things
1723 Expr::EvalResult Result
;
1724 if (!Cond
->EvaluateAsInt(Result
, getContext()))
1725 return false; // Not foldable, not integer or not fully evaluatable.
1727 llvm::APSInt Int
= Result
.Val
.getInt();
1728 if (!AllowLabels
&& CodeGenFunction::ContainsLabel(Cond
))
1729 return false; // Contains a label.
1735 /// Strip parentheses and simplistic logical-NOT operators.
1736 const Expr
*CodeGenFunction::stripCond(const Expr
*C
) {
1737 while (const UnaryOperator
*Op
= dyn_cast
<UnaryOperator
>(C
->IgnoreParens())) {
1738 if (Op
->getOpcode() != UO_LNot
)
1740 C
= Op
->getSubExpr();
1742 return C
->IgnoreParens();
1745 /// Determine whether the given condition is an instrumentable condition
1746 /// (i.e. no "&&" or "||").
1747 bool CodeGenFunction::isInstrumentedCondition(const Expr
*C
) {
1748 const BinaryOperator
*BOp
= dyn_cast
<BinaryOperator
>(stripCond(C
));
1749 return (!BOp
|| !BOp
->isLogicalOp());
1752 /// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
1753 /// increments a profile counter based on the semantics of the given logical
1754 /// operator opcode. This is used to instrument branch condition coverage for
1755 /// logical operators.
1756 void CodeGenFunction::EmitBranchToCounterBlock(
1757 const Expr
*Cond
, BinaryOperator::Opcode LOp
, llvm::BasicBlock
*TrueBlock
,
1758 llvm::BasicBlock
*FalseBlock
, uint64_t TrueCount
/* = 0 */,
1759 Stmt::Likelihood LH
/* =None */, const Expr
*CntrIdx
/* = nullptr */) {
1760 // If not instrumenting, just emit a branch.
1761 bool InstrumentRegions
= CGM
.getCodeGenOpts().hasProfileClangInstr();
1762 if (!InstrumentRegions
|| !isInstrumentedCondition(Cond
))
1763 return EmitBranchOnBoolExpr(Cond
, TrueBlock
, FalseBlock
, TrueCount
, LH
);
1765 llvm::BasicBlock
*ThenBlock
= nullptr;
1766 llvm::BasicBlock
*ElseBlock
= nullptr;
1767 llvm::BasicBlock
*NextBlock
= nullptr;
1769 // Create the block we'll use to increment the appropriate counter.
1770 llvm::BasicBlock
*CounterIncrBlock
= createBasicBlock("lop.rhscnt");
1772 // Set block pointers according to Logical-AND (BO_LAnd) semantics. This
1773 // means we need to evaluate the condition and increment the counter on TRUE:
1776 // goto CounterIncrBlock;
1780 // CounterIncrBlock:
1784 if (LOp
== BO_LAnd
) {
1785 ThenBlock
= CounterIncrBlock
;
1786 ElseBlock
= FalseBlock
;
1787 NextBlock
= TrueBlock
;
1790 // Set block pointers according to Logical-OR (BO_LOr) semantics. This means
1791 // we need to evaluate the condition and increment the counter on FALSE:
1796 // goto CounterIncrBlock;
1798 // CounterIncrBlock:
1802 else if (LOp
== BO_LOr
) {
1803 ThenBlock
= TrueBlock
;
1804 ElseBlock
= CounterIncrBlock
;
1805 NextBlock
= FalseBlock
;
1807 llvm_unreachable("Expected Opcode must be that of a Logical Operator");
1810 // Emit Branch based on condition.
1811 EmitBranchOnBoolExpr(Cond
, ThenBlock
, ElseBlock
, TrueCount
, LH
);
1813 // Emit the block containing the counter increment(s).
1814 EmitBlock(CounterIncrBlock
);
1816 // Increment corresponding counter; if index not provided, use Cond as index.
1817 incrementProfileCounter(CntrIdx
? CntrIdx
: Cond
);
1819 // Go to the next block.
1820 EmitBranch(NextBlock
);
1823 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1824 /// statement) to the specified blocks. Based on the condition, this might try
1825 /// to simplify the codegen of the conditional based on the branch.
1826 /// \param LH The value of the likelihood attribute on the True branch.
1827 /// \param ConditionalOp Used by MC/DC code coverage to track the result of the
1828 /// ConditionalOperator (ternary) through a recursive call for the operator's
1829 /// LHS and RHS nodes.
1830 void CodeGenFunction::EmitBranchOnBoolExpr(
1831 const Expr
*Cond
, llvm::BasicBlock
*TrueBlock
, llvm::BasicBlock
*FalseBlock
,
1832 uint64_t TrueCount
, Stmt::Likelihood LH
, const Expr
*ConditionalOp
) {
1833 Cond
= Cond
->IgnoreParens();
1835 if (const BinaryOperator
*CondBOp
= dyn_cast
<BinaryOperator
>(Cond
)) {
1836 // Handle X && Y in a condition.
1837 if (CondBOp
->getOpcode() == BO_LAnd
) {
1838 MCDCLogOpStack
.push_back(CondBOp
);
1840 // If we have "1 && X", simplify the code. "0 && X" would have constant
1841 // folded if the case was simple enough.
1842 bool ConstantBool
= false;
1843 if (ConstantFoldsToSimpleInteger(CondBOp
->getLHS(), ConstantBool
) &&
1845 // br(1 && X) -> br(X).
1846 incrementProfileCounter(CondBOp
);
1847 EmitBranchToCounterBlock(CondBOp
->getRHS(), BO_LAnd
, TrueBlock
,
1848 FalseBlock
, TrueCount
, LH
);
1849 MCDCLogOpStack
.pop_back();
1853 // If we have "X && 1", simplify the code to use an uncond branch.
1854 // "X && 0" would have been constant folded to 0.
1855 if (ConstantFoldsToSimpleInteger(CondBOp
->getRHS(), ConstantBool
) &&
1857 // br(X && 1) -> br(X).
1858 EmitBranchToCounterBlock(CondBOp
->getLHS(), BO_LAnd
, TrueBlock
,
1859 FalseBlock
, TrueCount
, LH
, CondBOp
);
1860 MCDCLogOpStack
.pop_back();
1864 // Emit the LHS as a conditional. If the LHS conditional is false, we
1865 // want to jump to the FalseBlock.
1866 llvm::BasicBlock
*LHSTrue
= createBasicBlock("land.lhs.true");
1867 // The counter tells us how often we evaluate RHS, and all of TrueCount
1868 // can be propagated to that branch.
1869 uint64_t RHSCount
= getProfileCount(CondBOp
->getRHS());
1871 ConditionalEvaluation
eval(*this);
1873 ApplyDebugLocation
DL(*this, Cond
);
1874 // Propagate the likelihood attribute like __builtin_expect
1875 // __builtin_expect(X && Y, 1) -> X and Y are likely
1876 // __builtin_expect(X && Y, 0) -> only Y is unlikely
1877 EmitBranchOnBoolExpr(CondBOp
->getLHS(), LHSTrue
, FalseBlock
, RHSCount
,
1878 LH
== Stmt::LH_Unlikely
? Stmt::LH_None
: LH
);
1882 incrementProfileCounter(CondBOp
);
1883 setCurrentProfileCount(getProfileCount(CondBOp
->getRHS()));
1885 // Any temporaries created here are conditional.
1887 EmitBranchToCounterBlock(CondBOp
->getRHS(), BO_LAnd
, TrueBlock
,
1888 FalseBlock
, TrueCount
, LH
);
1890 MCDCLogOpStack
.pop_back();
1894 if (CondBOp
->getOpcode() == BO_LOr
) {
1895 MCDCLogOpStack
.push_back(CondBOp
);
1897 // If we have "0 || X", simplify the code. "1 || X" would have constant
1898 // folded if the case was simple enough.
1899 bool ConstantBool
= false;
1900 if (ConstantFoldsToSimpleInteger(CondBOp
->getLHS(), ConstantBool
) &&
1902 // br(0 || X) -> br(X).
1903 incrementProfileCounter(CondBOp
);
1904 EmitBranchToCounterBlock(CondBOp
->getRHS(), BO_LOr
, TrueBlock
,
1905 FalseBlock
, TrueCount
, LH
);
1906 MCDCLogOpStack
.pop_back();
1910 // If we have "X || 0", simplify the code to use an uncond branch.
1911 // "X || 1" would have been constant folded to 1.
1912 if (ConstantFoldsToSimpleInteger(CondBOp
->getRHS(), ConstantBool
) &&
1914 // br(X || 0) -> br(X).
1915 EmitBranchToCounterBlock(CondBOp
->getLHS(), BO_LOr
, TrueBlock
,
1916 FalseBlock
, TrueCount
, LH
, CondBOp
);
1917 MCDCLogOpStack
.pop_back();
1920 // Emit the LHS as a conditional. If the LHS conditional is true, we
1921 // want to jump to the TrueBlock.
1922 llvm::BasicBlock
*LHSFalse
= createBasicBlock("lor.lhs.false");
1923 // We have the count for entry to the RHS and for the whole expression
1924 // being true, so we can divy up True count between the short circuit and
1927 getCurrentProfileCount() - getProfileCount(CondBOp
->getRHS());
1928 uint64_t RHSCount
= TrueCount
- LHSCount
;
1930 ConditionalEvaluation
eval(*this);
1932 // Propagate the likelihood attribute like __builtin_expect
1933 // __builtin_expect(X || Y, 1) -> only Y is likely
1934 // __builtin_expect(X || Y, 0) -> both X and Y are unlikely
1935 ApplyDebugLocation
DL(*this, Cond
);
1936 EmitBranchOnBoolExpr(CondBOp
->getLHS(), TrueBlock
, LHSFalse
, LHSCount
,
1937 LH
== Stmt::LH_Likely
? Stmt::LH_None
: LH
);
1938 EmitBlock(LHSFalse
);
1941 incrementProfileCounter(CondBOp
);
1942 setCurrentProfileCount(getProfileCount(CondBOp
->getRHS()));
1944 // Any temporaries created here are conditional.
1946 EmitBranchToCounterBlock(CondBOp
->getRHS(), BO_LOr
, TrueBlock
, FalseBlock
,
1950 MCDCLogOpStack
.pop_back();
1955 if (const UnaryOperator
*CondUOp
= dyn_cast
<UnaryOperator
>(Cond
)) {
1956 // br(!x, t, f) -> br(x, f, t)
1957 // Avoid doing this optimization when instrumenting a condition for MC/DC.
1958 // LNot is taken as part of the condition for simplicity, and changing its
1959 // sense negatively impacts test vector tracking.
1960 bool MCDCCondition
= CGM
.getCodeGenOpts().hasProfileClangInstr() &&
1961 CGM
.getCodeGenOpts().MCDCCoverage
&&
1962 isInstrumentedCondition(Cond
);
1963 if (CondUOp
->getOpcode() == UO_LNot
&& !MCDCCondition
) {
1964 // Negate the count.
1965 uint64_t FalseCount
= getCurrentProfileCount() - TrueCount
;
1966 // The values of the enum are chosen to make this negation possible.
1967 LH
= static_cast<Stmt::Likelihood
>(-LH
);
1968 // Negate the condition and swap the destination blocks.
1969 return EmitBranchOnBoolExpr(CondUOp
->getSubExpr(), FalseBlock
, TrueBlock
,
1974 if (const ConditionalOperator
*CondOp
= dyn_cast
<ConditionalOperator
>(Cond
)) {
1975 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1976 llvm::BasicBlock
*LHSBlock
= createBasicBlock("cond.true");
1977 llvm::BasicBlock
*RHSBlock
= createBasicBlock("cond.false");
1979 // The ConditionalOperator itself has no likelihood information for its
1980 // true and false branches. This matches the behavior of __builtin_expect.
1981 ConditionalEvaluation
cond(*this);
1982 EmitBranchOnBoolExpr(CondOp
->getCond(), LHSBlock
, RHSBlock
,
1983 getProfileCount(CondOp
), Stmt::LH_None
);
1985 // When computing PGO branch weights, we only know the overall count for
1986 // the true block. This code is essentially doing tail duplication of the
1987 // naive code-gen, introducing new edges for which counts are not
1988 // available. Divide the counts proportionally between the LHS and RHS of
1989 // the conditional operator.
1990 uint64_t LHSScaledTrueCount
= 0;
1993 getProfileCount(CondOp
) / (double)getCurrentProfileCount();
1994 LHSScaledTrueCount
= TrueCount
* LHSRatio
;
1998 EmitBlock(LHSBlock
);
1999 incrementProfileCounter(CondOp
);
2001 ApplyDebugLocation
DL(*this, Cond
);
2002 EmitBranchOnBoolExpr(CondOp
->getLHS(), TrueBlock
, FalseBlock
,
2003 LHSScaledTrueCount
, LH
, CondOp
);
2008 EmitBlock(RHSBlock
);
2009 EmitBranchOnBoolExpr(CondOp
->getRHS(), TrueBlock
, FalseBlock
,
2010 TrueCount
- LHSScaledTrueCount
, LH
, CondOp
);
2016 if (const CXXThrowExpr
*Throw
= dyn_cast
<CXXThrowExpr
>(Cond
)) {
2017 // Conditional operator handling can give us a throw expression as a
2018 // condition for a case like:
2019 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
2021 // br(c, throw x, br(y, t, f))
2022 EmitCXXThrowExpr(Throw
, /*KeepInsertionPoint*/false);
2026 // Emit the code with the fully general case.
2029 ApplyDebugLocation
DL(*this, Cond
);
2030 CondV
= EvaluateExprAsBool(Cond
);
2033 // If not at the top of the logical operator nest, update MCDC temp with the
2034 // boolean result of the evaluated condition.
2035 if (!MCDCLogOpStack
.empty()) {
2036 const Expr
*MCDCBaseExpr
= Cond
;
2037 // When a nested ConditionalOperator (ternary) is encountered in a boolean
2038 // expression, MC/DC tracks the result of the ternary, and this is tied to
2039 // the ConditionalOperator expression and not the ternary's LHS or RHS. If
2040 // this is the case, the ConditionalOperator expression is passed through
2041 // the ConditionalOp parameter and then used as the MCDC base expression.
2043 MCDCBaseExpr
= ConditionalOp
;
2045 maybeUpdateMCDCCondBitmap(MCDCBaseExpr
, CondV
);
2048 llvm::MDNode
*Weights
= nullptr;
2049 llvm::MDNode
*Unpredictable
= nullptr;
2051 // If the branch has a condition wrapped by __builtin_unpredictable,
2052 // create metadata that specifies that the branch is unpredictable.
2053 // Don't bother if not optimizing because that metadata would not be used.
2054 auto *Call
= dyn_cast
<CallExpr
>(Cond
->IgnoreImpCasts());
2055 if (Call
&& CGM
.getCodeGenOpts().OptimizationLevel
!= 0) {
2056 auto *FD
= dyn_cast_or_null
<FunctionDecl
>(Call
->getCalleeDecl());
2057 if (FD
&& FD
->getBuiltinID() == Builtin::BI__builtin_unpredictable
) {
2058 llvm::MDBuilder
MDHelper(getLLVMContext());
2059 Unpredictable
= MDHelper
.createUnpredictable();
2063 // If there is a Likelihood knowledge for the cond, lower it.
2064 // Note that if not optimizing this won't emit anything.
2065 llvm::Value
*NewCondV
= emitCondLikelihoodViaExpectIntrinsic(CondV
, LH
);
2066 if (CondV
!= NewCondV
)
2069 // Otherwise, lower profile counts. Note that we do this even at -O0.
2070 uint64_t CurrentCount
= std::max(getCurrentProfileCount(), TrueCount
);
2071 Weights
= createProfileWeights(TrueCount
, CurrentCount
- TrueCount
);
2074 Builder
.CreateCondBr(CondV
, TrueBlock
, FalseBlock
, Weights
, Unpredictable
);
2077 /// ErrorUnsupported - Print out an error that codegen doesn't support the
2078 /// specified stmt yet.
2079 void CodeGenFunction::ErrorUnsupported(const Stmt
*S
, const char *Type
) {
2080 CGM
.ErrorUnsupported(S
, Type
);
2083 /// emitNonZeroVLAInit - Emit the "zero" initialization of a
2084 /// variable-length array whose elements have a non-zero bit-pattern.
2086 /// \param baseType the inner-most element type of the array
2087 /// \param src - a char* pointing to the bit-pattern for a single
2088 /// base element of the array
2089 /// \param sizeInChars - the total size of the VLA, in chars
2090 static void emitNonZeroVLAInit(CodeGenFunction
&CGF
, QualType baseType
,
2091 Address dest
, Address src
,
2092 llvm::Value
*sizeInChars
) {
2093 CGBuilderTy
&Builder
= CGF
.Builder
;
2095 CharUnits baseSize
= CGF
.getContext().getTypeSizeInChars(baseType
);
2096 llvm::Value
*baseSizeInChars
2097 = llvm::ConstantInt::get(CGF
.IntPtrTy
, baseSize
.getQuantity());
2099 Address begin
= dest
.withElementType(CGF
.Int8Ty
);
2100 llvm::Value
*end
= Builder
.CreateInBoundsGEP(begin
.getElementType(),
2101 begin
.emitRawPointer(CGF
),
2102 sizeInChars
, "vla.end");
2104 llvm::BasicBlock
*originBB
= CGF
.Builder
.GetInsertBlock();
2105 llvm::BasicBlock
*loopBB
= CGF
.createBasicBlock("vla-init.loop");
2106 llvm::BasicBlock
*contBB
= CGF
.createBasicBlock("vla-init.cont");
2108 // Make a loop over the VLA. C99 guarantees that the VLA element
2109 // count must be nonzero.
2110 CGF
.EmitBlock(loopBB
);
2112 llvm::PHINode
*cur
= Builder
.CreatePHI(begin
.getType(), 2, "vla.cur");
2113 cur
->addIncoming(begin
.emitRawPointer(CGF
), originBB
);
2115 CharUnits curAlign
=
2116 dest
.getAlignment().alignmentOfArrayElement(baseSize
);
2118 // memcpy the individual element bit-pattern.
2119 Builder
.CreateMemCpy(Address(cur
, CGF
.Int8Ty
, curAlign
), src
, baseSizeInChars
,
2120 /*volatile*/ false);
2122 // Go to the next element.
2124 Builder
.CreateInBoundsGEP(CGF
.Int8Ty
, cur
, baseSizeInChars
, "vla.next");
2126 // Leave if that's the end of the VLA.
2127 llvm::Value
*done
= Builder
.CreateICmpEQ(next
, end
, "vla-init.isdone");
2128 Builder
.CreateCondBr(done
, contBB
, loopBB
);
2129 cur
->addIncoming(next
, loopBB
);
2131 CGF
.EmitBlock(contBB
);
2135 CodeGenFunction::EmitNullInitialization(Address DestPtr
, QualType Ty
) {
2136 // Ignore empty classes in C++.
2137 if (getLangOpts().CPlusPlus
) {
2138 if (const RecordType
*RT
= Ty
->getAs
<RecordType
>()) {
2139 if (cast
<CXXRecordDecl
>(RT
->getDecl())->isEmpty())
2144 if (DestPtr
.getElementType() != Int8Ty
)
2145 DestPtr
= DestPtr
.withElementType(Int8Ty
);
2147 // Get size and alignment info for this aggregate.
2148 CharUnits size
= getContext().getTypeSizeInChars(Ty
);
2150 llvm::Value
*SizeVal
;
2151 const VariableArrayType
*vla
;
2153 // Don't bother emitting a zero-byte memset.
2154 if (size
.isZero()) {
2155 // But note that getTypeInfo returns 0 for a VLA.
2156 if (const VariableArrayType
*vlaType
=
2157 dyn_cast_or_null
<VariableArrayType
>(
2158 getContext().getAsArrayType(Ty
))) {
2159 auto VlaSize
= getVLASize(vlaType
);
2160 SizeVal
= VlaSize
.NumElts
;
2161 CharUnits eltSize
= getContext().getTypeSizeInChars(VlaSize
.Type
);
2162 if (!eltSize
.isOne())
2163 SizeVal
= Builder
.CreateNUWMul(SizeVal
, CGM
.getSize(eltSize
));
2169 SizeVal
= CGM
.getSize(size
);
2173 // If the type contains a pointer to data member we can't memset it to zero.
2174 // Instead, create a null constant and copy it to the destination.
2175 // TODO: there are other patterns besides zero that we can usefully memset,
2176 // like -1, which happens to be the pattern used by member-pointers.
2177 if (!CGM
.getTypes().isZeroInitializable(Ty
)) {
2178 // For a VLA, emit a single element, then splat that over the VLA.
2179 if (vla
) Ty
= getContext().getBaseElementType(vla
);
2181 llvm::Constant
*NullConstant
= CGM
.EmitNullConstant(Ty
);
2183 llvm::GlobalVariable
*NullVariable
=
2184 new llvm::GlobalVariable(CGM
.getModule(), NullConstant
->getType(),
2185 /*isConstant=*/true,
2186 llvm::GlobalVariable::PrivateLinkage
,
2187 NullConstant
, Twine());
2188 CharUnits NullAlign
= DestPtr
.getAlignment();
2189 NullVariable
->setAlignment(NullAlign
.getAsAlign());
2190 Address
SrcPtr(NullVariable
, Builder
.getInt8Ty(), NullAlign
);
2192 if (vla
) return emitNonZeroVLAInit(*this, Ty
, DestPtr
, SrcPtr
, SizeVal
);
2194 // Get and call the appropriate llvm.memcpy overload.
2195 Builder
.CreateMemCpy(DestPtr
, SrcPtr
, SizeVal
, false);
2199 // Otherwise, just memset the whole thing to zero. This is legal
2200 // because in LLVM, all default initializers (other than the ones we just
2201 // handled above) are guaranteed to have a bit pattern of all zeros.
2202 Builder
.CreateMemSet(DestPtr
, Builder
.getInt8(0), SizeVal
, false);
2205 llvm::BlockAddress
*CodeGenFunction::GetAddrOfLabel(const LabelDecl
*L
) {
2206 // Make sure that there is a block for the indirect goto.
2207 if (!IndirectBranch
)
2208 GetIndirectGotoBlock();
2210 llvm::BasicBlock
*BB
= getJumpDestForLabel(L
).getBlock();
2212 // Make sure the indirect branch includes all of the address-taken blocks.
2213 IndirectBranch
->addDestination(BB
);
2214 return llvm::BlockAddress::get(CurFn
, BB
);
2217 llvm::BasicBlock
*CodeGenFunction::GetIndirectGotoBlock() {
2218 // If we already made the indirect branch for indirect goto, return its block.
2219 if (IndirectBranch
) return IndirectBranch
->getParent();
2221 CGBuilderTy
TmpBuilder(*this, createBasicBlock("indirectgoto"));
2223 // Create the PHI node that indirect gotos will add entries to.
2224 llvm::Value
*DestVal
= TmpBuilder
.CreatePHI(Int8PtrTy
, 0,
2225 "indirect.goto.dest");
2227 // Create the indirect branch instruction.
2228 IndirectBranch
= TmpBuilder
.CreateIndirectBr(DestVal
);
2229 return IndirectBranch
->getParent();
2232 /// Computes the length of an array in elements, as well as the base
2233 /// element type and a properly-typed first element pointer.
2234 llvm::Value
*CodeGenFunction::emitArrayLength(const ArrayType
*origArrayType
,
2237 const ArrayType
*arrayType
= origArrayType
;
2239 // If it's a VLA, we have to load the stored size. Note that
2240 // this is the size of the VLA in bytes, not its size in elements.
2241 llvm::Value
*numVLAElements
= nullptr;
2242 if (isa
<VariableArrayType
>(arrayType
)) {
2243 numVLAElements
= getVLASize(cast
<VariableArrayType
>(arrayType
)).NumElts
;
2245 // Walk into all VLAs. This doesn't require changes to addr,
2246 // which has type T* where T is the first non-VLA element type.
2248 QualType elementType
= arrayType
->getElementType();
2249 arrayType
= getContext().getAsArrayType(elementType
);
2251 // If we only have VLA components, 'addr' requires no adjustment.
2253 baseType
= elementType
;
2254 return numVLAElements
;
2256 } while (isa
<VariableArrayType
>(arrayType
));
2258 // We get out here only if we find a constant array type
2262 // We have some number of constant-length arrays, so addr should
2263 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
2264 // down to the first element of addr.
2265 SmallVector
<llvm::Value
*, 8> gepIndices
;
2267 // GEP down to the array type.
2268 llvm::ConstantInt
*zero
= Builder
.getInt32(0);
2269 gepIndices
.push_back(zero
);
2271 uint64_t countFromCLAs
= 1;
2274 llvm::ArrayType
*llvmArrayType
=
2275 dyn_cast
<llvm::ArrayType
>(addr
.getElementType());
2276 while (llvmArrayType
) {
2277 assert(isa
<ConstantArrayType
>(arrayType
));
2278 assert(cast
<ConstantArrayType
>(arrayType
)->getZExtSize() ==
2279 llvmArrayType
->getNumElements());
2281 gepIndices
.push_back(zero
);
2282 countFromCLAs
*= llvmArrayType
->getNumElements();
2283 eltType
= arrayType
->getElementType();
2286 dyn_cast
<llvm::ArrayType
>(llvmArrayType
->getElementType());
2287 arrayType
= getContext().getAsArrayType(arrayType
->getElementType());
2288 assert((!llvmArrayType
|| arrayType
) &&
2289 "LLVM and Clang types are out-of-synch");
2293 // From this point onwards, the Clang array type has been emitted
2294 // as some other type (probably a packed struct). Compute the array
2295 // size, and just emit the 'begin' expression as a bitcast.
2297 countFromCLAs
*= cast
<ConstantArrayType
>(arrayType
)->getZExtSize();
2298 eltType
= arrayType
->getElementType();
2299 arrayType
= getContext().getAsArrayType(eltType
);
2302 llvm::Type
*baseType
= ConvertType(eltType
);
2303 addr
= addr
.withElementType(baseType
);
2305 // Create the actual GEP.
2306 addr
= Address(Builder
.CreateInBoundsGEP(addr
.getElementType(),
2307 addr
.emitRawPointer(*this),
2308 gepIndices
, "array.begin"),
2309 ConvertTypeForMem(eltType
), addr
.getAlignment());
2314 llvm::Value
*numElements
2315 = llvm::ConstantInt::get(SizeTy
, countFromCLAs
);
2317 // If we had any VLA dimensions, factor them in.
2319 numElements
= Builder
.CreateNUWMul(numVLAElements
, numElements
);
2324 CodeGenFunction::VlaSizePair
CodeGenFunction::getVLASize(QualType type
) {
2325 const VariableArrayType
*vla
= getContext().getAsVariableArrayType(type
);
2326 assert(vla
&& "type was not a variable array type!");
2327 return getVLASize(vla
);
2330 CodeGenFunction::VlaSizePair
2331 CodeGenFunction::getVLASize(const VariableArrayType
*type
) {
2332 // The number of elements so far; always size_t.
2333 llvm::Value
*numElements
= nullptr;
2335 QualType elementType
;
2337 elementType
= type
->getElementType();
2338 llvm::Value
*vlaSize
= VLASizeMap
[type
->getSizeExpr()];
2339 assert(vlaSize
&& "no size for VLA!");
2340 assert(vlaSize
->getType() == SizeTy
);
2343 numElements
= vlaSize
;
2345 // It's undefined behavior if this wraps around, so mark it that way.
2346 // FIXME: Teach -fsanitize=undefined to trap this.
2347 numElements
= Builder
.CreateNUWMul(numElements
, vlaSize
);
2349 } while ((type
= getContext().getAsVariableArrayType(elementType
)));
2351 return { numElements
, elementType
};
2354 CodeGenFunction::VlaSizePair
2355 CodeGenFunction::getVLAElements1D(QualType type
) {
2356 const VariableArrayType
*vla
= getContext().getAsVariableArrayType(type
);
2357 assert(vla
&& "type was not a variable array type!");
2358 return getVLAElements1D(vla
);
2361 CodeGenFunction::VlaSizePair
2362 CodeGenFunction::getVLAElements1D(const VariableArrayType
*Vla
) {
2363 llvm::Value
*VlaSize
= VLASizeMap
[Vla
->getSizeExpr()];
2364 assert(VlaSize
&& "no size for VLA!");
2365 assert(VlaSize
->getType() == SizeTy
);
2366 return { VlaSize
, Vla
->getElementType() };
2369 void CodeGenFunction::EmitVariablyModifiedType(QualType type
) {
2370 assert(type
->isVariablyModifiedType() &&
2371 "Must pass variably modified type to EmitVLASizes!");
2373 EnsureInsertPoint();
2375 // We're going to walk down into the type and look for VLA
2378 assert(type
->isVariablyModifiedType());
2380 const Type
*ty
= type
.getTypePtr();
2381 switch (ty
->getTypeClass()) {
2383 #define TYPE(Class, Base)
2384 #define ABSTRACT_TYPE(Class, Base)
2385 #define NON_CANONICAL_TYPE(Class, Base)
2386 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2387 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
2388 #include "clang/AST/TypeNodes.inc"
2389 llvm_unreachable("unexpected dependent type!");
2391 // These types are never variably-modified.
2395 case Type::ExtVector
:
2396 case Type::ConstantMatrix
:
2400 case Type::TemplateSpecialization
:
2401 case Type::ObjCTypeParam
:
2402 case Type::ObjCObject
:
2403 case Type::ObjCInterface
:
2404 case Type::ObjCObjectPointer
:
2406 llvm_unreachable("type class is never variably-modified!");
2408 case Type::Elaborated
:
2409 type
= cast
<ElaboratedType
>(ty
)->getNamedType();
2412 case Type::Adjusted
:
2413 type
= cast
<AdjustedType
>(ty
)->getAdjustedType();
2417 type
= cast
<DecayedType
>(ty
)->getPointeeType();
2421 type
= cast
<PointerType
>(ty
)->getPointeeType();
2424 case Type::BlockPointer
:
2425 type
= cast
<BlockPointerType
>(ty
)->getPointeeType();
2428 case Type::LValueReference
:
2429 case Type::RValueReference
:
2430 type
= cast
<ReferenceType
>(ty
)->getPointeeType();
2433 case Type::MemberPointer
:
2434 type
= cast
<MemberPointerType
>(ty
)->getPointeeType();
2437 case Type::ArrayParameter
:
2438 case Type::ConstantArray
:
2439 case Type::IncompleteArray
:
2440 // Losing element qualification here is fine.
2441 type
= cast
<ArrayType
>(ty
)->getElementType();
2444 case Type::VariableArray
: {
2445 // Losing element qualification here is fine.
2446 const VariableArrayType
*vat
= cast
<VariableArrayType
>(ty
);
2448 // Unknown size indication requires no size computation.
2449 // Otherwise, evaluate and record it.
2450 if (const Expr
*sizeExpr
= vat
->getSizeExpr()) {
2451 // It's possible that we might have emitted this already,
2452 // e.g. with a typedef and a pointer to it.
2453 llvm::Value
*&entry
= VLASizeMap
[sizeExpr
];
2455 llvm::Value
*size
= EmitScalarExpr(sizeExpr
);
2458 // If the size is an expression that is not an integer constant
2459 // expression [...] each time it is evaluated it shall have a value
2460 // greater than zero.
2461 if (SanOpts
.has(SanitizerKind::VLABound
)) {
2462 SanitizerScope
SanScope(this);
2463 llvm::Value
*Zero
= llvm::Constant::getNullValue(size
->getType());
2464 clang::QualType SEType
= sizeExpr
->getType();
2465 llvm::Value
*CheckCondition
=
2466 SEType
->isSignedIntegerType()
2467 ? Builder
.CreateICmpSGT(size
, Zero
)
2468 : Builder
.CreateICmpUGT(size
, Zero
);
2469 llvm::Constant
*StaticArgs
[] = {
2470 EmitCheckSourceLocation(sizeExpr
->getBeginLoc()),
2471 EmitCheckTypeDescriptor(SEType
)};
2472 EmitCheck(std::make_pair(CheckCondition
, SanitizerKind::VLABound
),
2473 SanitizerHandler::VLABoundNotPositive
, StaticArgs
, size
);
2476 // Always zexting here would be wrong if it weren't
2477 // undefined behavior to have a negative bound.
2478 // FIXME: What about when size's type is larger than size_t?
2479 entry
= Builder
.CreateIntCast(size
, SizeTy
, /*signed*/ false);
2482 type
= vat
->getElementType();
2486 case Type::FunctionProto
:
2487 case Type::FunctionNoProto
:
2488 type
= cast
<FunctionType
>(ty
)->getReturnType();
2493 case Type::UnaryTransform
:
2494 case Type::Attributed
:
2495 case Type::BTFTagAttributed
:
2496 case Type::HLSLAttributedResource
:
2497 case Type::SubstTemplateTypeParm
:
2498 case Type::MacroQualified
:
2499 case Type::CountAttributed
:
2500 // Keep walking after single level desugaring.
2501 type
= type
.getSingleStepDesugaredType(getContext());
2505 case Type::Decltype
:
2507 case Type::DeducedTemplateSpecialization
:
2508 case Type::PackIndexing
:
2509 // Stop walking: nothing to do.
2512 case Type::TypeOfExpr
:
2513 // Stop walking: emit typeof expression.
2514 EmitIgnoredExpr(cast
<TypeOfExprType
>(ty
)->getUnderlyingExpr());
2518 type
= cast
<AtomicType
>(ty
)->getValueType();
2522 type
= cast
<PipeType
>(ty
)->getElementType();
2525 } while (type
->isVariablyModifiedType());
2528 Address
CodeGenFunction::EmitVAListRef(const Expr
* E
) {
2529 if (getContext().getBuiltinVaListType()->isArrayType())
2530 return EmitPointerWithAlignment(E
);
2531 return EmitLValue(E
).getAddress();
2534 Address
CodeGenFunction::EmitMSVAListRef(const Expr
*E
) {
2535 return EmitLValue(E
).getAddress();
2538 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr
*E
,
2539 const APValue
&Init
) {
2540 assert(Init
.hasValue() && "Invalid DeclRefExpr initializer!");
2541 if (CGDebugInfo
*Dbg
= getDebugInfo())
2542 if (CGM
.getCodeGenOpts().hasReducedDebugInfo())
2543 Dbg
->EmitGlobalVariable(E
->getDecl(), Init
);
2546 CodeGenFunction::PeepholeProtection
2547 CodeGenFunction::protectFromPeepholes(RValue rvalue
) {
2548 // At the moment, the only aggressive peephole we do in IR gen
2549 // is trunc(zext) folding, but if we add more, we can easily
2550 // extend this protection.
2552 if (!rvalue
.isScalar()) return PeepholeProtection();
2553 llvm::Value
*value
= rvalue
.getScalarVal();
2554 if (!isa
<llvm::ZExtInst
>(value
)) return PeepholeProtection();
2556 // Just make an extra bitcast.
2557 assert(HaveInsertPoint());
2558 llvm::Instruction
*inst
= new llvm::BitCastInst(value
, value
->getType(), "",
2559 Builder
.GetInsertBlock());
2561 PeepholeProtection protection
;
2562 protection
.Inst
= inst
;
2566 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection
) {
2567 if (!protection
.Inst
) return;
2569 // In theory, we could try to duplicate the peepholes now, but whatever.
2570 protection
.Inst
->eraseFromParent();
2573 void CodeGenFunction::emitAlignmentAssumption(llvm::Value
*PtrValue
,
2574 QualType Ty
, SourceLocation Loc
,
2575 SourceLocation AssumptionLoc
,
2576 llvm::Value
*Alignment
,
2577 llvm::Value
*OffsetValue
) {
2578 if (Alignment
->getType() != IntPtrTy
)
2580 Builder
.CreateIntCast(Alignment
, IntPtrTy
, false, "casted.align");
2581 if (OffsetValue
&& OffsetValue
->getType() != IntPtrTy
)
2583 Builder
.CreateIntCast(OffsetValue
, IntPtrTy
, true, "casted.offset");
2584 llvm::Value
*TheCheck
= nullptr;
2585 if (SanOpts
.has(SanitizerKind::Alignment
)) {
2586 llvm::Value
*PtrIntValue
=
2587 Builder
.CreatePtrToInt(PtrValue
, IntPtrTy
, "ptrint");
2590 bool IsOffsetZero
= false;
2591 if (const auto *CI
= dyn_cast
<llvm::ConstantInt
>(OffsetValue
))
2592 IsOffsetZero
= CI
->isZero();
2595 PtrIntValue
= Builder
.CreateSub(PtrIntValue
, OffsetValue
, "offsetptr");
2598 llvm::Value
*Zero
= llvm::ConstantInt::get(IntPtrTy
, 0);
2600 Builder
.CreateSub(Alignment
, llvm::ConstantInt::get(IntPtrTy
, 1));
2601 llvm::Value
*MaskedPtr
= Builder
.CreateAnd(PtrIntValue
, Mask
, "maskedptr");
2602 TheCheck
= Builder
.CreateICmpEQ(MaskedPtr
, Zero
, "maskcond");
2604 llvm::Instruction
*Assumption
= Builder
.CreateAlignmentAssumption(
2605 CGM
.getDataLayout(), PtrValue
, Alignment
, OffsetValue
);
2607 if (!SanOpts
.has(SanitizerKind::Alignment
))
2609 emitAlignmentAssumptionCheck(PtrValue
, Ty
, Loc
, AssumptionLoc
, Alignment
,
2610 OffsetValue
, TheCheck
, Assumption
);
2613 void CodeGenFunction::emitAlignmentAssumption(llvm::Value
*PtrValue
,
2615 SourceLocation AssumptionLoc
,
2616 llvm::Value
*Alignment
,
2617 llvm::Value
*OffsetValue
) {
2618 QualType Ty
= E
->getType();
2619 SourceLocation Loc
= E
->getExprLoc();
2621 emitAlignmentAssumption(PtrValue
, Ty
, Loc
, AssumptionLoc
, Alignment
,
2625 llvm::Value
*CodeGenFunction::EmitAnnotationCall(llvm::Function
*AnnotationFn
,
2626 llvm::Value
*AnnotatedVal
,
2627 StringRef AnnotationStr
,
2628 SourceLocation Location
,
2629 const AnnotateAttr
*Attr
) {
2630 SmallVector
<llvm::Value
*, 5> Args
= {
2632 CGM
.EmitAnnotationString(AnnotationStr
),
2633 CGM
.EmitAnnotationUnit(Location
),
2634 CGM
.EmitAnnotationLineNo(Location
),
2637 Args
.push_back(CGM
.EmitAnnotationArgs(Attr
));
2638 return Builder
.CreateCall(AnnotationFn
, Args
);
2641 void CodeGenFunction::EmitVarAnnotations(const VarDecl
*D
, llvm::Value
*V
) {
2642 assert(D
->hasAttr
<AnnotateAttr
>() && "no annotate attribute");
2643 for (const auto *I
: D
->specific_attrs
<AnnotateAttr
>())
2644 EmitAnnotationCall(CGM
.getIntrinsic(llvm::Intrinsic::var_annotation
,
2645 {V
->getType(), CGM
.ConstGlobalsPtrTy
}),
2646 V
, I
->getAnnotation(), D
->getLocation(), I
);
2649 Address
CodeGenFunction::EmitFieldAnnotations(const FieldDecl
*D
,
2651 assert(D
->hasAttr
<AnnotateAttr
>() && "no annotate attribute");
2652 llvm::Value
*V
= Addr
.emitRawPointer(*this);
2653 llvm::Type
*VTy
= V
->getType();
2654 auto *PTy
= dyn_cast
<llvm::PointerType
>(VTy
);
2655 unsigned AS
= PTy
? PTy
->getAddressSpace() : 0;
2656 llvm::PointerType
*IntrinTy
=
2657 llvm::PointerType::get(CGM
.getLLVMContext(), AS
);
2658 llvm::Function
*F
= CGM
.getIntrinsic(llvm::Intrinsic::ptr_annotation
,
2659 {IntrinTy
, CGM
.ConstGlobalsPtrTy
});
2661 for (const auto *I
: D
->specific_attrs
<AnnotateAttr
>()) {
2662 // FIXME Always emit the cast inst so we can differentiate between
2663 // annotation on the first field of a struct and annotation on the struct
2665 if (VTy
!= IntrinTy
)
2666 V
= Builder
.CreateBitCast(V
, IntrinTy
);
2667 V
= EmitAnnotationCall(F
, V
, I
->getAnnotation(), D
->getLocation(), I
);
2668 V
= Builder
.CreateBitCast(V
, VTy
);
2671 return Address(V
, Addr
.getElementType(), Addr
.getAlignment());
2674 CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
2676 CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction
*CGF
)
2678 assert(!CGF
->IsSanitizerScope
);
2679 CGF
->IsSanitizerScope
= true;
2682 CodeGenFunction::SanitizerScope::~SanitizerScope() {
2683 CGF
->IsSanitizerScope
= false;
2686 void CodeGenFunction::InsertHelper(llvm::Instruction
*I
,
2687 const llvm::Twine
&Name
,
2688 llvm::BasicBlock::iterator InsertPt
) const {
2689 LoopStack
.InsertHelper(I
);
2690 if (IsSanitizerScope
)
2691 I
->setNoSanitizeMetadata();
2694 void CGBuilderInserter::InsertHelper(
2695 llvm::Instruction
*I
, const llvm::Twine
&Name
,
2696 llvm::BasicBlock::iterator InsertPt
) const {
2697 llvm::IRBuilderDefaultInserter::InsertHelper(I
, Name
, InsertPt
);
2699 CGF
->InsertHelper(I
, Name
, InsertPt
);
2702 // Emits an error if we don't have a valid set of target features for the
2704 void CodeGenFunction::checkTargetFeatures(const CallExpr
*E
,
2705 const FunctionDecl
*TargetDecl
) {
2706 // SemaChecking cannot handle below x86 builtins because they have different
2707 // parameter ranges with different TargetAttribute of caller.
2708 if (CGM
.getContext().getTargetInfo().getTriple().isX86()) {
2709 unsigned BuiltinID
= TargetDecl
->getBuiltinID();
2710 if (BuiltinID
== X86::BI__builtin_ia32_cmpps
||
2711 BuiltinID
== X86::BI__builtin_ia32_cmpss
||
2712 BuiltinID
== X86::BI__builtin_ia32_cmppd
||
2713 BuiltinID
== X86::BI__builtin_ia32_cmpsd
) {
2714 const FunctionDecl
*FD
= dyn_cast_or_null
<FunctionDecl
>(CurCodeDecl
);
2715 llvm::StringMap
<bool> TargetFetureMap
;
2716 CGM
.getContext().getFunctionFeatureMap(TargetFetureMap
, FD
);
2717 llvm::APSInt Result
=
2718 *(E
->getArg(2)->getIntegerConstantExpr(CGM
.getContext()));
2719 if (Result
.getSExtValue() > 7 && !TargetFetureMap
.lookup("avx"))
2720 CGM
.getDiags().Report(E
->getBeginLoc(), diag::err_builtin_needs_feature
)
2721 << TargetDecl
->getDeclName() << "avx";
2724 return checkTargetFeatures(E
->getBeginLoc(), TargetDecl
);
2727 // Emits an error if we don't have a valid set of target features for the
2729 void CodeGenFunction::checkTargetFeatures(SourceLocation Loc
,
2730 const FunctionDecl
*TargetDecl
) {
2731 // Early exit if this is an indirect call.
2735 // Get the current enclosing function if it exists. If it doesn't
2736 // we can't check the target features anyhow.
2737 const FunctionDecl
*FD
= dyn_cast_or_null
<FunctionDecl
>(CurCodeDecl
);
2741 // Grab the required features for the call. For a builtin this is listed in
2742 // the td file with the default cpu, for an always_inline function this is any
2743 // listed cpu and any listed features.
2744 unsigned BuiltinID
= TargetDecl
->getBuiltinID();
2745 std::string MissingFeature
;
2746 llvm::StringMap
<bool> CallerFeatureMap
;
2747 CGM
.getContext().getFunctionFeatureMap(CallerFeatureMap
, FD
);
2748 // When compiling in HipStdPar mode we have to be conservative in rejecting
2749 // target specific features in the FE, and defer the possible error to the
2750 // AcceleratorCodeSelection pass, wherein iff an unsupported target builtin is
2751 // referenced by an accelerator executable function, we emit an error.
2752 bool IsHipStdPar
= getLangOpts().HIPStdPar
&& getLangOpts().CUDAIsDevice
;
2754 StringRef
FeatureList(CGM
.getContext().BuiltinInfo
.getRequiredFeatures(BuiltinID
));
2755 if (!Builtin::evaluateRequiredTargetFeatures(
2756 FeatureList
, CallerFeatureMap
) && !IsHipStdPar
) {
2757 CGM
.getDiags().Report(Loc
, diag::err_builtin_needs_feature
)
2758 << TargetDecl
->getDeclName()
2761 } else if (!TargetDecl
->isMultiVersion() &&
2762 TargetDecl
->hasAttr
<TargetAttr
>()) {
2763 // Get the required features for the callee.
2765 const TargetAttr
*TD
= TargetDecl
->getAttr
<TargetAttr
>();
2766 ParsedTargetAttr ParsedAttr
=
2767 CGM
.getContext().filterFunctionTargetAttrs(TD
);
2769 SmallVector
<StringRef
, 1> ReqFeatures
;
2770 llvm::StringMap
<bool> CalleeFeatureMap
;
2771 CGM
.getContext().getFunctionFeatureMap(CalleeFeatureMap
, TargetDecl
);
2773 for (const auto &F
: ParsedAttr
.Features
) {
2774 if (F
[0] == '+' && CalleeFeatureMap
.lookup(F
.substr(1)))
2775 ReqFeatures
.push_back(StringRef(F
).substr(1));
2778 for (const auto &F
: CalleeFeatureMap
) {
2779 // Only positive features are "required".
2781 ReqFeatures
.push_back(F
.getKey());
2783 if (!llvm::all_of(ReqFeatures
, [&](StringRef Feature
) {
2784 if (!CallerFeatureMap
.lookup(Feature
)) {
2785 MissingFeature
= Feature
.str();
2790 CGM
.getDiags().Report(Loc
, diag::err_function_needs_feature
)
2791 << FD
->getDeclName() << TargetDecl
->getDeclName() << MissingFeature
;
2792 } else if (!FD
->isMultiVersion() && FD
->hasAttr
<TargetAttr
>()) {
2793 llvm::StringMap
<bool> CalleeFeatureMap
;
2794 CGM
.getContext().getFunctionFeatureMap(CalleeFeatureMap
, TargetDecl
);
2796 for (const auto &F
: CalleeFeatureMap
) {
2797 if (F
.getValue() && (!CallerFeatureMap
.lookup(F
.getKey()) ||
2798 !CallerFeatureMap
.find(F
.getKey())->getValue()) &&
2800 CGM
.getDiags().Report(Loc
, diag::err_function_needs_feature
)
2801 << FD
->getDeclName() << TargetDecl
->getDeclName() << F
.getKey();
2806 void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK
) {
2807 if (!CGM
.getCodeGenOpts().SanitizeStats
)
2810 llvm::IRBuilder
<> IRB(Builder
.GetInsertBlock(), Builder
.GetInsertPoint());
2811 IRB
.SetCurrentDebugLocation(Builder
.getCurrentDebugLocation());
2812 CGM
.getSanStats().create(IRB
, SSK
);
2815 void CodeGenFunction::EmitKCFIOperandBundle(
2816 const CGCallee
&Callee
, SmallVectorImpl
<llvm::OperandBundleDef
> &Bundles
) {
2817 const FunctionProtoType
*FP
=
2818 Callee
.getAbstractInfo().getCalleeFunctionProtoType();
2820 Bundles
.emplace_back("kcfi", CGM
.CreateKCFITypeId(FP
->desugar()));
2823 llvm::Value
*CodeGenFunction::FormAArch64ResolverCondition(
2824 const MultiVersionResolverOption
&RO
) {
2825 llvm::SmallVector
<StringRef
, 8> CondFeatures
;
2826 for (const StringRef
&Feature
: RO
.Conditions
.Features
)
2827 CondFeatures
.push_back(Feature
);
2828 if (!CondFeatures
.empty()) {
2829 return EmitAArch64CpuSupports(CondFeatures
);
2834 llvm::Value
*CodeGenFunction::FormX86ResolverCondition(
2835 const MultiVersionResolverOption
&RO
) {
2836 llvm::Value
*Condition
= nullptr;
2838 if (!RO
.Conditions
.Architecture
.empty()) {
2839 StringRef Arch
= RO
.Conditions
.Architecture
;
2840 // If arch= specifies an x86-64 micro-architecture level, test the feature
2841 // with __builtin_cpu_supports, otherwise use __builtin_cpu_is.
2842 if (Arch
.starts_with("x86-64"))
2843 Condition
= EmitX86CpuSupports({Arch
});
2845 Condition
= EmitX86CpuIs(Arch
);
2848 if (!RO
.Conditions
.Features
.empty()) {
2849 llvm::Value
*FeatureCond
= EmitX86CpuSupports(RO
.Conditions
.Features
);
2851 Condition
? Builder
.CreateAnd(Condition
, FeatureCond
) : FeatureCond
;
2856 static void CreateMultiVersionResolverReturn(CodeGenModule
&CGM
,
2857 llvm::Function
*Resolver
,
2858 CGBuilderTy
&Builder
,
2859 llvm::Function
*FuncToReturn
,
2860 bool SupportsIFunc
) {
2861 if (SupportsIFunc
) {
2862 Builder
.CreateRet(FuncToReturn
);
2866 llvm::SmallVector
<llvm::Value
*, 10> Args(
2867 llvm::make_pointer_range(Resolver
->args()));
2869 llvm::CallInst
*Result
= Builder
.CreateCall(FuncToReturn
, Args
);
2870 Result
->setTailCallKind(llvm::CallInst::TCK_MustTail
);
2872 if (Resolver
->getReturnType()->isVoidTy())
2873 Builder
.CreateRetVoid();
2875 Builder
.CreateRet(Result
);
2878 void CodeGenFunction::EmitMultiVersionResolver(
2879 llvm::Function
*Resolver
, ArrayRef
<MultiVersionResolverOption
> Options
) {
2881 llvm::Triple::ArchType ArchType
=
2882 getContext().getTargetInfo().getTriple().getArch();
2885 case llvm::Triple::x86
:
2886 case llvm::Triple::x86_64
:
2887 EmitX86MultiVersionResolver(Resolver
, Options
);
2889 case llvm::Triple::aarch64
:
2890 EmitAArch64MultiVersionResolver(Resolver
, Options
);
2892 case llvm::Triple::riscv32
:
2893 case llvm::Triple::riscv64
:
2894 EmitRISCVMultiVersionResolver(Resolver
, Options
);
2898 assert(false && "Only implemented for x86, AArch64 and RISC-V targets");
2902 static int getPriorityFromAttrString(StringRef AttrStr
) {
2903 SmallVector
<StringRef
, 8> Attrs
;
2905 AttrStr
.split(Attrs
, ';');
2907 // Default Priority is zero.
2909 for (auto Attr
: Attrs
) {
2910 if (Attr
.consume_front("priority=")) {
2912 if (!Attr
.getAsInteger(0, Result
)) {
2921 void CodeGenFunction::EmitRISCVMultiVersionResolver(
2922 llvm::Function
*Resolver
, ArrayRef
<MultiVersionResolverOption
> Options
) {
2924 if (getContext().getTargetInfo().getTriple().getOS() !=
2925 llvm::Triple::OSType::Linux
) {
2926 CGM
.getDiags().Report(diag::err_os_unsupport_riscv_fmv
);
2930 llvm::BasicBlock
*CurBlock
= createBasicBlock("resolver_entry", Resolver
);
2931 Builder
.SetInsertPoint(CurBlock
);
2934 bool SupportsIFunc
= getContext().getTargetInfo().supportsIFunc();
2935 bool HasDefault
= false;
2936 unsigned DefaultIndex
= 0;
2938 SmallVector
<CodeGenFunction::MultiVersionResolverOption
, 10> CurrOptions(
2942 CurrOptions
, [](const CodeGenFunction::MultiVersionResolverOption
&LHS
,
2943 const CodeGenFunction::MultiVersionResolverOption
&RHS
) {
2944 return getPriorityFromAttrString(LHS
.Conditions
.Features
[0]) >
2945 getPriorityFromAttrString(RHS
.Conditions
.Features
[0]);
2948 // Check the each candidate function.
2949 for (unsigned Index
= 0; Index
< CurrOptions
.size(); Index
++) {
2951 if (CurrOptions
[Index
].Conditions
.Features
[0].starts_with("default")) {
2953 DefaultIndex
= Index
;
2957 Builder
.SetInsertPoint(CurBlock
);
2959 std::vector
<std::string
> TargetAttrFeats
=
2962 .parseTargetAttr(CurrOptions
[Index
].Conditions
.Features
[0])
2965 if (TargetAttrFeats
.empty())
2968 // FeaturesCondition: The bitmask of the required extension has been
2969 // enabled by the runtime object.
2970 // (__riscv_feature_bits.features[i] & REQUIRED_BITMASK) ==
2973 // When condition is met, return this version of the function.
2974 // Otherwise, try the next version.
2976 // if (FeaturesConditionVersion1)
2978 // else if (FeaturesConditionVersion2)
2980 // else if (FeaturesConditionVersion3)
2984 // return DefaultVersion;
2986 // TODO: Add a condition to check the length before accessing elements.
2987 // Without checking the length first, we may access an incorrect memory
2988 // address when using different versions.
2989 llvm::SmallVector
<StringRef
, 8> CurrTargetAttrFeats
;
2991 for (auto &Feat
: TargetAttrFeats
) {
2992 StringRef CurrFeat
= Feat
;
2993 if (CurrFeat
.starts_with('+'))
2994 CurrTargetAttrFeats
.push_back(CurrFeat
.substr(1));
2997 Builder
.SetInsertPoint(CurBlock
);
2998 llvm::Value
*FeatsCondition
= EmitRISCVCpuSupports(CurrTargetAttrFeats
);
3000 llvm::BasicBlock
*RetBlock
= createBasicBlock("resolver_return", Resolver
);
3001 CGBuilderTy
RetBuilder(*this, RetBlock
);
3002 CreateMultiVersionResolverReturn(
3003 CGM
, Resolver
, RetBuilder
, CurrOptions
[Index
].Function
, SupportsIFunc
);
3004 llvm::BasicBlock
*ElseBlock
= createBasicBlock("resolver_else", Resolver
);
3006 Builder
.SetInsertPoint(CurBlock
);
3007 Builder
.CreateCondBr(FeatsCondition
, RetBlock
, ElseBlock
);
3009 CurBlock
= ElseBlock
;
3012 // Finally, emit the default one.
3014 Builder
.SetInsertPoint(CurBlock
);
3015 CreateMultiVersionResolverReturn(CGM
, Resolver
, Builder
,
3016 CurrOptions
[DefaultIndex
].Function
,
3021 // If no generic/default, emit an unreachable.
3022 Builder
.SetInsertPoint(CurBlock
);
3023 llvm::CallInst
*TrapCall
= EmitTrapCall(llvm::Intrinsic::trap
);
3024 TrapCall
->setDoesNotReturn();
3025 TrapCall
->setDoesNotThrow();
3026 Builder
.CreateUnreachable();
3027 Builder
.ClearInsertionPoint();
3030 void CodeGenFunction::EmitAArch64MultiVersionResolver(
3031 llvm::Function
*Resolver
, ArrayRef
<MultiVersionResolverOption
> Options
) {
3032 assert(!Options
.empty() && "No multiversion resolver options found");
3033 assert(Options
.back().Conditions
.Features
.size() == 0 &&
3034 "Default case must be last");
3035 bool SupportsIFunc
= getContext().getTargetInfo().supportsIFunc();
3036 assert(SupportsIFunc
&&
3037 "Multiversion resolver requires target IFUNC support");
3038 bool AArch64CpuInitialized
= false;
3039 llvm::BasicBlock
*CurBlock
= createBasicBlock("resolver_entry", Resolver
);
3041 for (const MultiVersionResolverOption
&RO
: Options
) {
3042 Builder
.SetInsertPoint(CurBlock
);
3043 llvm::Value
*Condition
= FormAArch64ResolverCondition(RO
);
3045 // The 'default' or 'all features enabled' case.
3047 CreateMultiVersionResolverReturn(CGM
, Resolver
, Builder
, RO
.Function
,
3052 if (!AArch64CpuInitialized
) {
3053 Builder
.SetInsertPoint(CurBlock
, CurBlock
->begin());
3054 EmitAArch64CpuInit();
3055 AArch64CpuInitialized
= true;
3056 Builder
.SetInsertPoint(CurBlock
);
3059 llvm::BasicBlock
*RetBlock
= createBasicBlock("resolver_return", Resolver
);
3060 CGBuilderTy
RetBuilder(*this, RetBlock
);
3061 CreateMultiVersionResolverReturn(CGM
, Resolver
, RetBuilder
, RO
.Function
,
3063 CurBlock
= createBasicBlock("resolver_else", Resolver
);
3064 Builder
.CreateCondBr(Condition
, RetBlock
, CurBlock
);
3067 // If no default, emit an unreachable.
3068 Builder
.SetInsertPoint(CurBlock
);
3069 llvm::CallInst
*TrapCall
= EmitTrapCall(llvm::Intrinsic::trap
);
3070 TrapCall
->setDoesNotReturn();
3071 TrapCall
->setDoesNotThrow();
3072 Builder
.CreateUnreachable();
3073 Builder
.ClearInsertionPoint();
3076 void CodeGenFunction::EmitX86MultiVersionResolver(
3077 llvm::Function
*Resolver
, ArrayRef
<MultiVersionResolverOption
> Options
) {
3079 bool SupportsIFunc
= getContext().getTargetInfo().supportsIFunc();
3081 // Main function's basic block.
3082 llvm::BasicBlock
*CurBlock
= createBasicBlock("resolver_entry", Resolver
);
3083 Builder
.SetInsertPoint(CurBlock
);
3086 for (const MultiVersionResolverOption
&RO
: Options
) {
3087 Builder
.SetInsertPoint(CurBlock
);
3088 llvm::Value
*Condition
= FormX86ResolverCondition(RO
);
3090 // The 'default' or 'generic' case.
3092 assert(&RO
== Options
.end() - 1 &&
3093 "Default or Generic case must be last");
3094 CreateMultiVersionResolverReturn(CGM
, Resolver
, Builder
, RO
.Function
,
3099 llvm::BasicBlock
*RetBlock
= createBasicBlock("resolver_return", Resolver
);
3100 CGBuilderTy
RetBuilder(*this, RetBlock
);
3101 CreateMultiVersionResolverReturn(CGM
, Resolver
, RetBuilder
, RO
.Function
,
3103 CurBlock
= createBasicBlock("resolver_else", Resolver
);
3104 Builder
.CreateCondBr(Condition
, RetBlock
, CurBlock
);
3107 // If no generic/default, emit an unreachable.
3108 Builder
.SetInsertPoint(CurBlock
);
3109 llvm::CallInst
*TrapCall
= EmitTrapCall(llvm::Intrinsic::trap
);
3110 TrapCall
->setDoesNotReturn();
3111 TrapCall
->setDoesNotThrow();
3112 Builder
.CreateUnreachable();
3113 Builder
.ClearInsertionPoint();
3116 // Loc - where the diagnostic will point, where in the source code this
3117 // alignment has failed.
3118 // SecondaryLoc - if present (will be present if sufficiently different from
3119 // Loc), the diagnostic will additionally point a "Note:" to this location.
3120 // It should be the location where the __attribute__((assume_aligned))
3122 void CodeGenFunction::emitAlignmentAssumptionCheck(
3123 llvm::Value
*Ptr
, QualType Ty
, SourceLocation Loc
,
3124 SourceLocation SecondaryLoc
, llvm::Value
*Alignment
,
3125 llvm::Value
*OffsetValue
, llvm::Value
*TheCheck
,
3126 llvm::Instruction
*Assumption
) {
3127 assert(isa_and_nonnull
<llvm::CallInst
>(Assumption
) &&
3128 cast
<llvm::CallInst
>(Assumption
)->getCalledOperand() ==
3129 llvm::Intrinsic::getDeclaration(
3130 Builder
.GetInsertBlock()->getParent()->getParent(),
3131 llvm::Intrinsic::assume
) &&
3132 "Assumption should be a call to llvm.assume().");
3133 assert(&(Builder
.GetInsertBlock()->back()) == Assumption
&&
3134 "Assumption should be the last instruction of the basic block, "
3135 "since the basic block is still being generated.");
3137 if (!SanOpts
.has(SanitizerKind::Alignment
))
3140 // Don't check pointers to volatile data. The behavior here is implementation-
3142 if (Ty
->getPointeeType().isVolatileQualified())
3145 // We need to temorairly remove the assumption so we can insert the
3146 // sanitizer check before it, else the check will be dropped by optimizations.
3147 Assumption
->removeFromParent();
3150 SanitizerScope
SanScope(this);
3153 OffsetValue
= Builder
.getInt1(false); // no offset.
3155 llvm::Constant
*StaticData
[] = {EmitCheckSourceLocation(Loc
),
3156 EmitCheckSourceLocation(SecondaryLoc
),
3157 EmitCheckTypeDescriptor(Ty
)};
3158 llvm::Value
*DynamicData
[] = {EmitCheckValue(Ptr
),
3159 EmitCheckValue(Alignment
),
3160 EmitCheckValue(OffsetValue
)};
3161 EmitCheck({std::make_pair(TheCheck
, SanitizerKind::Alignment
)},
3162 SanitizerHandler::AlignmentAssumption
, StaticData
, DynamicData
);
3165 // We are now in the (new, empty) "cont" basic block.
3166 // Reintroduce the assumption.
3167 Builder
.Insert(Assumption
);
3168 // FIXME: Assumption still has it's original basic block as it's Parent.
3171 llvm::DebugLoc
CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location
) {
3172 if (CGDebugInfo
*DI
= getDebugInfo())
3173 return DI
->SourceLocToDebugLoc(Location
);
3175 return llvm::DebugLoc();
3179 CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value
*Cond
,
3180 Stmt::Likelihood LH
) {
3184 case Stmt::LH_Likely
:
3185 case Stmt::LH_Unlikely
:
3186 // Don't generate llvm.expect on -O0 as the backend won't use it for
3188 if (CGM
.getCodeGenOpts().OptimizationLevel
== 0)
3190 llvm::Type
*CondTy
= Cond
->getType();
3191 assert(CondTy
->isIntegerTy(1) && "expecting condition to be a boolean");
3192 llvm::Function
*FnExpect
=
3193 CGM
.getIntrinsic(llvm::Intrinsic::expect
, CondTy
);
3194 llvm::Value
*ExpectedValueOfCond
=
3195 llvm::ConstantInt::getBool(CondTy
, LH
== Stmt::LH_Likely
);
3196 return Builder
.CreateCall(FnExpect
, {Cond
, ExpectedValueOfCond
},
3197 Cond
->getName() + ".expval");
3199 llvm_unreachable("Unknown Likelihood");
3202 llvm::Value
*CodeGenFunction::emitBoolVecConversion(llvm::Value
*SrcVec
,
3203 unsigned NumElementsDst
,
3204 const llvm::Twine
&Name
) {
3205 auto *SrcTy
= cast
<llvm::FixedVectorType
>(SrcVec
->getType());
3206 unsigned NumElementsSrc
= SrcTy
->getNumElements();
3207 if (NumElementsSrc
== NumElementsDst
)
3210 std::vector
<int> ShuffleMask(NumElementsDst
, -1);
3211 for (unsigned MaskIdx
= 0;
3212 MaskIdx
< std::min
<>(NumElementsDst
, NumElementsSrc
); ++MaskIdx
)
3213 ShuffleMask
[MaskIdx
] = MaskIdx
;
3215 return Builder
.CreateShuffleVector(SrcVec
, ShuffleMask
, Name
);
3218 void CodeGenFunction::EmitPointerAuthOperandBundle(
3219 const CGPointerAuthInfo
&PointerAuth
,
3220 SmallVectorImpl
<llvm::OperandBundleDef
> &Bundles
) {
3221 if (!PointerAuth
.isSigned())
3224 auto *Key
= Builder
.getInt32(PointerAuth
.getKey());
3226 llvm::Value
*Discriminator
= PointerAuth
.getDiscriminator();
3228 Discriminator
= Builder
.getSize(0);
3230 llvm::Value
*Args
[] = {Key
, Discriminator
};
3231 Bundles
.emplace_back("ptrauth", Args
);
3234 static llvm::Value
*EmitPointerAuthCommon(CodeGenFunction
&CGF
,
3235 const CGPointerAuthInfo
&PointerAuth
,
3236 llvm::Value
*Pointer
,
3237 unsigned IntrinsicID
) {
3241 auto Key
= CGF
.Builder
.getInt32(PointerAuth
.getKey());
3243 llvm::Value
*Discriminator
= PointerAuth
.getDiscriminator();
3244 if (!Discriminator
) {
3245 Discriminator
= CGF
.Builder
.getSize(0);
3248 // Convert the pointer to intptr_t before signing it.
3249 auto OrigType
= Pointer
->getType();
3250 Pointer
= CGF
.Builder
.CreatePtrToInt(Pointer
, CGF
.IntPtrTy
);
3252 // call i64 @llvm.ptrauth.sign.i64(i64 %pointer, i32 %key, i64 %discriminator)
3253 auto Intrinsic
= CGF
.CGM
.getIntrinsic(IntrinsicID
);
3254 Pointer
= CGF
.EmitRuntimeCall(Intrinsic
, {Pointer
, Key
, Discriminator
});
3256 // Convert back to the original type.
3257 Pointer
= CGF
.Builder
.CreateIntToPtr(Pointer
, OrigType
);
3262 CodeGenFunction::EmitPointerAuthSign(const CGPointerAuthInfo
&PointerAuth
,
3263 llvm::Value
*Pointer
) {
3264 if (!PointerAuth
.shouldSign())
3266 return EmitPointerAuthCommon(*this, PointerAuth
, Pointer
,
3267 llvm::Intrinsic::ptrauth_sign
);
3270 static llvm::Value
*EmitStrip(CodeGenFunction
&CGF
,
3271 const CGPointerAuthInfo
&PointerAuth
,
3272 llvm::Value
*Pointer
) {
3273 auto StripIntrinsic
= CGF
.CGM
.getIntrinsic(llvm::Intrinsic::ptrauth_strip
);
3275 auto Key
= CGF
.Builder
.getInt32(PointerAuth
.getKey());
3276 // Convert the pointer to intptr_t before signing it.
3277 auto OrigType
= Pointer
->getType();
3278 Pointer
= CGF
.EmitRuntimeCall(
3279 StripIntrinsic
, {CGF
.Builder
.CreatePtrToInt(Pointer
, CGF
.IntPtrTy
), Key
});
3280 return CGF
.Builder
.CreateIntToPtr(Pointer
, OrigType
);
3284 CodeGenFunction::EmitPointerAuthAuth(const CGPointerAuthInfo
&PointerAuth
,
3285 llvm::Value
*Pointer
) {
3286 if (PointerAuth
.shouldStrip()) {
3287 return EmitStrip(*this, PointerAuth
, Pointer
);
3289 if (!PointerAuth
.shouldAuth()) {
3293 return EmitPointerAuthCommon(*this, PointerAuth
, Pointer
,
3294 llvm::Intrinsic::ptrauth_auth
);