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