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