clang 20.0.0git
CodeGenFunction.h
Go to the documentation of this file.
1//===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===//
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 is the internal per-function state used for llvm translation.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
14#define LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
15
16#include "CGBuilder.h"
17#include "CGDebugInfo.h"
18#include "CGLoopInfo.h"
19#include "CGValue.h"
20#include "CodeGenModule.h"
21#include "CodeGenPGO.h"
22#include "EHScopeStack.h"
23#include "VarBypassDetector.h"
24#include "clang/AST/CharUnits.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
31#include "clang/AST/StmtSYCL.h"
32#include "clang/AST/Type.h"
33#include "clang/Basic/ABI.h"
38#include "llvm/ADT/ArrayRef.h"
39#include "llvm/ADT/DenseMap.h"
40#include "llvm/ADT/MapVector.h"
41#include "llvm/ADT/SmallVector.h"
42#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
43#include "llvm/IR/Instructions.h"
44#include "llvm/IR/ValueHandle.h"
45#include "llvm/Support/Debug.h"
46#include "llvm/Transforms/Utils/SanitizerStats.h"
47#include <optional>
48
49namespace llvm {
50class BasicBlock;
51class LLVMContext;
52class MDNode;
53class SwitchInst;
54class Twine;
55class Value;
56class CanonicalLoopInfo;
57}
58
59namespace clang {
60class ASTContext;
61class CXXDestructorDecl;
62class CXXForRangeStmt;
63class CXXTryStmt;
64class Decl;
65class LabelDecl;
66class FunctionDecl;
67class FunctionProtoType;
68class LabelStmt;
69class ObjCContainerDecl;
70class ObjCInterfaceDecl;
71class ObjCIvarDecl;
72class ObjCMethodDecl;
73class ObjCImplementationDecl;
74class ObjCPropertyImplDecl;
75class TargetInfo;
76class VarDecl;
77class ObjCForCollectionStmt;
78class ObjCAtTryStmt;
79class ObjCAtThrowStmt;
80class ObjCAtSynchronizedStmt;
81class ObjCAutoreleasePoolStmt;
82class OMPUseDevicePtrClause;
83class OMPUseDeviceAddrClause;
84class SVETypeFlags;
85class OMPExecutableDirective;
86
87namespace analyze_os_log {
88class OSLogBufferLayout;
89}
90
91namespace CodeGen {
92class CodeGenTypes;
93class CGCallee;
94class CGFunctionInfo;
95class CGBlockInfo;
96class CGCXXABI;
97class BlockByrefHelpers;
98class BlockByrefInfo;
99class BlockFieldFlags;
100class RegionCodeGenTy;
101class TargetCodeGenInfo;
102struct OMPTaskDataTy;
103struct CGCoroData;
104
105/// The kind of evaluation to perform on values of a particular
106/// type. Basically, is the code in CGExprScalar, CGExprComplex, or
107/// CGExprAgg?
108///
109/// TODO: should vectors maybe be split out into their own thing?
115
116#define LIST_SANITIZER_CHECKS \
117 SANITIZER_CHECK(AddOverflow, add_overflow, 0) \
118 SANITIZER_CHECK(BuiltinUnreachable, builtin_unreachable, 0) \
119 SANITIZER_CHECK(CFICheckFail, cfi_check_fail, 0) \
120 SANITIZER_CHECK(DivremOverflow, divrem_overflow, 0) \
121 SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss, 0) \
122 SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0) \
123 SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch, 0) \
124 SANITIZER_CHECK(ImplicitConversion, implicit_conversion, 0) \
125 SANITIZER_CHECK(InvalidBuiltin, invalid_builtin, 0) \
126 SANITIZER_CHECK(InvalidObjCCast, invalid_objc_cast, 0) \
127 SANITIZER_CHECK(LoadInvalidValue, load_invalid_value, 0) \
128 SANITIZER_CHECK(MissingReturn, missing_return, 0) \
129 SANITIZER_CHECK(MulOverflow, mul_overflow, 0) \
130 SANITIZER_CHECK(NegateOverflow, negate_overflow, 0) \
131 SANITIZER_CHECK(NullabilityArg, nullability_arg, 0) \
132 SANITIZER_CHECK(NullabilityReturn, nullability_return, 1) \
133 SANITIZER_CHECK(NonnullArg, nonnull_arg, 0) \
134 SANITIZER_CHECK(NonnullReturn, nonnull_return, 1) \
135 SANITIZER_CHECK(OutOfBounds, out_of_bounds, 0) \
136 SANITIZER_CHECK(PointerOverflow, pointer_overflow, 0) \
137 SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds, 0) \
138 SANITIZER_CHECK(SubOverflow, sub_overflow, 0) \
139 SANITIZER_CHECK(TypeMismatch, type_mismatch, 1) \
140 SANITIZER_CHECK(AlignmentAssumption, alignment_assumption, 0) \
141 SANITIZER_CHECK(VLABoundNotPositive, vla_bound_not_positive, 0) \
142 SANITIZER_CHECK(BoundsSafety, bounds_safety, 0)
143
145#define SANITIZER_CHECK(Enum, Name, Version) Enum,
147#undef SANITIZER_CHECK
149
150/// Helper class with most of the code for saving a value for a
151/// conditional expression cleanup.
153 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
154
155 /// Answer whether the given value needs extra work to be saved.
156 static bool needsSaving(llvm::Value *value) {
157 if (!value)
158 return false;
159
160 // If it's not an instruction, we don't need to save.
161 if (!isa<llvm::Instruction>(value)) return false;
162
163 // If it's an instruction in the entry block, we don't need to save.
164 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
165 return (block != &block->getParent()->getEntryBlock());
166 }
167
168 static saved_type save(CodeGenFunction &CGF, llvm::Value *value);
169 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value);
170};
171
172/// A partial specialization of DominatingValue for llvm::Values that
173/// might be llvm::Instructions.
174template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
175 typedef T *type;
177 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
178 }
179};
180
181/// A specialization of DominatingValue for Address.
182template <> struct DominatingValue<Address> {
183 typedef Address type;
184
185 struct saved_type {
187 llvm::Type *ElementType;
190 llvm::PointerType *EffectiveType;
191 };
192
193 static bool needsSaving(type value) {
196 return true;
197 return false;
198 }
199 static saved_type save(CodeGenFunction &CGF, type value) {
200 return {DominatingLLVMValue::save(CGF, value.getBasePointer()),
201 value.getElementType(), value.getAlignment(),
202 DominatingLLVMValue::save(CGF, value.getOffset()), value.getType()};
203 }
205 return Address(DominatingLLVMValue::restore(CGF, value.BasePtr),
206 value.ElementType, value.Alignment, CGPointerAuthInfo(),
207 DominatingLLVMValue::restore(CGF, value.Offset));
208 }
209};
210
211/// A specialization of DominatingValue for RValue.
212template <> struct DominatingValue<RValue> {
213 typedef RValue type;
215 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
216 AggregateAddress, ComplexAddress };
217 union {
218 struct {
220 } Vals;
222 };
223 LLVM_PREFERRED_TYPE(Kind)
224 unsigned K : 3;
225
227 : Vals{Val1, DominatingLLVMValue::saved_type()}, K(K) {}
228
231 : Vals{Val1, Val2}, K(ComplexAddress) {}
232
233 saved_type(DominatingValue<Address>::saved_type AggregateAddr, unsigned K)
234 : AggregateAddr(AggregateAddr), K(K) {}
235
236 public:
237 static bool needsSaving(RValue value);
240
241 // implementations in CGCleanup.cpp
242 };
243
244 static bool needsSaving(type value) {
245 return saved_type::needsSaving(value);
246 }
247 static saved_type save(CodeGenFunction &CGF, type value) {
248 return saved_type::save(CGF, value);
249 }
251 return value.restore(CGF);
252 }
253};
254
255/// CodeGenFunction - This class organizes the per-function state that is used
256/// while generating LLVM code.
258 CodeGenFunction(const CodeGenFunction &) = delete;
259 void operator=(const CodeGenFunction &) = delete;
260
261 friend class CGCXXABI;
262public:
263 /// A jump destination is an abstract label, branching to which may
264 /// require a jump out through normal cleanups.
265 struct JumpDest {
266 JumpDest() : Block(nullptr), Index(0) {}
267 JumpDest(llvm::BasicBlock *Block, EHScopeStack::stable_iterator Depth,
268 unsigned Index)
269 : Block(Block), ScopeDepth(Depth), Index(Index) {}
270
271 bool isValid() const { return Block != nullptr; }
272 llvm::BasicBlock *getBlock() const { return Block; }
273 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
274 unsigned getDestIndex() const { return Index; }
275
276 // This should be used cautiously.
278 ScopeDepth = depth;
279 }
280
281 private:
282 llvm::BasicBlock *Block;
284 unsigned Index;
285 };
286
287 CodeGenModule &CGM; // Per-module state.
289
290 // For EH/SEH outlined funclets, this field points to parent's CGF
292
293 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
296
297 // Stores variables for which we can't generate correct lifetime markers
298 // because of jumps.
300
301 /// List of recently emitted OMPCanonicalLoops.
302 ///
303 /// Since OMPCanonicalLoops are nested inside other statements (in particular
304 /// CapturedStmt generated by OMPExecutableDirective and non-perfectly nested
305 /// loops), we cannot directly call OMPEmitOMPCanonicalLoop and receive its
306 /// llvm::CanonicalLoopInfo. Instead, we call EmitStmt and any
307 /// OMPEmitOMPCanonicalLoop called by it will add its CanonicalLoopInfo to
308 /// this stack when done. Entering a new loop requires clearing this list; it
309 /// either means we start parsing a new loop nest (in which case the previous
310 /// loop nest goes out of scope) or a second loop in the same level in which
311 /// case it would be ambiguous into which of the two (or more) loops the loop
312 /// nest would extend.
314
315 /// Stack to track the Logical Operator recursion nest for MC/DC.
317
318 /// Stack to track the controlled convergence tokens.
320
321 /// Number of nested loop to be consumed by the last surrounding
322 /// loop-associated directive.
324
325 // CodeGen lambda for loops and support for ordered clause
326 typedef llvm::function_ref<void(CodeGenFunction &, const OMPLoopDirective &,
327 JumpDest)>
329 typedef llvm::function_ref<void(CodeGenFunction &, SourceLocation,
330 const unsigned, const bool)>
332
333 // Codegen lambda for loop bounds in worksharing loop constructs
334 typedef llvm::function_ref<std::pair<LValue, LValue>(
337
338 // Codegen lambda for loop bounds in dispatch-based loop implementation
339 typedef llvm::function_ref<std::pair<llvm::Value *, llvm::Value *>(
341 Address UB)>
343
344 /// CGBuilder insert helper. This function is called after an
345 /// instruction is created using Builder.
346 void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
347 llvm::BasicBlock::iterator InsertPt) const;
348
349 /// CurFuncDecl - Holds the Decl for the current outermost
350 /// non-closure context.
351 const Decl *CurFuncDecl = nullptr;
352 /// CurCodeDecl - This is the inner-most code context, which includes blocks.
353 const Decl *CurCodeDecl = nullptr;
354 const CGFunctionInfo *CurFnInfo = nullptr;
356 llvm::Function *CurFn = nullptr;
357
358 /// Save Parameter Decl for coroutine.
360
361 // Holds coroutine data if the current function is a coroutine. We use a
362 // wrapper to manage its lifetime, so that we don't have to define CGCoroData
363 // in this header.
364 struct CGCoroInfo {
365 std::unique_ptr<CGCoroData> Data;
366 bool InSuspendBlock = false;
367 CGCoroInfo();
368 ~CGCoroInfo();
369 };
371
372 bool isCoroutine() const {
373 return CurCoro.Data != nullptr;
374 }
375
376 bool inSuspendBlock() const {
378 }
379
380 // Holds FramePtr for await_suspend wrapper generation,
381 // so that __builtin_coro_frame call can be lowered
382 // directly to value of its second argument
384 llvm::Value *FramePtr = nullptr;
385 };
387
388 // Generates wrapper function for `llvm.coro.await.suspend.*` intrinisics.
389 // It encapsulates SuspendExpr in a function, to separate it's body
390 // from the main coroutine to avoid miscompilations. Intrinisic
391 // is lowered to this function call in CoroSplit pass
392 // Function signature is:
393 // <type> __await_suspend_wrapper_<name>(ptr %awaiter, ptr %hdl)
394 // where type is one of (void, i1, ptr)
395 llvm::Function *generateAwaitSuspendWrapper(Twine const &CoroName,
396 Twine const &SuspendPointName,
397 CoroutineSuspendExpr const &S);
398
399 /// CurGD - The GlobalDecl for the current function being compiled.
401
402 /// PrologueCleanupDepth - The cleanup depth enclosing all the
403 /// cleanups associated with the parameters.
405
406 /// ReturnBlock - Unified return block.
408
409 /// ReturnValue - The temporary alloca to hold the return
410 /// value. This is invalid iff the function has no return value.
412
413 /// ReturnValuePointer - The temporary alloca to hold a pointer to sret.
414 /// This is invalid if sret is not in use.
416
417 /// If a return statement is being visited, this holds the return statment's
418 /// result expression.
419 const Expr *RetExpr = nullptr;
420
421 /// Return true if a label was seen in the current scope.
423 if (CurLexicalScope)
424 return CurLexicalScope->hasLabels();
425 return !LabelMap.empty();
426 }
427
428 /// AllocaInsertPoint - This is an instruction in the entry block before which
429 /// we prefer to insert allocas.
430 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
431
432private:
433 /// PostAllocaInsertPt - This is a place in the prologue where code can be
434 /// inserted that will be dominated by all the static allocas. This helps
435 /// achieve two things:
436 /// 1. Contiguity of all static allocas (within the prologue) is maintained.
437 /// 2. All other prologue code (which are dominated by static allocas) do
438 /// appear in the source order immediately after all static allocas.
439 ///
440 /// PostAllocaInsertPt will be lazily created when it is *really* required.
441 llvm::AssertingVH<llvm::Instruction> PostAllocaInsertPt = nullptr;
442
443public:
444 /// Return PostAllocaInsertPt. If it is not yet created, then insert it
445 /// immediately after AllocaInsertPt.
446 llvm::Instruction *getPostAllocaInsertPoint() {
447 if (!PostAllocaInsertPt) {
448 assert(AllocaInsertPt &&
449 "Expected static alloca insertion point at function prologue");
450 assert(AllocaInsertPt->getParent()->isEntryBlock() &&
451 "EBB should be entry block of the current code gen function");
452 PostAllocaInsertPt = AllocaInsertPt->clone();
453 PostAllocaInsertPt->setName("postallocapt");
454 PostAllocaInsertPt->insertAfter(AllocaInsertPt);
455 }
456
457 return PostAllocaInsertPt;
458 }
459
460 /// API for captured statement code generation.
462 public:
464 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
467 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
468
470 S.getCapturedRecordDecl()->field_begin();
471 for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
472 E = S.capture_end();
473 I != E; ++I, ++Field) {
474 if (I->capturesThis())
475 CXXThisFieldDecl = *Field;
476 else if (I->capturesVariable())
477 CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
478 else if (I->capturesVariableByCopy())
479 CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
480 }
481 }
482
483 virtual ~CGCapturedStmtInfo();
484
485 CapturedRegionKind getKind() const { return Kind; }
486
487 virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
488 // Retrieve the value of the context parameter.
489 virtual llvm::Value *getContextValue() const { return ThisValue; }
490
491 /// Lookup the captured field decl for a variable.
492 virtual const FieldDecl *lookup(const VarDecl *VD) const {
493 return CaptureFields.lookup(VD->getCanonicalDecl());
494 }
495
496 bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
497 virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
498
499 static bool classof(const CGCapturedStmtInfo *) {
500 return true;
501 }
502
503 /// Emit the captured statement body.
504 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
506 CGF.EmitStmt(S);
507 }
508
509 /// Get the name of the capture helper.
510 virtual StringRef getHelperName() const { return "__captured_stmt"; }
511
512 /// Get the CaptureFields
513 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> getCaptureFields() {
514 return CaptureFields;
515 }
516
517 private:
518 /// The kind of captured statement being generated.
520
521 /// Keep the map between VarDecl and FieldDecl.
522 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
523
524 /// The base address of the captured record, passed in as the first
525 /// argument of the parallel region function.
526 llvm::Value *ThisValue;
527
528 /// Captured 'this' type.
529 FieldDecl *CXXThisFieldDecl;
530 };
532
533 /// RAII for correct setting/restoring of CapturedStmtInfo.
535 private:
536 CodeGenFunction &CGF;
537 CGCapturedStmtInfo *PrevCapturedStmtInfo;
538 public:
540 CGCapturedStmtInfo *NewCapturedStmtInfo)
541 : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
542 CGF.CapturedStmtInfo = NewCapturedStmtInfo;
543 }
544 ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
545 };
546
547 /// An abstract representation of regular/ObjC call/message targets.
549 /// The function declaration of the callee.
550 const Decl *CalleeDecl;
551
552 public:
553 AbstractCallee() : CalleeDecl(nullptr) {}
554 AbstractCallee(const FunctionDecl *FD) : CalleeDecl(FD) {}
555 AbstractCallee(const ObjCMethodDecl *OMD) : CalleeDecl(OMD) {}
556 bool hasFunctionDecl() const {
557 return isa_and_nonnull<FunctionDecl>(CalleeDecl);
558 }
559 const Decl *getDecl() const { return CalleeDecl; }
560 unsigned getNumParams() const {
561 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
562 return FD->getNumParams();
563 return cast<ObjCMethodDecl>(CalleeDecl)->param_size();
564 }
565 const ParmVarDecl *getParamDecl(unsigned I) const {
566 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
567 return FD->getParamDecl(I);
568 return *(cast<ObjCMethodDecl>(CalleeDecl)->param_begin() + I);
569 }
570 };
571
572 /// Sanitizers enabled for this function.
574
575 /// True if CodeGen currently emits code implementing sanitizer checks.
576 bool IsSanitizerScope = false;
577
578 /// RAII object to set/unset CodeGenFunction::IsSanitizerScope.
580 CodeGenFunction *CGF;
581 public:
584 };
585
586 /// In C++, whether we are code generating a thunk. This controls whether we
587 /// should emit cleanups.
588 bool CurFuncIsThunk = false;
589
590 /// In ARC, whether we should autorelease the return value.
591 bool AutoreleaseResult = false;
592
593 /// Whether we processed a Microsoft-style asm block during CodeGen. These can
594 /// potentially set the return value.
595 bool SawAsmBlock = false;
596
598
599 /// True if the current function is an outlined SEH helper. This can be a
600 /// finally block or filter expression.
602
603 /// True if CodeGen currently emits code inside presereved access index
604 /// region.
606
607 /// True if the current statement has nomerge attribute.
609
610 /// True if the current statement has noinline attribute.
612
613 /// True if the current statement has always_inline attribute.
615
616 /// True if the current statement has noconvergent attribute.
618
619 /// HLSL Branch attribute.
620 HLSLControlFlowHintAttr::Spelling HLSLControlFlowAttr =
621 HLSLControlFlowHintAttr::SpellingNotCalculated;
622
623 // The CallExpr within the current statement that the musttail attribute
624 // applies to. nullptr if there is no 'musttail' on the current statement.
625 const CallExpr *MustTailCall = nullptr;
626
627 /// Returns true if a function must make progress, which means the
628 /// mustprogress attribute can be added.
629 bool