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