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