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
1228 if (CGM.getCodeGenOpts().WarnStackSize != UINT_MAX &&
1229 !CGM.getDiags().isIgnored(DiagID: diag::warn_fe_backend_frame_larger_than, Loc))
1230 Fn->addFnAttr(Kind: "warn-stack-size",
1231 Val: std::to_string(val: CGM.getCodeGenOpts().WarnStackSize));
1232
1233 if (RetTy->isVoidType()) {
1234 // Void type; nothing to return.
1235 ReturnValue = Address::invalid();
1236
1237 // Count the implicit return.
1238 if (!endsWithReturn(F: D))
1239 ++NumReturnExprs;
1240 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
1241 // Indirect return; emit returned value directly into sret slot.
1242 // This reduces code size, and affects correctness in C++.
1243 auto AI = CurFn->arg_begin();
1244 if (CurFnInfo->getReturnInfo().isSRetAfterThis())
1245 ++AI;
1246 ReturnValue = makeNaturalAddressForPointer(
1247 Ptr: &*AI, T: RetTy, Alignment: CurFnInfo->getReturnInfo().getIndirectAlign(), ForPointeeType: false,
1248 BaseInfo: nullptr, TBAAInfo: nullptr, IsKnownNonNull: KnownNonNull);
1249 if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
1250 ReturnValuePointer =
1251 CreateDefaultAlignTempAlloca(Ty: ReturnValue.getType(), Name: "result.ptr");
1252 Builder.CreateStore(Val: ReturnValue.emitRawPointer(CGF&: *this),
1253 Addr: ReturnValuePointer);
1254 }
1255 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
1256 !hasScalarEvaluationKind(T: CurFnInfo->getReturnType())) {
1257 // Load the sret pointer from the argument struct and return into that.
1258 unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
1259 llvm::Function::arg_iterator EI = CurFn->arg_end();
1260 --EI;
1261 llvm::Value *Addr = Builder.CreateStructGEP(
1262 Ty: CurFnInfo->getArgStruct(), Ptr: &*EI, Idx);
1263 llvm::Type *Ty =
1264 cast<llvm::GetElementPtrInst>(Val: Addr)->getResultElementType();
1265 ReturnValuePointer = Address(Addr, Ty, getPointerAlign());
1266 Addr = Builder.CreateAlignedLoad(Ty, Addr, Align: getPointerAlign(), Name: "agg.result");
1267 ReturnValue = Address(Addr, ConvertType(T: RetTy),
1268 CGM.getNaturalTypeAlignment(T: RetTy), KnownNonNull);
1269 } else {
1270 ReturnValue = CreateIRTempWithoutCast(T: RetTy, Name: "retval");
1271
1272 // Tell the epilog emitter to autorelease the result. We do this
1273 // now so that various specialized functions can suppress it
1274 // during their IR-generation.
1275 if (getLangOpts().ObjCAutoRefCount &&
1276 !CurFnInfo->isReturnsRetained() &&
1277 RetTy->isObjCRetainableType())
1278 AutoreleaseResult = true;
1279 }
1280
1281 EmitStartEHSpec(D: CurCodeDecl);
1282
1283 PrologueCleanupDepth = EHStack.stable_begin();
1284
1285 // Emit OpenMP specific initialization of the device functions.
1286 if (getLangOpts().OpenMP && CurCodeDecl)
1287 CGM.getOpenMPRuntime().emitFunctionProlog(CGF&: *this, D: CurCodeDecl);
1288
1289 if (FD && getLangOpts().HLSL) {
1290 // Handle emitting HLSL entry functions.
1291 if (FD->hasAttr<HLSLShaderAttr>()) {
1292 CGM.getHLSLRuntime().emitEntryFunction(FD, Fn);
1293 }
1294 }
1295
1296 EmitFunctionProlog(FI: *CurFnInfo, Fn: CurFn, Args);
1297
1298 if (const CXXMethodDecl *MD = dyn_cast_if_present<CXXMethodDecl>(Val: D);
1299 MD && !MD->isStatic()) {
1300 bool IsInLambda =
1301 MD->getParent()->isLambda() && MD->getOverloadedOperator() == OO_Call;
1302 if (MD->isImplicitObjectMemberFunction())
1303 CGM.getCXXABI().EmitInstanceFunctionProlog(CGF&: *this);
1304 if (IsInLambda) {
1305 // We're in a lambda; figure out the captures.
1306 MD->getParent()->getCaptureFields(Captures&: LambdaCaptureFields,
1307 ThisCapture&: LambdaThisCaptureField);
1308 if (LambdaThisCaptureField) {
1309 // If the lambda captures the object referred to by '*this' - either by
1310 // value or by reference, make sure CXXThisValue points to the correct
1311 // object.
1312
1313 // Get the lvalue for the field (which is a copy of the enclosing object
1314 // or contains the address of the enclosing object).
1315 LValue ThisFieldLValue = EmitLValueForLambdaField(Field: LambdaThisCaptureField);
1316 if (!LambdaThisCaptureField->getType()->isPointerType()) {
1317 // If the enclosing object was captured by value, just use its
1318 // address. Sign this pointer.
1319 CXXThisValue = ThisFieldLValue.getPointer(CGF&: *this);
1320 } else {
1321 // Load the lvalue pointed to by the field, since '*this' was captured
1322 // by reference.
1323 CXXThisValue =
1324 EmitLoadOfLValue(V: ThisFieldLValue, Loc: SourceLocation()).getScalarVal();
1325 }
1326 }
1327 for (auto *FD : MD->getParent()->fields()) {
1328 if (FD->hasCapturedVLAType()) {
1329 auto *ExprArg = EmitLoadOfLValue(V: EmitLValueForLambdaField(Field: FD),
1330 Loc: SourceLocation()).getScalarVal();
1331 auto VAT = FD->getCapturedVLAType();
1332 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
1333 }
1334 }
1335 } else if (MD->isImplicitObjectMemberFunction()) {
1336 // Not in a lambda; just use 'this' from the method.
1337 // FIXME: Should we generate a new load for each use of 'this'? The
1338 // fast register allocator would be happier...
1339 CXXThisValue = CXXABIThisValue;
1340 }
1341
1342 // Check the 'this' pointer once per function, if it's available.
1343 if (CXXABIThisValue) {
1344 SanitizerSet SkippedChecks;
1345 SkippedChecks.set(K: SanitizerKind::ObjectSize, Value: true);
1346 QualType ThisTy = MD->getThisType();
1347
1348 // If this is the call operator of a lambda with no captures, it
1349 // may have a static invoker function, which may call this operator with
1350 // a null 'this' pointer.
1351 if (isLambdaCallOperator(MD) && MD->getParent()->isCapturelessLambda())
1352 SkippedChecks.set(K: SanitizerKind::Null, Value: true);
1353
1354 EmitTypeCheck(
1355 TCK: isa<CXXConstructorDecl>(Val: MD) ? TCK_ConstructorCall : TCK_MemberCall,
1356 Loc, V: CXXABIThisValue, Type: ThisTy, Alignment: CXXABIThisAlignment, SkippedChecks);
1357 }
1358 }
1359
1360 // If any of the arguments have a variably modified type, make sure to
1361 // emit the type size, but only if the function is not naked. Naked functions
1362 // have no prolog to run this evaluation.
1363 if (!FD || !FD->hasAttr<NakedAttr>()) {
1364 for (const VarDecl *VD : Args) {
1365 // Dig out the type as written from ParmVarDecls; it's unclear whether
1366 // the standard (C99 6.9.1p10) requires this, but we're following the
1367 // precedent set by gcc.
1368 QualType Ty;
1369 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Val: VD))
1370 Ty = PVD->getOriginalType();
1371 else
1372 Ty = VD->getType();
1373
1374 if (Ty->isVariablyModifiedType())
1375 EmitVariablyModifiedType(Ty);
1376 }
1377 }
1378 // Emit a location at the end of the prologue.
1379 if (CGDebugInfo *DI = getDebugInfo())
1380 DI->EmitLocation(Builder, Loc: StartLoc);
1381 // TODO: Do we need to handle this in two places like we do with
1382 // target-features/target-cpu?
1383 if (CurFuncDecl)
1384 if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
1385 LargestVectorWidth = VecWidth->getVectorWidth();
1386
1387 if (CGM.shouldEmitConvergenceTokens())
1388 ConvergenceTokenStack.push_back(Elt: getOrEmitConvergenceEntryToken(F: CurFn));
1389}
1390
1391void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
1392 incrementProfileCounter(S: Body);
1393 maybeCreateMCDCCondBitmap();
1394 if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Val: Body))
1395 EmitCompoundStmtWithoutScope(S: *S);
1396 else
1397 EmitStmt(S: Body);
1398}
1399
1400/// When instrumenting to collect profile data, the counts for some blocks
1401/// such as switch cases need to not include the fall-through counts, so
1402/// emit a branch around the instrumentation code. When not instrumenting,
1403/// this just calls EmitBlock().
1404void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
1405 const Stmt *S) {
1406 llvm::BasicBlock *SkipCountBB = nullptr;
1407 if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
1408 // When instrumenting for profiling, the fallthrough to certain
1409 // statements needs to skip over the instrumentation code so that we
1410 // get an accurate count.
1411 SkipCountBB = createBasicBlock(name: "skipcount");
1412 EmitBranch(Block: SkipCountBB);
1413 }
1414 EmitBlock(BB);
1415 uint64_t CurrentCount = getCurrentProfileCount();
1416 incrementProfileCounter(ExecSkip: UseExecPath, S);
1417 setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
1418 if (SkipCountBB)
1419 EmitBlock(BB: SkipCountBB);
1420}
1421
1422/// Tries to mark the given function nounwind based on the
1423/// non-existence of any throwing calls within it. We believe this is
1424/// lightweight enough to do at -O0.
1425static void TryMarkNoThrow(llvm::Function *F) {
1426 // LLVM treats 'nounwind' on a function as part of the type, so we
1427 // can't do this on functions that can be overwritten.
1428 if (F->isInterposable()) return;
1429
1430 for (llvm::BasicBlock &BB : *F)
1431 for (llvm::Instruction &I : BB)
1432 if (I.mayThrow())
1433 return;
1434
1435 F->setDoesNotThrow();
1436}
1437
1438QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
1439 FunctionArgList &Args) {
1440 const FunctionDecl *FD = cast<FunctionDecl>(Val: GD.getDecl());
1441 QualType ResTy = FD->getReturnType();
1442
1443 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD);
1444 if (MD && MD->isImplicitObjectMemberFunction()) {
1445 if (CGM.getCXXABI().HasThisReturn(GD))
1446 ResTy = MD->getThisType();
1447 else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
1448 ResTy = CGM.getContext().VoidPtrTy;
1449 CGM.getCXXABI().buildThisParam(CGF&: *this, Params&: Args);
1450 }
1451
1452 // The base version of an inheriting constructor whose constructed base is a
1453 // virtual base is not passed any arguments (because it doesn't actually call
1454 // the inherited constructor).
1455 bool PassedParams = true;
1456 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: FD))
1457 if (auto Inherited = CD->getInheritedConstructor())
1458 PassedParams =
1459 getTypes().inheritingCtorHasParams(Inherited, Type: GD.getCtorType());
1460
1461 if (PassedParams) {
1462 for (auto *Param : FD->parameters()) {
1463 Args.push_back(Elt: Param);
1464 if (!Param->hasAttr<PassObjectSizeAttr>())
1465 continue;
1466
1467 auto *Implicit = ImplicitParamDecl::Create(
1468 C&: getContext(), DC: Param->getDeclContext(), IdLoc: Param->getLocation(),
1469 /*Id=*/nullptr, T: getContext().getSizeType(), ParamKind: ImplicitParamKind::Other);
1470 SizeArguments[Param] = Implicit;
1471 Args.push_back(Elt: Implicit);
1472 }
1473 }
1474
1475 if (MD && (isa<CXXConstructorDecl>(Val: MD) || isa<CXXDestructorDecl>(Val: MD)))
1476 CGM.getCXXABI().addImplicitStructorParams(CGF&: *this, ResTy, Params&: Args);
1477
1478 return ResTy;
1479}
1480
1481void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1482 const CGFunctionInfo &FnInfo) {
1483 assert(Fn && "generating code for null Function");
1484 const FunctionDecl *FD = cast<FunctionDecl>(Val: GD.getDecl());
1485 CurGD = GD;
1486
1487 FunctionArgList Args;
1488 QualType ResTy = BuildFunctionArgList(GD, Args);
1489
1490 CGM.getTargetCodeGenInfo().checkFunctionABI(CGM, Decl: FD);
1491
1492 if (FD->isInlineBuiltinDeclaration()) {
1493 // When generating code for a builtin with an inline declaration, use a
1494 // mangled name to hold the actual body, while keeping an external
1495 // definition in case the function pointer is referenced somewhere.
1496 std::string FDInlineName = (Fn->getName() + ".inline").str();
1497 llvm::Module *M = Fn->getParent();
1498 llvm::Function *Clone = M->getFunction(Name: FDInlineName);
1499 if (!Clone) {
1500 Clone = llvm::Function::Create(Ty: Fn->getFunctionType(),
1501 Linkage: llvm::GlobalValue::InternalLinkage,
1502 AddrSpace: Fn->getAddressSpace(), N: FDInlineName, M);
1503 Clone->addFnAttr(Kind: llvm::Attribute::AlwaysInline);
1504 }
1505 Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
1506 Fn = Clone;
1507 } else {
1508 // Detect the unusual situation where an inline version is shadowed by a
1509 // non-inline version. In that case we should pick the external one
1510 // everywhere. That's GCC behavior too. Unfortunately, I cannot find a way
1511 // to detect that situation before we reach codegen, so do some late
1512 // replacement.
1513 for (const FunctionDecl *PD = FD->getPreviousDecl(); PD;
1514 PD = PD->getPreviousDecl()) {
1515 if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
1516 std::string FDInlineName = (Fn->getName() + ".inline").str();
1517 llvm::Module *M = Fn->getParent();
1518 if (llvm::Function *Clone = M->getFunction(Name: FDInlineName)) {
1519 Clone->replaceAllUsesWith(V: Fn);
1520 Clone->eraseFromParent();
1521 }
1522 break;
1523 }
1524 }
1525 }
1526
1527 // Check if we should generate debug info for this function.
1528 if (FD->hasAttr<NoDebugAttr>()) {
1529 // Clear non-distinct debug info that was possibly attached to the function
1530 // due to an earlier declaration without the nodebug attribute
1531 Fn->setSubprogram(nullptr);
1532 // Disable debug info indefinitely for this function
1533 DebugInfo = nullptr;
1534 }
1535 // Finalize function debug info on exit.
1536 llvm::scope_exit Cleanup([this] {
1537 if (CGDebugInfo *DI = getDebugInfo())
1538 DI->completeFunction();
1539 });
1540
1541 // The function might not have a body if we're generating thunks for a
1542 // function declaration.
1543 SourceRange BodyRange;
1544 if (Stmt *Body = FD->getBody())
1545 BodyRange = Body->getSourceRange();
1546 else
1547 BodyRange = FD->getLocation();
1548 CurEHLocation = BodyRange.getEnd();
1549
1550 // Use the location of the start of the function to determine where
1551 // the function definition is located. By default use the location
1552 // of the declaration as the location for the subprogram. A function
1553 // may lack a declaration in the source code if it is created by code
1554 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1555 SourceLocation Loc = FD->getLocation();
1556
1557 // If this is a function specialization then use the pattern body
1558 // as the location for the function.
1559 if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
1560 if (SpecDecl->hasBody(Definition&: SpecDecl))
1561 Loc = SpecDecl->getLocation();
1562
1563 Stmt *Body = FD->getBody();
1564
1565 if (Body) {
1566 // Coroutines always emit lifetime markers.
1567 if (isa<CoroutineBodyStmt>(Val: Body))
1568 ShouldEmitLifetimeMarkers = true;
1569
1570 // Detect jumps that invalidate lifetime markers or bypass auto-var-init.
1571 bool NeedsBypassDetection =
1572 ShouldEmitLifetimeMarkers ||
1573 (CGM.getLangOpts().getTrivialAutoVarInit() !=
1574 LangOptions::TrivialAutoVarInitKind::Uninitialized);
1575 if (NeedsBypassDetection)
1576 Bypasses.Init(CGM, Body);
1577 }
1578
1579 // Emit the standard function prologue.
1580 StartFunction(GD, RetTy: ResTy, Fn, FnInfo, Args, Loc, StartLoc: BodyRange.getBegin());
1581
1582 // Save parameters for coroutine function.
1583 if (Body && isa_and_nonnull<CoroutineBodyStmt>(Val: Body))
1584 llvm::append_range(C&: FnArgs, R: FD->parameters());
1585
1586 // Ensure that the function adheres to the forward progress guarantee, which
1587 // is required by certain optimizations.
1588 // In C++11 and up, the attribute will be removed if the body contains a
1589 // trivial empty loop.
1590 if (checkIfFunctionMustProgress())
1591 CurFn->addFnAttr(Kind: llvm::Attribute::MustProgress);
1592
1593 // Generate the body of the function.
1594 PGO->assignRegionCounters(GD, Fn: CurFn);
1595 if (isa<CXXDestructorDecl>(Val: FD))
1596 EmitDestructorBody(Args);
1597 else if (isa<CXXConstructorDecl>(Val: FD))
1598 EmitConstructorBody(Args);
1599 else if (getLangOpts().CUDA &&
1600 !getLangOpts().CUDAIsDevice &&
1601 FD->hasAttr<CUDAGlobalAttr>())
1602 CGM.getCUDARuntime().emitDeviceStub(CGF&: *this, Args);
1603 else if (isa<CXXMethodDecl>(Val: FD) &&
1604 cast<CXXMethodDecl>(Val: FD)->isLambdaStaticInvoker()) {
1605 // The lambda static invoker function is special, because it forwards or
1606 // clones the body of the function call operator (but is actually static).
1607 EmitLambdaStaticInvokeBody(MD: cast<CXXMethodDecl>(Val: FD));
1608 } else if (isa<CXXMethodDecl>(Val: FD) &&
1609 isLambdaCallOperator(MD: cast<CXXMethodDecl>(Val: FD)) &&
1610 !FnInfo.isDelegateCall() &&
1611 cast<CXXMethodDecl>(Val: FD)->getParent()->getLambdaStaticInvoker() &&
1612 hasInAllocaArg(MD: cast<CXXMethodDecl>(Val: FD))) {
1613 // If emitting a lambda with static invoker on X86 Windows, change
1614 // the call operator body.
1615 // Make sure that this is a call operator with an inalloca arg and check
1616 // for delegate call to make sure this is the original call op and not the
1617 // new forwarding function for the static invoker.
1618 EmitLambdaInAllocaCallOpBody(MD: cast<CXXMethodDecl>(Val: FD));
1619 } else if (FD->isDefaulted() && isa<CXXMethodDecl>(Val: FD) &&
1620 (cast<CXXMethodDecl>(Val: FD)->isCopyAssignmentOperator() ||
1621 cast<CXXMethodDecl>(Val: FD)->isMoveAssignmentOperator())) {
1622 // Implicit copy-assignment gets the same special treatment as implicit
1623 // copy-constructors.
1624 emitImplicitAssignmentOperatorBody(Args);
1625 } else if (DeviceKernelAttr::isOpenCLSpelling(
1626 A: FD->getAttr<DeviceKernelAttr>()) &&
1627 GD.getKernelReferenceKind() == KernelReferenceKind::Kernel) {
1628 CallArgList CallArgs;
1629 for (unsigned i = 0; i < Args.size(); ++i) {
1630 Address ArgAddr = GetAddrOfLocalVar(VD: Args[i]);
1631 QualType ArgQualType = Args[i]->getType();
1632 RValue ArgRValue = convertTempToRValue(addr: ArgAddr, type: ArgQualType, Loc);
1633 CallArgs.add(rvalue: ArgRValue, type: ArgQualType);
1634 }
1635 GlobalDecl GDStub = GlobalDecl(FD, KernelReferenceKind::Stub);
1636 const FunctionType *FT = cast<FunctionType>(Val: FD->getType());
1637 CGM.getTargetCodeGenInfo().setOCLKernelStubCallingConvention(FT);
1638 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
1639 Args: CallArgs, Ty: FT, /*ChainCall=*/false, ABIInfoFD: getCurrentFunctionDecl());
1640 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(Info: FnInfo);
1641 llvm::Constant *GDStubFunctionPointer =
1642 CGM.getRawFunctionPointer(GD: GDStub, Ty: FTy);
1643 CGCallee GDStubCallee = CGCallee::forDirect(functionPtr: GDStubFunctionPointer, abstractInfo: GDStub);
1644 EmitCall(CallInfo: FnInfo, Callee: GDStubCallee, ReturnValue: ReturnValueSlot(), Args: CallArgs, CallOrInvoke: nullptr, IsMustTail: false,
1645 Loc);
1646 } else if (Body) {
1647 EmitFunctionBody(Body);
1648 } else
1649 llvm_unreachable("no definition for emitted function");
1650
1651 // C++11 [stmt.return]p2:
1652 // Flowing off the end of a function [...] results in undefined behavior in
1653 // a value-returning function.
1654 // C11 6.9.1p12:
1655 // If the '}' that terminates a function is reached, and the value of the
1656 // function call is used by the caller, the behavior is undefined.
1657 if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
1658 !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
1659 bool ShouldEmitUnreachable =
1660 CGM.getCodeGenOpts().StrictReturn ||
1661 !CGM.MayDropFunctionReturn(Context: FD->getASTContext(), ReturnType: FD->getReturnType());
1662 if (SanOpts.has(K: SanitizerKind::Return)) {
1663 auto CheckOrdinal = SanitizerKind::SO_Return;
1664 auto CheckHandler = SanitizerHandler::MissingReturn;
1665 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
1666 llvm::Value *IsFalse = Builder.getFalse();
1667 EmitCheck(Checked: std::make_pair(x&: IsFalse, y&: CheckOrdinal), Check: CheckHandler,
1668 StaticArgs: EmitCheckSourceLocation(Loc: FD->getLocation()), DynamicArgs: {});
1669 } else if (ShouldEmitUnreachable) {
1670 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1671 EmitTrapCall(IntrID: llvm::Intrinsic::trap);
1672 }
1673 if (SanOpts.has(K: SanitizerKind::Return) || ShouldEmitUnreachable) {
1674 Builder.CreateUnreachable();
1675 Builder.ClearInsertionPoint();
1676 }
1677 }
1678
1679 // Emit the standard function epilogue.
1680 FinishFunction(EndLoc: BodyRange.getEnd());
1681
1682 PGO->verifyCounterMap();
1683
1684 if (CurCodeDecl->hasAttr<PersonalityAttr>()) {
1685 StringRef Identifier =
1686 CurCodeDecl->getAttr<PersonalityAttr>()->getRoutine()->getName();
1687 llvm::FunctionCallee PersonalityRoutine =
1688 CGM.CreateRuntimeFunction(Ty: llvm::FunctionType::get(Result: CGM.Int32Ty, isVarArg: true),
1689 Name: Identifier, ExtraAttrs: {}, /*local=*/Local: true);
1690 Fn->setPersonalityFn(cast<llvm::Constant>(Val: PersonalityRoutine.getCallee()));
1691 }
1692
1693 // If we haven't marked the function nothrow through other means, do
1694 // a quick pass now to see if we can.
1695 if (!CurFn->doesNotThrow())
1696 TryMarkNoThrow(F: CurFn);
1697}
1698
1699/// ContainsLabel - Return true if the statement contains a label in it. If
1700/// this statement is not executed normally, it not containing a label means
1701/// that we can just remove the code.
1702bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1703 // Null statement, not a label!
1704 if (!S) return false;
1705
1706 // If this is a label, we have to emit the code, consider something like:
1707 // if (0) { ... foo: bar(); } goto foo;
1708 //
1709 // TODO: If anyone cared, we could track __label__'s, since we know that you
1710 // can't jump to one from outside their declared region.
1711 if (isa<LabelStmt>(Val: S))
1712 return true;
1713
1714 // If this is a case/default statement, and we haven't seen a switch, we have
1715 // to emit the code.
1716 if (isa<SwitchCase>(Val: S) && !IgnoreCaseStmts)
1717 return true;
1718
1719 // If this is a switch statement, we want to ignore cases below it.
1720 if (isa<SwitchStmt>(Val: S))
1721 IgnoreCaseStmts = true;
1722
1723 // Scan subexpressions for verboten labels.
1724 for (const Stmt *SubStmt : S->children())
1725 if (ContainsLabel(S: SubStmt, IgnoreCaseStmts))
1726 return true;
1727
1728 return false;
1729}
1730
1731/// containsBreak - Return true if the statement contains a break out of it.
1732/// If the statement (recursively) contains a switch or loop with a break
1733/// inside of it, this is fine.
1734bool CodeGenFunction::containsBreak(const Stmt *S) {
1735 // Null statement, not a label!
1736 if (!S) return false;
1737
1738 // If this is a switch or loop that defines its own break scope, then we can
1739 // include it and anything inside of it.
1740 if (isa<SwitchStmt>(Val: S) || isa<WhileStmt>(Val: S) || isa<DoStmt>(Val: S) ||
1741 isa<ForStmt>(Val: S))
1742 return false;
1743
1744 if (isa<BreakStmt>(Val: S))
1745 return true;
1746
1747 // Scan subexpressions for verboten breaks.
1748 for (const Stmt *SubStmt : S->children())
1749 if (containsBreak(S: SubStmt))
1750 return true;
1751
1752 return false;
1753}
1754
1755bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
1756 if (!S) return false;
1757
1758 // Some statement kinds add a scope and thus never add a decl to the current
1759 // scope. Note, this list is longer than the list of statements that might
1760 // have an unscoped decl nested within them, but this way is conservatively
1761 // correct even if more statement kinds are added.
1762 if (isa<IfStmt>(Val: S) || isa<SwitchStmt>(Val: S) || isa<WhileStmt>(Val: S) ||
1763 isa<DoStmt>(Val: S) || isa<ForStmt>(Val: S) || isa<CompoundStmt>(Val: S) ||
1764 isa<CXXForRangeStmt>(Val: S) || isa<CXXTryStmt>(Val: S) ||
1765 isa<ObjCForCollectionStmt>(Val: S) || isa<ObjCAtTryStmt>(Val: S))
1766 return false;
1767
1768 if (isa<DeclStmt>(Val: S))
1769 return true;
1770
1771 for (const Stmt *SubStmt : S->children())
1772 if (mightAddDeclToScope(S: SubStmt))
1773 return true;
1774
1775 return false;
1776}
1777
1778/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1779/// to a constant, or if it does but contains a label, return false. If it
1780/// constant folds return true and set the boolean result in Result.
1781bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1782 bool &ResultBool,
1783 bool AllowLabels) {
1784 // If MC/DC is enabled, disable folding so that we can instrument all
1785 // conditions to yield complete test vectors. We still keep track of
1786 // folded conditions during region mapping and visualization.
1787 if (!AllowLabels && CGM.getCodeGenOpts().hasProfileClangInstr() &&
1788 CGM.getCodeGenOpts().MCDCCoverage)
1789 return false;
1790
1791 llvm::APSInt ResultInt;
1792 if (!ConstantFoldsToSimpleInteger(Cond, Result&: ResultInt, AllowLabels))
1793 return false;
1794
1795 ResultBool = ResultInt.getBoolValue();
1796 return true;
1797}
1798
1799/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1800/// to a constant, or if it does but contains a label, return false. If it
1801/// constant folds return true and set the folded value.
1802bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1803 llvm::APSInt &ResultInt,
1804 bool AllowLabels) {
1805 // FIXME: Rename and handle conversion of other evaluatable things
1806 // to bool.
1807 Expr::EvalResult Result;
1808 if (!Cond->EvaluateAsInt(Result, Ctx: getContext()))
1809 return false; // Not foldable, not integer or not fully evaluatable.
1810
1811 llvm::APSInt Int = Result.Val.getInt();
1812 if (!AllowLabels && CodeGenFunction::ContainsLabel(S: Cond))
1813 return false; // Contains a label.
1814
1815 PGO->markStmtMaybeUsed(S: Cond);
1816 ResultInt = std::move(Int);
1817 return true;
1818}
1819
1820/// Strip parentheses and simplistic logical-NOT operators.
1821const Expr *CodeGenFunction::stripCond(const Expr *C) {
1822 while (true) {
1823 const Expr *SC = IgnoreExprNodes(
1824 E: C, Fns&: IgnoreParensSingleStep, Fns&: IgnoreUOpLNotSingleStep,
1825 Fns&: IgnoreBuiltinExpectSingleStep, Fns&: IgnoreImplicitCastsSingleStep);
1826 if (C == SC)
1827 return SC;
1828 C = SC;
1829 }
1830}
1831
1832/// Determine whether the given condition is an instrumentable condition
1833/// (i.e. no "&&" or "||").
1834bool CodeGenFunction::isInstrumentedCondition(const Expr *C) {
1835 const BinaryOperator *BOp = dyn_cast<BinaryOperator>(Val: stripCond(C));
1836 return (!BOp || !BOp->isLogicalOp());
1837}
1838
1839/// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
1840/// increments a profile counter based on the semantics of the given logical
1841/// operator opcode. This is used to instrument branch condition coverage for
1842/// logical operators.
1843void CodeGenFunction::EmitBranchToCounterBlock(
1844 const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock,
1845 llvm::BasicBlock *FalseBlock, uint64_t TrueCount /* = 0 */,
1846 Stmt::Likelihood LH /* =None */, const Expr *CntrIdx /* = nullptr */) {
1847 // If not instrumenting, just emit a branch.
1848 bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
1849 if (!InstrumentRegions || !isInstrumentedCondition(C: Cond))
1850 return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH);
1851
1852 const Stmt *CntrStmt = (CntrIdx ? CntrIdx : Cond);
1853
1854 llvm::BasicBlock *ThenBlock = nullptr;
1855 llvm::BasicBlock *ElseBlock = nullptr;
1856 llvm::BasicBlock *NextBlock = nullptr;
1857
1858 // Create the block we'll use to increment the appropriate counter.
1859 llvm::BasicBlock *CounterIncrBlock = createBasicBlock(name: "lop.rhscnt");
1860
1861 llvm::BasicBlock *SkipIncrBlock =
1862 (hasSkipCounter(S: CntrStmt) ? createBasicBlock(name: "lop.rhsskip") : nullptr);
1863 llvm::BasicBlock *SkipNextBlock = nullptr;
1864
1865 // Set block pointers according to Logical-AND (BO_LAnd) semantics. This
1866 // means we need to evaluate the condition and increment the counter on TRUE:
1867 //
1868 // if (Cond)
1869 // goto CounterIncrBlock;
1870 // else
1871 // goto FalseBlock;
1872 //
1873 // CounterIncrBlock:
1874 // Counter++;
1875 // goto TrueBlock;
1876
1877 if (LOp == BO_LAnd) {
1878 SkipNextBlock = FalseBlock;
1879 ThenBlock = CounterIncrBlock;
1880 ElseBlock = (SkipIncrBlock ? SkipIncrBlock : SkipNextBlock);
1881 NextBlock = TrueBlock;
1882 }
1883
1884 // Set block pointers according to Logical-OR (BO_LOr) semantics. This means
1885 // we need to evaluate the condition and increment the counter on FALSE:
1886 //
1887 // if (Cond)
1888 // goto TrueBlock;
1889 // else
1890 // goto CounterIncrBlock;
1891 //
1892 // CounterIncrBlock:
1893 // Counter++;
1894 // goto FalseBlock;
1895
1896 else if (LOp == BO_LOr) {
1897 SkipNextBlock = TrueBlock;
1898 ThenBlock = (SkipIncrBlock ? SkipIncrBlock : SkipNextBlock);
1899 ElseBlock = CounterIncrBlock;
1900 NextBlock = FalseBlock;
1901 } else {
1902 llvm_unreachable("Expected Opcode must be that of a Logical Operator");
1903 }
1904
1905 // Emit Branch based on condition.
1906 EmitBranchOnBoolExpr(Cond, TrueBlock: ThenBlock, FalseBlock: ElseBlock, TrueCount, LH);
1907
1908 if (SkipIncrBlock) {
1909 EmitBlock(BB: SkipIncrBlock);
1910 incrementProfileCounter(ExecSkip: UseSkipPath, S: CntrStmt);
1911 EmitBranch(Block: SkipNextBlock);
1912 }
1913
1914 // Emit the block containing the counter increment(s).
1915 EmitBlock(BB: CounterIncrBlock);
1916
1917 // Increment corresponding counter; if index not provided, use Cond as index.
1918 incrementProfileCounter(ExecSkip: UseExecPath, S: CntrStmt);
1919
1920 // Go to the next block.
1921 EmitBranch(Block: NextBlock);
1922}
1923
1924/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1925/// statement) to the specified blocks. Based on the condition, this might try
1926/// to simplify the codegen of the conditional based on the branch.
1927/// \param LH The value of the likelihood attribute on the True branch.
1928/// \param ConditionalOp Used by MC/DC code coverage to track the result of the
1929/// ConditionalOperator (ternary) through a recursive call for the operator's
1930/// LHS and RHS nodes.
1931void CodeGenFunction::EmitBranchOnBoolExpr(
1932 const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock,
1933 uint64_t TrueCount, Stmt::Likelihood LH, const Expr *ConditionalOp,
1934 const VarDecl *ConditionalDecl) {
1935 Cond = Cond->IgnoreParens();
1936
1937 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Val: Cond)) {
1938 bool HasSkip = hasSkipCounter(S: CondBOp);
1939
1940 // Handle X && Y in a condition.
1941 if (CondBOp->getOpcode() == BO_LAnd) {
1942 // If we have "1 && X", simplify the code. "0 && X" would have constant
1943 // folded if the case was simple enough.
1944 bool ConstantBool = false;
1945 if (ConstantFoldsToSimpleInteger(Cond: CondBOp->getLHS(), ResultBool&: ConstantBool) &&
1946 ConstantBool) {
1947 // br(1 && X) -> br(X).
1948 incrementProfileCounter(S: CondBOp);
1949 EmitBranchToCounterBlock(Cond: CondBOp->getRHS(), LOp: BO_LAnd, TrueBlock,
1950 FalseBlock, TrueCount, LH);
1951 return;
1952 }
1953
1954 // If we have "X && 1", simplify the code to use an uncond branch.
1955 // "X && 0" would have been constant folded to 0.
1956 if (ConstantFoldsToSimpleInteger(Cond: CondBOp->getRHS(), ResultBool&: ConstantBool) &&
1957 ConstantBool) {
1958 // br(X && 1) -> br(X).
1959 EmitBranchToCounterBlock(Cond: CondBOp->getLHS(), LOp: BO_LAnd, TrueBlock,
1960 FalseBlock, TrueCount, LH, CntrIdx: CondBOp);
1961 return;
1962 }
1963
1964 // Emit the LHS as a conditional. If the LHS conditional is false, we
1965 // want to jump to the FalseBlock.
1966 llvm::BasicBlock *LHSTrue = createBasicBlock(name: "land.lhs.true");
1967 llvm::BasicBlock *LHSFalse =
1968 (HasSkip ? createBasicBlock(name: "land.lhsskip") : FalseBlock);
1969 // The counter tells us how often we evaluate RHS, and all of TrueCount
1970 // can be propagated to that branch.
1971 uint64_t RHSCount = getProfileCount(S: CondBOp->getRHS());
1972
1973 ConditionalEvaluation eval(*this);
1974 {
1975 ApplyDebugLocation DL(*this, Cond);
1976 // Propagate the likelihood attribute like __builtin_expect
1977 // __builtin_expect(X && Y, 1) -> X and Y are likely
1978 // __builtin_expect(X && Y, 0) -> only Y is unlikely
1979 EmitBranchOnBoolExpr(Cond: CondBOp->getLHS(), TrueBlock: LHSTrue, FalseBlock: LHSFalse, TrueCount: RHSCount,
1980 LH: LH == Stmt::LH_Unlikely ? Stmt::LH_None : LH);
1981 if (HasSkip) {
1982 EmitBlock(BB: LHSFalse);
1983 incrementProfileCounter(ExecSkip: UseSkipPath, S: CondBOp);
1984 EmitBranch(Block: FalseBlock);
1985 }
1986 EmitBlock(BB: LHSTrue);
1987 }
1988
1989 incrementProfileCounter(ExecSkip: UseExecPath, S: CondBOp);
1990 setCurrentProfileCount(getProfileCount(S: CondBOp->getRHS()));
1991
1992 // Any temporaries created here are conditional.
1993 eval.begin(CGF&: *this);
1994 EmitBranchToCounterBlock(Cond: CondBOp->getRHS(), LOp: BO_LAnd, TrueBlock,
1995 FalseBlock, TrueCount, LH);
1996 eval.end(CGF&: *this);
1997 return;
1998 }
1999
2000 if (CondBOp->getOpcode() == BO_LOr) {
2001 // If we have "0 || X", simplify the code. "1 || X" would have constant
2002 // folded if the case was simple enough.
2003 bool ConstantBool = false;
2004 if (ConstantFoldsToSimpleInteger(Cond: CondBOp->getLHS(), ResultBool&: ConstantBool) &&
2005 !ConstantBool) {
2006 // br(0 || X) -> br(X).
2007 incrementProfileCounter(S: CondBOp);
2008 EmitBranchToCounterBlock(Cond: CondBOp->getRHS(), LOp: BO_LOr, TrueBlock,
2009 FalseBlock, TrueCount, LH);
2010 return;
2011 }
2012
2013 // If we have "X || 0", simplify the code to use an uncond branch.
2014 // "X || 1" would have been constant folded to 1.
2015 if (ConstantFoldsToSimpleInteger(Cond: CondBOp->getRHS(), ResultBool&: ConstantBool) &&
2016 !ConstantBool) {
2017 // br(X || 0) -> br(X).
2018 EmitBranchToCounterBlock(Cond: CondBOp->getLHS(), LOp: BO_LOr, TrueBlock,
2019 FalseBlock, TrueCount, LH, CntrIdx: CondBOp);
2020 return;
2021 }
2022 // Emit the LHS as a conditional. If the LHS conditional is true, we
2023 // want to jump to the TrueBlock.
2024 llvm::BasicBlock *LHSTrue =
2025 (HasSkip ? createBasicBlock(name: "lor.lhsskip") : TrueBlock);
2026 llvm::BasicBlock *LHSFalse = createBasicBlock(name: "lor.lhs.false");
2027 // We have the count for entry to the RHS and for the whole expression
2028 // being true, so we can divy up True count between the short circuit and
2029 // the RHS.
2030 uint64_t LHSCount =
2031 getCurrentProfileCount() - getProfileCount(S: CondBOp->getRHS());
2032 uint64_t RHSCount = TrueCount - LHSCount;
2033
2034 ConditionalEvaluation eval(*this);
2035 {
2036 // Propagate the likelihood attribute like __builtin_expect
2037 // __builtin_expect(X || Y, 1) -> only Y is likely
2038 // __builtin_expect(X || Y, 0) -> both X and Y are unlikely
2039 ApplyDebugLocation DL(*this, Cond);
2040 EmitBranchOnBoolExpr(Cond: CondBOp->getLHS(), TrueBlock: LHSTrue, FalseBlock: LHSFalse, TrueCount: LHSCount,
2041 LH: LH == Stmt::LH_Likely ? Stmt::LH_None : LH);
2042 if (HasSkip) {
2043 EmitBlock(BB: LHSTrue);
2044 incrementProfileCounter(ExecSkip: UseSkipPath, S: CondBOp);
2045 EmitBranch(Block: TrueBlock);
2046 }
2047 EmitBlock(BB: LHSFalse);
2048 }
2049
2050 incrementProfileCounter(ExecSkip: UseExecPath, S: CondBOp);
2051 setCurrentProfileCount(getProfileCount(S: CondBOp->getRHS()));
2052
2053 // Any temporaries created here are conditional.
2054 eval.begin(CGF&: *this);
2055 EmitBranchToCounterBlock(Cond: CondBOp->getRHS(), LOp: BO_LOr, TrueBlock, FalseBlock,
2056 TrueCount: RHSCount, LH);
2057
2058 eval.end(CGF&: *this);
2059 return;
2060 }
2061 }
2062
2063 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Val: Cond)) {
2064 // br(!x, t, f) -> br(x, f, t)
2065 // Avoid doing this optimization when instrumenting a condition for MC/DC.
2066 // LNot is taken as part of the condition for simplicity, and changing its
2067 // sense negatively impacts test vector tracking.
2068 bool MCDCCondition = CGM.getCodeGenOpts().hasProfileClangInstr() &&
2069 CGM.getCodeGenOpts().MCDCCoverage &&
2070 isInstrumentedCondition(C: Cond);
2071 if (CondUOp->getOpcode() == UO_LNot && !MCDCCondition) {
2072 // Negate the count.
2073 uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
2074 // The values of the enum are chosen to make this negation possible.
2075 LH = static_cast<Stmt::Likelihood>(-LH);
2076 // Negate the condition and swap the destination blocks.
2077 return EmitBranchOnBoolExpr(Cond: CondUOp->getSubExpr(), TrueBlock: FalseBlock, FalseBlock: TrueBlock,
2078 TrueCount: FalseCount, LH);
2079 }
2080 }
2081
2082 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Val: Cond)) {
2083 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
2084 llvm::BasicBlock *LHSBlock = createBasicBlock(name: "cond.true");
2085 llvm::BasicBlock *RHSBlock = createBasicBlock(name: "cond.false");
2086
2087 // The ConditionalOperator itself has no likelihood information for its
2088 // true and false branches. This matches the behavior of __builtin_expect.
2089 ConditionalEvaluation cond(*this);
2090 EmitBranchOnBoolExpr(Cond: CondOp->getCond(), TrueBlock: LHSBlock, FalseBlock: RHSBlock,
2091 TrueCount: getProfileCount(S: CondOp), LH: Stmt::LH_None);
2092
2093 // When computing PGO branch weights, we only know the overall count for
2094 // the true block. This code is essentially doing tail duplication of the
2095 // naive code-gen, introducing new edges for which counts are not
2096 // available. Divide the counts proportionally between the LHS and RHS of
2097 // the conditional operator.
2098 uint64_t LHSScaledTrueCount = 0;
2099 if (TrueCount) {
2100 double LHSRatio =
2101 getProfileCount(S: CondOp) / (double)getCurrentProfileCount();
2102 LHSScaledTrueCount = TrueCount * LHSRatio;
2103 }
2104
2105 cond.begin(CGF&: *this);
2106 EmitBlock(BB: LHSBlock);
2107 incrementProfileCounter(ExecSkip: UseExecPath, S: CondOp);
2108 {
2109 ApplyDebugLocation DL(*this, Cond);
2110 EmitBranchOnBoolExpr(Cond: CondOp->getLHS(), TrueBlock, FalseBlock,
2111 TrueCount: LHSScaledTrueCount, LH, ConditionalOp: CondOp);
2112 }
2113 cond.end(CGF&: *this);
2114
2115 cond.begin(CGF&: *this);
2116 EmitBlock(BB: RHSBlock);
2117 incrementProfileCounter(ExecSkip: UseSkipPath, S: CondOp);
2118 EmitBranchOnBoolExpr(Cond: CondOp->getRHS(), TrueBlock, FalseBlock,
2119 TrueCount: TrueCount - LHSScaledTrueCount, LH, ConditionalOp: CondOp);
2120 cond.end(CGF&: *this);
2121
2122 return;
2123 }
2124
2125 if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Val: Cond)) {
2126 // Conditional operator handling can give us a throw expression as a
2127 // condition for a case like:
2128 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
2129 // Fold this to:
2130 // br(c, throw x, br(y, t, f))
2131 EmitCXXThrowExpr(E: Throw, /*KeepInsertionPoint*/false);
2132 return;
2133 }
2134
2135 // Emit the code with the fully general case.
2136 llvm::Value *CondV;
2137 {
2138 ApplyDebugLocation DL(*this, Cond);
2139 CondV = EvaluateExprAsBool(E: Cond);
2140 }
2141
2142 MaybeEmitDeferredVarDeclInit(var: ConditionalDecl);
2143
2144 // If not at the top of the logical operator nest, update MCDC temp with the
2145 // boolean result of the evaluated condition.
2146 {
2147 const Expr *MCDCBaseExpr = Cond;
2148 // When a nested ConditionalOperator (ternary) is encountered in a boolean
2149 // expression, MC/DC tracks the result of the ternary, and this is tied to
2150 // the ConditionalOperator expression and not the ternary's LHS or RHS. If
2151 // this is the case, the ConditionalOperator expression is passed through
2152 // the ConditionalOp parameter and then used as the MCDC base expression.
2153 if (ConditionalOp)
2154 MCDCBaseExpr = ConditionalOp;
2155
2156 if (isMCDCBranchExpr(E: stripCond(C: MCDCBaseExpr)) &&
2157 !isMCDCDecisionExpr(E: stripCond(C: Cond)))
2158 maybeUpdateMCDCCondBitmap(E: MCDCBaseExpr, Val: CondV);
2159 }
2160
2161 llvm::MDNode *Weights = nullptr;
2162 llvm::MDNode *Unpredictable = nullptr;
2163
2164 // If the branch has a condition wrapped by __builtin_unpredictable,
2165 // create metadata that specifies that the branch is unpredictable.
2166 // Don't bother if not optimizing because that metadata would not be used.
2167 auto *Call = dyn_cast<CallExpr>(Val: Cond->IgnoreImpCasts());
2168 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
2169 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: Call->getCalleeDecl());
2170 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
2171 llvm::MDBuilder MDHelper(getLLVMContext());
2172 Unpredictable = MDHelper.createUnpredictable();
2173 }
2174 }
2175
2176 // If there is a Likelihood knowledge for the cond, lower it.
2177 // Note that if not optimizing this won't emit anything.
2178 llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(Cond: CondV, LH);
2179 if (CondV != NewCondV)
2180 CondV = NewCondV;
2181 else {
2182 // Otherwise, lower profile counts. Note that we do this even at -O0.
2183 uint64_t CurrentCount = std::max(a: getCurrentProfileCount(), b: TrueCount);
2184 Weights = createProfileWeights(TrueCount, FalseCount: CurrentCount - TrueCount);
2185 }
2186
2187 llvm::Instruction *BrInst = Builder.CreateCondBr(Cond: CondV, True: TrueBlock, False: FalseBlock,
2188 BranchWeights: Weights, Unpredictable);
2189 addInstToNewSourceAtom(KeyInstruction: BrInst, Backup: CondV);
2190
2191 switch (HLSLControlFlowAttr) {
2192 case HLSLControlFlowHintAttr::Microsoft_branch:
2193 case HLSLControlFlowHintAttr::Microsoft_flatten: {
2194 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
2195
2196 llvm::ConstantInt *BranchHintConstant =
2197 HLSLControlFlowAttr ==
2198 HLSLControlFlowHintAttr::Spelling::Microsoft_branch
2199 ? llvm::ConstantInt::get(Ty: CGM.Int32Ty, V: 1)
2200 : llvm::ConstantInt::get(Ty: CGM.Int32Ty, V: 2);
2201
2202 SmallVector<llvm::Metadata *, 2> Vals(
2203 {MDHelper.createString(Str: "hlsl.controlflow.hint"),
2204 MDHelper.createConstant(C: BranchHintConstant)});
2205 BrInst->setMetadata(Kind: "hlsl.controlflow.hint",
2206 Node: llvm::MDNode::get(Context&: CGM.getLLVMContext(), MDs: Vals));
2207 break;
2208 }
2209 // This is required to avoid warnings during compilation
2210 case HLSLControlFlowHintAttr::SpellingNotCalculated:
2211 break;
2212 }
2213}
2214
2215llvm::Value *CodeGenFunction::EmitScalarOrConstFoldImmArg(unsigned ICEArguments,
2216 unsigned Idx,
2217 const CallExpr *E) {
2218 llvm::Value *Arg = nullptr;
2219 if ((ICEArguments & (1 << Idx)) == 0) {
2220 Arg = EmitScalarExpr(E: E->getArg(Arg: Idx));
2221 } else {
2222 // If this is required to be a constant, constant fold it so that we
2223 // know that the generated intrinsic gets a ConstantInt.
2224 std::optional<llvm::APSInt> Result =
2225 E->getArg(Arg: Idx)->getIntegerConstantExpr(Ctx: getContext());
2226 assert(Result && "Expected argument to be a constant");
2227 Arg = llvm::ConstantInt::get(Context&: getLLVMContext(), V: *Result);
2228 }
2229 return Arg;
2230}
2231
2232/// ErrorUnsupported - Print out an error that codegen doesn't support the
2233/// specified stmt yet.
2234void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
2235 CGM.ErrorUnsupported(S, Type);
2236}
2237
2238/// emitNonZeroVLAInit - Emit the "zero" initialization of a
2239/// variable-length array whose elements have a non-zero bit-pattern.
2240///
2241/// \param baseType the inner-most element type of the array
2242/// \param src - a char* pointing to the bit-pattern for a single
2243/// base element of the array
2244/// \param sizeInChars - the total size of the VLA, in chars
2245static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
2246 Address dest, Address src,
2247 llvm::Value *sizeInChars) {
2248 CGBuilderTy &Builder = CGF.Builder;
2249
2250 CharUnits baseSize = CGF.getContext().getTypeSizeInChars(T: baseType);
2251 llvm::Value *baseSizeInChars
2252 = llvm::ConstantInt::get(Ty: CGF.IntPtrTy, V: baseSize.getQuantity());
2253
2254 Address begin = dest.withElementType(ElemTy: CGF.Int8Ty);
2255 llvm::Value *end = Builder.CreateInBoundsGEP(Ty: begin.getElementType(),
2256 Ptr: begin.emitRawPointer(CGF),
2257 IdxList: sizeInChars, Name: "vla.end");
2258
2259 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
2260 llvm::BasicBlock *loopBB = CGF.createBasicBlock(name: "vla-init.loop");
2261 llvm::BasicBlock *contBB = CGF.createBasicBlock(name: "vla-init.cont");
2262
2263 // Make a loop over the VLA. C99 guarantees that the VLA element
2264 // count must be nonzero.
2265 CGF.EmitBlock(BB: loopBB);
2266
2267 llvm::PHINode *cur = Builder.CreatePHI(Ty: begin.getType(), NumReservedValues: 2, Name: "vla.cur");
2268 cur->addIncoming(V: begin.emitRawPointer(CGF), BB: originBB);
2269
2270 CharUnits curAlign =
2271 dest.getAlignment().alignmentOfArrayElement(elementSize: baseSize);
2272
2273 // memcpy the individual element bit-pattern.
2274 Builder.CreateMemCpy(Dest: Address(cur, CGF.Int8Ty, curAlign), Src: src, Size: baseSizeInChars,
2275 /*volatile*/ IsVolatile: false);
2276
2277 // Go to the next element.
2278 llvm::Value *next =
2279 Builder.CreateInBoundsGEP(Ty: CGF.Int8Ty, Ptr: cur, IdxList: baseSizeInChars, Name: "vla.next");
2280
2281 // Leave if that's the end of the VLA.
2282 llvm::Value *done = Builder.CreateICmpEQ(LHS: next, RHS: end, Name: "vla-init.isdone");
2283 Builder.CreateCondBr(Cond: done, True: contBB, False: loopBB);
2284 cur->addIncoming(V: next, BB: loopBB);
2285
2286 CGF.EmitBlock(BB: contBB);
2287}
2288
2289Address CodeGenFunction::EmitAddressOfPFPField(Address RecordPtr,
2290 const PFPField &Field) {
2291 return EmitAddressOfPFPField(
2292 RecordPtr,
2293 FieldPtr: Builder.CreateConstInBoundsByteGEP(Addr: RecordPtr.withElementType(ElemTy: Int8Ty),
2294 Offset: Field.Offset),
2295 Field: Field.Field);
2296}
2297
2298Address CodeGenFunction::EmitAddressOfPFPField(Address RecordPtr,
2299 Address PtrPtr,
2300 const FieldDecl *Field) {
2301 llvm::Value *Disc;
2302 if (CGM.getContext().arePFPFieldsTriviallyCopyable(RD: Field->getParent())) {
2303 uint64_t FieldSignature =
2304 llvm::getPointerAuthStableSipHash(S: CGM.getPFPFieldName(FD: Field));
2305 Disc = llvm::ConstantInt::get(Ty: CGM.Int64Ty, V: FieldSignature);
2306 } else
2307 Disc = Builder.CreatePtrToInt(V: RecordPtr.getBasePointer(), DestTy: CGM.Int64Ty);
2308
2309 llvm::GlobalValue *DS = CGM.getPFPDeactivationSymbol(FD: Field);
2310 llvm::OperandBundleDef DSBundle("deactivation-symbol", DS);
2311 llvm::Value *Args[] = {PtrPtr.getBasePointer(), Disc, Builder.getTrue()};
2312 return Address(
2313 Builder.CreateCall(Callee: CGM.getIntrinsic(IID: llvm::Intrinsic::protected_field_ptr,
2314 Tys: PtrPtr.getType()),
2315 Args, OpBundles: DSBundle),
2316 VoidPtrTy, PtrPtr.getAlignment());
2317}
2318
2319void
2320CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
2321 // Ignore empty classes in C++.
2322 if (getLangOpts().CPlusPlus)
2323 if (const auto *RD = Ty->getAsCXXRecordDecl(); RD && RD->isEmpty())
2324 return;
2325
2326 if (DestPtr.getElementType() != Int8Ty)
2327 DestPtr = DestPtr.withElementType(ElemTy: Int8Ty);
2328
2329 // Get size and alignment info for this aggregate.
2330 CharUnits size = getContext().getTypeSizeInChars(T: Ty);
2331
2332 llvm::Value *SizeVal;
2333 const VariableArrayType *vla;
2334
2335 // Don't bother emitting a zero-byte memset.
2336 if (size.isZero()) {
2337 // But note that getTypeInfo returns 0 for a VLA.
2338 if (const VariableArrayType *vlaType =
2339 dyn_cast_or_null<VariableArrayType>(
2340 Val: getContext().getAsArrayType(T: Ty))) {
2341 auto VlaSize = getVLASize(vla: vlaType);
2342 SizeVal = VlaSize.NumElts;
2343 CharUnits eltSize = getContext().getTypeSizeInChars(T: VlaSize.Type);
2344 if (!eltSize.isOne())
2345 SizeVal = Builder.CreateNUWMul(LHS: SizeVal, RHS: CGM.getSize(numChars: eltSize));
2346 vla = vlaType;
2347 } else {
2348 return;
2349 }
2350 } else {
2351 SizeVal = CGM.getSize(numChars: size);
2352 vla = nullptr;
2353 }
2354
2355 // If the type contains a pointer to data member we can't memset it to zero.
2356 // Instead, create a null constant and copy it to the destination.
2357 // TODO: there are other patterns besides zero that we can usefully memset,
2358 // like -1, which happens to be the pattern used by member-pointers.
2359 if (!CGM.getTypes().isZeroInitializable(T: Ty)) {
2360 // For a VLA, emit a single element, then splat that over the VLA.
2361 if (vla) Ty = getContext().getBaseElementType(VAT: vla);
2362
2363 llvm::Constant *NullConstant = CGM.EmitNullConstant(T: Ty);
2364
2365 llvm::GlobalVariable *NullVariable =
2366 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
2367 /*isConstant=*/true,
2368 llvm::GlobalVariable::PrivateLinkage,
2369 NullConstant, Twine());
2370 CharUnits NullAlign = DestPtr.getAlignment();
2371 NullVariable->setAlignment(NullAlign.getAsAlign());
2372 Address SrcPtr(NullVariable, Builder.getInt8Ty(), NullAlign);
2373
2374 if (vla) return emitNonZeroVLAInit(CGF&: *this, baseType: Ty, dest: DestPtr, src: SrcPtr, sizeInChars: SizeVal);
2375
2376 // Get and call the appropriate llvm.memcpy overload.
2377 Builder.CreateMemCpy(Dest: DestPtr, Src: SrcPtr, Size: SizeVal, IsVolatile: false);
2378 } else {
2379 // Otherwise, just memset the whole thing to zero. This is legal
2380 // because in LLVM, all default initializers (other than the ones we just
2381 // handled above, and the case handled below) are guaranteed to have a bit
2382 // pattern of all zeros.
2383 Builder.CreateMemSet(Dest: DestPtr, Value: Builder.getInt8(C: 0), Size: SizeVal, IsVolatile: false);
2384 }
2385
2386 // With the pointer field protection feature, null pointers do not have a bit
2387 // pattern of zero in memory, so we must initialize them separately.
2388 for (auto &Field : getContext().findPFPFields(Ty)) {
2389 auto addr = EmitAddressOfPFPField(RecordPtr: DestPtr, Field);
2390 Builder.CreateStore(Val: llvm::ConstantPointerNull::get(T: VoidPtrTy), Addr: addr);
2391 }
2392}
2393
2394llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
2395 // Make sure that there is a block for the indirect goto.
2396 if (!IndirectBranch)
2397 GetIndirectGotoBlock();
2398
2399 llvm::BasicBlock *BB = getJumpDestForLabel(S: L).getBlock();
2400
2401 // Make sure the indirect branch includes all of the address-taken blocks.
2402 IndirectBranch->addDestination(Dest: BB);
2403 return llvm::BlockAddress::get(Ty: CurFn->getType(), BB);
2404}
2405
2406llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
2407 // If we already made the indirect branch for indirect goto, return its block.
2408 if (IndirectBranch) return IndirectBranch->getParent();
2409
2410 CGBuilderTy TmpBuilder(CGM, createBasicBlock(name: "indirectgoto"));
2411
2412 // Create the PHI node that indirect gotos will add entries to.
2413 llvm::Value *DestVal = TmpBuilder.CreatePHI(Ty: Int8PtrTy, NumReservedValues: 0,
2414 Name: "indirect.goto.dest");
2415
2416 // Create the indirect branch instruction.
2417 IndirectBranch = TmpBuilder.CreateIndirectBr(Addr: DestVal);
2418 return IndirectBranch->getParent();
2419}
2420
2421/// Computes the length of an array in elements, as well as the base
2422/// element type and a properly-typed first element pointer.
2423llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
2424 QualType &baseType,
2425 Address &addr) {
2426 const ArrayType *arrayType = origArrayType;
2427
2428 // If it's a VLA, we have to load the stored size. Note that
2429 // this is the size of the VLA in bytes, not its size in elements.
2430 llvm::Value *numVLAElements = nullptr;
2431 if (isa<VariableArrayType>(Val: arrayType)) {
2432 numVLAElements = getVLASize(vla: cast<VariableArrayType>(Val: arrayType)).NumElts;
2433
2434 // Walk into all VLAs. This doesn't require changes to addr,
2435 // which has type T* where T is the first non-VLA element type.
2436 do {
2437 QualType elementType = arrayType->getElementType();
2438 arrayType = getContext().getAsArrayType(T: elementType);
2439
2440 // If we only have VLA components, 'addr' requires no adjustment.
2441 if (!arrayType) {
2442 baseType = elementType;
2443 return numVLAElements;
2444 }
2445 } while (isa<VariableArrayType>(Val: arrayType));
2446
2447 // We get out here only if we find a constant array type
2448 // inside the VLA.
2449 }
2450
2451 // We have some number of constant-length arrays, so addr should
2452 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
2453 // down to the first element of addr.
2454 SmallVector<llvm::Value*, 8> gepIndices;
2455
2456 // GEP down to the array type.
2457 llvm::ConstantInt *zero = Builder.getInt32(C: 0);
2458 gepIndices.push_back(Elt: zero);
2459
2460 uint64_t countFromCLAs = 1;
2461 QualType eltType;
2462
2463 llvm::ArrayType *llvmArrayType =
2464 dyn_cast<llvm::ArrayType>(Val: addr.getElementType());
2465 while (llvmArrayType) {
2466 assert(isa<ConstantArrayType>(arrayType));
2467 assert(cast<ConstantArrayType>(arrayType)->getZExtSize() ==
2468 llvmArrayType->getNumElements());
2469
2470 gepIndices.push_back(Elt: zero);
2471 countFromCLAs *= llvmArrayType->getNumElements();
2472 eltType = arrayType->getElementType();
2473
2474 llvmArrayType =
2475 dyn_cast<llvm::ArrayType>(Val: llvmArrayType->getElementType());
2476 arrayType = getContext().getAsArrayType(T: arrayType->getElementType());
2477 assert((!llvmArrayType || arrayType) &&
2478 "LLVM and Clang types are out-of-synch");
2479 }
2480
2481 if (arrayType) {
2482 // From this point onwards, the Clang array type has been emitted
2483 // as some other type (probably a packed struct). Compute the array
2484 // size, and just emit the 'begin' expression as a bitcast.
2485 while (arrayType) {
2486 countFromCLAs *= cast<ConstantArrayType>(Val: arrayType)->getZExtSize();
2487 eltType = arrayType->getElementType();
2488 arrayType = getContext().getAsArrayType(T: eltType);
2489 }
2490
2491 llvm::Type *baseType = ConvertType(T: eltType);
2492 addr = addr.withElementType(ElemTy: baseType);
2493 } else {
2494 // Create the actual GEP.
2495 addr = Address(Builder.CreateInBoundsGEP(Ty: addr.getElementType(),
2496 Ptr: addr.emitRawPointer(CGF&: *this),
2497 IdxList: gepIndices, Name: "array.begin"),
2498 ConvertTypeForMem(T: eltType), addr.getAlignment());
2499 }
2500
2501 baseType = eltType;
2502
2503 llvm::Value *numElements
2504 = llvm::ConstantInt::get(Ty: SizeTy, V: countFromCLAs);
2505
2506 // If we had any VLA dimensions, factor them in.
2507 if (numVLAElements)
2508 numElements = Builder.CreateNUWMul(LHS: numVLAElements, RHS: numElements);
2509
2510 return numElements;
2511}
2512
2513CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
2514 const VariableArrayType *vla = getContext().getAsVariableArrayType(T: type);
2515 assert(vla && "type was not a variable array type!");
2516 return getVLASize(vla);
2517}
2518
2519CodeGenFunction::VlaSizePair
2520CodeGenFunction::getVLASize(const VariableArrayType *type) {
2521 // The number of elements so far; always size_t.
2522 llvm::Value *numElements = nullptr;
2523
2524 QualType elementType;
2525 do {
2526 elementType = type->getElementType();
2527 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
2528 assert(vlaSize && "no size for VLA!");
2529 assert(vlaSize->getType() == SizeTy);
2530
2531 if (!numElements) {
2532 numElements = vlaSize;
2533 } else {
2534 // It's undefined behavior if this wraps around, so mark it that way.
2535 // FIXME: Teach -fsanitize=undefined to trap this.
2536 numElements = Builder.CreateNUWMul(LHS: numElements, RHS: vlaSize);
2537 }
2538 } while ((type = getContext().getAsVariableArrayType(T: elementType)));
2539
2540 return { numElements, elementType };
2541}
2542
2543CodeGenFunction::VlaSizePair
2544CodeGenFunction::getVLAElements1D(QualType type) {
2545 const VariableArrayType *vla = getContext().getAsVariableArrayType(T: type);
2546 assert(vla && "type was not a variable array type!");
2547 return getVLAElements1D(vla);
2548}
2549
2550CodeGenFunction::VlaSizePair
2551CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
2552 llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
2553 assert(VlaSize && "no size for VLA!");
2554 assert(VlaSize->getType() == SizeTy);
2555 return { VlaSize, Vla->getElementType() };
2556}
2557
2558void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
2559 assert(type->isVariablyModifiedType() &&
2560 "Must pass variably modified type to EmitVLASizes!");
2561
2562 EnsureInsertPoint();
2563
2564 // We're going to walk down into the type and look for VLA
2565 // expressions.
2566 do {
2567 assert(type->isVariablyModifiedType());
2568
2569 const Type *ty = type.getTypePtr();
2570 switch (ty->getTypeClass()) {
2571
2572#define TYPE(Class, Base)
2573#define ABSTRACT_TYPE(Class, Base)
2574#define NON_CANONICAL_TYPE(Class, Base)
2575#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2576#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
2577#include "clang/AST/TypeNodes.inc"
2578 llvm_unreachable("unexpected dependent type!");
2579
2580 // These types are never variably-modified.
2581 case Type::Builtin:
2582 case Type::Complex:
2583 case Type::Vector:
2584 case Type::ExtVector:
2585 case Type::ConstantMatrix:
2586 case Type::Record:
2587 case Type::Enum:
2588 case Type::Using:
2589 case Type::TemplateSpecialization:
2590 case Type::ObjCTypeParam:
2591 case Type::ObjCObject:
2592 case Type::ObjCInterface:
2593 case Type::ObjCObjectPointer:
2594 case Type::BitInt:
2595 case Type::HLSLInlineSpirv:
2596 case Type::PredefinedSugar:
2597 llvm_unreachable("type class is never variably-modified!");
2598
2599 case Type::Adjusted:
2600 type = cast<AdjustedType>(Val: ty)->getAdjustedType();
2601 break;
2602
2603 case Type::Decayed:
2604 type = cast<DecayedType>(Val: ty)->getPointeeType();
2605 break;
2606
2607 case Type::Pointer:
2608 type = cast<PointerType>(Val: ty)->getPointeeType();
2609 break;
2610
2611 case Type::BlockPointer:
2612 type = cast<BlockPointerType>(Val: ty)->getPointeeType();
2613 break;
2614
2615 case Type::LValueReference:
2616 case Type::RValueReference:
2617 type = cast<ReferenceType>(Val: ty)->getPointeeType();
2618 break;
2619
2620 case Type::MemberPointer:
2621 type = cast<MemberPointerType>(Val: ty)->getPointeeType();
2622 break;
2623
2624 case Type::ArrayParameter:
2625 case Type::ConstantArray:
2626 case Type::IncompleteArray:
2627 // Losing element qualification here is fine.
2628 type = cast<ArrayType>(Val: ty)->getElementType();
2629 break;
2630
2631 case Type::VariableArray: {
2632 // Losing element qualification here is fine.
2633 const VariableArrayType *vat = cast<VariableArrayType>(Val: ty);
2634
2635 // Unknown size indication requires no size computation.
2636 // Otherwise, evaluate and record it.
2637 if (const Expr *sizeExpr = vat->getSizeExpr()) {
2638 // It's possible that we might have emitted this already,
2639 // e.g. with a typedef and a pointer to it.
2640 llvm::Value *&entry = VLASizeMap[sizeExpr];
2641 if (!entry) {
2642 llvm::Value *size = EmitScalarExpr(E: sizeExpr);
2643
2644 // C11 6.7.6.2p5:
2645 // If the size is an expression that is not an integer constant
2646 // expression [...] each time it is evaluated it shall have a value
2647 // greater than zero.
2648 if (SanOpts.has(K: SanitizerKind::VLABound)) {
2649 auto CheckOrdinal = SanitizerKind::SO_VLABound;
2650 auto CheckHandler = SanitizerHandler::VLABoundNotPositive;
2651 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
2652 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: size->getType());
2653 clang::QualType SEType = sizeExpr->getType();
2654 llvm::Value *CheckCondition =
2655 SEType->isSignedIntegerType()
2656 ? Builder.CreateICmpSGT(LHS: size, RHS: Zero)
2657 : Builder.CreateICmpUGT(LHS: size, RHS: Zero);
2658 llvm::Constant *StaticArgs[] = {
2659 EmitCheckSourceLocation(Loc: sizeExpr->getBeginLoc()),
2660 EmitCheckTypeDescriptor(T: SEType)};
2661 EmitCheck(Checked: std::make_pair(x&: CheckCondition, y&: CheckOrdinal),
2662 Check: CheckHandler, StaticArgs, DynamicArgs: size);
2663 }
2664
2665 // Always zexting here would be wrong if it weren't
2666 // undefined behavior to have a negative bound.
2667 // FIXME: What about when size's type is larger than size_t?
2668 entry = Builder.CreateIntCast(V: size, DestTy: SizeTy, /*signed*/ isSigned: false);
2669 }
2670 }
2671 type = vat->getElementType();
2672 break;
2673 }
2674
2675 case Type::FunctionProto:
2676 case Type::FunctionNoProto:
2677 type = cast<FunctionType>(Val: ty)->getReturnType();
2678 break;
2679
2680 case Type::Paren:
2681 case Type::TypeOf:
2682 case Type::UnaryTransform:
2683 case Type::Attributed:
2684 case Type::BTFTagAttributed:
2685 case Type::OverflowBehavior:
2686 case Type::HLSLAttributedResource:
2687 case Type::SubstTemplateTypeParm:
2688 case Type::MacroQualified:
2689 case Type::CountAttributed:
2690 case Type::LateParsedAttr:
2691 // Keep walking after single level desugaring.
2692 type = type.getSingleStepDesugaredType(Context: getContext());
2693 break;
2694
2695 case Type::Typedef:
2696 case Type::Decltype:
2697 case Type::Auto:
2698 case Type::DeducedTemplateSpecialization:
2699 case Type::PackIndexing:
2700 // Stop walking: nothing to do.
2701 return;
2702
2703 case Type::TypeOfExpr:
2704 // Stop walking: emit typeof expression.
2705 EmitIgnoredExpr(E: cast<TypeOfExprType>(Val: ty)->getUnderlyingExpr());
2706 return;
2707
2708 case Type::Atomic:
2709 type = cast<AtomicType>(Val: ty)->getValueType();
2710 break;
2711
2712 case Type::Pipe:
2713 type = cast<PipeType>(Val: ty)->getElementType();
2714 break;
2715 }
2716 } while (type->isVariablyModifiedType());
2717}
2718
2719Address CodeGenFunction::EmitVAListRef(const Expr* E) {
2720 if (getContext().getBuiltinVaListType()->isArrayType())
2721 return EmitPointerWithAlignment(Addr: E);
2722 return EmitLValue(E).getAddress();
2723}
2724
2725Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
2726 return EmitLValue(E).getAddress();
2727}
2728
2729Address CodeGenFunction::EmitZOSVAListRef(const Expr *E) {
2730 return EmitPointerWithAlignment(Addr: E);
2731}
2732
2733void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
2734 const APValue &Init) {
2735 assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
2736 if (CGDebugInfo *Dbg = getDebugInfo())
2737 if (CGM.getCodeGenOpts().hasReducedDebugInfo())
2738 Dbg->EmitGlobalVariable(VD: E->getDecl(), Init);
2739}
2740
2741CodeGenFunction::PeepholeProtection
2742CodeGenFunction::protectFromPeepholes(RValue rvalue) {
2743 // At the moment, the only aggressive peephole we do in IR gen
2744 // is trunc(zext) folding, but if we add more, we can easily
2745 // extend this protection.
2746
2747 if (!rvalue.isScalar()) return PeepholeProtection();
2748 llvm::Value *value = rvalue.getScalarVal();
2749 if (!isa<llvm::ZExtInst>(Val: value)) return PeepholeProtection();
2750
2751 // Just make an extra bitcast.
2752 assert(HaveInsertPoint());
2753 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
2754 Builder.GetInsertBlock());
2755
2756 PeepholeProtection protection;
2757 protection.Inst = inst;
2758 return protection;
2759}
2760
2761void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
2762 if (!protection.Inst) return;
2763
2764 // In theory, we could try to duplicate the peepholes now, but whatever.
2765 protection.Inst->eraseFromParent();
2766}
2767
2768void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2769 QualType Ty, SourceLocation Loc,
2770 SourceLocation AssumptionLoc,
2771 llvm::Value *Alignment,
2772 llvm::Value *OffsetValue) {
2773 if (Alignment->getType() != IntPtrTy)
2774 Alignment =
2775 Builder.CreateIntCast(V: Alignment, DestTy: IntPtrTy, isSigned: false, Name: "casted.align");
2776 if (OffsetValue && OffsetValue->getType() != IntPtrTy)
2777 OffsetValue =
2778 Builder.CreateIntCast(V: OffsetValue, DestTy: IntPtrTy, isSigned: true, Name: "casted.offset");
2779 llvm::Value *TheCheck = nullptr;
2780 if (SanOpts.has(K: SanitizerKind::Alignment)) {
2781 llvm::Value *PtrIntValue =
2782 Builder.CreatePtrToInt(V: PtrValue, DestTy: IntPtrTy, Name: "ptrint");
2783
2784 if (OffsetValue) {
2785 bool IsOffsetZero = false;
2786 if (const auto *CI = dyn_cast<llvm::ConstantInt>(Val: OffsetValue))
2787 IsOffsetZero = CI->isZero();
2788
2789 if (!IsOffsetZero)
2790 PtrIntValue = Builder.CreateSub(LHS: PtrIntValue, RHS: OffsetValue, Name: "offsetptr");
2791 }
2792
2793 llvm::Value *Zero = llvm::ConstantInt::get(Ty: IntPtrTy, V: 0);
2794 llvm::Value *Mask =
2795 Builder.CreateSub(LHS: Alignment, RHS: llvm::ConstantInt::get(Ty: IntPtrTy, V: 1));
2796 llvm::Value *MaskedPtr = Builder.CreateAnd(LHS: PtrIntValue, RHS: Mask, Name: "maskedptr");
2797 TheCheck = Builder.CreateICmpEQ(LHS: MaskedPtr, RHS: Zero, Name: "maskcond");
2798 }
2799 llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
2800 DL: CGM.getDataLayout(), PtrValue, Alignment, OffsetValue);
2801
2802 if (!SanOpts.has(K: SanitizerKind::Alignment))
2803 return;
2804 emitAlignmentAssumptionCheck(Ptr: PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2805 OffsetValue, TheCheck, Assumption);
2806}
2807
2808void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2809 const Expr *E,
2810 SourceLocation AssumptionLoc,
2811 llvm::Value *Alignment,
2812 llvm::Value *OffsetValue) {
2813 QualType Ty = E->getType();
2814 SourceLocation Loc = E->getExprLoc();
2815
2816 emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2817 OffsetValue);
2818}
2819
2820llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
2821 llvm::Value *AnnotatedVal,
2822 StringRef AnnotationStr,
2823 SourceLocation Location,
2824 const AnnotateAttr *Attr) {
2825 SmallVector<llvm::Value *, 5> Args = {
2826 AnnotatedVal,
2827 CGM.EmitAnnotationString(Str: AnnotationStr),
2828 CGM.EmitAnnotationUnit(Loc: Location),
2829 CGM.EmitAnnotationLineNo(L: Location),
2830 };
2831 if (Attr)
2832 Args.push_back(Elt: CGM.EmitAnnotationArgs(Attr));
2833 return Builder.CreateCall(Callee: AnnotationFn, Args);
2834}
2835
2836void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
2837 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2838 for (const auto *I : D->specific_attrs<AnnotateAttr>())
2839 EmitAnnotationCall(AnnotationFn: CGM.getIntrinsic(IID: llvm::Intrinsic::var_annotation,
2840 Tys: {V->getType(), CGM.ConstGlobalsPtrTy}),
2841 AnnotatedVal: V, AnnotationStr: I->getAnnotation(), Location: D->getLocation(), Attr: I);
2842}
2843
2844Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
2845 Address Addr) {
2846 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2847 llvm::Value *V = Addr.emitRawPointer(CGF&: *this);
2848 llvm::Type *VTy = V->getType();
2849 auto *PTy = dyn_cast<llvm::PointerType>(Val: VTy);
2850 unsigned AS = PTy ? PTy->getAddressSpace() : 0;
2851 llvm::PointerType *IntrinTy =
2852 llvm::PointerType::get(C&: CGM.getLLVMContext(), AddressSpace: AS);
2853 llvm::Function *F = CGM.getIntrinsic(IID: llvm::Intrinsic::ptr_annotation,
2854 Tys: {IntrinTy, CGM.ConstGlobalsPtrTy});
2855
2856 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2857 // FIXME Always emit the cast inst so we can differentiate between
2858 // annotation on the first field of a struct and annotation on the struct
2859 // itself.
2860 if (VTy != IntrinTy)
2861 V = Builder.CreateBitCast(V, DestTy: IntrinTy);
2862 V = EmitAnnotationCall(AnnotationFn: F, AnnotatedVal: V, AnnotationStr: I->getAnnotation(), Location: D->getLocation(), Attr: I);
2863 V = Builder.CreateBitCast(V, DestTy: VTy);
2864 }
2865
2866 return Address(V, Addr.getElementType(), Addr.getAlignment());
2867}
2868
2869CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
2870
2871CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
2872 : CGF(CGF) {
2873 assert(!CGF->IsSanitizerScope);
2874 CGF->IsSanitizerScope = true;
2875}
2876
2877CodeGenFunction::SanitizerScope::~SanitizerScope() {
2878 CGF->IsSanitizerScope = false;
2879}
2880
2881void CodeGenFunction::InsertHelper(llvm::Instruction *I,
2882 const llvm::Twine &Name,
2883 llvm::BasicBlock::iterator InsertPt) const {
2884 LoopStack.InsertHelper(I);
2885 if (IsSanitizerScope)
2886 I->setNoSanitizeMetadata();
2887}
2888
2889void CGBuilderInserter::InsertHelper(
2890 llvm::Instruction *I, const llvm::Twine &Name,
2891 llvm::BasicBlock::iterator InsertPt) const {
2892 llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, InsertPt);
2893 if (CGF)
2894 CGF->InsertHelper(I, Name, InsertPt);
2895}
2896
2897// Emits an error if we don't have a valid set of target features for the
2898// called function.
2899void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
2900 const FunctionDecl *TargetDecl) {
2901 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: CurCodeDecl);
2902 CodeGenUtils::checkTargetFeatures(Ctx&: CGM.getContext(), Diags&: CGM.getDiags(),
2903 LangOpts: getLangOpts(), E, Caller: FD, TargetDecl);
2904}
2905
2906// Emits an error if we don't have a valid set of target features for the
2907// called function.
2908void CodeGenFunction::checkTargetFeatures(SourceLocation Loc,
2909 const FunctionDecl *TargetDecl) {
2910 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: CurCodeDecl);
2911 CodeGenUtils::checkTargetFeatures(Ctx&: CGM.getContext(), Diags&: CGM.getDiags(),
2912 LangOpts: getLangOpts(), Loc, Caller: FD, TargetDecl);
2913}
2914
2915void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2916 if (!CGM.getCodeGenOpts().SanitizeStats)
2917 return;
2918
2919 llvm::IRBuilder<> IRB(Builder.GetInsertPoint());
2920 IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2921 CGM.getSanStats().create(B&: IRB, SK: SSK);
2922}
2923
2924void CodeGenFunction::EmitKCFIOperandBundle(
2925 const CGCallee &Callee, SmallVectorImpl<llvm::OperandBundleDef> &Bundles) {
2926 const CGCalleeInfo &CI = Callee.getAbstractInfo();
2927 const FunctionProtoType *FP = CI.getCalleeFunctionProtoType();
2928 if (!FP)
2929 return;
2930
2931 StringRef Salt;
2932 if (const auto &Info = FP->getExtraAttributeInfo())
2933 Salt = Info.CFISalt;
2934
2935 Bundles.emplace_back(Args: "kcfi", Args: CGM.CreateKCFITypeId(T: FP->desugar(), Salt));
2936}
2937
2938llvm::Value *
2939CodeGenFunction::FormAArch64ResolverCondition(const FMVResolverOption &RO) {
2940 return RO.Features.empty() ? nullptr : EmitAArch64CpuSupports(FeatureStrs: RO.Features);
2941}
2942
2943llvm::Value *
2944CodeGenFunction::FormX86ResolverCondition(const FMVResolverOption &RO) {
2945 llvm::Value *Condition = nullptr;
2946
2947 if (RO.Architecture) {
2948 StringRef Arch = *RO.Architecture;
2949 // If arch= specifies an x86-64 micro-architecture level, test the feature
2950 // with __builtin_cpu_supports, otherwise use __builtin_cpu_is.
2951 if (Arch.starts_with(Prefix: "x86-64"))
2952 Condition = EmitX86CpuSupports(FeatureStrs: {Arch});
2953 else
2954 Condition = EmitX86CpuIs(CPUStr: Arch);
2955 }
2956
2957 if (!RO.Features.empty()) {
2958 llvm::Value *FeatureCond = EmitX86CpuSupports(FeatureStrs: RO.Features);
2959 Condition =
2960 Condition ? Builder.CreateAnd(LHS: Condition, RHS: FeatureCond) : FeatureCond;
2961 }
2962 return Condition;
2963}
2964
2965static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
2966 llvm::Function *Resolver,
2967 CGBuilderTy &Builder,
2968 llvm::Function *FuncToReturn,
2969 bool SupportsIFunc) {
2970 if (SupportsIFunc) {
2971 Builder.CreateRet(V: FuncToReturn);
2972 return;
2973 }
2974
2975 llvm::SmallVector<llvm::Value *, 10> Args(
2976 llvm::make_pointer_range(Range: Resolver->args()));
2977
2978 llvm::CallInst *Result = Builder.CreateCall(Callee: FuncToReturn, Args);
2979 Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2980
2981 if (Resolver->getReturnType()->isVoidTy())
2982 Builder.CreateRetVoid();
2983 else
2984 Builder.CreateRet(V: Result);
2985}
2986
2987void CodeGenFunction::EmitMultiVersionResolver(
2988 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
2989 llvm::SaveAndRestore<llvm::Function *> savedCurFn(CurFn, Resolver);
2990 llvm::Triple::ArchType ArchType =
2991 getContext().getTargetInfo().getTriple().getArch();
2992
2993 switch (ArchType) {
2994 case llvm::Triple::x86:
2995 case llvm::Triple::x86_64:
2996 EmitX86MultiVersionResolver(Resolver, Options);
2997 return;
2998 case llvm::Triple::aarch64:
2999 EmitAArch64MultiVersionResolver(Resolver, Options);
3000 return;
3001 case llvm::Triple::riscv32:
3002 case llvm::Triple::riscv64:
3003 case llvm::Triple::riscv32be:
3004 case llvm::Triple::riscv64be:
3005 EmitRISCVMultiVersionResolver(Resolver, Options);
3006 return;
3007 case llvm::Triple::ppc:
3008 case llvm::Triple::ppc64:
3009 if (getContext().getTargetInfo().getTriple().isOSAIX()) {
3010 EmitPPCAIXMultiVersionResolver(Resolver, Options);
3011 return;
3012 }
3013 [[fallthrough]];
3014 default:
3015 assert(false &&
3016 "Only implemented for x86, AArch64, RISC-V, and PowerPC AIX");
3017 }
3018}
3019
3020/**
3021 * define internal ptr @foo.resolver() {
3022 * entry:
3023 * %is_version_1 = __builtin_cpu_supports(version_1)
3024 * br i1 %1, label %if.version_1, label %if.else_2
3025 *
3026 * if.version_1:
3027 * ret ptr @foo.version_1
3028 *
3029 * if.else_2:
3030 * %is_version_2 = __builtin_cpu_supports(version_2)
3031 * ...
3032 * if.else: ; preds = %entry
3033 * ret ptr @foo.default
3034 * }
3035 */
3036void CodeGenFunction::EmitPPCAIXMultiVersionResolver(
3037 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3038
3039 // entry:
3040 llvm::BasicBlock *CurBlock = createBasicBlock(name: "entry", parent: Resolver);
3041
3042 SmallVector<std::pair<llvm::Value *, llvm::BasicBlock *>, 3> PhiArgs;
3043 for (const FMVResolverOption &RO : Options) {
3044 Builder.SetInsertPoint(CurBlock);
3045 // The 'default' or 'generic' case.
3046 if (!RO.Architecture && RO.Features.empty()) {
3047 // if.else:
3048 // ret ptr @foo.default
3049 assert(&RO == Options.end() - 1 &&
3050 "Default or Generic case must be last");
3051 Builder.CreateRet(V: RO.Function);
3052 return;
3053 }
3054 // if.else_n:
3055 // %is_version_n = __builtin_cpu_supports(version_n)
3056 // br i1 %is_version_n, label %if.version_n, label %if.else_n+1
3057 //
3058 // if.version_n:
3059 // ret ptr @foo_version_n
3060 assert(RO.Features.size() == 1 &&
3061 "for now one feature requirement per version");
3062
3063 StringRef FeatureStr = RO.Features[0];
3064 StringRef BuiltinCpuSupportsArg;
3065 bool IsNegated = false;
3066
3067 if (FeatureStr.starts_with(Prefix: "cpu=")) {
3068 // CPU specification - map to ISA level
3069 StringRef CPU = FeatureStr.split(Separator: "=").second.trim();
3070 BuiltinCpuSupportsArg = llvm::StringSwitch<StringRef>(CPU)
3071#define PPC_AIX_CLONES_CPU(CPU_NAME, AIX_BUILTIN_CPU_SUPPORTS_NAME, _) \
3072 .Case(CPU_NAME, AIX_BUILTIN_CPU_SUPPORTS_NAME)
3073#include "llvm/TargetParser/PPCTargetParser.def"
3074 .Default(Value: "error");
3075 } else {
3076 // Feature strings arrive here already normalized:
3077 // - Positive features: just the name (e.g., "altivec")
3078 // - Negated features: "no-" prefix (e.g., "no-altivec")
3079 if (FeatureStr.starts_with(Prefix: "no-")) {
3080 IsNegated = true;
3081 FeatureStr = FeatureStr.drop_front(N: 3);
3082 }
3083
3084 // Map feature names to __builtin_cpu_supports() strings
3085 BuiltinCpuSupportsArg =
3086 llvm::StringSwitch<StringRef>(FeatureStr)
3087#define PPC_AIX_CLONES_FEATURE(FEATURE_NAME, AIX_BUILTIN_CPU_SUPPORTS_NAME, _, \
3088 __) \
3089 .Case(FEATURE_NAME, AIX_BUILTIN_CPU_SUPPORTS_NAME)
3090#include "llvm/TargetParser/PPCTargetParser.def"
3091 // Features without runtime checks return empty string
3092 .Default(Value: "");
3093
3094 // All features in target_clones must have runtime detection
3095 assert(!BuiltinCpuSupportsArg.empty() &&
3096 "Feature without runtime detection should have been rejected in "
3097 "Sema");
3098 }
3099
3100 assert(getContext().getTargetInfo().validateCpuSupports(
3101 BuiltinCpuSupportsArg));
3102
3103 llvm::Value *Condition =
3104 EmitPPCBuiltinCpu(BuiltinID: Builtin::BI__builtin_cpu_supports,
3105 ReturnType: Builder.getInt1Ty(), CPUStr: BuiltinCpuSupportsArg);
3106
3107 // Negate the condition if this is a negated feature
3108 if (IsNegated) {
3109 Condition = Builder.CreateNot(V: Condition, Name: "neg");
3110 }
3111
3112 llvm::BasicBlock *ThenBlock = createBasicBlock(name: "if.version", parent: Resolver);
3113 CurBlock = createBasicBlock(name: "if.else", parent: Resolver);
3114 Builder.CreateCondBr(Cond: Condition, True: ThenBlock, False: CurBlock);
3115
3116 Builder.SetInsertPoint(ThenBlock);
3117 Builder.CreateRet(V: RO.Function);
3118 }
3119
3120 llvm_unreachable("Default case missing");
3121}
3122
3123void CodeGenFunction::EmitRISCVMultiVersionResolver(
3124 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3125
3126 if (getContext().getTargetInfo().getTriple().getOS() !=
3127 llvm::Triple::OSType::Linux) {
3128 CGM.getDiags().Report(DiagID: diag::err_os_unsupport_riscv_fmv);
3129 return;
3130 }
3131
3132 llvm::BasicBlock *CurBlock = createBasicBlock(name: "resolver_entry", parent: Resolver);
3133 Builder.SetInsertPoint(CurBlock);
3134 EmitRISCVCpuInit();
3135
3136 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
3137 bool HasDefault = false;
3138 unsigned DefaultIndex = 0;
3139
3140 // Check the each candidate function.
3141 for (unsigned Index = 0; Index < Options.size(); Index++) {
3142
3143 if (Options[Index].Features.empty()) {
3144 HasDefault = true;
3145 DefaultIndex = Index;
3146 continue;
3147 }
3148
3149 Builder.SetInsertPoint(CurBlock);
3150
3151 // FeaturesCondition: The bitmask of the required extension has been
3152 // enabled by the runtime object.
3153 // (__riscv_feature_bits.features[i] & REQUIRED_BITMASK) ==
3154 // REQUIRED_BITMASK
3155 //
3156 // When condition is met, return this version of the function.
3157 // Otherwise, try the next version.
3158 //
3159 // if (FeaturesConditionVersion1)
3160 // return Version1;
3161 // else if (FeaturesConditionVersion2)
3162 // return Version2;
3163 // else if (FeaturesConditionVersion3)
3164 // return Version3;
3165 // ...
3166 // else
3167 // return DefaultVersion;
3168
3169 // TODO: Add a condition to check the length before accessing elements.
3170 // Without checking the length first, we may access an incorrect memory
3171 // address when using different versions.
3172 llvm::SmallVector<StringRef, 8> CurrTargetAttrFeats;
3173 llvm::SmallVector<std::string, 8> TargetAttrFeats;
3174
3175 for (StringRef Feat : Options[Index].Features) {
3176 std::vector<std::string> FeatStr =
3177 getContext().getTargetInfo().parseTargetAttr(Str: Feat).Features;
3178
3179 assert(FeatStr.size() == 1 && "Feature string not delimited");
3180
3181 std::string &CurrFeat = FeatStr.front();
3182 if (CurrFeat[0] == '+')
3183 TargetAttrFeats.push_back(Elt: CurrFeat.substr(pos: 1));
3184 }
3185
3186 if (TargetAttrFeats.empty())
3187 continue;
3188
3189 for (std::string &Feat : TargetAttrFeats)
3190 CurrTargetAttrFeats.push_back(Elt: Feat);
3191
3192 Builder.SetInsertPoint(CurBlock);
3193 llvm::Value *FeatsCondition = EmitRISCVCpuSupports(FeaturesStrs: CurrTargetAttrFeats);
3194
3195 llvm::BasicBlock *RetBlock = createBasicBlock(name: "resolver_return", parent: Resolver);
3196 CGBuilderTy RetBuilder(CGM, RetBlock);
3197 CreateMultiVersionResolverReturn(CGM, Resolver, Builder&: RetBuilder,
3198 FuncToReturn: Options[Index].Function, SupportsIFunc);
3199 llvm::BasicBlock *ElseBlock = createBasicBlock(name: "resolver_else", parent: Resolver);
3200
3201 Builder.SetInsertPoint(CurBlock);
3202 Builder.CreateCondBr(Cond: FeatsCondition, True: RetBlock, False: ElseBlock);
3203
3204 CurBlock = ElseBlock;
3205 }
3206
3207 // Finally, emit the default one.
3208 if (HasDefault) {
3209 Builder.SetInsertPoint(CurBlock);
3210 CreateMultiVersionResolverReturn(
3211 CGM, Resolver, Builder, FuncToReturn: Options[DefaultIndex].Function, SupportsIFunc);
3212 return;
3213 }
3214
3215 // If no generic/default, emit an unreachable.
3216 Builder.SetInsertPoint(CurBlock);
3217 EmitTrapCallAndMakeUnreachable();
3218}
3219
3220void CodeGenFunction::EmitAArch64MultiVersionResolver(
3221 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3222 assert(!Options.empty() && "No multiversion resolver options found");
3223 assert(Options.back().Features.size() == 0 && "Default case must be last");
3224 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
3225 assert(SupportsIFunc &&
3226 "Multiversion resolver requires target IFUNC support");
3227 bool AArch64CpuInitialized = false;
3228 llvm::BasicBlock *CurBlock = createBasicBlock(name: "resolver_entry", parent: Resolver);
3229
3230 for (const FMVResolverOption &RO : Options) {
3231 // Skip unreachable versions.
3232 if (RO.Function == nullptr)
3233 continue;
3234
3235 Builder.SetInsertPoint(CurBlock);
3236 llvm::Value *Condition = FormAArch64ResolverCondition(RO);
3237
3238 // The 'default' or 'all features enabled' case.
3239 if (!Condition) {
3240 CreateMultiVersionResolverReturn(CGM, Resolver, Builder, FuncToReturn: RO.Function,
3241 SupportsIFunc);
3242 return;
3243 }
3244
3245 if (!AArch64CpuInitialized) {
3246 Builder.SetInsertPoint(CurBlock->begin());
3247 EmitAArch64CpuInit();
3248 AArch64CpuInitialized = true;
3249 Builder.SetInsertPoint(CurBlock);
3250 }
3251
3252 llvm::BasicBlock *RetBlock = createBasicBlock(name: "resolver_return", parent: Resolver);
3253 CGBuilderTy RetBuilder(CGM, RetBlock);
3254 CreateMultiVersionResolverReturn(CGM, Resolver, Builder&: RetBuilder, FuncToReturn: RO.Function,
3255 SupportsIFunc);
3256 CurBlock = createBasicBlock(name: "resolver_else", parent: Resolver);
3257 Builder.CreateCondBr(Cond: Condition, True: RetBlock, False: CurBlock);
3258 }
3259
3260 // If no default, emit an unreachable.
3261 Builder.SetInsertPoint(CurBlock);
3262 EmitTrapCallAndMakeUnreachable();
3263}
3264
3265void CodeGenFunction::EmitX86MultiVersionResolver(
3266 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3267
3268 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
3269
3270 // Main function's basic block.
3271 llvm::BasicBlock *CurBlock = createBasicBlock(name: "resolver_entry", parent: Resolver);
3272 Builder.SetInsertPoint(CurBlock);
3273 EmitX86CpuInit();
3274
3275 for (const FMVResolverOption &RO : Options) {
3276 Builder.SetInsertPoint(CurBlock);
3277 llvm::Value *Condition = FormX86ResolverCondition(RO);
3278
3279 // The 'default' or 'generic' case.
3280 if (!Condition) {
3281 assert(&RO == Options.end() - 1 &&
3282 "Default or Generic case must be last");
3283 CreateMultiVersionResolverReturn(CGM, Resolver, Builder, FuncToReturn: RO.Function,
3284 SupportsIFunc);
3285 return;
3286 }
3287
3288 llvm::BasicBlock *RetBlock = createBasicBlock(name: "resolver_return", parent: Resolver);
3289 CGBuilderTy RetBuilder(CGM, RetBlock);
3290 CreateMultiVersionResolverReturn(CGM, Resolver, Builder&: RetBuilder, FuncToReturn: RO.Function,
3291 SupportsIFunc);
3292 CurBlock = createBasicBlock(name: "resolver_else", parent: Resolver);
3293 Builder.CreateCondBr(Cond: Condition, True: RetBlock, False: CurBlock);
3294 }
3295
3296 // If no generic/default, emit an unreachable.
3297 Builder.SetInsertPoint(CurBlock);
3298 EmitTrapCallAndMakeUnreachable();
3299}
3300
3301// Loc - where the diagnostic will point, where in the source code this
3302// alignment has failed.
3303// SecondaryLoc - if present (will be present if sufficiently different from
3304// Loc), the diagnostic will additionally point a "Note:" to this location.
3305// It should be the location where the __attribute__((assume_aligned))
3306// was written e.g.
3307void CodeGenFunction::emitAlignmentAssumptionCheck(
3308 llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
3309 SourceLocation SecondaryLoc, llvm::Value *Alignment,
3310 llvm::Value *OffsetValue, llvm::Value *TheCheck,
3311 llvm::Instruction *Assumption) {
3312 assert(isa_and_nonnull<llvm::CallInst>(Assumption) &&
3313 cast<llvm::CallInst>(Assumption)->getCalledOperand() ==
3314 llvm::Intrinsic::getOrInsertDeclaration(Builder.getModule(),
3315 llvm::Intrinsic::assume) &&
3316 "Assumption should be a call to llvm.assume().");
3317 assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
3318 "Assumption should be the last instruction of the basic block, "
3319 "since the basic block is still being generated.");
3320
3321 if (!SanOpts.has(K: SanitizerKind::Alignment))
3322 return;
3323
3324 // Don't check pointers to volatile data. The behavior here is implementation-
3325 // defined.
3326 if (Ty->getPointeeType().isVolatileQualified())
3327 return;
3328
3329 // We need to temorairly remove the assumption so we can insert the
3330 // sanitizer check before it, else the check will be dropped by optimizations.
3331 Assumption->removeFromParent();
3332
3333 {
3334 auto CheckOrdinal = SanitizerKind::SO_Alignment;
3335 auto CheckHandler = SanitizerHandler::AlignmentAssumption;
3336 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
3337
3338 if (!OffsetValue)
3339 OffsetValue = Builder.getInt1(V: false); // no offset.
3340
3341 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
3342 EmitCheckSourceLocation(Loc: SecondaryLoc),
3343 EmitCheckTypeDescriptor(T: Ty)};
3344 llvm::Value *DynamicData[] = {Ptr, Alignment, OffsetValue};
3345 EmitCheck(Checked: {std::make_pair(x&: TheCheck, y&: CheckOrdinal)}, Check: CheckHandler,
3346 StaticArgs: StaticData, DynamicArgs: DynamicData);
3347 }
3348
3349 // We are now in the (new, empty) "cont" basic block.
3350 // Reintroduce the assumption.
3351 Builder.Insert(I: Assumption);
3352 // FIXME: Assumption still has it's original basic block as it's Parent.
3353}
3354
3355llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
3356 if (CGDebugInfo *DI = getDebugInfo())
3357 return DI->SourceLocToDebugLoc(Loc: Location);
3358
3359 return llvm::DebugLoc();
3360}
3361
3362llvm::Value *
3363CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
3364 Stmt::Likelihood LH) {
3365 switch (LH) {
3366 case Stmt::LH_None:
3367 return Cond;
3368 case Stmt::LH_Likely:
3369 case Stmt::LH_Unlikely:
3370 // Don't generate llvm.expect on -O0 as the backend won't use it for
3371 // anything.
3372 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
3373 return Cond;
3374 llvm::Type *CondTy = Cond->getType();
3375 assert(CondTy->isIntegerTy(1) && "expecting condition to be a boolean");
3376 llvm::Function *FnExpect =
3377 CGM.getIntrinsic(IID: llvm::Intrinsic::expect, Tys: CondTy);
3378 llvm::Value *ExpectedValueOfCond =
3379 llvm::ConstantInt::getBool(Ty: CondTy, V: LH == Stmt::LH_Likely);
3380 return Builder.CreateCall(Callee: FnExpect, Args: {Cond, ExpectedValueOfCond},
3381 Name: Cond->getName() + ".expval");
3382 }
3383 llvm_unreachable("Unknown Likelihood");
3384}
3385
3386llvm::Value *CodeGenFunction::emitBoolVecConversion(llvm::Value *SrcVec,
3387 unsigned NumElementsDst,
3388 const llvm::Twine &Name) {
3389 auto *SrcTy = cast<llvm::FixedVectorType>(Val: SrcVec->getType());
3390 unsigned NumElementsSrc = SrcTy->getNumElements();
3391 if (NumElementsSrc == NumElementsDst)
3392 return SrcVec;
3393
3394 std::vector<int> ShuffleMask(NumElementsDst, -1);
3395 for (unsigned MaskIdx = 0;
3396 MaskIdx < std::min<>(a: NumElementsDst, b: NumElementsSrc); ++MaskIdx)
3397 ShuffleMask[MaskIdx] = MaskIdx;
3398
3399 return Builder.CreateShuffleVector(V: SrcVec, Mask: ShuffleMask, Name);
3400}
3401
3402void CodeGenFunction::EmitPointerAuthOperandBundle(
3403 const CGPointerAuthInfo &PointerAuth,
3404 SmallVectorImpl<llvm::OperandBundleDef> &Bundles) {
3405 if (!PointerAuth.isSigned())
3406 return;
3407
3408 auto *Key = Builder.getInt32(C: PointerAuth.getKey());
3409
3410 llvm::Value *Discriminator = PointerAuth.getDiscriminator();
3411 if (!Discriminator)
3412 Discriminator = Builder.getSize(N: 0);
3413
3414 llvm::Value *Args[] = {Key, Discriminator};
3415 Bundles.emplace_back(Args: "ptrauth", Args);
3416}
3417
3418static llvm::Value *EmitPointerAuthCommon(CodeGenFunction &CGF,
3419 const CGPointerAuthInfo &PointerAuth,
3420 llvm::Value *Pointer,
3421 unsigned IntrinsicID) {
3422 if (!PointerAuth)
3423 return Pointer;
3424
3425 auto Key = CGF.Builder.getInt32(C: PointerAuth.getKey());
3426
3427 llvm::Value *Discriminator = PointerAuth.getDiscriminator();
3428 if (!Discriminator) {
3429 Discriminator = CGF.Builder.getSize(N: 0);
3430 }
3431
3432 // Convert the pointer to intptr_t before signing it.
3433 auto OrigType = Pointer->getType();
3434 Pointer = CGF.Builder.CreatePtrToInt(V: Pointer, DestTy: CGF.IntPtrTy);
3435
3436 // call i64 @llvm.ptrauth.sign.i64(i64 %pointer, i32 %key, i64 %discriminator)
3437 auto Intrinsic = CGF.CGM.getIntrinsic(IID: IntrinsicID);
3438 Pointer = CGF.EmitRuntimeCall(callee: Intrinsic, args: {Pointer, Key, Discriminator});
3439
3440 // Convert back to the original type.
3441 Pointer = CGF.Builder.CreateIntToPtr(V: Pointer, DestTy: OrigType);
3442 return Pointer;
3443}
3444
3445llvm::Value *
3446CodeGenFunction::EmitPointerAuthSign(const CGPointerAuthInfo &PointerAuth,
3447 llvm::Value *Pointer) {
3448 if (!PointerAuth.shouldSign())
3449 return Pointer;
3450 return EmitPointerAuthCommon(CGF&: *this, PointerAuth, Pointer,
3451 IntrinsicID: llvm::Intrinsic::ptrauth_sign);
3452}
3453
3454static llvm::Value *EmitStrip(CodeGenFunction &CGF,
3455 const CGPointerAuthInfo &PointerAuth,
3456 llvm::Value *Pointer) {
3457 auto StripIntrinsic = CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::ptrauth_strip);
3458
3459 auto Key = CGF.Builder.getInt32(C: PointerAuth.getKey());
3460 // Convert the pointer to intptr_t before signing it.
3461 auto OrigType = Pointer->getType();
3462 Pointer = CGF.EmitRuntimeCall(
3463 callee: StripIntrinsic, args: {CGF.Builder.CreatePtrToInt(V: Pointer, DestTy: CGF.IntPtrTy), Key});
3464 return CGF.Builder.CreateIntToPtr(V: Pointer, DestTy: OrigType);
3465}
3466
3467llvm::Value *
3468CodeGenFunction::EmitPointerAuthAuth(const CGPointerAuthInfo &PointerAuth,
3469 llvm::Value *Pointer) {
3470 if (PointerAuth.shouldStrip()) {
3471 return EmitStrip(CGF&: *this, PointerAuth, Pointer);
3472 }
3473 if (!PointerAuth.shouldAuth()) {
3474 return Pointer;
3475 }
3476
3477 return EmitPointerAuthCommon(CGF&: *this, PointerAuth, Pointer,
3478 IntrinsicID: llvm::Intrinsic::ptrauth_auth);
3479}
3480
3481void CodeGenFunction::addInstToCurrentSourceAtom(
3482 llvm::Instruction *KeyInstruction, llvm::Value *Backup) {
3483 if (CGDebugInfo *DI = getDebugInfo())
3484 DI->addInstToCurrentSourceAtom(KeyInstruction, Backup);
3485}
3486
3487void CodeGenFunction::addInstToSpecificSourceAtom(
3488 llvm::Instruction *KeyInstruction, llvm::Value *Backup, uint64_t Atom) {
3489 if (CGDebugInfo *DI = getDebugInfo())
3490 DI->addInstToSpecificSourceAtom(KeyInstruction, Backup, Atom);
3491}
3492
3493void CodeGenFunction::addInstToNewSourceAtom(llvm::Instruction *KeyInstruction,
3494 llvm::Value *Backup) {
3495 if (CGDebugInfo *DI = getDebugInfo()) {
3496 ApplyAtomGroup Grp(getDebugInfo());
3497 DI->addInstToCurrentSourceAtom(KeyInstruction, Backup);
3498 }
3499}
3500
3501void CodeGenFunction::emitPFPPostCopyUpdates(Address DestPtr, Address SrcPtr,
3502 QualType Ty) {
3503 for (auto &Field : getContext().findPFPFields(Ty)) {
3504 if (getContext().arePFPFieldsTriviallyCopyable(RD: Field.Field->getParent()))
3505 continue;
3506 auto DestFieldPtr = EmitAddressOfPFPField(RecordPtr: DestPtr, Field);
3507 auto SrcFieldPtr = EmitAddressOfPFPField(RecordPtr: SrcPtr, Field);
3508 Builder.CreateStore(Val: Builder.CreateLoad(Addr: SrcFieldPtr), Addr: DestFieldPtr);
3509 }
3510}
3511