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