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