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