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 private: 1755 /// CXXThisDecl - When generating code for a C++ member function, 1756 /// this will hold the implicit 'this' declaration. 1757 ImplicitParamDecl *CXXABIThisDecl = nullptr; 1758 llvm::Value *CXXABIThisValue = nullptr; 1759 llvm::Value *CXXThisValue = nullptr; 1760 CharUnits CXXABIThisAlignment; 1761 CharUnits CXXThisAlignment; 1762 1763 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within 1764 /// this expression. 1765 Address CXXDefaultInitExprThis = Address::invalid(); 1766 1767 /// The current array initialization index when evaluating an 1768 /// ArrayInitIndexExpr within an ArrayInitLoopExpr. 1769 llvm::Value *ArrayInitIndex = nullptr; 1770 1771 /// The values of function arguments to use when evaluating 1772 /// CXXInheritedCtorInitExprs within this context. 1773 CallArgList CXXInheritedCtorInitExprArgs; 1774 1775 /// CXXStructorImplicitParamDecl - When generating code for a constructor or 1776 /// destructor, this will hold the implicit argument (e.g. VTT). 1777 ImplicitParamDecl *CXXStructorImplicitParamDecl = nullptr; 1778 llvm::Value *CXXStructorImplicitParamValue = nullptr; 1779 1780 /// OutermostConditional - Points to the outermost active 1781 /// conditional control. This is used so that we know if a 1782 /// temporary should be destroyed conditionally. 1783 ConditionalEvaluation *OutermostConditional = nullptr; 1784 1785 /// The current lexical scope. 1786 LexicalScope *CurLexicalScope = nullptr; 1787 1788 /// The current source location that should be used for exception 1789 /// handling code. 1790 SourceLocation CurEHLocation; 1791 1792 /// BlockByrefInfos - For each __block variable, contains 1793 /// information about the layout of the variable. 1794 llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos; 1795 1796 /// Used by -fsanitize=nullability-return to determine whether the return 1797 /// value can be checked. 1798 llvm::Value *RetValNullabilityPrecondition = nullptr; 1799 1800 /// Check if -fsanitize=nullability-return instrumentation is required for 1801 /// this function. 1802 bool requiresReturnValueNullabilityCheck() const { 1803 return RetValNullabilityPrecondition; 1804 } 1805 1806 /// Used to store precise source locations for return statements by the 1807 /// runtime return value checks. 1808 Address ReturnLocation = Address::invalid(); 1809 1810 /// Check if the return value of this function requires sanitization. 1811 bool requiresReturnValueCheck() const; 1812 1813 llvm::BasicBlock *TerminateLandingPad = nullptr; 1814 llvm::BasicBlock *TerminateHandler = nullptr; 1815 llvm::BasicBlock *TrapBB = nullptr; 1816 1817 /// Terminate funclets keyed by parent funclet pad. 1818 llvm::MapVector<llvm::Value *, llvm::BasicBlock *> TerminateFunclets; 1819 1820 /// Largest vector width used in ths function. Will be used to create a 1821 /// function attribute. 1822 unsigned LargestVectorWidth = 0; 1823 1824 /// True if we need emit the life-time markers. 1825 const bool ShouldEmitLifetimeMarkers; 1826 1827 /// Add OpenCL kernel arg metadata and the kernel attribute metadata to 1828 /// the function metadata. 1829 void EmitOpenCLKernelMetadata(const FunctionDecl *FD, 1830 llvm::Function *Fn); 1831 1832 public: 1833 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false); 1834 ~CodeGenFunction(); 1835 1836 CodeGenTypes &getTypes() const { return CGM.getTypes(); } 1837 ASTContext &getContext() const { return CGM.getContext(); } 1838 CGDebugInfo *getDebugInfo() { 1839 if (DisableDebugInfo) 1840 return nullptr; 1841 return DebugInfo; 1842 } 1843 void disableDebugInfo() { DisableDebugInfo = true; } 1844 void enableDebugInfo() { DisableDebugInfo = false; } 1845 1846 bool shouldUseFusedARCCalls() { 1847 return CGM.getCodeGenOpts().OptimizationLevel == 0; 1848 } 1849 1850 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); } 1851 1852 /// Returns a pointer to the function's exception object and selector slot, 1853 /// which is assigned in every landing pad. 1854 Address getExceptionSlot(); 1855 Address getEHSelectorSlot(); 1856 1857 /// Returns the contents of the function's exception object and selector 1858 /// slots. 1859 llvm::Value *getExceptionFromSlot(); 1860 llvm::Value *getSelectorFromSlot(); 1861 1862 Address getNormalCleanupDestSlot(); 1863 1864 llvm::BasicBlock *getUnreachableBlock() { 1865 if (!UnreachableBlock) { 1866 UnreachableBlock = createBasicBlock("unreachable"); 1867 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock); 1868 } 1869 return UnreachableBlock; 1870 } 1871 1872 llvm::BasicBlock *getInvokeDest() { 1873 if (!EHStack.requiresLandingPad()) return nullptr; 1874 return getInvokeDestImpl(); 1875 } 1876 1877 bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; } 1878 1879 const TargetInfo &getTarget() const { return Target; } 1880 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); } 1881 const TargetCodeGenInfo &getTargetHooks() const { 1882 return CGM.getTargetCodeGenInfo(); 1883 } 1884 1885 //===--------------------------------------------------------------------===// 1886 // Cleanups 1887 //===--------------------------------------------------------------------===// 1888 1889 typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty); 1890 1891 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 1892 Address arrayEndPointer, 1893 QualType elementType, 1894 CharUnits elementAlignment, 1895 Destroyer *destroyer); 1896 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 1897 llvm::Value *arrayEnd, 1898 QualType elementType, 1899 CharUnits elementAlignment, 1900 Destroyer *destroyer); 1901 1902 void pushDestroy(QualType::DestructionKind dtorKind, 1903 Address addr, QualType type); 1904 void pushEHDestroy(QualType::DestructionKind dtorKind, 1905 Address addr, QualType type); 1906 void pushDestroy(CleanupKind kind, Address addr, QualType type, 1907 Destroyer *destroyer, bool useEHCleanupForArray); 1908 void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, 1909 QualType type, Destroyer *destroyer, 1910 bool useEHCleanupForArray); 1911 void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete, 1912 llvm::Value *CompletePtr, 1913 QualType ElementType); 1914 void pushStackRestore(CleanupKind kind, Address SPMem); 1915 void emitDestroy(Address addr, QualType type, Destroyer *destroyer, 1916 bool useEHCleanupForArray); 1917 llvm::Function *generateDestroyHelper(Address addr, QualType type, 1918 Destroyer *destroyer, 1919 bool useEHCleanupForArray, 1920 const VarDecl *VD); 1921 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end, 1922 QualType elementType, CharUnits elementAlign, 1923 Destroyer *destroyer, 1924 bool checkZeroLength, bool useEHCleanup); 1925 1926 Destroyer *getDestroyer(QualType::DestructionKind destructionKind); 1927 1928 /// Determines whether an EH cleanup is required to destroy a type 1929 /// with the given destruction kind. 1930 bool needsEHCleanup(QualType::DestructionKind kind) { 1931 switch (kind) { 1932 case QualType::DK_none: 1933 return false; 1934 case QualType::DK_cxx_destructor: 1935 case QualType::DK_objc_weak_lifetime: 1936 case QualType::DK_nontrivial_c_struct: 1937 return getLangOpts().Exceptions; 1938 case QualType::DK_objc_strong_lifetime: 1939 return getLangOpts().Exceptions && 1940 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions; 1941 } 1942 llvm_unreachable("bad destruction kind"); 1943 } 1944 1945 CleanupKind getCleanupKind(QualType::DestructionKind kind) { 1946 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup); 1947 } 1948 1949 //===--------------------------------------------------------------------===// 1950 // Objective-C 1951 //===--------------------------------------------------------------------===// 1952 1953 void GenerateObjCMethod(const ObjCMethodDecl *OMD); 1954 1955 void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD); 1956 1957 /// GenerateObjCGetter - Synthesize an Objective-C property getter function. 1958 void GenerateObjCGetter(ObjCImplementationDecl *IMP, 1959 const ObjCPropertyImplDecl *PID); 1960 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl, 1961 const ObjCPropertyImplDecl *propImpl, 1962 const ObjCMethodDecl *GetterMothodDecl, 1963 llvm::Constant *AtomicHelperFn); 1964 1965 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 1966 ObjCMethodDecl *MD, bool ctor); 1967 1968 /// GenerateObjCSetter - Synthesize an Objective-C property setter function 1969 /// for the given property. 1970 void GenerateObjCSetter(ObjCImplementationDecl *IMP, 1971 const ObjCPropertyImplDecl *PID); 1972 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl, 1973 const ObjCPropertyImplDecl *propImpl, 1974 llvm::Constant *AtomicHelperFn); 1975 1976 //===--------------------------------------------------------------------===// 1977 // Block Bits 1978 //===--------------------------------------------------------------------===// 1979 1980 /// Emit block literal. 1981 /// \return an LLVM value which is a pointer to a struct which contains 1982 /// information about the block, including the block invoke function, the 1983 /// captured variables, etc. 1984 llvm::Value *EmitBlockLiteral(const BlockExpr *); 1985 1986 llvm::Function *GenerateBlockFunction(GlobalDecl GD, 1987 const CGBlockInfo &Info, 1988 const DeclMapTy &ldm, 1989 bool IsLambdaConversionToBlock, 1990 bool BuildGlobalBlock); 1991 1992 /// Check if \p T is a C++ class that has a destructor that can throw. 1993 static bool cxxDestructorCanThrow(QualType T); 1994 1995 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo); 1996 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo); 1997 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction( 1998 const ObjCPropertyImplDecl *PID); 1999 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction( 2000 const ObjCPropertyImplDecl *PID); 2001 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty); 2002 2003 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags, 2004 bool CanThrow); 2005 2006 class AutoVarEmission; 2007 2008 void emitByrefStructureInit(const AutoVarEmission &emission); 2009 2010 /// Enter a cleanup to destroy a __block variable. Note that this 2011 /// cleanup should be a no-op if the variable hasn't left the stack 2012 /// yet; if a cleanup is required for the variable itself, that needs 2013 /// to be done externally. 2014 /// 2015 /// \param Kind Cleanup kind. 2016 /// 2017 /// \param Addr When \p LoadBlockVarAddr is false, the address of the __block 2018 /// structure that will be passed to _Block_object_dispose. When 2019 /// \p LoadBlockVarAddr is true, the address of the field of the block 2020 /// structure that holds the address of the __block structure. 2021 /// 2022 /// \param Flags The flag that will be passed to _Block_object_dispose. 2023 /// 2024 /// \param LoadBlockVarAddr Indicates whether we need to emit a load from 2025 /// \p Addr to get the address of the __block structure. 2026 void enterByrefCleanup(CleanupKind Kind, Address Addr, BlockFieldFlags Flags, 2027 bool LoadBlockVarAddr, bool CanThrow); 2028 2029 void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum, 2030 llvm::Value *ptr); 2031 2032 Address LoadBlockStruct(); 2033 Address GetAddrOfBlockDecl(const VarDecl *var); 2034 2035 /// BuildBlockByrefAddress - Computes the location of the 2036 /// data in a variable which is declared as __block. 2037 Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V, 2038 bool followForward = true); 2039 Address emitBlockByrefAddress(Address baseAddr, 2040 const BlockByrefInfo &info, 2041 bool followForward, 2042 const llvm::Twine &name); 2043 2044 const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var); 2045 2046 QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args); 2047 2048 void GenerateCode(GlobalDecl GD, llvm::Function *Fn, 2049 const CGFunctionInfo &FnInfo); 2050 2051 /// Annotate the function with an attribute that disables TSan checking at 2052 /// runtime. 2053 void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn); 2054 2055 /// Emit code for the start of a function. 2056 /// \param Loc The location to be associated with the function. 2057 /// \param StartLoc The location of the function body. 2058 void StartFunction(GlobalDecl GD, 2059 QualType RetTy, 2060 llvm::Function *Fn, 2061 const CGFunctionInfo &FnInfo, 2062 const FunctionArgList &Args, 2063 SourceLocation Loc = SourceLocation(), 2064 SourceLocation StartLoc = SourceLocation()); 2065 2066 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor); 2067 2068 void EmitConstructorBody(FunctionArgList &Args); 2069 void EmitDestructorBody(FunctionArgList &Args); 2070 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args); 2071 void EmitFunctionBody(const Stmt *Body); 2072 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S); 2073 2074 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator, 2075 CallArgList &CallArgs); 2076 void EmitLambdaBlockInvokeBody(); 2077 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD); 2078 void EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD); 2079 void EmitLambdaVLACapture(const VariableArrayType *VAT, LValue LV) { 2080 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV); 2081 } 2082 void EmitAsanPrologueOrEpilogue(bool Prologue); 2083 2084 /// Emit the unified return block, trying to avoid its emission when 2085 /// possible. 2086 /// \return The debug location of the user written return statement if the 2087 /// return block is is avoided. 2088 llvm::DebugLoc EmitReturnBlock(); 2089 2090 /// FinishFunction - Complete IR generation of the current function. It is 2091 /// legal to call this function even if there is no current insertion point. 2092 void FinishFunction(SourceLocation EndLoc=SourceLocation()); 2093 2094 void StartThunk(llvm::Function *Fn, GlobalDecl GD, 2095 const CGFunctionInfo &FnInfo, bool IsUnprototyped); 2096 2097 void EmitCallAndReturnForThunk(llvm::FunctionCallee Callee, 2098 const ThunkInfo *Thunk, bool IsUnprototyped); 2099 2100 void FinishThunk(); 2101 2102 /// Emit a musttail call for a thunk with a potentially adjusted this pointer. 2103 void EmitMustTailThunk(GlobalDecl GD, llvm::Value *AdjustedThisPtr, 2104 llvm::FunctionCallee Callee); 2105 2106 /// Generate a thunk for the given method. 2107 void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 2108 GlobalDecl GD, const ThunkInfo &Thunk, 2109 bool IsUnprototyped); 2110 2111 llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn, 2112 const CGFunctionInfo &FnInfo, 2113 GlobalDecl GD, const ThunkInfo &Thunk); 2114 2115 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type, 2116 FunctionArgList &Args); 2117 2118 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init); 2119 2120 /// Struct with all information about dynamic [sub]class needed to set vptr. 2121 struct VPtr { 2122 BaseSubobject Base; 2123 const CXXRecordDecl *NearestVBase; 2124 CharUnits OffsetFromNearestVBase; 2125 const CXXRecordDecl *VTableClass; 2126 }; 2127 2128 /// Initialize the vtable pointer of the given subobject. 2129 void InitializeVTablePointer(const VPtr &vptr); 2130 2131 typedef llvm::SmallVector<VPtr, 4> VPtrsVector; 2132 2133 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; 2134 VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass); 2135 2136 void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase, 2137 CharUnits OffsetFromNearestVBase, 2138 bool BaseIsNonVirtualPrimaryBase, 2139 const CXXRecordDecl *VTableClass, 2140 VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs); 2141 2142 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl); 2143 2144 /// GetVTablePtr - Return the Value of the vtable pointer member pointed 2145 /// to by This. 2146 llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy, 2147 const CXXRecordDecl *VTableClass); 2148 2149 enum CFITypeCheckKind { 2150 CFITCK_VCall, 2151 CFITCK_NVCall, 2152 CFITCK_DerivedCast, 2153 CFITCK_UnrelatedCast, 2154 CFITCK_ICall, 2155 CFITCK_NVMFCall, 2156 CFITCK_VMFCall, 2157 }; 2158 2159 /// Derived is the presumed address of an object of type T after a 2160 /// cast. If T is a polymorphic class type, emit a check that the virtual 2161 /// table for Derived belongs to a class derived from T. 2162 void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived, 2163 bool MayBeNull, CFITypeCheckKind TCK, 2164 SourceLocation Loc); 2165 2166 /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable. 2167 /// If vptr CFI is enabled, emit a check that VTable is valid. 2168 void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable, 2169 CFITypeCheckKind TCK, SourceLocation Loc); 2170 2171 /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for 2172 /// RD using llvm.type.test. 2173 void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable, 2174 CFITypeCheckKind TCK, SourceLocation Loc); 2175 2176 /// If whole-program virtual table optimization is enabled, emit an assumption 2177 /// that VTable is a member of RD's type identifier. Or, if vptr CFI is 2178 /// enabled, emit a check that VTable is a member of RD's type identifier. 2179 void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD, 2180 llvm::Value *VTable, SourceLocation Loc); 2181 2182 /// Returns whether we should perform a type checked load when loading a 2183 /// virtual function for virtual calls to members of RD. This is generally 2184 /// true when both vcall CFI and whole-program-vtables are enabled. 2185 bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD); 2186 2187 /// Emit a type checked load from the given vtable. 2188 llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable, 2189 uint64_t VTableByteOffset); 2190 2191 /// EnterDtorCleanups - Enter the cleanups necessary to complete the 2192 /// given phase of destruction for a destructor. The end result 2193 /// should call destructors on members and base classes in reverse 2194 /// order of their construction. 2195 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type); 2196 2197 /// ShouldInstrumentFunction - Return true if the current function should be 2198 /// instrumented with __cyg_profile_func_* calls 2199 bool ShouldInstrumentFunction(); 2200 2201 /// ShouldXRayInstrument - Return true if the current function should be 2202 /// instrumented with XRay nop sleds. 2203 bool ShouldXRayInstrumentFunction() const; 2204 2205 /// AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit 2206 /// XRay custom event handling calls. 2207 bool AlwaysEmitXRayCustomEvents() const; 2208 2209 /// AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit 2210 /// XRay typed event handling calls. 2211 bool AlwaysEmitXRayTypedEvents() const; 2212 2213 /// Encode an address into a form suitable for use in a function prologue. 2214 llvm::Constant *EncodeAddrForUseInPrologue(llvm::Function *F, 2215 llvm::Constant *Addr); 2216 2217 /// Decode an address used in a function prologue, encoded by \c 2218 /// EncodeAddrForUseInPrologue. 2219 llvm::Value *DecodeAddrUsedInPrologue(llvm::Value *F, 2220 llvm::Value *EncodedAddr); 2221 2222 /// EmitFunctionProlog - Emit the target specific LLVM code to load the 2223 /// arguments for the given function. This is also responsible for naming the 2224 /// LLVM function arguments. 2225 void EmitFunctionProlog(const CGFunctionInfo &FI, 2226 llvm::Function *Fn, 2227 const FunctionArgList &Args); 2228 2229 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the 2230 /// given temporary. 2231 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, 2232 SourceLocation EndLoc); 2233 2234 /// Emit a test that checks if the return value \p RV is nonnull. 2235 void EmitReturnValueCheck(llvm::Value *RV); 2236 2237 /// EmitStartEHSpec - Emit the start of the exception spec. 2238 void EmitStartEHSpec(const Decl *D); 2239 2240 /// EmitEndEHSpec - Emit the end of the exception spec. 2241 void EmitEndEHSpec(const Decl *D); 2242 2243 /// getTerminateLandingPad - Return a landing pad that just calls terminate. 2244 llvm::BasicBlock *getTerminateLandingPad(); 2245 2246 /// getTerminateLandingPad - Return a cleanup funclet that just calls 2247 /// terminate. 2248 llvm::BasicBlock *getTerminateFunclet(); 2249 2250 /// getTerminateHandler - Return a handler (not a landing pad, just 2251 /// a catch handler) that just calls terminate. This is used when 2252 /// a terminate scope encloses a try. 2253 llvm::BasicBlock *getTerminateHandler(); 2254 2255 llvm::Type *ConvertTypeForMem(QualType T); 2256 llvm::Type *ConvertType(QualType T); 2257 llvm::Type *ConvertType(const TypeDecl *T) { 2258 return ConvertType(getContext().getTypeDeclType(T)); 2259 } 2260 2261 /// LoadObjCSelf - Load the value of self. This function is only valid while 2262 /// generating code for an Objective-C method. 2263 llvm::Value *LoadObjCSelf(); 2264 2265 /// TypeOfSelfObject - Return type of object that this self represents. 2266 QualType TypeOfSelfObject(); 2267 2268 /// getEvaluationKind - Return the TypeEvaluationKind of QualType \c T. 2269 static TypeEvaluationKind getEvaluationKind(QualType T); 2270 2271 static bool hasScalarEvaluationKind(QualType T) { 2272 return getEvaluationKind(T) == TEK_Scalar; 2273 } 2274 2275 static bool hasAggregateEvaluationKind(QualType T) { 2276 return getEvaluationKind(T) == TEK_Aggregate; 2277 } 2278 2279 /// createBasicBlock - Create an LLVM basic block. 2280 llvm::BasicBlock *createBasicBlock(const Twine &name = "", 2281 llvm::Function *parent = nullptr, 2282 llvm::BasicBlock *before = nullptr) { 2283 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before); 2284 } 2285 2286 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified 2287 /// label maps to. 2288 JumpDest getJumpDestForLabel(const LabelDecl *S); 2289 2290 /// SimplifyForwardingBlocks - If the given basic block is only a branch to 2291 /// another basic block, simplify it. This assumes that no other code could 2292 /// potentially reference the basic block. 2293 void SimplifyForwardingBlocks(llvm::BasicBlock *BB); 2294 2295 /// EmitBlock - Emit the given block \arg BB and set it as the insert point, 2296 /// adding a fall-through branch from the current insert block if 2297 /// necessary. It is legal to call this function even if there is no current 2298 /// insertion point. 2299 /// 2300 /// IsFinished - If true, indicates that the caller has finished emitting 2301 /// branches to the given block and does not expect to emit code into it. This 2302 /// means the block can be ignored if it is unreachable. 2303 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); 2304 2305 /// EmitBlockAfterUses - Emit the given block somewhere hopefully 2306 /// near its uses, and leave the insertion point in it. 2307 void EmitBlockAfterUses(llvm::BasicBlock *BB); 2308 2309 /// EmitBranch - Emit a branch to the specified basic block from the current 2310 /// insert block, taking care to avoid creation of branches from dummy 2311 /// blocks. It is legal to call this function even if there is no current 2312 /// insertion point. 2313 /// 2314 /// This function clears the current insertion point. The caller should follow 2315 /// calls to this function with calls to Emit*Block prior to generation new 2316 /// code. 2317 void EmitBranch(llvm::BasicBlock *Block); 2318 2319 /// HaveInsertPoint - True if an insertion point is defined. If not, this 2320 /// indicates that the current code being emitted is unreachable. 2321 bool HaveInsertPoint() const { 2322 return Builder.GetInsertBlock() != nullptr; 2323 } 2324 2325 /// EnsureInsertPoint - Ensure that an insertion point is defined so that 2326 /// emitted IR has a place to go. Note that by definition, if this function 2327 /// creates a block then that block is unreachable; callers may do better to 2328 /// detect when no insertion point is defined and simply skip IR generation. 2329 void EnsureInsertPoint() { 2330 if (!HaveInsertPoint()) 2331 EmitBlock(createBasicBlock()); 2332 } 2333 2334 /// ErrorUnsupported - Print out an error that codegen doesn't support the 2335 /// specified stmt yet. 2336 void ErrorUnsupported(const Stmt *S, const char *Type); 2337 2338 //===--------------------------------------------------------------------===// 2339 // Helpers 2340 //===--------------------------------------------------------------------===// 2341 2342 LValue MakeAddrLValue(Address Addr, QualType T, 2343 AlignmentSource Source = AlignmentSource::Type) { 2344 return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source), 2345 CGM.getTBAAAccessInfo(T)); 2346 } 2347 2348 LValue MakeAddrLValue(Address Addr, QualType T, LValueBaseInfo BaseInfo, 2349 TBAAAccessInfo TBAAInfo) { 2350 return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, TBAAInfo); 2351 } 2352 2353 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment, 2354 AlignmentSource Source = AlignmentSource::Type) { 2355 return LValue::MakeAddr(Address(V, Alignment), T, getContext(), 2356 LValueBaseInfo(Source), CGM.getTBAAAccessInfo(T)); 2357 } 2358 2359 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment, 2360 LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo) { 2361 return LValue::MakeAddr(Address(V, Alignment), T, getContext(), 2362 BaseInfo, TBAAInfo); 2363 } 2364 2365 LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T); 2366 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T); 2367 2368 Address EmitLoadOfReference(LValue RefLVal, 2369 LValueBaseInfo *PointeeBaseInfo = nullptr, 2370 TBAAAccessInfo *PointeeTBAAInfo = nullptr); 2371 LValue EmitLoadOfReferenceLValue(LValue RefLVal); 2372 LValue EmitLoadOfReferenceLValue(Address RefAddr, QualType RefTy, 2373 AlignmentSource Source = 2374 AlignmentSource::Type) { 2375 LValue RefLVal = MakeAddrLValue(RefAddr, RefTy, LValueBaseInfo(Source), 2376 CGM.getTBAAAccessInfo(RefTy)); 2377 return EmitLoadOfReferenceLValue(RefLVal); 2378 } 2379 2380 Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy, 2381 LValueBaseInfo *BaseInfo = nullptr, 2382 TBAAAccessInfo *TBAAInfo = nullptr); 2383 LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy); 2384 2385 /// CreateTempAlloca - This creates an alloca and inserts it into the entry 2386 /// block if \p ArraySize is nullptr, otherwise inserts it at the current 2387 /// insertion point of the builder. The caller is responsible for setting an 2388 /// appropriate alignment on 2389 /// the alloca. 2390 /// 2391 /// \p ArraySize is the number of array elements to be allocated if it 2392 /// is not nullptr. 2393 /// 2394 /// LangAS::Default is the address space of pointers to local variables and 2395 /// temporaries, as exposed in the source language. In certain 2396 /// configurations, this is not the same as the alloca address space, and a 2397 /// cast is needed to lift the pointer from the alloca AS into 2398 /// LangAS::Default. This can happen when the target uses a restricted 2399 /// address space for the stack but the source language requires 2400 /// LangAS::Default to be a generic address space. The latter condition is 2401 /// common for most programming languages; OpenCL is an exception in that 2402 /// LangAS::Default is the private address space, which naturally maps 2403 /// to the stack. 2404 /// 2405 /// Because the address of a temporary is often exposed to the program in 2406 /// various ways, this function will perform the cast. The original alloca 2407 /// instruction is returned through \p Alloca if it is not nullptr. 2408 /// 2409 /// The cast is not performaed in CreateTempAllocaWithoutCast. This is 2410 /// more efficient if the caller knows that the address will not be exposed. 2411 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, const Twine &Name = "tmp", 2412 llvm::Value *ArraySize = nullptr); 2413 Address CreateTempAlloca(llvm::Type *Ty, CharUnits align, 2414 const Twine &Name = "tmp", 2415 llvm::Value *ArraySize = nullptr, 2416 Address *Alloca = nullptr); 2417 Address CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align, 2418 const Twine &Name = "tmp", 2419 llvm::Value *ArraySize = nullptr); 2420 2421 /// CreateDefaultAlignedTempAlloca - This creates an alloca with the 2422 /// default ABI alignment of the given LLVM type. 2423 /// 2424 /// IMPORTANT NOTE: This is *not* generally the right alignment for 2425 /// any given AST type that happens to have been lowered to the 2426 /// given IR type. This should only ever be used for function-local, 2427 /// IR-driven manipulations like saving and restoring a value. Do 2428 /// not hand this address off to arbitrary IRGen routines, and especially 2429 /// do not pass it as an argument to a function that might expect a 2430 /// properly ABI-aligned value. 2431 Address CreateDefaultAlignTempAlloca(llvm::Type *Ty, 2432 const Twine &Name = "tmp"); 2433 2434 /// InitTempAlloca - Provide an initial value for the given alloca which 2435 /// will be observable at all locations in the function. 2436 /// 2437 /// The address should be something that was returned from one of 2438 /// the CreateTempAlloca or CreateMemTemp routines, and the 2439 /// initializer must be valid in the entry block (i.e. it must 2440 /// either be a constant or an argument value). 2441 void InitTempAlloca(Address Alloca, llvm::Value *Value); 2442 2443 /// CreateIRTemp - Create a temporary IR object of the given type, with 2444 /// appropriate alignment. This routine should only be used when an temporary 2445 /// value needs to be stored into an alloca (for example, to avoid explicit 2446 /// PHI construction), but the type is the IR type, not the type appropriate 2447 /// for storing in memory. 2448 /// 2449 /// That is, this is exactly equivalent to CreateMemTemp, but calling 2450 /// ConvertType instead of ConvertTypeForMem. 2451 Address CreateIRTemp(QualType T, const Twine &Name = "tmp"); 2452 2453 /// CreateMemTemp - Create a temporary memory object of the given type, with 2454 /// appropriate alignmen and cast it to the default address space. Returns 2455 /// the original alloca instruction by \p Alloca if it is not nullptr. 2456 Address CreateMemTemp(QualType T, const Twine &Name = "tmp", 2457 Address *Alloca = nullptr); 2458 Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp", 2459 Address *Alloca = nullptr); 2460 2461 /// CreateMemTemp - Create a temporary memory object of the given type, with 2462 /// appropriate alignmen without casting it to the default address space. 2463 Address CreateMemTempWithoutCast(QualType T, const Twine &Name = "tmp"); 2464 Address CreateMemTempWithoutCast(QualType T, CharUnits Align, 2465 const Twine &Name = "tmp"); 2466 2467 /// CreateAggTemp - Create a temporary memory object for the given 2468 /// aggregate type. 2469 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp", 2470 Address *Alloca = nullptr) { 2471 return AggValueSlot::forAddr(CreateMemTemp(T, Name, Alloca), 2472 T.getQualifiers(), 2473 AggValueSlot::IsNotDestructed, 2474 AggValueSlot::DoesNotNeedGCBarriers, 2475 AggValueSlot::IsNotAliased, 2476 AggValueSlot::DoesNotOverlap); 2477 } 2478 2479 /// Emit a cast to void* in the appropriate address space. 2480 llvm::Value *EmitCastToVoidPtr(llvm::Value *value); 2481 2482 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 2483 /// expression and compare the result against zero, returning an Int1Ty value. 2484 llvm::Value *EvaluateExprAsBool(const Expr *E); 2485 2486 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result. 2487 void EmitIgnoredExpr(const Expr *E); 2488 2489 /// EmitAnyExpr - Emit code to compute the specified expression which can have 2490 /// any type. The result is returned as an RValue struct. If this is an 2491 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 2492 /// the result should be returned. 2493 /// 2494 /// \param ignoreResult True if the resulting value isn't used. 2495 RValue EmitAnyExpr(const Expr *E, 2496 AggValueSlot aggSlot = AggValueSlot::ignored(), 2497 bool ignoreResult = false); 2498 2499 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address 2500 // or the value of the expression, depending on how va_list is defined. 2501 Address EmitVAListRef(const Expr *E); 2502 2503 /// Emit a "reference" to a __builtin_ms_va_list; this is 2504 /// always the value of the expression, because a __builtin_ms_va_list is a 2505 /// pointer to a char. 2506 Address EmitMSVAListRef(const Expr *E); 2507 2508 /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will 2509 /// always be accessible even if no aggregate location is provided. 2510 RValue EmitAnyExprToTemp(const Expr *E); 2511 2512 /// EmitAnyExprToMem - Emits the code necessary to evaluate an 2513 /// arbitrary expression into the given memory location. 2514 void EmitAnyExprToMem(const Expr *E, Address Location, 2515 Qualifiers Quals, bool IsInitializer); 2516 2517 void EmitAnyExprToExn(const Expr *E, Address Addr); 2518 2519 /// EmitExprAsInit - Emits the code necessary to initialize a 2520 /// location in memory with the given initializer. 2521 void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue, 2522 bool capturedByInit); 2523 2524 /// hasVolatileMember - returns true if aggregate type has a volatile 2525 /// member. 2526 bool hasVolatileMember(QualType T) { 2527 if (const RecordType *RT = T->getAs<RecordType>()) { 2528 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 2529 return RD->hasVolatileMember(); 2530 } 2531 return false; 2532 } 2533 2534 /// Determine whether a return value slot may overlap some other object. 2535 AggValueSlot::Overlap_t getOverlapForReturnValue() { 2536 // FIXME: Assuming no overlap here breaks guaranteed copy elision for base 2537 // class subobjects. These cases may need to be revisited depending on the 2538 // resolution of the relevant core issue. 2539 return AggValueSlot::DoesNotOverlap; 2540 } 2541 2542 /// Determine whether a field initialization may overlap some other object. 2543 AggValueSlot::Overlap_t getOverlapForFieldInit(const FieldDecl *FD); 2544 2545 /// Determine whether a base class initialization may overlap some other 2546 /// object. 2547 AggValueSlot::Overlap_t getOverlapForBaseInit(const CXXRecordDecl *RD, 2548 const CXXRecordDecl *BaseRD, 2549 bool IsVirtual); 2550 2551 /// Emit an aggregate assignment. 2552 void EmitAggregateAssign(LValue Dest, LValue Src, QualType EltTy) { 2553 bool IsVolatile = hasVolatileMember(EltTy); 2554 EmitAggregateCopy(Dest, Src, EltTy, AggValueSlot::MayOverlap, IsVolatile); 2555 } 2556 2557 void EmitAggregateCopyCtor(LValue Dest, LValue Src, 2558 AggValueSlot::Overlap_t MayOverlap) { 2559 EmitAggregateCopy(Dest, Src, Src.getType(), MayOverlap); 2560 } 2561 2562 /// EmitAggregateCopy - Emit an aggregate copy. 2563 /// 2564 /// \param isVolatile \c true iff either the source or the destination is 2565 /// volatile. 2566 /// \param MayOverlap Whether the tail padding of the destination might be 2567 /// occupied by some other object. More efficient code can often be 2568 /// generated if not. 2569 void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy, 2570 AggValueSlot::Overlap_t MayOverlap, 2571 bool isVolatile = false); 2572 2573 /// GetAddrOfLocalVar - Return the address of a local variable. 2574 Address GetAddrOfLocalVar(const VarDecl *VD) { 2575 auto it = LocalDeclMap.find(VD); 2576 assert(it != LocalDeclMap.end() && 2577 "Invalid argument to GetAddrOfLocalVar(), no decl!"); 2578 return it->second; 2579 } 2580 2581 /// Given an opaque value expression, return its LValue mapping if it exists, 2582 /// otherwise create one. 2583 LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e); 2584 2585 /// Given an opaque value expression, return its RValue mapping if it exists, 2586 /// otherwise create one. 2587 RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e); 2588 2589 /// Get the index of the current ArrayInitLoopExpr, if any. 2590 llvm::Value *getArrayInitIndex() { return ArrayInitIndex; } 2591 2592 /// getAccessedFieldNo - Given an encoded value and a result number, return 2593 /// the input field number being accessed. 2594 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); 2595 2596 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L); 2597 llvm::BasicBlock *GetIndirectGotoBlock(); 2598 2599 /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts. 2600 static bool IsWrappedCXXThis(const Expr *E); 2601 2602 /// EmitNullInitialization - Generate code to set a value of the given type to 2603 /// null, If the type contains data member pointers, they will be initialized 2604 /// to -1 in accordance with the Itanium C++ ABI. 2605 void EmitNullInitialization(Address DestPtr, QualType Ty); 2606 2607 /// Emits a call to an LLVM variable-argument intrinsic, either 2608 /// \c llvm.va_start or \c llvm.va_end. 2609 /// \param ArgValue A reference to the \c va_list as emitted by either 2610 /// \c EmitVAListRef or \c EmitMSVAListRef. 2611 /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise, 2612 /// calls \c llvm.va_end. 2613 llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart); 2614 2615 /// Generate code to get an argument from the passed in pointer 2616 /// and update it accordingly. 2617 /// \param VE The \c VAArgExpr for which to generate code. 2618 /// \param VAListAddr Receives a reference to the \c va_list as emitted by 2619 /// either \c EmitVAListRef or \c EmitMSVAListRef. 2620 /// \returns A pointer to the argument. 2621 // FIXME: We should be able to get rid of this method and use the va_arg 2622 // instruction in LLVM instead once it works well enough. 2623 Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr); 2624 2625 /// emitArrayLength - Compute the length of an array, even if it's a 2626 /// VLA, and drill down to the base element type. 2627 llvm::Value *emitArrayLength(const ArrayType *arrayType, 2628 QualType &baseType, 2629 Address &addr); 2630 2631 /// EmitVLASize - Capture all the sizes for the VLA expressions in 2632 /// the given variably-modified type and store them in the VLASizeMap. 2633 /// 2634 /// This function can be called with a null (unreachable) insert point. 2635 void EmitVariablyModifiedType(QualType Ty); 2636 2637 struct VlaSizePair { 2638 llvm::Value *NumElts; 2639 QualType Type; 2640 2641 VlaSizePair(llvm::Value *NE, QualType T) : NumElts(NE), Type(T) {} 2642 }; 2643 2644 /// Return the number of elements for a single dimension 2645 /// for the given array type. 2646 VlaSizePair getVLAElements1D(const VariableArrayType *vla); 2647 VlaSizePair getVLAElements1D(QualType vla); 2648 2649 /// Returns an LLVM value that corresponds to the size, 2650 /// in non-variably-sized elements, of a variable length array type, 2651 /// plus that largest non-variably-sized element type. Assumes that 2652 /// the type has already been emitted with EmitVariablyModifiedType. 2653 VlaSizePair getVLASize(const VariableArrayType *vla); 2654 VlaSizePair getVLASize(QualType vla); 2655 2656 /// LoadCXXThis - Load the value of 'this'. This function is only valid while 2657 /// generating code for an C++ member function. 2658 llvm::Value *LoadCXXThis() { 2659 assert(CXXThisValue && "no 'this' value for this function"); 2660 return CXXThisValue; 2661 } 2662 Address LoadCXXThisAddress(); 2663 2664 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have 2665 /// virtual bases. 2666 // FIXME: Every place that calls LoadCXXVTT is something 2667 // that needs to be abstracted properly. 2668 llvm::Value *LoadCXXVTT() { 2669 assert(CXXStructorImplicitParamValue && "no VTT value for this function"); 2670 return CXXStructorImplicitParamValue; 2671 } 2672 2673 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a 2674 /// complete class to the given direct base. 2675 Address 2676 GetAddressOfDirectBaseInCompleteClass(Address Value, 2677 const CXXRecordDecl *Derived, 2678 const CXXRecordDecl *Base, 2679 bool BaseIsVirtual); 2680 2681 static bool ShouldNullCheckClassCastValue(const CastExpr *Cast); 2682 2683 /// GetAddressOfBaseClass - This function will add the necessary delta to the 2684 /// load of 'this' and returns address of the base class. 2685 Address GetAddressOfBaseClass(Address Value, 2686 const CXXRecordDecl *Derived, 2687 CastExpr::path_const_iterator PathBegin, 2688 CastExpr::path_const_iterator PathEnd, 2689 bool NullCheckValue, SourceLocation Loc); 2690 2691 Address GetAddressOfDerivedClass(Address Value, 2692 const CXXRecordDecl *Derived, 2693 CastExpr::path_const_iterator PathBegin, 2694 CastExpr::path_const_iterator PathEnd, 2695 bool NullCheckValue); 2696 2697 /// GetVTTParameter - Return the VTT parameter that should be passed to a 2698 /// base constructor/destructor with virtual bases. 2699 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move 2700 /// to ItaniumCXXABI.cpp together with all the references to VTT. 2701 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase, 2702 bool Delegating); 2703 2704 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 2705 CXXCtorType CtorType, 2706 const FunctionArgList &Args, 2707 SourceLocation Loc); 2708 // It's important not to confuse this and the previous function. Delegating 2709 // constructors are the C++0x feature. The constructor delegate optimization 2710 // is used to reduce duplication in the base and complete consturctors where 2711 // they are substantially the same. 2712 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 2713 const FunctionArgList &Args); 2714 2715 /// Emit a call to an inheriting constructor (that is, one that invokes a 2716 /// constructor inherited from a base class) by inlining its definition. This 2717 /// is necessary if the ABI does not support forwarding the arguments to the 2718 /// base class constructor (because they're variadic or similar). 2719 void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor, 2720 CXXCtorType CtorType, 2721 bool ForVirtualBase, 2722 bool Delegating, 2723 CallArgList &Args); 2724 2725 /// Emit a call to a constructor inherited from a base class, passing the 2726 /// current constructor's arguments along unmodified (without even making 2727 /// a copy). 2728 void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D, 2729 bool ForVirtualBase, Address This, 2730 bool InheritedFromVBase, 2731 const CXXInheritedCtorInitExpr *E); 2732 2733 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 2734 bool ForVirtualBase, bool Delegating, 2735 AggValueSlot ThisAVS, const CXXConstructExpr *E); 2736 2737 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 2738 bool ForVirtualBase, bool Delegating, 2739 Address This, CallArgList &Args, 2740 AggValueSlot::Overlap_t Overlap, 2741 SourceLocation Loc, bool NewPointerIsChecked); 2742 2743 /// Emit assumption load for all bases. Requires to be be called only on 2744 /// most-derived class and not under construction of the object. 2745 void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This); 2746 2747 /// Emit assumption that vptr load == global vtable. 2748 void EmitVTableAssumptionLoad(const VPtr &vptr, Address This); 2749 2750 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 2751 Address This, Address Src, 2752 const CXXConstructExpr *E); 2753 2754 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 2755 const ArrayType *ArrayTy, 2756 Address ArrayPtr, 2757 const CXXConstructExpr *E, 2758 bool NewPointerIsChecked, 2759 bool ZeroInitialization = false); 2760 2761 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 2762 llvm::Value *NumElements, 2763 Address ArrayPtr, 2764 const CXXConstructExpr *E, 2765 bool NewPointerIsChecked, 2766 bool ZeroInitialization = false); 2767 2768 static Destroyer destroyCXXObject; 2769 2770 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, 2771 bool ForVirtualBase, bool Delegating, Address This, 2772 QualType ThisTy); 2773 2774 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType, 2775 llvm::Type *ElementTy, Address NewPtr, 2776 llvm::Value *NumElements, 2777 llvm::Value *AllocSizeWithoutCookie); 2778 2779 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, 2780 Address Ptr); 2781 2782 llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr); 2783 void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr); 2784 2785 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E); 2786 void EmitCXXDeleteExpr(const CXXDeleteExpr *E); 2787 2788 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr, 2789 QualType DeleteTy, llvm::Value *NumElements = nullptr, 2790 CharUnits CookieSize = CharUnits()); 2791 2792 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, 2793 const CallExpr *TheCallExpr, bool IsDelete); 2794 2795 llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E); 2796 llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE); 2797 Address EmitCXXUuidofExpr(const CXXUuidofExpr *E); 2798 2799 /// Situations in which we might emit a check for the suitability of a 2800 /// pointer or glvalue. Needs to be kept in sync with ubsan_handlers.cpp in 2801 /// compiler-rt. 2802 enum TypeCheckKind { 2803 /// Checking the operand of a load. Must be suitably sized and aligned. 2804 TCK_Load, 2805 /// Checking the destination of a store. Must be suitably sized and aligned. 2806 TCK_Store, 2807 /// Checking the bound value in a reference binding. Must be suitably sized 2808 /// and aligned, but is not required to refer to an object (until the 2809 /// reference is used), per core issue 453. 2810 TCK_ReferenceBinding, 2811 /// Checking the object expression in a non-static data member access. Must 2812 /// be an object within its lifetime. 2813 TCK_MemberAccess, 2814 /// Checking the 'this' pointer for a call to a non-static member function. 2815 /// Must be an object within its lifetime. 2816 TCK_MemberCall, 2817 /// Checking the 'this' pointer for a constructor call. 2818 TCK_ConstructorCall, 2819 /// Checking the operand of a static_cast to a derived pointer type. Must be 2820 /// null or an object within its lifetime. 2821 TCK_DowncastPointer, 2822 /// Checking the operand of a static_cast to a derived reference type. Must 2823 /// be an object within its lifetime. 2824 TCK_DowncastReference, 2825 /// Checking the operand of a cast to a base object. Must be suitably sized 2826 /// and aligned. 2827 TCK_Upcast, 2828 /// Checking the operand of a cast to a virtual base object. Must be an 2829 /// object within its lifetime. 2830 TCK_UpcastToVirtualBase, 2831 /// Checking the value assigned to a _Nonnull pointer. Must not be null. 2832 TCK_NonnullAssign, 2833 /// Checking the operand of a dynamic_cast or a typeid expression. Must be 2834 /// null or an object within its lifetime. 2835 TCK_DynamicOperation 2836 }; 2837 2838 /// Determine whether the pointer type check \p TCK permits null pointers. 2839 static bool isNullPointerAllowed(TypeCheckKind TCK); 2840 2841 /// Determine whether the pointer type check \p TCK requires a vptr check. 2842 static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty); 2843 2844 /// Whether any type-checking sanitizers are enabled. If \c false, 2845 /// calls to EmitTypeCheck can be skipped. 2846 bool sanitizePerformTypeCheck() const; 2847 2848 /// Emit a check that \p V is the address of storage of the 2849 /// appropriate size and alignment for an object of type \p Type 2850 /// (or if ArraySize is provided, for an array of that bound). 2851 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V, 2852 QualType Type, CharUnits Alignment = CharUnits::Zero(), 2853 SanitizerSet SkippedChecks = SanitizerSet(), 2854 llvm::Value *ArraySize = nullptr); 2855 2856 /// Emit a check that \p Base points into an array object, which 2857 /// we can access at index \p Index. \p Accessed should be \c false if we 2858 /// this expression is used as an lvalue, for instance in "&Arr[Idx]". 2859 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index, 2860 QualType IndexType, bool Accessed); 2861 2862 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 2863 bool isInc, bool isPre); 2864 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 2865 bool isInc, bool isPre); 2866 2867 /// Converts Location to a DebugLoc, if debug information is enabled. 2868 llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location); 2869 2870 /// Get the record field index as represented in debug info. 2871 unsigned getDebugInfoFIndex(const RecordDecl *Rec, unsigned FieldIndex); 2872 2873 2874 //===--------------------------------------------------------------------===// 2875 // Declaration Emission 2876 //===--------------------------------------------------------------------===// 2877 2878 /// EmitDecl - Emit a declaration. 2879 /// 2880 /// This function can be called with a null (unreachable) insert point. 2881 void EmitDecl(const Decl &D); 2882 2883 /// EmitVarDecl - Emit a local variable declaration. 2884 /// 2885 /// This function can be called with a null (unreachable) insert point. 2886 void EmitVarDecl(const VarDecl &D); 2887 2888 void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, 2889 bool capturedByInit); 2890 2891 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D, 2892 llvm::Value *Address); 2893 2894 /// Determine whether the given initializer is trivial in the sense 2895 /// that it requires no code to be generated. 2896 bool isTrivialInitializer(const Expr *Init); 2897 2898 /// EmitAutoVarDecl - Emit an auto variable declaration. 2899 /// 2900 /// This function can be called with a null (unreachable) insert point. 2901 void EmitAutoVarDecl(const VarDecl &D); 2902 2903 class AutoVarEmission { 2904 friend class CodeGenFunction; 2905 2906 const VarDecl *Variable; 2907 2908 /// The address of the alloca for languages with explicit address space 2909 /// (e.g. OpenCL) or alloca casted to generic pointer for address space 2910 /// agnostic languages (e.g. C++). Invalid if the variable was emitted 2911 /// as a global constant. 2912 Address Addr; 2913 2914 llvm::Value *NRVOFlag; 2915 2916 /// True if the variable is a __block variable that is captured by an 2917 /// escaping block. 2918 bool IsEscapingByRef; 2919 2920 /// True if the variable is of aggregate type and has a constant 2921 /// initializer. 2922 bool IsConstantAggregate; 2923 2924 /// Non-null if we should use lifetime annotations. 2925 llvm::Value *SizeForLifetimeMarkers; 2926 2927 /// Address with original alloca instruction. Invalid if the variable was 2928 /// emitted as a global constant. 2929 Address AllocaAddr; 2930 2931 struct Invalid {}; 2932 AutoVarEmission(Invalid) 2933 : Variable(nullptr), Addr(Address::invalid()), 2934 AllocaAddr(Address::invalid()) {} 2935 2936 AutoVarEmission(const VarDecl &variable) 2937 : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr), 2938 IsEscapingByRef(false), IsConstantAggregate(false), 2939 SizeForLifetimeMarkers(nullptr), AllocaAddr(Address::invalid()) {} 2940 2941 bool wasEmittedAsGlobal() const { return !Addr.isValid(); } 2942 2943 public: 2944 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); } 2945 2946 bool useLifetimeMarkers() const { 2947 return SizeForLifetimeMarkers != nullptr; 2948 } 2949 llvm::Value *getSizeForLifetimeMarkers() const { 2950 assert(useLifetimeMarkers()); 2951 return SizeForLifetimeMarkers; 2952 } 2953 2954 /// Returns the raw, allocated address, which is not necessarily 2955 /// the address of the object itself. It is casted to default 2956 /// address space for address space agnostic languages. 2957 Address getAllocatedAddress() const { 2958 return Addr; 2959 } 2960 2961 /// Returns the address for the original alloca instruction. 2962 Address getOriginalAllocatedAddress() const { return AllocaAddr; } 2963 2964 /// Returns the address of the object within this declaration. 2965 /// Note that this does not chase the forwarding pointer for 2966 /// __block decls. 2967 Address getObjectAddress(CodeGenFunction &CGF) const { 2968 if (!IsEscapingByRef) return Addr; 2969 2970 return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false); 2971 } 2972 }; 2973 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var); 2974 void EmitAutoVarInit(const AutoVarEmission &emission); 2975 void EmitAutoVarCleanups(const AutoVarEmission &emission); 2976 void emitAutoVarTypeCleanup(const AutoVarEmission &emission, 2977 QualType::DestructionKind dtorKind); 2978 2979 /// Emits the alloca and debug information for the size expressions for each 2980 /// dimension of an array. It registers the association of its (1-dimensional) 2981 /// QualTypes and size expression's debug node, so that CGDebugInfo can 2982 /// reference this node when creating the DISubrange object to describe the 2983 /// array types. 2984 void EmitAndRegisterVariableArrayDimensions(CGDebugInfo *DI, 2985 const VarDecl &D, 2986 bool EmitDebugInfo); 2987 2988 void EmitStaticVarDecl(const VarDecl &D, 2989 llvm::GlobalValue::LinkageTypes Linkage); 2990 2991 class ParamValue { 2992 llvm::Value *Value; 2993 unsigned Alignment; 2994 ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {} 2995 public: 2996 static ParamValue forDirect(llvm::Value *value) { 2997 return ParamValue(value, 0); 2998 } 2999 static ParamValue forIndirect(Address addr) { 3000 assert(!addr.getAlignment().isZero()); 3001 return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity()); 3002 } 3003 3004 bool isIndirect() const { return Alignment != 0; } 3005 llvm::Value *getAnyValue() const { return Value; } 3006 3007 llvm::Value *getDirectValue() const { 3008 assert(!isIndirect()); 3009 return Value; 3010 } 3011 3012 Address getIndirectAddress() const { 3013 assert(isIndirect()); 3014 return Address(Value, CharUnits::fromQuantity(Alignment)); 3015 } 3016 }; 3017 3018 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl. 3019 void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo); 3020 3021 /// protectFromPeepholes - Protect a value that we're intending to 3022 /// store to the side, but which will probably be used later, from 3023 /// aggressive peepholing optimizations that might delete it. 3024 /// 3025 /// Pass the result to unprotectFromPeepholes to declare that 3026 /// protection is no longer required. 3027 /// 3028 /// There's no particular reason why this shouldn't apply to 3029 /// l-values, it's just that no existing peepholes work on pointers. 3030 PeepholeProtection protectFromPeepholes(RValue rvalue); 3031 void unprotectFromPeepholes(PeepholeProtection protection); 3032 3033 void emitAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty, 3034 SourceLocation Loc, 3035 SourceLocation AssumptionLoc, 3036 llvm::Value *Alignment, 3037 llvm::Value *OffsetValue, 3038 llvm::Value *TheCheck, 3039 llvm::Instruction *Assumption); 3040 3041 void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty, 3042 SourceLocation Loc, SourceLocation AssumptionLoc, 3043 llvm::Value *Alignment, 3044 llvm::Value *OffsetValue = nullptr); 3045 3046 void emitAlignmentAssumption(llvm::Value *PtrValue, const Expr *E, 3047 SourceLocation AssumptionLoc, 3048 llvm::Value *Alignment, 3049 llvm::Value *OffsetValue = nullptr); 3050 3051 //===--------------------------------------------------------------------===// 3052 // Statement Emission 3053 //===--------------------------------------------------------------------===// 3054 3055 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info. 3056 void EmitStopPoint(const Stmt *S); 3057 3058 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call 3059 /// this function even if there is no current insertion point. 3060 /// 3061 /// This function may clear the current insertion point; callers should use 3062 /// EnsureInsertPoint if they wish to subsequently generate code without first 3063 /// calling EmitBlock, EmitBranch, or EmitStmt. 3064 void EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs = None); 3065 3066 /// EmitSimpleStmt - Try to emit a "simple" statement which does not 3067 /// necessarily require an insertion point or debug information; typically 3068 /// because the statement amounts to a jump or a container of other 3069 /// statements. 3070 /// 3071 /// \return True if the statement was handled. 3072 bool EmitSimpleStmt(const Stmt *S); 3073 3074 Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false, 3075 AggValueSlot AVS = AggValueSlot::ignored()); 3076 Address EmitCompoundStmtWithoutScope(const CompoundStmt &S, 3077 bool GetLast = false, 3078 AggValueSlot AVS = 3079 AggValueSlot::ignored()); 3080 3081 /// EmitLabel - Emit the block for the given label. It is legal to call this 3082 /// function even if there is no current insertion point. 3083 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt. 3084 3085 void EmitLabelStmt(const LabelStmt &S); 3086 void EmitAttributedStmt(const AttributedStmt &S); 3087 void EmitGotoStmt(const GotoStmt &S); 3088 void EmitIndirectGotoStmt(const IndirectGotoStmt &S); 3089 void EmitIfStmt(const IfStmt &S); 3090 3091 void EmitWhileStmt(const WhileStmt &S, 3092 ArrayRef<const Attr *> Attrs = None); 3093 void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None); 3094 void EmitForStmt(const ForStmt &S, 3095 ArrayRef<const Attr *> Attrs = None); 3096 void EmitReturnStmt(const ReturnStmt &S); 3097 void EmitDeclStmt(const DeclStmt &S); 3098 void EmitBreakStmt(const BreakStmt &S); 3099 void EmitContinueStmt(const ContinueStmt &S); 3100 void EmitSwitchStmt(const SwitchStmt &S); 3101 void EmitDefaultStmt(const DefaultStmt &S); 3102 void EmitCaseStmt(const CaseStmt &S); 3103 void EmitCaseStmtRange(const CaseStmt &S); 3104 void EmitAsmStmt(const AsmStmt &S); 3105 3106 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S); 3107 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S); 3108 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S); 3109 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S); 3110 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S); 3111 3112 void EmitCoroutineBody(const CoroutineBodyStmt &S); 3113 void EmitCoreturnStmt(const CoreturnStmt &S); 3114 RValue EmitCoawaitExpr(const CoawaitExpr &E, 3115 AggValueSlot aggSlot = AggValueSlot::ignored(), 3116 bool ignoreResult = false); 3117 LValue EmitCoawaitLValue(const CoawaitExpr *E); 3118 RValue EmitCoyieldExpr(const CoyieldExpr &E, 3119 AggValueSlot aggSlot = AggValueSlot::ignored(), 3120 bool ignoreResult = false); 3121 LValue EmitCoyieldLValue(const CoyieldExpr *E); 3122 RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID); 3123 3124 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 3125 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 3126 3127 void EmitCXXTryStmt(const CXXTryStmt &S); 3128 void EmitSEHTryStmt(const SEHTryStmt &S); 3129 void EmitSEHLeaveStmt(const SEHLeaveStmt &S); 3130 void EnterSEHTryStmt(const SEHTryStmt &S); 3131 void ExitSEHTryStmt(const SEHTryStmt &S); 3132 3133 void pushSEHCleanup(CleanupKind kind, 3134 llvm::Function *FinallyFunc); 3135 void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter, 3136 const Stmt *OutlinedStmt); 3137 3138 llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF, 3139 const SEHExceptStmt &Except); 3140 3141 llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF, 3142 const SEHFinallyStmt &Finally); 3143 3144 void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF, 3145 llvm::Value *ParentFP, 3146 llvm::Value *EntryEBP); 3147 llvm::Value *EmitSEHExceptionCode(); 3148 llvm::Value *EmitSEHExceptionInfo(); 3149 llvm::Value *EmitSEHAbnormalTermination(); 3150 3151 /// Emit simple code for OpenMP directives in Simd-only mode. 3152 void EmitSimpleOMPExecutableDirective(const OMPExecutableDirective &D); 3153 3154 /// Scan the outlined statement for captures from the parent function. For 3155 /// each capture, mark the capture as escaped and emit a call to 3156 /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap. 3157 void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt, 3158 bool IsFilter); 3159 3160 /// Recovers the address of a local in a parent function. ParentVar is the 3161 /// address of the variable used in the immediate parent function. It can 3162 /// either be an alloca or a call to llvm.localrecover if there are nested 3163 /// outlined functions. ParentFP is the frame pointer of the outermost parent 3164 /// frame. 3165 Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF, 3166 Address ParentVar, 3167 llvm::Value *ParentFP); 3168 3169 void EmitCXXForRangeStmt(const CXXForRangeStmt &S, 3170 ArrayRef<const Attr *> Attrs = None); 3171 3172 /// Controls insertion of cancellation exit blocks in worksharing constructs. 3173 class OMPCancelStackRAII { 3174 CodeGenFunction &CGF; 3175 3176 public: 3177 OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, 3178 bool HasCancel) 3179 : CGF(CGF) { 3180 CGF.OMPCancelStack.enter(CGF, Kind, HasCancel); 3181 } 3182 ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); } 3183 }; 3184 3185 /// Returns calculated size of the specified type. 3186 llvm::Value *getTypeSize(QualType Ty); 3187 LValue InitCapturedStruct(const CapturedStmt &S); 3188 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K); 3189 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S); 3190 Address GenerateCapturedStmtArgument(const CapturedStmt &S); 3191 llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S, 3192 SourceLocation Loc); 3193 void GenerateOpenMPCapturedVars(const CapturedStmt &S, 3194 SmallVectorImpl<llvm::Value *> &CapturedVars); 3195 void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy, 3196 SourceLocation Loc); 3197 /// Perform element by element copying of arrays with type \a 3198 /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure 3199 /// generated by \a CopyGen. 3200 /// 3201 /// \param DestAddr Address of the destination array. 3202 /// \param SrcAddr Address of the source array. 3203 /// \param OriginalType Type of destination and source arrays. 3204 /// \param CopyGen Copying procedure that copies value of single array element 3205 /// to another single array element. 3206 void EmitOMPAggregateAssign( 3207 Address DestAddr, Address SrcAddr, QualType OriginalType, 3208 const llvm::function_ref<void(Address, Address)> CopyGen); 3209 /// Emit proper copying of data from one variable to another. 3210 /// 3211 /// \param OriginalType Original type of the copied variables. 3212 /// \param DestAddr Destination address. 3213 /// \param SrcAddr Source address. 3214 /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has 3215 /// type of the base array element). 3216 /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of 3217 /// the base array element). 3218 /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a 3219 /// DestVD. 3220 void EmitOMPCopy(QualType OriginalType, 3221 Address DestAddr, Address SrcAddr, 3222 const VarDecl *DestVD, const VarDecl *SrcVD, 3223 const Expr *Copy); 3224 /// Emit atomic update code for constructs: \a X = \a X \a BO \a E or 3225 /// \a X = \a E \a BO \a E. 3226 /// 3227 /// \param X Value to be updated. 3228 /// \param E Update value. 3229 /// \param BO Binary operation for update operation. 3230 /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update 3231 /// expression, false otherwise. 3232 /// \param AO Atomic ordering of the generated atomic instructions. 3233 /// \param CommonGen Code generator for complex expressions that cannot be 3234 /// expressed through atomicrmw instruction. 3235 /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was 3236 /// generated, <false, RValue::get(nullptr)> otherwise. 3237 std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr( 3238 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart, 3239 llvm::AtomicOrdering AO, SourceLocation Loc, 3240 const llvm::function_ref<RValue(RValue)> CommonGen); 3241 bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D, 3242 OMPPrivateScope &PrivateScope); 3243 void EmitOMPPrivateClause(const OMPExecutableDirective &D, 3244 OMPPrivateScope &PrivateScope); 3245 void EmitOMPUseDevicePtrClause( 3246 const OMPUseDevicePtrClause &C, OMPPrivateScope &PrivateScope, 3247 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap); 3248 void EmitOMPUseDeviceAddrClause( 3249 const OMPUseDeviceAddrClause &C, OMPPrivateScope &PrivateScope, 3250 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap); 3251 /// Emit code for copyin clause in \a D directive. The next code is 3252 /// generated at the start of outlined functions for directives: 3253 /// \code 3254 /// threadprivate_var1 = master_threadprivate_var1; 3255 /// operator=(threadprivate_var2, master_threadprivate_var2); 3256 /// ... 3257 /// __kmpc_barrier(&loc, global_tid); 3258 /// \endcode 3259 /// 3260 /// \param D OpenMP directive possibly with 'copyin' clause(s). 3261 /// \returns true if at least one copyin variable is found, false otherwise. 3262 bool EmitOMPCopyinClause(const OMPExecutableDirective &D); 3263 /// Emit initial code for lastprivate variables. If some variable is 3264 /// not also firstprivate, then the default initialization is used. Otherwise 3265 /// initialization of this variable is performed by EmitOMPFirstprivateClause 3266 /// method. 3267 /// 3268 /// \param D Directive that may have 'lastprivate' directives. 3269 /// \param PrivateScope Private scope for capturing lastprivate variables for 3270 /// proper codegen in internal captured statement. 3271 /// 3272 /// \returns true if there is at least one lastprivate variable, false 3273 /// otherwise. 3274 bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D, 3275 OMPPrivateScope &PrivateScope); 3276 /// Emit final copying of lastprivate values to original variables at 3277 /// the end of the worksharing or simd directive. 3278 /// 3279 /// \param D Directive that has at least one 'lastprivate' directives. 3280 /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if 3281 /// it is the last iteration of the loop code in associated directive, or to 3282 /// 'i1 false' otherwise. If this item is nullptr, no final check is required. 3283 void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D, 3284 bool NoFinals, 3285 llvm::Value *IsLastIterCond = nullptr); 3286 /// Emit initial code for linear clauses. 3287 void EmitOMPLinearClause(const OMPLoopDirective &D, 3288 CodeGenFunction::OMPPrivateScope &PrivateScope); 3289 /// Emit final code for linear clauses. 3290 /// \param CondGen Optional conditional code for final part of codegen for 3291 /// linear clause. 3292 void EmitOMPLinearClauseFinal( 3293 const OMPLoopDirective &D, 3294 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen); 3295 /// Emit initial code for reduction variables. Creates reduction copies 3296 /// and initializes them with the values according to OpenMP standard. 3297 /// 3298 /// \param D Directive (possibly) with the 'reduction' clause. 3299 /// \param PrivateScope Private scope for capturing reduction variables for 3300 /// proper codegen in internal captured statement. 3301 /// 3302 void EmitOMPReductionClauseInit(const OMPExecutableDirective &D, 3303 OMPPrivateScope &PrivateScope, 3304 bool ForInscan = false); 3305 /// Emit final update of reduction values to original variables at 3306 /// the end of the directive. 3307 /// 3308 /// \param D Directive that has at least one 'reduction' directives. 3309 /// \param ReductionKind The kind of reduction to perform. 3310 void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D, 3311 const OpenMPDirectiveKind ReductionKind); 3312 /// Emit initial code for linear variables. Creates private copies 3313 /// and initializes them with the values according to OpenMP standard. 3314 /// 3315 /// \param D Directive (possibly) with the 'linear' clause. 3316 /// \return true if at least one linear variable is found that should be 3317 /// initialized with the value of the original variable, false otherwise. 3318 bool EmitOMPLinearClauseInit(const OMPLoopDirective &D); 3319 3320 typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/, 3321 llvm::Function * /*OutlinedFn*/, 3322 const OMPTaskDataTy & /*Data*/)> 3323 TaskGenTy; 3324 void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S, 3325 const OpenMPDirectiveKind CapturedRegion, 3326 const RegionCodeGenTy &BodyGen, 3327 const TaskGenTy &TaskGen, OMPTaskDataTy &Data); 3328 struct OMPTargetDataInfo { 3329 Address BasePointersArray = Address::invalid(); 3330 Address PointersArray = Address::invalid(); 3331 Address SizesArray = Address::invalid(); 3332 unsigned NumberOfTargetItems = 0; 3333 explicit OMPTargetDataInfo() = default; 3334 OMPTargetDataInfo(Address BasePointersArray, Address PointersArray, 3335 Address SizesArray, unsigned NumberOfTargetItems) 3336 : BasePointersArray(BasePointersArray), PointersArray(PointersArray), 3337 SizesArray(SizesArray), NumberOfTargetItems(NumberOfTargetItems) {} 3338 }; 3339 void EmitOMPTargetTaskBasedDirective(const OMPExecutableDirective &S, 3340 const RegionCodeGenTy &BodyGen, 3341 OMPTargetDataInfo &InputInfo); 3342 3343 void EmitOMPParallelDirective(const OMPParallelDirective &S); 3344 void EmitOMPSimdDirective(const OMPSimdDirective &S); 3345 void EmitOMPForDirective(const OMPForDirective &S); 3346 void EmitOMPForSimdDirective(const OMPForSimdDirective &S); 3347 void EmitOMPSectionsDirective(const OMPSectionsDirective &S); 3348 void EmitOMPSectionDirective(const OMPSectionDirective &S); 3349 void EmitOMPSingleDirective(const OMPSingleDirective &S); 3350 void EmitOMPMasterDirective(const OMPMasterDirective &S); 3351 void EmitOMPCriticalDirective(const OMPCriticalDirective &S); 3352 void EmitOMPParallelForDirective(const OMPParallelForDirective &S); 3353 void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S); 3354 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S); 3355 void EmitOMPParallelMasterDirective(const OMPParallelMasterDirective &S); 3356 void EmitOMPTaskDirective(const OMPTaskDirective &S); 3357 void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S); 3358 void EmitOMPBarrierDirective(const OMPBarrierDirective &S); 3359 void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S); 3360 void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S); 3361 void EmitOMPFlushDirective(const OMPFlushDirective &S); 3362 void EmitOMPDepobjDirective(const OMPDepobjDirective &S); 3363 void EmitOMPScanDirective(const OMPScanDirective &S); 3364 void EmitOMPOrderedDirective(const OMPOrderedDirective &S); 3365 void EmitOMPAtomicDirective(const OMPAtomicDirective &S); 3366 void EmitOMPTargetDirective(const OMPTargetDirective &S); 3367 void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S); 3368 void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S); 3369 void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S); 3370 void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S); 3371 void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S); 3372 void 3373 EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S); 3374 void EmitOMPTeamsDirective(const OMPTeamsDirective &S); 3375 void 3376 EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S); 3377 void EmitOMPCancelDirective(const OMPCancelDirective &S); 3378 void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S); 3379 void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S); 3380 void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S); 3381 void EmitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective &S); 3382 void 3383 EmitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective &S); 3384 void EmitOMPParallelMasterTaskLoopDirective( 3385 const OMPParallelMasterTaskLoopDirective &S); 3386 void EmitOMPParallelMasterTaskLoopSimdDirective( 3387 const OMPParallelMasterTaskLoopSimdDirective &S); 3388 void EmitOMPDistributeDirective(const OMPDistributeDirective &S); 3389 void EmitOMPDistributeParallelForDirective( 3390 const OMPDistributeParallelForDirective &S); 3391 void EmitOMPDistributeParallelForSimdDirective( 3392 const OMPDistributeParallelForSimdDirective &S); 3393 void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S); 3394 void EmitOMPTargetParallelForSimdDirective( 3395 const OMPTargetParallelForSimdDirective &S); 3396 void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S); 3397 void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S); 3398 void 3399 EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S); 3400 void EmitOMPTeamsDistributeParallelForSimdDirective( 3401 const OMPTeamsDistributeParallelForSimdDirective &S); 3402 void EmitOMPTeamsDistributeParallelForDirective( 3403 const OMPTeamsDistributeParallelForDirective &S); 3404 void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S); 3405 void EmitOMPTargetTeamsDistributeDirective( 3406 const OMPTargetTeamsDistributeDirective &S); 3407 void EmitOMPTargetTeamsDistributeParallelForDirective( 3408 const OMPTargetTeamsDistributeParallelForDirective &S); 3409 void EmitOMPTargetTeamsDistributeParallelForSimdDirective( 3410 const OMPTargetTeamsDistributeParallelForSimdDirective &S); 3411 void EmitOMPTargetTeamsDistributeSimdDirective( 3412 const OMPTargetTeamsDistributeSimdDirective &S); 3413 3414 /// Emit device code for the target directive. 3415 static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM, 3416 StringRef ParentName, 3417 const OMPTargetDirective &S); 3418 static void 3419 EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName, 3420 const OMPTargetParallelDirective &S); 3421 /// Emit device code for the target parallel for directive. 3422 static void EmitOMPTargetParallelForDeviceFunction( 3423 CodeGenModule &CGM, StringRef ParentName, 3424 const OMPTargetParallelForDirective &S); 3425 /// Emit device code for the target parallel for simd directive. 3426 static void EmitOMPTargetParallelForSimdDeviceFunction( 3427 CodeGenModule &CGM, StringRef ParentName, 3428 const OMPTargetParallelForSimdDirective &S); 3429 /// Emit device code for the target teams directive. 3430 static void 3431 EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName, 3432 const OMPTargetTeamsDirective &S); 3433 /// Emit device code for the target teams distribute directive. 3434 static void EmitOMPTargetTeamsDistributeDeviceFunction( 3435 CodeGenModule &CGM, StringRef ParentName, 3436 const OMPTargetTeamsDistributeDirective &S); 3437 /// Emit device code for the target teams distribute simd directive. 3438 static void EmitOMPTargetTeamsDistributeSimdDeviceFunction( 3439 CodeGenModule &CGM, StringRef ParentName, 3440 const OMPTargetTeamsDistributeSimdDirective &S); 3441 /// Emit device code for the target simd directive. 3442 static void EmitOMPTargetSimdDeviceFunction(CodeGenModule &CGM, 3443 StringRef ParentName, 3444 const OMPTargetSimdDirective &S); 3445 /// Emit device code for the target teams distribute parallel for simd 3446 /// directive. 3447 static void EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction( 3448 CodeGenModule &CGM, StringRef ParentName, 3449 const OMPTargetTeamsDistributeParallelForSimdDirective &S); 3450 3451 static void EmitOMPTargetTeamsDistributeParallelForDeviceFunction( 3452 CodeGenModule &CGM, StringRef ParentName, 3453 const OMPTargetTeamsDistributeParallelForDirective &S); 3454 /// Emit inner loop of the worksharing/simd construct. 3455 /// 3456 /// \param S Directive, for which the inner loop must be emitted. 3457 /// \param RequiresCleanup true, if directive has some associated private 3458 /// variables. 3459 /// \param LoopCond Bollean condition for loop continuation. 3460 /// \param IncExpr Increment expression for loop control variable. 3461 /// \param BodyGen Generator for the inner body of the inner loop. 3462 /// \param PostIncGen Genrator for post-increment code (required for ordered 3463 /// loop directvies). 3464 void EmitOMPInnerLoop( 3465 const OMPExecutableDirective &S, bool RequiresCleanup, 3466 const Expr *LoopCond, const Expr *IncExpr, 3467 const llvm::function_ref<void(CodeGenFunction &)> BodyGen, 3468 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen); 3469 3470 JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind); 3471 /// Emit initial code for loop counters of loop-based directives. 3472 void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S, 3473 OMPPrivateScope &LoopScope); 3474 3475 /// Helper for the OpenMP loop directives. 3476 void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit); 3477 3478 /// Emit code for the worksharing loop-based directive. 3479 /// \return true, if this construct has any lastprivate clause, false - 3480 /// otherwise. 3481 bool EmitOMPWorksharingLoop(const OMPLoopDirective &S, Expr *EUB, 3482 const CodeGenLoopBoundsTy &CodeGenLoopBounds, 3483 const CodeGenDispatchBoundsTy &CGDispatchBounds); 3484 3485 /// Emit code for the distribute loop-based directive. 3486 void EmitOMPDistributeLoop(const OMPLoopDirective &S, 3487 const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr); 3488 3489 /// Helpers for the OpenMP loop directives. 3490 void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false); 3491 void EmitOMPSimdFinal( 3492 const OMPLoopDirective &D, 3493 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen); 3494 3495 /// Emits the lvalue for the expression with possibly captured variable. 3496 LValue EmitOMPSharedLValue(const Expr *E); 3497 3498 private: 3499 /// Helpers for blocks. 3500 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info); 3501 3502 /// struct with the values to be passed to the OpenMP loop-related functions 3503 struct OMPLoopArguments { 3504 /// loop lower bound 3505 Address LB = Address::invalid(); 3506 /// loop upper bound 3507 Address UB = Address::invalid(); 3508 /// loop stride 3509 Address ST = Address::invalid(); 3510 /// isLastIteration argument for runtime functions 3511 Address IL = Address::invalid(); 3512 /// Chunk value generated by sema 3513 llvm::Value *Chunk = nullptr; 3514 /// EnsureUpperBound 3515 Expr *EUB = nullptr; 3516 /// IncrementExpression 3517 Expr *IncExpr = nullptr; 3518 /// Loop initialization 3519 Expr *Init = nullptr; 3520 /// Loop exit condition 3521 Expr *Cond = nullptr; 3522 /// Update of LB after a whole chunk has been executed 3523 Expr *NextLB = nullptr; 3524 /// Update of UB after a whole chunk has been executed 3525 Expr *NextUB = nullptr; 3526 OMPLoopArguments() = default; 3527 OMPLoopArguments(Address LB, Address UB, Address ST, Address IL, 3528 llvm::Value *Chunk = nullptr, Expr *EUB = nullptr, 3529 Expr *IncExpr = nullptr, Expr *Init = nullptr, 3530 Expr *Cond = nullptr, Expr *NextLB = nullptr, 3531 Expr *NextUB = nullptr) 3532 : LB(LB), UB(UB), ST(ST), IL(IL), Chunk(Chunk), EUB(EUB), 3533 IncExpr(IncExpr), Init(Init), Cond(Cond), NextLB(NextLB), 3534 NextUB(NextUB) {} 3535 }; 3536 void EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic, 3537 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, 3538 const OMPLoopArguments &LoopArgs, 3539 const CodeGenLoopTy &CodeGenLoop, 3540 const CodeGenOrderedTy &CodeGenOrdered); 3541 void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind, 3542 bool IsMonotonic, const OMPLoopDirective &S, 3543 OMPPrivateScope &LoopScope, bool Ordered, 3544 const OMPLoopArguments &LoopArgs, 3545 const CodeGenDispatchBoundsTy &CGDispatchBounds); 3546 void EmitOMPDistributeOuterLoop(OpenMPDistScheduleClauseKind ScheduleKind, 3547 const OMPLoopDirective &S, 3548 OMPPrivateScope &LoopScope, 3549 const OMPLoopArguments &LoopArgs, 3550 const CodeGenLoopTy &CodeGenLoopContent); 3551 /// Emit code for sections directive. 3552 void EmitSections(const OMPExecutableDirective &S); 3553 3554 public: 3555 3556 //===--------------------------------------------------------------------===// 3557 // LValue Expression Emission 3558 //===--------------------------------------------------------------------===// 3559 3560 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type. 3561 RValue GetUndefRValue(QualType Ty); 3562 3563 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E 3564 /// and issue an ErrorUnsupported style diagnostic (using the 3565 /// provided Name). 3566 RValue EmitUnsupportedRValue(const Expr *E, 3567 const char *Name); 3568 3569 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue 3570 /// an ErrorUnsupported style diagnostic (using the provided Name). 3571 LValue EmitUnsupportedLValue(const Expr *E, 3572 const char *Name); 3573 3574 /// EmitLValue - Emit code to compute a designator that specifies the location 3575 /// of the expression. 3576 /// 3577 /// This can return one of two things: a simple address or a bitfield 3578 /// reference. In either case, the LLVM Value* in the LValue structure is 3579 /// guaranteed to be an LLVM pointer type. 3580 /// 3581 /// If this returns a bitfield reference, nothing about the pointee type of 3582 /// the LLVM value is known: For example, it may not be a pointer to an 3583 /// integer. 3584 /// 3585 /// If this returns a normal address, and if the lvalue's C type is fixed 3586 /// size, this method guarantees that the returned pointer type will point to 3587 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 3588 /// variable length type, this is not possible. 3589 /// 3590 LValue EmitLValue(const Expr *E); 3591 3592 /// Same as EmitLValue but additionally we generate checking code to 3593 /// guard against undefined behavior. This is only suitable when we know 3594 /// that the address will be used to access the object. 3595 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK); 3596 3597 RValue convertTempToRValue(Address addr, QualType type, 3598 SourceLocation Loc); 3599 3600 void EmitAtomicInit(Expr *E, LValue lvalue); 3601 3602 bool LValueIsSuitableForInlineAtomic(LValue Src); 3603 3604 RValue EmitAtomicLoad(LValue LV, SourceLocation SL, 3605 AggValueSlot Slot = AggValueSlot::ignored()); 3606 3607 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc, 3608 llvm::AtomicOrdering AO, bool IsVolatile = false, 3609 AggValueSlot slot = AggValueSlot::ignored()); 3610 3611 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit); 3612 3613 void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO, 3614 bool IsVolatile, bool isInit); 3615 3616 std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange( 3617 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc, 3618 llvm::AtomicOrdering Success = 3619 llvm::AtomicOrdering::SequentiallyConsistent, 3620 llvm::AtomicOrdering Failure = 3621 llvm::AtomicOrdering::SequentiallyConsistent, 3622 bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored()); 3623 3624 void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO, 3625 const llvm::function_ref<RValue(RValue)> &UpdateOp, 3626 bool IsVolatile); 3627 3628 /// EmitToMemory - Change a scalar value from its value 3629 /// representation to its in-memory representation. 3630 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty); 3631 3632 /// EmitFromMemory - Change a scalar value from its memory 3633 /// representation to its value representation. 3634 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty); 3635 3636 /// Check if the scalar \p Value is within the valid range for the given 3637 /// type \p Ty. 3638 /// 3639 /// Returns true if a check is needed (even if the range is unknown). 3640 bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty, 3641 SourceLocation Loc); 3642 3643 /// EmitLoadOfScalar - Load a scalar value from an address, taking 3644 /// care to appropriately convert from the memory representation to 3645 /// the LLVM value representation. 3646 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, 3647 SourceLocation Loc, 3648 AlignmentSource Source = AlignmentSource::Type, 3649 bool isNontemporal = false) { 3650 return EmitLoadOfScalar(Addr, Volatile, Ty, Loc, LValueBaseInfo(Source), 3651 CGM.getTBAAAccessInfo(Ty), isNontemporal); 3652 } 3653 3654 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, 3655 SourceLocation Loc, LValueBaseInfo BaseInfo, 3656 TBAAAccessInfo TBAAInfo, 3657 bool isNontemporal = false); 3658 3659 /// EmitLoadOfScalar - Load a scalar value from an address, taking 3660 /// care to appropriately convert from the memory representation to 3661 /// the LLVM value representation. The l-value must be a simple 3662 /// l-value. 3663 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc); 3664 3665 /// EmitStoreOfScalar - Store a scalar value to an address, taking 3666 /// care to appropriately convert from the memory representation to 3667 /// the LLVM value representation. 3668 void EmitStoreOfScalar(llvm::Value *Value, Address Addr, 3669 bool Volatile, QualType Ty, 3670 AlignmentSource Source = AlignmentSource::Type, 3671 bool isInit = false, bool isNontemporal = false) { 3672 EmitStoreOfScalar(Value, Addr, Volatile, Ty, LValueBaseInfo(Source), 3673 CGM.getTBAAAccessInfo(Ty), isInit, isNontemporal); 3674 } 3675 3676 void EmitStoreOfScalar(llvm::Value *Value, Address Addr, 3677 bool Volatile, QualType Ty, 3678 LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo, 3679 bool isInit = false, bool isNontemporal = false); 3680 3681 /// EmitStoreOfScalar - Store a scalar value to an address, taking 3682 /// care to appropriately convert from the memory representation to 3683 /// the LLVM value representation. The l-value must be a simple 3684 /// l-value. The isInit flag indicates whether this is an initialization. 3685 /// If so, atomic qualifiers are ignored and the store is always non-atomic. 3686 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false); 3687 3688 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, 3689 /// this method emits the address of the lvalue, then loads the result as an 3690 /// rvalue, returning the rvalue. 3691 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc); 3692 RValue EmitLoadOfExtVectorElementLValue(LValue V); 3693 RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc); 3694 RValue EmitLoadOfGlobalRegLValue(LValue LV); 3695 3696 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 3697 /// lvalue, where both are guaranteed to the have the same type, and that type 3698 /// is 'Ty'. 3699 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false); 3700 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst); 3701 void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst); 3702 3703 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints 3704 /// as EmitStoreThroughLValue. 3705 /// 3706 /// \param Result [out] - If non-null, this will be set to a Value* for the 3707 /// bit-field contents after the store, appropriate for use as the result of 3708 /// an assignment to the bit-field. 3709 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 3710 llvm::Value **Result=nullptr); 3711 3712 /// Emit an l-value for an assignment (simple or compound) of complex type. 3713 LValue EmitComplexAssignmentLValue(const BinaryOperator *E); 3714 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E); 3715 LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E, 3716 llvm::Value *&Result); 3717 3718 // Note: only available for agg return types 3719 LValue EmitBinaryOperatorLValue(const BinaryOperator *E); 3720 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E); 3721 // Note: only available for agg return types 3722 LValue EmitCallExprLValue(const CallExpr *E); 3723 // Note: only available for agg return types 3724 LValue EmitVAArgExprLValue(const VAArgExpr *E); 3725 LValue EmitDeclRefLValue(const DeclRefExpr *E); 3726 LValue EmitStringLiteralLValue(const StringLiteral *E); 3727 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E); 3728 LValue EmitPredefinedLValue(const PredefinedExpr *E); 3729 LValue EmitUnaryOpLValue(const UnaryOperator *E); 3730 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E, 3731 bool Accessed = false); 3732 LValue EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E); 3733 LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E, 3734 bool IsLowerBound = true); 3735 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E); 3736 LValue EmitMemberExpr(const MemberExpr *E); 3737 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E); 3738 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E); 3739 LValue EmitInitListLValue(const InitListExpr *E); 3740 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E); 3741 LValue EmitCastLValue(const CastExpr *E); 3742 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 3743 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e); 3744 3745 Address EmitExtVectorElementLValue(LValue V); 3746 3747 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc); 3748 3749 Address EmitArrayToPointerDecay(const Expr *Array, 3750 LValueBaseInfo *BaseInfo = nullptr, 3751 TBAAAccessInfo *TBAAInfo = nullptr); 3752 3753 class ConstantEmission { 3754 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference; 3755 ConstantEmission(llvm::Constant *C, bool isReference) 3756 : ValueAndIsReference(C, isReference) {} 3757 public: 3758 ConstantEmission() {} 3759 static ConstantEmission forReference(llvm::Constant *C) { 3760 return ConstantEmission(C, true); 3761 } 3762 static ConstantEmission forValue(llvm::Constant *C) { 3763 return ConstantEmission(C, false); 3764 } 3765 3766 explicit operator bool() const { 3767 return ValueAndIsReference.getOpaqueValue() != nullptr; 3768 } 3769 3770 bool isReference() const { return ValueAndIsReference.getInt(); } 3771 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const { 3772 assert(isReference()); 3773 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(), 3774 refExpr->getType()); 3775 } 3776 3777 llvm::Constant *getValue() const { 3778 assert(!isReference()); 3779 return ValueAndIsReference.getPointer(); 3780 } 3781 }; 3782 3783 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr); 3784 ConstantEmission tryEmitAsConstant(const MemberExpr *ME); 3785 llvm::Value *emitScalarConstant(const ConstantEmission &Constant, Expr *E); 3786 3787 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, 3788 AggValueSlot slot = AggValueSlot::ignored()); 3789 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e); 3790 3791 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface, 3792 const ObjCIvarDecl *Ivar); 3793 LValue EmitLValueForField(LValue Base, const FieldDecl* Field); 3794 LValue EmitLValueForLambdaField(const FieldDecl *Field); 3795 3796 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that 3797 /// if the Field is a reference, this will return the address of the reference 3798 /// and not the address of the value stored in the reference. 3799 LValue EmitLValueForFieldInitialization(LValue Base, 3800 const FieldDecl* Field); 3801 3802 LValue EmitLValueForIvar(QualType ObjectTy, 3803 llvm::Value* Base, const ObjCIvarDecl *Ivar, 3804 unsigned CVRQualifiers); 3805 3806 LValue EmitCXXConstructLValue(const CXXConstructExpr *E); 3807 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E); 3808 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E); 3809 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E); 3810 3811 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E); 3812 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E); 3813 LValue EmitStmtExprLValue(const StmtExpr *E); 3814 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E); 3815 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E); 3816 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init); 3817 3818 //===--------------------------------------------------------------------===// 3819 // Scalar Expression Emission 3820 //===--------------------------------------------------------------------===// 3821 3822 /// EmitCall - Generate a call of the given function, expecting the given 3823 /// result type, and using the given argument list which specifies both the 3824 /// LLVM arguments and the types they were derived from. 3825 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, 3826 ReturnValueSlot ReturnValue, const CallArgList &Args, 3827 llvm::CallBase **callOrInvoke, SourceLocation Loc); 3828 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, 3829 ReturnValueSlot ReturnValue, const CallArgList &Args, 3830 llvm::CallBase **callOrInvoke = nullptr) { 3831 return EmitCall(CallInfo, Callee, ReturnValue, Args, callOrInvoke, 3832 SourceLocation()); 3833 } 3834 RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E, 3835 ReturnValueSlot ReturnValue, llvm::Value *Chain = nullptr); 3836 RValue EmitCallExpr(const CallExpr *E, 3837 ReturnValueSlot ReturnValue = ReturnValueSlot()); 3838 RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 3839 CGCallee EmitCallee(const Expr *E); 3840 3841 void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl); 3842 void checkTargetFeatures(SourceLocation Loc, const FunctionDecl *TargetDecl); 3843 3844 llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee, 3845 const Twine &name = ""); 3846 llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee, 3847 ArrayRef<llvm::Value *> args, 3848 const Twine &name = ""); 3849 llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee, 3850 const Twine &name = ""); 3851 llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee, 3852 ArrayRef<llvm::Value *> args, 3853 const Twine &name = ""); 3854 3855 SmallVector<llvm::OperandBundleDef, 1> 3856 getBundlesForFunclet(llvm::Value *Callee); 3857 3858 llvm::CallBase *EmitCallOrInvoke(llvm::FunctionCallee Callee, 3859 ArrayRef<llvm::Value *> Args, 3860 const Twine &Name = ""); 3861 llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, 3862 ArrayRef<llvm::Value *> args, 3863 const Twine &name = ""); 3864 llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, 3865 const Twine &name = ""); 3866 void EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee, 3867 ArrayRef<llvm::Value *> args); 3868 3869 CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 3870 NestedNameSpecifier *Qual, 3871 llvm::Type *Ty); 3872 3873 CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD, 3874 CXXDtorType Type, 3875 const CXXRecordDecl *RD); 3876 3877 // Return the copy constructor name with the prefix "__copy_constructor_" 3878 // removed. 3879 static std::string getNonTrivialCopyConstructorStr(QualType QT, 3880 CharUnits Alignment, 3881 bool IsVolatile, 3882 ASTContext &Ctx); 3883 3884 // Return the destructor name with the prefix "__destructor_" removed. 3885 static std::string getNonTrivialDestructorStr(QualType QT, 3886 CharUnits Alignment, 3887 bool IsVolatile, 3888 ASTContext &Ctx); 3889 3890 // These functions emit calls to the special functions of non-trivial C 3891 // structs. 3892 void defaultInitNonTrivialCStructVar(LValue Dst); 3893 void callCStructDefaultConstructor(LValue Dst); 3894 void callCStructDestructor(LValue Dst); 3895 void callCStructCopyConstructor(LValue Dst, LValue Src); 3896 void callCStructMoveConstructor(LValue Dst, LValue Src); 3897 void callCStructCopyAssignmentOperator(LValue Dst, LValue Src); 3898 void callCStructMoveAssignmentOperator(LValue Dst, LValue Src); 3899 3900 RValue 3901 EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method, 3902 const CGCallee &Callee, 3903 ReturnValueSlot ReturnValue, llvm::Value *This, 3904 llvm::Value *ImplicitParam, 3905 QualType ImplicitParamTy, const CallExpr *E, 3906 CallArgList *RtlArgs); 3907 RValue EmitCXXDestructorCall(GlobalDecl Dtor, const CGCallee &Callee, 3908 llvm::Value *This, QualType ThisTy, 3909 llvm::Value *ImplicitParam, 3910 QualType ImplicitParamTy, const CallExpr *E); 3911 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, 3912 ReturnValueSlot ReturnValue); 3913 RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE, 3914 const CXXMethodDecl *MD, 3915 ReturnValueSlot ReturnValue, 3916 bool HasQualifier, 3917 NestedNameSpecifier *Qualifier, 3918 bool IsArrow, const Expr *Base); 3919 // Compute the object pointer. 3920 Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base, 3921 llvm::Value *memberPtr, 3922 const MemberPointerType *memberPtrType, 3923 LValueBaseInfo *BaseInfo = nullptr, 3924 TBAAAccessInfo *TBAAInfo = nullptr); 3925 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 3926 ReturnValueSlot ReturnValue); 3927 3928 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 3929 const CXXMethodDecl *MD, 3930 ReturnValueSlot ReturnValue); 3931 RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E); 3932 3933 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, 3934 ReturnValueSlot ReturnValue); 3935 3936 RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E, 3937 ReturnValueSlot ReturnValue); 3938 RValue EmitAMDGPUDevicePrintfCallExpr(const CallExpr *E, 3939 ReturnValueSlot ReturnValue); 3940 3941 RValue EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, 3942 const CallExpr *E, ReturnValueSlot ReturnValue); 3943 3944 RValue emitRotate(const CallExpr *E, bool IsRotateRight); 3945 3946 /// Emit IR for __builtin_os_log_format. 3947 RValue emitBuiltinOSLogFormat(const CallExpr &E); 3948 3949 /// Emit IR for __builtin_is_aligned. 3950 RValue EmitBuiltinIsAligned(const CallExpr *E); 3951 /// Emit IR for __builtin_align_up/__builtin_align_down. 3952 RValue EmitBuiltinAlignTo(const CallExpr *E, bool AlignUp); 3953 3954 llvm::Function *generateBuiltinOSLogHelperFunction( 3955 const analyze_os_log::OSLogBufferLayout &Layout, 3956 CharUnits BufferAlignment); 3957 3958 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 3959 3960 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call 3961 /// is unhandled by the current target. 3962 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E, 3963 ReturnValueSlot ReturnValue); 3964 3965 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty, 3966 const llvm::CmpInst::Predicate Fp, 3967 const llvm::CmpInst::Predicate Ip, 3968 const llvm::Twine &Name = ""); 3969 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E, 3970 ReturnValueSlot ReturnValue, 3971 llvm::Triple::ArchType Arch); 3972 llvm::Value *EmitARMMVEBuiltinExpr(unsigned BuiltinID, const CallExpr *E, 3973 ReturnValueSlot ReturnValue, 3974 llvm::Triple::ArchType Arch); 3975 llvm::Value *EmitARMCDEBuiltinExpr(unsigned BuiltinID, const CallExpr *E, 3976 ReturnValueSlot ReturnValue, 3977 llvm::Triple::ArchType Arch); 3978 llvm::Value *EmitCMSEClearRecord(llvm::Value *V, llvm::IntegerType *ITy, 3979 QualType RTy); 3980 llvm::Value *EmitCMSEClearRecord(llvm::Value *V, llvm::ArrayType *ATy, 3981 QualType RTy); 3982 3983 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID, 3984 unsigned LLVMIntrinsic, 3985 unsigned AltLLVMIntrinsic, 3986 const char *NameHint, 3987 unsigned Modifier, 3988 const CallExpr *E, 3989 SmallVectorImpl<llvm::Value *> &Ops, 3990 Address PtrOp0, Address PtrOp1, 3991 llvm::Triple::ArchType Arch); 3992 3993 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID, 3994 unsigned Modifier, llvm::Type *ArgTy, 3995 const CallExpr *E); 3996 llvm::Value *EmitNeonCall(llvm::Function *F, 3997 SmallVectorImpl<llvm::Value*> &O, 3998 const char *name, 3999 unsigned shift = 0, bool rightshift = false); 4000 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx, 4001 const llvm::ElementCount &Count); 4002 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx); 4003 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty, 4004 bool negateForRightShift); 4005 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt, 4006 llvm::Type *Ty, bool usgn, const char *name); 4007 llvm::Value *vectorWrapScalar16(llvm::Value *Op); 4008 /// SVEBuiltinMemEltTy - Returns the memory element type for this memory 4009 /// access builtin. Only required if it can't be inferred from the base 4010 /// pointer operand. 4011 llvm::Type *SVEBuiltinMemEltTy(SVETypeFlags TypeFlags); 4012 4013 SmallVector<llvm::Type *, 2> getSVEOverloadTypes(SVETypeFlags TypeFlags, 4014 llvm::Type *ReturnType, 4015 ArrayRef<llvm::Value *> Ops); 4016 llvm::Type *getEltType(SVETypeFlags TypeFlags); 4017 llvm::ScalableVectorType *getSVEType(const SVETypeFlags &TypeFlags); 4018 llvm::ScalableVectorType *getSVEPredType(SVETypeFlags TypeFlags); 4019 llvm::Value *EmitSVEAllTruePred(SVETypeFlags TypeFlags); 4020 llvm::Value *EmitSVEDupX(llvm::Value *Scalar); 4021 llvm::Value *EmitSVEDupX(llvm::Value *Scalar, llvm::Type *Ty); 4022 llvm::Value *EmitSVEReinterpret(llvm::Value *Val, llvm::Type *Ty); 4023 llvm::Value *EmitSVEPMull(SVETypeFlags TypeFlags, 4024 llvm::SmallVectorImpl<llvm::Value *> &Ops, 4025 unsigned BuiltinID); 4026 llvm::Value *EmitSVEMovl(SVETypeFlags TypeFlags, 4027 llvm::ArrayRef<llvm::Value *> Ops, 4028 unsigned BuiltinID); 4029 llvm::Value *EmitSVEPredicateCast(llvm::Value *Pred, 4030 llvm::ScalableVectorType *VTy); 4031 llvm::Value *EmitSVEGatherLoad(SVETypeFlags TypeFlags, 4032 llvm::SmallVectorImpl<llvm::Value *> &Ops, 4033 unsigned IntID); 4034 llvm::Value *EmitSVEScatterStore(SVETypeFlags TypeFlags, 4035 llvm::SmallVectorImpl<llvm::Value *> &Ops, 4036 unsigned IntID); 4037 llvm::Value *EmitSVEMaskedLoad(const CallExpr *, llvm::Type *ReturnTy, 4038 SmallVectorImpl<llvm::Value *> &Ops, 4039 unsigned BuiltinID, bool IsZExtReturn); 4040 llvm::Value *EmitSVEMaskedStore(const CallExpr *, 4041 SmallVectorImpl<llvm::Value *> &Ops, 4042 unsigned BuiltinID); 4043 llvm::Value *EmitSVEPrefetchLoad(SVETypeFlags TypeFlags, 4044 SmallVectorImpl<llvm::Value *> &Ops, 4045 unsigned BuiltinID); 4046 llvm::Value *EmitSVEGatherPrefetch(SVETypeFlags TypeFlags, 4047 SmallVectorImpl<llvm::Value *> &Ops, 4048 unsigned IntID); 4049 llvm::Value *EmitSVEStructLoad(SVETypeFlags TypeFlags, 4050 SmallVectorImpl<llvm::Value *> &Ops, unsigned IntID); 4051 llvm::Value *EmitSVEStructStore(SVETypeFlags TypeFlags, 4052 SmallVectorImpl<llvm::Value *> &Ops, 4053 unsigned IntID); 4054 llvm::Value *EmitAArch64SVEBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 4055 4056 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E, 4057 llvm::Triple::ArchType Arch); 4058 llvm::Value *EmitBPFBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 4059 4060 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops); 4061 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 4062 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 4063 llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 4064 llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 4065 llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 4066 llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID, 4067 const CallExpr *E); 4068 llvm::Value *EmitHexagonBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 4069 bool ProcessOrderScopeAMDGCN(llvm::Value *Order, llvm::Value *Scope, 4070 llvm::AtomicOrdering &AO, 4071 llvm::SyncScope::ID &SSID); 4072 4073 private: 4074 enum class MSVCIntrin; 4075 4076 public: 4077 llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E); 4078 4079 llvm::Value *EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args); 4080 4081 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E); 4082 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E); 4083 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E); 4084 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E); 4085 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E); 4086 llvm::Value *EmitObjCCollectionLiteral(const Expr *E, 4087 const ObjCMethodDecl *MethodWithObjects); 4088 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E); 4089 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, 4090 ReturnValueSlot Return = ReturnValueSlot()); 4091 4092 /// Retrieves the default cleanup kind for an ARC cleanup. 4093 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only. 4094 CleanupKind getARCCleanupKind() { 4095 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions 4096 ? NormalAndEHCleanup : NormalCleanup; 4097 } 4098 4099 // ARC primitives. 4100 void EmitARCInitWeak(Address addr, llvm::Value *value); 4101 void EmitARCDestroyWeak(Address addr); 4102 llvm::Value *EmitARCLoadWeak(Address addr); 4103 llvm::Value *EmitARCLoadWeakRetained(Address addr); 4104 llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored); 4105 void emitARCCopyAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr); 4106 void emitARCMoveAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr); 4107 void EmitARCCopyWeak(Address dst, Address src); 4108 void EmitARCMoveWeak(Address dst, Address src); 4109 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value); 4110 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value); 4111 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value, 4112 bool resultIgnored); 4113 llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value, 4114 bool resultIgnored); 4115 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value); 4116 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value); 4117 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory); 4118 void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise); 4119 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise); 4120 llvm::Value *EmitARCAutorelease(llvm::Value *value); 4121 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value); 4122 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value); 4123 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value); 4124 llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value); 4125 4126 llvm::Value *EmitObjCAutorelease(llvm::Value *value, llvm::Type *returnType); 4127 llvm::Value *EmitObjCRetainNonBlock(llvm::Value *value, 4128 llvm::Type *returnType); 4129 void EmitObjCRelease(llvm::Value *value, ARCPreciseLifetime_t precise); 4130 4131 std::pair<LValue,llvm::Value*> 4132 EmitARCStoreAutoreleasing(const BinaryOperator *e); 4133 std::pair<LValue,llvm::Value*> 4134 EmitARCStoreStrong(const BinaryOperator *e, bool ignored); 4135 std::pair<LValue,llvm::Value*> 4136 EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored); 4137 4138 llvm::Value *EmitObjCAlloc(llvm::Value *value, 4139 llvm::Type *returnType); 4140 llvm::Value *EmitObjCAllocWithZone(llvm::Value *value, 4141 llvm::Type *returnType); 4142 llvm::Value *EmitObjCAllocInit(llvm::Value *value, llvm::Type *resultType); 4143 4144 llvm::Value *EmitObjCThrowOperand(const Expr *expr); 4145 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr); 4146 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr); 4147 4148 llvm::Value *EmitARCExtendBlockObject(const Expr *expr); 4149 llvm::Value *EmitARCReclaimReturnedObject(const Expr *e, 4150 bool allowUnsafeClaim); 4151 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr); 4152 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr); 4153 llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr); 4154 4155 void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values); 4156 4157 static Destroyer destroyARCStrongImprecise; 4158 static Destroyer destroyARCStrongPrecise; 4159 static Destroyer destroyARCWeak; 4160 static Destroyer emitARCIntrinsicUse; 4161 static Destroyer destroyNonTrivialCStruct; 4162 4163 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr); 4164 llvm::Value *EmitObjCAutoreleasePoolPush(); 4165 llvm::Value *EmitObjCMRRAutoreleasePoolPush(); 4166 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr); 4167 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr); 4168 4169 /// Emits a reference binding to the passed in expression. 4170 RValue EmitReferenceBindingToExpr(const Expr *E); 4171 4172 //===--------------------------------------------------------------------===// 4173 // Expression Emission 4174 //===--------------------------------------------------------------------===// 4175 4176 // Expressions are broken into three classes: scalar, complex, aggregate. 4177 4178 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM 4179 /// scalar type, returning the result. 4180 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false); 4181 4182 /// Emit a conversion from the specified type to the specified destination 4183 /// type, both of which are LLVM scalar types. 4184 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy, 4185 QualType DstTy, SourceLocation Loc); 4186 4187 /// Emit a conversion from the specified complex type to the specified 4188 /// destination type, where the destination type is an LLVM scalar type. 4189 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, 4190 QualType DstTy, 4191 SourceLocation Loc); 4192 4193 /// EmitAggExpr - Emit the computation of the specified expression 4194 /// of aggregate type. The result is computed into the given slot, 4195 /// which may be null to indicate that the value is not needed. 4196 void EmitAggExpr(const Expr *E, AggValueSlot AS); 4197 4198 /// EmitAggExprToLValue - Emit the computation of the specified expression of 4199 /// aggregate type into a temporary LValue. 4200 LValue EmitAggExprToLValue(const Expr *E); 4201 4202 /// Build all the stores needed to initialize an aggregate at Dest with the 4203 /// value Val. 4204 void EmitAggregateStore(llvm::Value *Val, Address Dest, bool DestIsVolatile); 4205 4206 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object, 4207 /// make sure it survives garbage collection until this point. 4208 void EmitExtendGCLifetime(llvm::Value *object); 4209 4210 /// EmitComplexExpr - Emit the computation of the specified expression of 4211 /// complex type, returning the result. 4212 ComplexPairTy EmitComplexExpr(const Expr *E, 4213 bool IgnoreReal = false, 4214 bool IgnoreImag = false); 4215 4216 /// EmitComplexExprIntoLValue - Emit the given expression of complex 4217 /// type and place its result into the specified l-value. 4218 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit); 4219 4220 /// EmitStoreOfComplex - Store a complex number into the specified l-value. 4221 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit); 4222 4223 /// EmitLoadOfComplex - Load a complex number from the specified l-value. 4224 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc); 4225 4226 Address emitAddrOfRealComponent(Address complex, QualType complexType); 4227 Address emitAddrOfImagComponent(Address complex, QualType complexType); 4228 4229 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 4230 /// global variable that has already been created for it. If the initializer 4231 /// has a different type than GV does, this may free GV and return a different 4232 /// one. Otherwise it just returns GV. 4233 llvm::GlobalVariable * 4234 AddInitializerToStaticVarDecl(const VarDecl &D, 4235 llvm::GlobalVariable *GV); 4236 4237 // Emit an @llvm.invariant.start call for the given memory region. 4238 void EmitInvariantStart(llvm::Constant *Addr, CharUnits Size); 4239 4240 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++ 4241 /// variable with global storage. 4242 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr, 4243 bool PerformInit); 4244 4245 llvm::Function *createAtExitStub(const VarDecl &VD, llvm::FunctionCallee Dtor, 4246 llvm::Constant *Addr); 4247 4248 /// Call atexit() with a function that passes the given argument to 4249 /// the given function. 4250 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::FunctionCallee fn, 4251 llvm::Constant *addr); 4252 4253 /// Call atexit() with function dtorStub. 4254 void registerGlobalDtorWithAtExit(llvm::Constant *dtorStub); 4255 4256 /// Call unatexit() with function dtorStub. 4257 llvm::Value *unregisterGlobalDtorWithUnAtExit(llvm::Function *dtorStub); 4258 4259 /// Emit code in this function to perform a guarded variable 4260 /// initialization. Guarded initializations are used when it's not 4261 /// possible to prove that an initialization will be done exactly 4262 /// once, e.g. with a static local variable or a static data member 4263 /// of a class template. 4264 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr, 4265 bool PerformInit); 4266 4267 enum class GuardKind { VariableGuard, TlsGuard }; 4268 4269 /// Emit a branch to select whether or not to perform guarded initialization. 4270 void EmitCXXGuardedInitBranch(llvm::Value *NeedsInit, 4271 llvm::BasicBlock *InitBlock, 4272 llvm::BasicBlock *NoInitBlock, 4273 GuardKind Kind, const VarDecl *D); 4274 4275 /// GenerateCXXGlobalInitFunc - Generates code for initializing global 4276 /// variables. 4277 void 4278 GenerateCXXGlobalInitFunc(llvm::Function *Fn, 4279 ArrayRef<llvm::Function *> CXXThreadLocals, 4280 ConstantAddress Guard = ConstantAddress::invalid()); 4281 4282 /// GenerateCXXGlobalCleanUpFunc - Generates code for cleaning up global 4283 /// variables. 4284 void GenerateCXXGlobalCleanUpFunc( 4285 llvm::Function *Fn, 4286 const std::vector<std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH, 4287 llvm::Constant *>> &DtorsOrStermFinalizers); 4288 4289 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, 4290 const VarDecl *D, 4291 llvm::GlobalVariable *Addr, 4292 bool PerformInit); 4293 4294 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest); 4295 4296 void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp); 4297 4298 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true); 4299 4300 RValue EmitAtomicExpr(AtomicExpr *E); 4301 4302 //===--------------------------------------------------------------------===// 4303 // Annotations Emission 4304 //===--------------------------------------------------------------------===// 4305 4306 /// Emit an annotation call (intrinsic). 4307 llvm::Value *EmitAnnotationCall(llvm::Function *AnnotationFn, 4308 llvm::Value *AnnotatedVal, 4309 StringRef AnnotationStr, 4310 SourceLocation Location); 4311 4312 /// Emit local annotations for the local variable V, declared by D. 4313 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V); 4314 4315 /// Emit field annotations for the given field & value. Returns the 4316 /// annotation result. 4317 Address EmitFieldAnnotations(const FieldDecl *D, Address V); 4318 4319 //===--------------------------------------------------------------------===// 4320 // Internal Helpers 4321 //===--------------------------------------------------------------------===// 4322 4323 /// ContainsLabel - Return true if the statement contains a label in it. If 4324 /// this statement is not executed normally, it not containing a label means 4325 /// that we can just remove the code. 4326 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false); 4327 4328 /// containsBreak - Return true if the statement contains a break out of it. 4329 /// If the statement (recursively) contains a switch or loop with a break 4330 /// inside of it, this is fine. 4331 static bool containsBreak(const Stmt *S); 4332 4333 /// Determine if the given statement might introduce a declaration into the 4334 /// current scope, by being a (possibly-labelled) DeclStmt. 4335 static bool mightAddDeclToScope(const Stmt *S); 4336 4337 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 4338 /// to a constant, or if it does but contains a label, return false. If it 4339 /// constant folds return true and set the boolean result in Result. 4340 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, 4341 bool AllowLabels = false); 4342 4343 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 4344 /// to a constant, or if it does but contains a label, return false. If it 4345 /// constant folds return true and set the folded value. 4346 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result, 4347 bool AllowLabels = false); 4348 4349 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an 4350 /// if statement) to the specified blocks. Based on the condition, this might 4351 /// try to simplify the codegen of the conditional based on the branch. 4352 /// TrueCount should be the number of times we expect the condition to 4353 /// evaluate to true based on PGO data. 4354 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, 4355 llvm::BasicBlock *FalseBlock, uint64_t TrueCount); 4356 4357 /// Given an assignment `*LHS = RHS`, emit a test that checks if \p RHS is 4358 /// nonnull, if \p LHS is marked _Nonnull. 4359 void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc); 4360 4361 /// An enumeration which makes it easier to specify whether or not an 4362 /// operation is a subtraction. 4363 enum { NotSubtraction = false, IsSubtraction = true }; 4364 4365 /// Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to 4366 /// detect undefined behavior when the pointer overflow sanitizer is enabled. 4367 /// \p SignedIndices indicates whether any of the GEP indices are signed. 4368 /// \p IsSubtraction indicates whether the expression used to form the GEP 4369 /// is a subtraction. 4370 llvm::Value *EmitCheckedInBoundsGEP(llvm::Value *Ptr, 4371 ArrayRef<llvm::Value *> IdxList, 4372 bool SignedIndices, 4373 bool IsSubtraction, 4374 SourceLocation Loc, 4375 const Twine &Name = ""); 4376 4377 /// Specifies which type of sanitizer check to apply when handling a 4378 /// particular builtin. 4379 enum BuiltinCheckKind { 4380 BCK_CTZPassedZero, 4381 BCK_CLZPassedZero, 4382 }; 4383 4384 /// Emits an argument for a call to a builtin. If the builtin sanitizer is 4385 /// enabled, a runtime check specified by \p Kind is also emitted. 4386 llvm::Value *EmitCheckedArgForBuiltin(const Expr *E, BuiltinCheckKind Kind); 4387 4388 /// Emit a description of a type in a format suitable for passing to 4389 /// a runtime sanitizer handler. 4390 llvm::Constant *EmitCheckTypeDescriptor(QualType T); 4391 4392 /// Convert a value into a format suitable for passing to a runtime 4393 /// sanitizer handler. 4394 llvm::Value *EmitCheckValue(llvm::Value *V); 4395 4396 /// Emit a description of a source location in a format suitable for 4397 /// passing to a runtime sanitizer handler. 4398 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc); 4399 4400 /// Create a basic block that will either trap or call a handler function in 4401 /// the UBSan runtime with the provided arguments, and create a conditional 4402 /// branch to it. 4403 void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked, 4404 SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs, 4405 ArrayRef<llvm::Value *> DynamicArgs); 4406 4407 /// Emit a slow path cross-DSO CFI check which calls __cfi_slowpath 4408 /// if Cond if false. 4409 void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond, 4410 llvm::ConstantInt *TypeId, llvm::Value *Ptr, 4411 ArrayRef<llvm::Constant *> StaticArgs); 4412 4413 /// Emit a reached-unreachable diagnostic if \p Loc is valid and runtime 4414 /// checking is enabled. Otherwise, just emit an unreachable instruction. 4415 void EmitUnreachable(SourceLocation Loc); 4416 4417 /// Create a basic block that will call the trap intrinsic, and emit a 4418 /// conditional branch to it, for the -ftrapv checks. 4419 void EmitTrapCheck(llvm::Value *Checked); 4420 4421 /// Emit a call to trap or debugtrap and attach function attribute 4422 /// "trap-func-name" if specified. 4423 llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID); 4424 4425 /// Emit a stub for the cross-DSO CFI check function. 4426 void EmitCfiCheckStub(); 4427 4428 /// Emit a cross-DSO CFI failure handling function. 4429 void EmitCfiCheckFail(); 4430 4431 /// Create a check for a function parameter that may potentially be 4432 /// declared as non-null. 4433 void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc, 4434 AbstractCallee AC, unsigned ParmNum); 4435 4436 /// EmitCallArg - Emit a single call argument. 4437 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType); 4438 4439 /// EmitDelegateCallArg - We are performing a delegate call; that 4440 /// is, the current function is delegating to another one. Produce 4441 /// a r-value suitable for passing the given parameter. 4442 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param, 4443 SourceLocation loc); 4444 4445 /// SetFPAccuracy - Set the minimum required accuracy of the given floating 4446 /// point operation, expressed as the maximum relative error in ulp. 4447 void SetFPAccuracy(llvm::Value *Val, float Accuracy); 4448 4449 /// SetFPModel - Control floating point behavior via fp-model settings. 4450 void SetFPModel(); 4451 4452 /// Set the codegen fast-math flags. 4453 void SetFastMathFlags(FPOptions FPFeatures); 4454 4455 private: 4456 llvm::MDNode *getRangeForLoadFromType(QualType Ty); 4457 void EmitReturnOfRValue(RValue RV, QualType Ty); 4458 4459 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New); 4460 4461 llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4> 4462 DeferredReplacements; 4463 4464 /// Set the address of a local variable. 4465 void setAddrOfLocalVar(const VarDecl *VD, Address Addr) { 4466 assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!"); 4467 LocalDeclMap.insert({VD, Addr}); 4468 } 4469 4470 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty 4471 /// from function arguments into \arg Dst. See ABIArgInfo::Expand. 4472 /// 4473 /// \param AI - The first function argument of the expansion. 4474 void ExpandTypeFromArgs(QualType Ty, LValue Dst, 4475 llvm::Function::arg_iterator &AI); 4476 4477 /// ExpandTypeToArgs - Expand an CallArg \arg Arg, with the LLVM type for \arg 4478 /// Ty, into individual arguments on the provided vector \arg IRCallArgs, 4479 /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand. 4480 void ExpandTypeToArgs(QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy, 4481 SmallVectorImpl<llvm::Value *> &IRCallArgs, 4482 unsigned &IRCallArgPos); 4483 4484 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info, 4485 const Expr *InputExpr, std::string &ConstraintStr); 4486 4487 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info, 4488 LValue InputValue, QualType InputType, 4489 std::string &ConstraintStr, 4490 SourceLocation Loc); 4491 4492 /// Attempts to statically evaluate the object size of E. If that 4493 /// fails, emits code to figure the size of E out for us. This is 4494 /// pass_object_size aware. 4495 /// 4496 /// If EmittedExpr is non-null, this will use that instead of re-emitting E. 4497 llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type, 4498 llvm::IntegerType *ResType, 4499 llvm::Value *EmittedE, 4500 bool IsDynamic); 4501 4502 /// Emits the size of E, as required by __builtin_object_size. This 4503 /// function is aware of pass_object_size parameters, and will act accordingly 4504 /// if E is a parameter with the pass_object_size attribute. 4505 llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type, 4506 llvm::IntegerType *ResType, 4507 llvm::Value *EmittedE, 4508 bool IsDynamic); 4509 4510 void emitZeroOrPatternForAutoVarInit(QualType type, const VarDecl &D, 4511 Address Loc); 4512 4513 public: 4514 #ifndef NDEBUG 4515 // Determine whether the given argument is an Objective-C method 4516 // that may have type parameters in its signature. 4517 static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) { 4518 const DeclContext *dc = method->getDeclContext(); 4519 if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) { 4520 return classDecl->getTypeParamListAsWritten(); 4521 } 4522 4523 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) { 4524 return catDecl->getTypeParamList(); 4525 } 4526 4527 return false; 4528 } 4529 4530 template<typename T> 4531 static bool isObjCMethodWithTypeParams(const T *) { return false; } 4532 #endif 4533 4534 enum class EvaluationOrder { 4535 ///! No language constraints on evaluation order. 4536 Default, 4537 ///! Language semantics require left-to-right evaluation. 4538 ForceLeftToRight, 4539 ///! Language semantics require right-to-left evaluation. 4540 ForceRightToLeft 4541 }; 4542 4543 /// EmitCallArgs - Emit call arguments for a function. 4544 template <typename T> 4545 void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo, 4546 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange, 4547 AbstractCallee AC = AbstractCallee(), 4548 unsigned ParamsToSkip = 0, 4549 EvaluationOrder Order = EvaluationOrder::Default) { 4550 SmallVector<QualType, 16> ArgTypes; 4551 CallExpr::const_arg_iterator Arg = ArgRange.begin(); 4552 4553 assert((ParamsToSkip == 0 || CallArgTypeInfo) && 4554 "Can't skip parameters if type info is not provided"); 4555 if (CallArgTypeInfo) { 4556 #ifndef NDEBUG 4557 bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo); 4558 #endif 4559 4560 // First, use the argument types that the type info knows about 4561 for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip, 4562 E = CallArgTypeInfo->param_type_end(); 4563 I != E; ++I, ++Arg) { 4564 assert(Arg != ArgRange.end() && "Running over edge of argument list!"); 4565 assert((isGenericMethod || 4566 ((*I)->isVariablyModifiedType() || 4567 (*I).getNonReferenceType()->isObjCRetainableType() || 4568 getContext() 4569 .getCanonicalType((*I).getNonReferenceType()) 4570 .getTypePtr() == 4571 getContext() 4572 .getCanonicalType((*Arg)->getType()) 4573 .getTypePtr())) && 4574 "type mismatch in call argument!"); 4575 ArgTypes.push_back(*I); 4576 } 4577 } 4578 4579 // Either we've emitted all the call args, or we have a call to variadic 4580 // function. 4581 assert((Arg == ArgRange.end() || !CallArgTypeInfo || 4582 CallArgTypeInfo->isVariadic()) && 4583 "Extra arguments in non-variadic function!"); 4584 4585 // If we still have any arguments, emit them using the type of the argument. 4586 for (auto *A : llvm::make_range(Arg, ArgRange.end())) 4587 ArgTypes.push_back(CallArgTypeInfo ? getVarArgType(A) : A->getType()); 4588 4589 EmitCallArgs(Args, ArgTypes, ArgRange, AC, ParamsToSkip, Order); 4590 } 4591 4592 void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes, 4593 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange, 4594 AbstractCallee AC = AbstractCallee(), 4595 unsigned ParamsToSkip = 0, 4596 EvaluationOrder Order = EvaluationOrder::Default); 4597 4598 /// EmitPointerWithAlignment - Given an expression with a pointer type, 4599 /// emit the value and compute our best estimate of the alignment of the 4600 /// pointee. 4601 /// 4602 /// \param BaseInfo - If non-null, this will be initialized with 4603 /// information about the source of the alignment and the may-alias 4604 /// attribute. Note that this function will conservatively fall back on 4605 /// the type when it doesn't recognize the expression and may-alias will 4606 /// be set to false. 4607 /// 4608 /// One reasonable way to use this information is when there's a language 4609 /// guarantee that the pointer must be aligned to some stricter value, and 4610 /// we're simply trying to ensure that sufficiently obvious uses of under- 4611 /// aligned objects don't get miscompiled; for example, a placement new 4612 /// into the address of a local variable. In such a case, it's quite 4613 /// reasonable to just ignore the returned alignment when it isn't from an 4614 /// explicit source. 4615 Address EmitPointerWithAlignment(const Expr *Addr, 4616 LValueBaseInfo *BaseInfo = nullptr, 4617 TBAAAccessInfo *TBAAInfo = nullptr); 4618 4619 /// If \p E references a parameter with pass_object_size info or a constant 4620 /// array size modifier, emit the object size divided by the size of \p EltTy. 4621 /// Otherwise return null. 4622 llvm::Value *LoadPassedObjectSize(const Expr *E, QualType EltTy); 4623 4624 void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK); 4625 4626 struct MultiVersionResolverOption { 4627 llvm::Function *Function; 4628 FunctionDecl *FD; 4629 struct Conds { 4630 StringRef Architecture; 4631 llvm::SmallVector<StringRef, 8> Features; 4632 4633 Conds(StringRef Arch, ArrayRef<StringRef> Feats) 4634 : Architecture(Arch), Features(Feats.begin(), Feats.end()) {} 4635 } Conditions; 4636 4637 MultiVersionResolverOption(llvm::Function *F, StringRef Arch, 4638 ArrayRef<StringRef> Feats) 4639 : Function(F), Conditions(Arch, Feats) {} 4640 }; 4641 4642 // Emits the body of a multiversion function's resolver. Assumes that the 4643 // options are already sorted in the proper order, with the 'default' option 4644 // last (if it exists). 4645 void EmitMultiVersionResolver(llvm::Function *Resolver, 4646 ArrayRef<MultiVersionResolverOption> Options); 4647 4648 static uint64_t GetX86CpuSupportsMask(ArrayRef<StringRef> FeatureStrs); 4649 4650 private: 4651 QualType getVarArgType(const Expr *Arg); 4652 4653 void EmitDeclMetadata(); 4654 4655 BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType, 4656 const AutoVarEmission &emission); 4657 4658 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst); 4659 4660 llvm::Value *GetValueForARMHint(unsigned BuiltinID); 4661 llvm::Value *EmitX86CpuIs(const CallExpr *E); 4662 llvm::Value *EmitX86CpuIs(StringRef CPUStr); 4663 llvm::Value *EmitX86CpuSupports(const CallExpr *E); 4664 llvm::Value *EmitX86CpuSupports(ArrayRef<StringRef> FeatureStrs); 4665 llvm::Value *EmitX86CpuSupports(uint64_t Mask); 4666 llvm::Value *EmitX86CpuInit(); 4667 llvm::Value *FormResolverCondition(const MultiVersionResolverOption &RO); 4668 }; 4669 4670 inline DominatingLLVMValue::saved_type 4671 DominatingLLVMValue::save(CodeGenFunction &CGF, llvm::Value *value) { 4672 if (!needsSaving(value)) return saved_type(value, false); 4673 4674 // Otherwise, we need an alloca. 4675 auto align = CharUnits::fromQuantity( 4676 CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType())); 4677 Address alloca = 4678 CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save"); 4679 CGF.Builder.CreateStore(value, alloca); 4680 4681 return saved_type(alloca.getPointer(), true); 4682 } 4683 4684 inline llvm::Value *DominatingLLVMValue::restore(CodeGenFunction &CGF, 4685 saved_type value) { 4686 // If the value says it wasn't saved, trust that it's still dominating. 4687 if (!value.getInt()) return value.getPointer(); 4688 4689 // Otherwise, it should be an alloca instruction, as set up in save(). 4690 auto alloca = cast<llvm::AllocaInst>(value.getPointer()); 4691 return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlign()); 4692 } 4693 4694 } // end namespace CodeGen 4695 4696 // Map the LangOption for floating point exception behavior into 4697 // the corresponding enum in the IR. 4698 llvm::fp::ExceptionBehavior 4699 ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind); 4700 } // end namespace clang 4701 4702 #endif 4703