clang 20.0.0git
CodeGenFunction.cpp
Go to the documentation of this file.
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"
25#include "clang/AST/ASTLambda.h"
26#include "clang/AST/Attr.h"
27#include "clang/AST/Decl.h"
28#include "clang/AST/DeclCXX.h"
29#include "clang/AST/Expr.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/StmtObjC.h"
38#include "llvm/ADT/ArrayRef.h"
39#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
40#include "llvm/IR/DataLayout.h"
41#include "llvm/IR/Dominators.h"
42#include "llvm/IR/FPEnv.h"
43#include "llvm/IR/IntrinsicInst.h"
44#include "llvm/IR/Intrinsics.h"
45#include "llvm/IR/MDBuilder.h"
46#include "llvm/IR/Operator.h"
47#include "llvm/Support/CRC.h"
48#include "llvm/Support/xxhash.h"
49#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
50#include "llvm/Transforms/Utils/PromoteMemToReg.h"
51#include <optional>
52
53using namespace clang;
54using namespace CodeGen;
55
56namespace llvm {
57extern cl::opt<bool> EnableSingleByteCoverage;
58} // namespace llvm
59
60/// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
61/// markers.
62static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
63 const LangOptions &LangOpts) {
64 if (CGOpts.DisableLifetimeMarkers)
65 return false;
66
67 // Sanitizers may use markers.
68 if (CGOpts.SanitizeAddressUseAfterScope ||
69 LangOpts.Sanitize.has(SanitizerKind::HWAddress) ||
70 LangOpts.Sanitize.has(SanitizerKind::Memory))
71 return true;
72
73 // For now, only in optimized builds.
74 return CGOpts.OptimizationLevel != 0;
75}
76
77CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
78 : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
79 Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
81 SanOpts(CGM.getLangOpts().Sanitize), CurFPFeatures(CGM.getLangOpts()),
82 DebugInfo(CGM.getModuleDebugInfo()), PGO(cgm),
83 ShouldEmitLifetimeMarkers(
84 shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) {
85 if (!suppressNewContext)
86 CGM.getCXXABI().getMangleContext().startNewFunction();
87 EHStack.setCGF(this);
88
89 SetFastMathFlags(CurFPFeatures);
90}
91
92CodeGenFunction::~CodeGenFunction() {
93 assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
94 assert(DeferredDeactivationCleanupStack.empty() &&
95 "missed to deactivate a cleanup");
96
97 if (getLangOpts().OpenMP && CurFn)
99
100 // If we have an OpenMPIRBuilder we want to finalize functions (incl.
101 // outlining etc) at some point. Doing it once the function codegen is done
102 // seems to be a reasonable spot. We do it here, as opposed to the deletion
103 // time of the CodeGenModule, because we have to ensure the IR has not yet
104 // been "emitted" to the outside, thus, modifications are still sensible.
105 if (CGM.getLangOpts().OpenMPIRBuilder && CurFn)
107}
108
109// Map the LangOption for exception behavior into
110// the corresponding enum in the IR.
111llvm::fp::ExceptionBehavior
113
114 switch (Kind) {
115 case LangOptions::FPE_Ignore: return llvm::fp::ebIgnore;
116 case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap;
117 case LangOptions::FPE_Strict: return llvm::fp::ebStrict;
118 default:
119 llvm_unreachable("Unsupported FP Exception Behavior");
120 }
121}
122
124 llvm::FastMathFlags FMF;
125 FMF.setAllowReassoc(FPFeatures.getAllowFPReassociate());
126 FMF.setNoNaNs(FPFeatures.getNoHonorNaNs());
127 FMF.setNoInfs(FPFeatures.getNoHonorInfs());
128 FMF.setNoSignedZeros(FPFeatures.getNoSignedZero());
129 FMF.setAllowReciprocal(FPFeatures.getAllowReciprocal());
130 FMF.setApproxFunc(FPFeatures.getAllowApproxFunc());
131 FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
132 Builder.setFastMathFlags(FMF);
133}
134
136 const Expr *E)
137 : CGF(CGF) {
138 ConstructorHelper(E->getFPFeaturesInEffect(CGF.getLangOpts()));
139}
140
142 FPOptions FPFeatures)
143 : CGF(CGF) {
144 ConstructorHelper(FPFeatures);
145}
146
147void CodeGenFunction::CGFPOptionsRAII::ConstructorHelper(FPOptions FPFeatures) {
148 OldFPFeatures = CGF.CurFPFeatures;
149 CGF.CurFPFeatures = FPFeatures;
150
151 OldExcept = CGF.Builder.getDefaultConstrainedExcept();
152 OldRounding = CGF.Builder.getDefaultConstrainedRounding();
153
154 if (OldFPFeatures == FPFeatures)
155 return;
156
157 FMFGuard.emplace(CGF.Builder);
158
159 llvm::RoundingMode NewRoundingBehavior = FPFeatures.getRoundingMode();
160 CGF.Builder.setDefaultConstrainedRounding(NewRoundingBehavior);
161 auto NewExceptionBehavior =
163 FPFeatures.getExceptionMode()));
164 CGF.Builder.setDefaultConstrainedExcept(NewExceptionBehavior);
165
166 CGF.SetFastMathFlags(FPFeatures);
167
168 assert((CGF.CurFuncDecl == nullptr || CGF.Builder.getIsFPConstrained() ||
169 isa<CXXConstructorDecl>(CGF.CurFuncDecl) ||
170 isa<CXXDestructorDecl>(CGF.CurFuncDecl) ||
171 (NewExceptionBehavior == llvm::fp::ebIgnore &&
172 NewRoundingBehavior == llvm::RoundingMode::NearestTiesToEven)) &&
173 "FPConstrained should be enabled on entire function");
174
175 auto mergeFnAttrValue = [&](StringRef Name, bool Value) {
176 auto OldValue =
177 CGF.CurFn->getFnAttribute(Name).getValueAsBool();
178 auto NewValue = OldValue & Value;
179 if (OldValue != NewValue)
180 CGF.CurFn->addFnAttr(Name, llvm::toStringRef(NewValue));
181 };
182 mergeFnAttrValue("no-infs-fp-math", FPFeatures.getNoHonorInfs());
183 mergeFnAttrValue("no-nans-fp-math", FPFeatures.getNoHonorNaNs());
184 mergeFnAttrValue("no-signed-zeros-fp-math", FPFeatures.getNoSignedZero());
185 mergeFnAttrValue(
186 "unsafe-fp-math",
187 FPFeatures.getAllowFPReassociate() && FPFeatures.getAllowReciprocal() &&
188 FPFeatures.getAllowApproxFunc() && FPFeatures.getNoSignedZero() &&
189 FPFeatures.allowFPContractAcrossStatement());
190}
191
193 CGF.CurFPFeatures = OldFPFeatures;
194 CGF.Builder.setDefaultConstrainedExcept(OldExcept);
195 CGF.Builder.setDefaultConstrainedRounding(OldRounding);
196}
197
198static LValue
199makeNaturalAlignAddrLValue(llvm::Value *V, QualType T, bool ForPointeeType,
200 bool MightBeSigned, CodeGenFunction &CGF,
201 KnownNonNull_t IsKnownNonNull = NotKnownNonNull) {
202 LValueBaseInfo BaseInfo;
203 TBAAAccessInfo TBAAInfo;
204 CharUnits Alignment =
205 CGF.CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo, ForPointeeType);
206 Address Addr =
207 MightBeSigned
208 ? CGF.makeNaturalAddressForPointer(V, T, Alignment, false, nullptr,
209 nullptr, IsKnownNonNull)
210 : Address(V, CGF.ConvertTypeForMem(T), Alignment, IsKnownNonNull);
211 return CGF.MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
212}
213
214LValue
216 KnownNonNull_t IsKnownNonNull) {
217 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ false,
218 /*MightBeSigned*/ true, *this,
219 IsKnownNonNull);
220}
221
222LValue
224 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ true,
225 /*MightBeSigned*/ true, *this);
226}
227
229 QualType T) {
230 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ false,
231 /*MightBeSigned*/ false, *this);
232}
233
235 QualType T) {
236 return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ true,
237 /*MightBeSigned*/ false, *this);
238}
239
242}
243
245 return CGM.getTypes().ConvertType(T);
246}
247
249 llvm::Type *LLVMTy) {
250 return CGM.getTypes().convertTypeForLoadStore(ASTTy, LLVMTy);
251}
252
254 type = type.getCanonicalType();
255 while (true) {
256 switch (type->getTypeClass()) {
257#define TYPE(name, parent)
258#define ABSTRACT_TYPE(name, parent)
259#define NON_CANONICAL_TYPE(name, parent) case Type::name:
260#define DEPENDENT_TYPE(name, parent) case Type::name:
261#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
262#include "clang/AST/TypeNodes.inc"
263 llvm_unreachable("non-canonical or dependent type in IR-generation");
264
265 case Type::Auto:
266 case Type::DeducedTemplateSpecialization:
267 llvm_unreachable("undeduced type in IR-generation");
268
269 // Various scalar types.
270 case Type::Builtin:
271 case Type::Pointer:
272 case Type::BlockPointer:
273 case Type::LValueReference:
274 case Type::RValueReference:
275 case Type::MemberPointer:
276 case Type::Vector:
277 case Type::ExtVector:
278 case Type::ConstantMatrix:
279 case Type::FunctionProto:
280 case Type::FunctionNoProto:
281 case Type::Enum:
282 case Type::ObjCObjectPointer:
283 case Type::Pipe:
284 case Type::BitInt:
285 return TEK_Scalar;
286
287 // Complexes.
288 case Type::Complex:
289 return TEK_Complex;
290
291 // Arrays, records, and Objective-C objects.
292 case Type::ConstantArray:
293 case Type::IncompleteArray:
294 case Type::VariableArray:
295 case Type::Record:
296 case Type::ObjCObject:
297 case Type::ObjCInterface:
298 case Type::ArrayParameter:
299 return TEK_Aggregate;
300
301 // We operate on atomic values according to their underlying type.
302 case Type::Atomic:
303 type = cast<AtomicType>(type)->getValueType();
304 continue;
305 }
306 llvm_unreachable("unknown type kind!");
307 }
308}
309
310llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
311 // For cleanliness, we try to avoid emitting the return block for
312 // simple cases.
313 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
314
315 if (CurBB) {
316 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
317
318 // We have a valid insert point, reuse it if it is empty or there are no
319 // explicit jumps to the return block.
320 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
321 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
322 delete ReturnBlock.getBlock();
323 ReturnBlock = JumpDest();
324 } else
326 return llvm::DebugLoc();
327 }
328
329 // Otherwise, if the return block is the target of a single direct
330 // branch then we can just put the code in that block instead. This
331 // cleans up functions which started with a unified return block.
332 if (ReturnBlock.getBlock()->hasOneUse()) {
333 llvm::BranchInst *BI =
334 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
335 if (BI && BI->isUnconditional() &&
336 BI->getSuccessor(0) == ReturnBlock.getBlock()) {
337 // Record/return the DebugLoc of the simple 'return' expression to be used
338 // later by the actual 'ret' instruction.
339 llvm::DebugLoc Loc = BI->getDebugLoc();
340 Builder.SetInsertPoint(BI->getParent());
341 BI->eraseFromParent();
342 delete ReturnBlock.getBlock();
343 ReturnBlock = JumpDest();
344 return Loc;
345 }
346 }
347
348 // FIXME: We are at an unreachable point, there is no reason to emit the block
349 // unless it has uses. However, we still need a place to put the debug
350 // region.end for now.
351
353 return llvm::DebugLoc();
354}
355
356static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
357 if (!BB) return;
358 if (!BB->use_empty()) {
359 CGF.CurFn->insert(CGF.CurFn->end(), BB);
360 return;
361 }
362 delete BB;
363}
364
366 assert(BreakContinueStack.empty() &&
367 "mismatched push/pop in break/continue stack!");
368 assert(LifetimeExtendedCleanupStack.empty() &&
369 "mismatched push/pop of cleanups in EHStack!");
370 assert(DeferredDeactivationCleanupStack.empty() &&
371 "mismatched activate/deactivate of cleanups!");
372
374 ConvergenceTokenStack.pop_back();
375 assert(ConvergenceTokenStack.empty() &&
376 "mismatched push/pop in convergence stack!");
377 }
378
379 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
380 && NumSimpleReturnExprs == NumReturnExprs
381 && ReturnBlock.getBlock()->use_empty();
382 // Usually the return expression is evaluated before the cleanup
383 // code. If the function contains only a simple return statement,
384 // such as a constant, the location before the cleanup code becomes
385 // the last useful breakpoint in the function, because the simple
386 // return expression will be evaluated after the cleanup code. To be
387 // safe, set the debug location for cleanup code to the location of
388 // the return statement. Otherwise the cleanup code should be at the
389 // end of the function's lexical scope.
390 //
391 // If there are multiple branches to the return block, the branch
392 // instructions will get the location of the return statements and
393 // all will be fine.
394 if (CGDebugInfo *DI = getDebugInfo()) {
395 if (OnlySimpleReturnStmts)
396 DI->EmitLocation(Builder, LastStopPoint);
397 else
398 DI->EmitLocation(Builder, EndLoc);
399 }
400
401 // Pop any cleanups that might have been associated with the
402 // parameters. Do this in whatever block we're currently in; it's
403 // important to do this before we enter the return block or return
404 // edges will be *really* confused.
405 bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
406 bool HasOnlyLifetimeMarkers =
408 bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
409
410 std::optional<ApplyDebugLocation> OAL;
411 if (HasCleanups) {
412 // Make sure the line table doesn't jump back into the body for
413 // the ret after it's been at EndLoc.
414 if (CGDebugInfo *DI = getDebugInfo()) {
415 if (OnlySimpleReturnStmts)
416 DI->EmitLocation(Builder, EndLoc);
417 else
418 // We may not have a valid end location. Try to apply it anyway, and
419 // fall back to an artificial location if needed.
421 }
422
424 }
425
426 // Emit function epilog (to return).
427 llvm::DebugLoc Loc = EmitReturnBlock();
428
430 if (CGM.getCodeGenOpts().InstrumentFunctions)
431 CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
432 if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
433 CurFn->addFnAttr("instrument-function-exit-inlined",
434 "__cyg_profile_func_exit");
435 }
436
437 // Emit debug descriptor for function end.
438 if (CGDebugInfo *DI = getDebugInfo())
439 DI->EmitFunctionEnd(Builder, CurFn);
440
441 // Reset the debug location to that of the simple 'return' expression, if any
442 // rather than that of the end of the function's scope '}'.
443 ApplyDebugLocation AL(*this, Loc);
444 EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
446
447 assert(EHStack.empty() &&
448 "did not remove all scopes from cleanup stack!");
449
450 // If someone did an indirect goto, emit the indirect goto block at the end of
451 // the function.
452 if (IndirectBranch) {
453 EmitBlock(IndirectBranch->getParent());
454 Builder.ClearInsertionPoint();
455 }
456
457 // If some of our locals escaped, insert a call to llvm.localescape in the
458 // entry block.
459 if (!EscapedLocals.empty()) {
460 // Invert the map from local to index into a simple vector. There should be
461 // no holes.
463 EscapeArgs.resize(EscapedLocals.size());
464 for (auto &Pair : EscapedLocals)
465 EscapeArgs[Pair.second] = Pair.first;
466 llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
467 &CGM.getModule(), llvm::Intrinsic::localescape);
468 CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
469 }
470
471 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
472 llvm::Instruction *Ptr = AllocaInsertPt;
473 AllocaInsertPt = nullptr;
474 Ptr->eraseFromParent();
475
476 // PostAllocaInsertPt, if created, was lazily created when it was required,
477 // remove it now since it was just created for our own convenience.
478 if (PostAllocaInsertPt) {
479 llvm::Instruction *PostPtr = PostAllocaInsertPt;
480 PostAllocaInsertPt = nullptr;
481 PostPtr->eraseFromParent();
482 }
483
484 // If someone took the address of a label but never did an indirect goto, we
485 // made a zero entry PHI node, which is illegal, zap it now.
486 if (IndirectBranch) {
487 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
488 if (PN->getNumIncomingValues() == 0) {
489 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
490 PN->eraseFromParent();
491 }
492 }
493
495 EmitIfUsed(*this, TerminateLandingPad);
496 EmitIfUsed(*this, TerminateHandler);
497 EmitIfUsed(*this, UnreachableBlock);
498
499 for (const auto &FuncletAndParent : TerminateFunclets)
500 EmitIfUsed(*this, FuncletAndParent.second);
501
502 if (CGM.getCodeGenOpts().EmitDeclMetadata)
503 EmitDeclMetadata();
504
505 for (const auto &R : DeferredReplacements) {
506 if (llvm::Value *Old = R.first) {
507 Old->replaceAllUsesWith(R.second);
508 cast<llvm::Instruction>(Old)->eraseFromParent();
509 }
510 }
511 DeferredReplacements.clear();
512
513 // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
514 // PHIs if the current function is a coroutine. We don't do it for all
515 // functions as it may result in slight increase in numbers of instructions
516 // if compiled with no optimizations. We do it for coroutine as the lifetime
517 // of CleanupDestSlot alloca make correct coroutine frame building very
518 // difficult.
520 llvm::DominatorTree DT(*CurFn);
521 llvm::PromoteMemToReg(
522 cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
524 }
525
526 // Scan function arguments for vector width.
527 for (llvm::Argument &A : CurFn->args())
528 if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
529 LargestVectorWidth =
530 std::max((uint64_t)LargestVectorWidth,
531 VT->getPrimitiveSizeInBits().getKnownMinValue());
532
533 // Update vector width based on return type.
534 if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
535 LargestVectorWidth =
536 std::max((uint64_t)LargestVectorWidth,
537 VT->getPrimitiveSizeInBits().getKnownMinValue());
538
539 if (CurFnInfo->getMaxVectorWidth() > LargestVectorWidth)
540 LargestVectorWidth = CurFnInfo->getMaxVectorWidth();
541
542 // Add the min-legal-vector-width attribute. This contains the max width from:
543 // 1. min-vector-width attribute used in the source program.
544 // 2. Any builtins used that have a vector width specified.
545 // 3. Values passed in and out of inline assembly.
546 // 4. Width of vector arguments and return types for this function.
547 // 5. Width of vector arguments and return types for functions called by this
548 // function.
549 if (getContext().getTargetInfo().getTriple().isX86())
550 CurFn->addFnAttr("min-legal-vector-width",
551 llvm::utostr(LargestVectorWidth));
552
553 // Add vscale_range attribute if appropriate.
554 std::optional<std::pair<unsigned, unsigned>> VScaleRange =
556 if (VScaleRange) {
557 CurFn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(
558 getLLVMContext(), VScaleRange->first, VScaleRange->second));
559 }
560
561 // If we generated an unreachable return block, delete it now.
562 if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) {
563 Builder.ClearInsertionPoint();
564 ReturnBlock.getBlock()->eraseFromParent();
565 }
566 if (ReturnValue.isValid()) {
567 auto *RetAlloca =
568 dyn_cast<llvm::AllocaInst>(ReturnValue.emitRawPointer(*this));
569 if (RetAlloca && RetAlloca->use_empty()) {
570 RetAlloca->eraseFromParent();
572 }
573 }
574}
575
576/// ShouldInstrumentFunction - Return true if the current function should be
577/// instrumented with __cyg_profile_func_* calls
579 if (!CGM.getCodeGenOpts().InstrumentFunctions &&
580 !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining &&
581 !CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
582 return false;
583 if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
584 return false;
585 return true;
586}
587
589 if (!CurFuncDecl)
590 return false;
591 return CurFuncDecl->hasAttr<DisableSanitizerInstrumentationAttr>();
592}
593
594/// ShouldXRayInstrument - Return true if the current function should be
595/// instrumented with XRay nop sleds.
597 return CGM.getCodeGenOpts().XRayInstrumentFunctions;
598}
599
600/// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
601/// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
603 return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
604 (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
607}
608
610 return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
611 (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
614}
615
616llvm::ConstantInt *
618 // Remove any (C++17) exception specifications, to allow calling e.g. a
619 // noexcept function through a non-noexcept pointer.
620 if (!Ty->isFunctionNoProtoType())
622 std::string Mangled;
623 llvm::raw_string_ostream Out(Mangled);
625 return llvm::ConstantInt::get(
626 CGM.Int32Ty, static_cast<uint32_t>(llvm::xxh3_64bits(Mangled)));
627}
628
629void CodeGenFunction::EmitKernelMetadata(const FunctionDecl *FD,
630 llvm::Function *Fn) {
631 if (!FD->hasAttr<OpenCLKernelAttr>() && !FD->hasAttr<CUDAGlobalAttr>())
632 return;
633
634 llvm::LLVMContext &Context = getLLVMContext();
635
636 CGM.GenKernelArgMetadata(Fn, FD, this);
637
638 if (!getLangOpts().OpenCL)
639 return;
640
641 if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
642 QualType HintQTy = A->getTypeHint();
643 const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
644 bool IsSignedInteger =
645 HintQTy->isSignedIntegerType() ||
646 (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType());
647 llvm::Metadata *AttrMDArgs[] = {
648 llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
649 CGM.getTypes().ConvertType(A->getTypeHint()))),
650 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
651 llvm::IntegerType::get(Context, 32),
652 llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
653 Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
654 }
655
656 if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
657 llvm::Metadata *AttrMDArgs[] = {
658 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
659 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
660 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
661 Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
662 }
663
664 if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
665 llvm::Metadata *AttrMDArgs[] = {
666 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
667 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
668 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
669 Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
670 }
671
672 if (const OpenCLIntelReqdSubGroupSizeAttr *A =
673 FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
674 llvm::Metadata *AttrMDArgs[] = {
675 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
676 Fn->setMetadata("intel_reqd_sub_group_size",
677 llvm::MDNode::get(Context, AttrMDArgs));
678 }
679}
680
681/// Determine whether the function F ends with a return stmt.
682static bool endsWithReturn(const Decl* F) {
683 const Stmt *Body = nullptr;
684 if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
685 Body = FD->getBody();
686 else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
687 Body = OMD->getBody();
688
689 if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
690 auto LastStmt = CS->body_rbegin();
691 if (LastStmt != CS->body_rend())
692 return isa<ReturnStmt>(*LastStmt);
693 }
694 return false;
695}
696
698 if (SanOpts.has(SanitizerKind::Thread)) {
699 Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
700 Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
701 }
702}
703
704/// Check if the return value of this function requires sanitization.
705bool CodeGenFunction::requiresReturnValueCheck() const {
706 return requiresReturnValueNullabilityCheck() ||
707 (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && CurCodeDecl &&
708 CurCodeDecl->getAttr<ReturnsNonNullAttr>());
709}
710
711static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
712 auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
713 if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
714 !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") ||
715 (MD->getNumParams() != 1 && MD->getNumParams() != 2))
716 return false;
717
718 if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
719 return false;
720
721 if (MD->getNumParams() == 2) {
722 auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
723 if (!PT || !PT->isVoidPointerType() ||
724 !PT->getPointeeType().isConstQualified())
725 return false;
726 }
727
728 return true;
729}
730
731bool CodeGenFunction::isInAllocaArgument(CGCXXABI &ABI, QualType Ty) {
732 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
733 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
734}
735
736bool CodeGenFunction::hasInAllocaArg(const CXXMethodDecl *MD) {
737 return getTarget().getTriple().getArch() == llvm::Triple::x86 &&
739 llvm::any_of(MD->parameters(), [&](ParmVarDecl *P) {
740 return isInAllocaArgument(CGM.getCXXABI(), P->getType());
741 });
742}
743
744/// Return the UBSan prologue signature for \p FD if one is available.
745static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
746 const FunctionDecl *FD) {
747 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
748 if (!MD->isStatic())
749 return nullptr;
751}
752
754 llvm::Function *Fn,
755 const CGFunctionInfo &FnInfo,
756 const FunctionArgList &Args,
758 SourceLocation StartLoc) {
759 assert(!CurFn &&
760 "Do not use a CodeGenFunction object for more than one function");
761
762 const Decl *D = GD.getDecl();
763
764 DidCallStackSave = false;
765 CurCodeDecl = D;
766 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
767 if (FD && FD->usesSEHTry())
768 CurSEHParent = GD;
769 CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
770 FnRetTy = RetTy;
771 CurFn = Fn;
772 CurFnInfo = &FnInfo;
773 assert(CurFn->isDeclaration() && "Function already has body?");
774
775 // If this function is ignored for any of the enabled sanitizers,
776 // disable the sanitizer for the function.
777 do {
778#define SANITIZER(NAME, ID) \
779 if (SanOpts.empty()) \
780 break; \
781 if (SanOpts.has(SanitizerKind::ID)) \
782 if (CGM.isInNoSanitizeList(SanitizerKind::ID, Fn, Loc)) \
783 SanOpts.set(SanitizerKind::ID, false);
784
785#include "clang/Basic/Sanitizers.def"
786#undef SANITIZER
787 } while (false);
788
789 if (D) {
790 const bool SanitizeBounds = SanOpts.hasOneOf(SanitizerKind::Bounds);
791 SanitizerMask no_sanitize_mask;
792 bool NoSanitizeCoverage = false;
793
794 for (auto *Attr : D->specific_attrs<NoSanitizeAttr>()) {
795 no_sanitize_mask |= Attr->getMask();
796 // SanitizeCoverage is not handled by SanOpts.
797 if (Attr->hasCoverage())
798 NoSanitizeCoverage = true;
799 }
800
801 // Apply the no_sanitize* attributes to SanOpts.
802 SanOpts.Mask &= ~no_sanitize_mask;
803 if (no_sanitize_mask & SanitizerKind::Address)
804 SanOpts.set(SanitizerKind::KernelAddress, false);
805 if (no_sanitize_mask & SanitizerKind::KernelAddress)
806 SanOpts.set(SanitizerKind::Address, false);
807 if (no_sanitize_mask & SanitizerKind::HWAddress)
808 SanOpts.set(SanitizerKind::KernelHWAddress, false);
809 if (no_sanitize_mask & SanitizerKind::KernelHWAddress)
810 SanOpts.set(SanitizerKind::HWAddress, false);
811
812 if (SanitizeBounds && !SanOpts.hasOneOf(SanitizerKind::Bounds))
813 Fn->addFnAttr(llvm::Attribute::NoSanitizeBounds);
814
815 if (NoSanitizeCoverage && CGM.getCodeGenOpts().hasSanitizeCoverage())
816 Fn->addFnAttr(llvm::Attribute::NoSanitizeCoverage);
817
818 // Some passes need the non-negated no_sanitize attribute. Pass them on.
820 if (no_sanitize_mask & SanitizerKind::Thread)
821 Fn->addFnAttr("no_sanitize_thread");
822 }
823 }
824
826 CurFn->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
827 } else {
828 // Apply sanitizer attributes to the function.
829 if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
830 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
831 if (SanOpts.hasOneOf(SanitizerKind::HWAddress |
832 SanitizerKind::KernelHWAddress))
833 Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
834 if (SanOpts.has(SanitizerKind::MemtagStack))
835 Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
836 if (SanOpts.has(SanitizerKind::Thread))
837 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
838 if (SanOpts.has(SanitizerKind::NumericalStability))
839 Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability);
840 if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
841 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
842 }
843 if (SanOpts.has(SanitizerKind::SafeStack))
844 Fn->addFnAttr(llvm::Attribute::SafeStack);
845 if (SanOpts.has(SanitizerKind::ShadowCallStack))
846 Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
847
848 // Apply fuzzing attribute to the function.
849 if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
850 Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
851
852 // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
853 // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
854 if (SanOpts.has(SanitizerKind::Thread)) {
855 if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
856 const IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
857 if (OMD->getMethodFamily() == OMF_dealloc ||
858 OMD->getMethodFamily() == OMF_initialize ||
859 (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
861 }
862 }
863 }
864
865 // Ignore unrelated casts in STL allocate() since the allocator must cast
866 // from void* to T* before object initialization completes. Don't match on the
867 // namespace because not all allocators are in std::
868 if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
870 SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
871 }
872
873 // Ignore null checks in coroutine functions since the coroutines passes
874 // are not aware of how to move the extra UBSan instructions across the split
875 // coroutine boundaries.
876 if (D && SanOpts.has(SanitizerKind::Null))
877 if (FD && FD->getBody() &&
878 FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
879 SanOpts.Mask &= ~SanitizerKind::Null;
880
881 // Add pointer authentication attributes.
882 const CodeGenOptions &CodeGenOpts = CGM.getCodeGenOpts();
883 if (CodeGenOpts.PointerAuth.ReturnAddresses)
884 Fn->addFnAttr("ptrauth-returns");
885 if (CodeGenOpts.PointerAuth.FunctionPointers)
886 Fn->addFnAttr("ptrauth-calls");
887 if (CodeGenOpts.PointerAuth.AuthTraps)
888 Fn->addFnAttr("ptrauth-auth-traps");
889 if (CodeGenOpts.PointerAuth.IndirectGotos)
890 Fn->addFnAttr("ptrauth-indirect-gotos");
891
892 // Apply xray attributes to the function (as a string, for now)
893 bool AlwaysXRayAttr = false;
894 if (const auto *XRayAttr = D ? D->getAttr<XRayInstrumentAttr>() : nullptr) {
899 if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction()) {
900 Fn->addFnAttr("function-instrument", "xray-always");
901 AlwaysXRayAttr = true;
902 }
903 if (XRayAttr->neverXRayInstrument())
904 Fn->addFnAttr("function-instrument", "xray-never");
905 if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
907 Fn->addFnAttr("xray-log-args",
908 llvm::utostr(LogArgs->getArgumentCount()));
909 }
910 } else {
912 Fn->addFnAttr(
913 "xray-instruction-threshold",
914 llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
915 }
916
918 if (CGM.getCodeGenOpts().XRayIgnoreLoops)
919 Fn->addFnAttr("xray-ignore-loops");
920
923 Fn->addFnAttr("xray-skip-exit");
924
927 Fn->addFnAttr("xray-skip-entry");
928
929 auto FuncGroups = CGM.getCodeGenOpts().XRayTotalFunctionGroups;
930 if (FuncGroups > 1) {
931 auto FuncName = llvm::ArrayRef<uint8_t>(CurFn->getName().bytes_begin(),
932 CurFn->getName().bytes_end());
933 auto Group = crc32(FuncName) % FuncGroups;
934 if (Group != CGM.getCodeGenOpts().XRaySelectedFunctionGroup &&
935 !AlwaysXRayAttr)
936 Fn->addFnAttr("function-instrument", "xray-never");
937 }
938 }
939
940 if (CGM.getCodeGenOpts().getProfileInstr() != CodeGenOptions::ProfileNone) {
943 Fn->addFnAttr(llvm::Attribute::SkipProfile);
944 break;
946 Fn->addFnAttr(llvm::Attribute::NoProfile);
947 break;
949 break;
950 }
951 }
952
953 unsigned Count, Offset;
954 if (const auto *Attr =
955 D ? D->getAttr<PatchableFunctionEntryAttr>() : nullptr) {
956 Count = Attr->getCount();
957 Offset = Attr->getOffset();
958 } else {
959 Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount;
960 Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset;
961 }
962 if (Count && Offset <= Count) {
963 Fn->addFnAttr("patchable-function-entry", std::to_string(Count - Offset));
964 if (Offset)
965 Fn->addFnAttr("patchable-function-prefix", std::to_string(Offset));
966 }
967 // Instruct that functions for COFF/CodeView targets should start with a
968 // patchable instruction, but only on x86/x64. Don't forward this to ARM/ARM64
969 // backends as they don't need it -- instructions on these architectures are
970 // always atomically patchable at runtime.
971 if (CGM.getCodeGenOpts().HotPatch &&
972 getContext().getTargetInfo().getTriple().isX86() &&
973 getContext().getTargetInfo().getTriple().getEnvironment() !=
974 llvm::Triple::CODE16)
975 Fn->addFnAttr("patchable-function", "prologue-short-redirect");
976
977 // Add no-jump-tables value.
978 if (CGM.getCodeGenOpts().NoUseJumpTables)
979 Fn->addFnAttr("no-jump-tables", "true");
980
981 // Add no-inline-line-tables value.
982 if (CGM.getCodeGenOpts().NoInlineLineTables)
983 Fn->addFnAttr("no-inline-line-tables");
984
985 // Add profile-sample-accurate value.
986 if (CGM.getCodeGenOpts().ProfileSampleAccurate)
987 Fn->addFnAttr("profile-sample-accurate");
988
989 if (!CGM.getCodeGenOpts().SampleProfileFile.empty())
990 Fn->addFnAttr("use-sample-profile");
991
992 if (D && D->hasAttr<CFICanonicalJumpTableAttr>())
993 Fn->addFnAttr("cfi-canonical-jump-table");
994
995 if (D && D->hasAttr<NoProfileFunctionAttr>())
996 Fn->addFnAttr(llvm::Attribute::NoProfile);
997
998 if (D && D->hasAttr<HybridPatchableAttr>())
999 Fn->addFnAttr(llvm::Attribute::HybridPatchable);
1000
1001 if (D) {
1002 // Function attributes take precedence over command line flags.
1003 if (auto *A = D->getAttr<FunctionReturnThunksAttr>()) {
1004 switch (A->getThunkType()) {
1005 case FunctionReturnThunksAttr::Kind::Keep:
1006 break;
1007 case FunctionReturnThunksAttr::Kind::Extern:
1008 Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern);
1009 break;
1010 }
1011 } else if (CGM.getCodeGenOpts().FunctionReturnThunks)
1012 Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern);
1013 }
1014
1015 if (FD && (getLangOpts().OpenCL ||
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("clspv_libclc_builtin",
1024 llvm::MDNode::get(getLLVMContext(), {}));
1025 }
1026
1027 // If we are checking function types, emit a function type signature as
1028 // prologue data.
1029 if (FD && SanOpts.has(SanitizerKind::Function)) {
1030 if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
1031 llvm::LLVMContext &Ctx = Fn->getContext();
1032 llvm::MDBuilder MDB(Ctx);
1033 Fn->setMetadata(
1034 llvm::LLVMContext::MD_func_sanitize,
1035 MDB.createRTTIPointerPrologue(
1036 PrologueSig, getUBSanFunctionTypeHash(FD->getType())));
1037 }
1038 }
1039
1040 // If we're checking nullability, we need to know whether we can check the
1041 // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
1042 if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
1044 if (Nullability && *Nullability == NullabilityKind::NonNull &&
1045 !FnRetTy->isRecordType()) {
1046 if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
1047 CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
1048 RetValNullabilityPrecondition =
1049 llvm::ConstantInt::getTrue(getLLVMContext());
1050 }
1051 }
1052
1053 // If we're in C++ mode and the function name is "main", it is guaranteed
1054 // to be norecurse by the standard (3.6.1.3 "The function main shall not be
1055 // used within a program").
1056 //
1057 // OpenCL C 2.0 v2.2-11 s6.9.i:
1058 // Recursion is not supported.
1059 //
1060 // SYCL v1.2.1 s3.10:
1061 // kernels cannot include RTTI information, exception classes,
1062 // recursive code, virtual functions or make use of C++ libraries that
1063 // are not compiled for the device.
1064 if (FD && ((getLangOpts().CPlusPlus && FD->isMain()) ||
1065 getLangOpts().OpenCL || getLangOpts().SYCLIsDevice ||
1066 (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>())))
1067 Fn->addFnAttr(llvm::Attribute::NoRecurse);
1068
1069 llvm::RoundingMode RM = getLangOpts().getDefaultRoundingMode();
1070 llvm::fp::ExceptionBehavior FPExceptionBehavior =
1071 ToConstrainedExceptMD(getLangOpts().getDefaultExceptionMode());
1072 Builder.setDefaultConstrainedRounding(RM);
1073 Builder.setDefaultConstrainedExcept(FPExceptionBehavior);
1074 if ((FD && (FD->UsesFPIntrin() || FD->hasAttr<StrictFPAttr>())) ||
1075 (!FD && (FPExceptionBehavior != llvm::fp::ebIgnore ||
1076 RM != llvm::RoundingMode::NearestTiesToEven))) {
1077 Builder.setIsFPConstrained(true);
1078 Fn->addFnAttr(llvm::Attribute::StrictFP);
1079 }
1080
1081 // If a custom alignment is used, force realigning to this alignment on
1082 // any main function which certainly will need it.
1083 if (FD && ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
1084 CGM.getCodeGenOpts().StackAlignment))
1085 Fn->addFnAttr("stackrealign");
1086
1087 // "main" doesn't need to zero out call-used registers.
1088 if (FD && FD->isMain())
1089 Fn->removeFnAttr("zero-call-used-regs");
1090
1091 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
1092
1093 // Create a marker to make it easy to insert allocas into the entryblock
1094 // later. Don't create this with the builder, because we don't want it
1095 // folded.
1096 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
1097 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
1098
1100
1101 Builder.SetInsertPoint(EntryBB);
1102
1103 // If we're checking the return value, allocate space for a pointer to a
1104 // precise source location of the checked return statement.
1105 if (requiresReturnValueCheck()) {
1106 ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
1107 Builder.CreateStore(llvm::ConstantPointerNull::get(Int8PtrTy),
1108 ReturnLocation);
1109 }
1110
1111 // Emit subprogram debug descriptor.
1112 if (CGDebugInfo *DI = getDebugInfo()) {
1113 // Reconstruct the type from the argument list so that implicit parameters,
1114 // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
1115 // convention.
1116 DI->emitFunctionStart(GD, Loc, StartLoc,
1117 DI->getFunctionType(FD, RetTy, Args), CurFn,
1119 }
1120
1122 if (CGM.getCodeGenOpts().InstrumentFunctions)
1123 CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
1124 if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
1125 CurFn->addFnAttr("instrument-function-entry-inlined",
1126 "__cyg_profile_func_enter");
1127 if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
1128 CurFn->addFnAttr("instrument-function-entry-inlined",
1129 "__cyg_profile_func_enter_bare");
1130 }
1131
1132 // Since emitting the mcount call here impacts optimizations such as function
1133 // inlining, we just add an attribute to insert a mcount call in backend.
1134 // The attribute "counting-function" is set to mcount function name which is
1135 // architecture dependent.
1136 if (CGM.getCodeGenOpts().InstrumentForProfiling) {
1137 // Calls to fentry/mcount should not be generated if function has
1138 // the no_instrument_function attribute.
1139 if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
1140 if (CGM.getCodeGenOpts().CallFEntry)
1141 Fn->addFnAttr("fentry-call", "true");
1142 else {
1143 Fn->addFnAttr("instrument-function-entry-inlined",
1144 getTarget().getMCountName());
1145 }
1146 if (CGM.getCodeGenOpts().MNopMCount) {
1147 if (!CGM.getCodeGenOpts().CallFEntry)
1148 CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1149 << "-mnop-mcount" << "-mfentry";
1150 Fn->addFnAttr("mnop-mcount");
1151 }
1152
1153 if (CGM.getCodeGenOpts().RecordMCount) {
1154 if (!CGM.getCodeGenOpts().CallFEntry)
1155 CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1156 << "-mrecord-mcount" << "-mfentry";
1157 Fn->addFnAttr("mrecord-mcount");
1158 }
1159 }
1160 }
1161
1162 if (CGM.getCodeGenOpts().PackedStack) {
1163 if (getContext().getTargetInfo().getTriple().getArch() !=
1164 llvm::Triple::systemz)
1165 CGM.getDiags().Report(diag::err_opt_not_valid_on_target)
1166 << "-mpacked-stack";
1167 Fn->addFnAttr("packed-stack");
1168 }
1169
1170 if (CGM.getCodeGenOpts().WarnStackSize != UINT_MAX &&
1171 !CGM.getDiags().isIgnored(diag::warn_fe_backend_frame_larger_than, Loc))
1172 Fn->addFnAttr("warn-stack-size",
1173 std::to_string(CGM.getCodeGenOpts().WarnStackSize));
1174
1175 if (RetTy->isVoidType()) {
1176 // Void type; nothing to return.
1178
1179 // Count the implicit return.
1180 if (!endsWithReturn(D))
1181 ++NumReturnExprs;
1183 // Indirect return; emit returned value directly into sret slot.
1184 // This reduces code size, and affects correctness in C++.
1185 auto AI = CurFn->arg_begin();
1187 ++AI;
1189 &*AI, RetTy, CurFnInfo->getReturnInfo().getIndirectAlign(), false,
1190 nullptr, nullptr, KnownNonNull);
1196 }
1199 // Load the sret pointer from the argument struct and return into that.
1200 unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
1201 llvm::Function::arg_iterator EI = CurFn->arg_end();
1202 --EI;
1203 llvm::Value *Addr = Builder.CreateStructGEP(
1204 CurFnInfo->getArgStruct(), &*EI, Idx);
1205 llvm::Type *Ty =
1206 cast<llvm::GetElementPtrInst>(Addr)->getResultElementType();
1208 Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result");
1209 ReturnValue = Address(Addr, ConvertType(RetTy),
1211 } else {
1212 ReturnValue = CreateIRTemp(RetTy, "retval");
1213
1214 // Tell the epilog emitter to autorelease the result. We do this
1215 // now so that various specialized functions can suppress it
1216 // during their IR-generation.
1217 if (getLangOpts().ObjCAutoRefCount &&
1219 RetTy->isObjCRetainableType())
1220 AutoreleaseResult = true;
1221 }
1222
1224
1226
1227 // Emit OpenMP specific initialization of the device functions.
1228 if (getLangOpts().OpenMP && CurCodeDecl)
1230
1231 if (FD && getLangOpts().HLSL) {
1232 // Handle emitting HLSL entry functions.
1233 if (FD->hasAttr<HLSLShaderAttr>()) {
1235 }
1237 }
1238
1240
1241 if (const CXXMethodDecl *MD = dyn_cast_if_present<CXXMethodDecl>(D);
1242 MD && !MD->isStatic()) {
1243 bool IsInLambda =
1244 MD->getParent()->isLambda() && MD->getOverloadedOperator() == OO_Call;
1247 if (IsInLambda) {
1248 // We're in a lambda; figure out the captures.
1252 // If the lambda captures the object referred to by '*this' - either by
1253 // value or by reference, make sure CXXThisValue points to the correct
1254 // object.
1255
1256 // Get the lvalue for the field (which is a copy of the enclosing object
1257 // or contains the address of the enclosing object).
1260 // If the enclosing object was captured by value, just use its
1261 // address. Sign this pointer.
1262 CXXThisValue = ThisFieldLValue.getPointer(*this);
1263 } else {
1264 // Load the lvalue pointed to by the field, since '*this' was captured
1265 // by reference.
1266 CXXThisValue =
1267 EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
1268 }
1269 }
1270 for (auto *FD : MD->getParent()->fields()) {
1271 if (FD->hasCapturedVLAType()) {
1272 auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
1274 auto VAT = FD->getCapturedVLAType();
1275 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
1276 }
1277 }
1278 } else if (MD->isImplicitObjectMemberFunction()) {
1279 // Not in a lambda; just use 'this' from the method.
1280 // FIXME: Should we generate a new load for each use of 'this'? The
1281 // fast register allocator would be happier...
1282 CXXThisValue = CXXABIThisValue;
1283 }
1284
1285 // Check the 'this' pointer once per function, if it's available.
1286 if (CXXABIThisValue) {
1287 SanitizerSet SkippedChecks;
1288 SkippedChecks.set(SanitizerKind::ObjectSize, true);
1289 QualType ThisTy = MD->getThisType();
1290
1291 // If this is the call operator of a lambda with no captures, it
1292 // may have a static invoker function, which may call this operator with
1293 // a null 'this' pointer.
1295 SkippedChecks.set(SanitizerKind::Null, true);
1296
1298 isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall : TCK_MemberCall,
1299 Loc, CXXABIThisValue, ThisTy, CXXABIThisAlignment, SkippedChecks);
1300 }
1301 }
1302
1303 // If any of the arguments have a variably modified type, make sure to
1304 // emit the type size, but only if the function is not naked. Naked functions
1305 // have no prolog to run this evaluation.
1306 if (!FD || !FD->hasAttr<NakedAttr>()) {
1307 for (const VarDecl *VD : Args) {
1308 // Dig out the type as written from ParmVarDecls; it's unclear whether
1309 // the standard (C99 6.9.1p10) requires this, but we're following the
1310 // precedent set by gcc.
1311 QualType Ty;
1312 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1313 Ty = PVD->getOriginalType();
1314 else
1315 Ty = VD->getType();
1316
1317 if (Ty->isVariablyModifiedType())
1319 }
1320 }
1321 // Emit a location at the end of the prologue.
1322 if (CGDebugInfo *DI = getDebugInfo())
1323 DI->EmitLocation(Builder, StartLoc);
1324 // TODO: Do we need to handle this in two places like we do with
1325 // target-features/target-cpu?
1326 if (CurFuncDecl)
1327 if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
1328 LargestVectorWidth = VecWidth->getVectorWidth();
1329
1331 ConvergenceTokenStack.push_back(getOrEmitConvergenceEntryToken(CurFn));
1332}
1333
1334void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
1337 if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1339 else
1340 EmitStmt(Body);
1341}
1342
1343/// When instrumenting to collect profile data, the counts for some blocks
1344/// such as switch cases need to not include the fall-through counts, so
1345/// emit a branch around the instrumentation code. When not instrumenting,
1346/// this just calls EmitBlock().
1347void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
1348 const Stmt *S) {
1349 llvm::BasicBlock *SkipCountBB = nullptr;
1350 // Do not skip over the instrumentation when single byte coverage mode is
1351 // enabled.
1354 // When instrumenting for profiling, the fallthrough to certain
1355 // statements needs to skip over the instrumentation code so that we
1356 // get an accurate count.
1357 SkipCountBB = createBasicBlock("skipcount");
1358 EmitBranch(SkipCountBB);
1359 }
1360 EmitBlock(BB);
1361 uint64_t CurrentCount = getCurrentProfileCount();
1364 if (SkipCountBB)
1365 EmitBlock(SkipCountBB);
1366}
1367
1368/// Tries to mark the given function nounwind based on the
1369/// non-existence of any throwing calls within it. We believe this is
1370/// lightweight enough to do at -O0.
1371static void TryMarkNoThrow(llvm::Function *F) {
1372 // LLVM treats 'nounwind' on a function as part of the type, so we
1373 // can't do this on functions that can be overwritten.
1374 if (F->isInterposable()) return;
1375
1376 for (llvm::BasicBlock &BB : *F)
1377 for (llvm::Instruction &I : BB)
1378 if (I.mayThrow())
1379 return;
1380
1381 F->setDoesNotThrow();
1382}
1383
1385 FunctionArgList &Args) {
1386 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1387 QualType ResTy = FD->getReturnType();
1388
1389 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1390 if (MD && MD->isImplicitObjectMemberFunction()) {
1391 if (CGM.getCXXABI().HasThisReturn(GD))
1392 ResTy = MD->getThisType();
1393 else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
1394 ResTy = CGM.getContext().VoidPtrTy;
1395 CGM.getCXXABI().buildThisParam(*this, Args);
1396 }
1397
1398 // The base version of an inheriting constructor whose constructed base is a
1399 // virtual base is not passed any arguments (because it doesn't actually call
1400 // the inherited constructor).
1401 bool PassedParams = true;
1402 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
1403 if (auto Inherited = CD->getInheritedConstructor())
1404 PassedParams =
1405 getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
1406
1407 if (PassedParams) {
1408 for (auto *Param : FD->parameters()) {
1409 Args.push_back(Param);
1410 if (!Param->hasAttr<PassObjectSizeAttr>())
1411 continue;
1412
1414 getContext(), Param->getDeclContext(), Param->getLocation(),
1415 /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamKind::Other);
1416 SizeArguments[Param] = Implicit;
1417 Args.push_back(Implicit);
1418 }
1419 }
1420
1421 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
1422 CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
1423
1424 return ResTy;
1425}
1426
1427void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1428 const CGFunctionInfo &FnInfo) {
1429 assert(Fn && "generating code for null Function");
1430 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1431 CurGD = GD;
1432
1433 FunctionArgList Args;
1434 QualType ResTy = BuildFunctionArgList(GD, Args);
1435
1437
1438 if (FD->isInlineBuiltinDeclaration()) {
1439 // When generating code for a builtin with an inline declaration, use a
1440 // mangled name to hold the actual body, while keeping an external
1441 // definition in case the function pointer is referenced somewhere.
1442 std::string FDInlineName = (Fn->getName() + ".inline").str();
1443 llvm::Module *M = Fn->getParent();
1444 llvm::Function *Clone = M->getFunction(FDInlineName);
1445 if (!Clone) {
1446 Clone = llvm::Function::Create(Fn->getFunctionType(),
1447 llvm::GlobalValue::InternalLinkage,
1448 Fn->getAddressSpace(), FDInlineName, M);
1449 Clone->addFnAttr(llvm::Attribute::AlwaysInline);
1450 }
1451 Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
1452 Fn = Clone;
1453 } else {
1454 // Detect the unusual situation where an inline version is shadowed by a
1455 // non-inline version. In that case we should pick the external one
1456 // everywhere. That's GCC behavior too. Unfortunately, I cannot find a way
1457 // to detect that situation before we reach codegen, so do some late
1458 // replacement.
1459 for (const FunctionDecl *PD = FD->getPreviousDecl(); PD;
1460 PD = PD->getPreviousDecl()) {
1461 if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
1462 std::string FDInlineName = (Fn->getName() + ".inline").str();
1463 llvm::Module *M = Fn->getParent();
1464 if (llvm::Function *Clone = M->getFunction(FDInlineName)) {
1465 Clone->replaceAllUsesWith(Fn);
1466 Clone->eraseFromParent();
1467 }
1468 break;
1469 }
1470 }
1471 }
1472
1473 // Check if we should generate debug info for this function.
1474 if (FD->hasAttr<NoDebugAttr>()) {
1475 // Clear non-distinct debug info that was possibly attached to the function
1476 // due to an earlier declaration without the nodebug attribute
1477 Fn->setSubprogram(nullptr);
1478 // Disable debug info indefinitely for this function
1479 DebugInfo = nullptr;
1480 }
1481
1482 // The function might not have a body if we're generating thunks for a
1483 // function declaration.
1484 SourceRange BodyRange;
1485 if (Stmt *Body = FD->getBody())
1486 BodyRange = Body->getSourceRange();
1487 else
1488 BodyRange = FD->getLocation();
1489 CurEHLocation = BodyRange.getEnd();
1490
1491 // Use the location of the start of the function to determine where
1492 // the function definition is located. By default use the location
1493 // of the declaration as the location for the subprogram. A function
1494 // may lack a declaration in the source code if it is created by code
1495 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1497
1498 // If this is a function specialization then use the pattern body
1499 // as the location for the function.
1500 if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
1501 if (SpecDecl->hasBody(SpecDecl))
1502 Loc = SpecDecl->getLocation();
1503
1504 Stmt *Body = FD->getBody();
1505
1506 if (Body) {
1507 // Coroutines always emit lifetime markers.
1508 if (isa<CoroutineBodyStmt>(Body))
1509 ShouldEmitLifetimeMarkers = true;
1510
1511 // Initialize helper which will detect jumps which can cause invalid
1512 // lifetime markers.
1513 if (ShouldEmitLifetimeMarkers)
1514 Bypasses.Init(Body);
1515 }
1516
1517 // Emit the standard function prologue.
1518 StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1519
1520 // Save parameters for coroutine function.
1521 if (Body && isa_and_nonnull<CoroutineBodyStmt>(Body))
1522 llvm::append_range(FnArgs, FD->parameters());
1523
1524 // Ensure that the function adheres to the forward progress guarantee, which
1525 // is required by certain optimizations.
1526 // In C++11 and up, the attribute will be removed if the body contains a
1527 // trivial empty loop.
1529 CurFn->addFnAttr(llvm::Attribute::MustProgress);
1530
1531 // Generate the body of the function.
1532 PGO.assignRegionCounters(GD, CurFn);
1533 if (isa<CXXDestructorDecl>(FD))
1534 EmitDestructorBody(Args);
1535 else if (isa<CXXConstructorDecl>(FD))
1536 EmitConstructorBody(Args);
1537 else if (getLangOpts().CUDA &&
1538 !getLangOpts().CUDAIsDevice &&
1539 FD->hasAttr<CUDAGlobalAttr>())
1540 CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1541 else if (isa<CXXMethodDecl>(FD) &&
1542 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1543 // The lambda static invoker function is special, because it forwards or
1544 // clones the body of the function call operator (but is actually static).
1545 EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
1546 } else if (isa<CXXMethodDecl>(FD) &&
1547 isLambdaCallOperator(cast<CXXMethodDecl>(FD)) &&
1548 !FnInfo.isDelegateCall() &&
1549 cast<CXXMethodDecl>(FD)->getParent()->getLambdaStaticInvoker() &&
1550 hasInAllocaArg(cast<CXXMethodDecl>(FD))) {
1551 // If emitting a lambda with static invoker on X86 Windows, change
1552 // the call operator body.
1553 // Make sure that this is a call operator with an inalloca arg and check
1554 // for delegate call to make sure this is the original call op and not the
1555 // new forwarding function for the static invoker.
1556 EmitLambdaInAllocaCallOpBody(cast<CXXMethodDecl>(FD));
1557 } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
1558 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1559 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1560 // Implicit copy-assignment gets the same special treatment as implicit
1561 // copy-constructors.
1563 } else if (Body) {
1564 EmitFunctionBody(Body);
1565 } else
1566 llvm_unreachable("no definition for emitted function");
1567
1568 // C++11 [stmt.return]p2:
1569 // Flowing off the end of a function [...] results in undefined behavior in
1570 // a value-returning function.
1571 // C11 6.9.1p12:
1572 // If the '}' that terminates a function is reached, and the value of the
1573 // function call is used by the caller, the behavior is undefined.
1575 !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
1576 bool ShouldEmitUnreachable =
1577 CGM.getCodeGenOpts().StrictReturn ||
1579 if (SanOpts.has(SanitizerKind::Return)) {
1580 SanitizerScope SanScope(this);
1581 llvm::Value *IsFalse = Builder.getFalse();
1582 EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
1583 SanitizerHandler::MissingReturn,
1584 EmitCheckSourceLocation(FD->getLocation()), std::nullopt);
1585 } else if (ShouldEmitUnreachable) {
1586 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1587 EmitTrapCall(llvm::Intrinsic::trap);
1588 }
1589 if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
1590 Builder.CreateUnreachable();
1591 Builder.ClearInsertionPoint();
1592 }
1593 }
1594
1595 // Emit the standard function epilogue.
1596 FinishFunction(BodyRange.getEnd());
1597
1598 // If we haven't marked the function nothrow through other means, do
1599 // a quick pass now to see if we can.
1600 if (!CurFn->doesNotThrow())
1602}
1603
1604/// ContainsLabel - Return true if the statement contains a label in it. If
1605/// this statement is not executed normally, it not containing a label means
1606/// that we can just remove the code.
1607bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1608 // Null statement, not a label!
1609 if (!S) return false;
1610
1611 // If this is a label, we have to emit the code, consider something like:
1612 // if (0) { ... foo: bar(); } goto foo;
1613 //
1614 // TODO: If anyone cared, we could track __label__'s, since we know that you
1615 // can't jump to one from outside their declared region.
1616 if (isa<LabelStmt>(S))
1617 return true;
1618
1619 // If this is a case/default statement, and we haven't seen a switch, we have
1620 // to emit the code.
1621 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1622 return true;
1623
1624 // If this is a switch statement, we want to ignore cases below it.
1625 if (isa<SwitchStmt>(S))
1626 IgnoreCaseStmts = true;
1627
1628 // Scan subexpressions for verboten labels.
1629 for (const Stmt *SubStmt : S->children())
1630 if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1631 return true;
1632
1633 return false;
1634}
1635
1636/// containsBreak - Return true if the statement contains a break out of it.
1637/// If the statement (recursively) contains a switch or loop with a break
1638/// inside of it, this is fine.
1639bool CodeGenFunction::containsBreak(const Stmt *S) {
1640 // Null statement, not a label!
1641 if (!S) return false;
1642
1643 // If this is a switch or loop that defines its own break scope, then we can
1644 // include it and anything inside of it.
1645 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1646 isa<ForStmt>(S))
1647 return false;
1648
1649 if (isa<BreakStmt>(S))
1650 return true;
1651
1652 // Scan subexpressions for verboten breaks.
1653 for (const Stmt *SubStmt : S->children())
1654 if (containsBreak(SubStmt))
1655 return true;
1656
1657 return false;
1658}
1659
1661 if (!S) return false;
1662
1663 // Some statement kinds add a scope and thus never add a decl to the current
1664 // scope. Note, this list is longer than the list of statements that might
1665 // have an unscoped decl nested within them, but this way is conservatively
1666 // correct even if more statement kinds are added.
1667 if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1668 isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
1669 isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
1670 isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
1671 return false;
1672
1673 if (isa<DeclStmt>(S))
1674 return true;
1675
1676 for (const Stmt *SubStmt : S->children())
1677 if (mightAddDeclToScope(SubStmt))
1678 return true;
1679
1680 return false;
1681}
1682
1683/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1684/// to a constant, or if it does but contains a label, return false. If it
1685/// constant folds return true and set the boolean result in Result.
1687 bool &ResultBool,
1688 bool AllowLabels) {
1689 // If MC/DC is enabled, disable folding so that we can instrument all
1690 // conditions to yield complete test vectors. We still keep track of
1691 // folded conditions during region mapping and visualization.
1692 if (!AllowLabels && CGM.getCodeGenOpts().hasProfileClangInstr() &&
1693 CGM.getCodeGenOpts().MCDCCoverage)
1694 return false;
1695
1696 llvm::APSInt ResultInt;
1697 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
1698 return false;
1699
1700 ResultBool = ResultInt.getBoolValue();
1701 return true;
1702}
1703
1704/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1705/// to a constant, or if it does but contains a label, return false. If it
1706/// constant folds return true and set the folded value.
1708 llvm::APSInt &ResultInt,
1709 bool AllowLabels) {
1710 // FIXME: Rename and handle conversion of other evaluatable things
1711 // to bool.
1713 if (!Cond->EvaluateAsInt(Result, getContext()))
1714 return false; // Not foldable, not integer or not fully evaluatable.
1715
1716 llvm::APSInt Int = Result.Val.getInt();
1717 if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
1718 return false; // Contains a label.
1719
1720 ResultInt = Int;
1721 return true;
1722}
1723
1724/// Strip parentheses and simplistic logical-NOT operators.
1725const Expr *CodeGenFunction::stripCond(const Expr *C) {
1726 while (const UnaryOperator *Op = dyn_cast<UnaryOperator>(C->IgnoreParens())) {
1727 if (Op->getOpcode() != UO_LNot)
1728 break;
1729 C = Op->getSubExpr();
1730 }
1731 return C->IgnoreParens();
1732}
1733
1734/// Determine whether the given condition is an instrumentable condition
1735/// (i.e. no "&&" or "||").
1737 const BinaryOperator *BOp = dyn_cast<BinaryOperator>(stripCond(C));
1738 return (!BOp || !BOp->isLogicalOp());
1739}
1740
1741/// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
1742/// increments a profile counter based on the semantics of the given logical
1743/// operator opcode. This is used to instrument branch condition coverage for
1744/// logical operators.
1746 const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock,
1747 llvm::BasicBlock *FalseBlock, uint64_t TrueCount /* = 0 */,
1748 Stmt::Likelihood LH /* =None */, const Expr *CntrIdx /* = nullptr */) {
1749 // If not instrumenting, just emit a branch.
1750 bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
1751 if (!InstrumentRegions || !isInstrumentedCondition(Cond))
1752 return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH);
1753
1754 llvm::BasicBlock *ThenBlock = nullptr;
1755 llvm::BasicBlock *ElseBlock = nullptr;
1756 llvm::BasicBlock *NextBlock = nullptr;
1757
1758 // Create the block we'll use to increment the appropriate counter.
1759 llvm::BasicBlock *CounterIncrBlock = createBasicBlock("lop.rhscnt");
1760
1761 // Set block pointers according to Logical-AND (BO_LAnd) semantics. This
1762 // means we need to evaluate the condition and increment the counter on TRUE:
1763 //
1764 // if (Cond)
1765 // goto CounterIncrBlock;
1766 // else
1767 // goto FalseBlock;
1768 //
1769 // CounterIncrBlock:
1770 // Counter++;
1771 // goto TrueBlock;
1772
1773 if (LOp == BO_LAnd) {
1774 ThenBlock = CounterIncrBlock;
1775 ElseBlock = FalseBlock;
1776 NextBlock = TrueBlock;
1777 }
1778
1779 // Set block pointers according to Logical-OR (BO_LOr) semantics. This means
1780 // we need to evaluate the condition and increment the counter on FALSE:
1781 //
1782 // if (Cond)
1783 // goto TrueBlock;
1784 // else
1785 // goto CounterIncrBlock;
1786 //
1787 // CounterIncrBlock:
1788 // Counter++;
1789 // goto FalseBlock;
1790
1791 else if (LOp == BO_LOr) {
1792 ThenBlock = TrueBlock;
1793 ElseBlock = CounterIncrBlock;
1794 NextBlock = FalseBlock;
1795 } else {
1796 llvm_unreachable("Expected Opcode must be that of a Logical Operator");
1797 }
1798
1799 // Emit Branch based on condition.
1800 EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, TrueCount, LH);
1801
1802 // Emit the block containing the counter increment(s).
1803 EmitBlock(CounterIncrBlock);
1804
1805 // Increment corresponding counter; if index not provided, use Cond as index.
1806 incrementProfileCounter(CntrIdx ? CntrIdx : Cond);
1807
1808 // Go to the next block.
1809 EmitBranch(NextBlock);
1810}
1811
1812/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1813/// statement) to the specified blocks. Based on the condition, this might try
1814/// to simplify the codegen of the conditional based on the branch.
1815/// \param LH The value of the likelihood attribute on the True branch.
1816/// \param ConditionalOp Used by MC/DC code coverage to track the result of the
1817/// ConditionalOperator (ternary) through a recursive call for the operator's
1818/// LHS and RHS nodes.
1820 const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock,
1821 uint64_t TrueCount, Stmt::Likelihood LH, const Expr *ConditionalOp) {
1822 Cond = Cond->IgnoreParens();
1823
1824 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1825 // Handle X && Y in a condition.
1826 if (CondBOp->getOpcode() == BO_LAnd) {
1827 MCDCLogOpStack.push_back(CondBOp);
1828
1829 // If we have "1 && X", simplify the code. "0 && X" would have constant
1830 // folded if the case was simple enough.
1831 bool ConstantBool = false;
1832 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1833 ConstantBool) {
1834 // br(1 && X) -> br(X).
1835 incrementProfileCounter(CondBOp);
1836 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1837 FalseBlock, TrueCount, LH);
1838 MCDCLogOpStack.pop_back();
1839 return;
1840 }
1841
1842 // If we have "X && 1", simplify the code to use an uncond branch.
1843 // "X && 0" would have been constant folded to 0.
1844 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1845 ConstantBool) {
1846 // br(X && 1) -> br(X).
1847 EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LAnd, TrueBlock,
1848 FalseBlock, TrueCount, LH, CondBOp);
1849 MCDCLogOpStack.pop_back();
1850 return;
1851 }
1852
1853 // Emit the LHS as a conditional. If the LHS conditional is false, we
1854 // want to jump to the FalseBlock.
1855 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1856 // The counter tells us how often we evaluate RHS, and all of TrueCount
1857 // can be propagated to that branch.
1858 uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
1859
1860 ConditionalEvaluation eval(*this);
1861 {
1862 ApplyDebugLocation DL(*this, Cond);
1863 // Propagate the likelihood attribute like __builtin_expect
1864 // __builtin_expect(X && Y, 1) -> X and Y are likely
1865 // __builtin_expect(X && Y, 0) -> only Y is unlikely
1866 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount,
1867 LH == Stmt::LH_Unlikely ? Stmt::LH_None : LH);
1868 EmitBlock(LHSTrue);
1869 }
1870
1871 incrementProfileCounter(CondBOp);
1872 setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1873
1874 // Any temporaries created here are conditional.
1875 eval.begin(*this);
1876 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1877 FalseBlock, TrueCount, LH);
1878 eval.end(*this);
1879 MCDCLogOpStack.pop_back();
1880 return;
1881 }
1882
1883 if (CondBOp->getOpcode() == BO_LOr) {
1884 MCDCLogOpStack.push_back(CondBOp);
1885
1886 // If we have "0 || X", simplify the code. "1 || X" would have constant
1887 // folded if the case was simple enough.
1888 bool ConstantBool = false;
1889 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1890 !ConstantBool) {
1891 // br(0 || X) -> br(X).
1892 incrementProfileCounter(CondBOp);
1893 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock,
1894 FalseBlock, TrueCount, LH);
1895 MCDCLogOpStack.pop_back();
1896 return;
1897 }
1898
1899 // If we have "X || 0", simplify the code to use an uncond branch.
1900 // "X || 1" would have been constant folded to 1.
1901 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1902 !ConstantBool) {
1903 // br(X || 0) -> br(X).
1904 EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LOr, TrueBlock,
1905 FalseBlock, TrueCount, LH, CondBOp);
1906 MCDCLogOpStack.pop_back();
1907 return;
1908 }
1909 // Emit the LHS as a conditional. If the LHS conditional is true, we
1910 // want to jump to the TrueBlock.
1911 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
1912 // We have the count for entry to the RHS and for the whole expression
1913 // being true, so we can divy up True count between the short circuit and
1914 // the RHS.
1915 uint64_t LHSCount =
1916 getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
1917 uint64_t RHSCount = TrueCount - LHSCount;
1918
1919 ConditionalEvaluation eval(*this);
1920 {
1921 // Propagate the likelihood attribute like __builtin_expect
1922 // __builtin_expect(X || Y, 1) -> only Y is likely
1923 // __builtin_expect(X || Y, 0) -> both X and Y are unlikely
1924 ApplyDebugLocation DL(*this, Cond);
1925 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount,
1926 LH == Stmt::LH_Likely ? Stmt::LH_None : LH);
1927 EmitBlock(LHSFalse);
1928 }
1929
1930 incrementProfileCounter(CondBOp);
1931 setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1932
1933 // Any temporaries created here are conditional.
1934 eval.begin(*this);
1935 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock, FalseBlock,
1936 RHSCount, LH);
1937
1938 eval.end(*this);
1939 MCDCLogOpStack.pop_back();
1940 return;
1941 }
1942 }
1943
1944 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1945 // br(!x, t, f) -> br(x, f, t)
1946 // Avoid doing this optimization when instrumenting a condition for MC/DC.
1947 // LNot is taken as part of the condition for simplicity, and changing its
1948 // sense negatively impacts test vector tracking.
1949 bool MCDCCondition = CGM.getCodeGenOpts().hasProfileClangInstr() &&
1950 CGM.getCodeGenOpts().MCDCCoverage &&
1952 if (CondUOp->getOpcode() == UO_LNot && !MCDCCondition) {
1953 // Negate the count.
1954 uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
1955 // The values of the enum are chosen to make this negation possible.
1956 LH = static_cast<Stmt::Likelihood>(-LH);
1957 // Negate the condition and swap the destination blocks.
1958 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1959 FalseCount, LH);
1960 }
1961 }
1962
1963 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1964 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1965 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1966 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1967
1968 // The ConditionalOperator itself has no likelihood information for its
1969 // true and false branches. This matches the behavior of __builtin_expect.
1970 ConditionalEvaluation cond(*this);
1971 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
1973
1974 // When computing PGO branch weights, we only know the overall count for
1975 // the true block. This code is essentially doing tail duplication of the
1976 // naive code-gen, introducing new edges for which counts are not
1977 // available. Divide the counts proportionally between the LHS and RHS of
1978 // the conditional operator.
1979 uint64_t LHSScaledTrueCount = 0;
1980 if (TrueCount) {
1981 double LHSRatio =
1983 LHSScaledTrueCount = TrueCount * LHSRatio;
1984 }
1985
1986 cond.begin(*this);
1987 EmitBlock(LHSBlock);
1989 {
1990 ApplyDebugLocation DL(*this, Cond);
1991 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
1992 LHSScaledTrueCount, LH, CondOp);
1993 }
1994 cond.end(*this);
1995
1996 cond.begin(*this);
1997 EmitBlock(RHSBlock);
1998 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
1999 TrueCount - LHSScaledTrueCount, LH, CondOp);
2000 cond.end(*this);
2001
2002 return;
2003 }
2004
2005 if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
2006 // Conditional operator handling can give us a throw expression as a
2007 // condition for a case like:
2008 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
2009 // Fold this to:
2010 // br(c, throw x, br(y, t, f))
2011 EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
2012 return;
2013 }
2014
2015 // Emit the code with the fully general case.
2016 llvm::Value *CondV;
2017 {
2018 ApplyDebugLocation DL(*this, Cond);
2019 CondV = EvaluateExprAsBool(Cond);
2020 }
2021
2022 // If not at the top of the logical operator nest, update MCDC temp with the
2023 // boolean result of the evaluated condition.
2024 if (!MCDCLogOpStack.empty()) {
2025 const Expr *MCDCBaseExpr = Cond;
2026 // When a nested ConditionalOperator (ternary) is encountered in a boolean
2027 // expression, MC/DC tracks the result of the ternary, and this is tied to
2028 // the ConditionalOperator expression and not the ternary's LHS or RHS. If
2029 // this is the case, the ConditionalOperator expression is passed through
2030 // the ConditionalOp parameter and then used as the MCDC base expression.
2031 if (ConditionalOp)
2032 MCDCBaseExpr = ConditionalOp;
2033
2034 maybeUpdateMCDCCondBitmap(MCDCBaseExpr, CondV);
2035 }
2036
2037 llvm::MDNode *Weights = nullptr;
2038 llvm::MDNode *Unpredictable = nullptr;
2039
2040 // If the branch has a condition wrapped by __builtin_unpredictable,
2041 // create metadata that specifies that the branch is unpredictable.
2042 // Don't bother if not optimizing because that metadata would not be used.
2043 auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
2044 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
2045 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
2046 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
2047 llvm::MDBuilder MDHelper(getLLVMContext());
2048 Unpredictable = MDHelper.createUnpredictable();
2049 }
2050 }
2051
2052 // If there is a Likelihood knowledge for the cond, lower it.
2053 // Note that if not optimizing this won't emit anything.
2054 llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(CondV, LH);
2055 if (CondV != NewCondV)
2056 CondV = NewCondV;
2057 else {
2058 // Otherwise, lower profile counts. Note that we do this even at -O0.
2059 uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
2060 Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount);
2061 }
2062
2063 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
2064}
2065
2066/// ErrorUnsupported - Print out an error that codegen doesn't support the
2067/// specified stmt yet.
2068void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
2070}
2071
2072/// emitNonZeroVLAInit - Emit the "zero" initialization of a
2073/// variable-length array whose elements have a non-zero bit-pattern.
2074///
2075/// \param baseType the inner-most element type of the array
2076/// \param src - a char* pointing to the bit-pattern for a single
2077/// base element of the array
2078/// \param sizeInChars - the total size of the VLA, in chars
2080 Address dest, Address src,
2081 llvm::Value *sizeInChars) {
2083
2084 CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
2085 llvm::Value *baseSizeInChars
2086 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
2087
2088 Address begin = dest.withElementType(CGF.Int8Ty);
2089 llvm::Value *end = Builder.CreateInBoundsGEP(begin.getElementType(),
2090 begin.emitRawPointer(CGF),
2091 sizeInChars, "vla.end");
2092
2093 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
2094 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
2095 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
2096
2097 // Make a loop over the VLA. C99 guarantees that the VLA element
2098 // count must be nonzero.
2099 CGF.EmitBlock(loopBB);
2100
2101 llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
2102 cur->addIncoming(begin.emitRawPointer(CGF), originBB);
2103
2104 CharUnits curAlign =
2105 dest.getAlignment().alignmentOfArrayElement(baseSize);
2106
2107 // memcpy the individual element bit-pattern.
2108 Builder.CreateMemCpy(Address(cur, CGF.Int8Ty, curAlign), src, baseSizeInChars,
2109 /*volatile*/ false);
2110
2111 // Go to the next element.
2112 llvm::Value *next =
2113 Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
2114
2115 // Leave if that's the end of the VLA.
2116 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
2117 Builder.CreateCondBr(done, contBB, loopBB);
2118 cur->addIncoming(next, loopBB);
2119
2120 CGF.EmitBlock(contBB);
2121}
2122
2123void
2125 // Ignore empty classes in C++.
2126 if (getLangOpts().CPlusPlus) {
2127 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2128 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
2129 return;
2130 }
2131 }
2132
2133 if (DestPtr.getElementType() != Int8Ty)
2134 DestPtr = DestPtr.withElementType(Int8Ty);
2135
2136 // Get size and alignment info for this aggregate.
2138
2139 llvm::Value *SizeVal;
2140 const VariableArrayType *vla;
2141
2142 // Don't bother emitting a zero-byte memset.
2143 if (size.isZero()) {
2144 // But note that getTypeInfo returns 0 for a VLA.
2145 if (const VariableArrayType *vlaType =
2146 dyn_cast_or_null<VariableArrayType>(
2147 getContext().getAsArrayType(Ty))) {
2148 auto VlaSize = getVLASize(vlaType);
2149 SizeVal = VlaSize.NumElts;
2150 CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
2151 if (!eltSize.isOne())
2152 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
2153 vla = vlaType;
2154 } else {
2155 return;
2156 }
2157 } else {
2158 SizeVal = CGM.getSize(size);
2159 vla = nullptr;
2160 }
2161
2162 // If the type contains a pointer to data member we can't memset it to zero.
2163 // Instead, create a null constant and copy it to the destination.
2164 // TODO: there are other patterns besides zero that we can usefully memset,
2165 // like -1, which happens to be the pattern used by member-pointers.
2166 if (!CGM.getTypes().isZeroInitializable(Ty)) {
2167 // For a VLA, emit a single element, then splat that over the VLA.
2168 if (vla) Ty = getContext().getBaseElementType(vla);
2169
2170 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
2171
2172 llvm::GlobalVariable *NullVariable =
2173 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
2174 /*isConstant=*/true,
2175 llvm::GlobalVariable::PrivateLinkage,
2176 NullConstant, Twine());
2177 CharUnits NullAlign = DestPtr.getAlignment();
2178 NullVariable->setAlignment(NullAlign.getAsAlign());
2179 Address SrcPtr(NullVariable, Builder.getInt8Ty(), NullAlign);
2180
2181 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
2182
2183 // Get and call the appropriate llvm.memcpy overload.
2184 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
2185 return;
2186 }
2187
2188 // Otherwise, just memset the whole thing to zero. This is legal
2189 // because in LLVM, all default initializers (other than the ones we just
2190 // handled above) are guaranteed to have a bit pattern of all zeros.
2191 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
2192}
2193
2194llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
2195 // Make sure that there is a block for the indirect goto.
2196 if (!IndirectBranch)
2198
2199 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
2200
2201 // Make sure the indirect branch includes all of the address-taken blocks.
2202 IndirectBranch->addDestination(BB);
2203 return llvm::BlockAddress::get(CurFn, BB);
2204}
2205
2206llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
2207 // If we already made the indirect branch for indirect goto, return its block.
2208 if (IndirectBranch) return IndirectBranch->getParent();
2209
2210 CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
2211
2212 // Create the PHI node that indirect gotos will add entries to.
2213 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
2214 "indirect.goto.dest");
2215
2216 // Create the indirect branch instruction.
2217 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
2218 return IndirectBranch->getParent();
2219}
2220
2221/// Computes the length of an array in elements, as well as the base
2222/// element type and a properly-typed first element pointer.
2223llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
2224 QualType &baseType,
2225 Address &addr) {
2226 const ArrayType *arrayType = origArrayType;
2227
2228 // If it's a VLA, we have to load the stored size. Note that
2229 // this is the size of the VLA in bytes, not its size in elements.
2230 llvm::Value *numVLAElements = nullptr;
2231 if (isa<VariableArrayType>(arrayType)) {
2232 numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
2233
2234 // Walk into all VLAs. This doesn't require changes to addr,
2235 // which has type T* where T is the first non-VLA element type.
2236 do {
2237 QualType elementType = arrayType->getElementType();
2238 arrayType = getContext().getAsArrayType(elementType);
2239
2240 // If we only have VLA components, 'addr' requires no adjustment.
2241 if (!arrayType) {
2242 baseType = elementType;
2243 return numVLAElements;
2244 }
2245 } while (isa<VariableArrayType>(arrayType));
2246
2247 // We get out here only if we find a constant array type
2248 // inside the VLA.
2249 }
2250
2251 // We have some number of constant-length arrays, so addr should
2252 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
2253 // down to the first element of addr.
2255
2256 // GEP down to the array type.
2257 llvm::ConstantInt *zero = Builder.getInt32(0);
2258 gepIndices.push_back(zero);
2259
2260 uint64_t countFromCLAs = 1;
2261 QualType eltType;
2262
2263 llvm::ArrayType *llvmArrayType =
2264 dyn_cast<llvm::ArrayType>(addr.getElementType());
2265 while (llvmArrayType) {
2266 assert(isa<ConstantArrayType>(arrayType));
2267 assert(cast<ConstantArrayType>(arrayType)->getZExtSize() ==
2268 llvmArrayType->getNumElements());
2269
2270 gepIndices.push_back(zero);
2271 countFromCLAs *= llvmArrayType->getNumElements();
2272 eltType = arrayType->getElementType();
2273
2274 llvmArrayType =
2275 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
2276 arrayType = getContext().getAsArrayType(arrayType->getElementType());
2277 assert((!llvmArrayType || arrayType) &&
2278 "LLVM and Clang types are out-of-synch");
2279 }
2280
2281 if (arrayType) {
2282 // From this point onwards, the Clang array type has been emitted
2283 // as some other type (probably a packed struct). Compute the array
2284 // size, and just emit the 'begin' expression as a bitcast.
2285 while (arrayType) {
2286 countFromCLAs *= cast<ConstantArrayType>(arrayType)->getZExtSize();
2287 eltType = arrayType->getElementType();
2288 arrayType = getContext().getAsArrayType(eltType);
2289 }
2290
2291 llvm::Type *baseType = ConvertType(eltType);
2292 addr = addr.withElementType(baseType);
2293 } else {
2294 // Create the actual GEP.
2296 addr.emitRawPointer(*this),
2297 gepIndices, "array.begin"),
2298 ConvertTypeForMem(eltType), addr.getAlignment());
2299 }
2300
2301 baseType = eltType;
2302
2303 llvm::Value *numElements
2304 = llvm::ConstantInt::get(SizeTy, countFromCLAs);
2305
2306 // If we had any VLA dimensions, factor them in.
2307 if (numVLAElements)
2308 numElements = Builder.CreateNUWMul(numVLAElements, numElements);
2309
2310 return numElements;
2311}
2312
2313CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
2315 assert(vla && "type was not a variable array type!");
2316 return getVLASize(vla);
2317}
2318
2319CodeGenFunction::VlaSizePair
2321 // The number of elements so far; always size_t.
2322 llvm::Value *numElements = nullptr;
2323
2324 QualType elementType;
2325 do {
2326 elementType = type->getElementType();
2327 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
2328 assert(vlaSize && "no size for VLA!");
2329 assert(vlaSize->getType() == SizeTy);
2330
2331 if (!numElements) {
2332 numElements = vlaSize;
2333 } else {
2334 // It's undefined behavior if this wraps around, so mark it that way.
2335 // FIXME: Teach -fsanitize=undefined to trap this.
2336 numElements = Builder.CreateNUWMul(numElements, vlaSize);
2337 }
2338 } while ((type = getContext().getAsVariableArrayType(elementType)));
2339
2340 return { numElements, elementType };
2341}
2342
2343CodeGenFunction::VlaSizePair
2346 assert(vla && "type was not a variable array type!");
2347 return getVLAElements1D(vla);
2348}
2349
2350CodeGenFunction::VlaSizePair
2352 llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
2353 assert(VlaSize && "no size for VLA!");
2354 assert(VlaSize->getType() == SizeTy);
2355 return { VlaSize, Vla->getElementType() };
2356}
2357
2359 assert(type->isVariablyModifiedType() &&
2360 "Must pass variably modified type to EmitVLASizes!");
2361
2363
2364 // We're going to walk down into the type and look for VLA
2365 // expressions.
2366 do {
2367 assert(type->isVariablyModifiedType());
2368
2369 const Type *ty = type.getTypePtr();
2370 switch (ty->getTypeClass()) {
2371
2372#define TYPE(Class, Base)
2373#define ABSTRACT_TYPE(Class, Base)
2374#define NON_CANONICAL_TYPE(Class, Base)
2375#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2376#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
2377#include "clang/AST/TypeNodes.inc"
2378 llvm_unreachable("unexpected dependent type!");
2379
2380 // These types are never variably-modified.
2381 case Type::Builtin:
2382 case Type::Complex:
2383 case Type::Vector:
2384 case Type::ExtVector:
2385 case Type::ConstantMatrix:
2386 case Type::Record:
2387 case Type::Enum:
2388 case Type::Using:
2389 case Type::TemplateSpecialization:
2390 case Type::ObjCTypeParam:
2391 case Type::ObjCObject:
2392 case Type::ObjCInterface:
2393 case Type::ObjCObjectPointer:
2394 case Type::BitInt:
2395 llvm_unreachable("type class is never variably-modified!");
2396
2397 case Type::Elaborated:
2398 type = cast<ElaboratedType>(ty)->getNamedType();
2399 break;
2400
2401 case Type::Adjusted:
2402 type = cast<AdjustedType>(ty)->getAdjustedType();
2403 break;
2404
2405 case Type::Decayed:
2406 type = cast<DecayedType>(ty)->getPointeeType();
2407 break;
2408
2409 case Type::Pointer:
2410 type = cast<PointerType>(ty)->getPointeeType();
2411 break;
2412
2413 case Type::BlockPointer:
2414 type = cast<BlockPointerType>(ty)->getPointeeType();
2415 break;
2416
2417 case Type::LValueReference:
2418 case Type::RValueReference:
2419 type = cast<ReferenceType>(ty)->getPointeeType();
2420 break;
2421
2422 case Type::MemberPointer:
2423 type = cast<MemberPointerType>(ty)->getPointeeType();
2424 break;
2425
2426 case Type::ArrayParameter:
2427 case Type::ConstantArray:
2428 case Type::IncompleteArray:
2429 // Losing element qualification here is fine.
2430 type = cast<ArrayType>(ty)->getElementType();
2431 break;
2432
2433 case Type::VariableArray: {
2434 // Losing element qualification here is fine.
2435 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2436
2437 // Unknown size indication requires no size computation.
2438 // Otherwise, evaluate and record it.
2439 if (const Expr *sizeExpr = vat->getSizeExpr()) {
2440 // It's possible that we might have emitted this already,
2441 // e.g. with a typedef and a pointer to it.
2442 llvm::Value *&entry = VLASizeMap[sizeExpr];
2443 if (!entry) {
2444 llvm::Value *size = EmitScalarExpr(sizeExpr);
2445
2446 // C11 6.7.6.2p5:
2447 // If the size is an expression that is not an integer constant
2448 // expression [...] each time it is evaluated it shall have a value
2449 // greater than zero.
2450 if (SanOpts.has(SanitizerKind::VLABound)) {
2451 SanitizerScope SanScope(this);
2452 llvm::Value *Zero = llvm::Constant::getNullValue(size->getType());
2453 clang::QualType SEType = sizeExpr->getType();
2454 llvm::Value *CheckCondition =
2455 SEType->isSignedIntegerType()
2456 ? Builder.CreateICmpSGT(size, Zero)
2457 : Builder.CreateICmpUGT(size, Zero);
2458 llvm::Constant *StaticArgs[] = {
2459 EmitCheckSourceLocation(sizeExpr->getBeginLoc()),
2460 EmitCheckTypeDescriptor(SEType)};
2461 EmitCheck(std::make_pair(CheckCondition, SanitizerKind::VLABound),
2462 SanitizerHandler::VLABoundNotPositive, StaticArgs, size);
2463 }
2464
2465 // Always zexting here would be wrong if it weren't
2466 // undefined behavior to have a negative bound.
2467 // FIXME: What about when size's type is larger than size_t?
2468 entry = Builder.CreateIntCast(size, SizeTy, /*signed*/ false);
2469 }
2470 }
2471 type = vat->getElementType();
2472 break;
2473 }
2474
2475 case Type::FunctionProto:
2476 case Type::FunctionNoProto:
2477 type = cast<FunctionType>(ty)->getReturnType();
2478 break;
2479
2480 case Type::Paren:
2481 case Type::TypeOf:
2482 case Type::UnaryTransform:
2483 case Type::Attributed:
2484 case Type::BTFTagAttributed:
2485 case Type::SubstTemplateTypeParm:
2486 case Type::MacroQualified:
2487 case Type::CountAttributed:
2488 // Keep walking after single level desugaring.
2489 type = type.getSingleStepDesugaredType(getContext());
2490 break;
2491
2492 case Type::Typedef:
2493 case Type::Decltype:
2494 case Type::Auto:
2495 case Type::DeducedTemplateSpecialization:
2496 case Type::PackIndexing:
2497 // Stop walking: nothing to do.
2498 return;
2499
2500 case Type::TypeOfExpr:
2501 // Stop walking: emit typeof expression.
2502 EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
2503 return;
2504
2505 case Type::Atomic:
2506 type = cast<AtomicType>(ty)->getValueType();
2507 break;
2508
2509 case Type::Pipe:
2510 type = cast<PipeType>(ty)->getElementType();
2511 break;
2512 }
2513 } while (type->isVariablyModifiedType());
2514}
2515
2517 if (getContext().getBuiltinVaListType()->isArrayType())
2519 return EmitLValue(E).getAddress();
2520}
2521
2523 return EmitLValue(E).getAddress();
2524}
2525
2527 const APValue &Init) {
2528 assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
2529 if (CGDebugInfo *Dbg = getDebugInfo())
2531 Dbg->EmitGlobalVariable(E->getDecl(), Init);
2532}
2533
2534CodeGenFunction::PeepholeProtection
2536 // At the moment, the only aggressive peephole we do in IR gen
2537 // is trunc(zext) folding, but if we add more, we can easily
2538 // extend this protection.
2539
2540 if (!rvalue.isScalar()) return PeepholeProtection();
2541 llvm::Value *value = rvalue.getScalarVal();
2542 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
2543
2544 // Just make an extra bitcast.
2545 assert(HaveInsertPoint());
2546 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
2547 Builder.GetInsertBlock());
2548
2549 PeepholeProtection protection;
2550 protection.Inst = inst;
2551 return protection;
2552}
2553
2554void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
2555 if (!protection.Inst) return;
2556
2557 // In theory, we could try to duplicate the peepholes now, but whatever.
2558 protection.Inst->eraseFromParent();
2559}
2560
2561void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2563 SourceLocation AssumptionLoc,
2564 llvm::Value *Alignment,
2565 llvm::Value *OffsetValue) {
2566 if (Alignment->getType() != IntPtrTy)
2567 Alignment =
2568 Builder.CreateIntCast(Alignment, IntPtrTy, false, "casted.align");
2569 if (OffsetValue && OffsetValue->getType() != IntPtrTy)
2570 OffsetValue =
2571 Builder.CreateIntCast(OffsetValue, IntPtrTy, true, "casted.offset");
2572 llvm::Value *TheCheck = nullptr;
2573 if (SanOpts.has(SanitizerKind::Alignment)) {
2574 llvm::Value *PtrIntValue =
2575 Builder.CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
2576
2577 if (OffsetValue) {
2578 bool IsOffsetZero = false;
2579 if (const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue))
2580 IsOffsetZero = CI->isZero();
2581
2582 if (!IsOffsetZero)
2583 PtrIntValue = Builder.CreateSub(PtrIntValue, OffsetValue, "offsetptr");
2584 }
2585
2586 llvm::Value *Zero = llvm::ConstantInt::get(IntPtrTy, 0);
2587 llvm::Value *Mask =
2588 Builder.CreateSub(Alignment, llvm::ConstantInt::get(IntPtrTy, 1));
2589 llvm::Value *MaskedPtr = Builder.CreateAnd(PtrIntValue, Mask, "maskedptr");
2590 TheCheck = Builder.CreateICmpEQ(MaskedPtr, Zero, "maskcond");
2591 }
2592 llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
2593 CGM.getDataLayout(), PtrValue, Alignment, OffsetValue);
2594
2595 if (!SanOpts.has(SanitizerKind::Alignment))
2596 return;
2597 emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2598 OffsetValue, TheCheck, Assumption);
2599}
2600
2601void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2602 const Expr *E,
2603 SourceLocation AssumptionLoc,
2604 llvm::Value *Alignment,
2605 llvm::Value *OffsetValue) {
2606 QualType Ty = E->getType();
2608
2609 emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2610 OffsetValue);
2611}
2612
2613llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
2614 llvm::Value *AnnotatedVal,
2615 StringRef AnnotationStr,
2616 SourceLocation Location,
2617 const AnnotateAttr *Attr) {
2619 AnnotatedVal,
2620 CGM.EmitAnnotationString(AnnotationStr),
2621 CGM.EmitAnnotationUnit(Location),
2622 CGM.EmitAnnotationLineNo(Location),
2623 };
2624 if (Attr)
2625 Args.push_back(CGM.EmitAnnotationArgs(Attr));
2626 return Builder.CreateCall(AnnotationFn, Args);
2627}
2628
2629void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
2630 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2631 for (const auto *I : D->specific_attrs<AnnotateAttr>())
2632 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation,
2633 {V->getType(), CGM.ConstGlobalsPtrTy}),
2634 V, I->getAnnotation(), D->getLocation(), I);
2635}
2636
2638 Address Addr) {
2639 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2640 llvm::Value *V = Addr.emitRawPointer(*this);
2641 llvm::Type *VTy = V->getType();
2642 auto *PTy = dyn_cast<llvm::PointerType>(VTy);
2643 unsigned AS = PTy ? PTy->getAddressSpace() : 0;
2644 llvm::PointerType *IntrinTy =
2645 llvm::PointerType::get(CGM.getLLVMContext(), AS);
2646 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
2647 {IntrinTy, CGM.ConstGlobalsPtrTy});
2648
2649 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2650 // FIXME Always emit the cast inst so we can differentiate between
2651 // annotation on the first field of a struct and annotation on the struct
2652 // itself.
2653 if (VTy != IntrinTy)
2654 V = Builder.CreateBitCast(V, IntrinTy);
2655 V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation(), I);
2656 V = Builder.CreateBitCast(V, VTy);
2657 }
2658
2659 return Address(V, Addr.getElementType(), Addr.getAlignment());
2660}
2661
2663
2665 : CGF(CGF) {
2666 assert(!CGF->IsSanitizerScope);
2667 CGF->IsSanitizerScope = true;
2668}
2669
2671 CGF->IsSanitizerScope = false;
2672}
2673
2674void CodeGenFunction::InsertHelper(llvm::Instruction *I,
2675 const llvm::Twine &Name,
2676 llvm::BasicBlock::iterator InsertPt) const {
2678 if (IsSanitizerScope)
2679 I->setNoSanitizeMetadata();
2680}
2681
2683 llvm::Instruction *I, const llvm::Twine &Name,
2684 llvm::BasicBlock::iterator InsertPt) const {
2685 llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, InsertPt);
2686 if (CGF)
2687 CGF->InsertHelper(I, Name, InsertPt);
2688}
2689
2690// Emits an error if we don't have a valid set of target features for the
2691// called function.
2693 const FunctionDecl *TargetDecl) {
2694 // SemaChecking cannot handle below x86 builtins because they have different
2695 // parameter ranges with different TargetAttribute of caller.
2696 if (CGM.getContext().getTargetInfo().getTriple().isX86()) {
2697 unsigned BuiltinID = TargetDecl->getBuiltinID();
2698 if (BuiltinID == X86::BI__builtin_ia32_cmpps ||
2699 BuiltinID == X86::BI__builtin_ia32_cmpss ||
2700 BuiltinID == X86::BI__builtin_ia32_cmppd ||
2701 BuiltinID == X86::BI__builtin_ia32_cmpsd) {
2702 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
2703 llvm::StringMap<bool> TargetFetureMap;
2704 CGM.getContext().getFunctionFeatureMap(TargetFetureMap, FD);
2705 llvm::APSInt Result =
2706 *(E->getArg(2)->getIntegerConstantExpr(CGM.getContext()));
2707 if (Result.getSExtValue() > 7 && !TargetFetureMap.lookup("avx"))
2708 CGM.getDiags().Report(E->getBeginLoc(), diag::err_builtin_needs_feature)
2709 << TargetDecl->getDeclName() << "avx";
2710 }
2711 }
2712 return checkTargetFeatures(E->getBeginLoc(), TargetDecl);
2713}
2714
2715// Emits an error if we don't have a valid set of target features for the
2716// called function.
2718 const FunctionDecl *TargetDecl) {
2719 // Early exit if this is an indirect call.
2720 if (!TargetDecl)
2721 return;
2722
2723 // Get the current enclosing function if it exists. If it doesn't
2724 // we can't check the target features anyhow.
2725 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
2726 if (!FD)
2727 return;
2728
2729 // Grab the required features for the call. For a builtin this is listed in
2730 // the td file with the default cpu, for an always_inline function this is any
2731 // listed cpu and any listed features.
2732 unsigned BuiltinID = TargetDecl->getBuiltinID();
2733 std::string MissingFeature;
2734 llvm::StringMap<bool> CallerFeatureMap;
2735 CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD);
2736 // When compiling in HipStdPar mode we have to be conservative in rejecting
2737 // target specific features in the FE, and defer the possible error to the
2738 // AcceleratorCodeSelection pass, wherein iff an unsupported target builtin is
2739 // referenced by an accelerator executable function, we emit an error.
2740 bool IsHipStdPar = getLangOpts().HIPStdPar && getLangOpts().CUDAIsDevice;
2741 if (BuiltinID) {
2742 StringRef FeatureList(CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID));
2744 FeatureList, CallerFeatureMap) && !IsHipStdPar) {
2745 CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
2746 << TargetDecl->getDeclName()
2747 << FeatureList;
2748 }
2749 } else if (!TargetDecl->isMultiVersion() &&
2750 TargetDecl->hasAttr<TargetAttr>()) {
2751 // Get the required features for the callee.
2752
2753 const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
2756
2757 SmallVector<StringRef, 1> ReqFeatures;
2758 llvm::StringMap<bool> CalleeFeatureMap;
2759 CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
2760
2761 for (const auto &F : ParsedAttr.Features) {
2762 if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
2763 ReqFeatures.push_back(StringRef(F).substr(1));
2764 }
2765
2766 for (const auto &F : CalleeFeatureMap) {
2767 // Only positive features are "required".
2768 if (F.getValue())
2769 ReqFeatures.push_back(F.getKey());
2770 }
2771 if (!llvm::all_of(ReqFeatures, [&](StringRef Feature) {
2772 if (!CallerFeatureMap.lookup(Feature)) {
2773 MissingFeature = Feature.str();
2774 return false;
2775 }
2776 return true;
2777 }) && !IsHipStdPar)
2778 CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
2779 << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
2780 } else if (!FD->isMultiVersion() && FD->hasAttr<TargetAttr>()) {
2781 llvm::StringMap<bool> CalleeFeatureMap;
2782 CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
2783
2784 for (const auto &F : CalleeFeatureMap) {
2785 if (F.getValue() && (!CallerFeatureMap.lookup(F.getKey()) ||
2786 !CallerFeatureMap.find(F.getKey())->getValue()) &&
2787 !IsHipStdPar)
2788 CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
2789 << FD->getDeclName() << TargetDecl->getDeclName() << F.getKey();
2790 }
2791 }
2792}
2793
2794void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2795 if (!CGM.getCodeGenOpts().SanitizeStats)
2796 return;
2797
2798 llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2799 IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2800 CGM.getSanStats().create(IRB, SSK);
2801}
2802
2804 const CGCallee &Callee, SmallVectorImpl<llvm::OperandBundleDef> &Bundles) {
2805 const FunctionProtoType *FP =
2806 Callee.getAbstractInfo().getCalleeFunctionProtoType();
2807 if (FP)
2808 Bundles.emplace_back("kcfi", CGM.CreateKCFITypeId(FP->desugar()));
2809}
2810
2811llvm::Value *CodeGenFunction::FormAArch64ResolverCondition(
2812 const MultiVersionResolverOption &RO) {
2814 for (const StringRef &Feature : RO.Conditions.Features)
2815 CondFeatures.push_back(Feature);
2816 if (!CondFeatures.empty()) {
2817 return EmitAArch64CpuSupports(CondFeatures);
2818 }
2819 return nullptr;
2820}
2821
2822llvm::Value *CodeGenFunction::FormX86ResolverCondition(
2823 const MultiVersionResolverOption &RO) {
2824 llvm::Value *Condition = nullptr;
2825
2826 if (!RO.Conditions.Architecture.empty()) {
2827 StringRef Arch = RO.Conditions.Architecture;
2828 // If arch= specifies an x86-64 micro-architecture level, test the feature
2829 // with __builtin_cpu_supports, otherwise use __builtin_cpu_is.
2830 if (Arch.starts_with("x86-64"))
2831 Condition = EmitX86CpuSupports({Arch});
2832 else
2833 Condition = EmitX86CpuIs(Arch);
2834 }
2835
2836 if (!RO.Conditions.Features.empty()) {
2837 llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features);
2838 Condition =
2839 Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
2840 }
2841 return Condition;
2842}
2843
2845 llvm::Function *Resolver,
2847 llvm::Function *FuncToReturn,
2848 bool SupportsIFunc) {
2849 if (SupportsIFunc) {
2850 Builder.CreateRet(FuncToReturn);
2851 return;
2852 }
2853
2855 llvm::make_pointer_range(Resolver->args()));
2856
2857 llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
2858 Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2859
2860 if (Resolver->getReturnType()->isVoidTy())
2861 Builder.CreateRetVoid();
2862 else
2863 Builder.CreateRet(Result);
2864}
2865
2867 llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
2868
2869 llvm::Triple::ArchType ArchType =
2870 getContext().getTargetInfo().getTriple().getArch();
2871
2872 switch (ArchType) {
2873 case llvm::Triple::x86:
2874 case llvm::Triple::x86_64:
2875 EmitX86MultiVersionResolver(Resolver, Options);
2876 return;
2877 case llvm::Triple::aarch64:
2878 EmitAArch64MultiVersionResolver(Resolver, Options);
2879 return;
2880
2881 default:
2882 assert(false && "Only implemented for x86 and AArch64 targets");
2883 }
2884}
2885
2887 llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
2888 assert(!Options.empty() && "No multiversion resolver options found");
2889 assert(Options.back().Conditions.Features.size() == 0 &&
2890 "Default case must be last");
2891 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
2892 assert(SupportsIFunc &&
2893 "Multiversion resolver requires target IFUNC support");
2894 bool AArch64CpuInitialized = false;
2895 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
2896
2897 for (const MultiVersionResolverOption &RO : Options) {
2898 Builder.SetInsertPoint(CurBlock);
2899 llvm::Value *Condition = FormAArch64ResolverCondition(RO);
2900
2901 // The 'default' or 'all features enabled' case.
2902 if (!Condition) {
2903 CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
2904 SupportsIFunc);
2905 return;
2906 }
2907
2908 if (!AArch64CpuInitialized) {
2909 Builder.SetInsertPoint(CurBlock, CurBlock->begin());
2910 EmitAArch64CpuInit();
2911 AArch64CpuInitialized = true;
2912 Builder.SetInsertPoint(CurBlock);
2913 }
2914
2915 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
2916 CGBuilderTy RetBuilder(*this, RetBlock);
2917 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
2918 SupportsIFunc);
2919 CurBlock = createBasicBlock("resolver_else", Resolver);
2920 Builder.CreateCondBr(Condition, RetBlock, CurBlock);
2921 }
2922
2923 // If no default, emit an unreachable.
2924 Builder.SetInsertPoint(CurBlock);
2925 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2926 TrapCall->setDoesNotReturn();
2927 TrapCall->setDoesNotThrow();
2928 Builder.CreateUnreachable();
2929 Builder.ClearInsertionPoint();
2930}
2931
2933 llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
2934
2935 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
2936
2937 // Main function's basic block.
2938 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
2939 Builder.SetInsertPoint(CurBlock);
2940 EmitX86CpuInit();
2941
2942 for (const MultiVersionResolverOption &RO : Options) {
2943 Builder.SetInsertPoint(CurBlock);
2944 llvm::Value *Condition = FormX86ResolverCondition(RO);
2945
2946 // The 'default' or 'generic' case.
2947 if (!Condition) {
2948 assert(&RO == Options.end() - 1 &&
2949 "Default or Generic case must be last");
2950 CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
2951 SupportsIFunc);
2952 return;
2953 }
2954
2955 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
2956 CGBuilderTy RetBuilder(*this, RetBlock);
2957 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
2958 SupportsIFunc);
2959 CurBlock = createBasicBlock("resolver_else", Resolver);
2960 Builder.CreateCondBr(Condition, RetBlock, CurBlock);
2961 }
2962
2963 // If no generic/default, emit an unreachable.
2964 Builder.SetInsertPoint(CurBlock);
2965 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2966 TrapCall->setDoesNotReturn();
2967 TrapCall->setDoesNotThrow();
2968 Builder.CreateUnreachable();
2969 Builder.ClearInsertionPoint();
2970}
2971
2972// Loc - where the diagnostic will point, where in the source code this
2973// alignment has failed.
2974// SecondaryLoc - if present (will be present if sufficiently different from
2975// Loc), the diagnostic will additionally point a "Note:" to this location.
2976// It should be the location where the __attribute__((assume_aligned))
2977// was written e.g.
2979 llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
2980 SourceLocation SecondaryLoc, llvm::Value *Alignment,
2981 llvm::Value *OffsetValue, llvm::Value *TheCheck,
2982 llvm::Instruction *Assumption) {
2983 assert(isa_and_nonnull<llvm::CallInst>(Assumption) &&
2984 cast<llvm::CallInst>(Assumption)->getCalledOperand() ==
2985 llvm::Intrinsic::getDeclaration(
2986 Builder.GetInsertBlock()->getParent()->getParent(),
2987 llvm::Intrinsic::assume) &&
2988 "Assumption should be a call to llvm.assume().");
2989 assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
2990 "Assumption should be the last instruction of the basic block, "
2991 "since the basic block is still being generated.");
2992
2993 if (!SanOpts.has(SanitizerKind::Alignment))
2994 return;
2995
2996 // Don't check pointers to volatile data. The behavior here is implementation-
2997 // defined.
2999 return;
3000
3001 // We need to temorairly remove the assumption so we can insert the
3002 // sanitizer check before it, else the check will be dropped by optimizations.
3003 Assumption->removeFromParent();
3004
3005 {
3006 SanitizerScope SanScope(this);
3007
3008 if (!OffsetValue)
3009 OffsetValue = Builder.getInt1(false); // no offset.
3010
3011 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
3012 EmitCheckSourceLocation(SecondaryLoc),
3014 llvm::Value *DynamicData[] = {EmitCheckValue(Ptr),
3015 EmitCheckValue(Alignment),
3016 EmitCheckValue(OffsetValue)};
3017 EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
3018 SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
3019 }
3020
3021 // We are now in the (new, empty) "cont" basic block.
3022 // Reintroduce the assumption.
3023 Builder.Insert(Assumption);
3024 // FIXME: Assumption still has it's original basic block as it's Parent.
3025}
3026
3028 if (CGDebugInfo *DI = getDebugInfo())
3029 return DI->SourceLocToDebugLoc(Location);
3030
3031 return llvm::DebugLoc();
3032}
3033
3034llvm::Value *
3035CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
3036 Stmt::Likelihood LH) {
3037 switch (LH) {
3038 case Stmt::LH_None:
3039 return Cond;
3040 case Stmt::LH_Likely:
3041 case Stmt::LH_Unlikely:
3042 // Don't generate llvm.expect on -O0 as the backend won't use it for
3043 // anything.
3044 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
3045 return Cond;
3046 llvm::Type *CondTy = Cond->getType();
3047 assert(CondTy->isIntegerTy(1) && "expecting condition to be a boolean");
3048 llvm::Function *FnExpect =
3049 CGM.getIntrinsic(llvm::Intrinsic::expect, CondTy);
3050 llvm::Value *ExpectedValueOfCond =
3051 llvm::ConstantInt::getBool(CondTy, LH == Stmt::LH_Likely);
3052 return Builder.CreateCall(FnExpect, {Cond, ExpectedValueOfCond},
3053 Cond->getName() + ".expval");
3054 }
3055 llvm_unreachable("Unknown Likelihood");
3056}
3057
3058llvm::Value *CodeGenFunction::emitBoolVecConversion(llvm::Value *SrcVec,
3059 unsigned NumElementsDst,
3060 const llvm::Twine &Name) {
3061 auto *SrcTy = cast<llvm::FixedVectorType>(SrcVec->getType());
3062 unsigned NumElementsSrc = SrcTy->getNumElements();
3063 if (NumElementsSrc == NumElementsDst)
3064 return SrcVec;
3065
3066 std::vector<int> ShuffleMask(NumElementsDst, -1);
3067 for (unsigned MaskIdx = 0;
3068 MaskIdx < std::min<>(NumElementsDst, NumElementsSrc); ++MaskIdx)
3069 ShuffleMask[MaskIdx] = MaskIdx;
3070
3071 return Builder.CreateShuffleVector(SrcVec, ShuffleMask, Name);
3072}
3073
3075 const CGPointerAuthInfo &PointerAuth,
3077 if (!PointerAuth.isSigned())
3078 return;
3079
3080 auto *Key = Builder.getInt32(PointerAuth.getKey());
3081
3082 llvm::Value *Discriminator = PointerAuth.getDiscriminator();
3083 if (!Discriminator)
3084 Discriminator = Builder.getSize(0);
3085
3086 llvm::Value *Args[] = {Key, Discriminator};
3087 Bundles.emplace_back("ptrauth", Args);
3088}
3089
3091 const CGPointerAuthInfo &PointerAuth,
3092 llvm::Value *Pointer,
3093 unsigned IntrinsicID) {
3094 if (!PointerAuth)
3095 return Pointer;
3096
3097 auto Key = CGF.Builder.getInt32(PointerAuth.getKey());
3098
3099 llvm::Value *Discriminator = PointerAuth.getDiscriminator();
3100 if (!Discriminator) {
3101 Discriminator = CGF.Builder.getSize(0);
3102 }
3103
3104 // Convert the pointer to intptr_t before signing it.
3105 auto OrigType = Pointer->getType();
3106 Pointer = CGF.Builder.CreatePtrToInt(Pointer, CGF.IntPtrTy);
3107
3108 // call i64 @llvm.ptrauth.sign.i64(i64 %pointer, i32 %key, i64 %discriminator)
3109 auto Intrinsic = CGF.CGM.getIntrinsic(IntrinsicID);
3110 Pointer = CGF.EmitRuntimeCall(Intrinsic, {Pointer, Key, Discriminator});
3111
3112 // Convert back to the original type.
3113 Pointer = CGF.Builder.CreateIntToPtr(Pointer, OrigType);
3114 return Pointer;
3115}
3116
3117llvm::Value *
3119 llvm::Value *Pointer) {
3120 if (!PointerAuth.shouldSign())
3121 return Pointer;
3122 return EmitPointerAuthCommon(*this, PointerAuth, Pointer,
3123 llvm::Intrinsic::ptrauth_sign);
3124}
3125
3126static llvm::Value *EmitStrip(CodeGenFunction &CGF,
3127 const CGPointerAuthInfo &PointerAuth,
3128 llvm::Value *Pointer) {
3129 auto StripIntrinsic = CGF.CGM.getIntrinsic(llvm::Intrinsic::ptrauth_strip);
3130
3131 auto Key = CGF.Builder.getInt32(PointerAuth.getKey());
3132 // Convert the pointer to intptr_t before signing it.
3133 auto OrigType = Pointer->getType();
3135 StripIntrinsic, {CGF.Builder.CreatePtrToInt(Pointer, CGF.IntPtrTy), Key});
3136 return CGF.Builder.CreateIntToPtr(Pointer, OrigType);
3137}
3138
3139llvm::Value *
3141 llvm::Value *Pointer) {
3142 if (PointerAuth.shouldStrip()) {
3143 return EmitStrip(*this, PointerAuth, Pointer);
3144 }
3145 if (!PointerAuth.shouldAuth()) {
3146 return Pointer;
3147 }
3148
3149 return EmitPointerAuthCommon(*this, PointerAuth, Pointer,
3150 llvm::Intrinsic::ptrauth_auth);
3151}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3341
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
Defines enum values for all the target-independent builtin functions.
const Decl * D
Expr * E
static llvm::Value * EmitPointerAuthCommon(CodeGenFunction &CGF, const CGPointerAuthInfo &PointerAuth, llvm::Value *Pointer, unsigned IntrinsicID)
static void CreateMultiVersionResolverReturn(CodeGenModule &CGM, llvm::Function *Resolver, CGBuilderTy &Builder, llvm::Function *FuncToReturn, bool SupportsIFunc)
static llvm::Value * EmitStrip(CodeGenFunction &CGF, const CGPointerAuthInfo &PointerAuth, llvm::Value *Pointer)
static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, Address dest, Address src, llvm::Value *sizeInChars)
emitNonZeroVLAInit - Emit the "zero" initialization of a variable-length array whose elements have a ...
static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB)
static LValue makeNaturalAlignAddrLValue(llvm::Value *V, QualType T, bool ForPointeeType, bool MightBeSigned, CodeGenFunction &CGF, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
static void TryMarkNoThrow(llvm::Function *F)
Tries to mark the given function nounwind based on the non-existence of any throwing calls within it.
static llvm::Constant * getPrologueSignature(CodeGenModule &CGM, const FunctionDecl *FD)
Return the UBSan prologue signature for FD if one is available.
static bool endsWithReturn(const Decl *F)
Determine whether the function F ends with a return stmt.
static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts, const LangOptions &LangOpts)
shouldEmitLifetimeMarkers - Decide whether we need emit the life-time markers.
static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
llvm::MachO::Target Target
Definition: MachO.h:51
SourceLocation Loc
Definition: SemaObjC.cpp:759
Defines the Objective-C statement AST node classes.
Enumerates target-specific builtins in their own namespaces within namespace clang.
__device__ double
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const
Parses the target attributes passed in, and returns only the ones that are valid feature names.
CanQualType VoidPtrTy
Definition: ASTContext.h:1146
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:662
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2828
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3571
QualType getElementType() const
Definition: Type.h:3583
Attr - This represents one attribute.
Definition: Attr.h:42
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3860
static bool isLogicalOp(Opcode Opc)
Definition: Expr.h:3993
const char * getRequiredFeatures(unsigned ID) const
Definition: Builtins.h:255
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2539
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2064
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition: DeclCXX.cpp:2500
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2190
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2603
bool isStatic() const
Definition: DeclCXX.cpp:2224
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1023
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Definition: DeclCXX.cpp:1680
bool isCapturelessLambda() const
Definition: DeclCXX.h:1069
A C++ throw-expression (C++ [except.throw]).
Definition: ExprCXX.h:1206
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2830
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition: CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
Definition: CharUnits.h:214
bool isOne() const
isOne - Test whether the quantity equals one.
Definition: CharUnits.h:125
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::string SampleProfileFile
Name of the profile file to use with -fprofile-sample-use.
bool hasProfileClangInstr() const
Check if Clang profile instrumenation is on.
XRayInstrSet XRayInstrumentationBundle
Set of XRay instrumentation kinds to emit.
bool hasSanitizeCoverage() const
PointerAuthOptions PointerAuth
Configuration for pointer-signing.
bool hasReducedDebugInfo() const
Check if type and variable info should be emitted.
bool hasSanitizeBinaryMetadata() const
unsigned getInAllocaFieldIndex() const
@ InAlloca
InAlloca - Pass the argument directly using the LLVM inalloca attribute.
@ Indirect
Indirect - Pass the argument indirectly via a hidden pointer with the specified alignment (0 indicate...
CharUnits getIndirectAlign() const
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition: Address.h:128
static Address invalid()
Definition: Address.h:176
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition: Address.h:251
CharUnits getAlignment() const
Definition: Address.h:189
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition: Address.h:207
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition: Address.h:274
bool isValid() const
Definition: Address.h:177
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition: Address.h:199
A scoped helper to set the current debug location to the specified location or preferred location of ...
Definition: CGDebugInfo.h:855
static ApplyDebugLocation CreateDefaultArtificial(CodeGenFunction &CGF, SourceLocation TemporaryLocation)
Apply TemporaryLocation if it is valid.
Definition: CGDebugInfo.h:902
This is an IRBuilder insertion helper that forwards to CodeGenFunction::InsertHelper,...
Definition: CGBuilder.h:29
void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock::iterator InsertPt) const override
This forwards to CodeGenFunction::InsertHelper.
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:135
llvm::CallInst * CreateMemSet(Address Dest, llvm::Value *Value, llvm::Value *Size, bool IsVolatile=false)
Definition: CGBuilder.h:396
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition: CGBuilder.h:218
llvm::CallInst * CreateMemCpy(Address Dest, Address Src, llvm::Value *Size, bool IsVolatile=false)
Definition: CGBuilder.h:363
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition: CGBuilder.h:127
llvm::ConstantInt * getSize(CharUnits N)
Definition: CGBuilder.h:98
Address CreateInBoundsGEP(Address Addr, ArrayRef< llvm::Value * > IdxList, llvm::Type *ElementType, CharUnits Align, const Twine &Name="")
Definition: CGBuilder.h:344
virtual void emitDeviceStub(CodeGenFunction &CGF, FunctionArgList &Args)=0
Emits a kernel launch stub.
Implements C++ ABI-specific code generation functions.
Definition: CGCXXABI.h:43
virtual bool hasMostDerivedReturn(GlobalDecl GD) const
Definition: CGCXXABI.h:131
virtual bool HasThisReturn(GlobalDecl GD) const
Returns true if the given constructor or destructor is one of the kinds that the ABI says returns 'th...
Definition: CGCXXABI.h:123
virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF)=0
Emit the ABI-specific prolog for the function.
@ RAA_DirectInMemory
Pass it on the stack using its defined layout.
Definition: CGCXXABI.h:158
void buildThisParam(CodeGenFunction &CGF, FunctionArgList &Params)
Build a parameter variable suitable for 'this'.
Definition: CGCXXABI.cpp:128
virtual void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, FunctionArgList &Params)=0
Insert any ABI-specific implicit parameters into the parameter list for a function.
virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const =0
Returns how an argument of the given record type should be passed.
MangleContext & getMangleContext()
Gets the mangle context.
Definition: CGCXXABI.h:113
All available information about a concrete callee.
Definition: CGCall.h:63
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:58
CGFunctionInfo - Class to encapsulate the information about a function definition.
bool isReturnsRetained() const
In ARC, whether this function retains its return value.
CanQualType getReturnType() const
unsigned getMaxVectorWidth() const
Return the maximum vector width in the arguments.
llvm::StructType * getArgStruct() const
Get the struct type used to represent all the arguments in memory.
void setHLSLFunctionAttributes(const FunctionDecl *FD, llvm::Function *Fn)
void emitEntryFunction(const FunctionDecl *FD, llvm::Function *Fn)
virtual void functionFinished(CodeGenFunction &CGF)
Cleans up references to the objects in finished function.
llvm::OpenMPIRBuilder & getOMPBuilder()
virtual void emitFunctionProlog(CodeGenFunction &CGF, const Decl *D)
Emits OpenMP-specific function prolog.
llvm::Value * getDiscriminator() const
CGFPOptionsRAII(CodeGenFunction &CGF, FPOptions FPFeatures)
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::Value * EmitPointerAuthAuth(const CGPointerAuthInfo &Info, llvm::Value *Pointer)
void EmitDestructorBody(FunctionArgList &Args)
void EmitBranchToCounterBlock(const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount=0, Stmt::Likelihood LH=Stmt::LH_None, const Expr *CntrIdx=nullptr)
EmitBranchToCounterBlock - Emit a conditional branch to a new block that increments a profile counter...
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
void EmitNullInitialization(Address DestPtr, QualType Ty)
EmitNullInitialization - Generate code to set a value of the given type to null, If the type contains...
void EmitPointerAuthOperandBundle(const CGPointerAuthInfo &Info, SmallVectorImpl< llvm::OperandBundleDef > &Bundles)
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
ContainsLabel - Return true if the statement contains a label in it.
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount, Stmt::Likelihood LH=Stmt::LH_None, const Expr *ConditionalOp=nullptr)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
llvm::CallInst * EmitTrapCall(llvm::Intrinsic::ID IntrID)
Emit a call to trap or debugtrap and attach function attribute "trap-func-name" if specified.
JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target)
The given basic block lies in the current EH scope, but may be a target of a potentially scope-crossi...
void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK)
SanitizerSet SanOpts
Sanitizers enabled for this function.
void unprotectFromPeepholes(PeepholeProtection protection)
void EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD)
bool ShouldInstrumentFunction()
ShouldInstrumentFunction - Return true if the current function should be instrumented with __cyg_prof...
Address EmitCompoundStmtWithoutScope(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
static bool hasScalarEvaluationKind(QualType T)
LValue MakeNaturalAlignPointeeRawAddrLValue(llvm::Value *V, QualType T)
Same as MakeNaturalAlignPointeeAddrLValue except that the pointer is known to be unsigned.
void EmitKCFIOperandBundle(const CGCallee &Callee, SmallVectorImpl< llvm::OperandBundleDef > &Bundles)
void emitAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue, llvm::Value *TheCheck, llvm::Instruction *Assumption)
llvm::BlockAddress * GetAddrOfLabel(const LabelDecl *L)
RawAddress CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
llvm::Value * emitArrayLength(const ArrayType *arrayType, QualType &baseType, Address &addr)
emitArrayLength - Compute the length of an array, even if it's a VLA, and drill down to the base elem...
VlaSizePair getVLASize(const VariableArrayType *vla)
Returns an LLVM value that corresponds to the size, in non-variably-sized elements,...
void EmitEndEHSpec(const Decl *D)
EmitEndEHSpec - Emit the end of the exception spec.
bool CurFuncIsThunk
In C++, whether we are code generating a thunk.
void EmitAArch64MultiVersionResolver(llvm::Function *Resolver, ArrayRef< MultiVersionResolverOption > Options)
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
llvm::SmallVector< DeferredDeactivateCleanup > DeferredDeactivationCleanupStack
void EmitVariablyModifiedType(QualType Ty)
EmitVLASize - Capture all the sizes for the VLA expressions in the given variably-modified type and s...
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
const LangOptions & getLangOpts() const
void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, SourceLocation EndLoc)
EmitFunctionEpilog - Emit the target specific LLVM code to return the given temporary.
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler.
llvm::BasicBlock * EHResumeBlock
EHResumeBlock - Unified block containing a call to llvm.eh.resume.
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
static bool isInstrumentedCondition(const Expr *C)
isInstrumentedCondition - Determine whether the given condition is an instrumentable condition (i....
void EmitX86MultiVersionResolver(llvm::Function *Resolver, ArrayRef< MultiVersionResolverOption > Options)
void EmitFunctionBody(const Stmt *Body)
Address makeNaturalAddressForPointer(llvm::Value *Ptr, QualType T, CharUnits Alignment=CharUnits::Zero(), bool ForPointeeType=false, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
Construct an address with the natural alignment of T.
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
@ TCK_ConstructorCall
Checking the 'this' pointer for a constructor call.
@ TCK_MemberCall
Checking the 'this' pointer for a call to a non-static member function.
void setCurrentProfileCount(uint64_t Count)
Set the profiler's current count.
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize, std::initializer_list< llvm::Value ** > ValuesToReload={})
Takes the old cleanup stack size and emits the cleanup blocks that have been added.
llvm::Type * ConvertTypeForMem(QualType T)
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
llvm::AssertingVH< llvm::Instruction > AllocaInsertPt
AllocaInsertPoint - This is an instruction in the entry block before which we prefer to insert alloca...
bool AlwaysEmitXRayCustomEvents() const
AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit XRay custom event handling c...
JumpDest ReturnBlock
ReturnBlock - Unified return block.
void EmitVarAnnotations(const VarDecl *D, llvm::Value *V)
Emit local annotations for the local variable V, declared by D.
llvm::Value * EmitPointerAuthSign(const CGPointerAuthInfo &Info, llvm::Value *Pointer)
static const Expr * stripCond(const Expr *C)
Ignore parentheses and logical-NOT to track conditions consistently.
PeepholeProtection protectFromPeepholes(RValue rvalue)
protectFromPeepholes - Protect a value that we're intending to store to the side, but which will prob...
const TargetInfo & getTarget() const
llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location)
Converts Location to a DebugLoc, if debug information is enabled.
void EmitFunctionProlog(const CGFunctionInfo &FI, llvm::Function *Fn, const FunctionArgList &Args)
EmitFunctionProlog - Emit the target specific LLVM code to load the arguments for the given function.
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerMask > > Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs)
Create a basic block that will either trap or call a handler function in the UBSan runtime with the p...
void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S)
bool ShouldSkipSanitizerInstrumentation()
ShouldSkipSanitizerInstrumentation - Return true if the current function should not be instrumented w...
uint64_t getCurrentProfileCount()
Get the profiler's current count.
SmallVector< const BinaryOperator *, 16 > MCDCLogOpStack
Stack to track the Logical Operator recursion nest for MC/DC.
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn)
Annotate the function with an attribute that disables TSan checking at runtime.
void ErrorUnsupported(const Stmt *S, const char *Type)
ErrorUnsupported - Print out an error that codegen doesn't support the specified stmt yet.
Address EmitVAListRef(const Expr *E)
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
void maybeCreateMCDCCondBitmap()
Allocate a temp value on the stack that MCDC can use to track condition results.
SmallVector< llvm::IntrinsicInst *, 4 > ConvergenceTokenStack
Stack to track the controlled convergence tokens.
void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue=nullptr)
llvm::Value * emitBoolVecConversion(llvm::Value *SrcVec, unsigned NumElementsDst, const llvm::Twine &Name="")
LValue MakeNaturalAlignRawAddrLValue(llvm::Value *V, QualType T)
bool ShouldXRayInstrumentFunction() const
ShouldXRayInstrument - Return true if the current function should be instrumented with XRay nop sleds...
void EmitStartEHSpec(const Decl *D)
EmitStartEHSpec - Emit the start of the exception spec.
void EmitMultiVersionResolver(llvm::Function *Resolver, ArrayRef< MultiVersionResolverOption > Options)
llvm::Value * EmitCheckValue(llvm::Value *V)
Convert a value into a format suitable for passing to a runtime sanitizer handler.
VlaSizePair getVLAElements1D(const VariableArrayType *vla)
Return the number of elements for a single dimension for the given array type.
bool AlwaysEmitXRayTypedEvents() const
AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit XRay typed event handling ...
void EmitConstructorBody(FunctionArgList &Args)
void SetFastMathFlags(FPOptions FPFeatures)
Set the codegen fast-math flags.
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
void maybeUpdateMCDCCondBitmap(const Expr *E, llvm::Value *Val)
Update the MCDC temp value with the condition's evaluated result.
void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl)
void EmitLambdaInAllocaCallOpBody(const CXXMethodDecl *MD)
llvm::SmallVector< char, 256 > LifetimeExtendedCleanupStack
void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init)
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, bool AllowLabels=false)
ConstantFoldsToSimpleInteger - If the specified expression does not fold to a constant,...
Address ReturnValuePointer
ReturnValuePointer - The temporary alloca to hold a pointer to sret.
llvm::ConstantInt * getUBSanFunctionTypeHash(QualType T) const
Return a type hash constant for a function instrumented by -fsanitize=function.
JumpDest getJumpDestForLabel(const LabelDecl *S)
getBasicBlockForLabel - Return the LLVM basicblock that the specified label maps to.
llvm::DenseMap< const ValueDecl *, FieldDecl * > LambdaCaptureFields
bool AutoreleaseResult
In ARC, whether we should autorelease the return value.
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
llvm::Type * ConvertType(QualType T)
CodeGenTypes & getTypes() const
bool IsSanitizerScope
True if CodeGen currently emits code implementing sanitizer checks.
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, LValue LV, QualType Type, SanitizerSet SkippedChecks=SanitizerSet(), llvm::Value *ArraySize=nullptr)
llvm::SmallVector< const ParmVarDecl *, 4 > FnArgs
Save Parameter Decl for coroutine.
QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args)
RawAddress NormalCleanupDest
i32s containing the indexes of the cleanup destinations.
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
Address EmitMSVAListRef(const Expr *E)
Emit a "reference" to a __builtin_ms_va_list; this is always the value of the expression,...
EHScopeStack::stable_iterator PrologueCleanupDepth
PrologueCleanupDepth - The cleanup depth enclosing all the cleanups associated with the parameters.
static bool mightAddDeclToScope(const Stmt *S)
Determine if the given statement might introduce a declaration into the current scope,...
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
RawAddress CreateIRTemp(QualType T, const Twine &Name="tmp")
CreateIRTemp - Create a temporary IR object of the given type, with appropriate alignment.
void emitImplicitAssignmentOperatorBody(FunctionArgList &Args)
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
const CGFunctionInfo * CurFnInfo
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock::iterator InsertPt) const
CGBuilder insert helper.
Address EmitFieldAnnotations(const FieldDecl *D, Address V)
Emit field annotations for the given field & value.
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
void EmitStmt(const Stmt *S, ArrayRef< const Attr * > Attrs=std::nullopt)
EmitStmt - Emit the code for the statement.
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T)
Given a value of type T* that may not be to a complete object, construct an l-value with the natural ...
llvm::LLVMContext & getLLVMContext()
bool SawAsmBlock
Whether we processed a Microsoft-style asm block during CodeGen.
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
bool checkIfFunctionMustProgress()
Returns true if a function must make progress, which means the mustprogress attribute can be added.
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
llvm::Value * EmitAnnotationCall(llvm::Function *AnnotationFn, llvm::Value *AnnotatedVal, StringRef AnnotationStr, SourceLocation Location, const AnnotateAttr *Attr)
Emit an annotation call (intrinsic).
llvm::BasicBlock * GetIndirectGotoBlock()
llvm::Type * convertTypeForLoadStore(QualType ASTTy, llvm::Type *LLVMTy=nullptr)
llvm::DebugLoc EmitReturnBlock()
Emit the unified return block, trying to avoid its emission when possible.
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
LValue EmitLValueForLambdaField(const FieldDecl *Field)
static bool containsBreak(const Stmt *S)
containsBreak - Return true if the statement contains a break out of it.
This class organizes the cross-function state that is used while generating LLVM code.
CGHLSLRuntime & getHLSLRuntime()
Return a reference to the configured HLSL runtime.
llvm::Constant * EmitAnnotationArgs(const AnnotateAttr *Attr)
Emit additional args of the annotation.
llvm::Module & getModule() const
DiagnosticsEngine & getDiags() const
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
const LangOptions & getLangOpts() const
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
llvm::Constant * EmitAnnotationLineNo(SourceLocation L)
Emit the annotation line number.
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
const llvm::DataLayout & getDataLayout() const
bool shouldEmitConvergenceTokens() const
CGCXXABI & getCXXABI() const
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, StringRef Category=StringRef()) const
Imbue XRay attributes to a function, applying the always/never attribute lists in the process.
ProfileList::ExclusionType isFunctionBlockedFromProfileInstr(llvm::Function *Fn, SourceLocation Loc) const
ASTContext & getContext() const
llvm::SanitizerStatReport & getSanStats()
llvm::Constant * EmitAnnotationString(StringRef Str)
Emit an annotation string.
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
llvm::LLVMContext & getLLVMContext()
void GenKernelArgMetadata(llvm::Function *FN, const FunctionDecl *FD=nullptr, CodeGenFunction *CGF=nullptr)
OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument information in the program executab...
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
llvm::ConstantInt * CreateKCFITypeId(QualType T)
Generate a KCFI type identifier for T.
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys=std::nullopt)
bool MayDropFunctionReturn(const ASTContext &Context, QualType ReturnType) const
Whether this function's return type has no side effects, and thus may be trivially discarded if it is...
Definition: CGCall.cpp:1795
llvm::Constant * EmitAnnotationUnit(SourceLocation Loc)
Emit the annotation's translation unit.
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
void assignRegionCounters(GlobalDecl GD, llvm::Function *Fn)
Assign counters to regions and configure them for PGO of a given function.
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
bool inheritingCtorHasParams(const InheritedConstructor &Inherited, CXXCtorType Type)
Determine if a C++ inheriting constructor should have parameters matching those of its inherited cons...
Definition: CGCall.cpp:325
llvm::Type * convertTypeForLoadStore(QualType T, llvm::Type *LLVMTy=nullptr)
Given that T is a scalar type, return the IR type that should be used for load and store operations.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
bool isZeroInitializable(QualType T)
IsZeroInitializable - Return whether a type can be zero-initialized (in the C++ sense) with an LLVM z...
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
Definition: EHScopeStack.h:393
bool containsOnlyLifetimeMarkers(stable_iterator Old) const
Definition: CGCleanup.cpp:115
bool empty() const
Determines whether the exception-scopes stack is empty.
Definition: EHScopeStack.h:359
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition: CGCall.h:368
LValue - This represents an lvalue references.
Definition: CGValue.h:182
llvm::Value * getPointer(CodeGenFunction &CGF) const
Address getAddress() const
Definition: CGValue.h:361
void InsertHelper(llvm::Instruction *I) const
Function called by the CodeGenFunction when an instruction is created.
Definition: CGLoopInfo.cpp:840
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition: CGValue.h:42
bool isScalar() const
Definition: CGValue.h:64
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition: CGValue.h:71
llvm::Value * getPointer() const
Definition: Address.h:66
bool isValid() const
Definition: Address.h:62
virtual void checkFunctionABI(CodeGenModule &CGM, const FunctionDecl *Decl) const
Any further codegen related checks that need to be done on a function signature in a target specific ...
Definition: TargetInfo.h:90
virtual llvm::Constant * getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const
Return a constant used by UBSan as a signature to identify functions possessing type information,...
Definition: TargetInfo.h:219
void Init(const Stmt *Body)
Clear the object and pre-process for the given statement, usually function body statement.
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1611
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4213
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
T * getAttr() const
Definition: DeclBase.h:580
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:523
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks,...
Definition: DeclBase.cpp:1242
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:566
SourceLocation getLocation() const
Definition: DeclBase.h:446
bool hasAttr() const
Definition: DeclBase.h:584
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
This represents one expression.
Definition: Expr.h:110
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition: Expr.cpp:3864
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3066
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3050
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
ExtVectorType - Extended vector type.
Definition: Type.h:4118
LangOptions::FPExceptionModeKind getExceptionMode() const
Definition: LangOptions.h:893
bool allowFPContractAcrossStatement() const
Definition: LangOptions.h:868
RoundingMode getRoundingMode() const
Definition: LangOptions.h:881
Represents a member of a struct/union/class.
Definition: Decl.h:3030
Represents a function declaration or definition.
Definition: Decl.h:1932
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2562
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3224
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3618
bool UsesFPIntrin() const
Determine whether the function was declared in source context that requires constrained FP intrinsics...
Definition: Decl.h:2781
bool usesSEHTry() const
Indicates the function uses __try.
Definition: Decl.h:2443
QualType getReturnType() const
Definition: Decl.h:2717
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2646
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:4099
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3300
bool isInlineBuiltinDeclaration() const
Determine if this function provides an inline implementation of a builtin.
Definition: Decl.cpp:3435
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition: Decl.h:2353
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3294
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2310
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3965
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5007
QualType desugar() const
Definition: Type.h:5551
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
CXXCtorType getCtorType() const
Definition: GlobalDecl.h:105
const Decl * getDecl() const
Definition: GlobalDecl.h:103
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition: Decl.cpp:5378
Represents the declaration of a label.
Definition: Decl.h:499
FPExceptionModeKind
Possible floating point exception behavior.
Definition: LangOptions.h:276
@ FPE_Strict
Strictly preserve the floating-point exception semantics.
Definition: LangOptions.h:282
@ FPE_MayTrap
Transformations do not cause new exceptions but may hide some.
Definition: LangOptions.h:280
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Definition: LangOptions.h:278
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:476
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:482
RoundingMode getDefaultRoundingMode() const
Definition: LangOptions.h:780
virtual void mangleCanonicalTypeName(QualType T, raw_ostream &, bool NormalizeIntegers=false)=0
Generates a unique string for an externally visible type for use with TBAA or type uniquing.
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
Represents a parameter to a function.
Definition: Decl.h:1722
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3192
@ Forbid
Profiling is forbidden using the noprofile attribute.
Definition: ProfileList.h:37
@ Skip
Profiling is skipped using the skipprofile attribute.
Definition: ProfileList.h:35
@ Allow
Profiling is allowed.
Definition: ProfileList.h:33
A (possibly-)qualified type.
Definition: Type.h:941
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7839
field_range fields() const
Definition: Decl.h:4351
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5970
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:205
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition: Stmt.h:84
StmtClass getStmtClass() const
Definition: Stmt.h:1363
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
Likelihood
The likelihood of a branch being taken.
Definition: Stmt.h:1306
@ LH_Unlikely
Branch has the [[unlikely]] attribute.
Definition: Stmt.h:1307
@ LH_None
No attribute set or branches of the IfStmt have the same attribute.
Definition: Stmt.h:1308
@ LH_Likely
Branch has the [[likely]] attribute.
Definition: Stmt.h:1310
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
bool supportsIFunc() const
Identify whether this target supports IFuncs.
Definition: TargetInfo.h:1503
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
virtual std::optional< std::pair< unsigned, unsigned > > getVScaleRange(const LangOptions &LangOpts) const
Returns target-specific min and max values VScale_Range.
Definition: TargetInfo.h:1017
The base class of the type hierarchy.
Definition: Type.h:1829
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isVoidType() const
Definition: Type.h:8324
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2146
bool isPointerType() const
Definition: Type.h:8008
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2718
TypeClass getTypeClass() const
Definition: Type.h:2339
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8545
bool isRecordType() const
Definition: Type.h:8108
bool isObjCRetainableType() const
Definition: Type.cpp:4950
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4693
bool isFunctionNoProtoType() const
Definition: Type.h:2532
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2188
QualType getType() const
Definition: Decl.h:678
Represents a variable declaration or definition.
Definition: Decl.h:879
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3800
Expr * getSizeExpr() const
Definition: Type.h:3819
QualType getElementType() const
Definition: Type.h:4040
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition: limits.h:64
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
TypeEvaluationKind
The kind of evaluation to perform on values of a particular type.
@ NotKnownNonNull
Definition: Address.h:33
constexpr XRayInstrMask Typed
Definition: XRayInstr.h:42
constexpr XRayInstrMask FunctionExit
Definition: XRayInstr.h:40
constexpr XRayInstrMask FunctionEntry
Definition: XRayInstr.h:39
constexpr XRayInstrMask Custom
Definition: XRayInstr.h:41
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
Matches all kinds of arrays.
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2263
The JSON file list parser is used to communicate input to InstallAPI.
@ OpenCL
Definition: LangStandard.h:66
@ CPlusPlus
Definition: LangStandard.h:56
@ NonNull
Values of this type can never be null.
BinaryOperatorKind
@ OMF_initialize
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Result
The result type of a method or function.
const FunctionProtoType * T
llvm::fp::ExceptionBehavior ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind)
@ Other
Other implicit parameter.
@ EST_None
no exception specification
@ Implicit
An implicit conversion.
unsigned long uint64_t
unsigned int uint32_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
cl::opt< bool > EnableSingleByteCoverage
This structure provides a set of types that are commonly used during IR emission.
llvm::PointerType * ConstGlobalsPtrTy
void* in the address space for constant globals
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:57
bool ReturnAddresses
Should return addresses be authenticated?
PointerAuthSchema FunctionPointers
The ABI for C function pointers.
bool AuthTraps
Do authentication failures cause a trap?
bool IndirectGotos
Do indirect goto label addresses need to be authenticated?
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
Definition: Sanitizers.h:168
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:159
SanitizerMask Mask
Bitmask of enabled sanitizers.
Definition: Sanitizers.h:182
bool hasOneOf(SanitizerMask K) const
Check if one or more sanitizers are enabled.
Definition: Sanitizers.h:165
XRayInstrMask Mask
Definition: XRayInstr.h:65
bool has(XRayInstrMask K) const
Definition: XRayInstr.h:48