1//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This coordinates the per-function state used while generating code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CodeGenFunction.h"
14#include "CGBlocks.h"
15#include "CGCUDARuntime.h"
16#include "CGCXXABI.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/IgnoreExpr.h"
31#include "clang/AST/StmtCXX.h"
32#include "clang/AST/StmtObjC.h"
33#include "clang/Basic/Builtins.h"
34#include "clang/Basic/CodeGenOptions.h"
35#include "clang/Basic/DiagnosticFrontend.h"
36#include "clang/Basic/TargetBuiltins.h"
37#include "clang/Basic/TargetInfo.h"
38#include "clang/CodeGen/CGFunctionInfo.h"
39#include "clang/CodeGenUtils/FunctionUtils.h"
40#include "llvm/ADT/ArrayRef.h"
41#include "llvm/ADT/ScopeExit.h"
42#include "llvm/ADT/StringExtras.h"
43#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
44#include "llvm/IR/DataLayout.h"
45#include "llvm/IR/Dominators.h"
46#include "llvm/IR/FPEnv.h"
47#include "llvm/IR/Instruction.h"
48#include "llvm/IR/IntrinsicInst.h"
49#include "llvm/IR/Intrinsics.h"
50#include "llvm/IR/IntrinsicsPowerPC.h"
51#include "llvm/IR/MDBuilder.h"
52#include "llvm/Support/CRC.h"
53#include "llvm/Support/SaveAndRestore.h"
54#include "llvm/Support/SipHash.h"
55#include "llvm/Support/xxhash.h"
56#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
57#include "llvm/Transforms/Utils/PromoteMemToReg.h"
58#include <optional>
59
60using namespace clang;
61using namespace CodeGen;
62
63CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
64 : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
65 Builder(cgm, cgm.getModule().getContext(), CGBuilderInserterTy(this)),
66 SanOpts(CGM.getLangOpts().Sanitize), CurFPFeatures(CGM.getLangOpts()),
67 DebugInfo(CGM.getModuleDebugInfo()),
68 PGO(std::make_unique<CodeGenPGO>(args&: cgm)),
69 ShouldEmitLifetimeMarkers(CodeGenUtils::shouldEmitLifetimeMarkers(
70 CGOpts: CGM.getCodeGenOpts(), LangOpts: CGM.getLangOpts())) {
71 if (!suppressNewContext)
72 CGM.getCXXABI().getMangleContext().startNewFunction();
73 EHStack.setCGF(this);
74
75 SetFastMathFlags(CurFPFeatures);
76}
77
78const FunctionDecl *CodeGenFunction::getCurrentFunctionDecl() const {
79 const auto *FD = dyn_cast_or_null<FunctionDecl>(Val: CurCodeDecl);
80 if (!FD)
81 FD = dyn_cast_or_null<FunctionDecl>(Val: CurFuncDecl);
82 return FD;
83}
84
85CodeGenFunction::~CodeGenFunction() {
86 assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
87 assert(DeferredDeactivationCleanupStack.empty() &&
88 "missed to deactivate a cleanup");
89
90 if (getLangOpts().OpenMP && CurFn)
91 CGM.getOpenMPRuntime().functionFinished(CGF&: *this);
92
93 // If we have an OpenMPIRBuilder we want to finalize functions (incl.
94 // outlining etc) at some point. Doing it once the function codegen is done
95 // seems to be a reasonable spot. We do it here, as opposed to the deletion
96 // time of the CodeGenModule, because we have to ensure the IR has not yet
97 // been "emitted" to the outside, thus, modifications are still sensible.
98 if (CGM.getLangOpts().OpenMPIRBuilder && CurFn)
99 CGM.getOpenMPRuntime().getOMPBuilder().finalize(Fn: CurFn);
100}
101
102// Map the LangOption for exception behavior into
103// the corresponding enum in the IR.
104llvm::fp::ExceptionBehavior
105clang::ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind) {
106
107 switch (Kind) {
108 case LangOptions::FPE_Ignore: return llvm::fp::ebIgnore;
109 case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap;
110 case LangOptions::FPE_Strict: return llvm::fp::ebStrict;
111 default:
112 llvm_unreachable("Unsupported FP Exception Behavior");
113 }
114}
115
116void CodeGenFunction::SetFastMathFlags(FPOptions FPFeatures) {
117 llvm::FastMathFlags FMF;
118 FMF.setAllowReassoc(FPFeatures.getAllowFPReassociate());
119 FMF.setNoNaNs(FPFeatures.getNoHonorNaNs());
120 FMF.setNoInfs(FPFeatures.getNoHonorInfs());
121 FMF.setNoSignedZeros(FPFeatures.getNoSignedZero());
122 FMF.setAllowReciprocal(FPFeatures.getAllowReciprocal());
123 FMF.setApproxFunc(FPFeatures.getAllowApproxFunc());
124 FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
125 Builder.setFastMathFlags(FMF);
126}
127
128CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
129 const Expr *E)
130 : CGF(CGF) {
131 ConstructorHelper(FPFeatures: E->getFPFeaturesInEffect(LO: CGF.getLangOpts()));
132}
133
134CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
135 FPOptions FPFeatures)
136 : CGF(CGF) {
137 ConstructorHelper(FPFeatures);
138}
139
140void CodeGenFunction::CGFPOptionsRAII::ConstructorHelper(FPOptions FPFeatures) {
141 OldFPFeatures = CGF.CurFPFeatures;
142 CGF.CurFPFeatures = FPFeatures;
143
144 OldExcept = CGF.Builder.getDefaultConstrainedExcept();
145 OldRounding = CGF.Builder.getDefaultConstrainedRounding();
146
147 if (OldFPFeatures == FPFeatures)
148 return;
149
150 FMFGuard.emplace(args&: CGF.Builder);
151
152 llvm::RoundingMode NewRoundingBehavior = FPFeatures.getRoundingMode();
153 CGF.Builder.setDefaultConstrainedRounding(NewRoundingBehavior);
154 auto NewExceptionBehavior =
155 ToConstrainedExceptMD(Kind: FPFeatures.getExceptionMode());
156 CGF.Builder.setDefaultConstrainedExcept(NewExceptionBehavior);
157
158 CGF.SetFastMathFlags(FPFeatures);
159
160 assert((CGF.CurFuncDecl == nullptr || CGF.Builder.getIsFPConstrained() ||
161 isa<CXXConstructorDecl>(CGF.CurFuncDecl) ||
162 isa<CXXDestructorDecl>(CGF.CurFuncDecl) ||
163 (NewExceptionBehavior == llvm::fp::ebIgnore &&
164 NewRoundingBehavior == llvm::RoundingMode::NearestTiesToEven)) &&
165 "FPConstrained should be enabled on entire function");
166
167 auto mergeFnAttrValue = [&](StringRef Name, bool Value) {
168 auto OldValue =
169 CGF.CurFn->getFnAttribute(Kind: Name).getValueAsBool();
170 auto NewValue = OldValue & Value;
171 if (OldValue != NewValue)
172 CGF.CurFn->addFnAttr(Kind: Name, Val: llvm::toStringRef(B: NewValue));
173 };
174 mergeFnAttrValue("no-signed-zeros-fp-math", FPFeatures.getNoSignedZero());
175}
176
177CodeGenFunction::CGFPOptionsRAII::~CGFPOptionsRAII() {
178 CGF.CurFPFeatures = OldFPFeatures;
179 CGF.Builder.setDefaultConstrainedExcept(OldExcept);
180 CGF.Builder.setDefaultConstrainedRounding(OldRounding);
181}
182
183static LValue
184makeNaturalAlignAddrLValue(llvm::Value *V, QualType T, bool ForPointeeType,
185 bool MightBeSigned, CodeGenFunction &CGF,
186 KnownNonNull_t IsKnownNonNull = NotKnownNonNull) {
187 LValueBaseInfo BaseInfo;
188 TBAAAccessInfo TBAAInfo;
189 CharUnits Alignment =
190 CGF.CGM.getNaturalTypeAlignment(T, BaseInfo: &BaseInfo, TBAAInfo: &TBAAInfo, forPointeeType: ForPointeeType);
191 Address Addr =
192 MightBeSigned
193 ? CGF.makeNaturalAddressForPointer(Ptr: V, T, Alignment, ForPointeeType: false, BaseInfo: nullptr,
194 TBAAInfo: nullptr, IsKnownNonNull)
195 : Address(V, CGF.ConvertTypeForMem(T), Alignment, IsKnownNonNull);
196 return CGF.MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
197}
198
199LValue
200CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T,
201 KnownNonNull_t IsKnownNonNull) {
202 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ false,
203 /*MightBeSigned*/ true, CGF&: *this,
204 IsKnownNonNull);
205}
206
207LValue
208CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
209 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ true,
210 /*MightBeSigned*/ true, CGF&: *this);
211}
212
213LValue CodeGenFunction::MakeNaturalAlignRawAddrLValue(llvm::Value *V,
214 QualType T) {
215 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ false,
216 /*MightBeSigned*/ false, CGF&: *this);
217}
218
219LValue CodeGenFunction::MakeNaturalAlignPointeeRawAddrLValue(llvm::Value *V,
220 QualType T) {
221 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ true,
222 /*MightBeSigned*/ false, CGF&: *this);
223}
224
225llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
226 return CGM.getTypes().ConvertTypeForMem(T);
227}
228
229llvm::Type *CodeGenFunction::ConvertType(QualType T) {
230 return CGM.getTypes().ConvertType(T);
231}
232
233llvm::Type *CodeGenFunction::convertTypeForLoadStore(QualType ASTTy,
234 llvm::Type *LLVMTy) {
235 return CGM.getTypes().convertTypeForLoadStore(T: ASTTy, LLVMTy);
236}
237
238TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
239 type = type.getCanonicalType();
240 while (true) {
241 switch (type->getTypeClass()) {
242#define TYPE(name, parent)
243#define ABSTRACT_TYPE(name, parent)
244#define NON_CANONICAL_TYPE(name, parent) case Type::name:
245#define DEPENDENT_TYPE(name, parent) case Type::name:
246#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
247#include "clang/AST/TypeNodes.inc"
248 llvm_unreachable("non-canonical or dependent type in IR-generation");
249
250 case Type::Auto:
251 case Type::DeducedTemplateSpecialization:
252 llvm_unreachable("undeduced type in IR-generation");
253
254 // Various scalar types.
255 case Type::Builtin:
256 case Type::Pointer:
257 case Type::BlockPointer:
258 case Type::LValueReference:
259 case Type::RValueReference:
260 case Type::MemberPointer:
261 case Type::Vector:
262 case Type::ExtVector:
263 case Type::ConstantMatrix:
264 case Type::FunctionProto:
265 case Type::FunctionNoProto:
266 case Type::Enum:
267 case Type::ObjCObjectPointer:
268 case Type::Pipe:
269 case Type::BitInt:
270 case Type::HLSLAttributedResource:
271 case Type::HLSLInlineSpirv:
272 case Type::OverflowBehavior:
273 return TEK_Scalar;
274
275 // Complexes.
276 case Type::Complex:
277 return TEK_Complex;
278
279 // Arrays, records, and Objective-C objects.
280 case Type::ConstantArray:
281 case Type::IncompleteArray:
282 case Type::VariableArray:
283 case Type::Record:
284 case Type::ObjCObject:
285 case Type::ObjCInterface:
286 case Type::ArrayParameter:
287 return TEK_Aggregate;
288
289 // We operate on atomic values according to their underlying type.
290 case Type::Atomic:
291 type = cast<AtomicType>(Val&: type)->getValueType();
292 continue;
293 }
294 llvm_unreachable("unknown type kind!");
295 }
296}
297
298llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
299 // For cleanliness, we try to avoid emitting the return block for
300 // simple cases.
301 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
302
303 if (CurBB) {
304 assert(!CurBB->hasTerminator() && "Unexpected terminated block.");
305
306 // We have a valid insert point, reuse it if it is empty or there are no
307 // explicit jumps to the return block.
308 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
309 ReturnBlock.getBlock()->replaceAllUsesWith(V: CurBB);
310 delete ReturnBlock.getBlock();
311 ReturnBlock = JumpDest();
312 } else
313 EmitBlock(BB: ReturnBlock.getBlock());
314 return llvm::DebugLoc();
315 }
316
317 // Otherwise, if the return block is the target of a single direct
318 // branch then we can just put the code in that block instead. This
319 // cleans up functions which started with a unified return block.
320 if (ReturnBlock.getBlock()->hasOneUse()) {
321 auto *BI =
322 dyn_cast<llvm::UncondBrInst>(Val: *ReturnBlock.getBlock()->user_begin());
323 if (BI && BI->getSuccessor(i: 0) == ReturnBlock.getBlock()) {
324 // Record/return the DebugLoc of the simple 'return' expression to be used
325 // later by the actual 'ret' instruction.
326 llvm::DebugLoc Loc = BI->getDebugLoc();
327 Builder.SetInsertPoint(BI->getParent());
328 BI->eraseFromParent();
329 delete ReturnBlock.getBlock();
330 ReturnBlock = JumpDest();
331 return Loc;
332 }
333 }
334
335 // FIXME: We are at an unreachable point, there is no reason to emit the block
336 // unless it has uses. However, we still need a place to put the debug
337 // region.end for now.
338
339 EmitBlock(BB: ReturnBlock.getBlock());
340 return llvm::DebugLoc();
341}
342
343static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
344 if (!BB) return;
345 if (!BB->use_empty()) {
346 CGF.CurFn->insert(Position: CGF.CurFn->end(), BB);
347 return;
348 }
349 delete BB;
350}
351
352void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
353 assert(BreakContinueStack.empty() &&
354 "mismatched push/pop in break/continue stack!");
355 assert(LifetimeExtendedCleanupStack.empty() &&
356 "mismatched push/pop of cleanups in EHStack!");
357 assert(DeferredDeactivationCleanupStack.empty() &&
358 "mismatched activate/deactivate of cleanups!");
359
360 if (CGM.shouldEmitConvergenceTokens()) {
361 ConvergenceTokenStack.pop_back();
362 assert(ConvergenceTokenStack.empty() &&
363 "mismatched push/pop in convergence stack!");
364 }
365
366 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
367 && NumSimpleReturnExprs == NumReturnExprs
368 && ReturnBlock.getBlock()->use_empty();
369 // Usually the return expression is evaluated before the cleanup
370 // code. If the function contains only a simple return statement,
371 // such as a constant, the location before the cleanup code becomes
372 // the last useful breakpoint in the function, because the simple
373 // return expression will be evaluated after the cleanup code. To be
374 // safe, set the debug location for cleanup code to the location of
375 // the return statement. Otherwise the cleanup code should be at the
376 // end of the function's lexical scope.
377 //
378 // If there are multiple branches to the return block, the branch
379 // instructions will get the location of the return statements and
380 // all will be fine.
381 if (CGDebugInfo *DI = getDebugInfo()) {
382 if (OnlySimpleReturnStmts)
383 DI->EmitLocation(Builder, Loc: LastStopPoint);
384 else
385 DI->EmitLocation(Builder, Loc: EndLoc);
386 }
387
388 // Pop any cleanups that might have been associated with the
389 // parameters. Do this in whatever block we're currently in; it's
390 // important to do this before we enter the return block or return
391 // edges will be *really* confused.
392 bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
393 bool HasOnlyNoopCleanups =
394 HasCleanups && EHStack.containsOnlyNoopCleanups(Old: PrologueCleanupDepth);
395 bool EmitRetDbgLoc = !HasCleanups || HasOnlyNoopCleanups;
396
397 std::optional<ApplyDebugLocation> OAL;
398 if (HasCleanups) {
399 // Make sure the line table doesn't jump back into the body for
400 // the ret after it's been at EndLoc.
401 if (CGDebugInfo *DI = getDebugInfo()) {
402 if (OnlySimpleReturnStmts)
403 DI->EmitLocation(Builder, Loc: EndLoc);
404 else
405 // We may not have a valid end location. Try to apply it anyway, and
406 // fall back to an artificial location if needed.
407 OAL = ApplyDebugLocation::CreateDefaultArtificial(CGF&: *this, TemporaryLocation: EndLoc);
408 }
409
410 PopCleanupBlocks(OldCleanupStackSize: PrologueCleanupDepth);
411 }
412
413 // Emit function epilog (to return).
414 llvm::DebugLoc Loc = EmitReturnBlock();
415
416 if (ShouldInstrumentFunction()) {
417 if (CGM.getCodeGenOpts().InstrumentFunctions)
418 CurFn->addFnAttr(Kind: "instrument-function-exit", Val: "__cyg_profile_func_exit");
419 if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
420 CurFn->addFnAttr(Kind: "instrument-function-exit-inlined",
421 Val: "__cyg_profile_func_exit");
422 }
423
424 // Emit debug descriptor for function end.
425 if (CGDebugInfo *DI = getDebugInfo())
426 DI->EmitFunctionEnd(Builder, Fn: CurFn);
427
428 // Reset the debug location to that of the simple 'return' expression, if any
429 // rather than that of the end of the function's scope '}'.
430 uint64_t RetKeyInstructionsAtomGroup = Loc ? Loc->getAtomGroup() : 0;
431 ApplyDebugLocation AL(*this, Loc);
432 EmitFunctionEpilog(FI: *CurFnInfo, EmitRetDbgLoc, EndLoc,
433 RetKeyInstructionsSourceAtom: RetKeyInstructionsAtomGroup);
434 EmitEndEHSpec(D: CurCodeDecl);
435
436 assert(EHStack.empty() &&
437 "did not remove all scopes from cleanup stack!");
438
439 // If someone did an indirect goto, emit the indirect goto block at the end of
440 // the function.
441 if (IndirectBranch) {
442 EmitBlock(BB: IndirectBranch->getParent());
443 Builder.ClearInsertionPoint();
444 }
445
446 // If some of our locals escaped, insert a call to llvm.localescape in the
447 // entry block.
448 if (!EscapedLocals.empty()) {
449 // Invert the map from local to index into a simple vector. There should be
450 // no holes.
451 SmallVector<llvm::Value *, 4> EscapeArgs;
452 EscapeArgs.resize(N: EscapedLocals.size());
453 for (auto &Pair : EscapedLocals)
454 EscapeArgs[Pair.second] = Pair.first;
455 llvm::Function *FrameEscapeFn = llvm::Intrinsic::getOrInsertDeclaration(
456 M: &CGM.getModule(), id: llvm::Intrinsic::localescape);
457 CGBuilderTy(CGM, AllocaInsertPt).CreateCall(Callee: FrameEscapeFn, Args: EscapeArgs);
458 }
459
460 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
461 llvm::Instruction *Ptr = AllocaInsertPt;
462 AllocaInsertPt = nullptr;
463 Ptr->eraseFromParent();
464
465 // PostAllocaInsertPt, if created, was lazily created when it was required,
466 // remove it now since it was just created for our own convenience.
467 if (PostAllocaInsertPt) {
468 llvm::Instruction *PostPtr = PostAllocaInsertPt;
469 PostAllocaInsertPt = nullptr;
470 PostPtr->eraseFromParent();
471 }
472
473 // If someone took the address of a label but never did an indirect goto, we
474 // made a zero entry PHI node, which is illegal, zap it now.
475 if (IndirectBranch) {
476 llvm::PHINode *PN = cast<llvm::PHINode>(Val: IndirectBranch->getAddress());
477 if (PN->getNumIncomingValues() == 0) {
478 PN->replaceAllUsesWith(V: llvm::PoisonValue::get(T: PN->getType()));
479 PN->eraseFromParent();
480 }
481 }
482
483 EmitIfUsed(CGF&: *this, BB: EHResumeBlock);
484 EmitIfUsed(CGF&: *this, BB: TerminateLandingPad);
485 EmitIfUsed(CGF&: *this, BB: TerminateHandler);
486 EmitIfUsed(CGF&: *this, BB: UnreachableBlock);
487
488 for (const auto &FuncletAndParent : TerminateFunclets)
489 EmitIfUsed(CGF&: *this, BB: FuncletAndParent.second);
490
491 if (CGM.getCodeGenOpts().EmitDeclMetadata)
492 EmitDeclMetadata();
493
494 for (const auto &R : DeferredReplacements) {
495 if (llvm::Value *Old = R.first) {
496 Old->replaceAllUsesWith(V: R.second);
497 cast<llvm::Instruction>(Val: Old)->eraseFromParent();
498 }
499 }
500 DeferredReplacements.clear();
501
502 // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
503 // PHIs if the current function is a coroutine. We don't do it for all
504 // functions as it may result in slight increase in numbers of instructions
505 // if compiled with no optimizations. We do it for coroutine as the lifetime
506 // of CleanupDestSlot alloca make correct coroutine frame building very
507 // difficult.
508 if (NormalCleanupDest.isValid() && isCoroutine()) {
509 llvm::DominatorTree DT(*CurFn);
510 llvm::PromoteMemToReg(
511 Allocas: cast<llvm::AllocaInst>(Val: NormalCleanupDest.getPointer()), DT);
512 NormalCleanupDest = Address::invalid();
513 }
514
515 // Scan function arguments for vector width.
516 for (llvm::Argument &A : CurFn->args())
517 if (auto *VT = dyn_cast<llvm::VectorType>(Val: A.getType()))
518 LargestVectorWidth =
519 std::max(a: (uint64_t)LargestVectorWidth,
520 b: VT->getPrimitiveSizeInBits().getKnownMinValue());
521
522 // Update vector width based on return type.
523 if (auto *VT = dyn_cast<llvm::VectorType>(Val: CurFn->getReturnType()))
524 LargestVectorWidth =
525 std::max(a: (uint64_t)LargestVectorWidth,
526 b: VT->getPrimitiveSizeInBits().getKnownMinValue());
527
528 if (CurFnInfo->getMaxVectorWidth() > LargestVectorWidth)
529 LargestVectorWidth = CurFnInfo->getMaxVectorWidth();
530
531 // Add the min-legal-vector-width attribute. This contains the max width from:
532 // 1. min-vector-width attribute used in the source program.
533 // 2. Any builtins used that have a vector width specified.
534 // 3. Values passed in and out of inline assembly.
535 // 4. Width of vector arguments and return types for this function.
536 // 5. Width of vector arguments and return types for functions called by this
537 // function.
538 if (getContext().getTargetInfo().getTriple().isX86())
539 CurFn->addFnAttr(Kind: "min-legal-vector-width",
540 Val: llvm::utostr(X: LargestVectorWidth));
541
542 // If we generated an unreachable return block, delete it now.
543 if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) {
544 Builder.ClearInsertionPoint();
545 ReturnBlock.getBlock()->eraseFromParent();
546 }
547 if (ReturnValue.isValid()) {
548 auto *RetAlloca =
549 dyn_cast<llvm::AllocaInst>(Val: ReturnValue.emitRawPointer(CGF&: *this));
550 if (RetAlloca && RetAlloca->use_empty()) {
551 RetAlloca->eraseFromParent();
552 ReturnValue = Address::invalid();
553 }
554 }
555}
556
557/// ShouldInstrumentFunction - Return true if the current function should be
558/// instrumented with __cyg_profile_func_* calls
559bool CodeGenFunction::ShouldInstrumentFunction() {
560 if (!CGM.getCodeGenOpts().InstrumentFunctions &&
561 !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining &&
562 !CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
563 return false;
564 if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
565 return false;
566 return true;
567}
568
569bool CodeGenFunction::ShouldSkipSanitizerInstrumentation() {
570 if (!CurFuncDecl)
571 return false;
572 return CurFuncDecl->hasAttr<DisableSanitizerInstrumentationAttr>();
573}
574
575/// ShouldXRayInstrument - Return true if the current function should be
576/// instrumented with XRay nop sleds.
577bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
578 return CGM.getCodeGenOpts().XRayInstrumentFunctions;
579}
580
581/// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
582/// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
583bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
584 return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
585 (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
586 CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
587 XRayInstrKind::Custom);
588}
589
590bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
591 return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
592 (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
593 CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
594 XRayInstrKind::Typed);
595}
596
597llvm::ConstantInt *
598CodeGenFunction::getUBSanFunctionTypeHash(QualType Ty) const {
599 // Remove any (C++17) exception specifications, to allow calling e.g. a
600 // noexcept function through a non-noexcept pointer.
601 if (!Ty->isFunctionNoProtoType())
602 Ty = getContext().getFunctionTypeWithExceptionSpec(Orig: Ty, ESI: EST_None);
603 std::string Mangled;
604 llvm::raw_string_ostream Out(Mangled);
605 CGM.getCXXABI().getMangleContext().mangleCanonicalTypeName(T: Ty, Out, NormalizeIntegers: false);
606 return llvm::ConstantInt::get(
607 Ty: CGM.Int32Ty, V: static_cast<uint32_t>(llvm::xxh3_64bits(data: Mangled)));
608}
609
610void CodeGenFunction::EmitKernelMetadata(const FunctionDecl *FD,
611 llvm::Function *Fn) {
612 if (!FD->hasAttr<DeviceKernelAttr>() && !FD->hasAttr<CUDAGlobalAttr>())
613 return;
614
615 llvm::LLVMContext &Context = getLLVMContext();
616
617 CGM.GenKernelArgMetadata(FN: Fn, FD, CGF: this);
618
619 if (!(getLangOpts().OpenCL ||
620 (getLangOpts().CUDA &&
621 getContext().getTargetInfo().getTriple().isSPIRV())))
622 return;
623
624 if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
625 QualType HintQTy = A->getTypeHint();
626 const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
627 bool IsSignedInteger =
628 HintQTy->isSignedIntegerType() ||
629 (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType());
630 llvm::Metadata *AttrMDArgs[] = {
631 llvm::ConstantAsMetadata::get(C: llvm::PoisonValue::get(
632 T: CGM.getTypes().ConvertType(T: A->getTypeHint()))),
633 llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::get(
634 Ty: llvm::IntegerType::get(C&: Context, NumBits: 32),
635 V: llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
636 Fn->setMetadata(Kind: "vec_type_hint", Node: llvm::MDNode::get(Context, MDs: AttrMDArgs));
637 }
638
639 if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
640 auto Eval = [&](Expr *E) {
641 return E->EvaluateKnownConstInt(Ctx: FD->getASTContext()).getExtValue();
642 };
643 llvm::Metadata *AttrMDArgs[] = {
644 llvm::ConstantAsMetadata::get(C: Builder.getInt32(C: Eval(A->getXDim()))),
645 llvm::ConstantAsMetadata::get(C: Builder.getInt32(C: Eval(A->getYDim()))),
646 llvm::ConstantAsMetadata::get(C: Builder.getInt32(C: Eval(A->getZDim())))};
647 Fn->setMetadata(Kind: "work_group_size_hint", Node: llvm::MDNode::get(Context, MDs: AttrMDArgs));
648 }
649
650 if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
651 auto Eval = [&](Expr *E) {
652 return E->EvaluateKnownConstInt(Ctx: FD->getASTContext()).getExtValue();
653 };
654 llvm::Metadata *AttrMDArgs[] = {
655 llvm::ConstantAsMetadata::get(C: Builder.getInt32(C: Eval(A->getXDim()))),
656 llvm::ConstantAsMetadata::get(C: Builder.getInt32(C: Eval(A->getYDim()))),
657 llvm::ConstantAsMetadata::get(C: Builder.getInt32(C: Eval(A->getZDim())))};
658 Fn->setMetadata(Kind: "reqd_work_group_size", Node: llvm::MDNode::get(Context, MDs: AttrMDArgs));
659 }
660
661 if (const OpenCLIntelReqdSubGroupSizeAttr *A =
662 FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
663 llvm::Metadata *AttrMDArgs[] = {
664 llvm::ConstantAsMetadata::get(C: Builder.getInt32(C: A->getSubGroupSize()))};
665 Fn->setMetadata(Kind: "intel_reqd_sub_group_size",
666 Node: llvm::MDNode::get(Context, MDs: AttrMDArgs));
667 }
668}
669
670/// Determine whether the function F ends with a return stmt.
671static bool endsWithReturn(const Decl* F) {
672 const Stmt *Body = nullptr;
673 if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: F))
674 Body = FD->getBody();
675 else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(Val: F))
676 Body = OMD->getBody();
677
678 if (auto *CS = dyn_cast_or_null<CompoundStmt>(Val: Body)) {
679 auto LastStmt = CS->body_rbegin();
680 if (LastStmt != CS->body_rend())
681 return isa<ReturnStmt>(Val: *LastStmt);
682 }
683 return false;
684}
685
686void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
687 if (SanOpts.has(K: SanitizerKind::Thread)) {
688 Fn->addFnAttr(Kind: "sanitize_thread_no_checking_at_run_time");
689 Fn->removeFnAttr(Kind: llvm::Attribute::SanitizeThread);
690 }
691}
692
693/// Check if the return value of this function requires sanitization.
694bool CodeGenFunction::requiresReturnValueCheck() const {
695 return requiresReturnValueNullabilityCheck() ||
696 (SanOpts.has(K: SanitizerKind::ReturnsNonnullAttribute) && CurCodeDecl &&
697 CurCodeDecl->getAttr<ReturnsNonNullAttr>());
698}
699
700static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
701 auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: D);
702 if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
703 !MD->getDeclName().getAsIdentifierInfo()->isStr(Str: "allocate") ||
704 (MD->getNumParams() != 1 && MD->getNumParams() != 2))
705 return false;
706
707 if (!Ctx.hasSameType(T1: MD->parameters()[0]->getType(), T2: Ctx.getSizeType()))
708 return false;
709
710 if (MD->getNumParams() == 2) {
711 auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
712 if (!PT || !PT->isVoidPointerType() ||
713 !PT->getPointeeType().isConstQualified())
714 return false;
715 }
716
717 return true;
718}
719
720bool CodeGenFunction::isInAllocaArgument(CGCXXABI &ABI, QualType Ty) {
721 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
722 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
723}
724
725bool CodeGenFunction::hasInAllocaArg(const CXXMethodDecl *MD) {
726 return getTarget().getTriple().getArch() == llvm::Triple::x86 &&
727 getTarget().getCXXABI().isMicrosoft() &&
728 llvm::any_of(Range: MD->parameters(), P: [&](ParmVarDecl *P) {
729 return isInAllocaArgument(ABI&: CGM.getCXXABI(), Ty: P->getType());
730 });
731}
732
733/// Return the UBSan prologue signature for \p FD if one is available.
734static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
735 const FunctionDecl *FD) {
736 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD))
737 if (!MD->isStatic())
738 return nullptr;
739 return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
740}
741
742void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
743 llvm::Function *Fn,
744 const CGFunctionInfo &FnInfo,
745 const FunctionArgList &Args,
746 SourceLocation Loc,
747 SourceLocation StartLoc) {
748 assert(!CurFn &&
749 "Do not use a CodeGenFunction object for more than one function");
750
751 const Decl *D = GD.getDecl();
752
753 DidCallStackSave = false;
754 CurCodeDecl = D;
755 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: D);
756 if (FD && FD->usesSEHTry())
757 CurSEHParent = GD;
758 CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
759 FnRetTy = RetTy;
760 CurFn = Fn;
761 CurFnInfo = &FnInfo;
762 assert(CurFn->isDeclaration() && "Function already has body?");
763
764 // If this function is ignored for any of the enabled sanitizers,
765 // disable the sanitizer for the function.
766 do {
767#define SANITIZER(NAME, ID) \
768 if (SanOpts.empty()) \
769 break; \
770 if (SanOpts.has(SanitizerKind::ID)) \
771 if (CGM.isInNoSanitizeList(SanitizerKind::ID, Fn, Loc)) \
772 SanOpts.set(SanitizerKind::ID, false);
773
774#include "clang/Basic/Sanitizers.def"
775#undef SANITIZER
776 } while (false);
777
778 if (D) {
779 const bool SanitizeBounds = SanOpts.hasOneOf(K: SanitizerKind::Bounds);
780 SanitizerMask no_sanitize_mask;
781 bool NoSanitizeCoverage = false;
782
783 for (auto *Attr : D->specific_attrs<NoSanitizeAttr>()) {
784 no_sanitize_mask |= Attr->getMask();
785 // SanitizeCoverage is not handled by SanOpts.
786 if (Attr->hasCoverage())
787 NoSanitizeCoverage = true;
788 }
789
790 // Apply the no_sanitize* attributes to SanOpts.
791 SanOpts.Mask &= ~no_sanitize_mask;
792 if (no_sanitize_mask & SanitizerKind::Address)
793 SanOpts.set(K: SanitizerKind::KernelAddress, Value: false);
794 if (no_sanitize_mask & SanitizerKind::KernelAddress)
795 SanOpts.set(K: SanitizerKind::Address, Value: false);
796 if (no_sanitize_mask & SanitizerKind::HWAddress)
797 SanOpts.set(K: SanitizerKind::KernelHWAddress, Value: false);
798 if (no_sanitize_mask & SanitizerKind::KernelHWAddress)
799 SanOpts.set(K: SanitizerKind::HWAddress, Value: false);
800
801 if (SanitizeBounds && !SanOpts.hasOneOf(K: SanitizerKind::Bounds))
802 Fn->addFnAttr(Kind: llvm::Attribute::NoSanitizeBounds);
803
804 if (NoSanitizeCoverage && CGM.getCodeGenOpts().hasSanitizeCoverage())
805 Fn->addFnAttr(Kind: llvm::Attribute::NoSanitizeCoverage);
806
807 // Some passes need the non-negated no_sanitize attribute. Pass them on.
808 if (CGM.getCodeGenOpts().hasSanitizeBinaryMetadata()) {
809 if (no_sanitize_mask & SanitizerKind::Thread)
810 Fn->addFnAttr(Kind: "no_sanitize_thread");
811 }
812 }
813
814 if (ShouldSkipSanitizerInstrumentation()) {
815 CurFn->addFnAttr(Kind: llvm::Attribute::DisableSanitizerInstrumentation);
816 } else {
817 // Apply sanitizer attributes to the function.
818 if (SanOpts.hasOneOf(K: SanitizerKind::Address | SanitizerKind::KernelAddress))
819 Fn->addFnAttr(Kind: llvm::Attribute::SanitizeAddress);
820 if (SanOpts.hasOneOf(K: SanitizerKind::HWAddress |
821 SanitizerKind::KernelHWAddress))
822 Fn->addFnAttr(Kind: llvm::Attribute::SanitizeHWAddress);
823 if (SanOpts.has(K: SanitizerKind::MemtagStack))
824 Fn->addFnAttr(Kind: llvm::Attribute::SanitizeMemTag);
825 if (SanOpts.has(K: SanitizerKind::Thread))
826 Fn->addFnAttr(Kind: llvm::Attribute::SanitizeThread);
827 if (SanOpts.has(K: SanitizerKind::Type))
828 Fn->addFnAttr(Kind: llvm::Attribute::SanitizeType);
829 if (SanOpts.has(K: SanitizerKind::NumericalStability))
830 Fn->addFnAttr(Kind: llvm::Attribute::SanitizeNumericalStability);
831 if (SanOpts.hasOneOf(K: SanitizerKind::Memory | SanitizerKind::KernelMemory))
832 Fn->addFnAttr(Kind: llvm::Attribute::SanitizeMemory);
833 if (SanOpts.has(K: SanitizerKind::AllocToken))
834 Fn->addFnAttr(Kind: llvm::Attribute::SanitizeAllocToken);
835 }
836 if (SanOpts.has(K: SanitizerKind::SafeStack))
837 Fn->addFnAttr(Kind: llvm::Attribute::SafeStack);
838 if (SanOpts.has(K: SanitizerKind::ShadowCallStack))
839 Fn->addFnAttr(Kind: llvm::Attribute::ShadowCallStack);
840
841 if (SanOpts.has(K: SanitizerKind::Realtime))
842 if (FD && FD->getASTContext().hasAnyFunctionEffects())
843 for (const FunctionEffectWithCondition &Fe : FD->getFunctionEffects()) {
844 if (Fe.Effect.kind() == FunctionEffect::Kind::NonBlocking)
845 Fn->addFnAttr(Kind: llvm::Attribute::SanitizeRealtime);
846 else if (Fe.Effect.kind() == FunctionEffect::Kind::Blocking)
847 Fn->addFnAttr(Kind: llvm::Attribute::SanitizeRealtimeBlocking);
848 }
849
850 // Apply fuzzing attribute to the function.
851 if (SanOpts.hasOneOf(K: SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
852 Fn->addFnAttr(Kind: llvm::Attribute::OptForFuzzing);
853
854 // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
855 // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
856 if (SanOpts.has(K: SanitizerKind::Thread)) {
857 if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(Val: D)) {
858 const IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(argIndex: 0);
859 if (OMD->getMethodFamily() == OMF_dealloc ||
860 OMD->getMethodFamily() == OMF_initialize ||
861 (OMD->getSelector().isUnarySelector() && II->isStr(Str: ".cxx_destruct"))) {
862 markAsIgnoreThreadCheckingAtRuntime(Fn);
863 }
864 }
865 }
866
867 // Ignore unrelated casts in STL allocate() since the allocator must cast
868 // from void* to T* before object initialization completes. Don't match on the
869 // namespace because not all allocators are in std::
870 if (D && SanOpts.has(K: SanitizerKind::CFIUnrelatedCast)) {
871 if (matchesStlAllocatorFn(D, Ctx: getContext()))
872 SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
873 }
874
875 // Ignore null checks in coroutine functions since the coroutines passes
876 // are not aware of how to move the extra UBSan instructions across the split
877 // coroutine boundaries.
878 if (D && SanOpts.has(K: SanitizerKind::Null))
879 if (FD && FD->getBody() &&
880 FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
881 SanOpts.Mask &= ~SanitizerKind::Null;
882
883 // Apply xray attributes to the function (as a string, for now)
884 bool AlwaysXRayAttr = false;
885 if (const auto *XRayAttr = D ? D->getAttr<XRayInstrumentAttr>() : nullptr) {
886 if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
887 K: XRayInstrKind::FunctionEntry) ||
888 CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
889 K: XRayInstrKind::FunctionExit)) {
890 if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction()) {
891 Fn->addFnAttr(Kind: "function-instrument", Val: "xray-always");
892 AlwaysXRayAttr = true;
893 }
894 if (XRayAttr->neverXRayInstrument())
895 Fn->addFnAttr(Kind: "function-instrument", Val: "xray-never");
896 if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
897 if (ShouldXRayInstrumentFunction())
898 Fn->addFnAttr(Kind: "xray-log-args",
899 Val: llvm::utostr(X: LogArgs->getArgumentCount()));
900 }
901 } else {
902 if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc))
903 Fn->addFnAttr(
904 Kind: "xray-instruction-threshold",
905 Val: llvm::itostr(X: CGM.getCodeGenOpts().XRayInstructionThreshold));
906 }
907
908 if (ShouldXRayInstrumentFunction()) {
909 if (CGM.getCodeGenOpts().XRayIgnoreLoops)
910 Fn->addFnAttr(Kind: "xray-ignore-loops");
911
912 if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
913 K: XRayInstrKind::FunctionExit))
914 Fn->addFnAttr(Kind: "xray-skip-exit");
915
916 if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
917 K: XRayInstrKind::FunctionEntry))
918 Fn->addFnAttr(Kind: "xray-skip-entry");
919
920 auto FuncGroups = CGM.getCodeGenOpts().XRayTotalFunctionGroups;
921 if (FuncGroups > 1) {
922 auto FuncName = llvm::ArrayRef<uint8_t>(CurFn->getName().bytes_begin(),
923 CurFn->getName().bytes_end());
924 auto Group = crc32(Data: FuncName) % FuncGroups;
925 if (Group != CGM.getCodeGenOpts().XRaySelectedFunctionGroup &&
926 !AlwaysXRayAttr)
927 Fn->addFnAttr(Kind: "function-instrument", Val: "xray-never");
928 }
929 }
930
931 if (CGM.getCodeGenOpts().getProfileInstr() !=
932 llvm::driver::ProfileInstrKind::ProfileNone) {
933 switch (CGM.isFunctionBlockedFromProfileInstr(Fn, Loc)) {
934 case ProfileList::Skip:
935 Fn->addFnAttr(Kind: llvm::Attribute::SkipProfile);
936 break;
937 case ProfileList::Forbid:
938 Fn->addFnAttr(Kind: llvm::Attribute::NoProfile);
939 break;
940 case ProfileList::Allow:
941 break;
942 }
943 }
944
945 unsigned Count, Offset;
946 StringRef Section;
947 if (const auto *Attr =
948 D ? D->getAttr<PatchableFunctionEntryAttr>() : nullptr) {
949 Count = Attr->getCount();
950 Offset = Attr->getOffset();
951 Section = Attr->getSection();
952 } else {
953 Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount;
954 Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset;
955 }
956 if (Section.empty())
957 Section = CGM.getCodeGenOpts().PatchableFunctionEntrySection;
958 if (Count && Offset <= Count) {
959 Fn->addFnAttr(Kind: "patchable-function-entry", Val: std::to_string(val: Count - Offset));
960 if (Offset)
961 Fn->addFnAttr(Kind: "patchable-function-prefix", Val: std::to_string(val: Offset));
962 if (!Section.empty())
963 Fn->addFnAttr(Kind: "patchable-function-entry-section", Val: Section);
964 }
965 // Instruct that functions for COFF/CodeView targets should start with a
966 // patchable instruction, but only on x86/x64. Don't forward this to ARM/ARM64
967 // backends as they don't need it -- instructions on these architectures are
968 // always atomically patchable at runtime.
969 if (CGM.getCodeGenOpts().HotPatch &&
970 getContext().getTargetInfo().getTriple().isX86() &&
971 getContext().getTargetInfo().getTriple().getEnvironment() !=
972 llvm::Triple::CODE16)
973 Fn->addFnAttr(Kind: "patchable-function", Val: "prologue-short-redirect");
974
975 // Add no-jump-tables value.
976 if (CGM.getCodeGenOpts().NoUseJumpTables)
977 Fn->addFnAttr(Kind: "no-jump-tables", Val: "true");
978
979 // Add no-inline-line-tables value.
980 if (CGM.getCodeGenOpts().NoInlineLineTables)
981 Fn->addFnAttr(Kind: "no-inline-line-tables");
982
983 // Add profile-sample-accurate value.
984 if (CGM.getCodeGenOpts().ProfileSampleAccurate)
985 Fn->addFnAttr(Kind: "profile-sample-accurate");
986
987 if (!CGM.getCodeGenOpts().SampleProfileFile.empty())
988 Fn->addFnAttr(Kind: "use-sample-profile");
989
990 if (D && D->hasAttr<CFICanonicalJumpTableAttr>())
991 Fn->addFnAttr(Kind: "cfi-canonical-jump-table");
992
993 if (D && D->hasAttr<NoProfileFunctionAttr>())
994 Fn->addFnAttr(Kind: llvm::Attribute::NoProfile);
995
996 if (D && D->hasAttr<HybridPatchableAttr>())
997 Fn->addFnAttr(Kind: llvm::Attribute::HybridPatchable);
998
999 if (D) {
1000 // Function attributes take precedence over command line flags.
1001 if (auto *A = D->getAttr<FunctionReturnThunksAttr>()) {
1002 switch (A->getThunkType()) {
1003 case FunctionReturnThunksAttr::Kind::Keep:
1004 break;
1005 case FunctionReturnThunksAttr::Kind::Extern:
1006 Fn->addFnAttr(Kind: llvm::Attribute::FnRetThunkExtern);
1007 break;
1008 }
1009 } else if (CGM.getCodeGenOpts().FunctionReturnThunks)
1010 Fn->addFnAttr(Kind: llvm::Attribute::FnRetThunkExtern);
1011 }
1012
1013 if (FD && (getLangOpts().OpenCL ||
1014 (getLangOpts().CUDA &&
1015 getContext().getTargetInfo().getTriple().isSPIRV()) ||
1016 ((getLangOpts().HIP || getLangOpts().OffloadViaLLVM) &&
1017 getLangOpts().CUDAIsDevice))) {
1018 // Add metadata for a kernel function.
1019 EmitKernelMetadata(FD, Fn);
1020 }
1021
1022 if (FD && FD->hasAttr<ClspvLibclcBuiltinAttr>()) {
1023 Fn->setMetadata(Kind: "clspv_libclc_builtin",
1024 Node: llvm::MDNode::get(Context&: getLLVMContext(), MDs: {}));
1025 }
1026
1027 // If we are checking function types, emit a function type signature as
1028 // prologue data. Kernel functions have strict alignment requirements and
1029 // cannot be call indirectly so we do not instrument them.
1030 if (FD && SanOpts.has(K: SanitizerKind::Function) &&
1031 !FD->getType()->isCFIUncheckedCalleeFunctionType() &&
1032 llvm::isCallableCC(CC: Fn->getCallingConv())) {
1033 if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
1034 llvm::LLVMContext &Ctx = Fn->getContext();
1035 llvm::MDBuilder MDB(Ctx);
1036 Fn->setMetadata(
1037 KindID: llvm::LLVMContext::MD_func_sanitize,
1038 Node: MDB.createRTTIPointerPrologue(
1039 PrologueSig, RTTI: getUBSanFunctionTypeHash(Ty: FD->getType())));
1040 }
1041 }
1042
1043 // If we're checking nullability, we need to know whether we can check the
1044 // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
1045 if (SanOpts.has(K: SanitizerKind::NullabilityReturn)) {
1046 auto Nullability = FnRetTy->getNullability();
1047 if (Nullability && *Nullability == NullabilityKind::NonNull &&
1048 !FnRetTy->isRecordType()) {
1049 if (!(SanOpts.has(K: SanitizerKind::ReturnsNonnullAttribute) &&
1050 CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
1051 RetValNullabilityPrecondition =
1052 llvm::ConstantInt::getTrue(Context&: getLLVMContext());
1053 }
1054 }
1055
1056 // Annotate C++ special member functions so that CopyProfPass can instrument
1057 // them, provided the object is at least as large as the size threshold.
1058 if (CGM.getCodeGenOpts().CopyProf) {
1059 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: D)) {
1060 StringRef Attr;
1061 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD)) {
1062 if (!CD->isMoveConstructor())
1063 Attr =
1064 CD->isCopyConstructor() ? "copyprof-copy-ctor" : "copyprof-ctor";
1065 } else if (isa<CXXDestructorDecl>(Val: MD)) {
1066 Attr = "copyprof-dtor";
1067 } else if (MD->isCopyAssignmentOperator()) {
1068 Attr = "copyprof-copy-assign-op";
1069 }
1070 if (!Attr.empty()) {
1071 // Finally, add the object size in bytes to the annotation.
1072 // A special member function always has an implicit object parameter, so
1073 // its type is guaranteed to be complete here.
1074 CharUnits ObjSize = getContext().getTypeSizeInChars(
1075 T: MD->getFunctionObjectParameterType());
1076 if (ObjSize.getQuantity() >=
1077 CGM.getCodeGenOpts().CopyProfStaticSizeThreshold)
1078 Fn->addFnAttr(Kind: Attr, Val: llvm::utostr(X: ObjSize.getQuantity()));
1079 }
1080 }
1081 }
1082
1083 // If we're in C++ mode and the function name is "main", it is guaranteed
1084 // to be norecurse by the standard (3.6.1.3 "The function main shall not be
1085 // used within a program").
1086 //
1087 // OpenCL C 2.0 v2.2-11 s6.9.i:
1088 // Recursion is not supported.
1089 //
1090 // HLSL
1091 // Recursion is not supported.
1092 //
1093 // SYCL v1.2.1 s3.10:
1094 // kernels cannot include RTTI information, exception classes,
1095 // recursive code, virtual functions or make use of C++ libraries that
1096 // are not compiled for the device.
1097 if (FD &&
1098 ((getLangOpts().CPlusPlus && FD->isMain()) || getLangOpts().OpenCL ||
1099 getLangOpts().HLSL || getLangOpts().SYCLIsDevice ||
1100 (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>())))
1101 Fn->addFnAttr(Kind: llvm::Attribute::NoRecurse);
1102
1103 llvm::RoundingMode RM = getLangOpts().getDefaultRoundingMode();
1104 llvm::fp::ExceptionBehavior FPExceptionBehavior =
1105 ToConstrainedExceptMD(Kind: getLangOpts().getDefaultExceptionMode());
1106 Builder.setDefaultConstrainedRounding(RM);
1107 Builder.setDefaultConstrainedExcept(FPExceptionBehavior);
1108 if ((FD && (FD->UsesFPIntrin() || FD->hasAttr<StrictFPAttr>())) ||
1109 (!FD && (FPExceptionBehavior != llvm::fp::ebIgnore ||
1110 RM != llvm::RoundingMode::NearestTiesToEven))) {
1111 Builder.setIsFPConstrained(true);
1112 Fn->addFnAttr(Kind: llvm::Attribute::StrictFP);
1113 }
1114
1115 // If a custom alignment is used, force realigning to this alignment on
1116 // any main function which certainly will need it.
1117 if (FD && ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
1118 CGM.getCodeGenOpts().StackAlignment))
1119 Fn->addFnAttr(Kind: "stackrealign");
1120
1121 // "main" doesn't need to zero out call-used registers.
1122 if (FD && FD->isMain())
1123 Fn->removeFnAttr(Kind: "zero-call-used-regs");
1124
1125 // Add vscale_range attribute if appropriate.
1126 llvm::StringMap<bool> FeatureMap;
1127 auto IsArmStreaming = TargetInfo::ArmStreamingKind::NotStreaming;
1128 if (FD) {
1129 getContext().getFunctionFeatureMap(FeatureMap, FD);
1130 if (const auto *T = FD->getType()->getAs<FunctionProtoType>())
1131 if (T->getAArch64SMEAttributes() &
1132 FunctionType::SME_PStateSMCompatibleMask)
1133 IsArmStreaming = TargetInfo::ArmStreamingKind::StreamingCompatible;
1134
1135 if (IsArmStreamingFunction(FD, IncludeLocallyStreaming: true))
1136 IsArmStreaming = TargetInfo::ArmStreamingKind::Streaming;
1137 }
1138 std::optional<std::pair<unsigned, unsigned>> VScaleRange =
1139 getContext().getTargetInfo().getVScaleRange(LangOpts: getLangOpts(), Mode: IsArmStreaming,
1140 FeatureMap: &FeatureMap);
1141 if (VScaleRange) {
1142 CurFn->addFnAttr(Attr: llvm::Attribute::getWithVScaleRangeArgs(
1143 Context&: getLLVMContext(), MinValue: VScaleRange->first, MaxValue: VScaleRange->second));
1144 }
1145
1146 llvm::BasicBlock *EntryBB = createBasicBlock(name: "entry", parent: CurFn);
1147
1148 // Create a marker to make it easy to insert allocas into the entryblock
1149 // later. Don't create this with the builder, because we don't want it
1150 // folded.
1151 llvm::Value *Poison = llvm::PoisonValue::get(T: Int32Ty);
1152 AllocaInsertPt = new llvm::BitCastInst(Poison, Int32Ty, "allocapt", EntryBB);
1153
1154 ReturnBlock = getJumpDestInCurrentScope(Name: "return");
1155
1156 Builder.SetInsertPoint(EntryBB);
1157
1158 // If we're checking the return value, allocate space for a pointer to a
1159 // precise source location of the checked return statement.
1160 if (requiresReturnValueCheck()) {
1161 ReturnLocation = CreateDefaultAlignTempAlloca(Ty: Int8PtrTy, Name: "return.sloc.ptr");
1162 Builder.CreateStore(Val: llvm::ConstantPointerNull::get(T: Int8PtrTy),
1163 Addr: ReturnLocation);
1164 }
1165
1166 // Emit subprogram debug descriptor.
1167 if (CGDebugInfo *DI = getDebugInfo()) {
1168 // Reconstruct the type from the argument list so that implicit parameters,
1169 // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
1170 // convention.
1171 DI->emitFunctionStart(GD, Loc, ScopeLoc: StartLoc,
1172 FnType: DI->getFunctionType(FD, RetTy, Args), Fn: CurFn,
1173 CurFnIsThunk: CurFuncIsThunk);
1174 }
1175
1176 if (ShouldInstrumentFunction()) {
1177 if (CGM.getCodeGenOpts().InstrumentFunctions)
1178 CurFn->addFnAttr(Kind: "instrument-function-entry", Val: "__cyg_profile_func_enter");
1179 if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
1180 CurFn->addFnAttr(Kind: "instrument-function-entry-inlined",
1181 Val: "__cyg_profile_func_enter");
1182 if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
1183 CurFn->addFnAttr(Kind: "instrument-function-entry-inlined",
1184 Val: "__cyg_profile_func_enter_bare");
1185 }
1186
1187 // Since emitting the mcount call here impacts optimizations such as function
1188 // inlining, we just add an attribute to insert a mcount call in backend.
1189 // The attribute "counting-function" is set to mcount function name which is
1190 // architecture dependent.
1191 if (CGM.getCodeGenOpts().InstrumentForProfiling) {
1192 // Calls to fentry/mcount should not be generated if function has
1193 // the no_instrument_function attribute.
1194 if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
1195 if (CGM.getCodeGenOpts().CallFEntry)
1196 Fn->addFnAttr(Kind: "fentry-call", Val: "true");
1197 else {
1198 Fn->addFnAttr(Kind: "instrument-function-entry-inlined",
1199 Val: getTarget().getMCountName());
1200 }
1201 if (CGM.getCodeGenOpts().MNopMCount) {
1202 if (!CGM.getCodeGenOpts().CallFEntry)
1203 CGM.getDiags().Report(DiagID: diag::err_opt_not_valid_without_opt)
1204 << "-mnop-mcount" << "-mfentry";
1205 Fn->addFnAttr(Kind: "mnop-mcount");
1206 }
1207
1208 if (CGM.getCodeGenOpts().RecordMCount) {
1209 if (!CGM.getCodeGenOpts().CallFEntry)
1210 CGM.getDiags().Report(DiagID: diag::err_opt_not_valid_without_opt)
1211 << "-mrecord-mcount" << "-mfentry";
1212 Fn->addFnAttr(Kind: "mrecord-mcount");
1213 }
1214 }
1215 }
1216
1217 if (CGM.getCodeGenOpts().PackedStack) {
1218 if (getContext().getTargetInfo().getTriple().getArch() !=
1219 llvm::Triple::systemz)
1220 CGM.getDiags().Report(DiagID: diag::err_opt_not_valid_on_target)
1221 << "-mpacked-stack";
1222 Fn->addFnAttr(Kind: "packed-stack");
1223 }
1224
1225 if (!CGM.getCodeGenOpts().ZOSPPA1Name)
1226 Fn->addFnAttr(Kind: "zos-ppa1-name", Val: "");
1227 else if (getContext().getTargetInfo().getTriple().isOSzOS() && FD &&
1228 FD->hasAttr<AsmLabelAttr>()) {
1229 std::string SrcName = CGM.getMangledNameIgnoringAsmLabel(GD, ND: FD);
1230 Fn->addFnAttr(Kind: "zos-ppa1-name", Val: SrcName);
1231 }
1232
1233 if (CGM.getCodeGenOpts().WarnStackSize != UINT_MAX &&
1234 !CGM.getDiags().isIgnored(DiagID: diag::warn_fe_backend_frame_larger_than, Loc))
1235 Fn->addFnAttr(Kind: "warn-stack-size",
1236 Val: std::to_string(val: CGM.getCodeGenOpts().WarnStackSize));
1237
1238 if (RetTy->isVoidType()) {
1239 // Void type; nothing to return.
1240 ReturnValue = Address::invalid();
1241
1242 // Count the implicit return.
1243 if (!endsWithReturn(F: D))
1244 ++NumReturnExprs;
1245 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
1246 // Indirect return; emit returned value directly into sret slot.
1247 // This reduces code size, and affects correctness in C++.
1248 auto AI = CurFn->arg_begin();
1249 if (CurFnInfo->getReturnInfo().isSRetAfterThis())
1250 ++AI;
1251 ReturnValue = makeNaturalAddressForPointer(
1252 Ptr: &*AI, T: RetTy, Alignment: CurFnInfo->getReturnInfo().getIndirectAlign(), ForPointeeType: false,
1253 BaseInfo: nullptr, TBAAInfo: nullptr, IsKnownNonNull: KnownNonNull);
1254 if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
1255 ReturnValuePointer =
1256 CreateDefaultAlignTempAlloca(Ty: ReturnValue.getType(), Name: "result.ptr");
1257 Builder.CreateStore(Val: ReturnValue.emitRawPointer(CGF&: *this),
1258 Addr: ReturnValuePointer);
1259 }
1260 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
1261 !hasScalarEvaluationKind(T: CurFnInfo->getReturnType())) {
1262 // Load the sret pointer from the argument struct and return into that.
1263 unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
1264 llvm::Function::arg_iterator EI = CurFn->arg_end();
1265 --EI;
1266 llvm::Value *Addr = Builder.CreateStructGEP(
1267 Ty: CurFnInfo->getArgStruct(), Ptr: &*EI, Idx);
1268 llvm::Type *Ty =
1269 cast<llvm::GetElementPtrInst>(Val: Addr)->getResultElementType();
1270 ReturnValuePointer = Address(Addr, Ty, getPointerAlign());
1271 Addr = Builder.CreateAlignedLoad(Ty, Addr, Align: getPointerAlign(), Name: "agg.result");
1272 ReturnValue = Address(Addr, ConvertType(T: RetTy),
1273 CGM.getNaturalTypeAlignment(T: RetTy), KnownNonNull);
1274 } else {
1275 ReturnValue = CreateIRTempWithoutCast(T: RetTy, Name: "retval");
1276
1277 // Tell the epilog emitter to autorelease the result. We do this
1278 // now so that various specialized functions can suppress it
1279 // during their IR-generation.
1280 if (getLangOpts().ObjCAutoRefCount &&
1281 !CurFnInfo->isReturnsRetained() &&
1282 RetTy->isObjCRetainableType())
1283 AutoreleaseResult = true;
1284 }
1285
1286 EmitStartEHSpec(D: CurCodeDecl);
1287
1288 PrologueCleanupDepth = EHStack.stable_begin();
1289
1290 // Emit OpenMP specific initialization of the device functions.
1291 if (getLangOpts().OpenMP && CurCodeDecl)
1292 CGM.getOpenMPRuntime().emitFunctionProlog(CGF&: *this, D: CurCodeDecl);
1293
1294 if (FD && getLangOpts().HLSL) {
1295 // Handle emitting HLSL entry functions.
1296 if (FD->hasAttr<HLSLShaderAttr>()) {
1297 CGM.getHLSLRuntime().emitEntryFunction(FD, Fn);
1298 }
1299 }
1300
1301 EmitFunctionProlog(FI: *CurFnInfo, Fn: CurFn, Args);
1302
1303 if (const CXXMethodDecl *MD = dyn_cast_if_present<CXXMethodDecl>(Val: D);
1304 MD && !MD->isStatic()) {
1305 bool IsInLambda =
1306 MD->getParent()->isLambda() && MD->getOverloadedOperator() == OO_Call;
1307 if (MD->isImplicitObjectMemberFunction())
1308 CGM.getCXXABI().EmitInstanceFunctionProlog(CGF&: *this);
1309 if (IsInLambda) {
1310 // We're in a lambda; figure out the captures.
1311 MD->getParent()->getCaptureFields(Captures&: LambdaCaptureFields,
1312 ThisCapture&: LambdaThisCaptureField);
1313 if (LambdaThisCaptureField) {
1314 // If the lambda captures the object referred to by '*this' - either by
1315 // value or by reference, make sure CXXThisValue points to the correct
1316 // object.
1317
1318 // Get the lvalue for the field (which is a copy of the enclosing object
1319 // or contains the address of the enclosing object).
1320 LValue ThisFieldLValue = EmitLValueForLambdaField(Field: LambdaThisCaptureField);
1321 if (!LambdaThisCaptureField->getType()->isPointerType()) {
1322 // If the enclosing object was captured by value, just use its
1323 // address. Sign this pointer.
1324 CXXThisValue = ThisFieldLValue.getPointer(CGF&: *this);
1325 } else {
1326 // Load the lvalue pointed to by the field, since '*this' was captured
1327 // by reference.
1328 CXXThisValue =
1329 EmitLoadOfLValue(V: ThisFieldLValue, Loc: SourceLocation()).getScalarVal();
1330 }
1331 }
1332 for (auto *FD : MD->getParent()->fields()) {
1333 if (FD->hasCapturedVLAType()) {
1334 auto *ExprArg = EmitLoadOfLValue(V: EmitLValueForLambdaField(Field: FD),
1335 Loc: SourceLocation()).getScalarVal();
1336 auto VAT = FD->getCapturedVLAType();
1337 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
1338 }
1339 }
1340 } else if (MD->isImplicitObjectMemberFunction()) {
1341 // Not in a lambda; just use 'this' from the method.
1342 // FIXME: Should we generate a new load for each use of 'this'? The
1343 // fast register allocator would be happier...
1344 CXXThisValue = CXXABIThisValue;
1345 }
1346
1347 // Check the 'this' pointer once per function, if it's available.
1348 if (CXXABIThisValue) {
1349 SanitizerSet SkippedChecks;
1350 SkippedChecks.set(K: SanitizerKind::ObjectSize, Value: true);
1351 QualType ThisTy = MD->getThisType();
1352
1353 // If this is the call operator of a lambda with no captures, it
1354 // may have a static invoker function, which may call this operator with
1355 // a null 'this' pointer.
1356 if (isLambdaCallOperator(MD) && MD->getParent()->isCapturelessLambda())
1357 SkippedChecks.set(K: SanitizerKind::Null, Value: true);
1358
1359 EmitTypeCheck(
1360 TCK: isa<CXXConstructorDecl>(Val: MD) ? TCK_ConstructorCall : TCK_MemberCall,
1361 Loc, V: CXXABIThisValue, Type: ThisTy, Alignment: CXXABIThisAlignment, SkippedChecks);
1362 }
1363 }
1364
1365 // If any of the arguments have a variably modified type, make sure to
1366 // emit the type size, but only if the function is not naked. Naked functions
1367 // have no prolog to run this evaluation.
1368 if (!FD || !FD->hasAttr<NakedAttr>()) {
1369 for (const VarDecl *VD : Args) {
1370 // Dig out the type as written from ParmVarDecls; it's unclear whether
1371 // the standard (C99 6.9.1p10) requires this, but we're following the
1372 // precedent set by gcc.
1373 QualType Ty;
1374 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Val: VD))
1375 Ty = PVD->getOriginalType();
1376 else
1377 Ty = VD->getType();
1378
1379 if (Ty->isVariablyModifiedType())
1380 EmitVariablyModifiedType(Ty);
1381 }
1382 }
1383 // Emit a location at the end of the prologue.
1384 if (CGDebugInfo *DI = getDebugInfo())
1385 DI->EmitLocation(Builder, Loc: StartLoc);
1386 // TODO: Do we need to handle this in two places like we do with
1387 // target-features/target-cpu?
1388 if (CurFuncDecl)
1389 if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
1390 LargestVectorWidth = VecWidth->getVectorWidth();
1391
1392 if (CGM.shouldEmitConvergenceTokens())
1393 ConvergenceTokenStack.push_back(Elt: getOrEmitConvergenceEntryToken(F: CurFn));
1394}
1395
1396void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
1397 incrementProfileCounter(S: Body);
1398 maybeCreateMCDCCondBitmap();
1399 if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Val: Body))
1400 EmitCompoundStmtWithoutScope(S: *S);
1401 else
1402 EmitStmt(S: Body);
1403}
1404
1405/// When instrumenting to collect profile data, the counts for some blocks
1406/// such as switch cases need to not include the fall-through counts, so
1407/// emit a branch around the instrumentation code. When not instrumenting,
1408/// this just calls EmitBlock().
1409void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
1410 const Stmt *S) {
1411 llvm::BasicBlock *SkipCountBB = nullptr;
1412 if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
1413 // When instrumenting for profiling, the fallthrough to certain
1414 // statements needs to skip over the instrumentation code so that we
1415 // get an accurate count.
1416 SkipCountBB = createBasicBlock(name: "skipcount");
1417 EmitBranch(Block: SkipCountBB);
1418 }
1419 EmitBlock(BB);
1420 uint64_t CurrentCount = getCurrentProfileCount();
1421 incrementProfileCounter(ExecSkip: UseExecPath, S);
1422 setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
1423 if (SkipCountBB)
1424 EmitBlock(BB: SkipCountBB);
1425}
1426
1427/// Tries to mark the given function nounwind based on the
1428/// non-existence of any throwing calls within it. We believe this is
1429/// lightweight enough to do at -O0.
1430static void TryMarkNoThrow(llvm::Function *F) {
1431 // LLVM treats 'nounwind' on a function as part of the type, so we
1432 // can't do this on functions that can be overwritten.
1433 if (F->isInterposable()) return;
1434
1435 for (llvm::BasicBlock &BB : *F)
1436 for (llvm::Instruction &I : BB)
1437 if (I.mayThrow())
1438 return;
1439
1440 F->setDoesNotThrow();
1441}
1442
1443QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
1444 FunctionArgList &Args) {
1445 const FunctionDecl *FD = cast<FunctionDecl>(Val: GD.getDecl());
1446 QualType ResTy = FD->getReturnType();
1447
1448 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD);
1449 if (MD && MD->isImplicitObjectMemberFunction()) {
1450 if (CGM.getCXXABI().HasThisReturn(GD))
1451 ResTy = MD->getThisType();
1452 else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
1453 ResTy = CGM.getContext().VoidPtrTy;
1454 CGM.getCXXABI().buildThisParam(CGF&: *this, Params&: Args);
1455 }
1456
1457 // The base version of an inheriting constructor whose constructed base is a
1458 // virtual base is not passed any arguments (because it doesn't actually call
1459 // the inherited constructor).
1460 bool PassedParams = true;
1461 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: FD))
1462 if (auto Inherited = CD->getInheritedConstructor())
1463 PassedParams =
1464 getTypes().inheritingCtorHasParams(Inherited, Type: GD.getCtorType());
1465
1466 if (PassedParams) {
1467 for (auto *Param : FD->parameters()) {
1468 Args.push_back(Elt: Param);
1469 if (!Param->hasAttr<PassObjectSizeAttr>())
1470 continue;
1471
1472 auto *Implicit = ImplicitParamDecl::Create(
1473 C&: getContext(), DC: Param->getDeclContext(), IdLoc: Param->getLocation(),
1474 /*Id=*/nullptr, T: getContext().getSizeType(), ParamKind: ImplicitParamKind::Other);
1475 SizeArguments[Param] = Implicit;
1476 Args.push_back(Elt: Implicit);
1477 }
1478 }
1479
1480 if (MD && (isa<CXXConstructorDecl>(Val: MD) || isa<CXXDestructorDecl>(Val: MD)))
1481 CGM.getCXXABI().addImplicitStructorParams(CGF&: *this, ResTy, Params&: Args);
1482
1483 return ResTy;
1484}
1485
1486void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1487 const CGFunctionInfo &FnInfo) {
1488 assert(Fn && "generating code for null Function");
1489 const FunctionDecl *FD = cast<FunctionDecl>(Val: GD.getDecl());
1490 CurGD = GD;
1491
1492 FunctionArgList Args;
1493 QualType ResTy = BuildFunctionArgList(GD, Args);
1494
1495 CGM.getTargetCodeGenInfo().checkFunctionABI(CGM, Decl: FD);
1496
1497 if (FD->isInlineBuiltinDeclaration()) {
1498 // When generating code for a builtin with an inline declaration, use a
1499 // mangled name to hold the actual body, while keeping an external
1500 // definition in case the function pointer is referenced somewhere.
1501 std::string FDInlineName = (Fn->getName() + ".inline").str();
1502 llvm::Module *M = Fn->getParent();
1503 llvm::Function *Clone = M->getFunction(Name: FDInlineName);
1504 if (!Clone) {
1505 Clone = llvm::Function::Create(Ty: Fn->getFunctionType(),
1506 Linkage: llvm::GlobalValue::InternalLinkage,
1507 AddrSpace: Fn->getAddressSpace(), N: FDInlineName, M);
1508 Clone->addFnAttr(Kind: llvm::Attribute::AlwaysInline);
1509 }
1510 Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
1511 Fn = Clone;
1512 } else {
1513 // Detect the unusual situation where an inline version is shadowed by a
1514 // non-inline version. In that case we should pick the external one
1515 // everywhere. That's GCC behavior too. Unfortunately, I cannot find a way
1516 // to detect that situation before we reach codegen, so do some late
1517 // replacement.
1518 for (const FunctionDecl *PD = FD->getPreviousDecl(); PD;
1519 PD = PD->getPreviousDecl()) {
1520 if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
1521 std::string FDInlineName = (Fn->getName() + ".inline").str();
1522 llvm::Module *M = Fn->getParent();
1523 if (llvm::Function *Clone = M->getFunction(Name: FDInlineName)) {
1524 Clone->replaceAllUsesWith(V: Fn);
1525 Clone->eraseFromParent();
1526 }
1527 break;
1528 }
1529 }
1530 }
1531
1532 // Check if we should generate debug info for this function.
1533 if (FD->hasAttr<NoDebugAttr>()) {
1534 // Clear non-distinct debug info that was possibly attached to the function
1535 // due to an earlier declaration without the nodebug attribute
1536 Fn->setSubprogram(nullptr);
1537 // Disable debug info indefinitely for this function
1538 DebugInfo = nullptr;
1539 }
1540 // Finalize function debug info on exit.
1541 llvm::scope_exit Cleanup([this] {
1542 if (CGDebugInfo *DI = getDebugInfo())
1543 DI->completeFunction();
1544 });
1545
1546 // The function might not have a body if we're generating thunks for a
1547 // function declaration.
1548 SourceRange BodyRange;
1549 if (Stmt *Body = FD->getBody())
1550 BodyRange = Body->getSourceRange();
1551 else
1552 BodyRange = FD->getLocation();
1553 CurEHLocation = BodyRange.getEnd();
1554
1555 // Use the location of the start of the function to determine where
1556 // the function definition is located. By default use the location
1557 // of the declaration as the location for the subprogram. A function
1558 // may lack a declaration in the source code if it is created by code
1559 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1560 SourceLocation Loc = FD->getLocation();
1561
1562 // If this is a function specialization then use the pattern body
1563 // as the location for the function.
1564 if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
1565 if (SpecDecl->hasBody(Definition&: SpecDecl))
1566 Loc = SpecDecl->getLocation();
1567
1568 Stmt *Body = FD->getBody();
1569
1570 if (Body) {
1571 // Coroutines always emit lifetime markers.
1572 if (isa<CoroutineBodyStmt>(Val: Body))
1573 ShouldEmitLifetimeMarkers = true;
1574
1575 // Detect jumps that invalidate lifetime markers or bypass auto-var-init.
1576 bool NeedsBypassDetection =
1577 ShouldEmitLifetimeMarkers ||
1578 (CGM.getLangOpts().getTrivialAutoVarInit() !=
1579 LangOptions::TrivialAutoVarInitKind::Uninitialized);
1580 if (NeedsBypassDetection)
1581 Bypasses.Init(CGM, Body);
1582 }
1583
1584 // Emit the standard function prologue.
1585 StartFunction(GD, RetTy: ResTy, Fn, FnInfo, Args, Loc, StartLoc: BodyRange.getBegin());
1586
1587 // Save parameters for coroutine function.
1588 if (Body && isa_and_nonnull<CoroutineBodyStmt>(Val: Body))
1589 llvm::append_range(C&: FnArgs, R: FD->parameters());
1590
1591 // Ensure that the function adheres to the forward progress guarantee, which
1592 // is required by certain optimizations.
1593 // In C++11 and up, the attribute will be removed if the body contains a
1594 // trivial empty loop.
1595 if (checkIfFunctionMustProgress())
1596 CurFn->addFnAttr(Kind: llvm::Attribute::MustProgress);
1597
1598 // Generate the body of the function.
1599 PGO->assignRegionCounters(GD, Fn: CurFn);
1600 if (isa<CXXDestructorDecl>(Val: FD))
1601 EmitDestructorBody(Args);
1602 else if (isa<CXXConstructorDecl>(Val: FD))
1603 EmitConstructorBody(Args);
1604 else if (getLangOpts().CUDA &&
1605 !getLangOpts().CUDAIsDevice &&
1606 FD->hasAttr<CUDAGlobalAttr>())
1607 CGM.getCUDARuntime().emitDeviceStub(CGF&: *this, Args);
1608 else if (isa<CXXMethodDecl>(Val: FD) &&
1609 cast<CXXMethodDecl>(Val: FD)->isLambdaStaticInvoker()) {
1610 // The lambda static invoker function is special, because it forwards or
1611 // clones the body of the function call operator (but is actually static).
1612 EmitLambdaStaticInvokeBody(MD: cast<CXXMethodDecl>(Val: FD));
1613 } else if (isa<CXXMethodDecl>(Val: FD) &&
1614 isLambdaCallOperator(MD: cast<CXXMethodDecl>(Val: FD)) &&
1615 !FnInfo.isDelegateCall() &&
1616 cast<CXXMethodDecl>(Val: FD)->getParent()->getLambdaStaticInvoker() &&
1617 hasInAllocaArg(MD: cast<CXXMethodDecl>(Val: FD))) {
1618 // If emitting a lambda with static invoker on X86 Windows, change
1619 // the call operator body.
1620 // Make sure that this is a call operator with an inalloca arg and check
1621 // for delegate call to make sure this is the original call op and not the
1622 // new forwarding function for the static invoker.
1623 EmitLambdaInAllocaCallOpBody(MD: cast<CXXMethodDecl>(Val: FD));
1624 } else if (FD->isDefaulted() && isa<CXXMethodDecl>(Val: FD) &&
1625 (cast<CXXMethodDecl>(Val: FD)->isCopyAssignmentOperator() ||
1626 cast<CXXMethodDecl>(Val: FD)->isMoveAssignmentOperator())) {
1627 // Implicit copy-assignment gets the same special treatment as implicit
1628 // copy-constructors.
1629 emitImplicitAssignmentOperatorBody(Args);
1630 } else if (DeviceKernelAttr::isOpenCLSpelling(
1631 A: FD->getAttr<DeviceKernelAttr>()) &&
1632 GD.getKernelReferenceKind() == KernelReferenceKind::Kernel) {
1633 CallArgList CallArgs;
1634 for (unsigned i = 0; i < Args.size(); ++i) {
1635 Address ArgAddr = GetAddrOfLocalVar(VD: Args[i]);
1636 QualType ArgQualType = Args[i]->getType();
1637 RValue ArgRValue = convertTempToRValue(addr: ArgAddr, type: ArgQualType, Loc);
1638 CallArgs.add(rvalue: ArgRValue, type: ArgQualType);
1639 }
1640 GlobalDecl GDStub = GlobalDecl(FD, KernelReferenceKind::Stub);
1641 const FunctionType *FT = cast<FunctionType>(Val: FD->getType());
1642 CGM.getTargetCodeGenInfo().setOCLKernelStubCallingConvention(FT);
1643 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
1644 Args: CallArgs, Ty: FT, /*ChainCall=*/false, ABIInfoFD: getCurrentFunctionDecl());
1645 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(Info: FnInfo);
1646 llvm::Constant *GDStubFunctionPointer =
1647 CGM.getRawFunctionPointer(GD: GDStub, Ty: FTy);
1648 CGCallee GDStubCallee = CGCallee::forDirect(functionPtr: GDStubFunctionPointer, abstractInfo: GDStub);
1649 EmitCall(CallInfo: FnInfo, Callee: GDStubCallee, ReturnValue: ReturnValueSlot(), Args: CallArgs, CallOrInvoke: nullptr, IsMustTail: false,
1650 Loc);
1651 } else if (Body) {
1652 EmitFunctionBody(Body);
1653 } else
1654 llvm_unreachable("no definition for emitted function");
1655
1656 // C++11 [stmt.return]p2:
1657 // Flowing off the end of a function [...] results in undefined behavior in
1658 // a value-returning function.
1659 // C11 6.9.1p12:
1660 // If the '}' that terminates a function is reached, and the value of the
1661 // function call is used by the caller, the behavior is undefined.
1662 if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
1663 !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
1664 bool ShouldEmitUnreachable =
1665 CGM.getCodeGenOpts().StrictReturn ||
1666 !CGM.MayDropFunctionReturn(Context: FD->getASTContext(), ReturnType: FD->getReturnType());
1667 if (SanOpts.has(K: SanitizerKind::Return)) {
1668 auto CheckOrdinal = SanitizerKind::SO_Return;
1669 auto CheckHandler = SanitizerHandler::MissingReturn;
1670 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
1671 llvm::Value *IsFalse = Builder.getFalse();
1672 EmitCheck(Checked: std::make_pair(x&: IsFalse, y&: CheckOrdinal), Check: CheckHandler,
1673 StaticArgs: EmitCheckSourceLocation(Loc: FD->getLocation()), DynamicArgs: {});
1674 } else if (ShouldEmitUnreachable) {
1675 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1676 EmitTrapCall(IntrID: llvm::Intrinsic::trap);
1677 }
1678 if (SanOpts.has(K: SanitizerKind::Return) || ShouldEmitUnreachable) {
1679 Builder.CreateUnreachable();
1680 Builder.ClearInsertionPoint();
1681 }
1682 }
1683
1684 // Emit the standard function epilogue.
1685 FinishFunction(EndLoc: BodyRange.getEnd());
1686
1687 PGO->verifyCounterMap();
1688
1689 if (CurCodeDecl->hasAttr<PersonalityAttr>()) {
1690 StringRef Identifier =
1691 CurCodeDecl->getAttr<PersonalityAttr>()->getRoutine()->getName();
1692 llvm::FunctionCallee PersonalityRoutine =
1693 CGM.CreateRuntimeFunction(Ty: llvm::FunctionType::get(Result: CGM.Int32Ty, isVarArg: true),
1694 Name: Identifier, ExtraAttrs: {}, /*local=*/Local: true);
1695 Fn->setPersonalityFn(cast<llvm::Constant>(Val: PersonalityRoutine.getCallee()));
1696 }
1697
1698 // If we haven't marked the function nothrow through other means, do
1699 // a quick pass now to see if we can.
1700 if (!CurFn->doesNotThrow())
1701 TryMarkNoThrow(F: CurFn);
1702}
1703
1704/// ContainsLabel - Return true if the statement contains a label in it. If
1705/// this statement is not executed normally, it not containing a label means
1706/// that we can just remove the code.
1707bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1708 // Null statement, not a label!
1709 if (!S) return false;
1710
1711 // If this is a label, we have to emit the code, consider something like:
1712 // if (0) { ... foo: bar(); } goto foo;
1713 //
1714 // TODO: If anyone cared, we could track __label__'s, since we know that you
1715 // can't jump to one from outside their declared region.
1716 if (isa<LabelStmt>(Val: S))
1717 return true;
1718
1719 // If this is a case/default statement, and we haven't seen a switch, we have
1720 // to emit the code.
1721 if (isa<SwitchCase>(Val: S) && !IgnoreCaseStmts)
1722 return true;
1723
1724 // If this is a switch statement, we want to ignore cases below it.
1725 if (isa<SwitchStmt>(Val: S))
1726 IgnoreCaseStmts = true;
1727
1728 // Scan subexpressions for verboten labels.
1729 for (const Stmt *SubStmt : S->children())
1730 if (ContainsLabel(S: SubStmt, IgnoreCaseStmts))
1731 return true;
1732
1733 return false;
1734}
1735
1736/// containsBreak - Return true if the statement contains a break out of it.
1737/// If the statement (recursively) contains a switch or loop with a break
1738/// inside of it, this is fine.
1739bool CodeGenFunction::containsBreak(const Stmt *S) {
1740 // Null statement, not a label!
1741 if (!S) return false;
1742
1743 // If this is a switch or loop that defines its own break scope, then we can
1744 // include it and anything inside of it.
1745 if (isa<SwitchStmt>(Val: S) || isa<WhileStmt>(Val: S) || isa<DoStmt>(Val: S) ||
1746 isa<ForStmt>(Val: S))
1747 return false;
1748
1749 if (isa<BreakStmt>(Val: S))
1750 return true;
1751
1752 // Scan subexpressions for verboten breaks.
1753 for (const Stmt *SubStmt : S->children())
1754 if (containsBreak(S: SubStmt))
1755 return true;
1756
1757 return false;
1758}
1759
1760bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
1761 if (!S) return false;
1762
1763 // Some statement kinds add a scope and thus never add a decl to the current
1764 // scope. Note, this list is longer than the list of statements that might
1765 // have an unscoped decl nested within them, but this way is conservatively
1766 // correct even if more statement kinds are added.
1767 if (isa<IfStmt>(Val: S) || isa<SwitchStmt>(Val: S) || isa<WhileStmt>(Val: S) ||
1768 isa<DoStmt>(Val: S) || isa<ForStmt>(Val: S) || isa<CompoundStmt>(Val: S) ||
1769 isa<CXXForRangeStmt>(Val: S) || isa<CXXTryStmt>(Val: S) ||
1770 isa<ObjCForCollectionStmt>(Val: S) || isa<ObjCAtTryStmt>(Val: S))
1771 return false;
1772
1773 if (isa<DeclStmt>(Val: S))
1774 return true;
1775
1776 for (const Stmt *SubStmt : S->children())
1777 if (mightAddDeclToScope(S: SubStmt))
1778 return true;
1779
1780 return false;
1781}
1782
1783/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1784/// to a constant, or if it does but contains a label, return false. If it
1785/// constant folds return true and set the boolean result in Result.
1786bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1787 bool &ResultBool,
1788 bool AllowLabels) {
1789 // If MC/DC is enabled, disable folding so that we can instrument all
1790 // conditions to yield complete test vectors. We still keep track of
1791 // folded conditions during region mapping and visualization.
1792 if (!AllowLabels && CGM.getCodeGenOpts().hasProfileClangInstr() &&
1793 CGM.getCodeGenOpts().MCDCCoverage)
1794 return false;
1795
1796 llvm::APSInt ResultInt;
1797 if (!ConstantFoldsToSimpleInteger(Cond, Result&: ResultInt, AllowLabels))
1798 return false;
1799
1800 ResultBool = ResultInt.getBoolValue();
1801 return true;
1802}
1803
1804/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1805/// to a constant, or if it does but contains a label, return false. If it
1806/// constant folds return true and set the folded value.
1807bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1808 llvm::APSInt &ResultInt,
1809 bool AllowLabels) {
1810 // FIXME: Rename and handle conversion of other evaluatable things
1811 // to bool.
1812 Expr::EvalResult Result;
1813 if (!Cond->EvaluateAsInt(Result, Ctx: getContext()))
1814 return false; // Not foldable, not integer or not fully evaluatable.
1815
1816 llvm::APSInt Int = Result.Val.getInt();
1817 if (!AllowLabels && CodeGenFunction::ContainsLabel(S: Cond))
1818 return false; // Contains a label.
1819
1820 PGO->markStmtMaybeUsed(S: Cond);
1821 ResultInt = std::move(Int);
1822 return true;
1823}
1824
1825/// Strip parentheses and simplistic logical-NOT operators.
1826const Expr *CodeGenFunction::stripCond(const Expr *C) {
1827 while (true) {
1828 const Expr *SC = IgnoreExprNodes(
1829 E: C, Fns&: IgnoreParensSingleStep, Fns&: IgnoreUOpLNotSingleStep,
1830 Fns&: IgnoreBuiltinExpectSingleStep, Fns&: IgnoreImplicitCastsSingleStep);
1831 if (C == SC)
1832 return SC;
1833 C = SC;
1834 }
1835}
1836
1837/// Determine whether the given condition is an instrumentable condition
1838/// (i.e. no "&&" or "||").
1839bool CodeGenFunction::isInstrumentedCondition(const Expr *C) {
1840 const BinaryOperator *BOp = dyn_cast<BinaryOperator>(Val: stripCond(C));
1841 return (!BOp || !BOp->isLogicalOp());
1842}
1843
1844/// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
1845/// increments a profile counter based on the semantics of the given logical
1846/// operator opcode. This is used to instrument branch condition coverage for
1847/// logical operators.
1848void CodeGenFunction::EmitBranchToCounterBlock(
1849 const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock,
1850 llvm::BasicBlock *FalseBlock, uint64_t TrueCount /* = 0 */,
1851 Stmt::Likelihood LH /* =None */, const Expr *CntrIdx /* = nullptr */) {
1852 // If not instrumenting, just emit a branch.
1853 bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
1854 if (!InstrumentRegions || !isInstrumentedCondition(C: Cond))
1855 return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH);
1856
1857 const Stmt *CntrStmt = (CntrIdx ? CntrIdx : Cond);
1858
1859 llvm::BasicBlock *ThenBlock = nullptr;
1860 llvm::BasicBlock *ElseBlock = nullptr;
1861 llvm::BasicBlock *NextBlock = nullptr;
1862
1863 // Create the block we'll use to increment the appropriate counter.
1864 llvm::BasicBlock *CounterIncrBlock = createBasicBlock(name: "lop.rhscnt");
1865
1866 llvm::BasicBlock *SkipIncrBlock =
1867 (hasSkipCounter(S: CntrStmt) ? createBasicBlock(name: "lop.rhsskip") : nullptr);
1868 llvm::BasicBlock *SkipNextBlock = nullptr;
1869
1870 // Set block pointers according to Logical-AND (BO_LAnd) semantics. This
1871 // means we need to evaluate the condition and increment the counter on TRUE:
1872 //
1873 // if (Cond)
1874 // goto CounterIncrBlock;
1875 // else
1876 // goto FalseBlock;
1877 //
1878 // CounterIncrBlock:
1879 // Counter++;
1880 // goto TrueBlock;
1881
1882 if (LOp == BO_LAnd) {
1883 SkipNextBlock = FalseBlock;
1884 ThenBlock = CounterIncrBlock;
1885 ElseBlock = (SkipIncrBlock ? SkipIncrBlock : SkipNextBlock);
1886 NextBlock = TrueBlock;
1887 }
1888
1889 // Set block pointers according to Logical-OR (BO_LOr) semantics. This means
1890 // we need to evaluate the condition and increment the counter on FALSE:
1891 //
1892 // if (Cond)
1893 // goto TrueBlock;
1894 // else
1895 // goto CounterIncrBlock;
1896 //
1897 // CounterIncrBlock:
1898 // Counter++;
1899 // goto FalseBlock;
1900
1901 else if (LOp == BO_LOr) {
1902 SkipNextBlock = TrueBlock;
1903 ThenBlock = (SkipIncrBlock ? SkipIncrBlock : SkipNextBlock);
1904 ElseBlock = CounterIncrBlock;
1905 NextBlock = FalseBlock;
1906 } else {
1907 llvm_unreachable("Expected Opcode must be that of a Logical Operator");
1908 }
1909
1910 // Emit Branch based on condition.
1911 EmitBranchOnBoolExpr(Cond, TrueBlock: ThenBlock, FalseBlock: ElseBlock, TrueCount, LH);
1912
1913 if (SkipIncrBlock) {
1914 EmitBlock(BB: SkipIncrBlock);
1915 incrementProfileCounter(ExecSkip: UseSkipPath, S: CntrStmt);
1916 EmitBranch(Block: SkipNextBlock);
1917 }
1918
1919 // Emit the block containing the counter increment(s).
1920 EmitBlock(BB: CounterIncrBlock);
1921
1922 // Increment corresponding counter; if index not provided, use Cond as index.
1923 incrementProfileCounter(ExecSkip: UseExecPath, S: CntrStmt);
1924
1925 // Go to the next block.
1926 EmitBranch(Block: NextBlock);
1927}
1928
1929/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1930/// statement) to the specified blocks. Based on the condition, this might try
1931/// to simplify the codegen of the conditional based on the branch.
1932/// \param LH The value of the likelihood attribute on the True branch.
1933/// \param ConditionalOp Used by MC/DC code coverage to track the result of the
1934/// ConditionalOperator (ternary) through a recursive call for the operator's
1935/// LHS and RHS nodes.
1936void CodeGenFunction::EmitBranchOnBoolExpr(
1937 const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock,
1938 uint64_t TrueCount, Stmt::Likelihood LH, const Expr *ConditionalOp,
1939 const VarDecl *ConditionalDecl) {
1940 Cond = Cond->IgnoreParens();
1941
1942 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Val: Cond)) {
1943 bool HasSkip = hasSkipCounter(S: CondBOp);
1944
1945 // Handle X && Y in a condition.
1946 if (CondBOp->getOpcode() == BO_LAnd) {
1947 // If we have "1 && X", simplify the code. "0 && X" would have constant
1948 // folded if the case was simple enough.
1949 bool ConstantBool = false;
1950 if (ConstantFoldsToSimpleInteger(Cond: CondBOp->getLHS(), ResultBool&: ConstantBool) &&
1951 ConstantBool) {
1952 // br(1 && X) -> br(X).
1953 incrementProfileCounter(S: CondBOp);
1954 EmitBranchToCounterBlock(Cond: CondBOp->getRHS(), LOp: BO_LAnd, TrueBlock,
1955 FalseBlock, TrueCount, LH);
1956 return;
1957 }
1958
1959 // If we have "X && 1", simplify the code to use an uncond branch.
1960 // "X && 0" would have been constant folded to 0.
1961 if (ConstantFoldsToSimpleInteger(Cond: CondBOp->getRHS(), ResultBool&: ConstantBool) &&
1962 ConstantBool) {
1963 // br(X && 1) -> br(X).
1964 EmitBranchToCounterBlock(Cond: CondBOp->getLHS(), LOp: BO_LAnd, TrueBlock,
1965 FalseBlock, TrueCount, LH, CntrIdx: CondBOp);
1966 return;
1967 }
1968
1969 // Emit the LHS as a conditional. If the LHS conditional is false, we
1970 // want to jump to the FalseBlock.
1971 llvm::BasicBlock *LHSTrue = createBasicBlock(name: "land.lhs.true");
1972 llvm::BasicBlock *LHSFalse =
1973 (HasSkip ? createBasicBlock(name: "land.lhsskip") : FalseBlock);
1974 // The counter tells us how often we evaluate RHS, and all of TrueCount
1975 // can be propagated to that branch.
1976 uint64_t RHSCount = getProfileCount(S: CondBOp->getRHS());
1977
1978 ConditionalEvaluation eval(*this);
1979 {
1980 ApplyDebugLocation DL(*this, Cond);
1981 // Propagate the likelihood attribute like __builtin_expect
1982 // __builtin_expect(X && Y, 1) -> X and Y are likely
1983 // __builtin_expect(X && Y, 0) -> only Y is unlikely
1984 EmitBranchOnBoolExpr(Cond: CondBOp->getLHS(), TrueBlock: LHSTrue, FalseBlock: LHSFalse, TrueCount: RHSCount,
1985 LH: LH == Stmt::LH_Unlikely ? Stmt::LH_None : LH);
1986 if (HasSkip) {
1987 EmitBlock(BB: LHSFalse);
1988 incrementProfileCounter(ExecSkip: UseSkipPath, S: CondBOp);
1989 EmitBranch(Block: FalseBlock);
1990 }
1991 EmitBlock(BB: LHSTrue);
1992 }
1993
1994 incrementProfileCounter(ExecSkip: UseExecPath, S: CondBOp);
1995 setCurrentProfileCount(getProfileCount(S: CondBOp->getRHS()));
1996
1997 // Any temporaries created here are conditional.
1998 eval.begin(CGF&: *this);
1999 EmitBranchToCounterBlock(Cond: CondBOp->getRHS(), LOp: BO_LAnd, TrueBlock,
2000 FalseBlock, TrueCount, LH);
2001 eval.end(CGF&: *this);
2002 return;
2003 }
2004
2005 if (CondBOp->getOpcode() == BO_LOr) {
2006 // If we have "0 || X", simplify the code. "1 || X" would have constant
2007 // folded if the case was simple enough.
2008 bool ConstantBool = false;
2009 if (ConstantFoldsToSimpleInteger(Cond: CondBOp->getLHS(), ResultBool&: ConstantBool) &&
2010 !ConstantBool) {
2011 // br(0 || X) -> br(X).
2012 incrementProfileCounter(S: CondBOp);
2013 EmitBranchToCounterBlock(Cond: CondBOp->getRHS(), LOp: BO_LOr, TrueBlock,
2014 FalseBlock, TrueCount, LH);
2015 return;
2016 }
2017
2018 // If we have "X || 0", simplify the code to use an uncond branch.
2019 // "X || 1" would have been constant folded to 1.
2020 if (ConstantFoldsToSimpleInteger(Cond: CondBOp->getRHS(), ResultBool&: ConstantBool) &&
2021 !ConstantBool) {
2022 // br(X || 0) -> br(X).
2023 EmitBranchToCounterBlock(Cond: CondBOp->getLHS(), LOp: BO_LOr, TrueBlock,
2024 FalseBlock, TrueCount, LH, CntrIdx: CondBOp);
2025 return;
2026 }
2027 // Emit the LHS as a conditional. If the LHS conditional is true, we
2028 // want to jump to the TrueBlock.
2029 llvm::BasicBlock *LHSTrue =
2030 (HasSkip ? createBasicBlock(name: "lor.lhsskip") : TrueBlock);
2031 llvm::BasicBlock *LHSFalse = createBasicBlock(name: "lor.lhs.false");
2032 // We have the count for entry to the RHS and for the whole expression
2033 // being true, so we can divy up True count between the short circuit and
2034 // the RHS.
2035 uint64_t LHSCount =
2036 getCurrentProfileCount() - getProfileCount(S: CondBOp->getRHS());
2037 uint64_t RHSCount = TrueCount - LHSCount;
2038
2039 ConditionalEvaluation eval(*this);
2040 {
2041 // Propagate the likelihood attribute like __builtin_expect
2042 // __builtin_expect(X || Y, 1) -> only Y is likely
2043 // __builtin_expect(X || Y, 0) -> both X and Y are unlikely
2044 ApplyDebugLocation DL(*this, Cond);
2045 EmitBranchOnBoolExpr(Cond: CondBOp->getLHS(), TrueBlock: LHSTrue, FalseBlock: LHSFalse, TrueCount: LHSCount,
2046 LH: LH == Stmt::LH_Likely ? Stmt::LH_None : LH);
2047 if (HasSkip) {
2048 EmitBlock(BB: LHSTrue);
2049 incrementProfileCounter(ExecSkip: UseSkipPath, S: CondBOp);
2050 EmitBranch(Block: TrueBlock);
2051 }
2052 EmitBlock(BB: LHSFalse);
2053 }
2054
2055 incrementProfileCounter(ExecSkip: UseExecPath, S: CondBOp);
2056 setCurrentProfileCount(getProfileCount(S: CondBOp->getRHS()));
2057
2058 // Any temporaries created here are conditional.
2059 eval.begin(CGF&: *this);
2060 EmitBranchToCounterBlock(Cond: CondBOp->getRHS(), LOp: BO_LOr, TrueBlock, FalseBlock,
2061 TrueCount: RHSCount, LH);
2062
2063 eval.end(CGF&: *this);
2064 return;
2065 }
2066 }
2067
2068 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Val: Cond)) {
2069 // br(!x, t, f) -> br(x, f, t)
2070 // Avoid doing this optimization when instrumenting a condition for MC/DC.
2071 // LNot is taken as part of the condition for simplicity, and changing its
2072 // sense negatively impacts test vector tracking.
2073 bool MCDCCondition = CGM.getCodeGenOpts().hasProfileClangInstr() &&
2074 CGM.getCodeGenOpts().MCDCCoverage &&
2075 isInstrumentedCondition(C: Cond);
2076 if (CondUOp->getOpcode() == UO_LNot && !MCDCCondition) {
2077 // Negate the count.
2078 uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
2079 // The values of the enum are chosen to make this negation possible.
2080 LH = static_cast<Stmt::Likelihood>(-LH);
2081 // Negate the condition and swap the destination blocks.
2082 return EmitBranchOnBoolExpr(Cond: CondUOp->getSubExpr(), TrueBlock: FalseBlock, FalseBlock: TrueBlock,
2083 TrueCount: FalseCount, LH);
2084 }
2085 }
2086
2087 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Val: Cond)) {
2088 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
2089 llvm::BasicBlock *LHSBlock = createBasicBlock(name: "cond.true");
2090 llvm::BasicBlock *RHSBlock = createBasicBlock(name: "cond.false");
2091
2092 // The ConditionalOperator itself has no likelihood information for its
2093 // true and false branches. This matches the behavior of __builtin_expect.
2094 ConditionalEvaluation cond(*this);
2095 EmitBranchOnBoolExpr(Cond: CondOp->getCond(), TrueBlock: LHSBlock, FalseBlock: RHSBlock,
2096 TrueCount: getProfileCount(S: CondOp), LH: Stmt::LH_None);
2097
2098 // When computing PGO branch weights, we only know the overall count for
2099 // the true block. This code is essentially doing tail duplication of the
2100 // naive code-gen, introducing new edges for which counts are not
2101 // available. Divide the counts proportionally between the LHS and RHS of
2102 // the conditional operator.
2103 uint64_t LHSScaledTrueCount = 0;
2104 if (TrueCount) {
2105 double LHSRatio =
2106 getProfileCount(S: CondOp) / (double)getCurrentProfileCount();
2107 LHSScaledTrueCount = TrueCount * LHSRatio;
2108 }
2109
2110 cond.begin(CGF&: *this);
2111 EmitBlock(BB: LHSBlock);
2112 incrementProfileCounter(ExecSkip: UseExecPath, S: CondOp);
2113 {
2114 ApplyDebugLocation DL(*this, Cond);
2115 EmitBranchOnBoolExpr(Cond: CondOp->getLHS(), TrueBlock, FalseBlock,
2116 TrueCount: LHSScaledTrueCount, LH, ConditionalOp: CondOp);
2117 }
2118 cond.end(CGF&: *this);
2119
2120 cond.begin(CGF&: *this);
2121 EmitBlock(BB: RHSBlock);
2122 incrementProfileCounter(ExecSkip: UseSkipPath, S: CondOp);
2123 EmitBranchOnBoolExpr(Cond: CondOp->getRHS(), TrueBlock, FalseBlock,
2124 TrueCount: TrueCount - LHSScaledTrueCount, LH, ConditionalOp: CondOp);
2125 cond.end(CGF&: *this);
2126
2127 return;
2128 }
2129
2130 if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Val: Cond)) {
2131 // Conditional operator handling can give us a throw expression as a
2132 // condition for a case like:
2133 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
2134 // Fold this to:
2135 // br(c, throw x, br(y, t, f))
2136 EmitCXXThrowExpr(E: Throw, /*KeepInsertionPoint*/false);
2137 return;
2138 }
2139
2140 // Emit the code with the fully general case.
2141 llvm::Value *CondV;
2142 {
2143 ApplyDebugLocation DL(*this, Cond);
2144 CondV = EvaluateExprAsBool(E: Cond);
2145 }
2146
2147 MaybeEmitDeferredVarDeclInit(var: ConditionalDecl);
2148
2149 // If not at the top of the logical operator nest, update MCDC temp with the
2150 // boolean result of the evaluated condition.
2151 {
2152 const Expr *MCDCBaseExpr = Cond;
2153 // When a nested ConditionalOperator (ternary) is encountered in a boolean
2154 // expression, MC/DC tracks the result of the ternary, and this is tied to
2155 // the ConditionalOperator expression and not the ternary's LHS or RHS. If
2156 // this is the case, the ConditionalOperator expression is passed through
2157 // the ConditionalOp parameter and then used as the MCDC base expression.
2158 if (ConditionalOp)
2159 MCDCBaseExpr = ConditionalOp;
2160
2161 if (isMCDCBranchExpr(E: stripCond(C: MCDCBaseExpr)) &&
2162 !isMCDCDecisionExpr(E: stripCond(C: Cond)))
2163 maybeUpdateMCDCCondBitmap(E: MCDCBaseExpr, Val: CondV);
2164 }
2165
2166 llvm::MDNode *Weights = nullptr;
2167 llvm::MDNode *Unpredictable = nullptr;
2168
2169 // If the branch has a condition wrapped by __builtin_unpredictable,
2170 // create metadata that specifies that the branch is unpredictable.
2171 // Don't bother if not optimizing because that metadata would not be used.
2172 auto *Call = dyn_cast<CallExpr>(Val: Cond->IgnoreImpCasts());
2173 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
2174 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: Call->getCalleeDecl());
2175 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
2176 llvm::MDBuilder MDHelper(getLLVMContext());
2177 Unpredictable = MDHelper.createUnpredictable();
2178 }
2179 }
2180
2181 // If there is a Likelihood knowledge for the cond, lower it.
2182 // Note that if not optimizing this won't emit anything.
2183 llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(Cond: CondV, LH);
2184 if (CondV != NewCondV)
2185 CondV = NewCondV;
2186 else {
2187 // Otherwise, lower profile counts. Note that we do this even at -O0.
2188 uint64_t CurrentCount = std::max(a: getCurrentProfileCount(), b: TrueCount);
2189 Weights = createProfileWeights(TrueCount, FalseCount: CurrentCount - TrueCount);
2190 }
2191
2192 llvm::Instruction *BrInst = Builder.CreateCondBr(Cond: CondV, True: TrueBlock, False: FalseBlock,
2193 BranchWeights: Weights, Unpredictable);
2194 addInstToNewSourceAtom(KeyInstruction: BrInst, Backup: CondV);
2195
2196 switch (HLSLControlFlowAttr) {
2197 case HLSLControlFlowHintAttr::Microsoft_branch:
2198 case HLSLControlFlowHintAttr::Microsoft_flatten: {
2199 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
2200
2201 llvm::ConstantInt *BranchHintConstant =
2202 HLSLControlFlowAttr ==
2203 HLSLControlFlowHintAttr::Spelling::Microsoft_branch
2204 ? llvm::ConstantInt::get(Ty: CGM.Int32Ty, V: 1)
2205 : llvm::ConstantInt::get(Ty: CGM.Int32Ty, V: 2);
2206
2207 SmallVector<llvm::Metadata *, 2> Vals(
2208 {MDHelper.createString(Str: "hlsl.controlflow.hint"),
2209 MDHelper.createConstant(C: BranchHintConstant)});
2210 BrInst->setMetadata(Kind: "hlsl.controlflow.hint",
2211 Node: llvm::MDNode::get(Context&: CGM.getLLVMContext(), MDs: Vals));
2212 break;
2213 }
2214 // This is required to avoid warnings during compilation
2215 case HLSLControlFlowHintAttr::SpellingNotCalculated:
2216 break;
2217 }
2218}
2219
2220llvm::Value *CodeGenFunction::EmitScalarOrConstFoldImmArg(unsigned ICEArguments,
2221 unsigned Idx,
2222 const CallExpr *E) {
2223 llvm::Value *Arg = nullptr;
2224 if ((ICEArguments & (1 << Idx)) == 0) {
2225 Arg = EmitScalarExpr(E: E->getArg(Arg: Idx));
2226 } else {
2227 // If this is required to be a constant, constant fold it so that we
2228 // know that the generated intrinsic gets a ConstantInt.
2229 std::optional<llvm::APSInt> Result =
2230 E->getArg(Arg: Idx)->getIntegerConstantExpr(Ctx: getContext());
2231 assert(Result && "Expected argument to be a constant");
2232 Arg = llvm::ConstantInt::get(Context&: getLLVMContext(), V: *Result);
2233 }
2234 return Arg;
2235}
2236
2237/// ErrorUnsupported - Print out an error that codegen doesn't support the
2238/// specified stmt yet.
2239void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
2240 CGM.ErrorUnsupported(S, Type);
2241}
2242
2243/// emitNonZeroVLAInit - Emit the "zero" initialization of a
2244/// variable-length array whose elements have a non-zero bit-pattern.
2245///
2246/// \param baseType the inner-most element type of the array
2247/// \param src - a char* pointing to the bit-pattern for a single
2248/// base element of the array
2249/// \param sizeInChars - the total size of the VLA, in chars
2250static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
2251 Address dest, Address src,
2252 llvm::Value *sizeInChars) {
2253 CGBuilderTy &Builder = CGF.Builder;
2254
2255 CharUnits baseSize = CGF.getContext().getTypeSizeInChars(T: baseType);
2256 llvm::Value *baseSizeInChars
2257 = llvm::ConstantInt::get(Ty: CGF.IntPtrTy, V: baseSize.getQuantity());
2258
2259 Address begin = dest.withElementType(ElemTy: CGF.Int8Ty);
2260 llvm::Value *end = Builder.CreateInBoundsGEP(Ty: begin.getElementType(),
2261 Ptr: begin.emitRawPointer(CGF),
2262 IdxList: sizeInChars, Name: "vla.end");
2263
2264 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
2265 llvm::BasicBlock *loopBB = CGF.createBasicBlock(name: "vla-init.loop");
2266 llvm::BasicBlock *contBB = CGF.createBasicBlock(name: "vla-init.cont");
2267
2268 // Make a loop over the VLA. C99 guarantees that the VLA element
2269 // count must be nonzero.
2270 CGF.EmitBlock(BB: loopBB);
2271
2272 llvm::PHINode *cur = Builder.CreatePHI(Ty: begin.getType(), NumReservedValues: 2, Name: "vla.cur");
2273 cur->addIncoming(V: begin.emitRawPointer(CGF), BB: originBB);
2274
2275 CharUnits curAlign =
2276 dest.getAlignment().alignmentOfArrayElement(elementSize: baseSize);
2277
2278 // memcpy the individual element bit-pattern.
2279 Builder.CreateMemCpy(Dest: Address(cur, CGF.Int8Ty, curAlign), Src: src, Size: baseSizeInChars,
2280 /*volatile*/ IsVolatile: false);
2281
2282 // Go to the next element.
2283 llvm::Value *next =
2284 Builder.CreateInBoundsGEP(Ty: CGF.Int8Ty, Ptr: cur, IdxList: baseSizeInChars, Name: "vla.next");
2285
2286 // Leave if that's the end of the VLA.
2287 llvm::Value *done = Builder.CreateICmpEQ(LHS: next, RHS: end, Name: "vla-init.isdone");
2288 Builder.CreateCondBr(Cond: done, True: contBB, False: loopBB);
2289 cur->addIncoming(V: next, BB: loopBB);
2290
2291 CGF.EmitBlock(BB: contBB);
2292}
2293
2294Address CodeGenFunction::EmitAddressOfPFPField(Address RecordPtr,
2295 const PFPField &Field) {
2296 return EmitAddressOfPFPField(
2297 RecordPtr,
2298 FieldPtr: Builder.CreateConstInBoundsByteGEP(Addr: RecordPtr.withElementType(ElemTy: Int8Ty),
2299 Offset: Field.Offset),
2300 Field: Field.Field);
2301}
2302
2303Address CodeGenFunction::EmitAddressOfPFPField(Address RecordPtr,
2304 Address PtrPtr,
2305 const FieldDecl *Field) {
2306 llvm::Value *Disc;
2307 if (CGM.getContext().arePFPFieldsTriviallyCopyable(RD: Field->getParent())) {
2308 uint64_t FieldSignature =
2309 llvm::getPointerAuthStableSipHash(S: CGM.getPFPFieldName(FD: Field));
2310 Disc = llvm::ConstantInt::get(Ty: CGM.Int64Ty, V: FieldSignature);
2311 } else
2312 Disc = Builder.CreatePtrToInt(V: RecordPtr.getBasePointer(), DestTy: CGM.Int64Ty);
2313
2314 llvm::GlobalValue *DS = CGM.getPFPDeactivationSymbol(FD: Field);
2315 llvm::OperandBundleDef DSBundle("deactivation-symbol", DS);
2316 llvm::Value *Args[] = {PtrPtr.getBasePointer(), Disc, Builder.getTrue()};
2317 return Address(
2318 Builder.CreateCall(Callee: CGM.getIntrinsic(IID: llvm::Intrinsic::protected_field_ptr,
2319 Tys: PtrPtr.getType()),
2320 Args, OpBundles: DSBundle),
2321 VoidPtrTy, PtrPtr.getAlignment());
2322}
2323
2324void
2325CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
2326 // Ignore empty classes in C++.
2327 if (getLangOpts().CPlusPlus)
2328 if (const auto *RD = Ty->getAsCXXRecordDecl(); RD && RD->isEmpty())
2329 return;
2330
2331 if (DestPtr.getElementType() != Int8Ty)
2332 DestPtr = DestPtr.withElementType(ElemTy: Int8Ty);
2333
2334 // Get size and alignment info for this aggregate.
2335 CharUnits size = getContext().getTypeSizeInChars(T: Ty);
2336
2337 llvm::Value *SizeVal;
2338 const VariableArrayType *vla;
2339
2340 // Don't bother emitting a zero-byte memset.
2341 if (size.isZero()) {
2342 // But note that getTypeInfo returns 0 for a VLA.
2343 if (const VariableArrayType *vlaType =
2344 dyn_cast_or_null<VariableArrayType>(
2345 Val: getContext().getAsArrayType(T: Ty))) {
2346 auto VlaSize = getVLASize(vla: vlaType);
2347 SizeVal = VlaSize.NumElts;
2348 CharUnits eltSize = getContext().getTypeSizeInChars(T: VlaSize.Type);
2349 if (!eltSize.isOne())
2350 SizeVal = Builder.CreateNUWMul(LHS: SizeVal, RHS: CGM.getSize(numChars: eltSize));
2351 vla = vlaType;
2352 } else {
2353 return;
2354 }
2355 } else {
2356 SizeVal = CGM.getSize(numChars: size);
2357 vla = nullptr;
2358 }
2359
2360 // If the type contains a pointer to data member we can't memset it to zero.
2361 // Instead, create a null constant and copy it to the destination.
2362 // TODO: there are other patterns besides zero that we can usefully memset,
2363 // like -1, which happens to be the pattern used by member-pointers.
2364 if (!CGM.getTypes().isZeroInitializable(T: Ty)) {
2365 // For a VLA, emit a single element, then splat that over the VLA.
2366 if (vla) Ty = getContext().getBaseElementType(VAT: vla);
2367
2368 llvm::Constant *NullConstant = CGM.EmitNullConstant(T: Ty);
2369
2370 llvm::GlobalVariable *NullVariable =
2371 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
2372 /*isConstant=*/true,
2373 llvm::GlobalVariable::PrivateLinkage,
2374 NullConstant, Twine());
2375 CharUnits NullAlign = DestPtr.getAlignment();
2376 NullVariable->setAlignment(NullAlign.getAsAlign());
2377 Address SrcPtr(NullVariable, Builder.getInt8Ty(), NullAlign);
2378
2379 if (vla) return emitNonZeroVLAInit(CGF&: *this, baseType: Ty, dest: DestPtr, src: SrcPtr, sizeInChars: SizeVal);
2380
2381 // Get and call the appropriate llvm.memcpy overload.
2382 Builder.CreateMemCpy(Dest: DestPtr, Src: SrcPtr, Size: SizeVal, IsVolatile: false);
2383 } else {
2384 // Otherwise, just memset the whole thing to zero. This is legal
2385 // because in LLVM, all default initializers (other than the ones we just
2386 // handled above, and the case handled below) are guaranteed to have a bit
2387 // pattern of all zeros.
2388 Builder.CreateMemSet(Dest: DestPtr, Value: Builder.getInt8(C: 0), Size: SizeVal, IsVolatile: false);
2389 }
2390
2391 // With the pointer field protection feature, null pointers do not have a bit
2392 // pattern of zero in memory, so we must initialize them separately.
2393 for (auto &Field : getContext().findPFPFields(Ty)) {
2394 auto addr = EmitAddressOfPFPField(RecordPtr: DestPtr, Field);
2395 Builder.CreateStore(Val: llvm::ConstantPointerNull::get(T: VoidPtrTy), Addr: addr);
2396 }
2397}
2398
2399llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
2400 // Make sure that there is a block for the indirect goto.
2401 if (!IndirectBranch)
2402 GetIndirectGotoBlock();
2403
2404 llvm::BasicBlock *BB = getJumpDestForLabel(S: L).getBlock();
2405
2406 // Make sure the indirect branch includes all of the address-taken blocks.
2407 IndirectBranch->addDestination(Dest: BB);
2408 return llvm::BlockAddress::get(Ty: CurFn->getType(), BB);
2409}
2410
2411llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
2412 // If we already made the indirect branch for indirect goto, return its block.
2413 if (IndirectBranch) return IndirectBranch->getParent();
2414
2415 CGBuilderTy TmpBuilder(CGM, createBasicBlock(name: "indirectgoto"));
2416
2417 // Create the PHI node that indirect gotos will add entries to.
2418 llvm::Value *DestVal = TmpBuilder.CreatePHI(Ty: Int8PtrTy, NumReservedValues: 0,
2419 Name: "indirect.goto.dest");
2420
2421 // Create the indirect branch instruction.
2422 IndirectBranch = TmpBuilder.CreateIndirectBr(Addr: DestVal);
2423 return IndirectBranch->getParent();
2424}
2425
2426/// Computes the length of an array in elements, as well as the base
2427/// element type and a properly-typed first element pointer.
2428llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
2429 QualType &baseType,
2430 Address &addr) {
2431 const ArrayType *arrayType = origArrayType;
2432
2433 // If it's a VLA, we have to load the stored size. Note that
2434 // this is the size of the VLA in bytes, not its size in elements.
2435 llvm::Value *numVLAElements = nullptr;
2436 if (isa<VariableArrayType>(Val: arrayType)) {
2437 numVLAElements = getVLASize(vla: cast<VariableArrayType>(Val: arrayType)).NumElts;
2438
2439 // Walk into all VLAs. This doesn't require changes to addr,
2440 // which has type T* where T is the first non-VLA element type.
2441 do {
2442 QualType elementType = arrayType->getElementType();
2443 arrayType = getContext().getAsArrayType(T: elementType);
2444
2445 // If we only have VLA components, 'addr' requires no adjustment.
2446 if (!arrayType) {
2447 baseType = elementType;
2448 return numVLAElements;
2449 }
2450 } while (isa<VariableArrayType>(Val: arrayType));
2451
2452 // We get out here only if we find a constant array type
2453 // inside the VLA.
2454 }
2455
2456 // We have some number of constant-length arrays, so addr should
2457 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
2458 // down to the first element of addr.
2459 SmallVector<llvm::Value*, 8> gepIndices;
2460
2461 // GEP down to the array type.
2462 llvm::ConstantInt *zero = Builder.getInt32(C: 0);
2463 gepIndices.push_back(Elt: zero);
2464
2465 uint64_t countFromCLAs = 1;
2466 QualType eltType;
2467
2468 llvm::ArrayType *llvmArrayType =
2469 dyn_cast<llvm::ArrayType>(Val: addr.getElementType());
2470 while (llvmArrayType) {
2471 assert(isa<ConstantArrayType>(arrayType));
2472 assert(cast<ConstantArrayType>(arrayType)->getZExtSize() ==
2473 llvmArrayType->getNumElements());
2474
2475 gepIndices.push_back(Elt: zero);
2476 countFromCLAs *= llvmArrayType->getNumElements();
2477 eltType = arrayType->getElementType();
2478
2479 llvmArrayType =
2480 dyn_cast<llvm::ArrayType>(Val: llvmArrayType->getElementType());
2481 arrayType = getContext().getAsArrayType(T: arrayType->getElementType());
2482 assert((!llvmArrayType || arrayType) &&
2483 "LLVM and Clang types are out-of-synch");
2484 }
2485
2486 if (arrayType) {
2487 // From this point onwards, the Clang array type has been emitted
2488 // as some other type (probably a packed struct). Compute the array
2489 // size, and just emit the 'begin' expression as a bitcast.
2490 while (arrayType) {
2491 countFromCLAs *= cast<ConstantArrayType>(Val: arrayType)->getZExtSize();
2492 eltType = arrayType->getElementType();
2493 arrayType = getContext().getAsArrayType(T: eltType);
2494 }
2495
2496 llvm::Type *baseType = ConvertType(T: eltType);
2497 addr = addr.withElementType(ElemTy: baseType);
2498 } else {
2499 // Create the actual GEP.
2500 addr = Address(Builder.CreateInBoundsGEP(Ty: addr.getElementType(),
2501 Ptr: addr.emitRawPointer(CGF&: *this),
2502 IdxList: gepIndices, Name: "array.begin"),
2503 ConvertTypeForMem(T: eltType), addr.getAlignment());
2504 }
2505
2506 baseType = eltType;
2507
2508 llvm::Value *numElements
2509 = llvm::ConstantInt::get(Ty: SizeTy, V: countFromCLAs);
2510
2511 // If we had any VLA dimensions, factor them in.
2512 if (numVLAElements)
2513 numElements = Builder.CreateNUWMul(LHS: numVLAElements, RHS: numElements);
2514
2515 return numElements;
2516}
2517
2518CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
2519 const VariableArrayType *vla = getContext().getAsVariableArrayType(T: type);
2520 assert(vla && "type was not a variable array type!");
2521 return getVLASize(vla);
2522}
2523
2524CodeGenFunction::VlaSizePair
2525CodeGenFunction::getVLASize(const VariableArrayType *type) {
2526 // The number of elements so far; always size_t.
2527 llvm::Value *numElements = nullptr;
2528
2529 QualType elementType;
2530 do {
2531 elementType = type->getElementType();
2532 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
2533 assert(vlaSize && "no size for VLA!");
2534 assert(vlaSize->getType() == SizeTy);
2535
2536 if (!numElements) {
2537 numElements = vlaSize;
2538 } else {
2539 // It's undefined behavior if this wraps around, so mark it that way.
2540 // FIXME: Teach -fsanitize=undefined to trap this.
2541 numElements = Builder.CreateNUWMul(LHS: numElements, RHS: vlaSize);
2542 }
2543 } while ((type = getContext().getAsVariableArrayType(T: elementType)));
2544
2545 return { numElements, elementType };
2546}
2547
2548CodeGenFunction::VlaSizePair
2549CodeGenFunction::getVLAElements1D(QualType type) {
2550 const VariableArrayType *vla = getContext().getAsVariableArrayType(T: type);
2551 assert(vla && "type was not a variable array type!");
2552 return getVLAElements1D(vla);
2553}
2554
2555CodeGenFunction::VlaSizePair
2556CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
2557 llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
2558 assert(VlaSize && "no size for VLA!");
2559 assert(VlaSize->getType() == SizeTy);
2560 return { VlaSize, Vla->getElementType() };
2561}
2562
2563void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
2564 assert(type->isVariablyModifiedType() &&
2565 "Must pass variably modified type to EmitVLASizes!");
2566
2567 EnsureInsertPoint();
2568
2569 // We're going to walk down into the type and look for VLA
2570 // expressions.
2571 do {
2572 assert(type->isVariablyModifiedType());
2573
2574 const Type *ty = type.getTypePtr();
2575 switch (ty->getTypeClass()) {
2576
2577#define TYPE(Class, Base)
2578#define ABSTRACT_TYPE(Class, Base)
2579#define NON_CANONICAL_TYPE(Class, Base)
2580#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2581#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
2582#include "clang/AST/TypeNodes.inc"
2583 llvm_unreachable("unexpected dependent type!");
2584
2585 // These types are never variably-modified.
2586 case Type::Builtin:
2587 case Type::Complex:
2588 case Type::Vector:
2589 case Type::ExtVector:
2590 case Type::ConstantMatrix:
2591 case Type::Record:
2592 case Type::Enum:
2593 case Type::Using:
2594 case Type::TemplateSpecialization:
2595 case Type::ObjCTypeParam:
2596 case Type::ObjCObject:
2597 case Type::ObjCInterface:
2598 case Type::ObjCObjectPointer:
2599 case Type::BitInt:
2600 case Type::HLSLInlineSpirv:
2601 case Type::PredefinedSugar:
2602 llvm_unreachable("type class is never variably-modified!");
2603
2604 case Type::Adjusted:
2605 type = cast<AdjustedType>(Val: ty)->getAdjustedType();
2606 break;
2607
2608 case Type::Decayed:
2609 type = cast<DecayedType>(Val: ty)->getPointeeType();
2610 break;
2611
2612 case Type::Pointer:
2613 type = cast<PointerType>(Val: ty)->getPointeeType();
2614 break;
2615
2616 case Type::BlockPointer:
2617 type = cast<BlockPointerType>(Val: ty)->getPointeeType();
2618 break;
2619
2620 case Type::LValueReference:
2621 case Type::RValueReference:
2622 type = cast<ReferenceType>(Val: ty)->getPointeeType();
2623 break;
2624
2625 case Type::MemberPointer:
2626 type = cast<MemberPointerType>(Val: ty)->getPointeeType();
2627 break;
2628
2629 case Type::ArrayParameter:
2630 case Type::ConstantArray:
2631 case Type::IncompleteArray:
2632 // Losing element qualification here is fine.
2633 type = cast<ArrayType>(Val: ty)->getElementType();
2634 break;
2635
2636 case Type::VariableArray: {
2637 // Losing element qualification here is fine.
2638 const VariableArrayType *vat = cast<VariableArrayType>(Val: ty);
2639
2640 // Unknown size indication requires no size computation.
2641 // Otherwise, evaluate and record it.
2642 if (const Expr *sizeExpr = vat->getSizeExpr()) {
2643 // It's possible that we might have emitted this already,
2644 // e.g. with a typedef and a pointer to it.
2645 llvm::Value *&entry = VLASizeMap[sizeExpr];
2646 if (!entry) {
2647 llvm::Value *size = EmitScalarExpr(E: sizeExpr);
2648
2649 // C11 6.7.6.2p5:
2650 // If the size is an expression that is not an integer constant
2651 // expression [...] each time it is evaluated it shall have a value
2652 // greater than zero.
2653 if (SanOpts.has(K: SanitizerKind::VLABound)) {
2654 auto CheckOrdinal = SanitizerKind::SO_VLABound;
2655 auto CheckHandler = SanitizerHandler::VLABoundNotPositive;
2656 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
2657 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: size->getType());
2658 clang::QualType SEType = sizeExpr->getType();
2659 llvm::Value *CheckCondition =
2660 SEType->isSignedIntegerType()
2661 ? Builder.CreateICmpSGT(LHS: size, RHS: Zero)
2662 : Builder.CreateICmpUGT(LHS: size, RHS: Zero);
2663 llvm::Constant *StaticArgs[] = {
2664 EmitCheckSourceLocation(Loc: sizeExpr->getBeginLoc()),
2665 EmitCheckTypeDescriptor(T: SEType)};
2666 EmitCheck(Checked: std::make_pair(x&: CheckCondition, y&: CheckOrdinal),
2667 Check: CheckHandler, StaticArgs, DynamicArgs: size);
2668 }
2669
2670 // Always zexting here would be wrong if it weren't
2671 // undefined behavior to have a negative bound.
2672 // FIXME: What about when size's type is larger than size_t?
2673 entry = Builder.CreateIntCast(V: size, DestTy: SizeTy, /*signed*/ isSigned: false);
2674 }
2675 }
2676 type = vat->getElementType();
2677 break;
2678 }
2679
2680 case Type::FunctionProto:
2681 case Type::FunctionNoProto:
2682 type = cast<FunctionType>(Val: ty)->getReturnType();
2683 break;
2684
2685 case Type::Paren:
2686 case Type::TypeOf:
2687 case Type::UnaryTransform:
2688 case Type::Attributed:
2689 case Type::BTFTagAttributed:
2690 case Type::OverflowBehavior:
2691 case Type::HLSLAttributedResource:
2692 case Type::SubstTemplateTypeParm:
2693 case Type::MacroQualified:
2694 case Type::CountAttributed:
2695 case Type::LateParsedAttr:
2696 // Keep walking after single level desugaring.
2697 type = type.getSingleStepDesugaredType(Context: getContext());
2698 break;
2699
2700 case Type::Typedef:
2701 case Type::Decltype:
2702 case Type::Auto:
2703 case Type::DeducedTemplateSpecialization:
2704 case Type::PackIndexing:
2705 // Stop walking: nothing to do.
2706 return;
2707
2708 case Type::TypeOfExpr:
2709 // Stop walking: emit typeof expression.
2710 EmitIgnoredExpr(E: cast<TypeOfExprType>(Val: ty)->getUnderlyingExpr());
2711 return;
2712
2713 case Type::Atomic:
2714 type = cast<AtomicType>(Val: ty)->getValueType();
2715 break;
2716
2717 case Type::Pipe:
2718 type = cast<PipeType>(Val: ty)->getElementType();
2719 break;
2720 }
2721 } while (type->isVariablyModifiedType());
2722}
2723
2724Address CodeGenFunction::EmitVAListRef(const Expr* E) {
2725 if (getContext().getBuiltinVaListType()->isArrayType())
2726 return EmitPointerWithAlignment(Addr: E);
2727 return EmitLValue(E).getAddress();
2728}
2729
2730Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
2731 return EmitLValue(E).getAddress();
2732}
2733
2734Address CodeGenFunction::EmitZOSVAListRef(const Expr *E) {
2735 return EmitPointerWithAlignment(Addr: E);
2736}
2737
2738void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
2739 const APValue &Init) {
2740 assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
2741 if (CGDebugInfo *Dbg = getDebugInfo())
2742 if (CGM.getCodeGenOpts().hasReducedDebugInfo())
2743 Dbg->EmitGlobalVariable(VD: E->getDecl(), Init);
2744}
2745
2746CodeGenFunction::PeepholeProtection
2747CodeGenFunction::protectFromPeepholes(RValue rvalue) {
2748 // At the moment, the only aggressive peephole we do in IR gen
2749 // is trunc(zext) folding, but if we add more, we can easily
2750 // extend this protection.
2751
2752 if (!rvalue.isScalar()) return PeepholeProtection();
2753 llvm::Value *value = rvalue.getScalarVal();
2754 if (!isa<llvm::ZExtInst>(Val: value)) return PeepholeProtection();
2755
2756 // Just make an extra bitcast.
2757 assert(HaveInsertPoint());
2758 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
2759 Builder.GetInsertBlock());
2760
2761 PeepholeProtection protection;
2762 protection.Inst = inst;
2763 return protection;
2764}
2765
2766void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
2767 if (!protection.Inst) return;
2768
2769 // In theory, we could try to duplicate the peepholes now, but whatever.
2770 protection.Inst->eraseFromParent();
2771}
2772
2773void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2774 QualType Ty, SourceLocation Loc,
2775 SourceLocation AssumptionLoc,
2776 llvm::Value *Alignment,
2777 llvm::Value *OffsetValue) {
2778 if (Alignment->getType() != IntPtrTy)
2779 Alignment =
2780 Builder.CreateIntCast(V: Alignment, DestTy: IntPtrTy, isSigned: false, Name: "casted.align");
2781 if (OffsetValue && OffsetValue->getType() != IntPtrTy)
2782 OffsetValue =
2783 Builder.CreateIntCast(V: OffsetValue, DestTy: IntPtrTy, isSigned: true, Name: "casted.offset");
2784 llvm::Value *TheCheck = nullptr;
2785 if (SanOpts.has(K: SanitizerKind::Alignment)) {
2786 llvm::Value *PtrIntValue =
2787 Builder.CreatePtrToInt(V: PtrValue, DestTy: IntPtrTy, Name: "ptrint");
2788
2789 if (OffsetValue) {
2790 bool IsOffsetZero = false;
2791 if (const auto *CI = dyn_cast<llvm::ConstantInt>(Val: OffsetValue))
2792 IsOffsetZero = CI->isZero();
2793
2794 if (!IsOffsetZero)
2795 PtrIntValue = Builder.CreateSub(LHS: PtrIntValue, RHS: OffsetValue, Name: "offsetptr");
2796 }
2797
2798 llvm::Value *Zero = llvm::ConstantInt::get(Ty: IntPtrTy, V: 0);
2799 llvm::Value *Mask =
2800 Builder.CreateSub(LHS: Alignment, RHS: llvm::ConstantInt::get(Ty: IntPtrTy, V: 1));
2801 llvm::Value *MaskedPtr = Builder.CreateAnd(LHS: PtrIntValue, RHS: Mask, Name: "maskedptr");
2802 TheCheck = Builder.CreateICmpEQ(LHS: MaskedPtr, RHS: Zero, Name: "maskcond");
2803 }
2804 llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
2805 DL: CGM.getDataLayout(), PtrValue, Alignment, OffsetValue);
2806
2807 if (!SanOpts.has(K: SanitizerKind::Alignment))
2808 return;
2809 emitAlignmentAssumptionCheck(Ptr: PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2810 OffsetValue, TheCheck, Assumption);
2811}
2812
2813void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2814 const Expr *E,
2815 SourceLocation AssumptionLoc,
2816 llvm::Value *Alignment,
2817 llvm::Value *OffsetValue) {
2818 QualType Ty = E->getType();
2819 SourceLocation Loc = E->getExprLoc();
2820
2821 emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2822 OffsetValue);
2823}
2824
2825llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
2826 llvm::Value *AnnotatedVal,
2827 StringRef AnnotationStr,
2828 SourceLocation Location,
2829 const AnnotateAttr *Attr) {
2830 SmallVector<llvm::Value *, 5> Args = {
2831 AnnotatedVal,
2832 CGM.EmitAnnotationString(Str: AnnotationStr),
2833 CGM.EmitAnnotationUnit(Loc: Location),
2834 CGM.EmitAnnotationLineNo(L: Location),
2835 };
2836 if (Attr)
2837 Args.push_back(Elt: CGM.EmitAnnotationArgs(Attr));
2838 return Builder.CreateCall(Callee: AnnotationFn, Args);
2839}
2840
2841void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
2842 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2843 for (const auto *I : D->specific_attrs<AnnotateAttr>())
2844 EmitAnnotationCall(AnnotationFn: CGM.getIntrinsic(IID: llvm::Intrinsic::var_annotation,
2845 Tys: {V->getType(), CGM.ConstGlobalsPtrTy}),
2846 AnnotatedVal: V, AnnotationStr: I->getAnnotation(), Location: D->getLocation(), Attr: I);
2847}
2848
2849Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
2850 Address Addr) {
2851 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2852 llvm::Value *V = Addr.emitRawPointer(CGF&: *this);
2853 llvm::Type *VTy = V->getType();
2854 auto *PTy = dyn_cast<llvm::PointerType>(Val: VTy);
2855 unsigned AS = PTy ? PTy->getAddressSpace() : 0;
2856 llvm::PointerType *IntrinTy =
2857 llvm::PointerType::get(C&: CGM.getLLVMContext(), AddressSpace: AS);
2858 llvm::Function *F = CGM.getIntrinsic(IID: llvm::Intrinsic::ptr_annotation,
2859 Tys: {IntrinTy, CGM.ConstGlobalsPtrTy});
2860
2861 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2862 // FIXME Always emit the cast inst so we can differentiate between
2863 // annotation on the first field of a struct and annotation on the struct
2864 // itself.
2865 if (VTy != IntrinTy)
2866 V = Builder.CreateBitCast(V, DestTy: IntrinTy);
2867 V = EmitAnnotationCall(AnnotationFn: F, AnnotatedVal: V, AnnotationStr: I->getAnnotation(), Location: D->getLocation(), Attr: I);
2868 V = Builder.CreateBitCast(V, DestTy: VTy);
2869 }
2870
2871 return Address(V, Addr.getElementType(), Addr.getAlignment());
2872}
2873
2874CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
2875
2876CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
2877 : CGF(CGF) {
2878 assert(!CGF->IsSanitizerScope);
2879 CGF->IsSanitizerScope = true;
2880}
2881
2882CodeGenFunction::SanitizerScope::~SanitizerScope() {
2883 CGF->IsSanitizerScope = false;
2884}
2885
2886void CodeGenFunction::InsertHelper(llvm::Instruction *I,
2887 const llvm::Twine &Name,
2888 llvm::BasicBlock::iterator InsertPt) const {
2889 LoopStack.InsertHelper(I);
2890 if (IsSanitizerScope)
2891 I->setNoSanitizeMetadata();
2892}
2893
2894void CGBuilderInserter::InsertHelper(
2895 llvm::Instruction *I, const llvm::Twine &Name,
2896 llvm::BasicBlock::iterator InsertPt) const {
2897 llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, InsertPt);
2898 if (CGF)
2899 CGF->InsertHelper(I, Name, InsertPt);
2900}
2901
2902// Emits an error if we don't have a valid set of target features for the
2903// called function.
2904void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
2905 const FunctionDecl *TargetDecl) {
2906 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: CurCodeDecl);
2907 CodeGenUtils::checkTargetFeatures(Ctx&: CGM.getContext(), Diags&: CGM.getDiags(),
2908 LangOpts: getLangOpts(), E, Caller: FD, TargetDecl);
2909}
2910
2911// Emits an error if we don't have a valid set of target features for the
2912// called function.
2913void CodeGenFunction::checkTargetFeatures(SourceLocation Loc,
2914 const FunctionDecl *TargetDecl) {
2915 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: CurCodeDecl);
2916 CodeGenUtils::checkTargetFeatures(Ctx&: CGM.getContext(), Diags&: CGM.getDiags(),
2917 LangOpts: getLangOpts(), Loc, Caller: FD, TargetDecl);
2918}
2919
2920void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2921 if (!CGM.getCodeGenOpts().SanitizeStats)
2922 return;
2923
2924 llvm::IRBuilder<> IRB(Builder.GetInsertPoint());
2925 IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2926 CGM.getSanStats().create(B&: IRB, SK: SSK);
2927}
2928
2929void CodeGenFunction::EmitKCFIOperandBundle(
2930 const CGCallee &Callee, SmallVectorImpl<llvm::OperandBundleDef> &Bundles) {
2931 const CGCalleeInfo &CI = Callee.getAbstractInfo();
2932 const FunctionProtoType *FP = CI.getCalleeFunctionProtoType();
2933 if (!FP)
2934 return;
2935
2936 StringRef Salt;
2937 if (const auto &Info = FP->getExtraAttributeInfo())
2938 Salt = Info.CFISalt;
2939
2940 Bundles.emplace_back(Args: "kcfi", Args: CGM.CreateKCFITypeId(T: FP->desugar(), Salt));
2941}
2942
2943llvm::Value *
2944CodeGenFunction::FormAArch64ResolverCondition(const FMVResolverOption &RO) {
2945 return RO.Features.empty() ? nullptr : EmitAArch64CpuSupports(FeatureStrs: RO.Features);
2946}
2947
2948llvm::Value *
2949CodeGenFunction::FormX86ResolverCondition(const FMVResolverOption &RO) {
2950 llvm::Value *Condition = nullptr;
2951
2952 if (RO.Architecture) {
2953 StringRef Arch = *RO.Architecture;
2954 // If arch= specifies an x86-64 micro-architecture level, test the feature
2955 // with __builtin_cpu_supports, otherwise use __builtin_cpu_is.
2956 if (Arch.starts_with(Prefix: "x86-64"))
2957 Condition = EmitX86CpuSupports(FeatureStrs: {Arch});
2958 else
2959 Condition = EmitX86CpuIs(CPUStr: Arch);
2960 }
2961
2962 if (!RO.Features.empty()) {
2963 llvm::Value *FeatureCond = EmitX86CpuSupports(FeatureStrs: RO.Features);
2964 Condition =
2965 Condition ? Builder.CreateAnd(LHS: Condition, RHS: FeatureCond) : FeatureCond;
2966 }
2967 return Condition;
2968}
2969
2970static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
2971 llvm::Function *Resolver,
2972 CGBuilderTy &Builder,
2973 llvm::Function *FuncToReturn,
2974 bool SupportsIFunc) {
2975 if (SupportsIFunc) {
2976 Builder.CreateRet(V: FuncToReturn);
2977 return;
2978 }
2979
2980 llvm::SmallVector<llvm::Value *, 10> Args(
2981 llvm::make_pointer_range(Range: Resolver->args()));
2982
2983 llvm::CallInst *Result = Builder.CreateCall(Callee: FuncToReturn, Args);
2984 Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2985
2986 if (Resolver->getReturnType()->isVoidTy())
2987 Builder.CreateRetVoid();
2988 else
2989 Builder.CreateRet(V: Result);
2990}
2991
2992void CodeGenFunction::EmitMultiVersionResolver(
2993 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
2994 llvm::SaveAndRestore<llvm::Function *> savedCurFn(CurFn, Resolver);
2995 llvm::Triple::ArchType ArchType =
2996 getContext().getTargetInfo().getTriple().getArch();
2997
2998 switch (ArchType) {
2999 case llvm::Triple::x86:
3000 case llvm::Triple::x86_64:
3001 EmitX86MultiVersionResolver(Resolver, Options);
3002 return;
3003 case llvm::Triple::aarch64:
3004 EmitAArch64MultiVersionResolver(Resolver, Options);
3005 return;
3006 case llvm::Triple::riscv32:
3007 case llvm::Triple::riscv64:
3008 case llvm::Triple::riscv32be:
3009 case llvm::Triple::riscv64be:
3010 EmitRISCVMultiVersionResolver(Resolver, Options);
3011 return;
3012 case llvm::Triple::ppc:
3013 case llvm::Triple::ppc64:
3014 if (getContext().getTargetInfo().getTriple().isOSAIX()) {
3015 EmitPPCAIXMultiVersionResolver(Resolver, Options);
3016 return;
3017 }
3018 [[fallthrough]];
3019 default:
3020 assert(false &&
3021 "Only implemented for x86, AArch64, RISC-V, and PowerPC AIX");
3022 }
3023}
3024
3025/**
3026 * define internal ptr @foo.resolver() {
3027 * entry:
3028 * %is_version_1 = __builtin_cpu_supports(version_1)
3029 * br i1 %1, label %if.version_1, label %if.else_2
3030 *
3031 * if.version_1:
3032 * ret ptr @foo.version_1
3033 *
3034 * if.else_2:
3035 * %is_version_2 = __builtin_cpu_supports(version_2)
3036 * ...
3037 * if.else: ; preds = %entry
3038 * ret ptr @foo.default
3039 * }
3040 */
3041void CodeGenFunction::EmitPPCAIXMultiVersionResolver(
3042 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3043
3044 // entry:
3045 llvm::BasicBlock *CurBlock = createBasicBlock(name: "entry", parent: Resolver);
3046
3047 SmallVector<std::pair<llvm::Value *, llvm::BasicBlock *>, 3> PhiArgs;
3048 for (const FMVResolverOption &RO : Options) {
3049 Builder.SetInsertPoint(CurBlock);
3050 // The 'default' or 'generic' case.
3051 if (!RO.Architecture && RO.Features.empty()) {
3052 // if.else:
3053 // ret ptr @foo.default
3054 assert(&RO == Options.end() - 1 &&
3055 "Default or Generic case must be last");
3056 Builder.CreateRet(V: RO.Function);
3057 return;
3058 }
3059 // if.else_n:
3060 // %is_version_n = __builtin_cpu_supports(version_n)
3061 // br i1 %is_version_n, label %if.version_n, label %if.else_n+1
3062 //
3063 // if.version_n:
3064 // ret ptr @foo_version_n
3065 assert(RO.Features.size() == 1 &&
3066 "for now one feature requirement per version");
3067
3068 StringRef FeatureStr = RO.Features[0];
3069 StringRef BuiltinCpuSupportsArg;
3070 bool IsNegated = false;
3071
3072 if (FeatureStr.starts_with(Prefix: "cpu=")) {
3073 // CPU specification - map to ISA level
3074 StringRef CPU = FeatureStr.split(Separator: "=").second.trim();
3075 BuiltinCpuSupportsArg = llvm::StringSwitch<StringRef>(CPU)
3076#define PPC_AIX_CLONES_CPU(CPU_NAME, AIX_BUILTIN_CPU_SUPPORTS_NAME, _) \
3077 .Case(CPU_NAME, AIX_BUILTIN_CPU_SUPPORTS_NAME)
3078#include "llvm/TargetParser/PPCTargetParser.def"
3079 .Default(Value: "error");
3080 } else {
3081 // Feature strings arrive here already normalized:
3082 // - Positive features: just the name (e.g., "altivec")
3083 // - Negated features: "no-" prefix (e.g., "no-altivec")
3084 if (FeatureStr.starts_with(Prefix: "no-")) {
3085 IsNegated = true;
3086 FeatureStr = FeatureStr.drop_front(N: 3);
3087 }
3088
3089 // Map feature names to __builtin_cpu_supports() strings
3090 BuiltinCpuSupportsArg =
3091 llvm::StringSwitch<StringRef>(FeatureStr)
3092#define PPC_AIX_CLONES_FEATURE(FEATURE_NAME, AIX_BUILTIN_CPU_SUPPORTS_NAME, _, \
3093 __) \
3094 .Case(FEATURE_NAME, AIX_BUILTIN_CPU_SUPPORTS_NAME)
3095#include "llvm/TargetParser/PPCTargetParser.def"
3096 // Features without runtime checks return empty string
3097 .Default(Value: "");
3098
3099 // All features in target_clones must have runtime detection
3100 assert(!BuiltinCpuSupportsArg.empty() &&
3101 "Feature without runtime detection should have been rejected in "
3102 "Sema");
3103 }
3104
3105 assert(getContext().getTargetInfo().validateCpuSupports(
3106 BuiltinCpuSupportsArg));
3107
3108 llvm::Value *Condition =
3109 EmitPPCBuiltinCpu(BuiltinID: Builtin::BI__builtin_cpu_supports,
3110 ReturnType: Builder.getInt1Ty(), CPUStr: BuiltinCpuSupportsArg);
3111
3112 // Negate the condition if this is a negated feature
3113 if (IsNegated) {
3114 Condition = Builder.CreateNot(V: Condition, Name: "neg");
3115 }
3116
3117 llvm::BasicBlock *ThenBlock = createBasicBlock(name: "if.version", parent: Resolver);
3118 CurBlock = createBasicBlock(name: "if.else", parent: Resolver);
3119 Builder.CreateCondBr(Cond: Condition, True: ThenBlock, False: CurBlock);
3120
3121 Builder.SetInsertPoint(ThenBlock);
3122 Builder.CreateRet(V: RO.Function);
3123 }
3124
3125 llvm_unreachable("Default case missing");
3126}
3127
3128void CodeGenFunction::EmitRISCVMultiVersionResolver(
3129 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3130
3131 if (getContext().getTargetInfo().getTriple().getOS() !=
3132 llvm::Triple::OSType::Linux) {
3133 CGM.getDiags().Report(DiagID: diag::err_os_unsupport_riscv_fmv);
3134 return;
3135 }
3136
3137 llvm::BasicBlock *CurBlock = createBasicBlock(name: "resolver_entry", parent: Resolver);
3138 Builder.SetInsertPoint(CurBlock);
3139 EmitRISCVCpuInit();
3140
3141 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
3142 bool HasDefault = false;
3143 unsigned DefaultIndex = 0;
3144
3145 // Check the each candidate function.
3146 for (unsigned Index = 0; Index < Options.size(); Index++) {
3147
3148 if (Options[Index].Features.empty()) {
3149 HasDefault = true;
3150 DefaultIndex = Index;
3151 continue;
3152 }
3153
3154 Builder.SetInsertPoint(CurBlock);
3155
3156 // FeaturesCondition: The bitmask of the required extension has been
3157 // enabled by the runtime object.
3158 // (__riscv_feature_bits.features[i] & REQUIRED_BITMASK) ==
3159 // REQUIRED_BITMASK
3160 //
3161 // When condition is met, return this version of the function.
3162 // Otherwise, try the next version.
3163 //
3164 // if (FeaturesConditionVersion1)
3165 // return Version1;
3166 // else if (FeaturesConditionVersion2)
3167 // return Version2;
3168 // else if (FeaturesConditionVersion3)
3169 // return Version3;
3170 // ...
3171 // else
3172 // return DefaultVersion;
3173
3174 // TODO: Add a condition to check the length before accessing elements.
3175 // Without checking the length first, we may access an incorrect memory
3176 // address when using different versions.
3177 llvm::SmallVector<StringRef, 8> CurrTargetAttrFeats;
3178 llvm::SmallVector<std::string, 8> TargetAttrFeats;
3179
3180 for (StringRef Feat : Options[Index].Features) {
3181 std::vector<std::string> FeatStr =
3182 getContext().getTargetInfo().parseTargetAttr(Str: Feat).Features;
3183
3184 assert(FeatStr.size() == 1 && "Feature string not delimited");
3185
3186 std::string &CurrFeat = FeatStr.front();
3187 if (CurrFeat[0] == '+')
3188 TargetAttrFeats.push_back(Elt: CurrFeat.substr(pos: 1));
3189 }
3190
3191 if (TargetAttrFeats.empty())
3192 continue;
3193
3194 for (std::string &Feat : TargetAttrFeats)
3195 CurrTargetAttrFeats.push_back(Elt: Feat);
3196
3197 Builder.SetInsertPoint(CurBlock);
3198 llvm::Value *FeatsCondition = EmitRISCVCpuSupports(FeaturesStrs: CurrTargetAttrFeats);
3199
3200 llvm::BasicBlock *RetBlock = createBasicBlock(name: "resolver_return", parent: Resolver);
3201 CGBuilderTy RetBuilder(CGM, RetBlock);
3202 CreateMultiVersionResolverReturn(CGM, Resolver, Builder&: RetBuilder,
3203 FuncToReturn: Options[Index].Function, SupportsIFunc);
3204 llvm::BasicBlock *ElseBlock = createBasicBlock(name: "resolver_else", parent: Resolver);
3205
3206 Builder.SetInsertPoint(CurBlock);
3207 Builder.CreateCondBr(Cond: FeatsCondition, True: RetBlock, False: ElseBlock);
3208
3209 CurBlock = ElseBlock;
3210 }
3211
3212 // Finally, emit the default one.
3213 if (HasDefault) {
3214 Builder.SetInsertPoint(CurBlock);
3215 CreateMultiVersionResolverReturn(
3216 CGM, Resolver, Builder, FuncToReturn: Options[DefaultIndex].Function, SupportsIFunc);
3217 return;
3218 }
3219
3220 // If no generic/default, emit an unreachable.
3221 Builder.SetInsertPoint(CurBlock);
3222 EmitTrapCallAndMakeUnreachable();
3223}
3224
3225void CodeGenFunction::EmitAArch64MultiVersionResolver(
3226 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3227 assert(!Options.empty() && "No multiversion resolver options found");
3228 assert(Options.back().Features.size() == 0 && "Default case must be last");
3229 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
3230 assert(SupportsIFunc &&
3231 "Multiversion resolver requires target IFUNC support");
3232 bool AArch64CpuInitialized = false;
3233 llvm::BasicBlock *CurBlock = createBasicBlock(name: "resolver_entry", parent: Resolver);
3234
3235 for (const FMVResolverOption &RO : Options) {
3236 // Skip unreachable versions.
3237 if (RO.Function == nullptr)
3238 continue;
3239
3240 Builder.SetInsertPoint(CurBlock);
3241 llvm::Value *Condition = FormAArch64ResolverCondition(RO);
3242
3243 // The 'default' or 'all features enabled' case.
3244 if (!Condition) {
3245 CreateMultiVersionResolverReturn(CGM, Resolver, Builder, FuncToReturn: RO.Function,
3246 SupportsIFunc);
3247 return;
3248 }
3249
3250 if (!AArch64CpuInitialized) {
3251 Builder.SetInsertPoint(CurBlock->begin());
3252 EmitAArch64CpuInit();
3253 AArch64CpuInitialized = true;
3254 Builder.SetInsertPoint(CurBlock);
3255 }
3256
3257 llvm::BasicBlock *RetBlock = createBasicBlock(name: "resolver_return", parent: Resolver);
3258 CGBuilderTy RetBuilder(CGM, RetBlock);
3259 CreateMultiVersionResolverReturn(CGM, Resolver, Builder&: RetBuilder, FuncToReturn: RO.Function,
3260 SupportsIFunc);
3261 CurBlock = createBasicBlock(name: "resolver_else", parent: Resolver);
3262 Builder.CreateCondBr(Cond: Condition, True: RetBlock, False: CurBlock);
3263 }
3264
3265 // If no default, emit an unreachable.
3266 Builder.SetInsertPoint(CurBlock);
3267 EmitTrapCallAndMakeUnreachable();
3268}
3269
3270void CodeGenFunction::EmitX86MultiVersionResolver(
3271 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3272
3273 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
3274
3275 // Main function's basic block.
3276 llvm::BasicBlock *CurBlock = createBasicBlock(name: "resolver_entry", parent: Resolver);
3277 Builder.SetInsertPoint(CurBlock);
3278 EmitX86CpuInit();
3279
3280 for (const FMVResolverOption &RO : Options) {
3281 Builder.SetInsertPoint(CurBlock);
3282 llvm::Value *Condition = FormX86ResolverCondition(RO);
3283
3284 // The 'default' or 'generic' case.
3285 if (!Condition) {
3286 assert(&RO == Options.end() - 1 &&
3287 "Default or Generic case must be last");
3288 CreateMultiVersionResolverReturn(CGM, Resolver, Builder, FuncToReturn: RO.Function,
3289 SupportsIFunc);
3290 return;
3291 }
3292
3293 llvm::BasicBlock *RetBlock = createBasicBlock(name: "resolver_return", parent: Resolver);
3294 CGBuilderTy RetBuilder(CGM, RetBlock);
3295 CreateMultiVersionResolverReturn(CGM, Resolver, Builder&: RetBuilder, FuncToReturn: RO.Function,
3296 SupportsIFunc);
3297 CurBlock = createBasicBlock(name: "resolver_else", parent: Resolver);
3298 Builder.CreateCondBr(Cond: Condition, True: RetBlock, False: CurBlock);
3299 }
3300
3301 // If no generic/default, emit an unreachable.
3302 Builder.SetInsertPoint(CurBlock);
3303 EmitTrapCallAndMakeUnreachable();
3304}
3305
3306// Loc - where the diagnostic will point, where in the source code this
3307// alignment has failed.
3308// SecondaryLoc - if present (will be present if sufficiently different from
3309// Loc), the diagnostic will additionally point a "Note:" to this location.
3310// It should be the location where the __attribute__((assume_aligned))
3311// was written e.g.
3312void CodeGenFunction::emitAlignmentAssumptionCheck(
3313 llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
3314 SourceLocation SecondaryLoc, llvm::Value *Alignment,
3315 llvm::Value *OffsetValue, llvm::Value *TheCheck,
3316 llvm::Instruction *Assumption) {
3317 assert(isa_and_nonnull<llvm::CallInst>(Assumption) &&
3318 cast<llvm::CallInst>(Assumption)->getCalledOperand() ==
3319 llvm::Intrinsic::getOrInsertDeclaration(Builder.getModule(),
3320 llvm::Intrinsic::assume) &&
3321 "Assumption should be a call to llvm.assume().");
3322 assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
3323 "Assumption should be the last instruction of the basic block, "
3324 "since the basic block is still being generated.");
3325
3326 if (!SanOpts.has(K: SanitizerKind::Alignment))
3327 return;
3328
3329 // Don't check pointers to volatile data. The behavior here is implementation-
3330 // defined.
3331 if (Ty->getPointeeType().isVolatileQualified())
3332 return;
3333
3334 // We need to temorairly remove the assumption so we can insert the
3335 // sanitizer check before it, else the check will be dropped by optimizations.
3336 Assumption->removeFromParent();
3337
3338 {
3339 auto CheckOrdinal = SanitizerKind::SO_Alignment;
3340 auto CheckHandler = SanitizerHandler::AlignmentAssumption;
3341 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
3342
3343 if (!OffsetValue)
3344 OffsetValue = Builder.getInt1(V: false); // no offset.
3345
3346 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
3347 EmitCheckSourceLocation(Loc: SecondaryLoc),
3348 EmitCheckTypeDescriptor(T: Ty)};
3349 llvm::Value *DynamicData[] = {Ptr, Alignment, OffsetValue};
3350 EmitCheck(Checked: {std::make_pair(x&: TheCheck, y&: CheckOrdinal)}, Check: CheckHandler,
3351 StaticArgs: StaticData, DynamicArgs: DynamicData);
3352 }
3353
3354 // We are now in the (new, empty) "cont" basic block.
3355 // Reintroduce the assumption.
3356 Builder.Insert(I: Assumption);
3357 // FIXME: Assumption still has it's original basic block as it's Parent.
3358}
3359
3360llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
3361 if (CGDebugInfo *DI = getDebugInfo())
3362 return DI->SourceLocToDebugLoc(Loc: Location);
3363
3364 return llvm::DebugLoc();
3365}
3366
3367llvm::Value *
3368CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
3369 Stmt::Likelihood LH) {
3370 switch (LH) {
3371 case Stmt::LH_None:
3372 return Cond;
3373 case Stmt::LH_Likely:
3374 case Stmt::LH_Unlikely:
3375 // Don't generate llvm.expect on -O0 as the backend won't use it for
3376 // anything.
3377 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
3378 return Cond;
3379 llvm::Type *CondTy = Cond->getType();
3380 assert(CondTy->isIntegerTy(1) && "expecting condition to be a boolean");
3381 llvm::Function *FnExpect =
3382 CGM.getIntrinsic(IID: llvm::Intrinsic::expect, Tys: CondTy);
3383 llvm::Value *ExpectedValueOfCond =
3384 llvm::ConstantInt::getBool(Ty: CondTy, V: LH == Stmt::LH_Likely);
3385 return Builder.CreateCall(Callee: FnExpect, Args: {Cond, ExpectedValueOfCond},
3386 Name: Cond->getName() + ".expval");
3387 }
3388 llvm_unreachable("Unknown Likelihood");
3389}
3390
3391llvm::Value *CodeGenFunction::emitBoolVecConversion(llvm::Value *SrcVec,
3392 unsigned NumElementsDst,
3393 const llvm::Twine &Name) {
3394 auto *SrcTy = cast<llvm::FixedVectorType>(Val: SrcVec->getType());
3395 unsigned NumElementsSrc = SrcTy->getNumElements();
3396 if (NumElementsSrc == NumElementsDst)
3397 return SrcVec;
3398
3399 std::vector<int> ShuffleMask(NumElementsDst, -1);
3400 for (unsigned MaskIdx = 0;
3401 MaskIdx < std::min<>(a: NumElementsDst, b: NumElementsSrc); ++MaskIdx)
3402 ShuffleMask[MaskIdx] = MaskIdx;
3403
3404 return Builder.CreateShuffleVector(V: SrcVec, Mask: ShuffleMask, Name);
3405}
3406
3407void CodeGenFunction::EmitPointerAuthOperandBundle(
3408 const CGPointerAuthInfo &PointerAuth,
3409 SmallVectorImpl<llvm::OperandBundleDef> &Bundles) {
3410 if (!PointerAuth.isSigned())
3411 return;
3412
3413 auto *Key = Builder.getInt32(C: PointerAuth.getKey());
3414
3415 llvm::Value *Discriminator = PointerAuth.getDiscriminator();
3416 if (!Discriminator)
3417 Discriminator = Builder.getSize(N: 0);
3418
3419 llvm::Value *Args[] = {Key, Discriminator};
3420 Bundles.emplace_back(Args: "ptrauth", Args);
3421}
3422
3423static llvm::Value *EmitPointerAuthCommon(CodeGenFunction &CGF,
3424 const CGPointerAuthInfo &PointerAuth,
3425 llvm::Value *Pointer,
3426 unsigned IntrinsicID) {
3427 if (!PointerAuth)
3428 return Pointer;
3429
3430 auto Key = CGF.Builder.getInt32(C: PointerAuth.getKey());
3431
3432 llvm::Value *Discriminator = PointerAuth.getDiscriminator();
3433 if (!Discriminator) {
3434 Discriminator = CGF.Builder.getSize(N: 0);
3435 }
3436
3437 // Convert the pointer to intptr_t before signing it.
3438 auto OrigType = Pointer->getType();
3439 Pointer = CGF.Builder.CreatePtrToInt(V: Pointer, DestTy: CGF.IntPtrTy);
3440
3441 // call i64 @llvm.ptrauth.sign.i64(i64 %pointer, i32 %key, i64 %discriminator)
3442 auto Intrinsic = CGF.CGM.getIntrinsic(IID: IntrinsicID);
3443 Pointer = CGF.EmitRuntimeCall(callee: Intrinsic, args: {Pointer, Key, Discriminator});
3444
3445 // Convert back to the original type.
3446 Pointer = CGF.Builder.CreateIntToPtr(V: Pointer, DestTy: OrigType);
3447 return Pointer;
3448}
3449
3450llvm::Value *
3451CodeGenFunction::EmitPointerAuthSign(const CGPointerAuthInfo &PointerAuth,
3452 llvm::Value *Pointer) {
3453 if (!PointerAuth.shouldSign())
3454 return Pointer;
3455 return EmitPointerAuthCommon(CGF&: *this, PointerAuth, Pointer,
3456 IntrinsicID: llvm::Intrinsic::ptrauth_sign);
3457}
3458
3459static llvm::Value *EmitStrip(CodeGenFunction &CGF,
3460 const CGPointerAuthInfo &PointerAuth,
3461 llvm::Value *Pointer) {
3462 auto StripIntrinsic = CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::ptrauth_strip);
3463
3464 auto Key = CGF.Builder.getInt32(C: PointerAuth.getKey());
3465 // Convert the pointer to intptr_t before signing it.
3466 auto OrigType = Pointer->getType();
3467 Pointer = CGF.EmitRuntimeCall(
3468 callee: StripIntrinsic, args: {CGF.Builder.CreatePtrToInt(V: Pointer, DestTy: CGF.IntPtrTy), Key});
3469 return CGF.Builder.CreateIntToPtr(V: Pointer, DestTy: OrigType);
3470}
3471
3472llvm::Value *
3473CodeGenFunction::EmitPointerAuthAuth(const CGPointerAuthInfo &PointerAuth,
3474 llvm::Value *Pointer) {
3475 if (PointerAuth.shouldStrip()) {
3476 return EmitStrip(CGF&: *this, PointerAuth, Pointer);
3477 }
3478 if (!PointerAuth.shouldAuth()) {
3479 return Pointer;
3480 }
3481
3482 return EmitPointerAuthCommon(CGF&: *this, PointerAuth, Pointer,
3483 IntrinsicID: llvm::Intrinsic::ptrauth_auth);
3484}
3485
3486void CodeGenFunction::addInstToCurrentSourceAtom(
3487 llvm::Instruction *KeyInstruction, llvm::Value *Backup) {
3488 if (CGDebugInfo *DI = getDebugInfo())
3489 DI->addInstToCurrentSourceAtom(KeyInstruction, Backup);
3490}
3491
3492void CodeGenFunction::addInstToSpecificSourceAtom(
3493 llvm::Instruction *KeyInstruction, llvm::Value *Backup, uint64_t Atom) {
3494 if (CGDebugInfo *DI = getDebugInfo())
3495 DI->addInstToSpecificSourceAtom(KeyInstruction, Backup, Atom);
3496}
3497
3498void CodeGenFunction::addInstToNewSourceAtom(llvm::Instruction *KeyInstruction,
3499 llvm::Value *Backup) {
3500 if (CGDebugInfo *DI = getDebugInfo()) {
3501 ApplyAtomGroup Grp(getDebugInfo());
3502 DI->addInstToCurrentSourceAtom(KeyInstruction, Backup);
3503 }
3504}
3505
3506void CodeGenFunction::emitPFPPostCopyUpdates(Address DestPtr, Address SrcPtr,
3507 QualType Ty) {
3508 for (auto &Field : getContext().findPFPFields(Ty)) {
3509 if (getContext().arePFPFieldsTriviallyCopyable(RD: Field.Field->getParent()))
3510 continue;
3511 auto DestFieldPtr = EmitAddressOfPFPField(RecordPtr: DestPtr, Field);
3512 auto SrcFieldPtr = EmitAddressOfPFPField(RecordPtr: SrcPtr, Field);
3513 Builder.CreateStore(Val: Builder.CreateLoad(Addr: SrcFieldPtr), Addr: DestFieldPtr);
3514 }
3515}
3516