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