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