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