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