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