clang 18.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"
30#include "clang/AST/Type.h"
31#include "clang/Basic/ABI.h"
36#include "llvm/ADT/ArrayRef.h"
37#include "llvm/ADT/DenseMap.h"
38#include "llvm/ADT/MapVector.h"
39#include "llvm/ADT/SmallVector.h"
40#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
41#include "llvm/IR/ValueHandle.h"
42#include "llvm/Support/Debug.h"
43#include "llvm/Transforms/Utils/SanitizerStats.h"
44#include <optional>
45
46namespace llvm {
47class BasicBlock;
48class LLVMContext;
49class MDNode;
50class SwitchInst;
51class Twine;
52class Value;
53class CanonicalLoopInfo;
54}
55
56namespace clang {
57class ASTContext;
58class CXXDestructorDecl;
59class CXXForRangeStmt;
60class CXXTryStmt;
61class Decl;
62class LabelDecl;
63class FunctionDecl;
64class FunctionProtoType;
65class LabelStmt;
66class ObjCContainerDecl;
67class ObjCInterfaceDecl;
68class ObjCIvarDecl;
69class ObjCMethodDecl;
70class ObjCImplementationDecl;
71class ObjCPropertyImplDecl;
72class TargetInfo;
73class VarDecl;
74class ObjCForCollectionStmt;
75class ObjCAtTryStmt;
76class ObjCAtThrowStmt;
77class ObjCAtSynchronizedStmt;
78class ObjCAutoreleasePoolStmt;
79class OMPUseDevicePtrClause;
80class OMPUseDeviceAddrClause;
81class SVETypeFlags;
82class OMPExecutableDirective;
83
84namespace analyze_os_log {
85class OSLogBufferLayout;
86}
87
88namespace CodeGen {
89class CodeGenTypes;
90class CGCallee;
91class CGFunctionInfo;
92class CGBlockInfo;
93class CGCXXABI;
94class BlockByrefHelpers;
95class BlockByrefInfo;
96class BlockFieldFlags;
97class RegionCodeGenTy;
98class TargetCodeGenInfo;
99struct OMPTaskDataTy;
100struct CGCoroData;
101
102/// The kind of evaluation to perform on values of a particular
103/// type. Basically, is the code in CGExprScalar, CGExprComplex, or
104/// CGExprAgg?
105///
106/// TODO: should vectors maybe be split out into their own thing?
112
113#define LIST_SANITIZER_CHECKS \
114 SANITIZER_CHECK(AddOverflow, add_overflow, 0) \
115 SANITIZER_CHECK(BuiltinUnreachable, builtin_unreachable, 0) \
116 SANITIZER_CHECK(CFICheckFail, cfi_check_fail, 0) \
117 SANITIZER_CHECK(DivremOverflow, divrem_overflow, 0) \
118 SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss, 0) \
119 SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0) \
120 SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch, 0) \
121 SANITIZER_CHECK(ImplicitConversion, implicit_conversion, 0) \
122 SANITIZER_CHECK(InvalidBuiltin, invalid_builtin, 0) \
123 SANITIZER_CHECK(InvalidObjCCast, invalid_objc_cast, 0) \
124 SANITIZER_CHECK(LoadInvalidValue, load_invalid_value, 0) \
125 SANITIZER_CHECK(MissingReturn, missing_return, 0) \
126 SANITIZER_CHECK(MulOverflow, mul_overflow, 0) \
127 SANITIZER_CHECK(NegateOverflow, negate_overflow, 0) \
128 SANITIZER_CHECK(NullabilityArg, nullability_arg, 0) \
129 SANITIZER_CHECK(NullabilityReturn, nullability_return, 1) \
130 SANITIZER_CHECK(NonnullArg, nonnull_arg, 0) \
131 SANITIZER_CHECK(NonnullReturn, nonnull_return, 1) \
132 SANITIZER_CHECK(OutOfBounds, out_of_bounds, 0) \
133 SANITIZER_CHECK(PointerOverflow, pointer_overflow, 0) \
134 SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds, 0) \
135 SANITIZER_CHECK(SubOverflow, sub_overflow, 0) \
136 SANITIZER_CHECK(TypeMismatch, type_mismatch, 1) \
137 SANITIZER_CHECK(AlignmentAssumption, alignment_assumption, 0) \
138 SANITIZER_CHECK(VLABoundNotPositive, vla_bound_not_positive, 0)
139
141#define SANITIZER_CHECK(Enum, Name, Version) Enum,
143#undef SANITIZER_CHECK
145
146/// Helper class with most of the code for saving a value for a
147/// conditional expression cleanup.
149 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
150
151 /// Answer whether the given value needs extra work to be saved.
152 static bool needsSaving(llvm::Value *value) {
153 // If it's not an instruction, we don't need to save.
154 if (!isa<llvm::Instruction>(value)) return false;
155
156 // If it's an instruction in the entry block, we don't need to save.
157 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
158 return (block != &block->getParent()->getEntryBlock());
159 }
160
161 static saved_type save(CodeGenFunction &CGF, llvm::Value *value);
162 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value);
163};
164
165/// A partial specialization of DominatingValue for llvm::Values that
166/// might be llvm::Instructions.
167template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
168 typedef T *type;
170 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
171 }
172};
173
174/// A specialization of DominatingValue for Address.
175template <> struct DominatingValue<Address> {
176 typedef Address type;
177
178 struct saved_type {
180 llvm::Type *ElementType;
182 };
183
184 static bool needsSaving(type value) {
186 }
187 static saved_type save(CodeGenFunction &CGF, type value) {
188 return { DominatingLLVMValue::save(CGF, value.getPointer()),
189 value.getElementType(), value.getAlignment() };
190 }
192 return Address(DominatingLLVMValue::restore(CGF, value.SavedValue),
193 value.ElementType, value.Alignment);
194 }
195};
196
197/// A specialization of DominatingValue for RValue.
198template <> struct DominatingValue<RValue> {
199 typedef RValue type;
201 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
202 AggregateAddress, ComplexAddress };
203
204 llvm::Value *Value;
205 llvm::Type *ElementType;
206 unsigned K : 3;
207 unsigned Align : 29;
208 saved_type(llvm::Value *v, llvm::Type *e, Kind k, unsigned a = 0)
209 : Value(v), ElementType(e), K(k), Align(a) {}
210
211 public:
212 static bool needsSaving(RValue value);
215
216 // implementations in CGCleanup.cpp
217 };
218
219 static bool needsSaving(type value) {
220 return saved_type::needsSaving(value);
221 }
222 static saved_type save(CodeGenFunction &CGF, type value) {
223 return saved_type::save(CGF, value);
224 }
226 return value.restore(CGF);
227 }
228};
229
230/// CodeGenFunction - This class organizes the per-function state that is used
231/// while generating LLVM code.
233 CodeGenFunction(const CodeGenFunction &) = delete;
234 void operator=(const CodeGenFunction &) = delete;
235
236 friend class CGCXXABI;
237public:
238 /// A jump destination is an abstract label, branching to which may
239 /// require a jump out through normal cleanups.
240 struct JumpDest {
241 JumpDest() : Block(nullptr), Index(0) {}
242 JumpDest(llvm::BasicBlock *Block, EHScopeStack::stable_iterator Depth,
243 unsigned Index)
244 : Block(Block), ScopeDepth(Depth), Index(Index) {}
245
246 bool isValid() const { return Block != nullptr; }
247 llvm::BasicBlock *getBlock() const { return Block; }
248 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
249 unsigned getDestIndex() const { return Index; }
250
251 // This should be used cautiously.
253 ScopeDepth = depth;
254 }
255
256 private:
257 llvm::BasicBlock *Block;
259 unsigned Index;
260 };
261
262 CodeGenModule &CGM; // Per-module state.
264
265 // For EH/SEH outlined funclets, this field points to parent's CGF
267
268 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
271
272 // Stores variables for which we can't generate correct lifetime markers
273 // because of jumps.
275
276 /// List of recently emitted OMPCanonicalLoops.
277 ///
278 /// Since OMPCanonicalLoops are nested inside other statements (in particular
279 /// CapturedStmt generated by OMPExecutableDirective and non-perfectly nested
280 /// loops), we cannot directly call OMPEmitOMPCanonicalLoop and receive its
281 /// llvm::CanonicalLoopInfo. Instead, we call EmitStmt and any
282 /// OMPEmitOMPCanonicalLoop called by it will add its CanonicalLoopInfo to
283 /// this stack when done. Entering a new loop requires clearing this list; it
284 /// either means we start parsing a new loop nest (in which case the previous
285 /// loop nest goes out of scope) or a second loop in the same level in which
286 /// case it would be ambiguous into which of the two (or more) loops the loop
287 /// nest would extend.
289
290 /// Number of nested loop to be consumed by the last surrounding
291 /// loop-associated directive.
293
294 // CodeGen lambda for loops and support for ordered clause
295 typedef llvm::function_ref<void(CodeGenFunction &, const OMPLoopDirective &,
296 JumpDest)>
298 typedef llvm::function_ref<void(CodeGenFunction &, SourceLocation,
299 const unsigned, const bool)>
301
302 // Codegen lambda for loop bounds in worksharing loop constructs
303 typedef llvm::function_ref<std::pair<LValue, LValue>(
306
307 // Codegen lambda for loop bounds in dispatch-based loop implementation
308 typedef llvm::function_ref<std::pair<llvm::Value *, llvm::Value *>(
310 Address UB)>
312
313 /// CGBuilder insert helper. This function is called after an
314 /// instruction is created using Builder.
315 void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
316 llvm::BasicBlock *BB,
317 llvm::BasicBlock::iterator InsertPt) const;
318
319 /// CurFuncDecl - Holds the Decl for the current outermost
320 /// non-closure context.
321 const Decl *CurFuncDecl = nullptr;
322 /// CurCodeDecl - This is the inner-most code context, which includes blocks.
323 const Decl *CurCodeDecl = nullptr;
324 const CGFunctionInfo *CurFnInfo = nullptr;
326 llvm::Function *CurFn = nullptr;
327
328 /// Save Parameter Decl for coroutine.
330
331 // Holds coroutine data if the current function is a coroutine. We use a
332 // wrapper to manage its lifetime, so that we don't have to define CGCoroData
333 // in this header.
334 struct CGCoroInfo {
335 std::unique_ptr<CGCoroData> Data;
336 bool InSuspendBlock = false;
337 CGCoroInfo();
338 ~CGCoroInfo();
339 };
341
342 bool isCoroutine() const {
343 return CurCoro.Data != nullptr;
344 }
345
346 bool inSuspendBlock() const {
348 }
349
350 /// CurGD - The GlobalDecl for the current function being compiled.
352
353 /// PrologueCleanupDepth - The cleanup depth enclosing all the
354 /// cleanups associated with the parameters.
356
357 /// ReturnBlock - Unified return block.
359
360 /// ReturnValue - The temporary alloca to hold the return
361 /// value. This is invalid iff the function has no return value.
363
364 /// ReturnValuePointer - The temporary alloca to hold a pointer to sret.
365 /// This is invalid if sret is not in use.
367
368 /// If a return statement is being visited, this holds the return statment's
369 /// result expression.
370 const Expr *RetExpr = nullptr;
371
372 /// Return true if a label was seen in the current scope.
374 if (CurLexicalScope)
375 return CurLexicalScope->hasLabels();
376 return !LabelMap.empty();
377 }
378
379 /// AllocaInsertPoint - This is an instruction in the entry block before which
380 /// we prefer to insert allocas.
381 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
382
383private:
384 /// PostAllocaInsertPt - This is a place in the prologue where code can be
385 /// inserted that will be dominated by all the static allocas. This helps
386 /// achieve two things:
387 /// 1. Contiguity of all static allocas (within the prologue) is maintained.
388 /// 2. All other prologue code (which are dominated by static allocas) do
389 /// appear in the source order immediately after all static allocas.
390 ///
391 /// PostAllocaInsertPt will be lazily created when it is *really* required.
392 llvm::AssertingVH<llvm::Instruction> PostAllocaInsertPt = nullptr;
393
394public:
395 /// Return PostAllocaInsertPt. If it is not yet created, then insert it
396 /// immediately after AllocaInsertPt.
397 llvm::Instruction *getPostAllocaInsertPoint() {
398 if (!PostAllocaInsertPt) {
399 assert(AllocaInsertPt &&
400 "Expected static alloca insertion point at function prologue");
401 assert(AllocaInsertPt->getParent()->isEntryBlock() &&
402 "EBB should be entry block of the current code gen function");
403 PostAllocaInsertPt = AllocaInsertPt->clone();
404 PostAllocaInsertPt->setName("postallocapt");
405 PostAllocaInsertPt->insertAfter(AllocaInsertPt);
406 }
407
408 return PostAllocaInsertPt;
409 }
410
411 /// API for captured statement code generation.
413 public:
415 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
418 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
419
421 S.getCapturedRecordDecl()->field_begin();
422 for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
423 E = S.capture_end();
424 I != E; ++I, ++Field) {
425 if (I->capturesThis())
426 CXXThisFieldDecl = *Field;
427 else if (I->capturesVariable())
428 CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
429 else if (I->capturesVariableByCopy())
430 CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
431 }
432 }
433
434 virtual ~CGCapturedStmtInfo();
435
436 CapturedRegionKind getKind() const { return Kind; }
437
438 virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
439 // Retrieve the value of the context parameter.
440 virtual llvm::Value *getContextValue() const { return ThisValue; }
441
442 /// Lookup the captured field decl for a variable.
443 virtual const FieldDecl *lookup(const VarDecl *VD) const {
444 return CaptureFields.lookup(VD->getCanonicalDecl());
445 }
446
447 bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
448 virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
449
450 static bool classof(const CGCapturedStmtInfo *) {
451 return true;
452 }
453
454 /// Emit the captured statement body.
455 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
457 CGF.EmitStmt(S);
458 }
459
460 /// Get the name of the capture helper.
461 virtual StringRef getHelperName() const { return "__captured_stmt"; }
462
463 /// Get the CaptureFields
464 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> getCaptureFields() {
465 return CaptureFields;
466 }
467
468 private:
469 /// The kind of captured statement being generated.
471
472 /// Keep the map between VarDecl and FieldDecl.
473 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
474
475 /// The base address of the captured record, passed in as the first
476 /// argument of the parallel region function.
477 llvm::Value *ThisValue;
478
479 /// Captured 'this' type.
480 FieldDecl *CXXThisFieldDecl;
481 };
483
484 /// RAII for correct setting/restoring of CapturedStmtInfo.
486 private:
487 CodeGenFunction &CGF;
488 CGCapturedStmtInfo *PrevCapturedStmtInfo;
489 public:
491 CGCapturedStmtInfo *NewCapturedStmtInfo)
492 : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
493 CGF.CapturedStmtInfo = NewCapturedStmtInfo;
494 }
495 ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
496 };
497
498 /// An abstract representation of regular/ObjC call/message targets.
500 /// The function declaration of the callee.
501 const Decl *CalleeDecl;
502
503 public:
504 AbstractCallee() : CalleeDecl(nullptr) {}
505 AbstractCallee(const FunctionDecl *FD) : CalleeDecl(FD) {}
506 AbstractCallee(const ObjCMethodDecl *OMD) : CalleeDecl(OMD) {}
507 bool hasFunctionDecl() const {
508 return isa_and_nonnull<FunctionDecl>(CalleeDecl);
509 }
510 const Decl *getDecl() const { return CalleeDecl; }
511 unsigned getNumParams() const {
512 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
513 return FD->getNumParams();
514 return cast<ObjCMethodDecl>(CalleeDecl)->param_size();
515 }
516 const ParmVarDecl *getParamDecl(unsigned I) const {
517 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
518 return FD->getParamDecl(I);
519 return *(cast<ObjCMethodDecl>(CalleeDecl)->param_begin() + I);
520 }
521 };
522
523 /// Sanitizers enabled for this function.
525
526 /// True if CodeGen currently emits code implementing sanitizer checks.
527 bool IsSanitizerScope = false;
528
529 /// RAII object to set/unset CodeGenFunction::IsSanitizerScope.
531 CodeGenFunction *CGF;
532 public:
535 };
536
537 /// In C++, whether we are code generating a thunk. This controls whether we
538 /// should emit cleanups.
539 bool CurFuncIsThunk = false;
540
541 /// In ARC, whether we should autorelease the return value.
542 bool AutoreleaseResult = false;
543
544 /// Whether we processed a Microsoft-style asm block during CodeGen. These can
545 /// potentially set the return value.
546 bool SawAsmBlock = false;
547
549
550 /// True if the current function is an outlined SEH helper. This can be a
551 /// finally block or filter expression.
553
554 /// True if CodeGen currently emits code inside presereved access index
555 /// region.
557
558 /// True if the current statement has nomerge attribute.
560
561 /// True if the current statement has noinline attribute.
563
564 /// True if the current statement has always_inline attribute.
566
567 // The CallExpr within the current statement that the musttail attribute
568 // applies to. nullptr if there is no 'musttail' on the current statement.
569 const CallExpr *MustTailCall = nullptr;
570
571 /// Returns true if a function must make progress, which means the
572 /// mustprogress attribute can be added.
574 if (CGM.getCodeGenOpts().getFiniteLoops() ==
576 return false;
577
578 // C++11 and later guarantees that a thread eventually will do one of the
579 // following (C++11 [intro.multithread]p24 and C++17 [intro.progress]p1):
580 // - terminate,
581 // - make a call to a library I/O function,
582 // - perform an access through a volatile glvalue, or
583 // - perform a synchronization operation or an atomic operation.
584 //
585 // Hence each function is 'mustprogress' in C++11 or later.
586 return getLangOpts().CPlusPlus11;
587 }
588
589 /// Returns true if a loop must make progress, which means the mustprogress
590 /// attribute can be added. \p HasConstantCond indicates whether the branch
591 /// condition is a known constant.
592 bool checkIfLoopMustProgress(bool HasConstantCond) {
593 if (CGM.getCodeGenOpts().getFiniteLoops() ==
595 return true;
596 if (CGM.getCodeGenOpts().getFiniteLoops() ==
598 return false;
599
600 // If the containing function must make progress, loops also must make
601 // progress (as in C++11 and later).
603 return true;
604
605 // Now apply rules for plain C (see 6.8.5.6 in C11).
606 // Loops with constant conditions do not have to make progress in any C
607 // version.
608 if (HasConstantCond)
609 return false;
610
611 // Loops with non-constant conditions must make progress in C11 and later.
612 return getLangOpts().C11;
613 }
614
616 llvm::Value *BlockPointer = nullptr;
617
618 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
620
621 /// A mapping from NRVO variables to the flags used to indicate
622 /// when the NRVO has been applied to this variable.
623 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
624
628
629 llvm::Instruction *CurrentFuncletPad = nullptr;
630
632 bool isRedundantBeforeReturn() override { return true; }
633
634 llvm::Value *Addr;
635 llvm::Value *Size;
636
637 public:
638 CallLifetimeEnd(Address addr, llvm::Value *size)
639 : Addr(addr.getPointer()), Size(size) {}
640
641 void Emit(CodeGenFunction &CGF, Flags flags) override {
642 CGF.EmitLifetimeEnd(Size, Addr);
643 }
644 };
645
646 /// Header for data within LifetimeExtendedCleanupStack.
648 /// The size of the following cleanup object.
649 unsigned Size;
650 /// The kind of cleanup to push: a value from the CleanupKind enumeration.
651 unsigned Kind : 31;
652 /// Whether this is a conditional cleanup.
653 unsigned IsConditional : 1;
654
655 size_t getSize() const { return Size; }
656 CleanupKind getKind() const { return (CleanupKind)Kind; }
657 bool isConditional() const { return IsConditional; }
658 };
659
660 /// i32s containing the indexes of the cleanup destinations.
662
664
665 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
666 llvm::BasicBlock *EHResumeBlock = nullptr;
667
668 /// The exception slot. All landing pads write the current exception pointer
669 /// into this alloca.
670 llvm::Value *ExceptionSlot = nullptr;
671
672 /// The selector slot. Under the MandatoryCleanup model, all landing pads
673 /// write the current selector value into this alloca.
674 llvm::AllocaInst *EHSelectorSlot = nullptr;
675
676 /// A stack of exception code slots. Entering an __except block pushes a slot
677 /// on the stack and leaving pops one. The __exception_code() intrinsic loads
678 /// a value from the top of the stack.
680
681 /// Value returned by __exception_info intrinsic.
682 llvm::Value *SEHInfo = nullptr;
683
684 /// Emits a landing pad for the current EH stack.
685 llvm::BasicBlock *EmitLandingPad();
686
687 llvm::BasicBlock *getInvokeDestImpl();
688
689 /// Parent loop-based directive for scan directive.
691 llvm::BasicBlock *OMPBeforeScanBlock = nullptr;
692 llvm::BasicBlock *OMPAfterScanBlock = nullptr;
693 llvm::BasicBlock *OMPScanExitBlock = nullptr;
694 llvm::BasicBlock *OMPScanDispatch = nullptr;
695 bool OMPFirstScanLoop = false;
696
697 /// Manages parent directive for scan directives.
699 CodeGenFunction &CGF;
700 const OMPExecutableDirective *ParentLoopDirectiveForScan;
701
702 public:
704 CodeGenFunction &CGF,
705 const OMPExecutableDirective &ParentLoopDirectiveForScan)
706 : CGF(CGF),
707 ParentLoopDirectiveForScan(CGF.OMPParentLoopDirectiveForScan) {
708 CGF.OMPParentLoopDirectiveForScan = &ParentLoopDirectiveForScan;
709 }
711 CGF.OMPParentLoopDirectiveForScan = ParentLoopDirectiveForScan;
712 }
713 };
714
715 template <class T>
717 return DominatingValue<T>::save(*this, value);
718 }
719
721 public:
722 CGFPOptionsRAII(CodeGenFunction &CGF, FPOptions FPFeatures);
723 CGFPOptionsRAII(CodeGenFunction &CGF, const Expr *E);
725
726 private:
727 void ConstructorHelper(FPOptions FPFeatures);
728 CodeGenFunction &CGF;
729 FPOptions OldFPFeatures;
730 llvm::fp::ExceptionBehavior OldExcept;
731 llvm::RoundingMode OldRounding;
732 std::optional<CGBuilderTy::FastMathFlagGuard> FMFGuard;
733 };
735
736public:
737 /// ObjCEHValueStack - Stack of Objective-C exception values, used for
738 /// rethrows.
740
741 /// A class controlling the emission of a finally block.
743 /// Where the catchall's edge through the cleanup should go.
744 JumpDest RethrowDest;
745
746 /// A function to call to enter the catch.
747 llvm::FunctionCallee BeginCatchFn;
748
749 /// An i1 variable indicating whether or not the @finally is
750 /// running for an exception.
751 llvm::AllocaInst *ForEHVar = nullptr;
752
753 /// An i8* variable into which the exception pointer to rethrow
754 /// has been saved.
755 llvm::AllocaInst *SavedExnVar = nullptr;
756
757 public:
758 void enter(CodeGenFunction &CGF, const Stmt *Finally,
759 llvm::FunctionCallee beginCatchFn,
760 llvm::FunctionCallee endCatchFn, llvm::FunctionCallee rethrowFn);
761 void exit(CodeGenFunction &CGF);
762 };
763
764 /// Returns true inside SEH __try blocks.
765 bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
766
767 /// Returns true while emitting a cleanuppad.
768 bool isCleanupPadScope() const {
769 return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad);
770 }
771
772 /// pushFullExprCleanup - Push a cleanup to be run at the end of the
773 /// current full-expression. Safe against the possibility that
774 /// we're currently inside a conditionally-evaluated expression.
775 template <class T, class... As>
776 void pushFullExprCleanup(CleanupKind kind, As... A) {
777 // If we're not in a conditional branch, or if none of the
778 // arguments requires saving, then use the unconditional cleanup.
780 return EHStack.pushCleanup<T>(kind, A...);
781
782 // Stash values in a tuple so we can guarantee the order of saves.
783 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
784 SavedTuple Saved{saveValueInCond(A)...};
785
786 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
787 EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
789 }
790
791 /// Queue a cleanup to be pushed after finishing the current full-expression,
792 /// potentially with an active flag.
793 template <class T, class... As>
796 return pushCleanupAfterFullExprWithActiveFlag<T>(Kind, Address::invalid(),
797 A...);
798
799 Address ActiveFlag = createCleanupActiveFlag();
800 assert(!DominatingValue<Address>::needsSaving(ActiveFlag) &&
801 "cleanup active flag should never need saving");
802
803 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
804 SavedTuple Saved{saveValueInCond(A)...};
805
806 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
807 pushCleanupAfterFullExprWithActiveFlag<CleanupType>(Kind, ActiveFlag, Saved);
808 }
809
810 template <class T, class... As>
812 Address ActiveFlag, As... A) {
813 LifetimeExtendedCleanupHeader Header = {sizeof(T), Kind,
814 ActiveFlag.isValid()};
815
816 size_t OldSize = LifetimeExtendedCleanupStack.size();
818 LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size +
819 (Header.IsConditional ? sizeof(ActiveFlag) : 0));
820
821 static_assert(sizeof(Header) % alignof(T) == 0,
822 "Cleanup will be allocated on misaligned address");
823 char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
824 new (Buffer) LifetimeExtendedCleanupHeader(Header);
825 new (Buffer + sizeof(Header)) T(A...);
826 if (Header.IsConditional)
827 new (Buffer + sizeof(Header) + sizeof(T)) Address(ActiveFlag);
828 }
829
830 /// Set up the last cleanup that was pushed as a conditional
831 /// full-expression cleanup.
834 }
835
838
839 /// PushDestructorCleanup - Push a cleanup to call the
840 /// complete-object destructor of an object of the given type at the
841 /// given address. Does nothing if T is not a C++ class type with a
842 /// non-trivial destructor.
844
845 /// PushDestructorCleanup - Push a cleanup to call the
846 /// complete-object variant of the given destructor on the object at
847 /// the given address.
849 Address Addr);
850
851 /// PopCleanupBlock - Will pop the cleanup entry on the stack and
852 /// process all branch fixups.
853 void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
854
855 /// DeactivateCleanupBlock - Deactivates the given cleanup block.
856 /// The block cannot be reactivated. Pops it if it's the top of the
857 /// stack.
858 ///
859 /// \param DominatingIP - An instruction which is known to
860 /// dominate the current IP (if set) and which lies along
861 /// all paths of execution between the current IP and the
862 /// the point at which the cleanup comes into scope.
864 llvm::Instruction *DominatingIP);
865
866 /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
867 /// Cannot be used to resurrect a deactivated cleanup.
868 ///
869 /// \param DominatingIP - An instruction which is known to
870 /// dominate the current IP (if set) and which lies along
871 /// all paths of execution between the current IP and the
872 /// the point at which the cleanup comes into scope.
874 llvm::Instruction *DominatingIP);
875
876 /// Enters a new scope for capturing cleanups, all of which
877 /// will be executed once the scope is exited.
879 EHScopeStack::stable_iterator CleanupStackDepth, OldCleanupScopeDepth;
880 size_t LifetimeExtendedCleanupStackSize;
881 bool OldDidCallStackSave;
882 protected:
884 private:
885
886 RunCleanupsScope(const RunCleanupsScope &) = delete;
887 void operator=(const RunCleanupsScope &) = delete;
888
889 protected:
891
892 public:
893 /// Enter a new cleanup scope.
896 {
897 CleanupStackDepth = CGF.EHStack.stable_begin();
898 LifetimeExtendedCleanupStackSize =
900 OldDidCallStackSave = CGF.DidCallStackSave;
901 CGF.DidCallStackSave = false;
902 OldCleanupScopeDepth = CGF.CurrentCleanupScopeDepth;
903 CGF.CurrentCleanupScopeDepth = CleanupStackDepth;
904 }
905
906 /// Exit this cleanup scope, emitting any accumulated cleanups.
908 if (PerformCleanup)
909 ForceCleanup();
910 }
911
912 /// Determine whether this scope requires any cleanups.
913 bool requiresCleanups() const {
914 return CGF.EHStack.stable_begin() != CleanupStackDepth;
915 }
916
917 /// Force the emission of cleanups now, instead of waiting
918 /// until this object is destroyed.
919 /// \param ValuesToReload - A list of values that need to be available at
920 /// the insertion point after cleanup emission. If cleanup emission created
921 /// a shared cleanup block, these value pointers will be rewritten.
922 /// Otherwise, they not will be modified.
923 void ForceCleanup(std::initializer_list<llvm::Value**> ValuesToReload = {}) {
924 assert(PerformCleanup && "Already forced cleanup");
925 CGF.DidCallStackSave = OldDidCallStackSave;
926 CGF.PopCleanupBlocks(CleanupStackDepth, LifetimeExtendedCleanupStackSize,
927 ValuesToReload);
928 PerformCleanup = false;
929 CGF.CurrentCleanupScopeDepth = OldCleanupScopeDepth;
930 }
931 };
932
933 // Cleanup stack depth of the RunCleanupsScope that was pushed most recently.
936
938 SourceRange Range;
940 LexicalScope *ParentScope;
941
942 LexicalScope(const LexicalScope &) = delete;
943 void operator=(const LexicalScope &) = delete;
944
945 public:
946 /// Enter a new cleanup scope.
948 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
949 CGF.CurLexicalScope = this;
950 if (CGDebugInfo *DI = CGF.getDebugInfo())
951 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
952 }
953
954 void addLabel(const LabelDecl *label) {
955 assert(PerformCleanup && "adding label to dead scope?");
956 Labels.push_back(label);
957 }
958
959 /// Exit this cleanup scope, emitting any accumulated
960 /// cleanups.
962 if (CGDebugInfo *DI = CGF.getDebugInfo())
963 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
964
965 // If we should perform a cleanup, force them now. Note that
966 // this ends the cleanup scope before rescoping any labels.
967 if (PerformCleanup) {
968 ApplyDebugLocation DL(CGF, Range.getEnd());
969 ForceCleanup();
970 }
971 }
972
973 /// Force the emission of cleanups now, instead of waiting
974 /// until this object is destroyed.
976 CGF.CurLexicalScope = ParentScope;
978
979 if (!Labels.empty())
981 }
982
983 bool hasLabels() const {
984 return !Labels.empty();
985 }
986
987 void rescopeLabels();
988 };
989
990 typedef llvm::DenseMap<const Decl *, Address> DeclMapTy;
991
992 /// The class used to assign some variables some temporarily addresses.
994 DeclMapTy SavedLocals;
995 DeclMapTy SavedTempAddresses;
996 OMPMapVars(const OMPMapVars &) = delete;
997 void operator=(const OMPMapVars &) = delete;
998
999 public:
1000 explicit OMPMapVars() = default;
1002 assert(SavedLocals.empty() && "Did not restored original addresses.");
1003 };
1004
1005 /// Sets the address of the variable \p LocalVD to be \p TempAddr in
1006 /// function \p CGF.
1007 /// \return true if at least one variable was set already, false otherwise.
1008 bool setVarAddr(CodeGenFunction &CGF, const VarDecl *LocalVD,
1009 Address TempAddr) {
1010 LocalVD = LocalVD->getCanonicalDecl();
1011 // Only save it once.
1012 if (SavedLocals.count(LocalVD)) return false;
1013
1014 // Copy the existing local entry to SavedLocals.
1015 auto it = CGF.LocalDeclMap.find(LocalVD);
1016 if (it != CGF.LocalDeclMap.end())
1017 SavedLocals.try_emplace(LocalVD, it->second);
1018 else
1019 SavedLocals.try_emplace(LocalVD, Address::invalid());
1020
1021 // Generate the private entry.
1022 QualType VarTy = LocalVD->getType();
1023 if (VarTy->isReferenceType()) {
1024 Address Temp = CGF.CreateMemTemp(VarTy);
1025 CGF.Builder.CreateStore(TempAddr.getPointer(), Temp);
1026 TempAddr = Temp;
1027 }
1028 SavedTempAddresses.try_emplace(LocalVD, TempAddr);
1029
1030 return true;
1031 }
1032
1033 /// Applies new addresses to the list of the variables.
1034 /// \return true if at least one variable is using new address, false
1035 /// otherwise.
1037 copyInto(SavedTempAddresses, CGF.LocalDeclMap);
1038 SavedTempAddresses.clear();
1039 return !SavedLocals.empty();
1040 }
1041
1042 /// Restores original addresses of the variables.
1044 if (!SavedLocals.empty()) {
1045 copyInto(SavedLocals, CGF.LocalDeclMap);
1046 SavedLocals.clear();
1047 }
1048 }
1049
1050 private:
1051 /// Copy all the entries in the source map over the corresponding
1052 /// entries in the destination, which must exist.
1053 static void copyInto(const DeclMapTy &Src, DeclMapTy &Dest) {
1054 for (auto &Pair : Src) {
1055 if (!Pair.second.isValid()) {
1056 Dest.erase(Pair.first);
1057 continue;
1058 }
1059
1060 auto I = Dest.find(Pair.first);
1061 if (I != Dest.end())
1062 I->second = Pair.second;
1063 else
1064 Dest.insert(Pair);
1065 }
1066 }
1067 };
1068
1069 /// The scope used to remap some variables as private in the OpenMP loop body
1070 /// (or other captured region emitted without outlining), and to restore old
1071 /// vars back on exit.
1073 OMPMapVars MappedVars;
1074 OMPPrivateScope(const OMPPrivateScope &) = delete;
1075 void operator=(const OMPPrivateScope &) = delete;
1076
1077 public:
1078 /// Enter a new OpenMP private scope.
1080
1081 /// Registers \p LocalVD variable as a private with \p Addr as the address
1082 /// of the corresponding private variable. \p
1083 /// PrivateGen is the address of the generated private variable.
1084 /// \return true if the variable is registered as private, false if it has
1085 /// been privatized already.
1086 bool addPrivate(const VarDecl *LocalVD, Address Addr) {
1087 assert(PerformCleanup && "adding private to dead scope");
1088 return MappedVars.setVarAddr(CGF, LocalVD, Addr);
1089 }
1090
1091 /// Privatizes local variables previously registered as private.
1092 /// Registration is separate from the actual privatization to allow
1093 /// initializers use values of the original variables, not the private one.
1094 /// This is important, for example, if the private variable is a class
1095 /// variable initialized by a constructor that references other private
1096 /// variables. But at initialization original variables must be used, not
1097 /// private copies.
1098 /// \return true if at least one variable was privatized, false otherwise.
1099 bool Privatize() { return MappedVars.apply(CGF); }
1100
1103 restoreMap();
1104 }
1105
1106 /// Exit scope - all the mapped variables are restored.
1108 if (PerformCleanup)
1109 ForceCleanup();
1110 }
1111
1112 /// Checks if the global variable is captured in current function.
1113 bool isGlobalVarCaptured(const VarDecl *VD) const {
1114 VD = VD->getCanonicalDecl();
1115 return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0;
1116 }
1117
1118 /// Restore all mapped variables w/o clean up. This is usefully when we want
1119 /// to reference the original variables but don't want the clean up because
1120 /// that could emit lifetime end too early, causing backend issue #56913.
1121 void restoreMap() { MappedVars.restore(CGF); }
1122 };
1123
1124 /// Save/restore original map of previously emitted local vars in case when we
1125 /// need to duplicate emission of the same code several times in the same
1126 /// function for OpenMP code.
1128 CodeGenFunction &CGF;
1129 DeclMapTy SavedMap;
1130
1131 public:
1133 : CGF(CGF), SavedMap(CGF.LocalDeclMap) {}
1134 ~OMPLocalDeclMapRAII() { SavedMap.swap(CGF.LocalDeclMap); }
1135 };
1136
1137 /// Takes the old cleanup stack size and emits the cleanup blocks
1138 /// that have been added.
1139 void
1141 std::initializer_list<llvm::Value **> ValuesToReload = {});
1142
1143 /// Takes the old cleanup stack size and emits the cleanup blocks
1144 /// that have been added, then adds all lifetime-extended cleanups from
1145 /// the given position to the stack.
1146 void
1148 size_t OldLifetimeExtendedStackSize,
1149 std::initializer_list<llvm::Value **> ValuesToReload = {});
1150
1151 void ResolveBranchFixups(llvm::BasicBlock *Target);
1152
1153 /// The given basic block lies in the current EH scope, but may be a
1154 /// target of a potentially scope-crossing jump; get a stable handle
1155 /// to which we can perform this jump later.
1157 return JumpDest(Target,
1160 }
1161
1162 /// The given basic block lies in the current EH scope, but may be a
1163 /// target of a potentially scope-crossing jump; get a stable handle
1164 /// to which we can perform this jump later.
1165 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
1167 }
1168
1169 /// EmitBranchThroughCleanup - Emit a branch from the current insert
1170 /// block through the normal cleanup handling code (if any) and then
1171 /// on to \arg Dest.
1173
1174 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
1175 /// specified destination obviously has no cleanups to run. 'false' is always
1176 /// a conservatively correct answer for this method.
1178
1179 /// popCatchScope - Pops the catch scope at the top of the EHScope
1180 /// stack, emitting any required code (other than the catch handlers
1181 /// themselves).
1183
1184 llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
1186 llvm::BasicBlock *
1188
1189 /// An object to manage conditionally-evaluated expressions.
1191 llvm::BasicBlock *StartBB;
1192
1193 public:
1195 : StartBB(CGF.Builder.GetInsertBlock()) {}
1196
1198 assert(CGF.OutermostConditional != this);
1199 if (!CGF.OutermostConditional)
1200 CGF.OutermostConditional = this;
1201 }
1202
1204 assert(CGF.OutermostConditional != nullptr);
1205 if (CGF.OutermostConditional == this)
1206 CGF.OutermostConditional = nullptr;
1207 }
1208
1209 /// Returns a block which will be executed prior to each
1210 /// evaluation of the conditional code.
1211 llvm::BasicBlock *getStartingBlock() const {
1212 return StartBB;
1213 }
1214 };
1215
1216 /// isInConditionalBranch - Return true if we're currently emitting
1217 /// one branch or the other of a conditional expression.
1218 bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
1219
1220 void setBeforeOutermostConditional(llvm::Value *value, Address addr) {
1221 assert(isInConditionalBranch());
1222 llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
1223 auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back());
1224 store->setAlignment(addr.getAlignment().getAsAlign());
1225 }
1226
1227 /// An RAII object to record that we're evaluating a statement
1228 /// expression.
1230 CodeGenFunction &CGF;
1231
1232 /// We have to save the outermost conditional: cleanups in a
1233 /// statement expression aren't conditional just because the
1234 /// StmtExpr is.
1235 ConditionalEvaluation *SavedOutermostConditional;
1236
1237 public:
1239 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
1240 CGF.OutermostConditional = nullptr;
1241 }
1242
1244 CGF.OutermostConditional = SavedOutermostConditional;
1245 CGF.EnsureInsertPoint();
1246 }
1247 };
1248
1249 /// An object which temporarily prevents a value from being
1250 /// destroyed by aggressive peephole optimizations that assume that
1251 /// all uses of a value have been realized in the IR.
1253 llvm::Instruction *Inst = nullptr;
1254 friend class CodeGenFunction;
1255
1256 public:
1258 };
1259
1260 /// A non-RAII class containing all the information about a bound
1261 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
1262 /// this which makes individual mappings very simple; using this
1263 /// class directly is useful when you have a variable number of
1264 /// opaque values or don't want the RAII functionality for some
1265 /// reason.
1267 const OpaqueValueExpr *OpaqueValue;
1268 bool BoundLValue;
1270
1272 bool boundLValue)
1273 : OpaqueValue(ov), BoundLValue(boundLValue) {}
1274 public:
1275 OpaqueValueMappingData() : OpaqueValue(nullptr) {}
1276
1277 static bool shouldBindAsLValue(const Expr *expr) {
1278 // gl-values should be bound as l-values for obvious reasons.
1279 // Records should be bound as l-values because IR generation
1280 // always keeps them in memory. Expressions of function type
1281 // act exactly like l-values but are formally required to be
1282 // r-values in C.
1283 return expr->isGLValue() ||
1284 expr->getType()->isFunctionType() ||
1285 hasAggregateEvaluationKind(expr->getType());
1286 }
1287
1289 const OpaqueValueExpr *ov,
1290 const Expr *e) {
1291 if (shouldBindAsLValue(ov))
1292 return bind(CGF, ov, CGF.EmitLValue(e));
1293 return bind(CGF, ov, CGF.EmitAnyExpr(e));
1294 }
1295
1297 const OpaqueValueExpr *ov,
1298 const LValue &lv) {
1299 assert(shouldBindAsLValue(ov));
1300 CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
1301 return OpaqueValueMappingData(ov, true);
1302 }
1303
1305 const OpaqueValueExpr *ov,
1306 const RValue &rv) {
1307 assert(!shouldBindAsLValue(ov));
1308 CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
1309
1310 OpaqueValueMappingData data(ov, false);
1311
1312 // Work around an extremely aggressive peephole optimization in
1313 // EmitScalarConversion which assumes that all other uses of a
1314 // value are extant.
1315 data.Protection = CGF.protectFromPeepholes(rv);
1316
1317 return data;
1318 }
1319
1320 bool isValid() const { return OpaqueValue != nullptr; }
1321 void clear() { OpaqueValue = nullptr; }
1322
1324 assert(OpaqueValue && "no data to unbind!");
1325
1326 if (BoundLValue) {
1327 CGF.OpaqueLValues.erase(OpaqueValue);
1328 } else {
1329 CGF.OpaqueRValues.erase(OpaqueValue);
1330 CGF.unprotectFromPeepholes(Protection);
1331 }
1332 }
1333 };
1334
1335 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
1337 CodeGenFunction &CGF;
1339
1340 public:
1341 static bool shouldBindAsLValue(const Expr *expr) {
1343 }
1344
1345 /// Build the opaque value mapping for the given conditional
1346 /// operator if it's the GNU ?: extension. This is a common
1347 /// enough pattern that the convenience operator is really
1348 /// helpful.
1349 ///
1351 const AbstractConditionalOperator *op) : CGF(CGF) {
1352 if (isa<ConditionalOperator>(op))
1353 // Leave Data empty.
1354 return;
1355
1356 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
1358 e->getCommon());
1359 }
1360
1361 /// Build the opaque value mapping for an OpaqueValueExpr whose source
1362 /// expression is set to the expression the OVE represents.
1364 : CGF(CGF) {
1365 if (OV) {
1366 assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "
1367 "for OVE with no source expression");
1369 }
1370 }
1371
1373 const OpaqueValueExpr *opaqueValue,
1374 LValue lvalue)
1375 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
1376 }
1377
1379 const OpaqueValueExpr *opaqueValue,
1380 RValue rvalue)
1381 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
1382 }
1383
1384 void pop() {
1385 Data.unbind(CGF);
1386 Data.clear();
1387 }
1388
1390 if (Data.isValid()) Data.unbind(CGF);
1391 }
1392 };
1393
1394private:
1395 CGDebugInfo *DebugInfo;
1396 /// Used to create unique names for artificial VLA size debug info variables.
1397 unsigned VLAExprCounter = 0;
1398 bool DisableDebugInfo = false;
1399
1400 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
1401 /// calling llvm.stacksave for multiple VLAs in the same scope.
1402 bool DidCallStackSave = false;
1403
1404 /// IndirectBranch - The first time an indirect goto is seen we create a block
1405 /// with an indirect branch. Every time we see the address of a label taken,
1406 /// we add the label to the indirect goto. Every subsequent indirect goto is
1407 /// codegen'd as a jump to the IndirectBranch's basic block.
1408 llvm::IndirectBrInst *IndirectBranch = nullptr;
1409
1410 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
1411 /// decls.
1412 DeclMapTy LocalDeclMap;
1413
1414 // Keep track of the cleanups for callee-destructed parameters pushed to the
1415 // cleanup stack so that they can be deactivated later.
1416 llvm::DenseMap<const ParmVarDecl *, EHScopeStack::stable_iterator>
1417 CalleeDestructedParamCleanups;
1418
1419 /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this
1420 /// will contain a mapping from said ParmVarDecl to its implicit "object_size"
1421 /// parameter.
1422 llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2>
1423 SizeArguments;
1424
1425 /// Track escaped local variables with auto storage. Used during SEH
1426 /// outlining to produce a call to llvm.localescape.
1427 llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
1428
1429 /// LabelMap - This keeps track of the LLVM basic block for each C label.
1430 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
1431
1432 // BreakContinueStack - This keeps track of where break and continue
1433 // statements should jump to.
1434 struct BreakContinue {
1435 BreakContinue(JumpDest Break, JumpDest Continue)
1436 : BreakBlock(Break), ContinueBlock(Continue) {}
1437
1438 JumpDest BreakBlock;
1439 JumpDest ContinueBlock;
1440 };
1441 SmallVector<BreakContinue, 8> BreakContinueStack;
1442
1443 /// Handles cancellation exit points in OpenMP-related constructs.
1444 class OpenMPCancelExitStack {
1445 /// Tracks cancellation exit point and join point for cancel-related exit
1446 /// and normal exit.
1447 struct CancelExit {
1448 CancelExit() = default;
1449 CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock,
1450 JumpDest ContBlock)
1451 : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {}
1452 OpenMPDirectiveKind Kind = llvm::omp::OMPD_unknown;
1453 /// true if the exit block has been emitted already by the special
1454 /// emitExit() call, false if the default codegen is used.
1455 bool HasBeenEmitted = false;
1456 JumpDest ExitBlock;
1457 JumpDest ContBlock;
1458 };
1459
1460 SmallVector<CancelExit, 8> Stack;
1461
1462 public:
1463 OpenMPCancelExitStack() : Stack(1) {}
1464 ~OpenMPCancelExitStack() = default;
1465 /// Fetches the exit block for the current OpenMP construct.
1466 JumpDest getExitBlock() const { return Stack.back().ExitBlock; }
1467 /// Emits exit block with special codegen procedure specific for the related
1468 /// OpenMP construct + emits code for normal construct cleanup.
1469 void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1470 const llvm::function_ref<void(CodeGenFunction &)> CodeGen) {
1471 if (Stack.back().Kind == Kind && getExitBlock().isValid()) {
1472 assert(CGF.getOMPCancelDestination(Kind).isValid());
1473 assert(CGF.HaveInsertPoint());
1474 assert(!Stack.back().HasBeenEmitted);
1475 auto IP = CGF.Builder.saveAndClearIP();
1476 CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1477 CodeGen(CGF);
1478 CGF.EmitBranch(Stack.back().ContBlock.getBlock());
1479 CGF.Builder.restoreIP(IP);
1480 Stack.back().HasBeenEmitted = true;
1481 }
1482 CodeGen(CGF);
1483 }
1484 /// Enter the cancel supporting \a Kind construct.
1485 /// \param Kind OpenMP directive that supports cancel constructs.
1486 /// \param HasCancel true, if the construct has inner cancel directive,
1487 /// false otherwise.
1488 void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) {
1489 Stack.push_back({Kind,
1490 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit")
1491 : JumpDest(),
1492 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont")
1493 : JumpDest()});
1494 }
1495 /// Emits default exit point for the cancel construct (if the special one
1496 /// has not be used) + join point for cancel/normal exits.
1497 void exit(CodeGenFunction &CGF) {
1498 if (getExitBlock().isValid()) {
1499 assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid());
1500 bool HaveIP = CGF.HaveInsertPoint();
1501 if (!Stack.back().HasBeenEmitted) {
1502 if (HaveIP)
1503 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1504 CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1505 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1506 }
1507 CGF.EmitBlock(Stack.back().ContBlock.getBlock());
1508 if (!HaveIP) {
1509 CGF.Builder.CreateUnreachable();
1510 CGF.Builder.ClearInsertionPoint();
1511 }
1512 }
1513 Stack.pop_back();
1514 }
1515 };
1516 OpenMPCancelExitStack OMPCancelStack;
1517
1518 /// Lower the Likelihood knowledge about the \p Cond via llvm.expect intrin.
1519 llvm::Value *emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
1520 Stmt::Likelihood LH);
1521
1522 CodeGenPGO PGO;
1523
1524 /// Calculate branch weights appropriate for PGO data
1525 llvm::MDNode *createProfileWeights(uint64_t TrueCount,
1526 uint64_t FalseCount) const;
1527 llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights) const;
1528 llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
1529 uint64_t LoopCount) const;
1530
1531public:
1532 /// Increment the profiler's counter for the given statement by \p StepV.
1533 /// If \p StepV is null, the default increment is 1.
1534 void incrementProfileCounter(const Stmt *S, llvm::Value *StepV = nullptr) {
1536 !CurFn->hasFnAttribute(llvm::Attribute::NoProfile) &&
1537 !CurFn->hasFnAttribute(llvm::Attribute::SkipProfile))
1538 PGO.emitCounterIncrement(Builder, S, StepV);
1539 PGO.setCurrentStmt(S);
1540 }
1541
1542 /// Get the profiler's count for the given statement.
1543 uint64_t getProfileCount(const Stmt *S) {
1544 return PGO.getStmtCount(S).value_or(0);
1545 }
1546
1547 /// Set the profiler's current count.
1548 void setCurrentProfileCount(uint64_t Count) {
1549 PGO.setCurrentRegionCount(Count);
1550 }
1551
1552 /// Get the profiler's current count. This is generally the count for the most
1553 /// recently incremented counter.
1555 return PGO.getCurrentRegionCount();
1556 }
1557
1558private:
1559
1560 /// SwitchInsn - This is nearest current switch instruction. It is null if
1561 /// current context is not in a switch.
1562 llvm::SwitchInst *SwitchInsn = nullptr;
1563 /// The branch weights of SwitchInsn when doing instrumentation based PGO.
1564 SmallVector<uint64_t, 16> *SwitchWeights = nullptr;
1565
1566 /// The likelihood attributes of the SwitchCase.
1567 SmallVector<Stmt::Likelihood, 16> *SwitchLikelihood = nullptr;
1568
1569 /// CaseRangeBlock - This block holds if condition check for last case
1570 /// statement range in current switch instruction.
1571 llvm::BasicBlock *CaseRangeBlock = nullptr;
1572
1573 /// OpaqueLValues - Keeps track of the current set of opaque value
1574 /// expressions.
1575 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
1576 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
1577
1578 // VLASizeMap - This keeps track of the associated size for each VLA type.
1579 // We track this by the size expression rather than the type itself because
1580 // in certain situations, like a const qualifier applied to an VLA typedef,
1581 // multiple VLA types can share the same size expression.
1582 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
1583 // enter/leave scopes.
1584 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
1585
1586 /// A block containing a single 'unreachable' instruction. Created
1587 /// lazily by getUnreachableBlock().
1588 llvm::BasicBlock *UnreachableBlock = nullptr;
1589
1590 /// Counts of the number return expressions in the function.
1591 unsigned NumReturnExprs = 0;
1592
1593 /// Count the number of simple (constant) return expressions in the function.
1594 unsigned NumSimpleReturnExprs = 0;
1595
1596 /// The last regular (non-return) debug location (breakpoint) in the function.
1597 SourceLocation LastStopPoint;
1598
1599public:
1600 /// Source location information about the default argument or member
1601 /// initializer expression we're evaluating, if any.
1605
1606 /// A scope within which we are constructing the fields of an object which
1607 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
1608 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
1610 public:
1612 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
1613 CGF.CXXDefaultInitExprThis = This;
1614 }
1616 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
1617 }
1618
1619 private:
1620 CodeGenFunction &CGF;
1621 Address OldCXXDefaultInitExprThis;
1622 };
1623
1624 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
1625 /// is overridden to be the object under construction.
1627 public:
1629 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
1630 OldCXXThisAlignment(CGF.CXXThisAlignment),
1632 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer();
1633 CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
1634 }
1636 CGF.CXXThisValue = OldCXXThisValue;
1637 CGF.CXXThisAlignment = OldCXXThisAlignment;
1638 }
1639
1640 public:
1642 llvm::Value *OldCXXThisValue;
1645 };
1646
1650 };
1651
1652 /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the
1653 /// current loop index is overridden.
1655 public:
1656 ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index)
1657 : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) {
1658 CGF.ArrayInitIndex = Index;
1659 }
1661 CGF.ArrayInitIndex = OldArrayInitIndex;
1662 }
1663
1664 private:
1665 CodeGenFunction &CGF;
1666 llvm::Value *OldArrayInitIndex;
1667 };
1668
1670 public:
1672 : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl),
1673 OldCurCodeDecl(CGF.CurCodeDecl),
1674 OldCXXABIThisDecl(CGF.CXXABIThisDecl),
1675 OldCXXABIThisValue(CGF.CXXABIThisValue),
1676 OldCXXThisValue(CGF.CXXThisValue),
1677 OldCXXABIThisAlignment(CGF.CXXABIThisAlignment),
1678 OldCXXThisAlignment(CGF.CXXThisAlignment),
1679 OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy),
1680 OldCXXInheritedCtorInitExprArgs(
1681 std::move(CGF.CXXInheritedCtorInitExprArgs)) {
1682 CGF.CurGD = GD;
1683 CGF.CurFuncDecl = CGF.CurCodeDecl =
1684 cast<CXXConstructorDecl>(GD.getDecl());
1685 CGF.CXXABIThisDecl = nullptr;
1686 CGF.CXXABIThisValue = nullptr;
1687 CGF.CXXThisValue = nullptr;
1688 CGF.CXXABIThisAlignment = CharUnits();
1689 CGF.CXXThisAlignment = CharUnits();
1691 CGF.FnRetTy = QualType();
1692 CGF.CXXInheritedCtorInitExprArgs.clear();
1693 }
1695 CGF.CurGD = OldCurGD;
1696 CGF.CurFuncDecl = OldCurFuncDecl;
1697 CGF.CurCodeDecl = OldCurCodeDecl;
1698 CGF.CXXABIThisDecl = OldCXXABIThisDecl;
1699 CGF.CXXABIThisValue = OldCXXABIThisValue;
1700 CGF.CXXThisValue = OldCXXThisValue;
1701 CGF.CXXABIThisAlignment = OldCXXABIThisAlignment;
1702 CGF.CXXThisAlignment = OldCXXThisAlignment;
1703 CGF.ReturnValue = OldReturnValue;
1704 CGF.FnRetTy = OldFnRetTy;
1705 CGF.CXXInheritedCtorInitExprArgs =
1706 std::move(OldCXXInheritedCtorInitExprArgs);
1707 }
1708
1709 private:
1710 CodeGenFunction &CGF;
1711 GlobalDecl OldCurGD;
1712 const Decl *OldCurFuncDecl;
1713 const Decl *OldCurCodeDecl;
1714 ImplicitParamDecl *OldCXXABIThisDecl;
1715 llvm::Value *OldCXXABIThisValue;
1716 llvm::Value *OldCXXThisValue;
1717 CharUnits OldCXXABIThisAlignment;
1718 CharUnits OldCXXThisAlignment;
1719 Address OldReturnValue;
1720 QualType OldFnRetTy;
1721 CallArgList OldCXXInheritedCtorInitExprArgs;
1722 };
1723
1724 // Helper class for the OpenMP IR Builder. Allows reusability of code used for
1725 // region body, and finalization codegen callbacks. This will class will also
1726 // contain privatization functions used by the privatization call backs
1727 //
1728 // TODO: this is temporary class for things that are being moved out of
1729 // CGOpenMPRuntime, new versions of current CodeGenFunction methods, or
1730 // utility function for use with the OMPBuilder. Once that move to use the
1731 // OMPBuilder is done, everything here will either become part of CodeGenFunc.
1732 // directly, or a new helper class that will contain functions used by both
1733 // this and the OMPBuilder
1734
1736
1740
1741 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
1742
1743 /// Cleanup action for allocate support.
1745
1746 private:
1747 llvm::CallInst *RTLFnCI;
1748
1749 public:
1750 OMPAllocateCleanupTy(llvm::CallInst *RLFnCI) : RTLFnCI(RLFnCI) {
1751 RLFnCI->removeFromParent();
1752 }
1753
1754 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
1755 if (!CGF.HaveInsertPoint())
1756 return;
1757 CGF.Builder.Insert(RTLFnCI);
1758 }
1759 };
1760
1761 /// Returns address of the threadprivate variable for the current
1762 /// thread. This Also create any necessary OMP runtime calls.
1763 ///
1764 /// \param VD VarDecl for Threadprivate variable.
1765 /// \param VDAddr Address of the Vardecl
1766 /// \param Loc The location where the barrier directive was encountered
1768 const VarDecl *VD, Address VDAddr,
1769 SourceLocation Loc);
1770
1771 /// Gets the OpenMP-specific address of the local variable /p VD.
1773 const VarDecl *VD);
1774 /// Get the platform-specific name separator.
1775 /// \param Parts different parts of the final name that needs separation
1776 /// \param FirstSeparator First separator used between the initial two
1777 /// parts of the name.
1778 /// \param Separator separator used between all of the rest consecutinve
1779 /// parts of the name
1780 static std::string getNameWithSeparators(ArrayRef<StringRef> Parts,
1781 StringRef FirstSeparator = ".",
1782 StringRef Separator = ".");
1783 /// Emit the Finalization for an OMP region
1784 /// \param CGF The Codegen function this belongs to
1785 /// \param IP Insertion point for generating the finalization code.
1787 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1788 assert(IP.getBlock()->end() != IP.getPoint() &&
1789 "OpenMP IR Builder should cause terminated block!");
1790
1791 llvm::BasicBlock *IPBB = IP.getBlock();
1792 llvm::BasicBlock *DestBB = IPBB->getUniqueSuccessor();
1793 assert(DestBB && "Finalization block should have one successor!");
1794
1795 // erase and replace with cleanup branch.
1796 IPBB->getTerminator()->eraseFromParent();
1797 CGF.Builder.SetInsertPoint(IPBB);
1799 CGF.EmitBranchThroughCleanup(Dest);
1800 }
1801
1802 /// Emit the body of an OMP region
1803 /// \param CGF The Codegen function this belongs to
1804 /// \param RegionBodyStmt The body statement for the OpenMP region being
1805 /// generated
1806 /// \param AllocaIP Where to insert alloca instructions
1807 /// \param CodeGenIP Where to insert the region code
1808 /// \param RegionName Name to be used for new blocks
1810 const Stmt *RegionBodyStmt,
1811 InsertPointTy AllocaIP,
1812 InsertPointTy CodeGenIP,
1813 Twine RegionName);
1814
1815 static void EmitCaptureStmt(CodeGenFunction &CGF, InsertPointTy CodeGenIP,
1816 llvm::BasicBlock &FiniBB, llvm::Function *Fn,
1818 llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock();
1819 if (llvm::Instruction *CodeGenIPBBTI = CodeGenIPBB->getTerminator())
1820 CodeGenIPBBTI->eraseFromParent();
1821
1822 CGF.Builder.SetInsertPoint(CodeGenIPBB);
1823
1824 if (Fn->doesNotThrow())
1825 CGF.EmitNounwindRuntimeCall(Fn, Args);
1826 else
1827 CGF.EmitRuntimeCall(Fn, Args);
1828
1829 if (CGF.Builder.saveIP().isSet())
1830 CGF.Builder.CreateBr(&FiniBB);
1831 }
1832
1833 /// Emit the body of an OMP region that will be outlined in
1834 /// OpenMPIRBuilder::finalize().
1835 /// \param CGF The Codegen function this belongs to
1836 /// \param RegionBodyStmt The body statement for the OpenMP region being
1837 /// generated
1838 /// \param AllocaIP Where to insert alloca instructions
1839 /// \param CodeGenIP Where to insert the region code
1840 /// \param RegionName Name to be used for new blocks
1842 const Stmt *RegionBodyStmt,
1843 InsertPointTy AllocaIP,
1844 InsertPointTy CodeGenIP,
1845 Twine RegionName);
1846
1847 /// RAII for preserving necessary info during Outlined region body codegen.
1849
1850 llvm::AssertingVH<llvm::Instruction> OldAllocaIP;
1851 CodeGenFunction::JumpDest OldReturnBlock;
1852 CodeGenFunction &CGF;
1853
1854 public:
1856 llvm::BasicBlock &RetBB)
1857 : CGF(cgf) {
1858 assert(AllocaIP.isSet() &&
1859 "Must specify Insertion point for allocas of outlined function");
1860 OldAllocaIP = CGF.AllocaInsertPt;
1861 CGF.AllocaInsertPt = &*AllocaIP.getPoint();
1862
1863 OldReturnBlock = CGF.ReturnBlock;
1864 CGF.ReturnBlock = CGF.getJumpDestInCurrentScope(&RetBB);
1865 }
1866
1868 CGF.AllocaInsertPt = OldAllocaIP;
1869 CGF.ReturnBlock = OldReturnBlock;
1870 }
1871 };
1872
1873 /// RAII for preserving necessary info during inlined region body codegen.
1875
1876 llvm::AssertingVH<llvm::Instruction> OldAllocaIP;
1877 CodeGenFunction &CGF;
1878
1879 public:
1881 llvm::BasicBlock &FiniBB)
1882 : CGF(cgf) {
1883 // Alloca insertion block should be in the entry block of the containing
1884 // function so it expects an empty AllocaIP in which case will reuse the
1885 // old alloca insertion point, or a new AllocaIP in the same block as
1886 // the old one
1887 assert((!AllocaIP.isSet() ||
1888 CGF.AllocaInsertPt->getParent() == AllocaIP.getBlock()) &&
1889 "Insertion point should be in the entry block of containing "
1890 "function!");
1891 OldAllocaIP = CGF.AllocaInsertPt;
1892 if (AllocaIP.isSet())
1893 CGF.AllocaInsertPt = &*AllocaIP.getPoint();
1894
1895 // TODO: Remove the call, after making sure the counter is not used by
1896 // the EHStack.
1897 // Since this is an inlined region, it should not modify the
1898 // ReturnBlock, and should reuse the one for the enclosing outlined
1899 // region. So, the JumpDest being return by the function is discarded
1900 (void)CGF.getJumpDestInCurrentScope(&FiniBB);
1901 }
1902
1904 };
1905 };
1906
1907private:
1908 /// CXXThisDecl - When generating code for a C++ member function,
1909 /// this will hold the implicit 'this' declaration.
1910 ImplicitParamDecl *CXXABIThisDecl = nullptr;
1911 llvm::Value *CXXABIThisValue = nullptr;
1912 llvm::Value *CXXThisValue = nullptr;
1913 CharUnits CXXABIThisAlignment;
1914 CharUnits CXXThisAlignment;
1915
1916 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
1917 /// this expression.
1918 Address CXXDefaultInitExprThis = Address::invalid();
1919
1920 /// The current array initialization index when evaluating an
1921 /// ArrayInitIndexExpr within an ArrayInitLoopExpr.
1922 llvm::Value *ArrayInitIndex = nullptr;
1923
1924 /// The values of function arguments to use when evaluating
1925 /// CXXInheritedCtorInitExprs within this context.
1926 CallArgList CXXInheritedCtorInitExprArgs;
1927
1928 /// CXXStructorImplicitParamDecl - When generating code for a constructor or
1929 /// destructor, this will hold the implicit argument (e.g. VTT).
1930 ImplicitParamDecl *CXXStructorImplicitParamDecl = nullptr;
1931 llvm::Value *CXXStructorImplicitParamValue = nullptr;
1932
1933 /// OutermostConditional - Points to the outermost active
1934 /// conditional control. This is used so that we know if a
1935 /// temporary should be destroyed conditionally.
1936 ConditionalEvaluation *OutermostConditional = nullptr;
1937
1938 /// The current lexical scope.
1939 LexicalScope *CurLexicalScope = nullptr;
1940
1941 /// The current source location that should be used for exception
1942 /// handling code.
1943 SourceLocation CurEHLocation;
1944
1945 /// BlockByrefInfos - For each __block variable, contains
1946 /// information about the layout of the variable.
1947 llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
1948
1949 /// Used by -fsanitize=nullability-return to determine whether the return
1950 /// value can be checked.
1951 llvm::Value *RetValNullabilityPrecondition = nullptr;
1952
1953 /// Check if -fsanitize=nullability-return instrumentation is required for
1954 /// this function.
1955 bool requiresReturnValueNullabilityCheck() const {
1956 return RetValNullabilityPrecondition;
1957 }
1958
1959 /// Used to store precise source locations for return statements by the
1960 /// runtime return value checks.
1961 Address ReturnLocation = Address::invalid();
1962
1963 /// Check if the return value of this function requires sanitization.
1964 bool requiresReturnValueCheck() const;
1965
1966 bool isInAllocaArgument(CGCXXABI &ABI, QualType Ty);
1967 bool hasInAllocaArg(const CXXMethodDecl *MD);
1968
1969 llvm::BasicBlock *TerminateLandingPad = nullptr;
1970 llvm::BasicBlock *TerminateHandler = nullptr;
1972
1973 /// Terminate funclets keyed by parent funclet pad.
1974 llvm::MapVector<llvm::Value *, llvm::BasicBlock *> TerminateFunclets;
1975
1976 /// Largest vector width used in ths function. Will be used to create a
1977 /// function attribute.
1978 unsigned LargestVectorWidth = 0;
1979
1980 /// True if we need emit the life-time markers. This is initially set in
1981 /// the constructor, but could be overwritten to true if this is a coroutine.
1982 bool ShouldEmitLifetimeMarkers;
1983
1984 /// Add OpenCL kernel arg metadata and the kernel attribute metadata to
1985 /// the function metadata.
1986 void EmitKernelMetadata(const FunctionDecl *FD, llvm::Function *Fn);
1987
1988public:
1989 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
1991
1992 CodeGenTypes &getTypes() const { return CGM.getTypes(); }
1993 ASTContext &getContext() const { return CGM.getContext(); }
1995 if (DisableDebugInfo)
1996 return nullptr;
1997 return DebugInfo;
1998 }
1999 void disableDebugInfo() { DisableDebugInfo = true; }
2000 void enableDebugInfo() { DisableDebugInfo = false; }
2001
2003 return CGM.getCodeGenOpts().OptimizationLevel == 0;
2004 }
2005
2006 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
2007
2008 /// Returns a pointer to the function's exception object and selector slot,
2009 /// which is assigned in every landing pad.
2012
2013 /// Returns the contents of the function's exception object and selector
2014 /// slots.
2015 llvm::Value *getExceptionFromSlot();
2016 llvm::Value *getSelectorFromSlot();
2017
2019
2020 llvm::BasicBlock *getUnreachableBlock() {
2021 if (!UnreachableBlock) {
2022 UnreachableBlock = createBasicBlock("unreachable");
2023 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
2024 }
2025 return UnreachableBlock;
2026 }
2027
2028 llvm::BasicBlock *getInvokeDest() {
2029 if (!EHStack.requiresLandingPad()) return nullptr;
2030 return getInvokeDestImpl();
2031 }
2032
2033 bool currentFunctionUsesSEHTry() const { return !!CurSEHParent; }
2034
2035 const TargetInfo &getTarget() const { return Target; }
2036 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
2038 return CGM.getTargetCodeGenInfo();
2039 }
2040
2041 //===--------------------------------------------------------------------===//
2042 // Cleanups
2043 //===--------------------------------------------------------------------===//
2044
2045 typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
2046
2047 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
2048 Address arrayEndPointer,
2049 QualType elementType,
2050 CharUnits elementAlignment,
2051 Destroyer *destroyer);
2052 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2053 llvm::Value *arrayEnd,
2054 QualType elementType,
2055 CharUnits elementAlignment,
2056 Destroyer *destroyer);
2057
2059 Address addr, QualType type);
2061 Address addr, QualType type);
2063 Destroyer *destroyer, bool useEHCleanupForArray);
2065 QualType type, Destroyer *destroyer,
2066 bool useEHCleanupForArray);
2067 void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
2068 llvm::Value *CompletePtr,
2069 QualType ElementType);
2072 std::pair<llvm::Value *, llvm::Value *> AddrSizePair);
2074 bool useEHCleanupForArray);
2076 Destroyer *destroyer,
2077 bool useEHCleanupForArray,
2078 const VarDecl *VD);
2079 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
2080 QualType elementType, CharUnits elementAlign,
2081 Destroyer *destroyer,
2082 bool checkZeroLength, bool useEHCleanup);
2083
2085
2086 /// Determines whether an EH cleanup is required to destroy a type
2087 /// with the given destruction kind.
2089 switch (kind) {
2090 case QualType::DK_none:
2091 return false;
2095 return getLangOpts().Exceptions;
2097 return getLangOpts().Exceptions &&
2098 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
2099 }
2100 llvm_unreachable("bad destruction kind");
2101 }
2102
2105 }
2106
2107 //===--------------------------------------------------------------------===//
2108 // Objective-C
2109 //===--------------------------------------------------------------------===//
2110
2112
2114
2115 /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
2117 const ObjCPropertyImplDecl *PID);
2119 const ObjCPropertyImplDecl *propImpl,
2120 const ObjCMethodDecl *GetterMothodDecl,
2121 llvm::Constant *AtomicHelperFn);
2122
2124 ObjCMethodDecl *MD, bool ctor);
2125
2126 /// GenerateObjCSetter - Synthesize an Objective-C property setter function
2127 /// for the given property.
2129 const ObjCPropertyImplDecl *PID);
2131 const ObjCPropertyImplDecl *propImpl,
2132 llvm::Constant *AtomicHelperFn);
2133
2134 //===--------------------------------------------------------------------===//
2135 // Block Bits
2136 //===--------------------------------------------------------------------===//
2137
2138 /// Emit block literal.
2139 /// \return an LLVM value which is a pointer to a struct which contains
2140 /// information about the block, including the block invoke function, the
2141 /// captured variables, etc.
2142 llvm::Value *EmitBlockLiteral(const BlockExpr *);
2143
2145 const CGBlockInfo &Info,
2146 const DeclMapTy &ldm,
2147 bool IsLambdaConversionToBlock,
2148 bool BuildGlobalBlock);
2149
2150 /// Check if \p T is a C++ class that has a destructor that can throw.
2152
2153 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
2154 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
2156 const ObjCPropertyImplDecl *PID);
2158 const ObjCPropertyImplDecl *PID);
2159 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
2160
2161 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags,
2162 bool CanThrow);
2163
2164 class AutoVarEmission;
2165
2167
2168 /// Enter a cleanup to destroy a __block variable. Note that this
2169 /// cleanup should be a no-op if the variable hasn't left the stack
2170 /// yet; if a cleanup is required for the variable itself, that needs
2171 /// to be done externally.
2172 ///
2173 /// \param Kind Cleanup kind.
2174 ///
2175 /// \param Addr When \p LoadBlockVarAddr is false, the address of the __block
2176 /// structure that will be passed to _Block_object_dispose. When
2177 /// \p LoadBlockVarAddr is true, the address of the field of the block
2178 /// structure that holds the address of the __block structure.
2179 ///
2180 /// \param Flags The flag that will be passed to _Block_object_dispose.
2181 ///
2182 /// \param LoadBlockVarAddr Indicates whether we need to emit a load from
2183 /// \p Addr to get the address of the __block structure.
2185 bool LoadBlockVarAddr, bool CanThrow);
2186
2187 void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
2188 llvm::Value *ptr);
2189
2192
2193 /// BuildBlockByrefAddress - Computes the location of the
2194 /// data in a variable which is declared as __block.
2196 bool followForward = true);
2198 const BlockByrefInfo &info,
2199 bool followForward,
2200 const llvm::Twine &name);
2201
2203
2205
2206 void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
2207 const CGFunctionInfo &FnInfo);
2208
2209 /// Annotate the function with an attribute that disables TSan checking at
2210 /// runtime.
2211 void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn);
2212
2213 /// Emit code for the start of a function.
2214 /// \param Loc The location to be associated with the function.
2215 /// \param StartLoc The location of the function body.
2217 QualType RetTy,
2218 llvm::Function *Fn,
2219 const CGFunctionInfo &FnInfo,
2220 const FunctionArgList &Args,
2222 SourceLocation StartLoc = SourceLocation());
2223
2225
2229 void EmitFunctionBody(const Stmt *Body);
2230 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
2231
2232 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
2233 CallArgList &CallArgs,
2234 const CGFunctionInfo *CallOpFnInfo = nullptr,
2235 llvm::Constant *CallOpFn = nullptr);
2239 CallArgList &CallArgs);
2241 const CGFunctionInfo **ImplFnInfo,
2242 llvm::Function **ImplFn);
2245 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2246 }
2247 void EmitAsanPrologueOrEpilogue(bool Prologue);
2248
2249 /// Emit the unified return block, trying to avoid its emission when
2250 /// possible.
2251 /// \return The debug location of the user written return statement if the
2252 /// return block is avoided.
2253 llvm::DebugLoc EmitReturnBlock();
2254
2255 /// FinishFunction - Complete IR generation of the current function. It is
2256 /// legal to call this function even if there is no current insertion point.
2258
2259 void StartThunk(llvm::Function *Fn, GlobalDecl GD,
2260 const CGFunctionInfo &FnInfo, bool IsUnprototyped);
2261
2262 void EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
2263 const ThunkInfo *Thunk, bool IsUnprototyped);
2264
2266
2267 /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
2268 void EmitMustTailThunk(GlobalDecl GD, llvm::Value *AdjustedThisPtr,
2269 llvm::FunctionCallee Callee);
2270
2271 /// Generate a thunk for the given method.
2272 void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
2273 GlobalDecl GD, const ThunkInfo &Thunk,
2274 bool IsUnprototyped);
2275
2276 llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
2277 const CGFunctionInfo &FnInfo,
2278 GlobalDecl GD, const ThunkInfo &Thunk);
2279
2281 FunctionArgList &Args);
2282
2284
2285 /// Struct with all information about dynamic [sub]class needed to set vptr.
2286 struct VPtr {
2291 };
2292
2293 /// Initialize the vtable pointer of the given subobject.
2295
2297
2300
2302 CharUnits OffsetFromNearestVBase,
2303 bool BaseIsNonVirtualPrimaryBase,
2304 const CXXRecordDecl *VTableClass,
2305 VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
2306
2308
2309 /// GetVTablePtr - Return the Value of the vtable pointer member pointed
2310 /// to by This.
2311 llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy,
2312 const CXXRecordDecl *VTableClass);
2313
2322 };
2323
2324 /// Derived is the presumed address of an object of type T after a
2325 /// cast. If T is a polymorphic class type, emit a check that the virtual
2326 /// table for Derived belongs to a class derived from T.
2327 void EmitVTablePtrCheckForCast(QualType T, Address Derived, bool MayBeNull,
2329
2330 /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
2331 /// If vptr CFI is enabled, emit a check that VTable is valid.
2332 void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
2334
2335 /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
2336 /// RD using llvm.type.test.
2337 void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
2339
2340 /// If whole-program virtual table optimization is enabled, emit an assumption
2341 /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
2342 /// enabled, emit a check that VTable is a member of RD's type identifier.
2344 llvm::Value *VTable, SourceLocation Loc);
2345
2346 /// Returns whether we should perform a type checked load when loading a
2347 /// virtual function for virtual calls to members of RD. This is generally
2348 /// true when both vcall CFI and whole-program-vtables are enabled.
2350
2351 /// Emit a type checked load from the given vtable.
2353 llvm::Value *VTable,
2354 llvm::Type *VTableTy,
2355 uint64_t VTableByteOffset);
2356
2357 /// EnterDtorCleanups - Enter the cleanups necessary to complete the
2358 /// given phase of destruction for a destructor. The end result
2359 /// should call destructors on members and base classes in reverse
2360 /// order of their construction.
2362
2363 /// ShouldInstrumentFunction - Return true if the current function should be
2364 /// instrumented with __cyg_profile_func_* calls
2366
2367 /// ShouldSkipSanitizerInstrumentation - Return true if the current function
2368 /// should not be instrumented with sanitizers.
2370
2371 /// ShouldXRayInstrument - Return true if the current function should be
2372 /// instrumented with XRay nop sleds.
2374
2375 /// AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit
2376 /// XRay custom event handling calls.
2378
2379 /// AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit
2380 /// XRay typed event handling calls.
2382
2383 /// Return a type hash constant for a function instrumented by
2384 /// -fsanitize=function.
2385 llvm::ConstantInt *getUBSanFunctionTypeHash(QualType T) const;
2386
2387 /// EmitFunctionProlog - Emit the target specific LLVM code to load the
2388 /// arguments for the given function. This is also responsible for naming the
2389 /// LLVM function arguments.
2391 llvm::Function *Fn,
2392 const FunctionArgList &Args);
2393
2394 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
2395 /// given temporary.
2396 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
2397 SourceLocation EndLoc);
2398
2399 /// Emit a test that checks if the return value \p RV is nonnull.
2400 void EmitReturnValueCheck(llvm::Value *RV);
2401
2402 /// EmitStartEHSpec - Emit the start of the exception spec.
2403 void EmitStartEHSpec(const Decl *D);
2404
2405 /// EmitEndEHSpec - Emit the end of the exception spec.
2406 void EmitEndEHSpec(const Decl *D);
2407
2408 /// getTerminateLandingPad - Return a landing pad that just calls terminate.
2409 llvm::BasicBlock *getTerminateLandingPad();
2410
2411 /// getTerminateLandingPad - Return a cleanup funclet that just calls
2412 /// terminate.
2413 llvm::BasicBlock *getTerminateFunclet();
2414
2415 /// getTerminateHandler - Return a handler (not a landing pad, just
2416 /// a catch handler) that just calls terminate. This is used when
2417 /// a terminate scope encloses a try.
2418 llvm::BasicBlock *getTerminateHandler();
2419
2421 llvm::Type *ConvertType(QualType T);
2422 llvm::Type *ConvertType(const TypeDecl *T) {
2423 return ConvertType(getContext().getTypeDeclType(T));
2424 }
2425
2426 /// LoadObjCSelf - Load the value of self. This function is only valid while
2427 /// generating code for an Objective-C method.
2428 llvm::Value *LoadObjCSelf();
2429
2430 /// TypeOfSelfObject - Return type of object that this self represents.
2432
2433 /// getEvaluationKind - Return the TypeEvaluationKind of QualType \c T.
2435
2437 return getEvaluationKind(T) == TEK_Scalar;
2438 }
2439
2441 return getEvaluationKind(T) == TEK_Aggregate;
2442 }
2443
2444 /// createBasicBlock - Create an LLVM basic block.
2445 llvm::BasicBlock *createBasicBlock(const Twine &name = "",
2446 llvm::Function *parent = nullptr,
2447 llvm::BasicBlock *before = nullptr) {
2448 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
2449 }
2450
2451 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
2452 /// label maps to.
2454
2455 /// SimplifyForwardingBlocks - If the given basic block is only a branch to
2456 /// another basic block, simplify it. This assumes that no other code could
2457 /// potentially reference the basic block.
2458 void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
2459
2460 /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
2461 /// adding a fall-through branch from the current insert block if
2462 /// necessary. It is legal to call this function even if there is no current
2463 /// insertion point.
2464 ///
2465 /// IsFinished - If true, indicates that the caller has finished emitting
2466 /// branches to the given block and does not expect to emit code into it. This
2467 /// means the block can be ignored if it is unreachable.
2468 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
2469
2470 /// EmitBlockAfterUses - Emit the given block somewhere hopefully
2471 /// near its uses, and leave the insertion point in it.
2472 void EmitBlockAfterUses(llvm::BasicBlock *BB);
2473
2474 /// EmitBranch - Emit a branch to the specified basic block from the current
2475 /// insert block, taking care to avoid creation of branches from dummy
2476 /// blocks. It is legal to call this function even if there is no current
2477 /// insertion point.
2478 ///
2479 /// This function clears the current insertion point. The caller should follow
2480 /// calls to this function with calls to Emit*Block prior to generation new
2481 /// code.
2482 void EmitBranch(llvm::BasicBlock *Block);
2483
2484 /// HaveInsertPoint - True if an insertion point is defined. If not, this
2485 /// indicates that the current code being emitted is unreachable.
2486 bool HaveInsertPoint() const {
2487 return Builder.GetInsertBlock() != nullptr;
2488 }
2489
2490 /// EnsureInsertPoint - Ensure that an insertion point is defined so that
2491 /// emitted IR has a place to go. Note that by definition, if this function
2492 /// creates a block then that block is unreachable; callers may do better to
2493 /// detect when no insertion point is defined and simply skip IR generation.
2495 if (!HaveInsertPoint())
2497 }
2498
2499 /// ErrorUnsupported - Print out an error that codegen doesn't support the
2500 /// specified stmt yet.
2501 void ErrorUnsupported(const Stmt *S, const char *Type);
2502
2503 //===--------------------------------------------------------------------===//
2504 // Helpers
2505 //===--------------------------------------------------------------------===//
2506
2509 return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source),
2511 }
2512
2514 TBAAAccessInfo TBAAInfo) {
2515 return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, TBAAInfo);
2516 }
2517
2518 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
2520 Address Addr(V, ConvertTypeForMem(T), Alignment);
2521 return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source),
2523 }
2524
2525 LValue
2528 return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source),
2529 TBAAAccessInfo());
2530 }
2531
2534
2536 LValueBaseInfo *PointeeBaseInfo = nullptr,
2537 TBAAAccessInfo *PointeeTBAAInfo = nullptr);
2540 AlignmentSource Source =
2542 LValue RefLVal = MakeAddrLValue(RefAddr, RefTy, LValueBaseInfo(Source),
2543 CGM.getTBAAAccessInfo(RefTy));
2544 return EmitLoadOfReferenceLValue(RefLVal);
2545 }
2546
2547 /// Load a pointer with type \p PtrTy stored at address \p Ptr.
2548 /// Note that \p PtrTy is the type of the loaded pointer, not the addresses
2549 /// it is loaded from.
2551 LValueBaseInfo *BaseInfo = nullptr,
2552 TBAAAccessInfo *TBAAInfo = nullptr);
2554
2555 /// CreateTempAlloca - This creates an alloca and inserts it into the entry
2556 /// block if \p ArraySize is nullptr, otherwise inserts it at the current
2557 /// insertion point of the builder. The caller is responsible for setting an
2558 /// appropriate alignment on
2559 /// the alloca.
2560 ///
2561 /// \p ArraySize is the number of array elements to be allocated if it
2562 /// is not nullptr.
2563 ///
2564 /// LangAS::Default is the address space of pointers to local variables and
2565 /// temporaries, as exposed in the source language. In certain
2566 /// configurations, this is not the same as the alloca address space, and a
2567 /// cast is needed to lift the pointer from the alloca AS into
2568 /// LangAS::Default. This can happen when the target uses a restricted
2569 /// address space for the stack but the source language requires
2570 /// LangAS::Default to be a generic address space. The latter condition is
2571 /// common for most programming languages; OpenCL is an exception in that
2572 /// LangAS::Default is the private address space, which naturally maps
2573 /// to the stack.
2574 ///
2575 /// Because the address of a temporary is often exposed to the program in
2576 /// various ways, this function will perform the cast. The original alloca
2577 /// instruction is returned through \p Alloca if it is not nullptr.
2578 ///
2579 /// The cast is not performaed in CreateTempAllocaWithoutCast. This is
2580 /// more efficient if the caller knows that the address will not be exposed.
2581 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, const Twine &Name = "tmp",
2582 llvm::Value *ArraySize = nullptr);
2583 Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
2584 const Twine &Name = "tmp",
2585 llvm::Value *ArraySize = nullptr,
2586 Address *Alloca = nullptr);
2588 const Twine &Name = "tmp",
2589 llvm::Value *ArraySize = nullptr);
2590
2591 /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
2592 /// default ABI alignment of the given LLVM type.
2593 ///
2594 /// IMPORTANT NOTE: This is *not* generally the right alignment for
2595 /// any given AST type that happens to have been lowered to the
2596 /// given IR type. This should only ever be used for function-local,
2597 /// IR-driven manipulations like saving and restoring a value. Do
2598 /// not hand this address off to arbitrary IRGen routines, and especially
2599 /// do not pass it as an argument to a function that might expect a
2600 /// properly ABI-aligned value.
2602 const Twine &Name = "tmp");
2603
2604 /// CreateIRTemp - Create a temporary IR object of the given type, with
2605 /// appropriate alignment. This routine should only be used when an temporary
2606 /// value needs to be stored into an alloca (for example, to avoid explicit
2607 /// PHI construction), but the type is the IR type, not the type appropriate
2608 /// for storing in memory.
2609 ///
2610 /// That is, this is exactly equivalent to CreateMemTemp, but calling
2611 /// ConvertType instead of ConvertTypeForMem.
2612 Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
2613
2614 /// CreateMemTemp - Create a temporary memory object of the given type, with
2615 /// appropriate alignmen and cast it to the default address space. Returns
2616 /// the original alloca instruction by \p Alloca if it is not nullptr.
2617 Address CreateMemTemp(QualType T, const Twine &Name = "tmp",
2618 Address *Alloca = nullptr);
2619 Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp",
2620 Address *Alloca = nullptr);
2621
2622 /// CreateMemTemp - Create a temporary memory object of the given type, with
2623 /// appropriate alignmen without casting it to the default address space.
2624 Address CreateMemTempWithoutCast(QualType T, const Twine &Name = "tmp");
2626 const Twine &Name = "tmp");
2627
2628 /// CreateAggTemp - Create a temporary memory object for the given
2629 /// aggregate type.
2630 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp",
2631 Address *Alloca = nullptr) {
2632 return AggValueSlot::forAddr(CreateMemTemp(T, Name, Alloca),
2633 T.getQualifiers(),
2638 }
2639
2640 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
2641 /// expression and compare the result against zero, returning an Int1Ty value.
2642 llvm::Value *EvaluateExprAsBool(const Expr *E);
2643
2644 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
2645 void EmitIgnoredExpr(const Expr *E);
2646
2647 /// EmitAnyExpr - Emit code to compute the specified expression which can have
2648 /// any type. The result is returned as an RValue struct. If this is an
2649 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
2650 /// the result should be returned.
2651 ///
2652 /// \param ignoreResult True if the resulting value isn't used.
2655 bool ignoreResult = false);
2656
2657 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
2658 // or the value of the expression, depending on how va_list is defined.
2660
2661 /// Emit a "reference" to a __builtin_ms_va_list; this is
2662 /// always the value of the expression, because a __builtin_ms_va_list is a
2663 /// pointer to a char.
2665
2666 /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will
2667 /// always be accessible even if no aggregate location is provided.
2669
2670 /// EmitAnyExprToMem - Emits the code necessary to evaluate an
2671 /// arbitrary expression into the given memory location.
2672 void EmitAnyExprToMem(const Expr *E, Address Location,
2673 Qualifiers Quals, bool IsInitializer);
2674
2675 void EmitAnyExprToExn(const Expr *E, Address Addr);
2676
2677 /// EmitExprAsInit - Emits the code necessary to initialize a
2678 /// location in memory with the given initializer.
2679 void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2680 bool capturedByInit);
2681
2682 /// hasVolatileMember - returns true if aggregate type has a volatile
2683 /// member.
2685 if (const RecordType *RT = T->getAs<RecordType>()) {
2686 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2687 return RD->hasVolatileMember();
2688 }
2689 return false;
2690 }
2691
2692 /// Determine whether a return value slot may overlap some other object.
2694 // FIXME: Assuming no overlap here breaks guaranteed copy elision for base
2695 // class subobjects. These cases may need to be revisited depending on the
2696 // resolution of the relevant core issue.
2698 }
2699
2700 /// Determine whether a field initialization may overlap some other object.
2702
2703 /// Determine whether a base class initialization may overlap some other
2704 /// object.
2706 const CXXRecordDecl *BaseRD,
2707 bool IsVirtual);
2708
2709 /// Emit an aggregate assignment.
2711 bool IsVolatile = hasVolatileMember(EltTy);
2712 EmitAggregateCopy(Dest, Src, EltTy, AggValueSlot::MayOverlap, IsVolatile);
2713 }
2714
2716 AggValueSlot::Overlap_t MayOverlap) {
2717 EmitAggregateCopy(Dest, Src, Src.getType(), MayOverlap);
2718 }
2719
2720 /// EmitAggregateCopy - Emit an aggregate copy.
2721 ///
2722 /// \param isVolatile \c true iff either the source or the destination is
2723 /// volatile.
2724 /// \param MayOverlap Whether the tail padding of the destination might be
2725 /// occupied by some other object. More efficient code can often be
2726 /// generated if not.
2728 AggValueSlot::Overlap_t MayOverlap,
2729 bool isVolatile = false);
2730
2731 /// GetAddrOfLocalVar - Return the address of a local variable.
2733 auto it = LocalDeclMap.find(VD);
2734 assert(it != LocalDeclMap.end() &&
2735 "Invalid argument to GetAddrOfLocalVar(), no decl!");
2736 return it->second;
2737 }
2738
2739 /// Given an opaque value expression, return its LValue mapping if it exists,
2740 /// otherwise create one.
2742
2743 /// Given an opaque value expression, return its RValue mapping if it exists,
2744 /// otherwise create one.
2746
2747 /// Get the index of the current ArrayInitLoopExpr, if any.
2748 llvm::Value *getArrayInitIndex() { return ArrayInitIndex; }
2749
2750 /// getAccessedFieldNo - Given an encoded value and a result number, return
2751 /// the input field number being accessed.
2752 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
2753
2754 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
2755 llvm::BasicBlock *GetIndirectGotoBlock();
2756
2757 /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts.
2758 static bool IsWrappedCXXThis(const Expr *E);
2759
2760 /// EmitNullInitialization - Generate code to set a value of the given type to
2761 /// null, If the type contains data member pointers, they will be initialized
2762 /// to -1 in accordance with the Itanium C++ ABI.
2764
2765 /// Emits a call to an LLVM variable-argument intrinsic, either
2766 /// \c llvm.va_start or \c llvm.va_end.
2767 /// \param ArgValue A reference to the \c va_list as emitted by either
2768 /// \c EmitVAListRef or \c EmitMSVAListRef.
2769 /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
2770 /// calls \c llvm.va_end.
2771 llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
2772
2773 /// Generate code to get an argument from the passed in pointer
2774 /// and update it accordingly.
2775 /// \param VE The \c VAArgExpr for which to generate code.
2776 /// \param VAListAddr Receives a reference to the \c va_list as emitted by
2777 /// either \c EmitVAListRef or \c EmitMSVAListRef.
2778 /// \returns A pointer to the argument.
2779 // FIXME: We should be able to get rid of this method and use the va_arg
2780 // instruction in LLVM instead once it works well enough.
2782
2783 /// emitArrayLength - Compute the length of an array, even if it's a
2784 /// VLA, and drill down to the base element type.
2786 QualType &baseType,
2787 Address &addr);
2788
2789 /// EmitVLASize - Capture all the sizes for the VLA expressions in
2790 /// the given variably-modified type and store them in the VLASizeMap.
2791 ///
2792 /// This function can be called with a null (unreachable) insert point.
2794
2796 llvm::Value *NumElts;
2798
2799 VlaSizePair(llvm::Value *NE, QualType T) : NumElts(NE), Type(T) {}
2800 };
2801
2802 /// Return the number of elements for a single dimension
2803 /// for the given array type.
2806
2807 /// Returns an LLVM value that corresponds to the size,
2808 /// in non-variably-sized elements, of a variable length array type,
2809 /// plus that largest non-variably-sized element type. Assumes that
2810 /// the type has already been emitted with EmitVariablyModifiedType.
2813
2814 /// LoadCXXThis - Load the value of 'this'. This function is only valid while
2815 /// generating code for an C++ member function.
2816 llvm::Value *LoadCXXThis() {
2817 assert(CXXThisValue && "no 'this' value for this function");
2818 return CXXThisValue;
2819 }
2821
2822 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
2823 /// virtual bases.
2824 // FIXME: Every place that calls LoadCXXVTT is something
2825 // that needs to be abstracted properly.
2826 llvm::Value *LoadCXXVTT() {
2827 assert(CXXStructorImplicitParamValue && "no VTT value for this function");
2828 return CXXStructorImplicitParamValue;
2829 }
2830
2831 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
2832 /// complete class to the given direct base.
2833 Address
2835 const CXXRecordDecl *Derived,
2836 const CXXRecordDecl *Base,
2837 bool BaseIsVirtual);
2838
2839 static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
2840
2841 /// GetAddressOfBaseClass - This function will add the necessary delta to the
2842 /// load of 'this' and returns address of the base class.
2844 const CXXRecordDecl *Derived,
2847 bool NullCheckValue, SourceLocation Loc);
2848
2850 const CXXRecordDecl *Derived,
2853 bool NullCheckValue);
2854
2855 /// GetVTTParameter - Return the VTT parameter that should be passed to a
2856 /// base constructor/destructor with virtual bases.
2857 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
2858 /// to ItaniumCXXABI.cpp together with all the references to VTT.
2859 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
2860 bool Delegating);
2861
2863 CXXCtorType CtorType,
2864 const FunctionArgList &Args,
2865 SourceLocation Loc);
2866 // It's important not to confuse this and the previous function. Delegating
2867 // constructors are the C++0x feature. The constructor delegate optimization
2868 // is used to reduce duplication in the base and complete consturctors where
2869 // they are substantially the same.
2871 const FunctionArgList &Args);
2872
2873 /// Emit a call to an inheriting constructor (that is, one that invokes a
2874 /// constructor inherited from a base class) by inlining its definition. This
2875 /// is necessary if the ABI does not support forwarding the arguments to the
2876 /// base class constructor (because they're variadic or similar).
2878 CXXCtorType CtorType,
2879 bool ForVirtualBase,
2880 bool Delegating,
2881 CallArgList &Args);
2882
2883 /// Emit a call to a constructor inherited from a base class, passing the
2884 /// current constructor's arguments along unmodified (without even making
2885 /// a copy).
2887 bool ForVirtualBase, Address This,
2888 bool InheritedFromVBase,
2889 const CXXInheritedCtorInitExpr *E);
2890
2892 bool ForVirtualBase, bool Delegating,
2893 AggValueSlot ThisAVS, const CXXConstructExpr *E);
2894
2896 bool ForVirtualBase, bool Delegating,
2897 Address This, CallArgList &Args,
2899 SourceLocation Loc, bool NewPointerIsChecked);
2900
2901 /// Emit assumption load for all bases. Requires to be called only on
2902 /// most-derived class and not under construction of the object.
2904
2905 /// Emit assumption that vptr load == global vtable.
2906 void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
2907
2909 Address This, Address Src,
2910 const CXXConstructExpr *E);
2911
2913 const ArrayType *ArrayTy,
2914 Address ArrayPtr,
2915 const CXXConstructExpr *E,
2916 bool NewPointerIsChecked,
2917 bool ZeroInitialization = false);
2918
2920 llvm::Value *NumElements,
2921 Address ArrayPtr,
2922 const CXXConstructExpr *E,
2923 bool NewPointerIsChecked,
2924 bool ZeroInitialization = false);
2925
2927
2929 bool ForVirtualBase, bool Delegating, Address This,
2930 QualType ThisTy);
2931
2932 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
2933 llvm::Type *ElementTy, Address NewPtr,
2934 llvm::Value *NumElements,
2935 llvm::Value *AllocSizeWithoutCookie);
2936
2937 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
2938 Address Ptr);
2939
2944
2945 llvm::Value *EmitLifetimeStart(llvm::TypeSize Size, llvm::Value *Addr);
2946 void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
2947
2948 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
2950
2951 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
2952 QualType DeleteTy, llvm::Value *NumElements = nullptr,
2953 CharUnits CookieSize = CharUnits());
2954
2956 const CallExpr *TheCallExpr, bool IsDelete);
2957
2958 llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
2959 llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
2961
2962 /// Situations in which we might emit a check for the suitability of a
2963 /// pointer or glvalue. Needs to be kept in sync with ubsan_handlers.cpp in
2964 /// compiler-rt.
2966 /// Checking the operand of a load. Must be suitably sized and aligned.
2968 /// Checking the destination of a store. Must be suitably sized and aligned.
2970 /// Checking the bound value in a reference binding. Must be suitably sized
2971 /// and aligned, but is not required to refer to an object (until the
2972 /// reference is used), per core issue 453.
2974 /// Checking the object expression in a non-static data member access. Must
2975 /// be an object within its lifetime.
2977 /// Checking the 'this' pointer for a call to a non-static member function.
2978 /// Must be an object within its lifetime.
2980 /// Checking the 'this' pointer for a constructor call.
2982 /// Checking the operand of a static_cast to a derived pointer type. Must be
2983 /// null or an object within its lifetime.
2985 /// Checking the operand of a static_cast to a derived reference type. Must
2986 /// be an object within its lifetime.
2988 /// Checking the operand of a cast to a base object. Must be suitably sized
2989 /// and aligned.
2991 /// Checking the operand of a cast to a virtual base object. Must be an
2992 /// object within its lifetime.
2994 /// Checking the value assigned to a _Nonnull pointer. Must not be null.
2996 /// Checking the operand of a dynamic_cast or a typeid expression. Must be
2997 /// null or an object within its lifetime.
3000
3001 /// Determine whether the pointer type check \p TCK permits null pointers.
3003
3004 /// Determine whether the pointer type check \p TCK requires a vptr check.
3006
3007 /// Whether any type-checking sanitizers are enabled. If \c false,
3008 /// calls to EmitTypeCheck can be skipped.
3010
3011 /// Emit a check that \p V is the address of storage of the
3012 /// appropriate size and alignment for an object of type \p Type
3013 /// (or if ArraySize is provided, for an array of that bound).
3014 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
3015 QualType Type, CharUnits Alignment = CharUnits::Zero(),
3016 SanitizerSet SkippedChecks = SanitizerSet(),
3017 llvm::Value *ArraySize = nullptr);
3018
3019 /// Emit a check that \p Base points into an array object, which
3020 /// we can access at index \p Index. \p Accessed should be \c false if we
3021 /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
3022 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
3023 QualType IndexType, bool Accessed);
3024
3025 // Find a struct's flexible array member. It may be embedded inside multiple
3026 // sub-structs, but must still be the last field.
3028 const RecordDecl *RD);
3029
3030 /// Find the FieldDecl specified in a FAM's "counted_by" attribute. Returns
3031 /// \p nullptr if either the attribute or the field doesn't exist.
3033
3034 /// Build an expression accessing the "counted_by" field.
3036 const ValueDecl *CountedByVD);
3037
3039 bool isInc, bool isPre);
3041 bool isInc, bool isPre);
3042
3043 /// Converts Location to a DebugLoc, if debug information is enabled.
3044 llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
3045
3046 /// Get the record field index as represented in debug info.
3047 unsigned getDebugInfoFIndex(const RecordDecl *Rec, unsigned FieldIndex);
3048
3049
3050 //===--------------------------------------------------------------------===//
3051 // Declaration Emission
3052 //===--------------------------------------------------------------------===//
3053
3054 /// EmitDecl - Emit a declaration.
3055 ///
3056 /// This function can be called with a null (unreachable) insert point.
3057 void EmitDecl(const Decl &D);
3058
3059 /// EmitVarDecl - Emit a local variable declaration.
3060 ///
3061 /// This function can be called with a null (unreachable) insert point.
3062 void EmitVarDecl(const VarDecl &D);
3063
3064 void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
3065 bool capturedByInit);
3066
3068 llvm::Value *Address);
3069
3070 /// Determine whether the given initializer is trivial in the sense
3071 /// that it requires no code to be generated.
3073
3074 /// EmitAutoVarDecl - Emit an auto variable declaration.
3075 ///
3076 /// This function can be called with a null (unreachable) insert point.
3077 void EmitAutoVarDecl(const VarDecl &D);
3078
3080 friend class CodeGenFunction;
3081
3082 const VarDecl *Variable;
3083
3084 /// The address of the alloca for languages with explicit address space
3085 /// (e.g. OpenCL) or alloca casted to generic pointer for address space
3086 /// agnostic languages (e.g. C++). Invalid if the variable was emitted
3087 /// as a global constant.
3088 Address Addr;
3089
3090 llvm::Value *NRVOFlag;
3091
3092 /// True if the variable is a __block variable that is captured by an
3093 /// escaping block.
3094 bool IsEscapingByRef;
3095
3096 /// True if the variable is of aggregate type and has a constant
3097 /// initializer.
3098 bool IsConstantAggregate;
3099
3100 /// Non-null if we should use lifetime annotations.
3101 llvm::Value *SizeForLifetimeMarkers;
3102
3103 /// Address with original alloca instruction. Invalid if the variable was
3104 /// emitted as a global constant.
3105 Address AllocaAddr;
3106
3107 struct Invalid {};
3108 AutoVarEmission(Invalid)
3109 : Variable(nullptr), Addr(Address::invalid()),
3110 AllocaAddr(Address::invalid()) {}
3111
3112 AutoVarEmission(const VarDecl &variable)
3113 : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
3114 IsEscapingByRef(false), IsConstantAggregate(false),
3115 SizeForLifetimeMarkers(nullptr), AllocaAddr(Address::invalid()) {}
3116
3117 bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
3118
3119 public:
3120 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
3121
3122 bool useLifetimeMarkers() const {
3123 return SizeForLifetimeMarkers != nullptr;
3124 }
3125 llvm::Value *getSizeForLifetimeMarkers() const {
3126 assert(useLifetimeMarkers());
3127 return SizeForLifetimeMarkers;
3128 }
3129
3130 /// Returns the raw, allocated address, which is not necessarily
3131 /// the address of the object itself. It is casted to default
3132 /// address space for address space agnostic languages.
3134 return Addr;
3135 }
3136
3137 /// Returns the address for the original alloca instruction.
3138 Address getOriginalAllocatedAddress() const { return AllocaAddr; }
3139
3140 /// Returns the address of the object within this declaration.
3141 /// Note that this does not chase the forwarding pointer for
3142 /// __block decls.
3144 if (!IsEscapingByRef) return Addr;
3145
3146 return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
3147 }
3148 };
3150 void EmitAutoVarInit(const AutoVarEmission &emission);
3153 QualType::DestructionKind dtorKind);
3154
3155 /// Emits the alloca and debug information for the size expressions for each
3156 /// dimension of an array. It registers the association of its (1-dimensional)
3157 /// QualTypes and size expression's debug node, so that CGDebugInfo can
3158 /// reference this node when creating the DISubrange object to describe the
3159 /// array types.
3161 const VarDecl &D,
3162 bool EmitDebugInfo);
3163
3165 llvm::GlobalValue::LinkageTypes Linkage);
3166
3168 llvm::Value *Value;
3169 llvm::Type *ElementType;
3170 unsigned Alignment;
3171 ParamValue(llvm::Value *V, llvm::Type *T, unsigned A)
3172 : Value(V), ElementType(T), Alignment(A) {}
3173 public:
3174 static ParamValue forDirect(llvm::Value *value) {
3175 return ParamValue(value, nullptr, 0);
3176 }
3178 assert(!addr.getAlignment().isZero());
3179 return ParamValue(addr.getPointer(), addr.getElementType(),
3180 addr.getAlignment().getQuantity());
3181 }
3182
3183 bool isIndirect() const { return Alignment != 0; }
3184 llvm::Value *getAnyValue() const { return Value; }
3185
3186 llvm::Value *getDirectValue() const {
3187 assert(!isIndirect());
3188 return Value;
3189 }
3190
3192 assert(isIndirect());
3193 return Address(Value, ElementType, CharUnits::fromQuantity(Alignment),
3194 KnownNonNull);
3195 }
3196 };
3197
3198 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
3199 void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
3200
3201 /// protectFromPeepholes - Protect a value that we're intending to
3202 /// store to the side, but which will probably be used later, from
3203 /// aggressive peepholing optimizations that might delete it.
3204 ///
3205 /// Pass the result to unprotectFromPeepholes to declare that
3206 /// protection is no longer required.
3207 ///
3208 /// There's no particular reason why this shouldn't apply to
3209 /// l-values, it's just that no existing peepholes work on pointers.
3212
3213 void emitAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty,
3214 SourceLocation Loc,
3215 SourceLocation AssumptionLoc,
3216 llvm::Value *Alignment,
3217 llvm::Value *OffsetValue,
3218 llvm::Value *TheCheck,
3219 llvm::Instruction *Assumption);
3220
3221 void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty,
3222 SourceLocation Loc, SourceLocation AssumptionLoc,
3223 llvm::Value *Alignment,
3224 llvm::Value *OffsetValue = nullptr);
3225
3226 void emitAlignmentAssumption(llvm::Value *PtrValue, const Expr *E,
3227 SourceLocation AssumptionLoc,
3228 llvm::Value *Alignment,
3229 llvm::Value *OffsetValue = nullptr);
3230
3231 //===--------------------------------------------------------------------===//
3232 // Statement Emission
3233 //===--------------------------------------------------------------------===//
3234
3235 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
3236 void EmitStopPoint(const Stmt *S);
3237
3238 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
3239 /// this function even if there is no current insertion point.
3240 ///
3241 /// This function may clear the current insertion point; callers should use
3242 /// EnsureInsertPoint if they wish to subsequently generate code without first
3243 /// calling EmitBlock, EmitBranch, or EmitStmt.
3244 void EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs = std::nullopt);
3245
3246 /// EmitSimpleStmt - Try to emit a "simple" statement which does not
3247 /// necessarily require an insertion point or debug information; typically
3248 /// because the statement amounts to a jump or a container of other
3249 /// statements.
3250 ///
3251 /// \return True if the statement was handled.
3253
3254 Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
3257 bool GetLast = false,
3258 AggValueSlot AVS =
3260
3261 /// EmitLabel - Emit the block for the given label. It is legal to call this
3262 /// function even if there is no current insertion point.
3263 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
3264
3265 void EmitLabelStmt(const LabelStmt &S);
3267 void EmitGotoStmt(const GotoStmt &S);
3269 void EmitIfStmt(const IfStmt &S);
3270
3272 ArrayRef<const Attr *> Attrs = std::nullopt);
3273 void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = std::nullopt);
3274 void EmitForStmt(const ForStmt &S,
3275 ArrayRef<const Attr *> Attrs = std::nullopt);
3277 void EmitDeclStmt(const DeclStmt &S);
3278 void EmitBreakStmt(const BreakStmt &S);
3284 void EmitAsmStmt(const AsmStmt &S);
3285
3291
3296 bool ignoreResult = false);
3300 bool ignoreResult = false);
3302 RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
3303
3304 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
3305 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
3306
3312 void VolatilizeTryBlocks(llvm::BasicBlock *BB,
3314
3316 llvm::Function *FinallyFunc);
3318 const Stmt *OutlinedStmt);
3319
3321 const SEHExceptStmt &Except);
3322
3324 const SEHFinallyStmt &Finally);
3325
3327 llvm::Value *ParentFP,
3328 llvm::Value *EntryEBP);
3329 llvm::Value *EmitSEHExceptionCode();
3330 llvm::Value *EmitSEHExceptionInfo();
3332
3333 /// Emit simple code for OpenMP directives in Simd-only mode.
3335
3336 /// Scan the outlined statement for captures from the parent function. For
3337 /// each capture, mark the capture as escaped and emit a call to
3338 /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
3340 bool IsFilter);
3341
3342 /// Recovers the address of a local in a parent function. ParentVar is the
3343 /// address of the variable used in the immediate parent function. It can
3344 /// either be an alloca or a call to llvm.localrecover if there are nested
3345 /// outlined functions. ParentFP is the frame pointer of the outermost parent
3346 /// frame.
3348 Address ParentVar,
3349 llvm::Value *ParentFP);
3350
3352 ArrayRef<const Attr *> Attrs = std::nullopt);
3353
3354 /// Controls insertion of cancellation exit blocks in worksharing constructs.
3356 CodeGenFunction &CGF;
3357
3358 public:
3360 bool HasCancel)
3361 : CGF(CGF) {
3362 CGF.OMPCancelStack.enter(CGF, Kind, HasCancel);
3363 }
3364 ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); }
3365 };
3366
3367 /// Returns calculated size of the specified type.
3368 llvm::Value *getTypeSize(QualType Ty);
3374 SourceLocation Loc);
3376 SmallVectorImpl<llvm::Value *> &CapturedVars);
3377 void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
3378 SourceLocation Loc);
3379 /// Perform element by element copying of arrays with type \a
3380 /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
3381 /// generated by \a CopyGen.
3382 ///
3383 /// \param DestAddr Address of the destination array.
3384 /// \param SrcAddr Address of the source array.
3385 /// \param OriginalType Type of destination and source arrays.
3386 /// \param CopyGen Copying procedure that copies value of single array element
3387 /// to another single array element.
3389 Address DestAddr, Address SrcAddr, QualType OriginalType,
3390 const llvm::function_ref<void(Address, Address)> CopyGen);
3391 /// Emit proper copying of data from one variable to another.
3392 ///
3393 /// \param OriginalType Original type of the copied variables.
3394 /// \param DestAddr Destination address.
3395 /// \param SrcAddr Source address.
3396 /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
3397 /// type of the base array element).
3398 /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
3399 /// the base array element).
3400 /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
3401 /// DestVD.
3402 void EmitOMPCopy(QualType OriginalType,
3403 Address DestAddr, Address SrcAddr,
3404 const VarDecl *DestVD, const VarDecl *SrcVD,
3405 const Expr *Copy);
3406 /// Emit atomic update code for constructs: \a X = \a X \a BO \a E or
3407 /// \a X = \a E \a BO \a E.
3408 ///
3409 /// \param X Value to be updated.
3410 /// \param E Update value.
3411 /// \param BO Binary operation for update operation.
3412 /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
3413 /// expression, false otherwise.
3414 /// \param AO Atomic ordering of the generated atomic instructions.
3415 /// \param CommonGen Code generator for complex expressions that cannot be
3416 /// expressed through atomicrmw instruction.
3417 /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
3418 /// generated, <false, RValue::get(nullptr)> otherwise.
3419 std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
3420 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3421 llvm::AtomicOrdering AO, SourceLocation Loc,
3422 const llvm::function_ref<RValue(RValue)> CommonGen);
3424 OMPPrivateScope &PrivateScope);
3426 OMPPrivateScope &PrivateScope);
3428 const OMPUseDevicePtrClause &C, OMPPrivateScope &PrivateScope,
3429 const llvm::DenseMap<const ValueDecl *, llvm::Value *>
3430 CaptureDeviceAddrMap);
3432 const OMPUseDeviceAddrClause &C, OMPPrivateScope &PrivateScope,
3433 const llvm::DenseMap<const ValueDecl *, llvm::Value *>
3434 CaptureDeviceAddrMap);
3435 /// Emit code for copyin clause in \a D directive. The next code is
3436 /// generated at the start of outlined functions for directives:
3437 /// \code
3438 /// threadprivate_var1 = master_threadprivate_var1;
3439 /// operator=(threadprivate_var2, master_threadprivate_var2);
3440 /// ...
3441 /// __kmpc_barrier(&loc, global_tid);
3442 /// \endcode
3443 ///
3444 /// \param D OpenMP directive possibly with 'copyin' clause(s).
3445 /// \returns true if at least one copyin variable is found, false otherwise.
3447 /// Emit initial code for lastprivate variables. If some variable is
3448 /// not also firstprivate, then the default initialization is used. Otherwise
3449 /// initialization of this variable is performed by EmitOMPFirstprivateClause
3450 /// method.
3451 ///
3452 /// \param D Directive that may have 'lastprivate' directives.
3453 /// \param PrivateScope Private scope for capturing lastprivate variables for
3454 /// proper codegen in internal captured statement.
3455 ///
3456 /// \returns true if there is at least one lastprivate variable, false
3457 /// otherwise.
3459 OMPPrivateScope &PrivateScope);
3460 /// Emit final copying of lastprivate values to original variables at
3461 /// the end of the worksharing or simd directive.
3462 ///
3463 /// \param D Directive that has at least one 'lastprivate' directives.
3464 /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
3465 /// it is the last iteration of the loop code in associated directive, or to
3466 /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
3468 bool NoFinals,
3469 llvm::Value *IsLastIterCond = nullptr);
3470 /// Emit initial code for linear clauses.
3472 CodeGenFunction::OMPPrivateScope &PrivateScope);
3473 /// Emit final code for linear clauses.
3474 /// \param CondGen Optional conditional code for final part of codegen for
3475 /// linear clause.
3477 const OMPLoopDirective &D,
3478 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen);
3479 /// Emit initial code for reduction variables. Creates reduction copies
3480 /// and initializes them with the values according to OpenMP standard.
3481 ///
3482 /// \param D Directive (possibly) with the 'reduction' clause.
3483 /// \param PrivateScope Private scope for capturing reduction variables for
3484 /// proper codegen in internal captured statement.
3485 ///
3487 OMPPrivateScope &PrivateScope,
3488 bool ForInscan = false);
3489 /// Emit final update of reduction values to original variables at
3490 /// the end of the directive.
3491 ///
3492 /// \param D Directive that has at least one 'reduction' directives.
3493 /// \param ReductionKind The kind of reduction to perform.
3495 const OpenMPDirectiveKind ReductionKind);
3496 /// Emit initial code for linear variables. Creates private copies
3497 /// and initializes them with the values according to OpenMP standard.
3498 ///
3499 /// \param D Directive (possibly) with the 'linear' clause.
3500 /// \return true if at least one linear variable is found that should be
3501 /// initialized with the value of the original variable, false otherwise.
3503
3504 typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
3505 llvm::Function * /*OutlinedFn*/,
3506 const OMPTaskDataTy & /*Data*/)>
3509 const OpenMPDirectiveKind CapturedRegion,
3510 const RegionCodeGenTy &BodyGen,
3511 const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
3518 explicit OMPTargetDataInfo() = default;
3521 unsigned NumberOfTargetItems)
3525 };
3527 const RegionCodeGenTy &BodyGen,
3528 OMPTargetDataInfo &InputInfo);
3531 CodeGenFunction &CGF,
3532 const CapturedStmt *CS,
3568 void
3571 void
3578 void
3594 void
3618
3619 /// Emit device code for the target directive.
3621 StringRef ParentName,
3622 const OMPTargetDirective &S);
3623 static void
3626 /// Emit device code for the target parallel for directive.
3628 CodeGenModule &CGM, StringRef ParentName,
3630 /// Emit device code for the target parallel for simd directive.
3632 CodeGenModule &CGM, StringRef ParentName,
3634 /// Emit device code for the target teams directive.
3635 static void
3637 const OMPTargetTeamsDirective &S);
3638 /// Emit device code for the target teams distribute directive.
3640 CodeGenModule &CGM, StringRef ParentName,
3642 /// Emit device code for the target teams distribute simd directive.
3644 CodeGenModule &CGM, StringRef ParentName,
3646 /// Emit device code for the target simd directive.
3648 StringRef ParentName,
3649 const OMPTargetSimdDirective &S);
3650 /// Emit device code for the target teams distribute parallel for simd
3651 /// directive.
3653 CodeGenModule &CGM, StringRef ParentName,
3655
3656 /// Emit device code for the target teams loop directive.
3658 CodeGenModule &CGM, StringRef ParentName,
3660
3661 /// Emit device code for the target parallel loop directive.
3663 CodeGenModule &CGM, StringRef ParentName,
3665
3667 CodeGenModule &CGM, StringRef ParentName,
3669
3670 /// Emit the Stmt \p S and return its topmost canonical loop, if any.
3671 /// TODO: The \p Depth paramter is not yet implemented and must be 1. In the
3672 /// future it is meant to be the number of loops expected in the loop nests
3673 /// (usually specified by the "collapse" clause) that are collapsed to a
3674 /// single loop by this function.
3675 llvm::CanonicalLoopInfo *EmitOMPCollapsedCanonicalLoopNest(const Stmt *S,
3676 int Depth);
3677
3678 /// Emit an OMPCanonicalLoop using the OpenMPIRBuilder.
3680
3681 /// Emit inner loop of the worksharing/simd construct.
3682 ///
3683 /// \param S Directive, for which the inner loop must be emitted.
3684 /// \param RequiresCleanup true, if directive has some associated private
3685 /// variables.
3686 /// \param LoopCond Bollean condition for loop continuation.
3687 /// \param IncExpr Increment expression for loop control variable.
3688 /// \param BodyGen Generator for the inner body of the inner loop.
3689 /// \param PostIncGen Genrator for post-increment code (required for ordered
3690 /// loop directvies).
3692 const OMPExecutableDirective &S, bool RequiresCleanup,
3693 const Expr *LoopCond, const Expr *IncExpr,
3694 const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
3695 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen);
3696
3698 /// Emit initial code for loop counters of loop-based directives.
3700 OMPPrivateScope &LoopScope);
3701
3702 /// Helper for the OpenMP loop directives.
3704
3705 /// Emit code for the worksharing loop-based directive.
3706 /// \return true, if this construct has any lastprivate clause, false -
3707 /// otherwise.
3709 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
3710 const CodeGenDispatchBoundsTy &CGDispatchBounds);
3711
3712 /// Emit code for the distribute loop-based directive.
3714 const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr);
3715
3716 /// Helpers for the OpenMP loop directives.
3719 const OMPLoopDirective &D,
3720 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen);
3721
3722 /// Emits the lvalue for the expression with possibly captured variable.
3724
3725private:
3726 /// Helpers for blocks.
3727 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
3728
3729 /// struct with the values to be passed to the OpenMP loop-related functions
3730 struct OMPLoopArguments {
3731 /// loop lower bound
3733 /// loop upper bound
3735 /// loop stride
3737 /// isLastIteration argument for runtime functions
3739 /// Chunk value generated by sema
3740 llvm::Value *Chunk = nullptr;
3741 /// EnsureUpperBound
3742 Expr *EUB = nullptr;
3743 /// IncrementExpression
3744 Expr *IncExpr = nullptr;
3745 /// Loop initialization
3746 Expr *Init = nullptr;
3747 /// Loop exit condition
3748 Expr *Cond = nullptr;
3749 /// Update of LB after a whole chunk has been executed
3750 Expr *NextLB = nullptr;
3751 /// Update of UB after a whole chunk has been executed
3752 Expr *NextUB = nullptr;
3753 OMPLoopArguments() = default;
3754 OMPLoopArguments(Address LB, Address UB, Address ST, Address IL,
3755 llvm::Value *Chunk = nullptr, Expr *EUB = nullptr,
3756 Expr *IncExpr = nullptr, Expr *Init = nullptr,
3757 Expr *Cond = nullptr, Expr *NextLB = nullptr,
3758 Expr *NextUB = nullptr)
3759 : LB(LB), UB(UB), ST(ST), IL(IL), Chunk(Chunk), EUB(EUB),
3760 IncExpr(IncExpr), Init(Init), Cond(Cond), NextLB(NextLB),
3761 NextUB(NextUB) {}
3762 };
3763 void EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
3764 const OMPLoopDirective &S, OMPPrivateScope &LoopScope,
3765 const OMPLoopArguments &LoopArgs,
3766 const CodeGenLoopTy &CodeGenLoop,
3767 const CodeGenOrderedTy &CodeGenOrdered);
3768 void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
3769 bool IsMonotonic, const OMPLoopDirective &S,
3770 OMPPrivateScope &LoopScope, bool Ordered,
3771 const OMPLoopArguments &LoopArgs,
3772 const CodeGenDispatchBoundsTy &CGDispatchBounds);
3773 void EmitOMPDistributeOuterLoop(OpenMPDistScheduleClauseKind ScheduleKind,
3774 const OMPLoopDirective &S,
3775 OMPPrivateScope &LoopScope,
3776 const OMPLoopArguments &LoopArgs,
3777 const CodeGenLoopTy &CodeGenLoopContent);
3778 /// Emit code for sections directive.
3779 void EmitSections(const OMPExecutableDirective &S);
3780
3781public:
3782
3783 //===--------------------------------------------------------------------===//
3784 // LValue Expression Emission
3785 //===--------------------------------------------------------------------===//
3786
3787 /// Create a check that a scalar RValue is non-null.
3789
3790 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
3792
3793 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
3794 /// and issue an ErrorUnsupported style diagnostic (using the
3795 /// provided Name).
3797 const char *Name);
3798
3799 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
3800 /// an ErrorUnsupported style diagnostic (using the provided Name).
3802 const char *Name);
3803
3804 /// EmitLValue - Emit code to compute a designator that specifies the location
3805 /// of the expression.
3806 ///
3807 /// This can return one of two things: a simple address or a bitfield
3808 /// reference. In either case, the LLVM Value* in the LValue structure is
3809 /// guaranteed to be an LLVM pointer type.
3810 ///
3811 /// If this returns a bitfield reference, nothing about the pointee type of
3812 /// the LLVM value is known: For example, it may not be a pointer to an
3813 /// integer.
3814 ///
3815 /// If this returns a normal address, and if the lvalue's C type is fixed
3816 /// size, this method guarantees that the returned pointer type will point to
3817 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
3818 /// variable length type, this is not possible.
3819 ///
3821 KnownNonNull_t IsKnownNonNull = NotKnownNonNull);
3822
3823private:
3824 LValue EmitLValueHelper(const Expr *E, KnownNonNull_t IsKnownNonNull);
3825
3826public:
3827 /// Same as EmitLValue but additionally we generate checking code to
3828 /// guard against undefined behavior. This is only suitable when we know
3829 /// that the address will be used to access the object.
3831
3833 SourceLocation Loc);
3834
3835 void EmitAtomicInit(Expr *E, LValue lvalue);
3836
3838
3841
3843 llvm::AtomicOrdering AO, bool IsVolatile = false,
3845
3846 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
3847
3848 void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
3849 bool IsVolatile, bool isInit);
3850
3851 std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
3852 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
3853 llvm::AtomicOrdering Success =
3854 llvm::AtomicOrdering::SequentiallyConsistent,
3855 llvm::AtomicOrdering Failure =
3856 llvm::AtomicOrdering::SequentiallyConsistent,
3857 bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
3858
3859 void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
3860 const llvm::function_ref<RValue(RValue)> &UpdateOp,
3861 bool IsVolatile);
3862
3863 /// EmitToMemory - Change a scalar value from its value
3864 /// representation to its in-memory representation.
3865 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
3866
3867 /// EmitFromMemory - Change a scalar value from its memory
3868 /// representation to its value representation.
3869 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
3870
3871 /// Check if the scalar \p Value is within the valid range for the given
3872 /// type \p Ty.
3873 ///
3874 /// Returns true if a check is needed (even if the range is unknown).
3875 bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
3876 SourceLocation Loc);
3877
3878 /// EmitLoadOfScalar - Load a scalar value from an address, taking
3879 /// care to appropriately convert from the memory representation to
3880 /// the LLVM value representation.
3881 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
3882 SourceLocation Loc,
3884 bool isNontemporal = false) {
3885 return EmitLoadOfScalar(Addr, Volatile, Ty, Loc, LValueBaseInfo(Source),
3886 CGM.getTBAAAccessInfo(Ty), isNontemporal);
3887 }
3888
3889 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
3890 SourceLocation Loc, LValueBaseInfo BaseInfo,
3891 TBAAAccessInfo TBAAInfo,
3892 bool isNontemporal = false);
3893
3894 /// EmitLoadOfScalar - Load a scalar value from an address, taking
3895 /// care to appropriately convert from the memory representation to
3896 /// the LLVM value representation. The l-value must be a simple
3897 /// l-value.
3898 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
3899
3900 /// EmitStoreOfScalar - Store a scalar value to an address, taking
3901 /// care to appropriately convert from the memory representation to
3902 /// the LLVM value representation.
3903 void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
3904 bool Volatile, QualType Ty,
3906 bool isInit = false, bool isNontemporal = false) {
3907 EmitStoreOfScalar(Value, Addr, Volatile, Ty, LValueBaseInfo(Source),
3908 CGM.getTBAAAccessInfo(Ty), isInit, isNontemporal);
3909 }
3910
3911 void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
3912 bool Volatile, QualType Ty,
3913 LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo,
3914 bool isInit = false, bool isNontemporal = false);
3915
3916 /// EmitStoreOfScalar - Store a scalar value to an address, taking
3917 /// care to appropriately convert from the memory representation to
3918 /// the LLVM value representation. The l-value must be a simple
3919 /// l-value. The isInit flag indicates whether this is an initialization.
3920 /// If so, atomic qualifiers are ignored and the store is always non-atomic.
3921 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
3922
3923 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
3924 /// this method emits the address of the lvalue, then loads the result as an
3925 /// rvalue, returning the rvalue.
3930
3931 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
3932 /// lvalue, where both are guaranteed to the have the same type, and that type
3933 /// is 'Ty'.
3934 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
3937
3938 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
3939 /// as EmitStoreThroughLValue.
3940 ///
3941 /// \param Result [out] - If non-null, this will be set to a Value* for the
3942 /// bit-field contents after the store, appropriate for use as the result of
3943 /// an assignment to the bit-field.
3945 llvm::Value **Result=nullptr);
3946
3947 /// Emit an l-value for an assignment (simple or compound) of complex type.
3951 llvm::Value *&Result);
3952
3953 // Note: only available for agg return types
3956 // Note: only available for agg return types
3958 // Note: only available for agg return types
3966 bool Accessed = false);
3969 bool IsLowerBound = true);
3980
3982
3984
3986 LValueBaseInfo *BaseInfo = nullptr,
3987 TBAAAccessInfo *TBAAInfo = nullptr);
3988
3990 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
3991 ConstantEmission(llvm::Constant *C, bool isReference)
3992 : ValueAndIsReference(C, isReference) {}
3993 public:
3995 static ConstantEmission forReference(llvm::Constant *C) {
3996 return ConstantEmission(C, true);
3997 }
3998 static ConstantEmission forValue(llvm::Constant *C) {
3999 return ConstantEmission(C, false);
4000 }
4001
4002 explicit operator bool() const {
4003 return ValueAndIsReference.getOpaqueValue() != nullptr;
4004 }
4005
4006 bool isReference() const { return ValueAndIsReference.getInt(); }
4008 assert(isReference());
4009 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
4010 refExpr->getType());
4011 }
4012
4013 llvm::Constant *getValue() const {
4014 assert(!isReference());
4015 return ValueAndIsReference.getPointer();
4016 }
4017 };
4018
4021 llvm::Value *emitScalarConstant(const ConstantEmission &Constant, Expr *E);
4022
4026
4028 const ObjCIvarDecl *Ivar);
4030 const ObjCIvarDecl *Ivar);
4034 llvm::Value *ThisValue);
4035
4036 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
4037 /// if the Field is a reference, this will return the address of the reference
4038 /// and not the address of the value stored in the reference.
4040 const FieldDecl* Field);
4041
4043 llvm::Value* Base, const ObjCIvarDecl *Ivar,
4044 unsigned CVRQualifiers);
4045
4050
4057
4058 //===--------------------------------------------------------------------===//
4059 // Scalar Expression Emission
4060 //===--------------------------------------------------------------------===//
4061
4062 /// EmitCall - Generate a call of the given function, expecting the given
4063 /// result type, and using the given argument list which specifies both the
4064 /// LLVM arguments and the types they were derived from.
4065 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
4067 llvm::CallBase **callOrInvoke, bool IsMustTail,
4068 SourceLocation Loc);
4069 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
4071 llvm::CallBase **callOrInvoke = nullptr,
4072 bool IsMustTail = false) {
4073 return EmitCall(CallInfo, Callee, ReturnValue, Args, callOrInvoke,
4074 IsMustTail, SourceLocation());
4075 }
4076 RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E,
4077 ReturnValueSlot ReturnValue, llvm::Value *Chain = nullptr);
4082
4083 void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
4085
4086 llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee,
4087 const Twine &name = "");
4088 llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee,
4090 const Twine &name = "");
4091 llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4092 const Twine &name = "");
4093 llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4095 const Twine &name = "");
4096
4098 getBundlesForFunclet(llvm::Value *Callee);
4099
4100 llvm::CallBase *EmitCallOrInvoke(llvm::FunctionCallee Callee,
4102 const Twine &Name = "");
4103 llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4105 const Twine &name = "");
4106 llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4107 const Twine &name = "");
4108 void EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4110
4112 NestedNameSpecifier *Qual,
4113 llvm::Type *Ty);
4114
4117 const CXXRecordDecl *RD);
4118
4119 // Return the copy constructor name with the prefix "__copy_constructor_"
4120 // removed.