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 "CGLoopInfo.h"
18#include "CGValue.h"
19#include "CodeGenModule.h"
20#include "EHScopeStack.h"
21#include "SanitizerHandler.h"
22#include "VarBypassDetector.h"
23#include "clang/AST/CharUnits.h"
24#include "clang/AST/CurrentSourceLocExprScope.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
27#include "clang/AST/ExprOpenMP.h"
28#include "clang/AST/StmtOpenACC.h"
29#include "clang/AST/StmtOpenMP.h"
30#include "clang/AST/StmtSYCL.h"
31#include "clang/AST/Type.h"
32#include "clang/Basic/ABI.h"
33#include "clang/Basic/CapturedStmt.h"
34#include "clang/Basic/CodeGenOptions.h"
35#include "clang/Basic/OpenMPKinds.h"
36#include "clang/Basic/TargetInfo.h"
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/DenseMap.h"
39#include "llvm/ADT/MapVector.h"
40#include "llvm/ADT/SmallVector.h"
41#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
42#include "llvm/IR/Instructions.h"
43#include "llvm/IR/ValueHandle.h"
44#include "llvm/Support/Debug.h"
45#include "llvm/Transforms/Utils/SanitizerStats.h"
46#include <optional>
47
48namespace llvm {
49class BasicBlock;
50class ConvergenceControlInst;
51class LLVMContext;
52class MDNode;
53class SwitchInst;
54class Twine;
55class Value;
56class CanonicalLoopInfo;
57} // namespace llvm
58
59namespace clang {
60class ASTContext;
61class CXXDestructorDecl;
62class CXXForRangeStmt;
63class CXXTryStmt;
64class Decl;
65class LabelDecl;
66class FunctionDecl;
67class FunctionProtoType;
68class LabelStmt;
69class ObjCContainerDecl;
70class ObjCInterfaceDecl;
71class ObjCIvarDecl;
72class ObjCMethodDecl;
73class ObjCImplementationDecl;
74class ObjCPropertyImplDecl;
75class TargetInfo;
76class VarDecl;
77class ObjCForCollectionStmt;
78class ObjCAtTryStmt;
79class ObjCAtThrowStmt;
80class ObjCAtSynchronizedStmt;
81class ObjCAutoreleasePoolStmt;
82class OMPUseDevicePtrClause;
83class OMPUseDeviceAddrClause;
84class SVETypeFlags;
85class OMPExecutableDirective;
86
87namespace analyze_os_log {
88class OSLogBufferLayout;
89}
90
91namespace CodeGen {
92class CodeGenTypes;
93class CodeGenPGO;
94class CGCallee;
95class CGFunctionInfo;
96class CGBlockInfo;
97class CGCXXABI;
98class BlockByrefHelpers;
99class BlockByrefInfo;
100class BlockFieldFlags;
101class RegionCodeGenTy;
102class TargetCodeGenInfo;
103struct OMPTaskDataTy;
104struct CGCoroData;
105
106// clang-format off
107/// The kind of evaluation to perform on values of a particular
108/// type. Basically, is the code in CGExprScalar, CGExprComplex, or
109/// CGExprAgg?
110///
111/// TODO: should vectors maybe be split out into their own thing?
112enum TypeEvaluationKind {
113 TEK_Scalar,
114 TEK_Complex,
115 TEK_Aggregate
116};
117// clang-format on
118
119/// Helper class with most of the code for saving a value for a
120/// conditional expression cleanup.
121struct DominatingLLVMValue {
122 typedef llvm::PointerIntPair<llvm::Value *, 1, bool> saved_type;
123
124 /// Answer whether the given value needs extra work to be saved.
125 static bool needsSaving(llvm::Value *value) {
126 if (!value)
127 return false;
128
129 // If it's not an instruction, we don't need to save.
130 if (!isa<llvm::Instruction>(Val: value))
131 return false;
132
133 // If it's an instruction in the entry block, we don't need to save.
134 llvm::BasicBlock *block = cast<llvm::Instruction>(Val: value)->getParent();
135 return (block != &block->getParent()->getEntryBlock());
136 }
137
138 static saved_type save(CodeGenFunction &CGF, llvm::Value *value);
139 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value);
140};
141
142/// A partial specialization of DominatingValue for llvm::Values that
143/// might be llvm::Instructions.
144template <class T> struct DominatingPointer<T, true> : DominatingLLVMValue {
145 typedef T *type;
146 static type restore(CodeGenFunction &CGF, saved_type value) {
147 return static_cast<T *>(DominatingLLVMValue::restore(CGF, value));
148 }
149};
150
151/// A specialization of DominatingValue for Address.
152template <> struct DominatingValue<Address> {
153 typedef Address type;
154
155 struct saved_type {
156 DominatingLLVMValue::saved_type BasePtr;
157 llvm::Type *ElementType;
158 CharUnits Alignment;
159 DominatingLLVMValue::saved_type Offset;
160 llvm::PointerType *EffectiveType;
161 };
162
163 static bool needsSaving(type value) {
164 if (DominatingLLVMValue::needsSaving(value: value.getBasePointer()) ||
165 DominatingLLVMValue::needsSaving(value: value.getOffset()))
166 return true;
167 return false;
168 }
169 static saved_type save(CodeGenFunction &CGF, type value) {
170 return {.BasePtr: DominatingLLVMValue::save(CGF, value: value.getBasePointer()),
171 .ElementType: value.getElementType(), .Alignment: value.getAlignment(),
172 .Offset: DominatingLLVMValue::save(CGF, value: value.getOffset()), .EffectiveType: value.getType()};
173 }
174 static type restore(CodeGenFunction &CGF, saved_type value) {
175 return Address(DominatingLLVMValue::restore(CGF, value: value.BasePtr),
176 value.ElementType, value.Alignment, CGPointerAuthInfo(),
177 DominatingLLVMValue::restore(CGF, value: value.Offset));
178 }
179};
180
181/// A specialization of DominatingValue for RValue.
182template <> struct DominatingValue<RValue> {
183 typedef RValue type;
184 class saved_type {
185 enum Kind {
186 ScalarLiteral,
187 ScalarAddress,
188 AggregateLiteral,
189 AggregateAddress,
190 ComplexAddress
191 };
192 union {
193 struct {
194 DominatingLLVMValue::saved_type first, second;
195 } Vals;
196 DominatingValue<Address>::saved_type AggregateAddr;
197 };
198 LLVM_PREFERRED_TYPE(Kind)
199 unsigned K : 3;
200
201 saved_type(DominatingLLVMValue::saved_type Val1, unsigned K)
202 : Vals{.first: Val1, .second: DominatingLLVMValue::saved_type()}, K(K) {}
203
204 saved_type(DominatingLLVMValue::saved_type Val1,
205 DominatingLLVMValue::saved_type Val2)
206 : Vals{.first: Val1, .second: Val2}, K(ComplexAddress) {}
207
208 saved_type(DominatingValue<Address>::saved_type AggregateAddr, unsigned K)
209 : AggregateAddr(AggregateAddr), K(K) {}
210
211 public:
212 static bool needsSaving(RValue value);
213 static saved_type save(CodeGenFunction &CGF, RValue value);
214 RValue restore(CodeGenFunction &CGF);
215
216 // implementations in CGCleanup.cpp
217 };
218
219 static bool needsSaving(type value) { return saved_type::needsSaving(value); }
220 static saved_type save(CodeGenFunction &CGF, type value) {
221 return saved_type::save(CGF, value);
222 }
223 static type restore(CodeGenFunction &CGF, saved_type value) {
224 return value.restore(CGF);
225 }
226};
227
228/// A scoped helper to set the current source atom group for
229/// CGDebugInfo::addInstToCurrentSourceAtom. A source atom is a source construct
230/// that is "interesting" for debug stepping purposes. We use an atom group
231/// number to track the instruction(s) that implement the functionality for the
232/// atom, plus backup instructions/source locations.
233class ApplyAtomGroup {
234 uint64_t OriginalAtom = 0;
235 CGDebugInfo *DI = nullptr;
236
237 ApplyAtomGroup(const ApplyAtomGroup &) = delete;
238 void operator=(const ApplyAtomGroup &) = delete;
239
240public:
241 ApplyAtomGroup(CGDebugInfo *DI);
242 ~ApplyAtomGroup();
243};
244
245/// CodeGenFunction - This class organizes the per-function state that is used
246/// while generating LLVM code.
247class CodeGenFunction : public CodeGenTypeCache {
248 CodeGenFunction(const CodeGenFunction &) = delete;
249 void operator=(const CodeGenFunction &) = delete;
250
251 friend class CGCXXABI;
252
253public:
254 /// A jump destination is an abstract label, branching to which may
255 /// require a jump out through normal cleanups.
256 struct JumpDest {
257 JumpDest() : Block(nullptr), Index(0) {}
258 JumpDest(llvm::BasicBlock *Block, EHScopeStack::stable_iterator Depth,
259 unsigned Index)
260 : Block(Block), ScopeDepth(Depth), Index(Index) {}
261
262 bool isValid() const { return Block != nullptr; }
263 llvm::BasicBlock *getBlock() const { return Block; }
264 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
265 unsigned getDestIndex() const { return Index; }
266
267 // This should be used cautiously.
268 void setScopeDepth(EHScopeStack::stable_iterator depth) {
269 ScopeDepth = depth;
270 }
271
272 private:
273 llvm::BasicBlock *Block;
274 EHScopeStack::stable_iterator ScopeDepth;
275 unsigned Index;
276 };
277
278 CodeGenModule &CGM; // Per-module state.
279 const TargetInfo &Target;
280
281 // For EH/SEH outlined funclets, this field points to parent's CGF
282 CodeGenFunction *ParentCGF = nullptr;
283
284 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
285 LoopInfoStack LoopStack;
286 CGBuilderTy Builder;
287
288 // Stores variables for which we can't generate correct lifetime markers
289 // because of jumps.
290 VarBypassDetector Bypasses;
291
292 /// List of recently emitted OMPCanonicalLoops.
293 ///
294 /// Since OMPCanonicalLoops are nested inside other statements (in particular
295 /// CapturedStmt generated by OMPExecutableDirective and non-perfectly nested
296 /// loops), we cannot directly call OMPEmitOMPCanonicalLoop and receive its
297 /// llvm::CanonicalLoopInfo. Instead, we call EmitStmt and any
298 /// OMPEmitOMPCanonicalLoop called by it will add its CanonicalLoopInfo to
299 /// this stack when done. Entering a new loop requires clearing this list; it
300 /// either means we start parsing a new loop nest (in which case the previous
301 /// loop nest goes out of scope) or a second loop in the same level in which
302 /// case it would be ambiguous into which of the two (or more) loops the loop
303 /// nest would extend.
304 SmallVector<llvm::CanonicalLoopInfo *, 4> OMPLoopNestStack;
305
306 /// Stack to track the controlled convergence tokens.
307 SmallVector<llvm::ConvergenceControlInst *, 4> ConvergenceTokenStack;
308
309 /// Number of nested loop to be consumed by the last surrounding
310 /// loop-associated directive.
311 int ExpectedOMPLoopDepth = 0;
312
313 // CodeGen lambda for loops and support for ordered clause
314 typedef llvm::function_ref<void(CodeGenFunction &, const OMPLoopDirective &,
315 JumpDest)>
316 CodeGenLoopTy;
317 typedef llvm::function_ref<void(CodeGenFunction &, SourceLocation,
318 const unsigned, const bool)>
319 CodeGenOrderedTy;
320
321 // Codegen lambda for loop bounds in worksharing loop constructs
322 typedef llvm::function_ref<std::pair<LValue, LValue>(
323 CodeGenFunction &, const OMPExecutableDirective &S)>
324 CodeGenLoopBoundsTy;
325
326 // Codegen lambda for loop bounds in dispatch-based loop implementation
327 typedef llvm::function_ref<std::pair<llvm::Value *, llvm::Value *>(
328 CodeGenFunction &, const OMPExecutableDirective &S, Address LB,
329 Address UB)>
330 CodeGenDispatchBoundsTy;
331
332 /// CGBuilder insert helper. This function is called after an
333 /// instruction is created using Builder.
334 void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
335 llvm::BasicBlock::iterator InsertPt) const;
336
337 /// CurFuncDecl - Holds the Decl for the current outermost
338 /// non-closure context.
339 const Decl *CurFuncDecl = nullptr;
340 /// CurCodeDecl - This is the inner-most code context, which includes blocks.
341 const Decl *CurCodeDecl = nullptr;
342 const CGFunctionInfo *CurFnInfo = nullptr;
343 QualType FnRetTy;
344 llvm::Function *CurFn = nullptr;
345
346 /// If a cast expression is being visited, this holds the current cast's
347 /// expression.
348 const CastExpr *CurCast = nullptr;
349
350 /// Save Parameter Decl for coroutine.
351 llvm::SmallVector<const ParmVarDecl *, 4> FnArgs;
352
353 // Holds coroutine data if the current function is a coroutine. We use a
354 // wrapper to manage its lifetime, so that we don't have to define CGCoroData
355 // in this header.
356 struct CGCoroInfo {
357 std::unique_ptr<CGCoroData> Data;
358 bool InSuspendBlock = false;
359 CGCoroInfo();
360 ~CGCoroInfo();
361 };
362 CGCoroInfo CurCoro;
363
364 bool isCoroutine() const { return CurCoro.Data != nullptr; }
365
366 bool inSuspendBlock() const {
367 return isCoroutine() && CurCoro.InSuspendBlock;
368 }
369
370 // Holds FramePtr for await_suspend wrapper generation,
371 // so that __builtin_coro_frame call can be lowered
372 // directly to value of its second argument
373 struct AwaitSuspendWrapperInfo {
374 llvm::Value *FramePtr = nullptr;
375 };
376 AwaitSuspendWrapperInfo CurAwaitSuspendWrapper;
377
378 // Generates wrapper function for `llvm.coro.await.suspend.*` intrinisics.
379 // It encapsulates SuspendExpr in a function, to separate it's body
380 // from the main coroutine to avoid miscompilations. Intrinisic
381 // is lowered to this function call in CoroSplit pass
382 // Function signature is:
383 // <type> __await_suspend_wrapper_<name>(ptr %awaiter, ptr %hdl)
384 // where type is one of (void, i1, ptr)
385 llvm::Function *generateAwaitSuspendWrapper(Twine const &CoroName,
386 Twine const &SuspendPointName,
387 CoroutineSuspendExpr const &S);
388
389 /// CurGD - The GlobalDecl for the current function being compiled.
390 GlobalDecl CurGD;
391
392 /// PrologueCleanupDepth - The cleanup depth enclosing all the
393 /// cleanups associated with the parameters.
394 EHScopeStack::stable_iterator PrologueCleanupDepth;
395
396 /// ReturnBlock - Unified return block.
397 JumpDest ReturnBlock;
398
399 /// ReturnValue - The temporary alloca to hold the return
400 /// value. This is invalid iff the function has no return value.
401 Address ReturnValue = Address::invalid();
402
403 /// ReturnValuePointer - The temporary alloca to hold a pointer to sret.
404 /// This is invalid if sret is not in use.
405 Address ReturnValuePointer = Address::invalid();
406
407 /// If a return statement is being visited, this holds the return statment's
408 /// result expression.
409 const Expr *RetExpr = nullptr;
410
411 /// Return true if a label was seen in the current scope.
412 bool hasLabelBeenSeenInCurrentScope() const {
413 if (CurLexicalScope)
414 return CurLexicalScope->hasLabels();
415 return !LabelMap.empty();
416 }
417
418 /// AllocaInsertPoint - This is an instruction in the entry block before which
419 /// we prefer to insert allocas.
420 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
421
422private:
423 /// PostAllocaInsertPt - This is a place in the prologue where code can be
424 /// inserted that will be dominated by all the static allocas. This helps
425 /// achieve two things:
426 /// 1. Contiguity of all static allocas (within the prologue) is maintained.
427 /// 2. All other prologue code (which are dominated by static allocas) do
428 /// appear in the source order immediately after all static allocas.
429 ///
430 /// PostAllocaInsertPt will be lazily created when it is *really* required.
431 llvm::AssertingVH<llvm::Instruction> PostAllocaInsertPt = nullptr;
432
433public:
434 /// Return PostAllocaInsertPt. If it is not yet created, then insert it
435 /// immediately after AllocaInsertPt.
436 llvm::Instruction *getPostAllocaInsertPoint() {
437 if (!PostAllocaInsertPt) {
438 assert(AllocaInsertPt &&
439 "Expected static alloca insertion point at function prologue");
440 assert(AllocaInsertPt->getParent()->isEntryBlock() &&
441 "EBB should be entry block of the current code gen function");
442 PostAllocaInsertPt = AllocaInsertPt->clone();
443 PostAllocaInsertPt->setName("postallocapt");
444 PostAllocaInsertPt->insertAfter(InsertPos: AllocaInsertPt->getIterator());
445 }
446
447 return PostAllocaInsertPt;
448 }
449
450 /// API for captured statement code generation.
451 class CGCapturedStmtInfo {
452 public:
453 explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
454 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
455 explicit CGCapturedStmtInfo(const CapturedStmt &S,
456 CapturedRegionKind K = CR_Default)
457 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
458
459 RecordDecl::field_iterator Field =
460 S.getCapturedRecordDecl()->field_begin();
461 for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
462 E = S.capture_end();
463 I != E; ++I, ++Field) {
464 if (I->capturesThis())
465 CXXThisFieldDecl = *Field;
466 else if (I->capturesVariable())
467 CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
468 else if (I->capturesVariableByCopy())
469 CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
470 }
471 }
472
473 virtual ~CGCapturedStmtInfo();
474
475 CapturedRegionKind getKind() const { return Kind; }
476
477 virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
478 // Retrieve the value of the context parameter.
479 virtual llvm::Value *getContextValue() const { return ThisValue; }
480
481 /// Lookup the captured field decl for a variable.
482 virtual const FieldDecl *lookup(const VarDecl *VD) const {
483 return CaptureFields.lookup(Val: VD->getCanonicalDecl());
484 }
485
486 bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
487 virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
488
489 static bool classof(const CGCapturedStmtInfo *) { return true; }
490
491 /// Emit the captured statement body.
492 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
493 CGF.incrementProfileCounter(S);
494 CGF.EmitStmt(S);
495 }
496
497 /// Get the name of the capture helper.
498 virtual StringRef getHelperName() const { return "__captured_stmt"; }
499
500 /// Get the CaptureFields
501 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> getCaptureFields() {
502 return CaptureFields;
503 }
504
505 private:
506 /// The kind of captured statement being generated.
507 CapturedRegionKind Kind;
508
509 /// Keep the map between VarDecl and FieldDecl.
510 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
511
512 /// The base address of the captured record, passed in as the first
513 /// argument of the parallel region function.
514 llvm::Value *ThisValue;
515
516 /// Captured 'this' type.
517 FieldDecl *CXXThisFieldDecl;
518 };
519 CGCapturedStmtInfo *CapturedStmtInfo = nullptr;
520
521 /// RAII for correct setting/restoring of CapturedStmtInfo.
522 class CGCapturedStmtRAII {
523 private:
524 CodeGenFunction &CGF;
525 CGCapturedStmtInfo *PrevCapturedStmtInfo;
526
527 public:
528 CGCapturedStmtRAII(CodeGenFunction &CGF,
529 CGCapturedStmtInfo *NewCapturedStmtInfo)
530 : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
531 CGF.CapturedStmtInfo = NewCapturedStmtInfo;
532 }
533 ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
534 };
535
536 /// An abstract representation of regular/ObjC call/message targets.
537 class AbstractCallee {
538 /// The function declaration of the callee.
539 const Decl *CalleeDecl;
540
541 public:
542 AbstractCallee() : CalleeDecl(nullptr) {}
543 AbstractCallee(const FunctionDecl *FD) : CalleeDecl(FD) {}
544 AbstractCallee(const ObjCMethodDecl *OMD) : CalleeDecl(OMD) {}
545 bool hasFunctionDecl() const {
546 return isa_and_nonnull<FunctionDecl>(Val: CalleeDecl);
547 }
548 const Decl *getDecl() const { return CalleeDecl; }
549 unsigned getNumParams() const {
550 if (const auto *FD = dyn_cast<FunctionDecl>(Val: CalleeDecl))
551 return FD->getNumParams();
552 return cast<ObjCMethodDecl>(Val: CalleeDecl)->param_size();
553 }
554 const ParmVarDecl *getParamDecl(unsigned I) const {
555 if (const auto *FD = dyn_cast<FunctionDecl>(Val: CalleeDecl))
556 return FD->getParamDecl(i: I);
557 return *(cast<ObjCMethodDecl>(Val: CalleeDecl)->param_begin() + I);
558 }
559 };
560
561 /// Sanitizers enabled for this function.
562 SanitizerSet SanOpts;
563
564 /// True if CodeGen currently emits code implementing sanitizer checks.
565 bool IsSanitizerScope = false;
566
567 /// RAII object to set/unset CodeGenFunction::IsSanitizerScope.
568 class SanitizerScope {
569 CodeGenFunction *CGF;
570
571 public:
572 SanitizerScope(CodeGenFunction *CGF);
573 ~SanitizerScope();
574 };
575
576 /// In C++, whether we are code generating a thunk. This controls whether we
577 /// should emit cleanups.
578 bool CurFuncIsThunk = false;
579
580 /// In ARC, whether we should autorelease the return value.
581 bool AutoreleaseResult = false;
582
583 /// Whether we processed a Microsoft-style asm block during CodeGen. These can
584 /// potentially set the return value.
585 bool SawAsmBlock = false;
586
587 GlobalDecl CurSEHParent;
588
589 /// True if the current function is an outlined SEH helper. This can be a
590 /// finally block or filter expression.
591 bool IsOutlinedSEHHelper = false;
592
593 /// True if CodeGen currently emits code inside presereved access index
594 /// region.
595 bool IsInPreservedAIRegion = false;
596
597 /// True if the current statement has nomerge attribute.
598 bool InNoMergeAttributedStmt = false;
599
600 /// True if the current statement has noinline attribute.
601 bool InNoInlineAttributedStmt = false;
602
603 /// True if the current statement has always_inline attribute.
604 bool InAlwaysInlineAttributedStmt = false;
605
606 /// True if the current statement has noconvergent attribute.
607 bool InNoConvergentAttributedStmt = false;
608
609 /// HLSL Branch attribute.
610 HLSLControlFlowHintAttr::Spelling HLSLControlFlowAttr =
611 HLSLControlFlowHintAttr::SpellingNotCalculated;
612
613 // The CallExpr within the current statement that the musttail attribute
614 // applies to. nullptr if there is no 'musttail' on the current statement.
615 const CallExpr *MustTailCall = nullptr;
616
617 /// Returns true if a function must make progress, which means the
618 /// mustprogress attribute can be added.
619 bool checkIfFunctionMustProgress() {
620 if (CGM.getCodeGenOpts().getFiniteLoops() ==
621 CodeGenOptions::FiniteLoopsKind::Never)
622 return false;
623
624 // C++11 and later guarantees that a thread eventually will do one of the
625 // following (C++11 [intro.multithread]p24 and C++17 [intro.progress]p1):
626 // - terminate,
627 // - make a call to a library I/O function,
628 // - perform an access through a volatile glvalue, or
629 // - perform a synchronization operation or an atomic operation.
630 //
631 // Hence each function is 'mustprogress' in C++11 or later.
632 return getLangOpts().CPlusPlus11;
633 }
634
635 /// Returns true if a loop must make progress, which means the mustprogress
636 /// attribute can be added. \p HasConstantCond indicates whether the branch
637 /// condition is a known constant.
638 bool checkIfLoopMustProgress(const Expr *, bool HasEmptyBody);
639
640 const CodeGen::CGBlockInfo *BlockInfo = nullptr;
641 llvm::Value *BlockPointer = nullptr;
642
643 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
644 FieldDecl *LambdaThisCaptureField = nullptr;
645
646 /// A mapping from NRVO variables to the flags used to indicate
647 /// when the NRVO has been applied to this variable.
648 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
649
650 EHScopeStack EHStack;
651 llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
652
653 // A stack of cleanups which were added to EHStack but have to be deactivated
654 // later before being popped or emitted. These are usually deactivated on
655 // exiting a `CleanupDeactivationScope` scope. For instance, after a
656 // full-expr.
657 //
658 // These are specially useful for correctly emitting cleanups while
659 // encountering branches out of expression (through stmt-expr or coroutine
660 // suspensions).
661 struct DeferredDeactivateCleanup {
662 EHScopeStack::stable_iterator Cleanup;
663 llvm::Instruction *DominatingIP;
664 };
665 llvm::SmallVector<DeferredDeactivateCleanup> DeferredDeactivationCleanupStack;
666
667 // Enters a new scope for capturing cleanups which are deferred to be
668 // deactivated, all of which will be deactivated once the scope is exited.
669 struct CleanupDeactivationScope {
670 CodeGenFunction &CGF;
671 size_t OldDeactivateCleanupStackSize;
672 bool Deactivated;
673 CleanupDeactivationScope(CodeGenFunction &CGF)
674 : CGF(CGF), OldDeactivateCleanupStackSize(
675 CGF.DeferredDeactivationCleanupStack.size()),
676 Deactivated(false) {}
677
678 void ForceDeactivate() {
679 assert(!Deactivated && "Deactivating already deactivated scope");
680 auto &Stack = CGF.DeferredDeactivationCleanupStack;
681 for (size_t I = Stack.size(); I > OldDeactivateCleanupStackSize; I--) {
682 CGF.DeactivateCleanupBlock(Cleanup: Stack[I - 1].Cleanup,
683 DominatingIP: Stack[I - 1].DominatingIP);
684 Stack[I - 1].DominatingIP->eraseFromParent();
685 }
686 Stack.resize(N: OldDeactivateCleanupStackSize);
687 Deactivated = true;
688 }
689
690 ~CleanupDeactivationScope() {
691 if (Deactivated)
692 return;
693 ForceDeactivate();
694 }
695 };
696
697 llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
698
699 llvm::Instruction *CurrentFuncletPad = nullptr;
700
701 class CallLifetimeEnd final : public EHScopeStack::Cleanup {
702 bool isRedundantBeforeReturn() override { return true; }
703
704 llvm::Value *Addr;
705
706 public:
707 CallLifetimeEnd(RawAddress addr) : Addr(addr.getPointer()) {}
708
709 void Emit(CodeGenFunction &CGF, Flags flags) override {
710 CGF.EmitLifetimeEnd(Addr);
711 }
712 };
713
714 // We are using objects of this 'cleanup' class to emit fake.use calls
715 // for -fextend-variable-liveness. They are placed at the end of a variable's
716 // scope analogous to lifetime markers.
717 class FakeUse final : public EHScopeStack::Cleanup {
718 Address Addr;
719
720 public:
721 FakeUse(Address addr) : Addr(addr) {}
722
723 void Emit(CodeGenFunction &CGF, Flags flags) override {
724 CGF.EmitFakeUse(Addr);
725 }
726 };
727
728 /// Header for data within LifetimeExtendedCleanupStack.
729 struct alignas(uint64_t) LifetimeExtendedCleanupHeader {
730 /// The size of the following cleanup object.
731 unsigned Size;
732 /// The kind of cleanup to push.
733 LLVM_PREFERRED_TYPE(CleanupKind)
734 unsigned Kind : 31;
735 /// Whether this is a conditional cleanup.
736 LLVM_PREFERRED_TYPE(bool)
737 unsigned IsConditional : 1;
738
739 size_t getSize() const { return Size; }
740 CleanupKind getKind() const { return (CleanupKind)Kind; }
741 bool isConditional() const { return IsConditional; }
742 };
743
744 /// i32s containing the indexes of the cleanup destinations.
745 RawAddress NormalCleanupDest = RawAddress::invalid();
746
747 unsigned NextCleanupDestIndex = 1;
748
749 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
750 llvm::BasicBlock *EHResumeBlock = nullptr;
751
752 /// The exception slot. All landing pads write the current exception pointer
753 /// into this alloca.
754 llvm::Value *ExceptionSlot = nullptr;
755
756 /// The selector slot. Under the MandatoryCleanup model, all landing pads
757 /// write the current selector value into this alloca.
758 llvm::AllocaInst *EHSelectorSlot = nullptr;
759
760 /// A stack of exception code slots. Entering an __except block pushes a slot
761 /// on the stack and leaving pops one. The __exception_code() intrinsic loads
762 /// a value from the top of the stack.
763 SmallVector<Address, 1> SEHCodeSlotStack;
764
765 /// Value returned by __exception_info intrinsic.
766 llvm::Value *SEHInfo = nullptr;
767
768 /// Emits a landing pad for the current EH stack.
769 llvm::BasicBlock *EmitLandingPad();
770
771 llvm::BasicBlock *getInvokeDestImpl();
772
773 /// Parent loop-based directive for scan directive.
774 const OMPExecutableDirective *OMPParentLoopDirectiveForScan = nullptr;
775 llvm::BasicBlock *OMPBeforeScanBlock = nullptr;
776 llvm::BasicBlock *OMPAfterScanBlock = nullptr;
777 llvm::BasicBlock *OMPScanExitBlock = nullptr;
778 llvm::BasicBlock *OMPScanDispatch = nullptr;
779 bool OMPFirstScanLoop = false;
780
781 /// Manages parent directive for scan directives.
782 class ParentLoopDirectiveForScanRegion {
783 CodeGenFunction &CGF;
784 const OMPExecutableDirective *ParentLoopDirectiveForScan;
785
786 public:
787 ParentLoopDirectiveForScanRegion(
788 CodeGenFunction &CGF,
789 const OMPExecutableDirective &ParentLoopDirectiveForScan)
790 : CGF(CGF),
791 ParentLoopDirectiveForScan(CGF.OMPParentLoopDirectiveForScan) {
792 CGF.OMPParentLoopDirectiveForScan = &ParentLoopDirectiveForScan;
793 }
794 ~ParentLoopDirectiveForScanRegion() {
795 CGF.OMPParentLoopDirectiveForScan = ParentLoopDirectiveForScan;
796 }
797 };
798
799 template <class T>
800 typename DominatingValue<T>::saved_type saveValueInCond(T value) {
801 return DominatingValue<T>::save(*this, value);
802 }
803
804 class CGFPOptionsRAII {
805 public:
806 CGFPOptionsRAII(CodeGenFunction &CGF, FPOptions FPFeatures);
807 CGFPOptionsRAII(CodeGenFunction &CGF, const Expr *E);
808 ~CGFPOptionsRAII();
809
810 private:
811 void ConstructorHelper(FPOptions FPFeatures);
812 CodeGenFunction &CGF;
813 FPOptions OldFPFeatures;
814 llvm::fp::ExceptionBehavior OldExcept;
815 llvm::RoundingMode OldRounding;
816 std::optional<CGBuilderTy::FastMathFlagGuard> FMFGuard;
817 };
818 FPOptions CurFPFeatures;
819
820 class CGAtomicOptionsRAII {
821 public:
822 CGAtomicOptionsRAII(CodeGenModule &CGM_, AtomicOptions AO)
823 : CGM(CGM_), SavedAtomicOpts(CGM.getAtomicOpts()) {
824 CGM.setAtomicOpts(AO);
825 }
826 CGAtomicOptionsRAII(CodeGenModule &CGM_, const AtomicAttr *AA)
827 : CGM(CGM_), SavedAtomicOpts(CGM.getAtomicOpts()) {
828 if (!AA)
829 return;
830 AtomicOptions AO = SavedAtomicOpts;
831 for (auto Option : AA->atomicOptions()) {
832 switch (Option) {
833 case AtomicAttr::remote_memory:
834 AO.remote_memory = true;
835 break;
836 case AtomicAttr::no_remote_memory:
837 AO.remote_memory = false;
838 break;
839 case AtomicAttr::fine_grained_memory:
840 AO.fine_grained_memory = true;
841 break;
842 case AtomicAttr::no_fine_grained_memory:
843 AO.fine_grained_memory = false;
844 break;
845 case AtomicAttr::ignore_denormal_mode:
846 AO.ignore_denormal_mode = true;
847 break;
848 case AtomicAttr::no_ignore_denormal_mode:
849 AO.ignore_denormal_mode = false;
850 break;
851 }
852 }
853 CGM.setAtomicOpts(AO);
854 }
855
856 CGAtomicOptionsRAII(const CGAtomicOptionsRAII &) = delete;
857 CGAtomicOptionsRAII &operator=(const CGAtomicOptionsRAII &) = delete;
858 ~CGAtomicOptionsRAII() { CGM.setAtomicOpts(SavedAtomicOpts); }
859
860 private:
861 CodeGenModule &CGM;
862 AtomicOptions SavedAtomicOpts;
863 };
864
865public:
866 /// ObjCEHValueStack - Stack of Objective-C exception values, used for
867 /// rethrows.
868 SmallVector<llvm::Value *, 8> ObjCEHValueStack;
869
870 /// A class controlling the emission of a finally block.
871 class FinallyInfo {
872 /// Where the catchall's edge through the cleanup should go.
873 JumpDest RethrowDest;
874
875 /// A function to call to enter the catch.
876 llvm::FunctionCallee BeginCatchFn;
877
878 /// An i1 variable indicating whether or not the @finally is
879 /// running for an exception.
880 llvm::AllocaInst *ForEHVar = nullptr;
881
882 /// An i8* variable into which the exception pointer to rethrow
883 /// has been saved.
884 llvm::AllocaInst *SavedExnVar = nullptr;
885
886 public:
887 void enter(CodeGenFunction &CGF, const Stmt *Finally,
888 llvm::FunctionCallee beginCatchFn,
889 llvm::FunctionCallee endCatchFn, llvm::FunctionCallee rethrowFn);
890 void exit(CodeGenFunction &CGF);
891 };
892
893 /// Returns true inside SEH __try blocks.
894 bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
895
896 /// Returns true while emitting a cleanuppad.
897 bool isCleanupPadScope() const {
898 return CurrentFuncletPad && isa<llvm::CleanupPadInst>(Val: CurrentFuncletPad);
899 }
900
901 /// pushFullExprCleanup - Push a cleanup to be run at the end of the
902 /// current full-expression. Safe against the possibility that
903 /// we're currently inside a conditionally-evaluated expression.
904 template <class T, class... As>
905 void pushFullExprCleanup(CleanupKind kind, As... A) {
906 // If we're not in a conditional branch, or if none of the
907 // arguments requires saving, then use the unconditional cleanup.
908 if (!isInConditionalBranch())
909 return EHStack.pushCleanup<T>(kind, A...);
910
911 // Stash values in a tuple so we can guarantee the order of saves.
912 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
913 SavedTuple Saved{saveValueInCond(A)...};
914
915 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
916 EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
917 initFullExprCleanup();
918 }
919
920 /// Queue a cleanup to be pushed after finishing the current full-expression,
921 /// potentially with an active flag.
922 template <class T, class... As>
923 void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
924 if (!isInConditionalBranch())
925 return pushCleanupAfterFullExprWithActiveFlag<T>(
926 Kind, RawAddress::invalid(), A...);
927
928 RawAddress ActiveFlag = createCleanupActiveFlag();
929 assert(!DominatingValue<Address>::needsSaving(ActiveFlag) &&
930 "cleanup active flag should never need saving");
931
932 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
933 SavedTuple Saved{saveValueInCond(A)...};
934
935 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
936 pushCleanupAfterFullExprWithActiveFlag<CleanupType>(Kind, ActiveFlag,
937 Saved);
938 }
939
940 template <class T, class... As>
941 void pushCleanupAfterFullExprWithActiveFlag(CleanupKind Kind,
942 RawAddress ActiveFlag, As... A) {
943 LifetimeExtendedCleanupHeader Header = {.Size: sizeof(T), .Kind: Kind,
944 .IsConditional: ActiveFlag.isValid()};
945
946 size_t OldSize = LifetimeExtendedCleanupStack.size();
947 LifetimeExtendedCleanupStack.resize(
948 N: LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size +
949 (Header.IsConditional ? sizeof(ActiveFlag) : 0));
950
951 static_assert((alignof(LifetimeExtendedCleanupHeader) == alignof(T)) &&
952 (alignof(T) == alignof(RawAddress)),
953 "Cleanup will be allocated on misaligned address");
954 char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
955 new (Buffer) LifetimeExtendedCleanupHeader(Header);
956 new (Buffer + sizeof(Header)) T(A...);
957 if (Header.IsConditional)
958 new (Buffer + sizeof(Header) + sizeof(T)) RawAddress(ActiveFlag);
959 }
960
961 // Push a cleanup onto EHStack and deactivate it later. It is usually
962 // deactivated when exiting a `CleanupDeactivationScope` (for example: after a
963 // full expression).
964 template <class T, class... As>
965 void pushCleanupAndDeferDeactivation(CleanupKind Kind, As... A) {
966 // Placeholder dominating IP for this cleanup.
967 llvm::Instruction *DominatingIP =
968 Builder.CreateFlagLoad(Addr: llvm::Constant::getNullValue(Ty: Int8PtrTy));
969 EHStack.pushCleanup<T>(Kind, A...);
970 DeferredDeactivationCleanupStack.push_back(
971 Elt: {.Cleanup: EHStack.stable_begin(), .DominatingIP: DominatingIP});
972 }
973
974 /// Set up the last cleanup that was pushed as a conditional
975 /// full-expression cleanup.
976 void initFullExprCleanup() {
977 initFullExprCleanupWithFlag(ActiveFlag: createCleanupActiveFlag());
978 }
979
980 void initFullExprCleanupWithFlag(RawAddress ActiveFlag);
981 RawAddress createCleanupActiveFlag();
982
983 /// PushDestructorCleanup - Push a cleanup to call the
984 /// complete-object destructor of an object of the given type at the
985 /// given address. Does nothing if T is not a C++ class type with a
986 /// non-trivial destructor.
987 void PushDestructorCleanup(QualType T, Address Addr);
988
989 /// PushDestructorCleanup - Push a cleanup to call the
990 /// complete-object variant of the given destructor on the object at
991 /// the given address.
992 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, QualType T,
993 Address Addr);
994
995 /// PopCleanupBlock - Will pop the cleanup entry on the stack and
996 /// process all branch fixups.
997 void PopCleanupBlock(bool FallThroughIsBranchThrough = false,
998 bool ForDeactivation = false);
999
1000 /// DeactivateCleanupBlock - Deactivates the given cleanup block.
1001 /// The block cannot be reactivated. Pops it if it's the top of the
1002 /// stack.
1003 ///
1004 /// \param DominatingIP - An instruction which is known to
1005 /// dominate the current IP (if set) and which lies along
1006 /// all paths of execution between the current IP and the
1007 /// the point at which the cleanup comes into scope.
1008 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
1009 llvm::Instruction *DominatingIP);
1010
1011 /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
1012 /// Cannot be used to resurrect a deactivated cleanup.
1013 ///
1014 /// \param DominatingIP - An instruction which is known to
1015 /// dominate the current IP (if set) and which lies along
1016 /// all paths of execution between the current IP and the
1017 /// the point at which the cleanup comes into scope.
1018 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
1019 llvm::Instruction *DominatingIP);
1020
1021 /// Enters a new scope for capturing cleanups, all of which
1022 /// will be executed once the scope is exited.
1023 class RunCleanupsScope {
1024 EHScopeStack::stable_iterator CleanupStackDepth, OldCleanupScopeDepth;
1025 size_t LifetimeExtendedCleanupStackSize;
1026 CleanupDeactivationScope DeactivateCleanups;
1027 bool OldDidCallStackSave;
1028
1029 protected:
1030 bool PerformCleanup;
1031
1032 private:
1033 RunCleanupsScope(const RunCleanupsScope &) = delete;
1034 void operator=(const RunCleanupsScope &) = delete;
1035
1036 protected:
1037 CodeGenFunction &CGF;
1038
1039 public:
1040 /// Enter a new cleanup scope.
1041 explicit RunCleanupsScope(CodeGenFunction &CGF)
1042 : DeactivateCleanups(CGF), PerformCleanup(true), CGF(CGF) {
1043 CleanupStackDepth = CGF.EHStack.stable_begin();
1044 LifetimeExtendedCleanupStackSize =
1045 CGF.LifetimeExtendedCleanupStack.size();
1046 OldDidCallStackSave = CGF.DidCallStackSave;
1047 CGF.DidCallStackSave = false;
1048 OldCleanupScopeDepth = CGF.CurrentCleanupScopeDepth;
1049 CGF.CurrentCleanupScopeDepth = CleanupStackDepth;
1050 }
1051
1052 /// Exit this cleanup scope, emitting any accumulated cleanups.
1053 ~RunCleanupsScope() {
1054 if (PerformCleanup)
1055 ForceCleanup();
1056 }
1057
1058 /// Determine whether this scope requires any cleanups.
1059 bool requiresCleanups() const {
1060 return CGF.EHStack.stable_begin() != CleanupStackDepth;
1061 }
1062
1063 /// Force the emission of cleanups now, instead of waiting
1064 /// until this object is destroyed.
1065 /// \param ValuesToReload - A list of values that need to be available at
1066 /// the insertion point after cleanup emission. If cleanup emission created
1067 /// a shared cleanup block, these value pointers will be rewritten.
1068 /// Otherwise, they not will be modified.
1069 void
1070 ForceCleanup(std::initializer_list<llvm::Value **> ValuesToReload = {}) {
1071 assert(PerformCleanup && "Already forced cleanup");
1072 CGF.DidCallStackSave = OldDidCallStackSave;
1073 DeactivateCleanups.ForceDeactivate();
1074 CGF.PopCleanupBlocks(OldCleanupStackSize: CleanupStackDepth, OldLifetimeExtendedStackSize: LifetimeExtendedCleanupStackSize,
1075 ValuesToReload);
1076 PerformCleanup = false;
1077 CGF.CurrentCleanupScopeDepth = OldCleanupScopeDepth;
1078 }
1079 };
1080
1081 // Cleanup stack depth of the RunCleanupsScope that was pushed most recently.
1082 EHScopeStack::stable_iterator CurrentCleanupScopeDepth =
1083 EHScopeStack::stable_end();
1084
1085 class LexicalScope : public RunCleanupsScope {
1086 SourceRange Range;
1087 SmallVector<const LabelDecl *, 4> Labels;
1088 LexicalScope *ParentScope;
1089
1090 LexicalScope(const LexicalScope &) = delete;
1091 void operator=(const LexicalScope &) = delete;
1092
1093 public:
1094 /// Enter a new cleanup scope.
1095 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range);
1096
1097 void addLabel(const LabelDecl *label) {
1098 assert(PerformCleanup && "adding label to dead scope?");
1099 Labels.push_back(Elt: label);
1100 }
1101
1102 /// Exit this cleanup scope, emitting any accumulated
1103 /// cleanups.
1104 ~LexicalScope();
1105
1106 /// Force the emission of cleanups now, instead of waiting
1107 /// until this object is destroyed.
1108 void ForceCleanup() {
1109 CGF.CurLexicalScope = ParentScope;
1110 RunCleanupsScope::ForceCleanup();
1111
1112 if (!Labels.empty())
1113 rescopeLabels();
1114 }
1115
1116 bool hasLabels() const { return !Labels.empty(); }
1117
1118 void rescopeLabels();
1119 };
1120
1121 typedef llvm::DenseMap<const Decl *, Address> DeclMapTy;
1122
1123 /// The class used to assign some variables some temporarily addresses.
1124 class OMPMapVars {
1125 DeclMapTy SavedLocals;
1126 DeclMapTy SavedTempAddresses;
1127 OMPMapVars(const OMPMapVars &) = delete;
1128 void operator=(const OMPMapVars &) = delete;
1129
1130 public:
1131 explicit OMPMapVars() = default;
1132 ~OMPMapVars() {
1133 assert(SavedLocals.empty() && "Did not restored original addresses.");
1134 };
1135
1136 /// Sets the address of the variable \p LocalVD to be \p TempAddr in
1137 /// function \p CGF.
1138 /// \return true if at least one variable was set already, false otherwise.
1139 bool setVarAddr(CodeGenFunction &CGF, const VarDecl *LocalVD,
1140 Address TempAddr) {
1141 LocalVD = LocalVD->getCanonicalDecl();
1142 // Only save it once.
1143 if (SavedLocals.count(Val: LocalVD))
1144 return false;
1145
1146 // Copy the existing local entry to SavedLocals.
1147 auto it = CGF.LocalDeclMap.find(Val: LocalVD);
1148 if (it != CGF.LocalDeclMap.end())
1149 SavedLocals.try_emplace(Key: LocalVD, Args&: it->second);
1150 else
1151 SavedLocals.try_emplace(Key: LocalVD, Args: Address::invalid());
1152
1153 // Generate the private entry.
1154 QualType VarTy = LocalVD->getType();
1155 if (VarTy->isReferenceType()) {
1156 Address Temp = CGF.CreateMemTemp(T: VarTy);
1157 CGF.Builder.CreateStore(Val: TempAddr.emitRawPointer(CGF), Addr: Temp);
1158 TempAddr = Temp;
1159 }
1160 SavedTempAddresses.try_emplace(Key: LocalVD, Args&: TempAddr);
1161
1162 return true;
1163 }
1164
1165 /// Applies new addresses to the list of the variables.
1166 /// \return true if at least one variable is using new address, false
1167 /// otherwise.
1168 bool apply(CodeGenFunction &CGF) {
1169 copyInto(Src: SavedTempAddresses, Dest&: CGF.LocalDeclMap);
1170 SavedTempAddresses.clear();
1171 return !SavedLocals.empty();
1172 }
1173
1174 /// Restores original addresses of the variables.
1175 void restore(CodeGenFunction &CGF) {
1176 if (!SavedLocals.empty()) {
1177 copyInto(Src: SavedLocals, Dest&: CGF.LocalDeclMap);
1178 SavedLocals.clear();
1179 }
1180 }
1181
1182 private:
1183 /// Copy all the entries in the source map over the corresponding
1184 /// entries in the destination, which must exist.
1185 static void copyInto(const DeclMapTy &Src, DeclMapTy &Dest) {
1186 for (auto &[Decl, Addr] : Src) {
1187 if (!Addr.isValid())
1188 Dest.erase(Val: Decl);
1189 else
1190 Dest.insert_or_assign(Key: Decl, Val: Addr);
1191 }
1192 }
1193 };
1194
1195 /// The scope used to remap some variables as private in the OpenMP loop body
1196 /// (or other captured region emitted without outlining), and to restore old
1197 /// vars back on exit.
1198 class OMPPrivateScope : public RunCleanupsScope {
1199 OMPMapVars MappedVars;
1200 OMPPrivateScope(const OMPPrivateScope &) = delete;
1201 void operator=(const OMPPrivateScope &) = delete;
1202
1203 public:
1204 /// Enter a new OpenMP private scope.
1205 explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
1206
1207 /// Registers \p LocalVD variable as a private with \p Addr as the address
1208 /// of the corresponding private variable. \p
1209 /// PrivateGen is the address of the generated private variable.
1210 /// \return true if the variable is registered as private, false if it has
1211 /// been privatized already.
1212 bool addPrivate(const VarDecl *LocalVD, Address Addr) {
1213 assert(PerformCleanup && "adding private to dead scope");
1214 return MappedVars.setVarAddr(CGF, LocalVD, TempAddr: Addr);
1215 }
1216
1217 /// Privatizes local variables previously registered as private.
1218 /// Registration is separate from the actual privatization to allow
1219 /// initializers use values of the original variables, not the private one.
1220 /// This is important, for example, if the private variable is a class
1221 /// variable initialized by a constructor that references other private
1222 /// variables. But at initialization original variables must be used, not
1223 /// private copies.
1224 /// \return true if at least one variable was privatized, false otherwise.
1225 bool Privatize() { return MappedVars.apply(CGF); }
1226
1227 void ForceCleanup() {
1228 RunCleanupsScope::ForceCleanup();
1229 restoreMap();
1230 }
1231
1232 /// Exit scope - all the mapped variables are restored.
1233 ~OMPPrivateScope() {
1234 if (PerformCleanup)
1235 ForceCleanup();
1236 }
1237
1238 /// Checks if the global variable is captured in current function.
1239 bool isGlobalVarCaptured(const VarDecl *VD) const {
1240 VD = VD->getCanonicalDecl();
1241 return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(Val: VD) > 0;
1242 }
1243
1244 /// Restore all mapped variables w/o clean up. This is usefully when we want
1245 /// to reference the original variables but don't want the clean up because
1246 /// that could emit lifetime end too early, causing backend issue #56913.
1247 void restoreMap() { MappedVars.restore(CGF); }
1248 };
1249
1250 /// Save/restore original map of previously emitted local vars in case when we
1251 /// need to duplicate emission of the same code several times in the same
1252 /// function for OpenMP code.
1253 class OMPLocalDeclMapRAII {
1254 CodeGenFunction &CGF;
1255 DeclMapTy SavedMap;
1256
1257 public:
1258 OMPLocalDeclMapRAII(CodeGenFunction &CGF)
1259 : CGF(CGF), SavedMap(CGF.LocalDeclMap) {}
1260 ~OMPLocalDeclMapRAII() { SavedMap.swap(RHS&: CGF.LocalDeclMap); }
1261 };
1262
1263 /// Takes the old cleanup stack size and emits the cleanup blocks
1264 /// that have been added.
1265 void
1266 PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
1267 std::initializer_list<llvm::Value **> ValuesToReload = {});
1268
1269 /// Takes the old cleanup stack size and emits the cleanup blocks
1270 /// that have been added, then adds all lifetime-extended cleanups from
1271 /// the given position to the stack.
1272 void
1273 PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
1274 size_t OldLifetimeExtendedStackSize,
1275 std::initializer_list<llvm::Value **> ValuesToReload = {});
1276
1277 void ResolveBranchFixups(llvm::BasicBlock *Target);
1278
1279 /// The given basic block lies in the current EH scope, but may be a
1280 /// target of a potentially scope-crossing jump; get a stable handle
1281 /// to which we can perform this jump later.
1282 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
1283 return JumpDest(Target, EHStack.getInnermostNormalCleanup(),
1284 NextCleanupDestIndex++);
1285 }
1286
1287 /// The given basic block lies in the current EH scope, but may be a
1288 /// target of a potentially scope-crossing jump; get a stable handle
1289 /// to which we can perform this jump later.
1290 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
1291 return getJumpDestInCurrentScope(Target: createBasicBlock(name: Name));
1292 }
1293
1294 /// EmitBranchThroughCleanup - Emit a branch from the current insert
1295 /// block through the normal cleanup handling code (if any) and then
1296 /// on to \arg Dest.
1297 void EmitBranchThroughCleanup(JumpDest Dest);
1298
1299 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
1300 /// specified destination obviously has no cleanups to run. 'false' is always
1301 /// a conservatively correct answer for this method.
1302 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
1303
1304 /// popCatchScope - Pops the catch scope at the top of the EHScope
1305 /// stack, emitting any required code (other than the catch handlers
1306 /// themselves).
1307 void popCatchScope();
1308
1309 llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
1310 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
1311 llvm::BasicBlock *
1312 getFuncletEHDispatchBlock(EHScopeStack::stable_iterator scope);
1313
1314 /// An object to manage conditionally-evaluated expressions.
1315 class ConditionalEvaluation {
1316 llvm::BasicBlock *StartBB;
1317
1318 public:
1319 ConditionalEvaluation(CodeGenFunction &CGF)
1320 : StartBB(CGF.Builder.GetInsertBlock()) {}
1321
1322 void begin(CodeGenFunction &CGF) {
1323 assert(CGF.OutermostConditional != this);
1324 if (!CGF.OutermostConditional)
1325 CGF.OutermostConditional = this;
1326 }
1327
1328 void end(CodeGenFunction &CGF) {
1329 assert(CGF.OutermostConditional != nullptr);
1330 if (CGF.OutermostConditional == this)
1331 CGF.OutermostConditional = nullptr;
1332 }
1333
1334 /// Returns a block which will be executed prior to each
1335 /// evaluation of the conditional code.
1336 llvm::BasicBlock *getStartingBlock() const { return StartBB; }
1337 };
1338
1339 /// isInConditionalBranch - Return true if we're currently emitting
1340 /// one branch or the other of a conditional expression.
1341 bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
1342
1343 void setBeforeOutermostConditional(llvm::Value *value, Address addr,
1344 CodeGenFunction &CGF) {
1345 assert(isInConditionalBranch());
1346 llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
1347 auto store = new llvm::StoreInst(value, addr.emitRawPointer(CGF),
1348 block->back().getIterator());
1349 store->setAlignment(addr.getAlignment().getAsAlign());
1350 }
1351
1352 /// An RAII object to record that we're evaluating a statement
1353 /// expression.
1354 class StmtExprEvaluation {
1355 CodeGenFunction &CGF;
1356
1357 /// We have to save the outermost conditional: cleanups in a
1358 /// statement expression aren't conditional just because the
1359 /// StmtExpr is.
1360 ConditionalEvaluation *SavedOutermostConditional;
1361
1362 public:
1363 StmtExprEvaluation(CodeGenFunction &CGF)
1364 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
1365 CGF.OutermostConditional = nullptr;
1366 }
1367
1368 ~StmtExprEvaluation() {
1369 CGF.OutermostConditional = SavedOutermostConditional;
1370 CGF.EnsureInsertPoint();
1371 }
1372 };
1373
1374 /// An object which temporarily prevents a value from being
1375 /// destroyed by aggressive peephole optimizations that assume that
1376 /// all uses of a value have been realized in the IR.
1377 class PeepholeProtection {
1378 llvm::Instruction *Inst = nullptr;
1379 friend class CodeGenFunction;
1380
1381 public:
1382 PeepholeProtection() = default;
1383 };
1384
1385 /// A non-RAII class containing all the information about a bound
1386 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
1387 /// this which makes individual mappings very simple; using this
1388 /// class directly is useful when you have a variable number of
1389 /// opaque values or don't want the RAII functionality for some
1390 /// reason.
1391 class OpaqueValueMappingData {
1392 const OpaqueValueExpr *OpaqueValue;
1393 bool BoundLValue;
1394 CodeGenFunction::PeepholeProtection Protection;
1395
1396 OpaqueValueMappingData(const OpaqueValueExpr *ov, bool boundLValue)
1397 : OpaqueValue(ov), BoundLValue(boundLValue) {}
1398
1399 public:
1400 OpaqueValueMappingData() : OpaqueValue(nullptr) {}
1401
1402 static bool shouldBindAsLValue(const Expr *expr) {
1403 // gl-values should be bound as l-values for obvious reasons.
1404 // Records should be bound as l-values because IR generation
1405 // always keeps them in memory. Expressions of function type
1406 // act exactly like l-values but are formally required to be
1407 // r-values in C.
1408 return expr->isGLValue() || expr->getType()->isFunctionType() ||
1409 hasAggregateEvaluationKind(T: expr->getType());
1410 }
1411
1412 static OpaqueValueMappingData
1413 bind(CodeGenFunction &CGF, const OpaqueValueExpr *ov, const Expr *e) {
1414 if (shouldBindAsLValue(expr: ov))
1415 return bind(CGF, ov, lv: CGF.EmitLValue(E: e));
1416 return bind(CGF, ov, rv: CGF.EmitAnyExpr(E: e));
1417 }
1418
1419 static OpaqueValueMappingData
1420 bind(CodeGenFunction &CGF, const OpaqueValueExpr *ov, const LValue &lv) {
1421 assert(shouldBindAsLValue(ov));
1422 CGF.OpaqueLValues.insert(KV: std::make_pair(x&: ov, y: lv));
1423 return OpaqueValueMappingData(ov, true);
1424 }
1425
1426 static OpaqueValueMappingData
1427 bind(CodeGenFunction &CGF, const OpaqueValueExpr *ov, const RValue &rv) {
1428 assert(!shouldBindAsLValue(ov));
1429 CGF.OpaqueRValues.insert(KV: std::make_pair(x&: ov, y: rv));
1430
1431 OpaqueValueMappingData data(ov, false);
1432
1433 // Work around an extremely aggressive peephole optimization in
1434 // EmitScalarConversion which assumes that all other uses of a
1435 // value are extant.
1436 data.Protection = CGF.protectFromPeepholes(rvalue: rv);
1437
1438 return data;
1439 }
1440
1441 bool isValid() const { return OpaqueValue != nullptr; }
1442 void clear() { OpaqueValue = nullptr; }
1443
1444 void unbind(CodeGenFunction &CGF) {
1445 assert(OpaqueValue && "no data to unbind!");
1446
1447 if (BoundLValue) {
1448 CGF.OpaqueLValues.erase(Val: OpaqueValue);
1449 } else {
1450 CGF.OpaqueRValues.erase(Val: OpaqueValue);
1451 CGF.unprotectFromPeepholes(protection: Protection);
1452 }
1453 }
1454 };
1455
1456 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
1457 class OpaqueValueMapping {
1458 CodeGenFunction &CGF;
1459 OpaqueValueMappingData Data;
1460
1461 public:
1462 static bool shouldBindAsLValue(const Expr *expr) {
1463 return OpaqueValueMappingData::shouldBindAsLValue(expr);
1464 }
1465
1466 /// Build the opaque value mapping for the given conditional
1467 /// operator if it's the GNU ?: extension. This is a common
1468 /// enough pattern that the convenience operator is really
1469 /// helpful.
1470 ///
1471 OpaqueValueMapping(CodeGenFunction &CGF,
1472 const AbstractConditionalOperator *op)
1473 : CGF(CGF) {
1474 if (isa<ConditionalOperator>(Val: op))
1475 // Leave Data empty.
1476 return;
1477
1478 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(Val: op);
1479 Data = OpaqueValueMappingData::bind(CGF, ov: e->getOpaqueValue(),
1480 e: e->getCommon());
1481 }
1482
1483 /// Build the opaque value mapping for an OpaqueValueExpr whose source
1484 /// expression is set to the expression the OVE represents.
1485 OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *OV)
1486 : CGF(CGF) {
1487 if (OV) {
1488 assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "
1489 "for OVE with no source expression");
1490 Data = OpaqueValueMappingData::bind(CGF, ov: OV, e: OV->getSourceExpr());
1491 }
1492 }
1493
1494 OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *opaqueValue,
1495 LValue lvalue)
1496 : CGF(CGF),
1497 Data(OpaqueValueMappingData::bind(CGF, ov: opaqueValue, lv: lvalue)) {}
1498
1499 OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *opaqueValue,
1500 RValue rvalue)
1501 : CGF(CGF),
1502 Data(OpaqueValueMappingData::bind(CGF, ov: opaqueValue, rv: rvalue)) {}
1503
1504 void pop() {
1505 Data.unbind(CGF);
1506 Data.clear();
1507 }
1508
1509 ~OpaqueValueMapping() {
1510 if (Data.isValid())
1511 Data.unbind(CGF);
1512 }
1513 };
1514
1515private:
1516 CGDebugInfo *DebugInfo;
1517 /// Used to create unique names for artificial VLA size debug info variables.
1518 unsigned VLAExprCounter = 0;
1519 bool DisableDebugInfo = false;
1520
1521 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
1522 /// calling llvm.stacksave for multiple VLAs in the same scope.
1523 bool DidCallStackSave = false;
1524
1525 /// IndirectBranch - The first time an indirect goto is seen we create a block
1526 /// with an indirect branch. Every time we see the address of a label taken,
1527 /// we add the label to the indirect goto. Every subsequent indirect goto is
1528 /// codegen'd as a jump to the IndirectBranch's basic block.
1529 llvm::IndirectBrInst *IndirectBranch = nullptr;
1530
1531 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
1532 /// decls.
1533 DeclMapTy LocalDeclMap;
1534
1535 // Keep track of the cleanups for callee-destructed parameters pushed to the
1536 // cleanup stack so that they can be deactivated later.
1537 llvm::DenseMap<const ParmVarDecl *, EHScopeStack::stable_iterator>
1538 CalleeDestructedParamCleanups;
1539
1540 /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this
1541 /// will contain a mapping from said ParmVarDecl to its implicit "object_size"
1542 /// parameter.
1543 llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2>
1544 SizeArguments;
1545
1546 /// Track escaped local variables with auto storage. Used during SEH
1547 /// outlining to produce a call to llvm.localescape.
1548 llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
1549
1550 /// LabelMap - This keeps track of the LLVM basic block for each C label.
1551 llvm::DenseMap<const LabelDecl *, JumpDest> LabelMap;
1552
1553 // BreakContinueStack - This keeps track of where break and continue
1554 // statements should jump to.
1555 struct BreakContinue {
1556 BreakContinue(const Stmt &LoopOrSwitch, JumpDest Break, JumpDest Continue)
1557 : LoopOrSwitch(&LoopOrSwitch), BreakBlock(Break),
1558 ContinueBlock(Continue) {}
1559
1560 const Stmt *LoopOrSwitch;
1561 JumpDest BreakBlock;
1562 JumpDest ContinueBlock;
1563 };
1564 SmallVector<BreakContinue, 8> BreakContinueStack;
1565
1566 /// Handles cancellation exit points in OpenMP-related constructs.
1567 class OpenMPCancelExitStack {
1568 /// Tracks cancellation exit point and join point for cancel-related exit
1569 /// and normal exit.
1570 struct CancelExit {
1571 CancelExit() = default;
1572 CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock,
1573 JumpDest ContBlock)
1574 : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {}
1575 OpenMPDirectiveKind Kind = llvm::omp::OMPD_unknown;
1576 /// true if the exit block has been emitted already by the special
1577 /// emitExit() call, false if the default codegen is used.
1578 bool HasBeenEmitted = false;
1579 JumpDest ExitBlock;
1580 JumpDest ContBlock;
1581 };
1582
1583 SmallVector<CancelExit, 8> Stack;
1584
1585 public:
1586 OpenMPCancelExitStack() : Stack(1) {}
1587 ~OpenMPCancelExitStack() = default;
1588 /// Fetches the exit block for the current OpenMP construct.
1589 JumpDest getExitBlock() const { return Stack.back().ExitBlock; }
1590 /// Emits exit block with special codegen procedure specific for the related
1591 /// OpenMP construct + emits code for normal construct cleanup.
1592 void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1593 const llvm::function_ref<void(CodeGenFunction &)> CodeGen) {
1594 if (Stack.back().Kind == Kind && getExitBlock().isValid()) {
1595 assert(CGF.getOMPCancelDestination(Kind).isValid());
1596 assert(CGF.HaveInsertPoint());
1597 assert(!Stack.back().HasBeenEmitted);
1598 auto IP = CGF.Builder.saveAndClearIP();
1599 CGF.EmitBlock(BB: Stack.back().ExitBlock.getBlock());
1600 CodeGen(CGF);
1601 CGF.EmitBranch(Block: Stack.back().ContBlock.getBlock());
1602 CGF.Builder.restoreIP(IP);
1603 Stack.back().HasBeenEmitted = true;
1604 }
1605 CodeGen(CGF);
1606 }
1607 /// Enter the cancel supporting \a Kind construct.
1608 /// \param Kind OpenMP directive that supports cancel constructs.
1609 /// \param HasCancel true, if the construct has inner cancel directive,
1610 /// false otherwise.
1611 void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) {
1612 Stack.push_back(Elt: {Kind,
1613 HasCancel ? CGF.getJumpDestInCurrentScope(Name: "cancel.exit")
1614 : JumpDest(),
1615 HasCancel ? CGF.getJumpDestInCurrentScope(Name: "cancel.cont")
1616 : JumpDest()});
1617 }
1618 /// Emits default exit point for the cancel construct (if the special one
1619 /// has not be used) + join point for cancel/normal exits.
1620 void exit(CodeGenFunction &CGF) {
1621 if (getExitBlock().isValid()) {
1622 assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid());
1623 bool HaveIP = CGF.HaveInsertPoint();
1624 if (!Stack.back().HasBeenEmitted) {
1625 if (HaveIP)
1626 CGF.EmitBranchThroughCleanup(Dest: Stack.back().ContBlock);
1627 CGF.EmitBlock(BB: Stack.back().ExitBlock.getBlock());
1628 CGF.EmitBranchThroughCleanup(Dest: Stack.back().ContBlock);
1629 }
1630 CGF.EmitBlock(BB: Stack.back().ContBlock.getBlock());
1631 if (!HaveIP) {
1632 CGF.Builder.CreateUnreachable();
1633 CGF.Builder.ClearInsertionPoint();
1634 }
1635 }
1636 Stack.pop_back();
1637 }
1638 };
1639 OpenMPCancelExitStack OMPCancelStack;
1640
1641 /// Lower the Likelihood knowledge about the \p Cond via llvm.expect intrin.
1642 llvm::Value *emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
1643 Stmt::Likelihood LH);
1644
1645 std::unique_ptr<CodeGenPGO> PGO;
1646
1647 /// Calculate branch weights appropriate for PGO data
1648 llvm::MDNode *createProfileWeights(uint64_t TrueCount,
1649 uint64_t FalseCount) const;
1650 llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights) const;
1651 llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
1652 uint64_t LoopCount) const;
1653
1654public:
1655 bool hasSkipCounter(const Stmt *S) const;
1656
1657 void markStmtAsUsed(bool Skipped, const Stmt *S);
1658 void markStmtMaybeUsed(const Stmt *S);
1659
1660 /// Used to specify which counter in a pair shall be incremented.
1661 /// For non-binary counters, a skip counter is derived as (Parent - Exec).
1662 /// In contrast for binary counters, a skip counter cannot be computed from
1663 /// the Parent counter. In such cases, dedicated SkipPath counters must be
1664 /// allocated and marked (incremented as binary counters). (Parent can be
1665 /// synthesized with (Exec + Skip) in simple cases)
1666 enum CounterForIncrement {
1667 UseExecPath = 0, ///< Exec (true)
1668 UseSkipPath, ///< Skip (false)
1669 };
1670
1671 /// Increment the profiler's counter for the given statement by \p StepV.
1672 /// If \p StepV is null, the default increment is 1.
1673 void incrementProfileCounter(const Stmt *S, llvm::Value *StepV = nullptr) {
1674 incrementProfileCounter(ExecSkip: UseExecPath, S, UseBoth: false, StepV);
1675 }
1676
1677 /// Emit increment of Counter.
1678 /// \param ExecSkip Use `Skipped` Counter if UseSkipPath is specified.
1679 /// \param S The Stmt that Counter is associated.
1680 /// \param UseBoth Mark both Exec/Skip as used. (for verification)
1681 /// \param StepV The offset Value for adding to Counter.
1682 void incrementProfileCounter(CounterForIncrement ExecSkip, const Stmt *S,
1683 bool UseBoth = false,
1684 llvm::Value *StepV = nullptr);
1685
1686 bool isMCDCCoverageEnabled() const {
1687 return (CGM.getCodeGenOpts().hasProfileClangInstr() &&
1688 CGM.getCodeGenOpts().MCDCCoverage &&
1689 !CurFn->hasFnAttribute(Kind: llvm::Attribute::NoProfile));
1690 }
1691
1692 /// Allocate a temp value on the stack that MCDC can use to track condition
1693 /// results.
1694 void maybeCreateMCDCCondBitmap();
1695
1696 bool isBinaryLogicalOp(const Expr *E) const {
1697 const BinaryOperator *BOp = dyn_cast<BinaryOperator>(Val: E->IgnoreParens());
1698 return (BOp && BOp->isLogicalOp());
1699 }
1700
1701 bool isMCDCDecisionExpr(const Expr *E) const;
1702 bool isMCDCBranchExpr(const Expr *E) const;
1703
1704 /// Zero-init the MCDC temp value.
1705 void maybeResetMCDCCondBitmap(const Expr *E);
1706
1707 /// Increment the profiler's counter for the given expression by \p StepV.
1708 /// If \p StepV is null, the default increment is 1.
1709 void maybeUpdateMCDCTestVectorBitmap(const Expr *E);
1710
1711 /// Update the MCDC temp value with the condition's evaluated result.
1712 void maybeUpdateMCDCCondBitmap(const Expr *E, llvm::Value *Val);
1713
1714 /// Get the profiler's count for the given statement.
1715 uint64_t getProfileCount(const Stmt *S);
1716
1717 /// Set the profiler's current count.
1718 void setCurrentProfileCount(uint64_t Count);
1719
1720 /// Get the profiler's current count. This is generally the count for the most
1721 /// recently incremented counter.
1722 uint64_t getCurrentProfileCount();
1723
1724 /// See CGDebugInfo::addInstToCurrentSourceAtom.
1725 void addInstToCurrentSourceAtom(llvm::Instruction *KeyInstruction,
1726 llvm::Value *Backup);
1727
1728 /// See CGDebugInfo::addInstToSpecificSourceAtom.
1729 void addInstToSpecificSourceAtom(llvm::Instruction *KeyInstruction,
1730 llvm::Value *Backup, uint64_t Atom);
1731
1732 /// Add \p KeyInstruction and an optional \p Backup instruction to a new atom
1733 /// group (See ApplyAtomGroup for more info).
1734 void addInstToNewSourceAtom(llvm::Instruction *KeyInstruction,
1735 llvm::Value *Backup);
1736
1737private:
1738 /// SwitchInsn - This is nearest current switch instruction. It is null if
1739 /// current context is not in a switch.
1740 llvm::SwitchInst *SwitchInsn = nullptr;
1741 /// The branch weights of SwitchInsn when doing instrumentation based PGO.
1742 SmallVector<uint64_t, 16> *SwitchWeights = nullptr;
1743
1744 /// The likelihood attributes of the SwitchCase.
1745 SmallVector<Stmt::Likelihood, 16> *SwitchLikelihood = nullptr;
1746
1747 /// CaseRangeBlock - This block holds if condition check for last case
1748 /// statement range in current switch instruction.
1749 llvm::BasicBlock *CaseRangeBlock = nullptr;
1750
1751 /// OpaqueLValues - Keeps track of the current set of opaque value
1752 /// expressions.
1753 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
1754 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
1755
1756 // VLASizeMap - This keeps track of the associated size for each VLA type.
1757 // We track this by the size expression rather than the type itself because
1758 // in certain situations, like a const qualifier applied to an VLA typedef,
1759 // multiple VLA types can share the same size expression.
1760 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
1761 // enter/leave scopes.
1762 llvm::DenseMap<const Expr *, llvm::Value *> VLASizeMap;
1763
1764 /// A block containing a single 'unreachable' instruction. Created
1765 /// lazily by getUnreachableBlock().
1766 llvm::BasicBlock *UnreachableBlock = nullptr;
1767
1768 /// Counts of the number return expressions in the function.
1769 unsigned NumReturnExprs = 0;
1770
1771 /// Count the number of simple (constant) return expressions in the function.
1772 unsigned NumSimpleReturnExprs = 0;
1773
1774 /// The last regular (non-return) debug location (breakpoint) in the function.
1775 SourceLocation LastStopPoint;
1776
1777public:
1778 /// Source location information about the default argument or member
1779 /// initializer expression we're evaluating, if any.
1780 CurrentSourceLocExprScope CurSourceLocExprScope;
1781 using SourceLocExprScopeGuard =
1782 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
1783
1784 /// A scope within which we are constructing the fields of an object which
1785 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
1786 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
1787 class FieldConstructionScope {
1788 public:
1789 FieldConstructionScope(CodeGenFunction &CGF, Address This)
1790 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
1791 CGF.CXXDefaultInitExprThis = This;
1792 }
1793 ~FieldConstructionScope() {
1794 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
1795 }
1796
1797 private:
1798 CodeGenFunction &CGF;
1799 Address OldCXXDefaultInitExprThis;
1800 };
1801
1802 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
1803 /// is overridden to be the object under construction.
1804 class CXXDefaultInitExprScope {
1805 public:
1806 CXXDefaultInitExprScope(CodeGenFunction &CGF, const CXXDefaultInitExpr *E)
1807 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
1808 OldCXXThisAlignment(CGF.CXXThisAlignment),
1809 SourceLocScope(E, CGF.CurSourceLocExprScope) {
1810 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getBasePointer();
1811 CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
1812 }
1813 ~CXXDefaultInitExprScope() {
1814 CGF.CXXThisValue = OldCXXThisValue;
1815 CGF.CXXThisAlignment = OldCXXThisAlignment;
1816 }
1817
1818 public:
1819 CodeGenFunction &CGF;
1820 llvm::Value *OldCXXThisValue;
1821 CharUnits OldCXXThisAlignment;
1822 SourceLocExprScopeGuard SourceLocScope;
1823 };
1824
1825 struct CXXDefaultArgExprScope : SourceLocExprScopeGuard {
1826 CXXDefaultArgExprScope(CodeGenFunction &CGF, const CXXDefaultArgExpr *E)
1827 : SourceLocExprScopeGuard(E, CGF.CurSourceLocExprScope) {}
1828 };
1829
1830 /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the
1831 /// current loop index is overridden.
1832 class ArrayInitLoopExprScope {
1833 public:
1834 ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index)
1835 : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) {
1836 CGF.ArrayInitIndex = Index;
1837 }
1838 ~ArrayInitLoopExprScope() { CGF.ArrayInitIndex = OldArrayInitIndex; }
1839
1840 private:
1841 CodeGenFunction &CGF;
1842 llvm::Value *OldArrayInitIndex;
1843 };
1844
1845 class InlinedInheritingConstructorScope {
1846 public:
1847 InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD)
1848 : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl),
1849 OldCurCodeDecl(CGF.CurCodeDecl),
1850 OldCXXABIThisDecl(CGF.CXXABIThisDecl),
1851 OldCXXABIThisValue(CGF.CXXABIThisValue),
1852 OldCXXThisValue(CGF.CXXThisValue),
1853 OldCXXABIThisAlignment(CGF.CXXABIThisAlignment),
1854 OldCXXThisAlignment(CGF.CXXThisAlignment),
1855 OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy),
1856 OldCXXInheritedCtorInitExprArgs(
1857 std::move(CGF.CXXInheritedCtorInitExprArgs)) {
1858 CGF.CurGD = GD;
1859 CGF.CurFuncDecl = CGF.CurCodeDecl =
1860 cast<CXXConstructorDecl>(Val: GD.getDecl());
1861 CGF.CXXABIThisDecl = nullptr;
1862 CGF.CXXABIThisValue = nullptr;
1863 CGF.CXXThisValue = nullptr;
1864 CGF.CXXABIThisAlignment = CharUnits();
1865 CGF.CXXThisAlignment = CharUnits();
1866 CGF.ReturnValue = Address::invalid();
1867 CGF.FnRetTy = QualType();
1868 CGF.CXXInheritedCtorInitExprArgs.clear();
1869 }
1870 ~InlinedInheritingConstructorScope() {
1871 CGF.CurGD = OldCurGD;
1872 CGF.CurFuncDecl = OldCurFuncDecl;
1873 CGF.CurCodeDecl = OldCurCodeDecl;
1874 CGF.CXXABIThisDecl = OldCXXABIThisDecl;
1875 CGF.CXXABIThisValue = OldCXXABIThisValue;
1876 CGF.CXXThisValue = OldCXXThisValue;
1877 CGF.CXXABIThisAlignment = OldCXXABIThisAlignment;
1878 CGF.CXXThisAlignment = OldCXXThisAlignment;
1879 CGF.ReturnValue = OldReturnValue;
1880 CGF.FnRetTy = OldFnRetTy;
1881 CGF.CXXInheritedCtorInitExprArgs =
1882 std::move(OldCXXInheritedCtorInitExprArgs);
1883 }
1884
1885 private:
1886 CodeGenFunction &CGF;
1887 GlobalDecl OldCurGD;
1888 const Decl *OldCurFuncDecl;
1889 const Decl *OldCurCodeDecl;
1890 ImplicitParamDecl *OldCXXABIThisDecl;
1891 llvm::Value *OldCXXABIThisValue;
1892 llvm::Value *OldCXXThisValue;
1893 CharUnits OldCXXABIThisAlignment;
1894 CharUnits OldCXXThisAlignment;
1895 Address OldReturnValue;
1896 QualType OldFnRetTy;
1897 CallArgList OldCXXInheritedCtorInitExprArgs;
1898 };
1899
1900 // Helper class for the OpenMP IR Builder. Allows reusability of code used for
1901 // region body, and finalization codegen callbacks. This will class will also
1902 // contain privatization functions used by the privatization call backs
1903 //
1904 // TODO: this is temporary class for things that are being moved out of
1905 // CGOpenMPRuntime, new versions of current CodeGenFunction methods, or
1906 // utility function for use with the OMPBuilder. Once that move to use the
1907 // OMPBuilder is done, everything here will either become part of CodeGenFunc.
1908 // directly, or a new helper class that will contain functions used by both
1909 // this and the OMPBuilder
1910
1911 struct OMPBuilderCBHelpers {
1912
1913 OMPBuilderCBHelpers() = delete;
1914 OMPBuilderCBHelpers(const OMPBuilderCBHelpers &) = delete;
1915 OMPBuilderCBHelpers &operator=(const OMPBuilderCBHelpers &) = delete;
1916
1917 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
1918
1919 /// Cleanup action for allocate support.
1920 class OMPAllocateCleanupTy final : public EHScopeStack::Cleanup {
1921
1922 private:
1923 llvm::CallInst *RTLFnCI;
1924
1925 public:
1926 OMPAllocateCleanupTy(llvm::CallInst *RLFnCI) : RTLFnCI(RLFnCI) {
1927 RLFnCI->removeFromParent();
1928 }
1929
1930 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
1931 if (!CGF.HaveInsertPoint())
1932 return;
1933 CGF.Builder.Insert(I: RTLFnCI);
1934 }
1935 };
1936
1937 /// Returns address of the threadprivate variable for the current
1938 /// thread. This Also create any necessary OMP runtime calls.
1939 ///
1940 /// \param VD VarDecl for Threadprivate variable.
1941 /// \param VDAddr Address of the Vardecl
1942 /// \param Loc The location where the barrier directive was encountered
1943 static Address getAddrOfThreadPrivate(CodeGenFunction &CGF,
1944 const VarDecl *VD, Address VDAddr,
1945 SourceLocation Loc);
1946
1947 /// Gets the OpenMP-specific address of the local variable /p VD.
1948 static Address getAddressOfLocalVariable(CodeGenFunction &CGF,
1949 const VarDecl *VD);
1950 /// Get the platform-specific name separator.
1951 /// \param Parts different parts of the final name that needs separation
1952 /// \param FirstSeparator First separator used between the initial two
1953 /// parts of the name.
1954 /// \param Separator separator used between all of the rest consecutinve
1955 /// parts of the name
1956 static std::string getNameWithSeparators(ArrayRef<StringRef> Parts,
1957 StringRef FirstSeparator = ".",
1958 StringRef Separator = ".");
1959 /// Emit the Finalization for an OMP region
1960 /// \param CGF The Codegen function this belongs to
1961 /// \param IP Insertion point for generating the finalization code.
1962 static void FinalizeOMPRegion(CodeGenFunction &CGF, InsertPointTy IP) {
1963 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1964 assert(IP.getBlock()->end() != IP.getPoint() &&
1965 "OpenMP IR Builder should cause terminated block!");
1966
1967 llvm::BasicBlock *IPBB = IP.getBlock();
1968 llvm::BasicBlock *DestBB = IPBB->getUniqueSuccessor();
1969 assert(DestBB && "Finalization block should have one successor!");
1970
1971 // erase and replace with cleanup branch.
1972 IPBB->getTerminator()->eraseFromParent();
1973 CGF.Builder.SetInsertPoint(IPBB);
1974 CodeGenFunction::JumpDest Dest = CGF.getJumpDestInCurrentScope(Target: DestBB);
1975 CGF.EmitBranchThroughCleanup(Dest);
1976 }
1977
1978 /// Emit the body of an OMP region
1979 /// \param CGF The Codegen function this belongs to
1980 /// \param RegionBodyStmt The body statement for the OpenMP region being
1981 /// generated
1982 /// \param AllocaIP Where to insert alloca instructions
1983 /// \param CodeGenIP Where to insert the region code
1984 /// \param RegionName Name to be used for new blocks
1985 static void EmitOMPInlinedRegionBody(CodeGenFunction &CGF,
1986 const Stmt *RegionBodyStmt,
1987 InsertPointTy AllocaIP,
1988 InsertPointTy CodeGenIP,
1989 Twine RegionName);
1990
1991 static void EmitCaptureStmt(CodeGenFunction &CGF, InsertPointTy CodeGenIP,
1992 llvm::BasicBlock &FiniBB, llvm::Function *Fn,
1993 ArrayRef<llvm::Value *> Args) {
1994 llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock();
1995 if (llvm::Instruction *CodeGenIPBBTI = CodeGenIPBB->getTerminator())
1996 CodeGenIPBBTI->eraseFromParent();
1997
1998 CGF.Builder.SetInsertPoint(CodeGenIPBB);
1999
2000 if (Fn->doesNotThrow())
2001 CGF.EmitNounwindRuntimeCall(callee: Fn, args: Args);
2002 else
2003 CGF.EmitRuntimeCall(callee: Fn, args: Args);
2004
2005 if (CGF.Builder.saveIP().isSet())
2006 CGF.Builder.CreateBr(Dest: &FiniBB);
2007 }
2008
2009 /// Emit the body of an OMP region that will be outlined in
2010 /// OpenMPIRBuilder::finalize().
2011 /// \param CGF The Codegen function this belongs to
2012 /// \param RegionBodyStmt The body statement for the OpenMP region being
2013 /// generated
2014 /// \param AllocaIP Where to insert alloca instructions
2015 /// \param CodeGenIP Where to insert the region code
2016 /// \param RegionName Name to be used for new blocks
2017 static void EmitOMPOutlinedRegionBody(CodeGenFunction &CGF,
2018 const Stmt *RegionBodyStmt,
2019 InsertPointTy AllocaIP,
2020 InsertPointTy CodeGenIP,
2021 Twine RegionName);
2022
2023 /// RAII for preserving necessary info during Outlined region body codegen.
2024 class OutlinedRegionBodyRAII {
2025
2026 llvm::AssertingVH<llvm::Instruction> OldAllocaIP;
2027 CodeGenFunction::JumpDest OldReturnBlock;
2028 CodeGenFunction &CGF;
2029
2030 public:
2031 OutlinedRegionBodyRAII(CodeGenFunction &cgf, InsertPointTy &AllocaIP,
2032 llvm::BasicBlock &RetBB)
2033 : CGF(cgf) {
2034 assert(AllocaIP.isSet() &&
2035 "Must specify Insertion point for allocas of outlined function");
2036 OldAllocaIP = CGF.AllocaInsertPt;
2037 CGF.AllocaInsertPt = &*AllocaIP.getPoint();
2038
2039 OldReturnBlock = CGF.ReturnBlock;
2040 CGF.ReturnBlock = CGF.getJumpDestInCurrentScope(Target: &RetBB);
2041 }
2042
2043 ~OutlinedRegionBodyRAII() {
2044 CGF.AllocaInsertPt = OldAllocaIP;
2045 CGF.ReturnBlock = OldReturnBlock;
2046 }
2047 };
2048
2049 /// RAII for preserving necessary info during inlined region body codegen.
2050 class InlinedRegionBodyRAII {
2051
2052 llvm::AssertingVH<llvm::Instruction> OldAllocaIP;
2053 CodeGenFunction &CGF;
2054
2055 public:
2056 InlinedRegionBodyRAII(CodeGenFunction &cgf, InsertPointTy &AllocaIP,
2057 llvm::BasicBlock &FiniBB)
2058 : CGF(cgf) {
2059 // Alloca insertion block should be in the entry block of the containing
2060 // function so it expects an empty AllocaIP in which case will reuse the
2061 // old alloca insertion point, or a new AllocaIP in the same block as
2062 // the old one
2063 assert((!AllocaIP.isSet() ||
2064 CGF.AllocaInsertPt->getParent() == AllocaIP.getBlock()) &&
2065 "Insertion point should be in the entry block of containing "
2066 "function!");
2067 OldAllocaIP = CGF.AllocaInsertPt;
2068 if (AllocaIP.isSet())
2069 CGF.AllocaInsertPt = &*AllocaIP.getPoint();
2070
2071 // TODO: Remove the call, after making sure the counter is not used by
2072 // the EHStack.
2073 // Since this is an inlined region, it should not modify the
2074 // ReturnBlock, and should reuse the one for the enclosing outlined
2075 // region. So, the JumpDest being return by the function is discarded
2076 (void)CGF.getJumpDestInCurrentScope(Target: &FiniBB);
2077 }
2078
2079 ~InlinedRegionBodyRAII() { CGF.AllocaInsertPt = OldAllocaIP; }
2080 };
2081 };
2082
2083private:
2084 /// CXXThisDecl - When generating code for a C++ member function,
2085 /// this will hold the implicit 'this' declaration.
2086 ImplicitParamDecl *CXXABIThisDecl = nullptr;
2087 llvm::Value *CXXABIThisValue = nullptr;
2088 llvm::Value *CXXThisValue = nullptr;
2089 CharUnits CXXABIThisAlignment;
2090 CharUnits CXXThisAlignment;
2091
2092 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
2093 /// this expression.
2094 Address CXXDefaultInitExprThis = Address::invalid();
2095
2096 /// The current array initialization index when evaluating an
2097 /// ArrayInitIndexExpr within an ArrayInitLoopExpr.
2098 llvm::Value *ArrayInitIndex = nullptr;
2099
2100 /// The values of function arguments to use when evaluating
2101 /// CXXInheritedCtorInitExprs within this context.
2102 CallArgList CXXInheritedCtorInitExprArgs;
2103
2104 /// CXXStructorImplicitParamDecl - When generating code for a constructor or
2105 /// destructor, this will hold the implicit argument (e.g. VTT).
2106 ImplicitParamDecl *CXXStructorImplicitParamDecl = nullptr;
2107 llvm::Value *CXXStructorImplicitParamValue = nullptr;
2108
2109 /// OutermostConditional - Points to the outermost active
2110 /// conditional control. This is used so that we know if a
2111 /// temporary should be destroyed conditionally.
2112 ConditionalEvaluation *OutermostConditional = nullptr;
2113
2114 /// The current lexical scope.
2115 LexicalScope *CurLexicalScope = nullptr;
2116
2117 /// The current source location that should be used for exception
2118 /// handling code.
2119 SourceLocation CurEHLocation;
2120
2121 /// BlockByrefInfos - For each __block variable, contains
2122 /// information about the layout of the variable.
2123 llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
2124
2125 /// Used by -fsanitize=nullability-return to determine whether the return
2126 /// value can be checked.
2127 llvm::Value *RetValNullabilityPrecondition = nullptr;
2128
2129 /// Check if -fsanitize=nullability-return instrumentation is required for
2130 /// this function.
2131 bool requiresReturnValueNullabilityCheck() const {
2132 return RetValNullabilityPrecondition;
2133 }
2134
2135 /// Used to store precise source locations for return statements by the
2136 /// runtime return value checks.
2137 Address ReturnLocation = Address::invalid();
2138
2139 /// Check if the return value of this function requires sanitization.
2140 bool requiresReturnValueCheck() const;
2141
2142 bool isInAllocaArgument(CGCXXABI &ABI, QualType Ty);
2143 bool hasInAllocaArg(const CXXMethodDecl *MD);
2144
2145 llvm::BasicBlock *TerminateLandingPad = nullptr;
2146 llvm::BasicBlock *TerminateHandler = nullptr;
2147 llvm::SmallVector<llvm::BasicBlock *, 2> TrapBBs;
2148
2149 /// Terminate funclets keyed by parent funclet pad.
2150 llvm::MapVector<llvm::Value *, llvm::BasicBlock *> TerminateFunclets;
2151
2152 /// Largest vector width used in ths function. Will be used to create a
2153 /// function attribute.
2154 unsigned LargestVectorWidth = 0;
2155
2156 /// True if we need emit the life-time markers. This is initially set in
2157 /// the constructor, but could be overwritten to true if this is a coroutine.
2158 bool ShouldEmitLifetimeMarkers;
2159
2160 /// Add OpenCL kernel arg metadata and the kernel attribute metadata to
2161 /// the function metadata.
2162 void EmitKernelMetadata(const FunctionDecl *FD, llvm::Function *Fn);
2163
2164public:
2165 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext = false);
2166 ~CodeGenFunction();
2167
2168 CodeGenTypes &getTypes() const { return CGM.getTypes(); }
2169 ASTContext &getContext() const { return CGM.getContext(); }
2170 CGDebugInfo *getDebugInfo() {
2171 if (DisableDebugInfo)
2172 return nullptr;
2173 return DebugInfo;
2174 }
2175 void disableDebugInfo() { DisableDebugInfo = true; }
2176 void enableDebugInfo() { DisableDebugInfo = false; }
2177
2178 bool shouldUseFusedARCCalls() {
2179 return CGM.getCodeGenOpts().OptimizationLevel == 0;
2180 }
2181
2182 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
2183
2184 /// Returns a pointer to the function's exception object and selector slot,
2185 /// which is assigned in every landing pad.
2186 Address getExceptionSlot();
2187 Address getEHSelectorSlot();
2188
2189 /// Returns the contents of the function's exception object and selector
2190 /// slots.
2191 llvm::Value *getExceptionFromSlot();
2192 llvm::Value *getSelectorFromSlot();
2193
2194 RawAddress getNormalCleanupDestSlot();
2195
2196 llvm::BasicBlock *getUnreachableBlock() {
2197 if (!UnreachableBlock) {
2198 UnreachableBlock = createBasicBlock(name: "unreachable");
2199 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
2200 }
2201 return UnreachableBlock;
2202 }
2203
2204 llvm::BasicBlock *getInvokeDest() {
2205 if (!EHStack.requiresLandingPad())
2206 return nullptr;
2207 return getInvokeDestImpl();
2208 }
2209
2210 bool currentFunctionUsesSEHTry() const { return !!CurSEHParent; }
2211
2212 const TargetInfo &getTarget() const { return Target; }
2213 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
2214 const TargetCodeGenInfo &getTargetHooks() const {
2215 return CGM.getTargetCodeGenInfo();
2216 }
2217
2218 //===--------------------------------------------------------------------===//
2219 // Cleanups
2220 //===--------------------------------------------------------------------===//
2221
2222 typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
2223
2224 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
2225 Address arrayEndPointer,
2226 QualType elementType,
2227 CharUnits elementAlignment,
2228 Destroyer *destroyer);
2229 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2230 llvm::Value *arrayEnd,
2231 QualType elementType,
2232 CharUnits elementAlignment,
2233 Destroyer *destroyer);
2234
2235 void pushDestroy(QualType::DestructionKind dtorKind, Address addr,
2236 QualType type);
2237 void pushEHDestroy(QualType::DestructionKind dtorKind, Address addr,
2238 QualType type);
2239 void pushDestroy(CleanupKind kind, Address addr, QualType type,
2240 Destroyer *destroyer, bool useEHCleanupForArray);
2241 void pushDestroyAndDeferDeactivation(QualType::DestructionKind dtorKind,
2242 Address addr, QualType type);
2243 void pushDestroyAndDeferDeactivation(CleanupKind cleanupKind, Address addr,
2244 QualType type, Destroyer *destroyer,
2245 bool useEHCleanupForArray);
2246 void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr,
2247 QualType type, Destroyer *destroyer,
2248 bool useEHCleanupForArray);
2249 void pushLifetimeExtendedDestroy(QualType::DestructionKind dtorKind,
2250 Address addr, QualType type);
2251 void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
2252 llvm::Value *CompletePtr,
2253 QualType ElementType);
2254 void pushStackRestore(CleanupKind kind, Address SPMem);
2255 void pushKmpcAllocFree(CleanupKind Kind,
2256 std::pair<llvm::Value *, llvm::Value *> AddrSizePair);
2257 void emitDestroy(Address addr, QualType type, Destroyer *destroyer,
2258 bool useEHCleanupForArray);
2259 llvm::Function *generateDestroyHelper(Address addr, QualType type,
2260 Destroyer *destroyer,
2261 bool useEHCleanupForArray,
2262 const VarDecl *VD);
2263 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
2264 QualType elementType, CharUnits elementAlign,
2265 Destroyer *destroyer, bool checkZeroLength,
2266 bool useEHCleanup);
2267
2268 Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
2269
2270 /// Determines whether an EH cleanup is required to destroy a type
2271 /// with the given destruction kind.
2272 bool needsEHCleanup(QualType::DestructionKind kind) {
2273 switch (kind) {
2274 case QualType::DK_none:
2275 return false;
2276 case QualType::DK_cxx_destructor:
2277 case QualType::DK_objc_weak_lifetime:
2278 case QualType::DK_nontrivial_c_struct:
2279 return getLangOpts().Exceptions;
2280 case QualType::DK_objc_strong_lifetime:
2281 return getLangOpts().Exceptions &&
2282 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
2283 }
2284 llvm_unreachable("bad destruction kind");
2285 }
2286
2287 CleanupKind getCleanupKind(QualType::DestructionKind kind) {
2288 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
2289 }
2290
2291 //===--------------------------------------------------------------------===//
2292 // Objective-C
2293 //===--------------------------------------------------------------------===//
2294
2295 void GenerateObjCMethod(const ObjCMethodDecl *OMD);
2296
2297 void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
2298
2299 /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
2300 void GenerateObjCGetter(ObjCImplementationDecl *IMP,
2301 const ObjCPropertyImplDecl *PID);
2302 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
2303 const ObjCPropertyImplDecl *propImpl,
2304 const ObjCMethodDecl *GetterMothodDecl,
2305 llvm::Constant *AtomicHelperFn);
2306
2307 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
2308 ObjCMethodDecl *MD, bool ctor);
2309
2310 /// GenerateObjCSetter - Synthesize an Objective-C property setter function
2311 /// for the given property.
2312 void GenerateObjCSetter(ObjCImplementationDecl *IMP,
2313 const ObjCPropertyImplDecl *PID);
2314 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
2315 const ObjCPropertyImplDecl *propImpl,
2316 llvm::Constant *AtomicHelperFn);
2317
2318 //===--------------------------------------------------------------------===//
2319 // Block Bits
2320 //===--------------------------------------------------------------------===//
2321
2322 /// Emit block literal.
2323 /// \return an LLVM value which is a pointer to a struct which contains
2324 /// information about the block, including the block invoke function, the
2325 /// captured variables, etc.
2326 llvm::Value *EmitBlockLiteral(const BlockExpr *);
2327
2328 llvm::Function *GenerateBlockFunction(GlobalDecl GD, const CGBlockInfo &Info,
2329 const DeclMapTy &ldm,
2330 bool IsLambdaConversionToBlock,
2331 bool BuildGlobalBlock);
2332
2333 /// Check if \p T is a C++ class that has a destructor that can throw.
2334 static bool cxxDestructorCanThrow(QualType T);
2335
2336 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
2337 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
2338 llvm::Constant *
2339 GenerateObjCAtomicSetterCopyHelperFunction(const ObjCPropertyImplDecl *PID);
2340 llvm::Constant *
2341 GenerateObjCAtomicGetterCopyHelperFunction(const ObjCPropertyImplDecl *PID);
2342 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
2343
2344 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags,
2345 bool CanThrow);
2346
2347 class AutoVarEmission;
2348
2349 void emitByrefStructureInit(const AutoVarEmission &emission);
2350
2351 /// Enter a cleanup to destroy a __block variable. Note that this
2352 /// cleanup should be a no-op if the variable hasn't left the stack
2353 /// yet; if a cleanup is required for the variable itself, that needs
2354 /// to be done externally.
2355 ///
2356 /// \param Kind Cleanup kind.
2357 ///
2358 /// \param Addr When \p LoadBlockVarAddr is false, the address of the __block
2359 /// structure that will be passed to _Block_object_dispose. When
2360 /// \p LoadBlockVarAddr is true, the address of the field of the block
2361 /// structure that holds the address of the __block structure.
2362 ///
2363 /// \param Flags The flag that will be passed to _Block_object_dispose.
2364 ///
2365 /// \param LoadBlockVarAddr Indicates whether we need to emit a load from
2366 /// \p Addr to get the address of the __block structure.
2367 void enterByrefCleanup(CleanupKind Kind, Address Addr, BlockFieldFlags Flags,
2368 bool LoadBlockVarAddr, bool CanThrow);
2369
2370 void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
2371 llvm::Value *ptr);
2372
2373 Address LoadBlockStruct();
2374 Address GetAddrOfBlockDecl(const VarDecl *var);
2375
2376 /// BuildBlockByrefAddress - Computes the location of the
2377 /// data in a variable which is declared as __block.
2378 Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V,
2379 bool followForward = true);
2380 Address emitBlockByrefAddress(Address baseAddr, const BlockByrefInfo &info,
2381 bool followForward, const llvm::Twine &name);
2382
2383 const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var);
2384
2385 QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args);
2386
2387 void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
2388 const CGFunctionInfo &FnInfo);
2389
2390 /// Annotate the function with an attribute that disables TSan checking at
2391 /// runtime.
2392 void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn);
2393
2394 /// Emit code for the start of a function.
2395 /// \param Loc The location to be associated with the function.
2396 /// \param StartLoc The location of the function body.
2397 void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn,
2398 const CGFunctionInfo &FnInfo, const FunctionArgList &Args,
2399 SourceLocation Loc = SourceLocation(),
2400 SourceLocation StartLoc = SourceLocation());
2401
2402 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor);
2403
2404 void EmitConstructorBody(FunctionArgList &Args);
2405 void EmitDestructorBody(FunctionArgList &Args);
2406 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
2407 void EmitFunctionBody(const Stmt *Body);
2408 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
2409
2410 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
2411 CallArgList &CallArgs,
2412 const CGFunctionInfo *CallOpFnInfo = nullptr,
2413 llvm::Constant *CallOpFn = nullptr);
2414 void EmitLambdaBlockInvokeBody();
2415 void EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD);
2416 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD,
2417 CallArgList &CallArgs);
2418 void EmitLambdaInAllocaImplFn(const CXXMethodDecl *CallOp,
2419 const CGFunctionInfo **ImplFnInfo,
2420 llvm::Function **ImplFn);
2421 void EmitLambdaInAllocaCallOpBody(const CXXMethodDecl *MD);
2422 void EmitLambdaVLACapture(const VariableArrayType *VAT, LValue LV) {
2423 EmitStoreThroughLValue(Src: RValue::get(V: VLASizeMap[VAT->getSizeExpr()]), Dst: LV);
2424 }
2425 void EmitAsanPrologueOrEpilogue(bool Prologue);
2426
2427 /// Emit the unified return block, trying to avoid its emission when
2428 /// possible.
2429 /// \return The debug location of the user written return statement if the
2430 /// return block is avoided.
2431 llvm::DebugLoc EmitReturnBlock();
2432
2433 /// FinishFunction - Complete IR generation of the current function. It is
2434 /// legal to call this function even if there is no current insertion point.
2435 void FinishFunction(SourceLocation EndLoc = SourceLocation());
2436
2437 void StartThunk(llvm::Function *Fn, GlobalDecl GD,
2438 const CGFunctionInfo &FnInfo, bool IsUnprototyped);
2439
2440 void EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
2441 const ThunkInfo *Thunk, bool IsUnprototyped);
2442
2443 void FinishThunk();
2444
2445 /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
2446 void EmitMustTailThunk(GlobalDecl GD, llvm::Value *AdjustedThisPtr,
2447 llvm::FunctionCallee Callee);
2448
2449 /// Generate a thunk for the given method.
2450 void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
2451 GlobalDecl GD, const ThunkInfo &Thunk,
2452 bool IsUnprototyped);
2453
2454 llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
2455 const CGFunctionInfo &FnInfo,
2456 GlobalDecl GD, const ThunkInfo &Thunk);
2457
2458 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
2459 FunctionArgList &Args);
2460
2461 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init);
2462
2463 /// Struct with all information about dynamic [sub]class needed to set vptr.
2464 struct VPtr {
2465 BaseSubobject Base;
2466 const CXXRecordDecl *NearestVBase;
2467 CharUnits OffsetFromNearestVBase;
2468 const CXXRecordDecl *VTableClass;
2469 };
2470
2471 /// Initialize the vtable pointer of the given subobject.
2472 void InitializeVTablePointer(const VPtr &vptr);
2473
2474 typedef llvm::SmallVector<VPtr, 4> VPtrsVector;
2475
2476 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
2477 VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass);
2478
2479 void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase,
2480 CharUnits OffsetFromNearestVBase,
2481 bool BaseIsNonVirtualPrimaryBase,
2482 const CXXRecordDecl *VTableClass,
2483 VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
2484
2485 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
2486
2487 // VTableTrapMode - whether we guarantee that loading the
2488 // vtable is guaranteed to trap on authentication failure,
2489 // even if the resulting vtable pointer is unused.
2490 enum class VTableAuthMode {
2491 Authenticate,
2492 MustTrap,
2493 UnsafeUbsanStrip // Should only be used for Vptr UBSan check
2494 };
2495 /// GetVTablePtr - Return the Value of the vtable pointer member pointed
2496 /// to by This.
2497 llvm::Value *
2498 GetVTablePtr(Address This, llvm::Type *VTableTy,
2499 const CXXRecordDecl *VTableClass,
2500 VTableAuthMode AuthMode = VTableAuthMode::Authenticate);
2501
2502 enum CFITypeCheckKind {
2503 CFITCK_VCall,
2504 CFITCK_NVCall,
2505 CFITCK_DerivedCast,
2506 CFITCK_UnrelatedCast,
2507 CFITCK_ICall,
2508 CFITCK_NVMFCall,
2509 CFITCK_VMFCall,
2510 };
2511
2512 /// Derived is the presumed address of an object of type T after a
2513 /// cast. If T is a polymorphic class type, emit a check that the virtual
2514 /// table for Derived belongs to a class derived from T.
2515 void EmitVTablePtrCheckForCast(QualType T, Address Derived, bool MayBeNull,
2516 CFITypeCheckKind TCK, SourceLocation Loc);
2517
2518 /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
2519 /// If vptr CFI is enabled, emit a check that VTable is valid.
2520 void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
2521 CFITypeCheckKind TCK, SourceLocation Loc);
2522
2523 /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
2524 /// RD using llvm.type.test.
2525 void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
2526 CFITypeCheckKind TCK, SourceLocation Loc);
2527
2528 /// If whole-program virtual table optimization is enabled, emit an assumption
2529 /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
2530 /// enabled, emit a check that VTable is a member of RD's type identifier.
2531 void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
2532 llvm::Value *VTable, SourceLocation Loc);
2533
2534 /// Returns whether we should perform a type checked load when loading a
2535 /// virtual function for virtual calls to members of RD. This is generally
2536 /// true when both vcall CFI and whole-program-vtables are enabled.
2537 bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD);
2538
2539 /// Emit a type checked load from the given vtable.
2540 llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD,
2541 llvm::Value *VTable,
2542 llvm::Type *VTableTy,
2543 uint64_t VTableByteOffset);
2544
2545 /// EnterDtorCleanups - Enter the cleanups necessary to complete the
2546 /// given phase of destruction for a destructor. The end result
2547 /// should call destructors on members and base classes in reverse
2548 /// order of their construction.
2549 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
2550
2551 /// ShouldInstrumentFunction - Return true if the current function should be
2552 /// instrumented with __cyg_profile_func_* calls
2553 bool ShouldInstrumentFunction();
2554
2555 /// ShouldSkipSanitizerInstrumentation - Return true if the current function
2556 /// should not be instrumented with sanitizers.
2557 bool ShouldSkipSanitizerInstrumentation();
2558
2559 /// ShouldXRayInstrument - Return true if the current function should be
2560 /// instrumented with XRay nop sleds.
2561 bool ShouldXRayInstrumentFunction() const;
2562
2563 /// AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit
2564 /// XRay custom event handling calls.
2565 bool AlwaysEmitXRayCustomEvents() const;
2566
2567 /// AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit
2568 /// XRay typed event handling calls.
2569 bool AlwaysEmitXRayTypedEvents() const;
2570
2571 /// Return a type hash constant for a function instrumented by
2572 /// -fsanitize=function.
2573 llvm::ConstantInt *getUBSanFunctionTypeHash(QualType T) const;
2574
2575 /// EmitFunctionProlog - Emit the target specific LLVM code to load the
2576 /// arguments for the given function. This is also responsible for naming the
2577 /// LLVM function arguments.
2578 void EmitFunctionProlog(const CGFunctionInfo &FI, llvm::Function *Fn,
2579 const FunctionArgList &Args);
2580
2581 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
2582 /// given temporary. Specify the source location atom group (Key Instructions
2583 /// debug info feature) for the `ret` using \p RetKeyInstructionsSourceAtom.
2584 /// If it's 0, the `ret` will get added to a new source atom group.
2585 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
2586 SourceLocation EndLoc,
2587 uint64_t RetKeyInstructionsSourceAtom);
2588
2589 /// Emit a test that checks if the return value \p RV is nonnull.
2590 void EmitReturnValueCheck(llvm::Value *RV);
2591
2592 /// EmitStartEHSpec - Emit the start of the exception spec.
2593 void EmitStartEHSpec(const Decl *D);
2594
2595 /// EmitEndEHSpec - Emit the end of the exception spec.
2596 void EmitEndEHSpec(const Decl *D);
2597
2598 /// getTerminateLandingPad - Return a landing pad that just calls terminate.
2599 llvm::BasicBlock *getTerminateLandingPad();
2600
2601 /// getTerminateLandingPad - Return a cleanup funclet that just calls
2602 /// terminate.
2603 llvm::BasicBlock *getTerminateFunclet();
2604
2605 /// getTerminateHandler - Return a handler (not a landing pad, just
2606 /// a catch handler) that just calls terminate. This is used when
2607 /// a terminate scope encloses a try.
2608 llvm::BasicBlock *getTerminateHandler();
2609
2610 llvm::Type *ConvertTypeForMem(QualType T);
2611 llvm::Type *ConvertType(QualType T);
2612 llvm::Type *convertTypeForLoadStore(QualType ASTTy,
2613 llvm::Type *LLVMTy = nullptr);
2614 llvm::Type *ConvertType(const TypeDecl *T) {
2615 return ConvertType(T: getContext().getTypeDeclType(Decl: T));
2616 }
2617
2618 /// LoadObjCSelf - Load the value of self. This function is only valid while
2619 /// generating code for an Objective-C method.
2620 llvm::Value *LoadObjCSelf();
2621
2622 /// TypeOfSelfObject - Return type of object that this self represents.
2623 QualType TypeOfSelfObject();
2624
2625 /// getEvaluationKind - Return the TypeEvaluationKind of QualType \c T.
2626 static TypeEvaluationKind getEvaluationKind(QualType T);
2627
2628 static bool hasScalarEvaluationKind(QualType T) {
2629 return getEvaluationKind(T) == TEK_Scalar;
2630 }
2631
2632 static bool hasAggregateEvaluationKind(QualType T) {
2633 return getEvaluationKind(T) == TEK_Aggregate;
2634 }
2635
2636 /// createBasicBlock - Create an LLVM basic block.
2637 llvm::BasicBlock *createBasicBlock(const Twine &name = "",
2638 llvm::Function *parent = nullptr,
2639 llvm::BasicBlock *before = nullptr) {
2640 return llvm::BasicBlock::Create(Context&: getLLVMContext(), Name: name, Parent: parent, InsertBefore: before);
2641 }
2642
2643 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
2644 /// label maps to.
2645 JumpDest getJumpDestForLabel(const LabelDecl *S);
2646
2647 /// SimplifyForwardingBlocks - If the given basic block is only a branch to
2648 /// another basic block, simplify it. This assumes that no other code could
2649 /// potentially reference the basic block.
2650 void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
2651
2652 /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
2653 /// adding a fall-through branch from the current insert block if
2654 /// necessary. It is legal to call this function even if there is no current
2655 /// insertion point.
2656 ///
2657 /// IsFinished - If true, indicates that the caller has finished emitting
2658 /// branches to the given block and does not expect to emit code into it. This
2659 /// means the block can be ignored if it is unreachable.
2660 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished = false);
2661
2662 /// EmitBlockAfterUses - Emit the given block somewhere hopefully
2663 /// near its uses, and leave the insertion point in it.
2664 void EmitBlockAfterUses(llvm::BasicBlock *BB);
2665
2666 /// EmitBranch - Emit a branch to the specified basic block from the current
2667 /// insert block, taking care to avoid creation of branches from dummy
2668 /// blocks. It is legal to call this function even if there is no current
2669 /// insertion point.
2670 ///
2671 /// This function clears the current insertion point. The caller should follow
2672 /// calls to this function with calls to Emit*Block prior to generation new
2673 /// code.
2674 void EmitBranch(llvm::BasicBlock *Block);
2675
2676 /// HaveInsertPoint - True if an insertion point is defined. If not, this
2677 /// indicates that the current code being emitted is unreachable.
2678 bool HaveInsertPoint() const { return Builder.GetInsertBlock() != nullptr; }
2679
2680 /// EnsureInsertPoint - Ensure that an insertion point is defined so that
2681 /// emitted IR has a place to go. Note that by definition, if this function
2682 /// creates a block then that block is unreachable; callers may do better to
2683 /// detect when no insertion point is defined and simply skip IR generation.
2684 void EnsureInsertPoint() {
2685 if (!HaveInsertPoint())
2686 EmitBlock(BB: createBasicBlock());
2687 }
2688
2689 /// ErrorUnsupported - Print out an error that codegen doesn't support the
2690 /// specified stmt yet.
2691 void ErrorUnsupported(const Stmt *S, const char *Type);
2692
2693 //===--------------------------------------------------------------------===//
2694 // Helpers
2695 //===--------------------------------------------------------------------===//
2696
2697 Address mergeAddressesInConditionalExpr(Address LHS, Address RHS,
2698 llvm::BasicBlock *LHSBlock,
2699 llvm::BasicBlock *RHSBlock,
2700 llvm::BasicBlock *MergeBlock,
2701 QualType MergedType) {
2702 Builder.SetInsertPoint(MergeBlock);
2703 llvm::PHINode *PtrPhi = Builder.CreatePHI(Ty: LHS.getType(), NumReservedValues: 2, Name: "cond");
2704 PtrPhi->addIncoming(V: LHS.getBasePointer(), BB: LHSBlock);
2705 PtrPhi->addIncoming(V: RHS.getBasePointer(), BB: RHSBlock);
2706 LHS.replaceBasePointer(P: PtrPhi);
2707 LHS.setAlignment(std::min(a: LHS.getAlignment(), b: RHS.getAlignment()));
2708 return LHS;
2709 }
2710
2711 /// Construct an address with the natural alignment of T. If a pointer to T
2712 /// is expected to be signed, the pointer passed to this function must have
2713 /// been signed, and the returned Address will have the pointer authentication
2714 /// information needed to authenticate the signed pointer.
2715 Address makeNaturalAddressForPointer(
2716 llvm::Value *Ptr, QualType T, CharUnits Alignment = CharUnits::Zero(),
2717 bool ForPointeeType = false, LValueBaseInfo *BaseInfo = nullptr,
2718 TBAAAccessInfo *TBAAInfo = nullptr,
2719 KnownNonNull_t IsKnownNonNull = NotKnownNonNull) {
2720 if (Alignment.isZero())
2721 Alignment =
2722 CGM.getNaturalTypeAlignment(T, BaseInfo, TBAAInfo, forPointeeType: ForPointeeType);
2723 return Address(Ptr, ConvertTypeForMem(T), Alignment,
2724 CGM.getPointerAuthInfoForPointeeType(type: T), /*Offset=*/nullptr,
2725 IsKnownNonNull);
2726 }
2727
2728 LValue MakeAddrLValue(Address Addr, QualType T,
2729 AlignmentSource Source = AlignmentSource::Type) {
2730 return MakeAddrLValue(Addr, T, BaseInfo: LValueBaseInfo(Source),
2731 TBAAInfo: CGM.getTBAAAccessInfo(AccessType: T));
2732 }
2733
2734 LValue MakeAddrLValue(Address Addr, QualType T, LValueBaseInfo BaseInfo,
2735 TBAAAccessInfo TBAAInfo) {
2736 return LValue::MakeAddr(Addr, type: T, Context&: getContext(), BaseInfo, TBAAInfo);
2737 }
2738
2739 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
2740 AlignmentSource Source = AlignmentSource::Type) {
2741 return MakeAddrLValue(Addr: makeNaturalAddressForPointer(Ptr: V, T, Alignment), T,
2742 BaseInfo: LValueBaseInfo(Source), TBAAInfo: CGM.getTBAAAccessInfo(AccessType: T));
2743 }
2744
2745 /// Same as MakeAddrLValue above except that the pointer is known to be
2746 /// unsigned.
2747 LValue MakeRawAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
2748 AlignmentSource Source = AlignmentSource::Type) {
2749 Address Addr(V, ConvertTypeForMem(T), Alignment);
2750 return LValue::MakeAddr(Addr, type: T, Context&: getContext(), BaseInfo: LValueBaseInfo(Source),
2751 TBAAInfo: CGM.getTBAAAccessInfo(AccessType: T));
2752 }
2753
2754 LValue
2755 MakeAddrLValueWithoutTBAA(Address Addr, QualType T,
2756 AlignmentSource Source = AlignmentSource::Type) {
2757 return LValue::MakeAddr(Addr, type: T, Context&: getContext(), BaseInfo: LValueBaseInfo(Source),
2758 TBAAInfo: TBAAAccessInfo());
2759 }
2760
2761 /// Given a value of type T* that may not be to a complete object, construct
2762 /// an l-value with the natural pointee alignment of T.
2763 LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
2764
2765 LValue
2766 MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T,
2767 KnownNonNull_t IsKnownNonNull = NotKnownNonNull);
2768
2769 /// Same as MakeNaturalAlignPointeeAddrLValue except that the pointer is known
2770 /// to be unsigned.
2771 LValue MakeNaturalAlignPointeeRawAddrLValue(llvm::Value *V, QualType T);
2772
2773 LValue MakeNaturalAlignRawAddrLValue(llvm::Value *V, QualType T);
2774
2775 Address EmitLoadOfReference(LValue RefLVal,
2776 LValueBaseInfo *PointeeBaseInfo = nullptr,
2777 TBAAAccessInfo *PointeeTBAAInfo = nullptr);
2778 LValue EmitLoadOfReferenceLValue(LValue RefLVal);
2779 LValue
2780 EmitLoadOfReferenceLValue(Address RefAddr, QualType RefTy,
2781 AlignmentSource Source = AlignmentSource::Type) {
2782 LValue RefLVal = MakeAddrLValue(Addr: RefAddr, T: RefTy, BaseInfo: LValueBaseInfo(Source),
2783 TBAAInfo: CGM.getTBAAAccessInfo(AccessType: RefTy));
2784 return EmitLoadOfReferenceLValue(RefLVal);
2785 }
2786
2787 /// Load a pointer with type \p PtrTy stored at address \p Ptr.
2788 /// Note that \p PtrTy is the type of the loaded pointer, not the addresses
2789 /// it is loaded from.
2790 Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
2791 LValueBaseInfo *BaseInfo = nullptr,
2792 TBAAAccessInfo *TBAAInfo = nullptr);
2793 LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy);
2794
2795private:
2796 struct AllocaTracker {
2797 void Add(llvm::AllocaInst *I) { Allocas.push_back(Elt: I); }
2798 llvm::SmallVector<llvm::AllocaInst *> Take() { return std::move(Allocas); }
2799
2800 private:
2801 llvm::SmallVector<llvm::AllocaInst *> Allocas;
2802 };
2803 AllocaTracker *Allocas = nullptr;
2804
2805 /// CGDecl helper.
2806 void emitStoresForConstant(const VarDecl &D, Address Loc, bool isVolatile,
2807 llvm::Constant *constant, bool IsAutoInit);
2808 /// CGDecl helper.
2809 void emitStoresForZeroInit(const VarDecl &D, Address Loc, bool isVolatile);
2810 /// CGDecl helper.
2811 void emitStoresForPatternInit(const VarDecl &D, Address Loc, bool isVolatile);
2812 /// CGDecl helper.
2813 void emitStoresForInitAfterBZero(llvm::Constant *Init, Address Loc,
2814 bool isVolatile, bool IsAutoInit);
2815
2816public:
2817 // Captures all the allocas created during the scope of its RAII object.
2818 struct AllocaTrackerRAII {
2819 AllocaTrackerRAII(CodeGenFunction &CGF)
2820 : CGF(CGF), OldTracker(CGF.Allocas) {
2821 CGF.Allocas = &Tracker;
2822 }
2823 ~AllocaTrackerRAII() { CGF.Allocas = OldTracker; }
2824
2825 llvm::SmallVector<llvm::AllocaInst *> Take() { return Tracker.Take(); }
2826
2827 private:
2828 CodeGenFunction &CGF;
2829 AllocaTracker *OldTracker;
2830 AllocaTracker Tracker;
2831 };
2832
2833private:
2834 /// If \p Alloca is not in the same address space as \p DestLangAS, insert an
2835 /// address space cast and return a new RawAddress based on this value.
2836 RawAddress MaybeCastStackAddressSpace(RawAddress Alloca, LangAS DestLangAS,
2837 llvm::Value *ArraySize = nullptr);
2838
2839public:
2840 /// CreateTempAlloca - This creates an alloca and inserts it into the entry
2841 /// block if \p ArraySize is nullptr, otherwise inserts it at the current
2842 /// insertion point of the builder. The caller is responsible for setting an
2843 /// appropriate alignment on
2844 /// the alloca.
2845 ///
2846 /// \p ArraySize is the number of array elements to be allocated if it
2847 /// is not nullptr.
2848 ///
2849 /// LangAS::Default is the address space of pointers to local variables and
2850 /// temporaries, as exposed in the source language. In certain
2851 /// configurations, this is not the same as the alloca address space, and a
2852 /// cast is needed to lift the pointer from the alloca AS into
2853 /// LangAS::Default. This can happen when the target uses a restricted
2854 /// address space for the stack but the source language requires
2855 /// LangAS::Default to be a generic address space. The latter condition is
2856 /// common for most programming languages; OpenCL is an exception in that
2857 /// LangAS::Default is the private address space, which naturally maps
2858 /// to the stack.
2859 ///
2860 /// Because the address of a temporary is often exposed to the program in
2861 /// various ways, this function will perform the cast. The original alloca
2862 /// instruction is returned through \p Alloca if it is not nullptr.
2863 ///
2864 /// The cast is not performaed in CreateTempAllocaWithoutCast. This is
2865 /// more efficient if the caller knows that the address will not be exposed.
2866 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, const Twine &Name = "tmp",
2867 llvm::Value *ArraySize = nullptr);
2868
2869 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
2870 /// block. The alloca is casted to the address space of \p UseAddrSpace if
2871 /// necessary.
2872 RawAddress CreateTempAlloca(llvm::Type *Ty, LangAS UseAddrSpace,
2873 CharUnits align, const Twine &Name = "tmp",
2874 llvm::Value *ArraySize = nullptr,
2875 RawAddress *Alloca = nullptr);
2876
2877 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
2878 /// block. The alloca is casted to default address space if necessary.
2879 ///
2880 /// FIXME: This version should be removed, and context should provide the
2881 /// context use address space used instead of default.
2882 RawAddress CreateTempAlloca(llvm::Type *Ty, CharUnits align,
2883 const Twine &Name = "tmp",
2884 llvm::Value *ArraySize = nullptr,
2885 RawAddress *Alloca = nullptr) {
2886 return CreateTempAlloca(Ty, UseAddrSpace: LangAS::Default, align, Name, ArraySize,
2887 Alloca);
2888 }
2889
2890 RawAddress CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align,
2891 const Twine &Name = "tmp",
2892 llvm::Value *ArraySize = nullptr);
2893
2894 /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
2895 /// default ABI alignment of the given LLVM type.
2896 ///
2897 /// IMPORTANT NOTE: This is *not* generally the right alignment for
2898 /// any given AST type that happens to have been lowered to the
2899 /// given IR type. This should only ever be used for function-local,
2900 /// IR-driven manipulations like saving and restoring a value. Do
2901 /// not hand this address off to arbitrary IRGen routines, and especially
2902 /// do not pass it as an argument to a function that might expect a
2903 /// properly ABI-aligned value.
2904 RawAddress CreateDefaultAlignTempAlloca(llvm::Type *Ty,
2905 const Twine &Name = "tmp");
2906
2907 /// CreateIRTemp - Create a temporary IR object of the given type, with
2908 /// appropriate alignment. This routine should only be used when an temporary
2909 /// value needs to be stored into an alloca (for example, to avoid explicit
2910 /// PHI construction), but the type is the IR type, not the type appropriate
2911 /// for storing in memory.
2912 ///
2913 /// That is, this is exactly equivalent to CreateMemTemp, but calling
2914 /// ConvertType instead of ConvertTypeForMem.
2915 RawAddress CreateIRTemp(QualType T, const Twine &Name = "tmp");
2916
2917 /// CreateMemTemp - Create a temporary memory object of the given type, with
2918 /// appropriate alignmen and cast it to the default address space. Returns
2919 /// the original alloca instruction by \p Alloca if it is not nullptr.
2920 RawAddress CreateMemTemp(QualType T, const Twine &Name = "tmp",
2921 RawAddress *Alloca = nullptr);
2922 RawAddress CreateMemTemp(QualType T, CharUnits Align,
2923 const Twine &Name = "tmp",
2924 RawAddress *Alloca = nullptr);
2925
2926 /// CreateMemTemp - Create a temporary memory object of the given type, with
2927 /// appropriate alignmen without casting it to the default address space.
2928 RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name = "tmp");
2929 RawAddress CreateMemTempWithoutCast(QualType T, CharUnits Align,
2930 const Twine &Name = "tmp");
2931
2932 /// CreateAggTemp - Create a temporary memory object for the given
2933 /// aggregate type.
2934 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp",
2935 RawAddress *Alloca = nullptr) {
2936 return AggValueSlot::forAddr(
2937 addr: CreateMemTemp(T, Name, Alloca), quals: T.getQualifiers(),
2938 isDestructed: AggValueSlot::IsNotDestructed, needsGC: AggValueSlot::DoesNotNeedGCBarriers,
2939 isAliased: AggValueSlot::IsNotAliased, mayOverlap: AggValueSlot::DoesNotOverlap);
2940 }
2941
2942 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
2943 /// expression and compare the result against zero, returning an Int1Ty value.
2944 llvm::Value *EvaluateExprAsBool(const Expr *E);
2945
2946 /// Retrieve the implicit cast expression of the rhs in a binary operator
2947 /// expression by passing pointers to Value and QualType
2948 /// This is used for implicit bitfield conversion checks, which
2949 /// must compare with the value before potential truncation.
2950 llvm::Value *EmitWithOriginalRHSBitfieldAssignment(const BinaryOperator *E,
2951 llvm::Value **Previous,
2952 QualType *SrcType);
2953
2954 /// Emit a check that an [implicit] conversion of a bitfield. It is not UB,
2955 /// so we use the value after conversion.
2956 void EmitBitfieldConversionCheck(llvm::Value *Src, QualType SrcType,
2957 llvm::Value *Dst, QualType DstType,
2958 const CGBitFieldInfo &Info,
2959 SourceLocation Loc);
2960
2961 /// EmitIgnoredExpr - Emit an expression in a context which ignores the
2962 /// result.
2963 void EmitIgnoredExpr(const Expr *E);
2964
2965 /// EmitAnyExpr - Emit code to compute the specified expression which can have
2966 /// any type. The result is returned as an RValue struct. If this is an
2967 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
2968 /// the result should be returned.
2969 ///
2970 /// \param ignoreResult True if the resulting value isn't used.
2971 RValue EmitAnyExpr(const Expr *E,
2972 AggValueSlot aggSlot = AggValueSlot::ignored(),
2973 bool ignoreResult = false);
2974
2975 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
2976 // or the value of the expression, depending on how va_list is defined.
2977 Address EmitVAListRef(const Expr *E);
2978
2979 /// Emit a "reference" to a __builtin_ms_va_list; this is
2980 /// always the value of the expression, because a __builtin_ms_va_list is a
2981 /// pointer to a char.
2982 Address EmitMSVAListRef(const Expr *E);
2983
2984 /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will
2985 /// always be accessible even if no aggregate location is provided.
2986 RValue EmitAnyExprToTemp(const Expr *E);
2987
2988 /// EmitAnyExprToMem - Emits the code necessary to evaluate an
2989 /// arbitrary expression into the given memory location.
2990 void EmitAnyExprToMem(const Expr *E, Address Location, Qualifiers Quals,
2991 bool IsInitializer);
2992
2993 void EmitAnyExprToExn(const Expr *E, Address Addr);
2994
2995 /// EmitInitializationToLValue - Emit an initializer to an LValue.
2996 void EmitInitializationToLValue(
2997 const Expr *E, LValue LV,
2998 AggValueSlot::IsZeroed_t IsZeroed = AggValueSlot::IsNotZeroed);
2999
3000 /// EmitExprAsInit - Emits the code necessary to initialize a
3001 /// location in memory with the given initializer.
3002 void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
3003 bool capturedByInit);
3004
3005 /// hasVolatileMember - returns true if aggregate type has a volatile
3006 /// member.
3007 bool hasVolatileMember(QualType T) {
3008 if (const auto *RD = T->getAsRecordDecl())
3009 return RD->hasVolatileMember();
3010 return false;
3011 }
3012
3013 /// Determine whether a return value slot may overlap some other object.
3014 AggValueSlot::Overlap_t getOverlapForReturnValue() {
3015 // FIXME: Assuming no overlap here breaks guaranteed copy elision for base
3016 // class subobjects. These cases may need to be revisited depending on the
3017 // resolution of the relevant core issue.
3018 return AggValueSlot::DoesNotOverlap;
3019 }
3020
3021 /// Determine whether a field initialization may overlap some other object.
3022 AggValueSlot::Overlap_t getOverlapForFieldInit(const FieldDecl *FD);
3023
3024 /// Determine whether a base class initialization may overlap some other
3025 /// object.
3026 AggValueSlot::Overlap_t getOverlapForBaseInit(const CXXRecordDecl *RD,
3027 const CXXRecordDecl *BaseRD,
3028 bool IsVirtual);
3029
3030 /// Emit an aggregate assignment.
3031 void EmitAggregateAssign(LValue Dest, LValue Src, QualType EltTy) {
3032 ApplyAtomGroup Grp(getDebugInfo());
3033 bool IsVolatile = hasVolatileMember(T: EltTy);
3034 EmitAggregateCopy(Dest, Src, EltTy, MayOverlap: AggValueSlot::MayOverlap, isVolatile: IsVolatile);
3035 }
3036
3037 void EmitAggregateCopyCtor(LValue Dest, LValue Src,
3038 AggValueSlot::Overlap_t MayOverlap) {
3039 EmitAggregateCopy(Dest, Src, EltTy: Src.getType(), MayOverlap);
3040 }
3041
3042 /// EmitAggregateCopy - Emit an aggregate copy.
3043 ///
3044 /// \param isVolatile \c true iff either the source or the destination is
3045 /// volatile.
3046 /// \param MayOverlap Whether the tail padding of the destination might be
3047 /// occupied by some other object. More efficient code can often be
3048 /// generated if not.
3049 void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy,
3050 AggValueSlot::Overlap_t MayOverlap,
3051 bool isVolatile = false);
3052
3053 /// GetAddrOfLocalVar - Return the address of a local variable.
3054 Address GetAddrOfLocalVar(const VarDecl *VD) {
3055 auto it = LocalDeclMap.find(Val: VD);
3056 assert(it != LocalDeclMap.end() &&
3057 "Invalid argument to GetAddrOfLocalVar(), no decl!");
3058 return it->second;
3059 }
3060
3061 /// Given an opaque value expression, return its LValue mapping if it exists,
3062 /// otherwise create one.
3063 LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e);
3064
3065 /// Given an opaque value expression, return its RValue mapping if it exists,
3066 /// otherwise create one.
3067 RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e);
3068
3069 /// isOpaqueValueEmitted - Return true if the opaque value expression has
3070 /// already been emitted.
3071 bool isOpaqueValueEmitted(const OpaqueValueExpr *E);
3072
3073 /// Get the index of the current ArrayInitLoopExpr, if any.
3074 llvm::Value *getArrayInitIndex() { return ArrayInitIndex; }
3075
3076 /// getAccessedFieldNo - Given an encoded value and a result number, return
3077 /// the input field number being accessed.
3078 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
3079
3080 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
3081 llvm::BasicBlock *GetIndirectGotoBlock();
3082
3083 /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts.
3084 static bool IsWrappedCXXThis(const Expr *E);
3085
3086 /// EmitNullInitialization - Generate code to set a value of the given type to
3087 /// null, If the type contains data member pointers, they will be initialized
3088 /// to -1 in accordance with the Itanium C++ ABI.
3089 void EmitNullInitialization(Address DestPtr, QualType Ty);
3090
3091 /// Emits a call to an LLVM variable-argument intrinsic, either
3092 /// \c llvm.va_start or \c llvm.va_end.
3093 /// \param ArgValue A reference to the \c va_list as emitted by either
3094 /// \c EmitVAListRef or \c EmitMSVAListRef.
3095 /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
3096 /// calls \c llvm.va_end.
3097 llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
3098
3099 /// Generate code to get an argument from the passed in pointer
3100 /// and update it accordingly.
3101 /// \param VE The \c VAArgExpr for which to generate code.
3102 /// \param VAListAddr Receives a reference to the \c va_list as emitted by
3103 /// either \c EmitVAListRef or \c EmitMSVAListRef.
3104 /// \returns A pointer to the argument.
3105 // FIXME: We should be able to get rid of this method and use the va_arg
3106 // instruction in LLVM instead once it works well enough.
3107 RValue EmitVAArg(VAArgExpr *VE, Address &VAListAddr,
3108 AggValueSlot Slot = AggValueSlot::ignored());
3109
3110 /// emitArrayLength - Compute the length of an array, even if it's a
3111 /// VLA, and drill down to the base element type.
3112 llvm::Value *emitArrayLength(const ArrayType *arrayType, QualType &baseType,
3113 Address &addr);
3114
3115 /// EmitVLASize - Capture all the sizes for the VLA expressions in
3116 /// the given variably-modified type and store them in the VLASizeMap.
3117 ///
3118 /// This function can be called with a null (unreachable) insert point.
3119 void EmitVariablyModifiedType(QualType Ty);
3120
3121 struct VlaSizePair {
3122 llvm::Value *NumElts;
3123 QualType Type;
3124
3125 VlaSizePair(llvm::Value *NE, QualType T) : NumElts(NE), Type(T) {}
3126 };
3127
3128 /// Return the number of elements for a single dimension
3129 /// for the given array type.
3130 VlaSizePair getVLAElements1D(const VariableArrayType *vla);
3131 VlaSizePair getVLAElements1D(QualType vla);
3132
3133 /// Returns an LLVM value that corresponds to the size,
3134 /// in non-variably-sized elements, of a variable length array type,
3135 /// plus that largest non-variably-sized element type. Assumes that
3136 /// the type has already been emitted with EmitVariablyModifiedType.
3137 VlaSizePair getVLASize(const VariableArrayType *vla);
3138 VlaSizePair getVLASize(QualType vla);
3139
3140 /// LoadCXXThis - Load the value of 'this'. This function is only valid while
3141 /// generating code for an C++ member function.
3142 llvm::Value *LoadCXXThis() {
3143 assert(CXXThisValue && "no 'this' value for this function");
3144 return CXXThisValue;
3145 }
3146 Address LoadCXXThisAddress();
3147
3148 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
3149 /// virtual bases.
3150 // FIXME: Every place that calls LoadCXXVTT is something
3151 // that needs to be abstracted properly.
3152 llvm::Value *LoadCXXVTT() {
3153 assert(CXXStructorImplicitParamValue && "no VTT value for this function");
3154 return CXXStructorImplicitParamValue;
3155 }
3156
3157 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
3158 /// complete class to the given direct base.
3159 Address GetAddressOfDirectBaseInCompleteClass(Address Value,
3160 const CXXRecordDecl *Derived,
3161 const CXXRecordDecl *Base,
3162 bool BaseIsVirtual);
3163
3164 static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
3165
3166 /// GetAddressOfBaseClass - This function will add the necessary delta to the
3167 /// load of 'this' and returns address of the base class.
3168 Address GetAddressOfBaseClass(Address Value, const CXXRecordDecl *Derived,
3169 CastExpr::path_const_iterator PathBegin,
3170 CastExpr::path_const_iterator PathEnd,
3171 bool NullCheckValue, SourceLocation Loc);
3172
3173 Address GetAddressOfDerivedClass(Address Value, const CXXRecordDecl *Derived,
3174 CastExpr::path_const_iterator PathBegin,
3175 CastExpr::path_const_iterator PathEnd,
3176 bool NullCheckValue);
3177
3178 /// GetVTTParameter - Return the VTT parameter that should be passed to a
3179 /// base constructor/destructor with virtual bases.
3180 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
3181 /// to ItaniumCXXABI.cpp together with all the references to VTT.
3182 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
3183 bool Delegating);
3184
3185 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
3186 CXXCtorType CtorType,
3187 const FunctionArgList &Args,
3188 SourceLocation Loc);
3189 // It's important not to confuse this and the previous function. Delegating
3190 // constructors are the C++0x feature. The constructor delegate optimization
3191 // is used to reduce duplication in the base and complete consturctors where
3192 // they are substantially the same.
3193 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
3194 const FunctionArgList &Args);
3195
3196 /// Emit a call to an inheriting constructor (that is, one that invokes a
3197 /// constructor inherited from a base class) by inlining its definition. This
3198 /// is necessary if the ABI does not support forwarding the arguments to the
3199 /// base class constructor (because they're variadic or similar).
3200 void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor,
3201 CXXCtorType CtorType,
3202 bool ForVirtualBase,
3203 bool Delegating,
3204 CallArgList &Args);
3205
3206 /// Emit a call to a constructor inherited from a base class, passing the
3207 /// current constructor's arguments along unmodified (without even making
3208 /// a copy).
3209 void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D,
3210 bool ForVirtualBase, Address This,
3211 bool InheritedFromVBase,
3212 const CXXInheritedCtorInitExpr *E);
3213
3214 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
3215 bool ForVirtualBase, bool Delegating,
3216 AggValueSlot ThisAVS, const CXXConstructExpr *E);
3217
3218 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
3219 bool ForVirtualBase, bool Delegating,
3220 Address This, CallArgList &Args,
3221 AggValueSlot::Overlap_t Overlap,
3222 SourceLocation Loc, bool NewPointerIsChecked,
3223 llvm::CallBase **CallOrInvoke = nullptr);
3224
3225 /// Emit assumption load for all bases. Requires to be called only on
3226 /// most-derived class and not under construction of the object.
3227 void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
3228
3229 /// Emit assumption that vptr load == global vtable.
3230 void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
3231
3232 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, Address This,
3233 Address Src, const CXXConstructExpr *E);
3234
3235 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
3236 const ArrayType *ArrayTy, Address ArrayPtr,
3237 const CXXConstructExpr *E,
3238 bool NewPointerIsChecked,
3239 bool ZeroInitialization = false);
3240
3241 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
3242 llvm::Value *NumElements, Address ArrayPtr,
3243 const CXXConstructExpr *E,
3244 bool NewPointerIsChecked,
3245 bool ZeroInitialization = false);
3246
3247 static Destroyer destroyCXXObject;
3248
3249 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
3250 bool ForVirtualBase, bool Delegating, Address This,
3251 QualType ThisTy);
3252
3253 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
3254 llvm::Type *ElementTy, Address NewPtr,
3255 llvm::Value *NumElements,
3256 llvm::Value *AllocSizeWithoutCookie);
3257
3258 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
3259 Address Ptr);
3260
3261 void EmitSehCppScopeBegin();
3262 void EmitSehCppScopeEnd();
3263 void EmitSehTryScopeBegin();
3264 void EmitSehTryScopeEnd();
3265
3266 bool EmitLifetimeStart(llvm::Value *Addr);
3267 void EmitLifetimeEnd(llvm::Value *Addr);
3268
3269 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
3270 void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
3271
3272 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
3273 QualType DeleteTy, llvm::Value *NumElements = nullptr,
3274 CharUnits CookieSize = CharUnits());
3275
3276 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
3277 const CallExpr *TheCallExpr, bool IsDelete);
3278
3279 llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
3280 llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
3281 Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
3282
3283 /// Situations in which we might emit a check for the suitability of a
3284 /// pointer or glvalue. Needs to be kept in sync with ubsan_handlers.cpp in
3285 /// compiler-rt.
3286 enum TypeCheckKind {
3287 /// Checking the operand of a load. Must be suitably sized and aligned.
3288 TCK_Load,
3289 /// Checking the destination of a store. Must be suitably sized and aligned.
3290 TCK_Store,
3291 /// Checking the bound value in a reference binding. Must be suitably sized
3292 /// and aligned, but is not required to refer to an object (until the
3293 /// reference is used), per core issue 453.
3294 TCK_ReferenceBinding,
3295 /// Checking the object expression in a non-static data member access. Must
3296 /// be an object within its lifetime.
3297 TCK_MemberAccess,
3298 /// Checking the 'this' pointer for a call to a non-static member function.
3299 /// Must be an object within its lifetime.
3300 TCK_MemberCall,
3301 /// Checking the 'this' pointer for a constructor call.
3302 TCK_ConstructorCall,
3303 /// Checking the operand of a static_cast to a derived pointer type. Must be
3304 /// null or an object within its lifetime.
3305 TCK_DowncastPointer,
3306 /// Checking the operand of a static_cast to a derived reference type. Must
3307 /// be an object within its lifetime.
3308 TCK_DowncastReference,
3309 /// Checking the operand of a cast to a base object. Must be suitably sized
3310 /// and aligned.
3311 TCK_Upcast,
3312 /// Checking the operand of a cast to a virtual base object. Must be an
3313 /// object within its lifetime.
3314 TCK_UpcastToVirtualBase,
3315 /// Checking the value assigned to a _Nonnull pointer. Must not be null.
3316 TCK_NonnullAssign,
3317 /// Checking the operand of a dynamic_cast or a typeid expression. Must be
3318 /// null or an object within its lifetime.
3319 TCK_DynamicOperation
3320 };
3321
3322 /// Determine whether the pointer type check \p TCK permits null pointers.
3323 static bool isNullPointerAllowed(TypeCheckKind TCK);
3324
3325 /// Determine whether the pointer type check \p TCK requires a vptr check.
3326 static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty);
3327
3328 /// Whether any type-checking sanitizers are enabled. If \c false,
3329 /// calls to EmitTypeCheck can be skipped.
3330 bool sanitizePerformTypeCheck() const;
3331
3332 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, LValue LV,
3333 QualType Type, SanitizerSet SkippedChecks = SanitizerSet(),
3334 llvm::Value *ArraySize = nullptr) {
3335 if (!sanitizePerformTypeCheck())
3336 return;
3337 EmitTypeCheck(TCK, Loc, V: LV.emitRawPointer(CGF&: *this), Type, Alignment: LV.getAlignment(),
3338 SkippedChecks, ArraySize);
3339 }
3340
3341 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, Address Addr,
3342 QualType Type, CharUnits Alignment = CharUnits::Zero(),
3343 SanitizerSet SkippedChecks = SanitizerSet(),
3344 llvm::Value *ArraySize = nullptr) {
3345 if (!sanitizePerformTypeCheck())
3346 return;
3347 EmitTypeCheck(TCK, Loc, V: Addr.emitRawPointer(CGF&: *this), Type, Alignment,
3348 SkippedChecks, ArraySize);
3349 }
3350
3351 /// Emit a check that \p V is the address of storage of the
3352 /// appropriate size and alignment for an object of type \p Type
3353 /// (or if ArraySize is provided, for an array of that bound).
3354 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
3355 QualType Type, CharUnits Alignment = CharUnits::Zero(),
3356 SanitizerSet SkippedChecks = SanitizerSet(),
3357 llvm::Value *ArraySize = nullptr);
3358
3359 /// Emit a check that \p Base points into an array object, which
3360 /// we can access at index \p Index. \p Accessed should be \c false if we
3361 /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
3362 void EmitBoundsCheck(const Expr *ArrayExpr, const Expr *ArrayExprBase,
3363 llvm::Value *Index, QualType IndexType, bool Accessed);
3364 void EmitBoundsCheckImpl(const Expr *ArrayExpr, QualType ArrayBaseType,
3365 llvm::Value *IndexVal, QualType IndexType,
3366 llvm::Value *BoundsVal, QualType BoundsType,
3367 bool Accessed);
3368
3369 /// Returns debug info, with additional annotation if
3370 /// CGM.getCodeGenOpts().SanitizeAnnotateDebugInfo[Ordinal] is enabled for
3371 /// any of the ordinals.
3372 llvm::DILocation *
3373 SanitizerAnnotateDebugInfo(ArrayRef<SanitizerKind::SanitizerOrdinal> Ordinals,
3374 SanitizerHandler Handler);
3375
3376 /// Build metadata used by the AllocToken instrumentation.
3377 llvm::MDNode *buildAllocToken(QualType AllocType);
3378 /// Emit and set additional metadata used by the AllocToken instrumentation.
3379 void EmitAllocToken(llvm::CallBase *CB, QualType AllocType);
3380 /// Build additional metadata used by the AllocToken instrumentation,
3381 /// inferring the type from an allocation call expression.
3382 llvm::MDNode *buildAllocToken(const CallExpr *E);
3383 /// Emit and set additional metadata used by the AllocToken instrumentation,
3384 /// inferring the type from an allocation call expression.
3385 void EmitAllocToken(llvm::CallBase *CB, const CallExpr *E);
3386
3387 llvm::Value *GetCountedByFieldExprGEP(const Expr *Base, const FieldDecl *FD,
3388 const FieldDecl *CountDecl);
3389
3390 /// Build an expression accessing the "counted_by" field.
3391 llvm::Value *EmitLoadOfCountedByField(const Expr *Base, const FieldDecl *FD,
3392 const FieldDecl *CountDecl);
3393
3394 // Emit bounds checking for flexible array and pointer members with the
3395 // counted_by attribute.
3396 void EmitCountedByBoundsChecking(const Expr *ArrayExpr, QualType ArrayType,
3397 Address ArrayInst, QualType IndexType,
3398 llvm::Value *IndexVal, bool Accessed,
3399 bool FlexibleArray);
3400
3401 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3402 bool isInc, bool isPre);
3403 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
3404 bool isInc, bool isPre);
3405
3406 /// Converts Location to a DebugLoc, if debug information is enabled.
3407 llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
3408
3409 /// Get the record field index as represented in debug info.
3410 unsigned getDebugInfoFIndex(const RecordDecl *Rec, unsigned FieldIndex);
3411
3412 //===--------------------------------------------------------------------===//
3413 // Declaration Emission
3414 //===--------------------------------------------------------------------===//
3415
3416 /// EmitDecl - Emit a declaration.
3417 ///
3418 /// This function can be called with a null (unreachable) insert point.
3419 void EmitDecl(const Decl &D, bool EvaluateConditionDecl = false);
3420
3421 /// EmitVarDecl - Emit a local variable declaration.
3422 ///
3423 /// This function can be called with a null (unreachable) insert point.
3424 void EmitVarDecl(const VarDecl &D);
3425
3426 void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
3427 bool capturedByInit);
3428
3429 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
3430 llvm::Value *Address);
3431
3432 /// Determine whether the given initializer is trivial in the sense
3433 /// that it requires no code to be generated.
3434 bool isTrivialInitializer(const Expr *Init);
3435
3436 /// EmitAutoVarDecl - Emit an auto variable declaration.
3437 ///
3438 /// This function can be called with a null (unreachable) insert point.
3439 void EmitAutoVarDecl(const VarDecl &D);
3440
3441 class AutoVarEmission {
3442 friend class CodeGenFunction;
3443
3444 const VarDecl *Variable;
3445
3446 /// The address of the alloca for languages with explicit address space
3447 /// (e.g. OpenCL) or alloca casted to generic pointer for address space
3448 /// agnostic languages (e.g. C++). Invalid if the variable was emitted
3449 /// as a global constant.
3450 Address Addr;
3451
3452 llvm::Value *NRVOFlag;
3453
3454 /// True if the variable is a __block variable that is captured by an
3455 /// escaping block.
3456 bool IsEscapingByRef;
3457
3458 /// True if the variable is of aggregate type and has a constant
3459 /// initializer.
3460 bool IsConstantAggregate;
3461
3462 /// True if lifetime markers should be used.
3463 bool UseLifetimeMarkers;
3464
3465 /// Address with original alloca instruction. Invalid if the variable was
3466 /// emitted as a global constant.
3467 RawAddress AllocaAddr;
3468
3469 struct Invalid {};
3470 AutoVarEmission(Invalid)
3471 : Variable(nullptr), Addr(Address::invalid()),
3472 AllocaAddr(RawAddress::invalid()) {}
3473
3474 AutoVarEmission(const VarDecl &variable)
3475 : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
3476 IsEscapingByRef(false), IsConstantAggregate(false),
3477 UseLifetimeMarkers(false), AllocaAddr(RawAddress::invalid()) {}
3478
3479 bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
3480
3481 public:
3482 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
3483
3484 bool useLifetimeMarkers() const { return UseLifetimeMarkers; }
3485
3486 /// Returns the raw, allocated address, which is not necessarily
3487 /// the address of the object itself. It is casted to default
3488 /// address space for address space agnostic languages.
3489 Address getAllocatedAddress() const { return Addr; }
3490
3491 /// Returns the address for the original alloca instruction.
3492 RawAddress getOriginalAllocatedAddress() const { return AllocaAddr; }
3493
3494 /// Returns the address of the object within this declaration.
3495 /// Note that this does not chase the forwarding pointer for
3496 /// __block decls.
3497 Address getObjectAddress(CodeGenFunction &CGF) const {
3498 if (!IsEscapingByRef)
3499 return Addr;
3500
3501 return CGF.emitBlockByrefAddress(baseAddr: Addr, V: Variable, /*forward*/ followForward: false);
3502 }
3503 };
3504 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
3505 void EmitAutoVarInit(const AutoVarEmission &emission);
3506 void EmitAutoVarCleanups(const AutoVarEmission &emission);
3507 void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
3508 QualType::DestructionKind dtorKind);
3509
3510 void MaybeEmitDeferredVarDeclInit(const VarDecl *var);
3511
3512 /// Emits the alloca and debug information for the size expressions for each
3513 /// dimension of an array. It registers the association of its (1-dimensional)
3514 /// QualTypes and size expression's debug node, so that CGDebugInfo can
3515 /// reference this node when creating the DISubrange object to describe the
3516 /// array types.
3517 void EmitAndRegisterVariableArrayDimensions(CGDebugInfo *DI, const VarDecl &D,
3518 bool EmitDebugInfo);
3519
3520 void EmitStaticVarDecl(const VarDecl &D,
3521 llvm::GlobalValue::LinkageTypes Linkage);
3522
3523 class ParamValue {
3524 union {
3525 Address Addr;
3526 llvm::Value *Value;
3527 };
3528
3529 bool IsIndirect;
3530
3531 ParamValue(llvm::Value *V) : Value(V), IsIndirect(false) {}
3532 ParamValue(Address A) : Addr(A), IsIndirect(true) {}
3533
3534 public:
3535 static ParamValue forDirect(llvm::Value *value) {
3536 return ParamValue(value);
3537 }
3538 static ParamValue forIndirect(Address addr) {
3539 assert(!addr.getAlignment().isZero());
3540 return ParamValue(addr);
3541 }
3542
3543 bool isIndirect() const { return IsIndirect; }
3544 llvm::Value *getAnyValue() const {
3545 if (!isIndirect())
3546 return Value;
3547 assert(!Addr.hasOffset() && "unexpected offset");
3548 return Addr.getBasePointer();
3549 }
3550
3551 llvm::Value *getDirectValue() const {
3552 assert(!isIndirect());
3553 return Value;
3554 }
3555
3556 Address getIndirectAddress() const {
3557 assert(isIndirect());
3558 return Addr;
3559 }
3560 };
3561
3562 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
3563 void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
3564
3565 /// protectFromPeepholes - Protect a value that we're intending to
3566 /// store to the side, but which will probably be used later, from
3567 /// aggressive peepholing optimizations that might delete it.
3568 ///
3569 /// Pass the result to unprotectFromPeepholes to declare that
3570 /// protection is no longer required.
3571 ///
3572 /// There's no particular reason why this shouldn't apply to
3573 /// l-values, it's just that no existing peepholes work on pointers.
3574 PeepholeProtection protectFromPeepholes(RValue rvalue);
3575 void unprotectFromPeepholes(PeepholeProtection protection);
3576
3577 void emitAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty,
3578 SourceLocation Loc,
3579 SourceLocation AssumptionLoc,
3580 llvm::Value *Alignment,
3581 llvm::Value *OffsetValue,
3582 llvm::Value *TheCheck,
3583 llvm::Instruction *Assumption);
3584
3585 void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty,
3586 SourceLocation Loc, SourceLocation AssumptionLoc,
3587 llvm::Value *Alignment,
3588 llvm::Value *OffsetValue = nullptr);
3589
3590 void emitAlignmentAssumption(llvm::Value *PtrValue, const Expr *E,
3591 SourceLocation AssumptionLoc,
3592 llvm::Value *Alignment,
3593 llvm::Value *OffsetValue = nullptr);
3594
3595 //===--------------------------------------------------------------------===//
3596 // Statement Emission
3597 //===--------------------------------------------------------------------===//
3598
3599 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
3600 void EmitStopPoint(const Stmt *S);
3601
3602 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
3603 /// this function even if there is no current insertion point.
3604 ///
3605 /// This function may clear the current insertion point; callers should use
3606 /// EnsureInsertPoint if they wish to subsequently generate code without first
3607 /// calling EmitBlock, EmitBranch, or EmitStmt.
3608 void EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs = {});
3609
3610 /// EmitSimpleStmt - Try to emit a "simple" statement which does not
3611 /// necessarily require an insertion point or debug information; typically
3612 /// because the statement amounts to a jump or a container of other
3613 /// statements.
3614 ///
3615 /// \return True if the statement was handled.
3616 bool EmitSimpleStmt(const Stmt *S, ArrayRef<const Attr *> Attrs);
3617
3618 Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
3619 AggValueSlot AVS = AggValueSlot::ignored());
3620 Address
3621 EmitCompoundStmtWithoutScope(const CompoundStmt &S, bool GetLast = false,
3622 AggValueSlot AVS = AggValueSlot::ignored());
3623
3624 /// EmitLabel - Emit the block for the given label. It is legal to call this
3625 /// function even if there is no current insertion point.
3626 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
3627
3628 void EmitLabelStmt(const LabelStmt &S);
3629 void EmitAttributedStmt(const AttributedStmt &S);
3630 void EmitGotoStmt(const GotoStmt &S);
3631 void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
3632 void EmitIfStmt(const IfStmt &S);
3633
3634 void EmitWhileStmt(const WhileStmt &S, ArrayRef<const Attr *> Attrs = {});
3635 void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = {});
3636 void EmitForStmt(const ForStmt &S, ArrayRef<const Attr *> Attrs = {});
3637 void EmitReturnStmt(const ReturnStmt &S);
3638 void EmitDeclStmt(const DeclStmt &S);
3639 void EmitBreakStmt(const BreakStmt &S);
3640 void EmitContinueStmt(const ContinueStmt &S);
3641 void EmitSwitchStmt(const SwitchStmt &S);
3642 void EmitDefaultStmt(const DefaultStmt &S, ArrayRef<const Attr *> Attrs);
3643 void EmitCaseStmt(const CaseStmt &S, ArrayRef<const Attr *> Attrs);
3644 void EmitCaseStmtRange(const CaseStmt &S, ArrayRef<const Attr *> Attrs);
3645 void EmitDeferStmt(const DeferStmt &S);
3646 void EmitAsmStmt(const AsmStmt &S);
3647
3648 const BreakContinue *GetDestForLoopControlStmt(const LoopControlStmt &S);
3649
3650 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
3651 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
3652 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
3653 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
3654 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
3655
3656 void EmitCoroutineBody(const CoroutineBodyStmt &S);
3657 void EmitCoreturnStmt(const CoreturnStmt &S);
3658 RValue EmitCoawaitExpr(const CoawaitExpr &E,
3659 AggValueSlot aggSlot = AggValueSlot::ignored(),
3660 bool ignoreResult = false);
3661 LValue EmitCoawaitLValue(const CoawaitExpr *E);
3662 RValue EmitCoyieldExpr(const CoyieldExpr &E,
3663 AggValueSlot aggSlot = AggValueSlot::ignored(),
3664 bool ignoreResult = false);
3665 LValue EmitCoyieldLValue(const CoyieldExpr *E);
3666 RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
3667
3668 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
3669 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
3670
3671 void EmitCXXTryStmt(const CXXTryStmt &S);
3672 void EmitSEHTryStmt(const SEHTryStmt &S);
3673 void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
3674 void EnterSEHTryStmt(const SEHTryStmt &S);
3675 void ExitSEHTryStmt(const SEHTryStmt &S);
3676 void VolatilizeTryBlocks(llvm::BasicBlock *BB,
3677 llvm::SmallPtrSet<llvm::BasicBlock *, 10> &V);
3678
3679 void pushSEHCleanup(CleanupKind kind, llvm::Function *FinallyFunc);
3680 void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
3681 const Stmt *OutlinedStmt);
3682
3683 llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
3684 const SEHExceptStmt &Except);
3685
3686 llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
3687 const SEHFinallyStmt &Finally);
3688
3689 void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
3690 llvm::Value *ParentFP, llvm::Value *EntryEBP);
3691 llvm::Value *EmitSEHExceptionCode();
3692 llvm::Value *EmitSEHExceptionInfo();
3693 llvm::Value *EmitSEHAbnormalTermination();
3694
3695 /// Emit simple code for OpenMP directives in Simd-only mode.
3696 void EmitSimpleOMPExecutableDirective(const OMPExecutableDirective &D);
3697
3698 /// Scan the outlined statement for captures from the parent function. For
3699 /// each capture, mark the capture as escaped and emit a call to
3700 /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
3701 void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
3702 bool IsFilter);
3703
3704 /// Recovers the address of a local in a parent function. ParentVar is the
3705 /// address of the variable used in the immediate parent function. It can
3706 /// either be an alloca or a call to llvm.localrecover if there are nested
3707 /// outlined functions. ParentFP is the frame pointer of the outermost parent
3708 /// frame.
3709 Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
3710 Address ParentVar, llvm::Value *ParentFP);
3711
3712 void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
3713 ArrayRef<const Attr *> Attrs = {});
3714
3715 /// Controls insertion of cancellation exit blocks in worksharing constructs.
3716 class OMPCancelStackRAII {
3717 CodeGenFunction &CGF;
3718
3719 public:
3720 OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
3721 bool HasCancel)
3722 : CGF(CGF) {
3723 CGF.OMPCancelStack.enter(CGF, Kind, HasCancel);
3724 }
3725 ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); }
3726 };
3727
3728 /// Returns calculated size of the specified type.
3729 llvm::Value *getTypeSize(QualType Ty);
3730 LValue InitCapturedStruct(const CapturedStmt &S);
3731 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
3732 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
3733 Address GenerateCapturedStmtArgument(const CapturedStmt &S);
3734 llvm::Function *
3735 GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S,
3736 const OMPExecutableDirective &D);
3737 void GenerateOpenMPCapturedVars(const CapturedStmt &S,
3738 SmallVectorImpl<llvm::Value *> &CapturedVars);
3739 void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
3740 SourceLocation Loc);
3741 /// Perform element by element copying of arrays with type \a
3742 /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
3743 /// generated by \a CopyGen.
3744 ///
3745 /// \param DestAddr Address of the destination array.
3746 /// \param SrcAddr Address of the source array.
3747 /// \param OriginalType Type of destination and source arrays.
3748 /// \param CopyGen Copying procedure that copies value of single array element
3749 /// to another single array element.
3750 void EmitOMPAggregateAssign(
3751 Address DestAddr, Address SrcAddr, QualType OriginalType,
3752 const llvm::function_ref<void(Address, Address)> CopyGen);
3753 /// Emit proper copying of data from one variable to another.
3754 ///
3755 /// \param OriginalType Original type of the copied variables.
3756 /// \param DestAddr Destination address.
3757 /// \param SrcAddr Source address.
3758 /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
3759 /// type of the base array element).
3760 /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
3761 /// the base array element).
3762 /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
3763 /// DestVD.
3764 void EmitOMPCopy(QualType OriginalType, Address DestAddr, Address SrcAddr,
3765 const VarDecl *DestVD, const VarDecl *SrcVD,
3766 const Expr *Copy);
3767 /// Emit atomic update code for constructs: \a X = \a X \a BO \a E or
3768 /// \a X = \a E \a BO \a E.
3769 ///
3770 /// \param X Value to be updated.
3771 /// \param E Update value.
3772 /// \param BO Binary operation for update operation.
3773 /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
3774 /// expression, false otherwise.
3775 /// \param AO Atomic ordering of the generated atomic instructions.
3776 /// \param CommonGen Code generator for complex expressions that cannot be
3777 /// expressed through atomicrmw instruction.
3778 /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
3779 /// generated, <false, RValue::get(nullptr)> otherwise.
3780 std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
3781 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3782 llvm::AtomicOrdering AO, SourceLocation Loc,
3783 const llvm::function_ref<RValue(RValue)> CommonGen);
3784 bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
3785 OMPPrivateScope &PrivateScope);
3786 void EmitOMPPrivateClause(const OMPExecutableDirective &D,
3787 OMPPrivateScope &PrivateScope);
3788 void EmitOMPUseDevicePtrClause(
3789 const OMPUseDevicePtrClause &C, OMPPrivateScope &PrivateScope,
3790 const llvm::DenseMap<const ValueDecl *, llvm::Value *>
3791 CaptureDeviceAddrMap);
3792 void EmitOMPUseDeviceAddrClause(
3793 const OMPUseDeviceAddrClause &C, OMPPrivateScope &PrivateScope,
3794 const llvm::DenseMap<const ValueDecl *, llvm::Value *>
3795 CaptureDeviceAddrMap);
3796 /// Emit code for copyin clause in \a D directive. The next code is
3797 /// generated at the start of outlined functions for directives:
3798 /// \code
3799 /// threadprivate_var1 = master_threadprivate_var1;
3800 /// operator=(threadprivate_var2, master_threadprivate_var2);
3801 /// ...
3802 /// __kmpc_barrier(&loc, global_tid);
3803 /// \endcode
3804 ///
3805 /// \param D OpenMP directive possibly with 'copyin' clause(s).
3806 /// \returns true if at least one copyin variable is found, false otherwise.
3807 bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
3808 /// Emit initial code for lastprivate variables. If some variable is
3809 /// not also firstprivate, then the default initialization is used. Otherwise
3810 /// initialization of this variable is performed by EmitOMPFirstprivateClause
3811 /// method.
3812 ///
3813 /// \param D Directive that may have 'lastprivate' directives.
3814 /// \param PrivateScope Private scope for capturing lastprivate variables for
3815 /// proper codegen in internal captured statement.
3816 ///
3817 /// \returns true if there is at least one lastprivate variable, false
3818 /// otherwise.
3819 bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
3820 OMPPrivateScope &PrivateScope);
3821 /// Emit final copying of lastprivate values to original variables at
3822 /// the end of the worksharing or simd directive.
3823 ///
3824 /// \param D Directive that has at least one 'lastprivate' directives.
3825 /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
3826 /// it is the last iteration of the loop code in associated directive, or to
3827 /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
3828 void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
3829 bool NoFinals,
3830 llvm::Value *IsLastIterCond = nullptr);
3831 /// Emit initial code for linear clauses.
3832 void EmitOMPLinearClause(const OMPLoopDirective &D,
3833 CodeGenFunction::OMPPrivateScope &PrivateScope);
3834 /// Emit final code for linear clauses.
3835 /// \param CondGen Optional conditional code for final part of codegen for
3836 /// linear clause.
3837 void EmitOMPLinearClauseFinal(
3838 const OMPLoopDirective &D,
3839 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen);
3840 /// Emit initial code for reduction variables. Creates reduction copies
3841 /// and initializes them with the values according to OpenMP standard.
3842 ///
3843 /// \param D Directive (possibly) with the 'reduction' clause.
3844 /// \param PrivateScope Private scope for capturing reduction variables for
3845 /// proper codegen in internal captured statement.
3846 ///
3847 void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
3848 OMPPrivateScope &PrivateScope,
3849 bool ForInscan = false);
3850 /// Emit final update of reduction values to original variables at
3851 /// the end of the directive.
3852 ///
3853 /// \param D Directive that has at least one 'reduction' directives.
3854 /// \param ReductionKind The kind of reduction to perform.
3855 void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D,
3856 const OpenMPDirectiveKind ReductionKind);
3857 /// Emit initial code for linear variables. Creates private copies
3858 /// and initializes them with the values according to OpenMP standard.
3859 ///
3860 /// \param D Directive (possibly) with the 'linear' clause.
3861 /// \return true if at least one linear variable is found that should be
3862 /// initialized with the value of the original variable, false otherwise.
3863 bool EmitOMPLinearClauseInit(const OMPLoopDirective &D);
3864
3865 typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
3866 llvm::Function * /*OutlinedFn*/,
3867 const OMPTaskDataTy & /*Data*/)>
3868 TaskGenTy;
3869 void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
3870 const OpenMPDirectiveKind CapturedRegion,
3871 const RegionCodeGenTy &BodyGen,
3872 const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
3873 struct OMPTargetDataInfo {
3874 Address BasePointersArray = Address::invalid();
3875 Address PointersArray = Address::invalid();
3876 Address SizesArray = Address::invalid();
3877 Address MappersArray = Address::invalid();
3878 unsigned NumberOfTargetItems = 0;
3879 explicit OMPTargetDataInfo() = default;
3880 OMPTargetDataInfo(Address BasePointersArray, Address PointersArray,
3881 Address SizesArray, Address MappersArray,
3882 unsigned NumberOfTargetItems)
3883 : BasePointersArray(BasePointersArray), PointersArray(PointersArray),
3884 SizesArray(SizesArray), MappersArray(MappersArray),
3885 NumberOfTargetItems(NumberOfTargetItems) {}
3886 };
3887 void EmitOMPTargetTaskBasedDirective(const OMPExecutableDirective &S,
3888 const RegionCodeGenTy &BodyGen,
3889 OMPTargetDataInfo &InputInfo);
3890 void processInReduction(const OMPExecutableDirective &S, OMPTaskDataTy &Data,
3891 CodeGenFunction &CGF, const CapturedStmt *CS,
3892 OMPPrivateScope &Scope);
3893 void EmitOMPMetaDirective(const OMPMetaDirective &S);
3894 void EmitOMPParallelDirective(const OMPParallelDirective &S);
3895 void EmitOMPSimdDirective(const OMPSimdDirective &S);
3896 void EmitOMPTileDirective(const OMPTileDirective &S);
3897 void EmitOMPStripeDirective(const OMPStripeDirective &S);
3898 void EmitOMPUnrollDirective(const OMPUnrollDirective &S);
3899 void EmitOMPReverseDirective(const OMPReverseDirective &S);
3900 void EmitOMPInterchangeDirective(const OMPInterchangeDirective &S);
3901 void EmitOMPFuseDirective(const OMPFuseDirective &S);
3902 void EmitOMPForDirective(const OMPForDirective &S);
3903 void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
3904 void EmitOMPScopeDirective(const OMPScopeDirective &S);
3905 void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
3906 void EmitOMPSectionDirective(const OMPSectionDirective &S);
3907 void EmitOMPSingleDirective(const OMPSingleDirective &S);
3908 void EmitOMPMasterDirective(const OMPMasterDirective &S);
3909 void EmitOMPMaskedDirective(const OMPMaskedDirective &S);
3910 void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
3911 void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
3912 void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
3913 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
3914 void EmitOMPParallelMasterDirective(const OMPParallelMasterDirective &S);
3915 void EmitOMPTaskDirective(const OMPTaskDirective &S);
3916 void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
3917 void EmitOMPErrorDirective(const OMPErrorDirective &S);
3918 void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
3919 void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
3920 void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
3921 void EmitOMPFlushDirective(const OMPFlushDirective &S);
3922 void EmitOMPDepobjDirective(const OMPDepobjDirective &S);
3923 void EmitOMPScanDirective(const OMPScanDirective &S);
3924 void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
3925 void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
3926 void EmitOMPTargetDirective(const OMPTargetDirective &S);
3927 void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
3928 void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S);
3929 void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S);
3930 void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S);
3931 void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S);
3932 void
3933 EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S);
3934 void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
3935 void
3936 EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
3937 void EmitOMPCancelDirective(const OMPCancelDirective &S);
3938 void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S);
3939 void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S);
3940 void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S);
3941 void EmitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective &S);
3942 void EmitOMPMaskedTaskLoopDirective(const OMPMaskedTaskLoopDirective &S);
3943 void
3944 EmitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective &S);
3945 void
3946 EmitOMPMaskedTaskLoopSimdDirective(const OMPMaskedTaskLoopSimdDirective &S);
3947 void EmitOMPParallelMasterTaskLoopDirective(
3948 const OMPParallelMasterTaskLoopDirective &S);
3949 void EmitOMPParallelMaskedTaskLoopDirective(
3950 const OMPParallelMaskedTaskLoopDirective &S);
3951 void EmitOMPParallelMasterTaskLoopSimdDirective(
3952 const OMPParallelMasterTaskLoopSimdDirective &S);
3953 void EmitOMPParallelMaskedTaskLoopSimdDirective(
3954 const OMPParallelMaskedTaskLoopSimdDirective &S);
3955 void EmitOMPDistributeDirective(const OMPDistributeDirective &S);
3956 void EmitOMPDistributeParallelForDirective(
3957 const OMPDistributeParallelForDirective &S);
3958 void EmitOMPDistributeParallelForSimdDirective(
3959 const OMPDistributeParallelForSimdDirective &S);
3960 void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
3961 void EmitOMPTargetParallelForSimdDirective(
3962 const OMPTargetParallelForSimdDirective &S);
3963 void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S);
3964 void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S);
3965 void
3966 EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S);
3967 void EmitOMPTeamsDistributeParallelForSimdDirective(
3968 const OMPTeamsDistributeParallelForSimdDirective &S);
3969 void EmitOMPTeamsDistributeParallelForDirective(
3970 const OMPTeamsDistributeParallelForDirective &S);
3971 void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S);
3972 void EmitOMPTargetTeamsDistributeDirective(
3973 const OMPTargetTeamsDistributeDirective &S);
3974 void EmitOMPTargetTeamsDistributeParallelForDirective(
3975 const OMPTargetTeamsDistributeParallelForDirective &S);
3976 void EmitOMPTargetTeamsDistributeParallelForSimdDirective(
3977 const OMPTargetTeamsDistributeParallelForSimdDirective &S);
3978 void EmitOMPTargetTeamsDistributeSimdDirective(
3979 const OMPTargetTeamsDistributeSimdDirective &S);
3980 void EmitOMPGenericLoopDirective(const OMPGenericLoopDirective &S);
3981 void EmitOMPParallelGenericLoopDirective(const OMPLoopDirective &S);
3982 void EmitOMPTargetParallelGenericLoopDirective(
3983 const OMPTargetParallelGenericLoopDirective &S);
3984 void EmitOMPTargetTeamsGenericLoopDirective(
3985 const OMPTargetTeamsGenericLoopDirective &S);
3986 void EmitOMPTeamsGenericLoopDirective(const OMPTeamsGenericLoopDirective &S);
3987 void EmitOMPInteropDirective(const OMPInteropDirective &S);
3988 void EmitOMPParallelMaskedDirective(const OMPParallelMaskedDirective &S);
3989 void EmitOMPAssumeDirective(const OMPAssumeDirective &S);
3990
3991 /// Emit device code for the target directive.
3992 static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3993 StringRef ParentName,
3994 const OMPTargetDirective &S);
3995 static void
3996 EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
3997 const OMPTargetParallelDirective &S);
3998 /// Emit device code for the target parallel for directive.
3999 static void EmitOMPTargetParallelForDeviceFunction(
4000 CodeGenModule &CGM, StringRef ParentName,
4001 const OMPTargetParallelForDirective &S);
4002 /// Emit device code for the target parallel for simd directive.
4003 static void EmitOMPTargetParallelForSimdDeviceFunction(
4004 CodeGenModule &CGM, StringRef ParentName,
4005 const OMPTargetParallelForSimdDirective &S);
4006 /// Emit device code for the target teams directive.
4007 static void
4008 EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
4009 const OMPTargetTeamsDirective &S);
4010 /// Emit device code for the target teams distribute directive.
4011 static void EmitOMPTargetTeamsDistributeDeviceFunction(
4012 CodeGenModule &CGM, StringRef ParentName,
4013 const OMPTargetTeamsDistributeDirective &S);
4014 /// Emit device code for the target teams distribute simd directive.
4015 static void EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4016 CodeGenModule &CGM, StringRef ParentName,
4017 const OMPTargetTeamsDistributeSimdDirective &S);
4018 /// Emit device code for the target simd directive.
4019 static void EmitOMPTargetSimdDeviceFunction(CodeGenModule &CGM,
4020 StringRef ParentName,
4021 const OMPTargetSimdDirective &S);
4022 /// Emit device code for the target teams distribute parallel for simd
4023 /// directive.
4024 static void EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
4025 CodeGenModule &CGM, StringRef ParentName,
4026 const OMPTargetTeamsDistributeParallelForSimdDirective &S);
4027
4028 /// Emit device code for the target teams loop directive.
4029 static void EmitOMPTargetTeamsGenericLoopDeviceFunction(
4030 CodeGenModule &CGM, StringRef ParentName,
4031 const OMPTargetTeamsGenericLoopDirective &S);
4032
4033 /// Emit device code for the target parallel loop directive.
4034 static void EmitOMPTargetParallelGenericLoopDeviceFunction(
4035 CodeGenModule &CGM, StringRef ParentName,
4036 const OMPTargetParallelGenericLoopDirective &S);
4037
4038 static void EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
4039 CodeGenModule &CGM, StringRef ParentName,
4040 const OMPTargetTeamsDistributeParallelForDirective &S);
4041
4042 /// Emit the Stmt \p S and return its topmost canonical loop, if any.
4043 /// TODO: The \p Depth paramter is not yet implemented and must be 1. In the
4044 /// future it is meant to be the number of loops expected in the loop nests
4045 /// (usually specified by the "collapse" clause) that are collapsed to a
4046 /// single loop by this function.
4047 llvm::CanonicalLoopInfo *EmitOMPCollapsedCanonicalLoopNest(const Stmt *S,
4048 int Depth);
4049
4050 /// Emit an OMPCanonicalLoop using the OpenMPIRBuilder.
4051 void EmitOMPCanonicalLoop(const OMPCanonicalLoop *S);
4052
4053 /// Emit inner loop of the worksharing/simd construct.
4054 ///
4055 /// \param S Directive, for which the inner loop must be emitted.
4056 /// \param RequiresCleanup true, if directive has some associated private
4057 /// variables.
4058 /// \param LoopCond Bollean condition for loop continuation.
4059 /// \param IncExpr Increment expression for loop control variable.
4060 /// \param BodyGen Generator for the inner body of the inner loop.
4061 /// \param PostIncGen Genrator for post-increment code (required for ordered
4062 /// loop directvies).
4063 void EmitOMPInnerLoop(
4064 const OMPExecutableDirective &S, bool RequiresCleanup,
4065 const Expr *LoopCond, const Expr *IncExpr,
4066 const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
4067 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen);
4068
4069 JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
4070 /// Emit initial code for loop counters of loop-based directives.
4071 void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S,
4072 OMPPrivateScope &LoopScope);
4073
4074 /// Helper for the OpenMP loop directives.
4075 void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
4076
4077 /// Emit code for the worksharing loop-based directive.
4078 /// \return true, if this construct has any lastprivate clause, false -
4079 /// otherwise.
4080 bool EmitOMPWorksharingLoop(const OMPLoopDirective &S, Expr *EUB,
4081 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
4082 const CodeGenDispatchBoundsTy &CGDispatchBounds);
4083
4084 /// Emit code for the distribute loop-based directive.
4085 void EmitOMPDistributeLoop(const OMPLoopDirective &S,
4086 const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr);
4087
4088 /// Helpers for the OpenMP loop directives.
4089 void EmitOMPSimdInit(const OMPLoopDirective &D);
4090 void EmitOMPSimdFinal(
4091 const OMPLoopDirective &D,
4092 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen);
4093
4094 /// Emits the lvalue for the expression with possibly captured variable.
4095 LValue EmitOMPSharedLValue(const Expr *E);
4096
4097private:
4098 /// Helpers for blocks.
4099 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
4100
4101 /// struct with the values to be passed to the OpenMP loop-related functions
4102 struct OMPLoopArguments {
4103 /// loop lower bound
4104 Address LB = Address::invalid();
4105 /// loop upper bound
4106 Address UB = Address::invalid();
4107 /// loop stride
4108 Address ST = Address::invalid();
4109 /// isLastIteration argument for runtime functions
4110 Address IL = Address::invalid();
4111 /// Chunk value generated by sema
4112 llvm::Value *Chunk = nullptr;
4113 /// EnsureUpperBound
4114 Expr *EUB = nullptr;
4115 /// IncrementExpression
4116 Expr *IncExpr = nullptr;
4117 /// Loop initialization
4118 Expr *Init = nullptr;
4119 /// Loop exit condition
4120 Expr *Cond = nullptr;
4121 /// Update of LB after a whole chunk has been executed
4122 Expr *NextLB = nullptr;
4123 /// Update of UB after a whole chunk has been executed
4124 Expr *NextUB = nullptr;
4125 /// Distinguish between the for distribute and sections
4126 OpenMPDirectiveKind DKind = llvm::omp::OMPD_unknown;
4127 OMPLoopArguments() = default;
4128 OMPLoopArguments(Address LB, Address UB, Address ST, Address IL,
4129 llvm::Value *Chunk = nullptr, Expr *EUB = nullptr,
4130 Expr *IncExpr = nullptr, Expr *Init = nullptr,
4131 Expr *Cond = nullptr, Expr *NextLB = nullptr,
4132 Expr *NextUB = nullptr)
4133 : LB(LB), UB(UB), ST(ST), IL(IL), Chunk(Chunk), EUB(EUB),
4134 IncExpr(IncExpr), Init(Init), Cond(Cond), NextLB(NextLB),
4135 NextUB(NextUB) {}
4136 };
4137 void EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
4138 const OMPLoopDirective &S, OMPPrivateScope &LoopScope,
4139 const OMPLoopArguments &LoopArgs,
4140 const CodeGenLoopTy &CodeGenLoop,
4141 const CodeGenOrderedTy &CodeGenOrdered);
4142 void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
4143 bool IsMonotonic, const OMPLoopDirective &S,
4144 OMPPrivateScope &LoopScope, bool Ordered,
4145 const OMPLoopArguments &LoopArgs,
4146 const CodeGenDispatchBoundsTy &CGDispatchBounds);
4147 void EmitOMPDistributeOuterLoop(OpenMPDistScheduleClauseKind ScheduleKind,
4148 const OMPLoopDirective &S,
4149 OMPPrivateScope &LoopScope,
4150 const OMPLoopArguments &LoopArgs,
4151 const CodeGenLoopTy &CodeGenLoopContent);
4152 /// Emit code for sections directive.
4153 void EmitSections(const OMPExecutableDirective &S);
4154
4155public:
4156 //===--------------------------------------------------------------------===//
4157 // OpenACC Emission
4158 //===--------------------------------------------------------------------===//
4159 void EmitOpenACCComputeConstruct(const OpenACCComputeConstruct &S) {
4160 // TODO OpenACC: Implement this. It is currently implemented as a 'no-op',
4161 // simply emitting its structured block, but in the future we will implement
4162 // some sort of IR.
4163 EmitStmt(S: S.getStructuredBlock());
4164 }
4165
4166 void EmitOpenACCLoopConstruct(const OpenACCLoopConstruct &S) {
4167 // TODO OpenACC: Implement this. It is currently implemented as a 'no-op',
4168 // simply emitting its loop, but in the future we will implement
4169 // some sort of IR.
4170 EmitStmt(S: S.getLoop());
4171 }
4172
4173 void EmitOpenACCCombinedConstruct(const OpenACCCombinedConstruct &S) {
4174 // TODO OpenACC: Implement this. It is currently implemented as a 'no-op',
4175 // simply emitting its loop, but in the future we will implement
4176 // some sort of IR.
4177 EmitStmt(S: S.getLoop());
4178 }
4179
4180 void EmitOpenACCDataConstruct(const OpenACCDataConstruct &S) {
4181 // TODO OpenACC: Implement this. It is currently implemented as a 'no-op',
4182 // simply emitting its structured block, but in the future we will implement
4183 // some sort of IR.
4184 EmitStmt(S: S.getStructuredBlock());
4185 }
4186
4187 void EmitOpenACCEnterDataConstruct(const OpenACCEnterDataConstruct &S) {
4188 // TODO OpenACC: Implement this. It is currently implemented as a 'no-op',
4189 // but in the future we will implement some sort of IR.
4190 }
4191
4192 void EmitOpenACCExitDataConstruct(const OpenACCExitDataConstruct &S) {
4193 // TODO OpenACC: Implement this. It is currently implemented as a 'no-op',
4194 // but in the future we will implement some sort of IR.
4195 }
4196
4197 void EmitOpenACCHostDataConstruct(const OpenACCHostDataConstruct &S) {
4198 // TODO OpenACC: Implement this. It is currently implemented as a 'no-op',
4199 // simply emitting its structured block, but in the future we will implement
4200 // some sort of IR.
4201 EmitStmt(S: S.getStructuredBlock());
4202 }
4203
4204 void EmitOpenACCWaitConstruct(const OpenACCWaitConstruct &S) {
4205 // TODO OpenACC: Implement this. It is currently implemented as a 'no-op',
4206 // but in the future we will implement some sort of IR.
4207 }
4208
4209 void EmitOpenACCInitConstruct(const OpenACCInitConstruct &S) {
4210 // TODO OpenACC: Implement this. It is currently implemented as a 'no-op',
4211 // but in the future we will implement some sort of IR.
4212 }
4213
4214 void EmitOpenACCShutdownConstruct(const OpenACCShutdownConstruct &S) {
4215 // TODO OpenACC: Implement this. It is currently implemented as a 'no-op',
4216 // but in the future we will implement some sort of IR.
4217 }
4218
4219 void EmitOpenACCSetConstruct(const OpenACCSetConstruct &S) {
4220 // TODO OpenACC: Implement this. It is currently implemented as a 'no-op',
4221 // but in the future we will implement some sort of IR.
4222 }
4223
4224 void EmitOpenACCUpdateConstruct(const OpenACCUpdateConstruct &S) {
4225 // TODO OpenACC: Implement this. It is currently implemented as a 'no-op',
4226 // but in the future we will implement some sort of IR.
4227 }
4228
4229 void EmitOpenACCAtomicConstruct(const OpenACCAtomicConstruct &S) {
4230 // TODO OpenACC: Implement this. It is currently implemented as a 'no-op',
4231 // simply emitting its associated stmt, but in the future we will implement
4232 // some sort of IR.
4233 EmitStmt(S: S.getAssociatedStmt());
4234 }
4235 void EmitOpenACCCacheConstruct(const OpenACCCacheConstruct &S) {
4236 // TODO OpenACC: Implement this. It is currently implemented as a 'no-op',
4237 // but in the future we will implement some sort of IR.
4238 }
4239
4240 //===--------------------------------------------------------------------===//
4241 // LValue Expression Emission
4242 //===--------------------------------------------------------------------===//
4243
4244 /// Create a check that a scalar RValue is non-null.
4245 llvm::Value *EmitNonNullRValueCheck(RValue RV, QualType T);
4246
4247 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
4248 RValue GetUndefRValue(QualType Ty);
4249
4250 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
4251 /// and issue an ErrorUnsupported style diagnostic (using the
4252 /// provided Name).
4253 RValue EmitUnsupportedRValue(const Expr *E, const char *Name);
4254
4255 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
4256 /// an ErrorUnsupported style diagnostic (using the provided Name).
4257 LValue EmitUnsupportedLValue(const Expr *E, const char *Name);
4258
4259 /// EmitLValue - Emit code to compute a designator that specifies the location
4260 /// of the expression.
4261 ///
4262 /// This can return one of two things: a simple address or a bitfield
4263 /// reference. In either case, the LLVM Value* in the LValue structure is
4264 /// guaranteed to be an LLVM pointer type.
4265 ///
4266 /// If this returns a bitfield reference, nothing about the pointee type of
4267 /// the LLVM value is known: For example, it may not be a pointer to an
4268 /// integer.
4269 ///
4270 /// If this returns a normal address, and if the lvalue's C type is fixed
4271 /// size, this method guarantees that the returned pointer type will point to
4272 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
4273 /// variable length type, this is not possible.
4274 ///
4275 LValue EmitLValue(const Expr *E,
4276 KnownNonNull_t IsKnownNonNull = NotKnownNonNull);
4277
4278private:
4279 LValue EmitLValueHelper(const Expr *E, KnownNonNull_t IsKnownNonNull);
4280
4281public:
4282 /// Same as EmitLValue but additionally we generate checking code to
4283 /// guard against undefined behavior. This is only suitable when we know
4284 /// that the address will be used to access the object.
4285 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
4286
4287 RValue convertTempToRValue(Address addr, QualType type, SourceLocation Loc);
4288
4289 void EmitAtomicInit(Expr *E, LValue lvalue);
4290
4291 bool LValueIsSuitableForInlineAtomic(LValue Src);
4292
4293 RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
4294 AggValueSlot Slot = AggValueSlot::ignored());
4295
4296 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
4297 llvm::AtomicOrdering AO, bool IsVolatile = false,
4298 AggValueSlot slot = AggValueSlot::ignored());
4299
4300 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
4301
4302 void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
4303 bool IsVolatile, bool isInit);
4304
4305 std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
4306 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
4307 llvm::AtomicOrdering Success =
4308 llvm::AtomicOrdering::SequentiallyConsistent,
4309 llvm::AtomicOrdering Failure =
4310 llvm::AtomicOrdering::SequentiallyConsistent,
4311 bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
4312
4313 /// Emit an atomicrmw instruction, and applying relevant metadata when
4314 /// applicable.
4315 llvm::AtomicRMWInst *emitAtomicRMWInst(
4316 llvm::AtomicRMWInst::BinOp Op, Address Addr, llvm::Value *Val,
4317 llvm::AtomicOrdering Order = llvm::AtomicOrdering::SequentiallyConsistent,
4318 llvm::SyncScope::ID SSID = llvm::SyncScope::System,
4319 const AtomicExpr *AE = nullptr);
4320
4321 void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
4322 const llvm::function_ref<RValue(RValue)> &UpdateOp,
4323 bool IsVolatile);
4324
4325 /// EmitToMemory - Change a scalar value from its value
4326 /// representation to its in-memory representation.
4327 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
4328
4329 /// EmitFromMemory - Change a scalar value from its memory
4330 /// representation to its value representation.
4331 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
4332
4333 /// Check if the scalar \p Value is within the valid range for the given
4334 /// type \p Ty.
4335 ///
4336 /// Returns true if a check is needed (even if the range is unknown).
4337 bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
4338 SourceLocation Loc);
4339
4340 /// EmitLoadOfScalar - Load a scalar value from an address, taking
4341 /// care to appropriately convert from the memory representation to
4342 /// the LLVM value representation.
4343 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
4344 SourceLocation Loc,
4345 AlignmentSource Source = AlignmentSource::Type,
4346 bool isNontemporal = false) {
4347 return EmitLoadOfScalar(Addr, Volatile, Ty, Loc, BaseInfo: LValueBaseInfo(Source),
4348 TBAAInfo: CGM.getTBAAAccessInfo(AccessType: Ty), isNontemporal);
4349 }
4350
4351 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
4352 SourceLocation Loc, LValueBaseInfo BaseInfo,
4353 TBAAAccessInfo TBAAInfo,
4354 bool isNontemporal = false);
4355
4356 /// EmitLoadOfScalar - Load a scalar value from an address, taking
4357 /// care to appropriately convert from the memory representation to
4358 /// the LLVM value representation. The l-value must be a simple
4359 /// l-value.
4360 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
4361
4362 /// EmitStoreOfScalar - Store a scalar value to an address, taking
4363 /// care to appropriately convert from the memory representation to
4364 /// the LLVM value representation.
4365 void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile,
4366 QualType Ty,
4367 AlignmentSource Source = AlignmentSource::Type,
4368 bool isInit = false, bool isNontemporal = false) {
4369 EmitStoreOfScalar(Value, Addr, Volatile, Ty, BaseInfo: LValueBaseInfo(Source),
4370 TBAAInfo: CGM.getTBAAAccessInfo(AccessType: Ty), isInit, isNontemporal);
4371 }
4372
4373 void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile,
4374 QualType Ty, LValueBaseInfo BaseInfo,
4375 TBAAAccessInfo TBAAInfo, bool isInit = false,
4376 bool isNontemporal = false);
4377
4378 /// EmitStoreOfScalar - Store a scalar value to an address, taking
4379 /// care to appropriately convert from the memory representation to
4380 /// the LLVM value representation. The l-value must be a simple
4381 /// l-value. The isInit flag indicates whether this is an initialization.
4382 /// If so, atomic qualifiers are ignored and the store is always non-atomic.
4383 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
4384 bool isInit = false);
4385
4386 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
4387 /// this method emits the address of the lvalue, then loads the result as an
4388 /// rvalue, returning the rvalue.
4389 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
4390 RValue EmitLoadOfExtVectorElementLValue(LValue V);
4391 RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc);
4392 RValue EmitLoadOfGlobalRegLValue(LValue LV);
4393
4394 /// Like EmitLoadOfLValue but also handles complex and aggregate types.
4395 RValue EmitLoadOfAnyValue(LValue V,
4396 AggValueSlot Slot = AggValueSlot::ignored(),
4397 SourceLocation Loc = {});
4398
4399 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
4400 /// lvalue, where both are guaranteed to the have the same type, and that type
4401 /// is 'Ty'.
4402 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
4403 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
4404 void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
4405
4406 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
4407 /// as EmitStoreThroughLValue.
4408 ///
4409 /// \param Result [out] - If non-null, this will be set to a Value* for the
4410 /// bit-field contents after the store, appropriate for use as the result of
4411 /// an assignment to the bit-field.
4412 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
4413 llvm::Value **Result = nullptr);
4414
4415 /// Emit an l-value for an assignment (simple or compound) of complex type.
4416 LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
4417 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
4418 LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
4419 llvm::Value *&Result);
4420
4421 // Note: only available for agg return types
4422 LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
4423 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
4424 // Note: only available for agg return types
4425 LValue EmitCallExprLValue(const CallExpr *E,
4426 llvm::CallBase **CallOrInvoke = nullptr);
4427 // Note: only available for agg return types
4428 LValue EmitVAArgExprLValue(const VAArgExpr *E);
4429 LValue EmitDeclRefLValue(const DeclRefExpr *E);
4430 LValue EmitStringLiteralLValue(const StringLiteral *E);
4431 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
4432 LValue EmitPredefinedLValue(const PredefinedExpr *E);
4433 LValue EmitUnaryOpLValue(const UnaryOperator *E);
4434 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
4435 bool Accessed = false);
4436 llvm::Value *EmitMatrixIndexExpr(const Expr *E);
4437 LValue EmitMatrixSingleSubscriptExpr(const MatrixSingleSubscriptExpr *E);
4438 LValue EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E);
4439 LValue EmitArraySectionExpr(const ArraySectionExpr *E,
4440 bool IsLowerBound = true);
4441 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
4442 LValue EmitMemberExpr(const MemberExpr *E);
4443 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
4444 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
4445 LValue EmitInitListLValue(const InitListExpr *E);
4446 void EmitIgnoredConditionalOperator(const AbstractConditionalOperator *E);
4447 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
4448 LValue EmitCastLValue(const CastExpr *E);
4449 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
4450 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
4451 LValue EmitHLSLArrayAssignLValue(const BinaryOperator *E);
4452
4453 std::pair<LValue, LValue> EmitHLSLOutArgLValues(const HLSLOutArgExpr *E,
4454 QualType Ty);
4455 LValue EmitHLSLOutArgExpr(const HLSLOutArgExpr *E, CallArgList &Args,
4456 QualType Ty);
4457
4458 Address EmitExtVectorElementLValue(LValue V);
4459
4460 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
4461
4462 Address EmitArrayToPointerDecay(const Expr *Array,
4463 LValueBaseInfo *BaseInfo = nullptr,
4464 TBAAAccessInfo *TBAAInfo = nullptr);
4465
4466 class ConstantEmission {
4467 llvm::PointerIntPair<llvm::Constant *, 1, bool> ValueAndIsReference;
4468 ConstantEmission(llvm::Constant *C, bool isReference)
4469 : ValueAndIsReference(C, isReference) {}
4470
4471 public:
4472 ConstantEmission() {}
4473 static ConstantEmission forReference(llvm::Constant *C) {
4474 return ConstantEmission(C, true);
4475 }
4476 static ConstantEmission forValue(llvm::Constant *C) {
4477 return ConstantEmission(C, false);
4478 }
4479
4480 explicit operator bool() const {
4481 return ValueAndIsReference.getOpaqueValue() != nullptr;
4482 }
4483
4484 bool isReference() const { return ValueAndIsReference.getInt(); }
4485 LValue getReferenceLValue(CodeGenFunction &CGF, const Expr *RefExpr) const {
4486 assert(isReference());
4487 return CGF.MakeNaturalAlignAddrLValue(V: ValueAndIsReference.getPointer(),
4488 T: RefExpr->getType());
4489 }
4490
4491 llvm::Constant *getValue() const {
4492 assert(!isReference());
4493 return ValueAndIsReference.getPointer();
4494 }
4495 };
4496
4497 ConstantEmission tryEmitAsConstant(const DeclRefExpr *RefExpr);
4498 ConstantEmission tryEmitAsConstant(const MemberExpr *ME);
4499 llvm::Value *emitScalarConstant(const ConstantEmission &Constant, Expr *E);
4500
4501 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
4502 AggValueSlot slot = AggValueSlot::ignored());
4503 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
4504
4505 void FlattenAccessAndTypeLValue(LValue LVal,
4506 SmallVectorImpl<LValue> &AccessList);
4507
4508 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
4509 const ObjCIvarDecl *Ivar);
4510 llvm::Value *EmitIvarOffsetAsPointerDiff(const ObjCInterfaceDecl *Interface,
4511 const ObjCIvarDecl *Ivar);
4512 LValue EmitLValueForField(LValue Base, const FieldDecl *Field,
4513 bool IsInBounds = true);
4514 LValue EmitLValueForLambdaField(const FieldDecl *Field);
4515 LValue EmitLValueForLambdaField(const FieldDecl *Field,
4516 llvm::Value *ThisValue);
4517
4518 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
4519 /// if the Field is a reference, this will return the address of the reference
4520 /// and not the address of the value stored in the reference.
4521 LValue EmitLValueForFieldInitialization(LValue Base, const FieldDecl *Field);
4522
4523 LValue EmitLValueForIvar(QualType ObjectTy, llvm::Value *Base,
4524 const ObjCIvarDecl *Ivar, unsigned CVRQualifiers);
4525
4526 LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
4527 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
4528 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
4529 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
4530
4531 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
4532 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
4533 LValue EmitStmtExprLValue(const StmtExpr *E);
4534 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
4535 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
4536 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init);
4537
4538 //===--------------------------------------------------------------------===//
4539 // Scalar Expression Emission
4540 //===--------------------------------------------------------------------===//
4541
4542 /// EmitCall - Generate a call of the given function, expecting the given
4543 /// result type, and using the given argument list which specifies both the
4544 /// LLVM arguments and the types they were derived from.
4545 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
4546 ReturnValueSlot ReturnValue, const CallArgList &Args,
4547 llvm::CallBase **CallOrInvoke, bool IsMustTail,
4548 SourceLocation Loc,
4549 bool IsVirtualFunctionPointerThunk = false);
4550 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
4551 ReturnValueSlot ReturnValue, const CallArgList &Args,
4552 llvm::CallBase **CallOrInvoke = nullptr,
4553 bool IsMustTail = false) {
4554 return EmitCall(CallInfo, Callee, ReturnValue, Args, CallOrInvoke,
4555 IsMustTail, Loc: SourceLocation());
4556 }
4557 RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E,
4558 ReturnValueSlot ReturnValue, llvm::Value *Chain = nullptr,
4559 llvm::CallBase **CallOrInvoke = nullptr,
4560 CGFunctionInfo const **ResolvedFnInfo = nullptr);
4561
4562 // If a Call or Invoke instruction was emitted for this CallExpr, this method
4563 // writes the pointer to `CallOrInvoke` if it's not null.
4564 RValue EmitCallExpr(const CallExpr *E,
4565 ReturnValueSlot ReturnValue = ReturnValueSlot(),
4566 llvm::CallBase **CallOrInvoke = nullptr);
4567 RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue,
4568 llvm::CallBase **CallOrInvoke = nullptr);
4569 CGCallee EmitCallee(const Expr *E);
4570
4571 void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
4572 void checkTargetFeatures(SourceLocation Loc, const FunctionDecl *TargetDecl);
4573
4574 llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee,
4575 const Twine &name = "");
4576 llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee,
4577 ArrayRef<llvm::Value *> args,
4578 const Twine &name = "");
4579 llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4580 const Twine &name = "");
4581 llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4582 ArrayRef<Address> args,
4583 const Twine &name = "");
4584 llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4585 ArrayRef<llvm::Value *> args,
4586 const Twine &name = "");
4587
4588 SmallVector<llvm::OperandBundleDef, 1>
4589 getBundlesForFunclet(llvm::Value *Callee);
4590
4591 llvm::CallBase *EmitCallOrInvoke(llvm::FunctionCallee Callee,
4592 ArrayRef<llvm::Value *> Args,
4593 const Twine &Name = "");
4594 llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4595 ArrayRef<llvm::Value *> args,
4596 const Twine &name = "");
4597 llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4598 const Twine &name = "");
4599 void EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4600 ArrayRef<llvm::Value *> args);
4601
4602 CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
4603 NestedNameSpecifier Qual, llvm::Type *Ty);
4604
4605 CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
4606 CXXDtorType Type,
4607 const CXXRecordDecl *RD);
4608
4609 bool isPointerKnownNonNull(const Expr *E);
4610 /// Check whether the underlying base pointer is a constant null.
4611 bool isUnderlyingBasePointerConstantNull(const Expr *E);
4612
4613 /// Create the discriminator from the storage address and the entity hash.
4614 llvm::Value *EmitPointerAuthBlendDiscriminator(llvm::Value *StorageAddress,
4615 llvm::Value *Discriminator);
4616 CGPointerAuthInfo EmitPointerAuthInfo(const PointerAuthSchema &Schema,
4617 llvm::Value *StorageAddress,
4618 GlobalDecl SchemaDecl,
4619 QualType SchemaType);
4620
4621 llvm::Value *EmitPointerAuthSign(const CGPointerAuthInfo &Info,
4622 llvm::Value *Pointer);
4623
4624 llvm::Value *EmitPointerAuthAuth(const CGPointerAuthInfo &Info,
4625 llvm::Value *Pointer);
4626
4627 llvm::Value *emitPointerAuthResign(llvm::Value *Pointer, QualType PointerType,
4628 const CGPointerAuthInfo &CurAuthInfo,
4629 const CGPointerAuthInfo &NewAuthInfo,
4630 bool IsKnownNonNull);
4631 llvm::Value *emitPointerAuthResignCall(llvm::Value *Pointer,
4632 const CGPointerAuthInfo &CurInfo,
4633 const CGPointerAuthInfo &NewInfo);
4634
4635 void EmitPointerAuthOperandBundle(
4636 const CGPointerAuthInfo &Info,
4637 SmallVectorImpl<llvm::OperandBundleDef> &Bundles);
4638
4639 CGPointerAuthInfo EmitPointerAuthInfo(PointerAuthQualifier Qualifier,
4640 Address StorageAddress);
4641 llvm::Value *EmitPointerAuthQualify(PointerAuthQualifier Qualifier,
4642 llvm::Value *Pointer, QualType ValueType,
4643 Address StorageAddress,
4644 bool IsKnownNonNull);
4645 llvm::Value *EmitPointerAuthQualify(PointerAuthQualifier Qualifier,
4646 const Expr *PointerExpr,
4647 Address StorageAddress);
4648 llvm::Value *EmitPointerAuthUnqualify(PointerAuthQualifier Qualifier,
4649 llvm::Value *Pointer,
4650 QualType PointerType,
4651 Address StorageAddress,
4652 bool IsKnownNonNull);
4653 void EmitPointerAuthCopy(PointerAuthQualifier Qualifier, QualType Type,
4654 Address DestField, Address SrcField);
4655
4656 std::pair<llvm::Value *, CGPointerAuthInfo>
4657 EmitOrigPointerRValue(const Expr *E);
4658
4659 llvm::Value *authPointerToPointerCast(llvm::Value *ResultPtr,
4660 QualType SourceType, QualType DestType);
4661 Address authPointerToPointerCast(Address Ptr, QualType SourceType,
4662 QualType DestType);
4663
4664 Address getAsNaturalAddressOf(Address Addr, QualType PointeeTy);
4665
4666 llvm::Value *getAsNaturalPointerTo(Address Addr, QualType PointeeType) {
4667 return getAsNaturalAddressOf(Addr, PointeeTy: PointeeType).getBasePointer();
4668 }
4669
4670 // Return the copy constructor name with the prefix "__copy_constructor_"
4671 // removed.
4672 static std::string getNonTrivialCopyConstructorStr(QualType QT,
4673 CharUnits Alignment,
4674 bool IsVolatile,
4675 ASTContext &Ctx);
4676
4677 // Return the destructor name with the prefix "__destructor_" removed.
4678 static std::string getNonTrivialDestructorStr(QualType QT,
4679 CharUnits Alignment,
4680 bool IsVolatile,
4681 ASTContext &Ctx);
4682
4683 // These functions emit calls to the special functions of non-trivial C
4684 // structs.
4685 void defaultInitNonTrivialCStructVar(LValue Dst);
4686 void callCStructDefaultConstructor(LValue Dst);
4687 void callCStructDestructor(LValue Dst);
4688 void callCStructCopyConstructor(LValue Dst, LValue Src);
4689 void callCStructMoveConstructor(LValue Dst, LValue Src);
4690 void callCStructCopyAssignmentOperator(LValue Dst, LValue Src);
4691 void callCStructMoveAssignmentOperator(LValue Dst, LValue Src);
4692
4693 RValue EmitCXXMemberOrOperatorCall(
4694 const CXXMethodDecl *Method, const CGCallee &Callee,
4695 ReturnValueSlot ReturnValue, llvm::Value *This,
4696 llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *E,
4697 CallArgList *RtlArgs, llvm::CallBase **CallOrInvoke);
4698 RValue EmitCXXDestructorCall(GlobalDecl Dtor, const CGCallee &Callee,
4699 llvm::Value *This, QualType ThisTy,
4700 llvm::Value *ImplicitParam,
4701 QualType ImplicitParamTy, const CallExpr *E,
4702 llvm::CallBase **CallOrInvoke = nullptr);
4703 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
4704 ReturnValueSlot ReturnValue,
4705 llvm::CallBase **CallOrInvoke = nullptr);
4706 RValue EmitCXXMemberOrOperatorMemberCallExpr(
4707 const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
4708 bool HasQualifier, NestedNameSpecifier Qualifier, bool IsArrow,
4709 const Expr *Base, llvm::CallBase **CallOrInvoke);
4710 // Compute the object pointer.
4711 Address EmitCXXMemberDataPointerAddress(
4712 const Expr *E, Address base, llvm::Value *memberPtr,
4713 const MemberPointerType *memberPtrType, bool IsInBounds,
4714 LValueBaseInfo *BaseInfo = nullptr, TBAAAccessInfo *TBAAInfo = nullptr);
4715 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
4716 ReturnValueSlot ReturnValue,
4717 llvm::CallBase **CallOrInvoke);
4718
4719 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
4720 const CXXMethodDecl *MD,
4721 ReturnValueSlot ReturnValue,
4722 llvm::CallBase **CallOrInvoke);
4723 RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
4724
4725 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
4726 ReturnValueSlot ReturnValue,
4727 llvm::CallBase **CallOrInvoke);
4728
4729 RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E);
4730 RValue EmitAMDGPUDevicePrintfCallExpr(const CallExpr *E);
4731
4732 RValue EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
4733 const CallExpr *E, ReturnValueSlot ReturnValue);
4734
4735 RValue emitRotate(const CallExpr *E, bool IsRotateRight);
4736
4737 /// Emit IR for __builtin_os_log_format.
4738 RValue emitBuiltinOSLogFormat(const CallExpr &E);
4739
4740 /// Emit IR for __builtin_is_aligned.
4741 RValue EmitBuiltinIsAligned(const CallExpr *E);
4742 /// Emit IR for __builtin_align_up/__builtin_align_down.
4743 RValue EmitBuiltinAlignTo(const CallExpr *E, bool AlignUp);
4744
4745 llvm::Function *generateBuiltinOSLogHelperFunction(
4746 const analyze_os_log::OSLogBufferLayout &Layout,
4747 CharUnits BufferAlignment);
4748
4749 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue,
4750 llvm::CallBase **CallOrInvoke);
4751
4752 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
4753 /// is unhandled by the current target.
4754 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
4755 ReturnValueSlot ReturnValue);
4756
4757 llvm::Value *
4758 EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
4759 const llvm::CmpInst::Predicate Pred,
4760 const llvm::Twine &Name = "");
4761 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
4762 ReturnValueSlot ReturnValue,
4763 llvm::Triple::ArchType Arch);
4764 llvm::Value *EmitARMMVEBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
4765 ReturnValueSlot ReturnValue,
4766 llvm::Triple::ArchType Arch);
4767 llvm::Value *EmitARMCDEBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
4768 ReturnValueSlot ReturnValue,
4769 llvm::Triple::ArchType Arch);
4770 llvm::Value *EmitCMSEClearRecord(llvm::Value *V, llvm::IntegerType *ITy,
4771 QualType RTy);
4772 llvm::Value *EmitCMSEClearRecord(llvm::Value *V, llvm::ArrayType *ATy,
4773 QualType RTy);
4774
4775 llvm::Value *
4776 EmitCommonNeonBuiltinExpr(unsigned BuiltinID, unsigned LLVMIntrinsic,
4777 unsigned AltLLVMIntrinsic, const char *NameHint,
4778 unsigned Modifier, const CallExpr *E,
4779 SmallVectorImpl<llvm::Value *> &Ops, Address PtrOp0,
4780 Address PtrOp1, llvm::Triple::ArchType Arch);
4781
4782 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
4783 unsigned Modifier, llvm::Type *ArgTy,
4784 const CallExpr *E);
4785 llvm::Value *EmitNeonCall(llvm::Function *F,
4786 SmallVectorImpl<llvm::Value *> &O, const char *name,
4787 unsigned shift = 0, bool rightshift = false);
4788 llvm::Value *EmitFP8NeonCall(unsigned IID, ArrayRef<llvm::Type *> Tys,
4789 SmallVectorImpl<llvm::Value *> &O,
4790 const CallExpr *E, const char *name);
4791 llvm::Value *EmitFP8NeonCvtCall(unsigned IID, llvm::Type *Ty0,
4792 llvm::Type *Ty1, bool Extract,
4793 SmallVectorImpl<llvm::Value *> &Ops,
4794 const CallExpr *E, const char *name);
4795 llvm::Value *EmitFP8NeonFDOTCall(unsigned IID, bool ExtendLaneArg,
4796 llvm::Type *RetTy,
4797 SmallVectorImpl<llvm::Value *> &Ops,
4798 const CallExpr *E, const char *name);
4799 llvm::Value *EmitFP8NeonFMLACall(unsigned IID, bool ExtendLaneArg,
4800 llvm::Type *RetTy,
4801 SmallVectorImpl<llvm::Value *> &Ops,
4802 const CallExpr *E, const char *name);
4803 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx,
4804 const llvm::ElementCount &Count);
4805 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
4806 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
4807 bool negateForRightShift);
4808 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
4809 llvm::Type *Ty, bool usgn, const char *name);
4810 llvm::Value *vectorWrapScalar16(llvm::Value *Op);
4811 /// SVEBuiltinMemEltTy - Returns the memory element type for this memory
4812 /// access builtin. Only required if it can't be inferred from the base
4813 /// pointer operand.
4814 llvm::Type *SVEBuiltinMemEltTy(const SVETypeFlags &TypeFlags);
4815
4816 SmallVector<llvm::Type *, 2>
4817 getSVEOverloadTypes(const SVETypeFlags &TypeFlags, llvm::Type *ReturnType,
4818 ArrayRef<llvm::Value *> Ops);
4819 llvm::Type *getEltType(const SVETypeFlags &TypeFlags);
4820 llvm::ScalableVectorType *getSVEType(const SVETypeFlags &TypeFlags);
4821 llvm::ScalableVectorType *getSVEPredType(const SVETypeFlags &TypeFlags);
4822 llvm::Value *EmitSVETupleSetOrGet(const SVETypeFlags &TypeFlags,
4823 ArrayRef<llvm::Value *> Ops);
4824 llvm::Value *EmitSVETupleCreate(const SVETypeFlags &TypeFlags,
4825 llvm::Type *ReturnType,
4826 ArrayRef<llvm::Value *> Ops);
4827 llvm::Value *EmitSVEAllTruePred(const SVETypeFlags &TypeFlags);
4828 llvm::Value *EmitSVEDupX(llvm::Value *Scalar);
4829 llvm::Value *EmitSVEDupX(llvm::Value *Scalar, llvm::Type *Ty);
4830 llvm::Value *EmitSVEReinterpret(llvm::Value *Val, llvm::Type *Ty);
4831 llvm::Value *EmitSVEPMull(const SVETypeFlags &TypeFlags,
4832 llvm::SmallVectorImpl<llvm::Value *> &Ops,
4833 unsigned BuiltinID);
4834 llvm::Value *EmitSVEMovl(const SVETypeFlags &TypeFlags,
4835 llvm::ArrayRef<llvm::Value *> Ops,
4836 unsigned BuiltinID);
4837 llvm::Value *EmitSVEPredicateCast(llvm::Value *Pred,
4838 llvm::ScalableVectorType *VTy);
4839 llvm::Value *EmitSVEPredicateTupleCast(llvm::Value *PredTuple,
4840 llvm::StructType *Ty);
4841 llvm::Value *EmitSVEGatherLoad(const SVETypeFlags &TypeFlags,
4842 llvm::SmallVectorImpl<llvm::Value *> &Ops,
4843 unsigned IntID);
4844 llvm::Value *EmitSVEScatterStore(const SVETypeFlags &TypeFlags,
4845 llvm::SmallVectorImpl<llvm::Value *> &Ops,
4846 unsigned IntID);
4847 llvm::Value *EmitSVEMaskedLoad(const CallExpr *, llvm::Type *ReturnTy,
4848 SmallVectorImpl<llvm::Value *> &Ops,
4849 unsigned BuiltinID, bool IsZExtReturn);
4850 llvm::Value *EmitSVEMaskedStore(const CallExpr *,
4851 SmallVectorImpl<llvm::Value *> &Ops,
4852 unsigned BuiltinID);
4853 llvm::Value *EmitSVEPrefetchLoad(const SVETypeFlags &TypeFlags,
4854 SmallVectorImpl<llvm::Value *> &Ops,
4855 unsigned BuiltinID);
4856 llvm::Value *EmitSVEGatherPrefetch(const SVETypeFlags &TypeFlags,
4857 SmallVectorImpl<llvm::Value *> &Ops,
4858 unsigned IntID);
4859 llvm::Value *EmitSVEStructLoad(const SVETypeFlags &TypeFlags,
4860 SmallVectorImpl<llvm::Value *> &Ops,
4861 unsigned IntID);
4862 llvm::Value *EmitSVEStructStore(const SVETypeFlags &TypeFlags,
4863 SmallVectorImpl<llvm::Value *> &Ops,
4864 unsigned IntID);
4865 llvm::Value *EmitAArch64SVEBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4866
4867 llvm::Value *EmitSMELd1St1(const SVETypeFlags &TypeFlags,
4868 llvm::SmallVectorImpl<llvm::Value *> &Ops,
4869 unsigned IntID);
4870 llvm::Value *EmitSMEReadWrite(const SVETypeFlags &TypeFlags,
4871 llvm::SmallVectorImpl<llvm::Value *> &Ops,
4872 unsigned IntID);
4873 llvm::Value *EmitSMEZero(const SVETypeFlags &TypeFlags,
4874 llvm::SmallVectorImpl<llvm::Value *> &Ops,
4875 unsigned IntID);
4876 llvm::Value *EmitSMELdrStr(const SVETypeFlags &TypeFlags,
4877 llvm::SmallVectorImpl<llvm::Value *> &Ops,
4878 unsigned IntID);
4879
4880 void GetAArch64SVEProcessedOperands(unsigned BuiltinID, const CallExpr *E,
4881 SmallVectorImpl<llvm::Value *> &Ops,
4882 SVETypeFlags TypeFlags);
4883
4884 llvm::Value *EmitAArch64SMEBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4885
4886 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E,
4887 llvm::Triple::ArchType Arch);
4888 llvm::Value *EmitBPFBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4889
4890 llvm::Value *BuildVector(ArrayRef<llvm::Value *> Ops);
4891 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4892 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4893 llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4894 llvm::Value *EmitHLSLBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
4895 ReturnValueSlot ReturnValue);
4896
4897 // Returns a builtin function that the SPIR-V backend will expand into a spec
4898 // constant.
4899 llvm::Function *
4900 getSpecConstantFunction(const clang::QualType &SpecConstantType);
4901
4902 llvm::Value *EmitDirectXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4903 llvm::Value *EmitSPIRVBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4904 llvm::Value *EmitScalarOrConstFoldImmArg(unsigned ICEArguments, unsigned Idx,
4905 const CallExpr *E);
4906 llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4907 llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4908 llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
4909 const CallExpr *E);
4910 llvm::Value *EmitHexagonBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4911 llvm::Value *EmitRISCVBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
4912 ReturnValueSlot ReturnValue);
4913
4914 llvm::Value *EmitRISCVCpuSupports(const CallExpr *E);
4915 llvm::Value *EmitRISCVCpuSupports(ArrayRef<StringRef> FeaturesStrs);
4916 llvm::Value *EmitRISCVCpuInit();
4917 llvm::Value *EmitRISCVCpuIs(const CallExpr *E);
4918 llvm::Value *EmitRISCVCpuIs(StringRef CPUStr);
4919
4920 void AddAMDGPUFenceAddressSpaceMMRA(llvm::Instruction *Inst,
4921 const CallExpr *E);
4922 void ProcessOrderScopeAMDGCN(llvm::Value *Order, llvm::Value *Scope,
4923 llvm::AtomicOrdering &AO,
4924 llvm::SyncScope::ID &SSID);
4925
4926 enum class MSVCIntrin;
4927 llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
4928
4929 llvm::Value *EmitBuiltinAvailable(const VersionTuple &Version);
4930
4931 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
4932 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
4933 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
4934 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
4935 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
4936 llvm::Value *
4937 EmitObjCCollectionLiteral(const Expr *E,
4938 const ObjCMethodDecl *MethodWithObjects);
4939 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
4940 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
4941 ReturnValueSlot Return = ReturnValueSlot());
4942
4943 /// Retrieves the default cleanup kind for an ARC cleanup.
4944 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
4945 CleanupKind getARCCleanupKind() {
4946 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions ? NormalAndEHCleanup
4947 : NormalCleanup;
4948 }
4949
4950 // ARC primitives.
4951 void EmitARCInitWeak(Address addr, llvm::Value *value);
4952 void EmitARCDestroyWeak(Address addr);
4953 llvm::Value *EmitARCLoadWeak(Address addr);
4954 llvm::Value *EmitARCLoadWeakRetained(Address addr);
4955 llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
4956 void emitARCCopyAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr);
4957 void emitARCMoveAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr);
4958 void EmitARCCopyWeak(Address dst, Address src);
4959 void EmitARCMoveWeak(Address dst, Address src);
4960 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
4961 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
4962 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
4963 bool resultIgnored);
4964 llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
4965 bool resultIgnored);
4966 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
4967 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
4968 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
4969 void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise);
4970 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
4971 llvm::Value *EmitARCAutorelease(llvm::Value *value);
4972 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
4973 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
4974 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
4975 llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value);
4976
4977 llvm::Value *EmitObjCAutorelease(llvm::Value *value, llvm::Type *returnType);
4978 llvm::Value *EmitObjCRetainNonBlock(llvm::Value *value,
4979 llvm::Type *returnType);
4980 void EmitObjCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
4981
4982 std::pair<LValue, llvm::Value *>
4983 EmitARCStoreAutoreleasing(const BinaryOperator *e);
4984 std::pair<LValue, llvm::Value *> EmitARCStoreStrong(const BinaryOperator *e,
4985 bool ignored);
4986 std::pair<LValue, llvm::Value *>
4987 EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored);
4988
4989 llvm::Value *EmitObjCAlloc(llvm::Value *value, llvm::Type *returnType);
4990 llvm::Value *EmitObjCAllocWithZone(llvm::Value *value,
4991 llvm::Type *returnType);
4992 llvm::Value *EmitObjCAllocInit(llvm::Value *value, llvm::Type *resultType);
4993
4994 llvm::Value *EmitObjCThrowOperand(const Expr *expr);
4995 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
4996 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
4997
4998 llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
4999 llvm::Value *EmitARCReclaimReturnedObject(const Expr *e,
5000 bool allowUnsafeClaim);
5001 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
5002 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
5003 llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr);
5004
5005 void EmitARCIntrinsicUse(ArrayRef<llvm::Value *> values);
5006
5007 void EmitARCNoopIntrinsicUse(ArrayRef<llvm::Value *> values);
5008
5009 static Destroyer destroyARCStrongImprecise;
5010 static Destroyer destroyARCStrongPrecise;
5011 static Destroyer destroyARCWeak;
5012 static Destroyer emitARCIntrinsicUse;
5013 static Destroyer destroyNonTrivialCStruct;
5014
5015 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
5016 llvm::Value *EmitObjCAutoreleasePoolPush();
5017 llvm::Value *EmitObjCMRRAutoreleasePoolPush();
5018 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
5019 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
5020
5021 /// Emits a reference binding to the passed in expression.
5022 RValue EmitReferenceBindingToExpr(const Expr *E);
5023
5024 //===--------------------------------------------------------------------===//
5025 // Expression Emission
5026 //===--------------------------------------------------------------------===//
5027
5028 // Expressions are broken into three classes: scalar, complex, aggregate.
5029
5030 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
5031 /// scalar type, returning the result.
5032 llvm::Value *EmitScalarExpr(const Expr *E, bool IgnoreResultAssign = false);
5033
5034 /// Emit a conversion from the specified type to the specified destination
5035 /// type, both of which are LLVM scalar types.
5036 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
5037 QualType DstTy, SourceLocation Loc);
5038
5039 /// Emit a conversion from the specified complex type to the specified
5040 /// destination type, where the destination type is an LLVM scalar type.
5041 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
5042 QualType DstTy,
5043 SourceLocation Loc);
5044
5045 /// EmitAggExpr - Emit the computation of the specified expression
5046 /// of aggregate type. The result is computed into the given slot,
5047 /// which may be null to indicate that the value is not needed.
5048 void EmitAggExpr(const Expr *E, AggValueSlot AS);
5049
5050 /// EmitAggExprToLValue - Emit the computation of the specified expression of
5051 /// aggregate type into a temporary LValue.
5052 LValue EmitAggExprToLValue(const Expr *E);
5053
5054 enum ExprValueKind { EVK_RValue, EVK_NonRValue };
5055
5056 /// EmitAggFinalDestCopy - Emit copy of the specified aggregate into
5057 /// destination address.
5058 void EmitAggFinalDestCopy(QualType Type, AggValueSlot Dest, const LValue &Src,
5059 ExprValueKind SrcKind);
5060
5061 /// Create a store to \arg DstPtr from \arg Src, truncating the stored value
5062 /// to at most \arg DstSize bytes.
5063 void CreateCoercedStore(llvm::Value *Src, Address Dst, llvm::TypeSize DstSize,
5064 bool DstIsVolatile);
5065
5066 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
5067 /// make sure it survives garbage collection until this point.
5068 void EmitExtendGCLifetime(llvm::Value *object);
5069
5070 /// EmitComplexExpr - Emit the computation of the specified expression of
5071 /// complex type, returning the result.
5072 ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal = false,
5073 bool IgnoreImag = false);
5074
5075 /// EmitComplexExprIntoLValue - Emit the given expression of complex
5076 /// type and place its result into the specified l-value.
5077 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
5078
5079 /// EmitStoreOfComplex - Store a complex number into the specified l-value.
5080 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
5081
5082 /// EmitLoadOfComplex - Load a complex number from the specified l-value.
5083 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
5084
5085 ComplexPairTy EmitPromotedComplexExpr(const Expr *E, QualType PromotionType);
5086 llvm::Value *EmitPromotedScalarExpr(const Expr *E, QualType PromotionType);
5087 ComplexPairTy EmitPromotedValue(ComplexPairTy result, QualType PromotionType);
5088 ComplexPairTy EmitUnPromotedValue(ComplexPairTy result,
5089 QualType PromotionType);
5090
5091 Address emitAddrOfRealComponent(Address complex, QualType complexType);
5092 Address emitAddrOfImagComponent(Address complex, QualType complexType);
5093
5094 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
5095 /// global variable that has already been created for it. If the initializer
5096 /// has a different type than GV does, this may free GV and return a different
5097 /// one. Otherwise it just returns GV.
5098 llvm::GlobalVariable *AddInitializerToStaticVarDecl(const VarDecl &D,
5099 llvm::GlobalVariable *GV);
5100
5101 // Emit an @llvm.invariant.start call for the given memory region.
5102 void EmitInvariantStart(llvm::Constant *Addr, CharUnits Size);
5103
5104 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
5105 /// variable with global storage.
5106 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::GlobalVariable *GV,
5107 bool PerformInit);
5108
5109 llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::FunctionCallee Dtor,
5110 llvm::Constant *Addr);
5111
5112 llvm::Function *createTLSAtExitStub(const VarDecl &VD,
5113 llvm::FunctionCallee Dtor,
5114 llvm::Constant *Addr,
5115 llvm::FunctionCallee &AtExit);
5116
5117 /// Call atexit() with a function that passes the given argument to
5118 /// the given function.
5119 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::FunctionCallee fn,
5120 llvm::Constant *addr);
5121
5122 /// Registers the dtor using 'llvm.global_dtors' for platforms that do not
5123 /// support an 'atexit()' function.
5124 void registerGlobalDtorWithLLVM(const VarDecl &D, llvm::FunctionCallee fn,
5125 llvm::Constant *addr);
5126
5127 /// Call atexit() with function dtorStub.
5128 void registerGlobalDtorWithAtExit(llvm::Constant *dtorStub);
5129
5130 /// Call unatexit() with function dtorStub.
5131 llvm::Value *unregisterGlobalDtorWithUnAtExit(llvm::Constant *dtorStub);
5132
5133 /// Emit code in this function to perform a guarded variable
5134 /// initialization. Guarded initializations are used when it's not
5135 /// possible to prove that an initialization will be done exactly
5136 /// once, e.g. with a static local variable or a static data member
5137 /// of a class template.
5138 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
5139 bool PerformInit);
5140
5141 enum class GuardKind { VariableGuard, TlsGuard };
5142
5143 /// Emit a branch to select whether or not to perform guarded initialization.
5144 void EmitCXXGuardedInitBranch(llvm::Value *NeedsInit,
5145 llvm::BasicBlock *InitBlock,
5146 llvm::BasicBlock *NoInitBlock, GuardKind Kind,
5147 const VarDecl *D);
5148
5149 /// GenerateCXXGlobalInitFunc - Generates code for initializing global
5150 /// variables.
5151 void
5152 GenerateCXXGlobalInitFunc(llvm::Function *Fn,
5153 ArrayRef<llvm::Function *> CXXThreadLocals,
5154 ConstantAddress Guard = ConstantAddress::invalid());
5155
5156 /// GenerateCXXGlobalCleanUpFunc - Generates code for cleaning up global
5157 /// variables.
5158 void GenerateCXXGlobalCleanUpFunc(
5159 llvm::Function *Fn,
5160 ArrayRef<std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
5161 llvm::Constant *>>
5162 DtorsOrStermFinalizers);
5163
5164 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, const VarDecl *D,
5165 llvm::GlobalVariable *Addr,
5166 bool PerformInit);
5167
5168 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
5169
5170 void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
5171
5172 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
5173
5174 RValue EmitAtomicExpr(AtomicExpr *E);
5175
5176 void EmitFakeUse(Address Addr);
5177
5178 //===--------------------------------------------------------------------===//
5179 // Annotations Emission
5180 //===--------------------------------------------------------------------===//
5181
5182 /// Emit an annotation call (intrinsic).
5183 llvm::Value *EmitAnnotationCall(llvm::Function *AnnotationFn,
5184 llvm::Value *AnnotatedVal,
5185 StringRef AnnotationStr,
5186 SourceLocation Location,
5187 const AnnotateAttr *Attr);
5188
5189 /// Emit local annotations for the local variable V, declared by D.
5190 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
5191
5192 /// Emit field annotations for the given field & value. Returns the
5193 /// annotation result.
5194 Address EmitFieldAnnotations(const FieldDecl *D, Address V);
5195
5196 //===--------------------------------------------------------------------===//
5197 // Internal Helpers
5198 //===--------------------------------------------------------------------===//
5199
5200 /// ContainsLabel - Return true if the statement contains a label in it. If
5201 /// this statement is not executed normally, it not containing a label means
5202 /// that we can just remove the code.
5203 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
5204
5205 /// containsBreak - Return true if the statement contains a break out of it.
5206 /// If the statement (recursively) contains a switch or loop with a break
5207 /// inside of it, this is fine.
5208 static bool containsBreak(const Stmt *S);
5209
5210 /// Determine if the given statement might introduce a declaration into the
5211 /// current scope, by being a (possibly-labelled) DeclStmt.
5212 static bool mightAddDeclToScope(const Stmt *S);
5213
5214 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
5215 /// to a constant, or if it does but contains a label, return false. If it
5216 /// constant folds return true and set the boolean result in Result.
5217 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result,
5218 bool AllowLabels = false);
5219
5220 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
5221 /// to a constant, or if it does but contains a label, return false. If it
5222 /// constant folds return true and set the folded value.
5223 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result,
5224 bool AllowLabels = false);
5225
5226 /// Ignore parentheses and logical-NOT to track conditions consistently.
5227 static const Expr *stripCond(const Expr *C);
5228
5229 /// isInstrumentedCondition - Determine whether the given condition is an
5230 /// instrumentable condition (i.e. no "&&" or "||").
5231 static bool isInstrumentedCondition(const Expr *C);
5232
5233 /// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
5234 /// increments a profile counter based on the semantics of the given logical
5235 /// operator opcode. This is used to instrument branch condition coverage
5236 /// for logical operators.
5237 void EmitBranchToCounterBlock(const Expr *Cond, BinaryOperator::Opcode LOp,
5238 llvm::BasicBlock *TrueBlock,
5239 llvm::BasicBlock *FalseBlock,
5240 uint64_t TrueCount = 0,
5241 Stmt::Likelihood LH = Stmt::LH_None,
5242 const Expr *CntrIdx = nullptr);
5243
5244 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
5245 /// if statement) to the specified blocks. Based on the condition, this might
5246 /// try to simplify the codegen of the conditional based on the branch.
5247 /// TrueCount should be the number of times we expect the condition to
5248 /// evaluate to true based on PGO data.
5249 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
5250 llvm::BasicBlock *FalseBlock, uint64_t TrueCount,
5251 Stmt::Likelihood LH = Stmt::LH_None,
5252 const Expr *ConditionalOp = nullptr,
5253 const VarDecl *ConditionalDecl = nullptr);
5254
5255 /// Given an assignment `*LHS = RHS`, emit a test that checks if \p RHS is
5256 /// nonnull, if \p LHS is marked _Nonnull.
5257 void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc);
5258
5259 /// An enumeration which makes it easier to specify whether or not an
5260 /// operation is a subtraction.
5261 enum { NotSubtraction = false, IsSubtraction = true };
5262
5263 /// Emit pointer + index arithmetic.
5264 llvm::Value *EmitPointerArithmetic(const BinaryOperator *BO,
5265 Expr *pointerOperand, llvm::Value *pointer,
5266 Expr *indexOperand, llvm::Value *index,
5267 bool isSubtraction);
5268
5269 /// Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to
5270 /// detect undefined behavior when the pointer overflow sanitizer is enabled.
5271 /// \p SignedIndices indicates whether any of the GEP indices are signed.
5272 /// \p IsSubtraction indicates whether the expression used to form the GEP
5273 /// is a subtraction.
5274 llvm::Value *EmitCheckedInBoundsGEP(llvm::Type *ElemTy, llvm::Value *Ptr,
5275 ArrayRef<llvm::Value *> IdxList,
5276 bool SignedIndices, bool IsSubtraction,
5277 SourceLocation Loc,
5278 const Twine &Name = "");
5279
5280 Address EmitCheckedInBoundsGEP(Address Addr, ArrayRef<llvm::Value *> IdxList,
5281 llvm::Type *elementType, bool SignedIndices,
5282 bool IsSubtraction, SourceLocation Loc,
5283 CharUnits Align, const Twine &Name = "");
5284
5285 /// Specifies which type of sanitizer check to apply when handling a
5286 /// particular builtin.
5287 enum BuiltinCheckKind {
5288 BCK_CTZPassedZero,
5289 BCK_CLZPassedZero,
5290 BCK_AssumePassedFalse,
5291 };
5292
5293 /// Emits an argument for a call to a builtin. If the builtin sanitizer is
5294 /// enabled, a runtime check specified by \p Kind is also emitted.
5295 llvm::Value *EmitCheckedArgForBuiltin(const Expr *E, BuiltinCheckKind Kind);
5296
5297 /// Emits an argument for a call to a `__builtin_assume`. If the builtin
5298 /// sanitizer is enabled, a runtime check is also emitted.
5299 llvm::Value *EmitCheckedArgForAssume(const Expr *E);
5300
5301 /// Emit a description of a type in a format suitable for passing to
5302 /// a runtime sanitizer handler.
5303 llvm::Constant *EmitCheckTypeDescriptor(QualType T);
5304
5305 /// Convert a value into a format suitable for passing to a runtime
5306 /// sanitizer handler.
5307 llvm::Value *EmitCheckValue(llvm::Value *V);
5308
5309 /// Emit a description of a source location in a format suitable for
5310 /// passing to a runtime sanitizer handler.
5311 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
5312
5313 void EmitKCFIOperandBundle(const CGCallee &Callee,
5314 SmallVectorImpl<llvm::OperandBundleDef> &Bundles);
5315
5316 /// Create a basic block that will either trap or call a handler function in
5317 /// the UBSan runtime with the provided arguments, and create a conditional
5318 /// branch to it.
5319 void
5320 EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
5321 Checked,
5322 SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs,
5323 ArrayRef<llvm::Value *> DynamicArgs,
5324 const TrapReason *TR = nullptr);
5325
5326 /// Emit a slow path cross-DSO CFI check which calls __cfi_slowpath
5327 /// if Cond if false.
5328 void EmitCfiSlowPathCheck(SanitizerKind::SanitizerOrdinal Ordinal,
5329 llvm::Value *Cond, llvm::ConstantInt *TypeId,
5330 llvm::Value *Ptr,
5331 ArrayRef<llvm::Constant *> StaticArgs);
5332
5333 /// Emit a reached-unreachable diagnostic if \p Loc is valid and runtime
5334 /// checking is enabled. Otherwise, just emit an unreachable instruction.
5335 void EmitUnreachable(SourceLocation Loc);
5336
5337 /// Create a basic block that will call the trap intrinsic, and emit a
5338 /// conditional branch to it, for the -ftrapv checks.
5339 void EmitTrapCheck(llvm::Value *Checked, SanitizerHandler CheckHandlerID,
5340 bool NoMerge = false, const TrapReason *TR = nullptr);
5341
5342 /// Emit a call to trap or debugtrap and attach function attribute
5343 /// "trap-func-name" if specified.
5344 llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
5345
5346 /// Emit a stub for the cross-DSO CFI check function.
5347 void EmitCfiCheckStub();
5348
5349 /// Emit a cross-DSO CFI failure handling function.
5350 void EmitCfiCheckFail();
5351
5352 /// Create a check for a function parameter that may potentially be
5353 /// declared as non-null.
5354 void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
5355 AbstractCallee AC, unsigned ParmNum);
5356
5357 void EmitNonNullArgCheck(Address Addr, QualType ArgType,
5358 SourceLocation ArgLoc, AbstractCallee AC,
5359 unsigned ParmNum);
5360
5361 /// EmitWriteback - Emit callbacks for function.
5362 void EmitWritebacks(const CallArgList &Args);
5363
5364 /// EmitCallArg - Emit a single call argument.
5365 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
5366
5367 /// EmitDelegateCallArg - We are performing a delegate call; that
5368 /// is, the current function is delegating to another one. Produce
5369 /// a r-value suitable for passing the given parameter.
5370 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
5371 SourceLocation loc);
5372
5373 /// SetFPAccuracy - Set the minimum required accuracy of the given floating
5374 /// point operation, expressed as the maximum relative error in ulp.
5375 void SetFPAccuracy(llvm::Value *Val, float Accuracy);
5376
5377 /// Set the minimum required accuracy of the given sqrt operation
5378 /// based on CodeGenOpts.
5379 void SetSqrtFPAccuracy(llvm::Value *Val);
5380
5381 /// Set the minimum required accuracy of the given sqrt operation based on
5382 /// CodeGenOpts.
5383 void SetDivFPAccuracy(llvm::Value *Val);
5384
5385 /// Set the codegen fast-math flags.
5386 void SetFastMathFlags(FPOptions FPFeatures);
5387
5388 // Truncate or extend a boolean vector to the requested number of elements.
5389 llvm::Value *emitBoolVecConversion(llvm::Value *SrcVec,
5390 unsigned NumElementsDst,
5391 const llvm::Twine &Name = "");
5392
5393 void maybeAttachRangeForLoad(llvm::LoadInst *Load, QualType Ty,
5394 SourceLocation Loc);
5395
5396private:
5397 // Emits a convergence_loop instruction for the given |BB|, with |ParentToken|
5398 // as it's parent convergence instr.
5399 llvm::ConvergenceControlInst *emitConvergenceLoopToken(llvm::BasicBlock *BB);
5400
5401 // Adds a convergence_ctrl token with |ParentToken| as parent convergence
5402 // instr to the call |Input|.
5403 llvm::CallBase *addConvergenceControlToken(llvm::CallBase *Input);
5404
5405 // Find the convergence_entry instruction |F|, or emits ones if none exists.
5406 // Returns the convergence instruction.
5407 llvm::ConvergenceControlInst *
5408 getOrEmitConvergenceEntryToken(llvm::Function *F);
5409
5410private:
5411 llvm::MDNode *getRangeForLoadFromType(QualType Ty);
5412 void EmitReturnOfRValue(RValue RV, QualType Ty);
5413
5414 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
5415
5416 llvm::SmallVector<std::pair<llvm::WeakTrackingVH, llvm::Value *>, 4>
5417 DeferredReplacements;
5418
5419 /// Set the address of a local variable.
5420 void setAddrOfLocalVar(const VarDecl *VD, Address Addr) {
5421 assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!");
5422 LocalDeclMap.insert(KV: {VD, Addr});
5423 }
5424
5425 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
5426 /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
5427 ///
5428 /// \param AI - The first function argument of the expansion.
5429 void ExpandTypeFromArgs(QualType Ty, LValue Dst,
5430 llvm::Function::arg_iterator &AI);
5431
5432 /// ExpandTypeToArgs - Expand an CallArg \arg Arg, with the LLVM type for \arg
5433 /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
5434 /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
5435 void ExpandTypeToArgs(QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
5436 SmallVectorImpl<llvm::Value *> &IRCallArgs,
5437 unsigned &IRCallArgPos);
5438
5439 std::pair<llvm::Value *, llvm::Type *>
5440 EmitAsmInput(const TargetInfo::ConstraintInfo &Info, const Expr *InputExpr,
5441 std::string &ConstraintStr);
5442
5443 std::pair<llvm::Value *, llvm::Type *>
5444 EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info, LValue InputValue,
5445 QualType InputType, std::string &ConstraintStr,
5446 SourceLocation Loc);
5447
5448 /// Attempts to statically evaluate the object size of E. If that
5449 /// fails, emits code to figure the size of E out for us. This is
5450 /// pass_object_size aware.
5451 ///
5452 /// If EmittedExpr is non-null, this will use that instead of re-emitting E.
5453 llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
5454 llvm::IntegerType *ResType,
5455 llvm::Value *EmittedE,
5456 bool IsDynamic);
5457
5458 /// Emits the size of E, as required by __builtin_object_size. This
5459 /// function is aware of pass_object_size parameters, and will act accordingly
5460 /// if E is a parameter with the pass_object_size attribute.
5461 llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type,
5462 llvm::IntegerType *ResType,
5463 llvm::Value *EmittedE, bool IsDynamic);
5464
5465 llvm::Value *emitCountedBySize(const Expr *E, llvm::Value *EmittedE,
5466 unsigned Type, llvm::IntegerType *ResType);
5467
5468 llvm::Value *emitCountedByMemberSize(const MemberExpr *E, const Expr *Idx,
5469 llvm::Value *EmittedE,
5470 QualType CastedArrayElementTy,
5471 unsigned Type,
5472 llvm::IntegerType *ResType);
5473
5474 llvm::Value *emitCountedByPointerSize(const ImplicitCastExpr *E,
5475 const Expr *Idx, llvm::Value *EmittedE,
5476 QualType CastedArrayElementTy,
5477 unsigned Type,
5478 llvm::IntegerType *ResType);
5479
5480 void emitZeroOrPatternForAutoVarInit(QualType type, const VarDecl &D,
5481 Address Loc);
5482
5483public:
5484 enum class EvaluationOrder {
5485 ///! No language constraints on evaluation order.
5486 Default,
5487 ///! Language semantics require left-to-right evaluation.
5488 ForceLeftToRight,
5489 ///! Language semantics require right-to-left evaluation.
5490 ForceRightToLeft
5491 };
5492
5493 // Wrapper for function prototype sources. Wraps either a FunctionProtoType or
5494 // an ObjCMethodDecl.
5495 struct PrototypeWrapper {
5496 llvm::PointerUnion<const FunctionProtoType *, const ObjCMethodDecl *> P;
5497
5498 PrototypeWrapper(const FunctionProtoType *FT) : P(FT) {}
5499 PrototypeWrapper(const ObjCMethodDecl *MD) : P(MD) {}
5500 };
5501
5502 void EmitCallArgs(CallArgList &Args, PrototypeWrapper Prototype,
5503 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
5504 AbstractCallee AC = AbstractCallee(),
5505 unsigned ParamsToSkip = 0,
5506 EvaluationOrder Order = EvaluationOrder::Default);
5507
5508 /// EmitPointerWithAlignment - Given an expression with a pointer type,
5509 /// emit the value and compute our best estimate of the alignment of the
5510 /// pointee.
5511 ///
5512 /// \param BaseInfo - If non-null, this will be initialized with
5513 /// information about the source of the alignment and the may-alias
5514 /// attribute. Note that this function will conservatively fall back on
5515 /// the type when it doesn't recognize the expression and may-alias will
5516 /// be set to false.
5517 ///
5518 /// One reasonable way to use this information is when there's a language
5519 /// guarantee that the pointer must be aligned to some stricter value, and
5520 /// we're simply trying to ensure that sufficiently obvious uses of under-
5521 /// aligned objects don't get miscompiled; for example, a placement new
5522 /// into the address of a local variable. In such a case, it's quite
5523 /// reasonable to just ignore the returned alignment when it isn't from an
5524 /// explicit source.
5525 Address
5526 EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo = nullptr,
5527 TBAAAccessInfo *TBAAInfo = nullptr,
5528 KnownNonNull_t IsKnownNonNull = NotKnownNonNull);
5529
5530 /// If \p E references a parameter with pass_object_size info or a constant
5531 /// array size modifier, emit the object size divided by the size of \p EltTy.
5532 /// Otherwise return null.
5533 llvm::Value *LoadPassedObjectSize(const Expr *E, QualType EltTy);
5534
5535 void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK);
5536
5537 struct FMVResolverOption {
5538 llvm::Function *Function;
5539 llvm::SmallVector<StringRef, 8> Features;
5540 std::optional<StringRef> Architecture;
5541
5542 FMVResolverOption(llvm::Function *F, ArrayRef<StringRef> Feats,
5543 std::optional<StringRef> Arch = std::nullopt)
5544 : Function(F), Features(Feats), Architecture(Arch) {}
5545 };
5546
5547 // Emits the body of a multiversion function's resolver. Assumes that the
5548 // options are already sorted in the proper order, with the 'default' option
5549 // last (if it exists).
5550 void EmitMultiVersionResolver(llvm::Function *Resolver,
5551 ArrayRef<FMVResolverOption> Options);
5552 void EmitX86MultiVersionResolver(llvm::Function *Resolver,
5553 ArrayRef<FMVResolverOption> Options);
5554 void EmitAArch64MultiVersionResolver(llvm::Function *Resolver,
5555 ArrayRef<FMVResolverOption> Options);
5556 void EmitRISCVMultiVersionResolver(llvm::Function *Resolver,
5557 ArrayRef<FMVResolverOption> Options);
5558
5559private:
5560 QualType getVarArgType(const Expr *Arg);
5561
5562 void EmitDeclMetadata();
5563
5564 BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType,
5565 const AutoVarEmission &emission);
5566
5567 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
5568
5569 llvm::Value *GetValueForARMHint(unsigned BuiltinID);
5570 llvm::Value *EmitX86CpuIs(const CallExpr *E);
5571 llvm::Value *EmitX86CpuIs(StringRef CPUStr);
5572 llvm::Value *EmitX86CpuSupports(const CallExpr *E);
5573 llvm::Value *EmitX86CpuSupports(ArrayRef<StringRef> FeatureStrs);
5574 llvm::Value *EmitX86CpuSupports(std::array<uint32_t, 4> FeatureMask);
5575 llvm::Value *EmitX86CpuInit();
5576 llvm::Value *FormX86ResolverCondition(const FMVResolverOption &RO);
5577 llvm::Value *EmitAArch64CpuInit();
5578 llvm::Value *FormAArch64ResolverCondition(const FMVResolverOption &RO);
5579 llvm::Value *EmitAArch64CpuSupports(const CallExpr *E);
5580 llvm::Value *EmitAArch64CpuSupports(ArrayRef<StringRef> FeatureStrs);
5581};
5582
5583inline DominatingLLVMValue::saved_type
5584DominatingLLVMValue::save(CodeGenFunction &CGF, llvm::Value *value) {
5585 if (!needsSaving(value))
5586 return saved_type(value, false);
5587
5588 // Otherwise, we need an alloca.
5589 auto align = CharUnits::fromQuantity(
5590 Quantity: CGF.CGM.getDataLayout().getPrefTypeAlign(Ty: value->getType()));
5591 Address alloca =
5592 CGF.CreateTempAlloca(Ty: value->getType(), align, Name: "cond-cleanup.save");
5593 CGF.Builder.CreateStore(Val: value, Addr: alloca);
5594
5595 return saved_type(alloca.emitRawPointer(CGF), true);
5596}
5597
5598inline llvm::Value *DominatingLLVMValue::restore(CodeGenFunction &CGF,
5599 saved_type value) {
5600 // If the value says it wasn't saved, trust that it's still dominating.
5601 if (!value.getInt())
5602 return value.getPointer();
5603
5604 // Otherwise, it should be an alloca instruction, as set up in save().
5605 auto alloca = cast<llvm::AllocaInst>(Val: value.getPointer());
5606 return CGF.Builder.CreateAlignedLoad(Ty: alloca->getAllocatedType(), Ptr: alloca,
5607 Align: alloca->getAlign());
5608}
5609
5610} // end namespace CodeGen
5611
5612// Map the LangOption for floating point exception behavior into
5613// the corresponding enum in the IR.
5614llvm::fp::ExceptionBehavior
5615ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind);
5616} // end namespace clang
5617
5618#endif
5619