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