1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This coordinates the per-function state used while generating code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CGBlocks.h" 16 #include "CGCleanup.h" 17 #include "CGCUDARuntime.h" 18 #include "CGCXXABI.h" 19 #include "CGDebugInfo.h" 20 #include "CGOpenMPRuntime.h" 21 #include "CodeGenModule.h" 22 #include "CodeGenPGO.h" 23 #include "TargetInfo.h" 24 #include "clang/AST/ASTContext.h" 25 #include "clang/AST/Decl.h" 26 #include "clang/AST/DeclCXX.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/CodeGen/CGFunctionInfo.h" 31 #include "clang/Frontend/CodeGenOptions.h" 32 #include "llvm/IR/DataLayout.h" 33 #include "llvm/IR/Intrinsics.h" 34 #include "llvm/IR/MDBuilder.h" 35 #include "llvm/IR/Operator.h" 36 using namespace clang; 37 using namespace CodeGen; 38 39 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext) 40 : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()), 41 Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(), 42 CGBuilderInserterTy(this)), 43 CurFn(nullptr), ReturnValue(Address::invalid()), 44 CapturedStmtInfo(nullptr), 45 SanOpts(CGM.getLangOpts().Sanitize), IsSanitizerScope(false), 46 CurFuncIsThunk(false), AutoreleaseResult(false), SawAsmBlock(false), 47 IsOutlinedSEHHelper(false), 48 BlockInfo(nullptr), BlockPointer(nullptr), 49 LambdaThisCaptureField(nullptr), NormalCleanupDest(nullptr), 50 NextCleanupDestIndex(1), FirstBlockInfo(nullptr), EHResumeBlock(nullptr), 51 ExceptionSlot(nullptr), EHSelectorSlot(nullptr), 52 DebugInfo(CGM.getModuleDebugInfo()), 53 DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(nullptr), 54 PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr), 55 CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0), 56 NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr), 57 CXXABIThisValue(nullptr), CXXThisValue(nullptr), 58 CXXStructorImplicitParamDecl(nullptr), 59 CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr), 60 CurLexicalScope(nullptr), TerminateLandingPad(nullptr), 61 TerminateHandler(nullptr), TrapBB(nullptr) { 62 if (!suppressNewContext) 63 CGM.getCXXABI().getMangleContext().startNewFunction(); 64 65 llvm::FastMathFlags FMF; 66 if (CGM.getLangOpts().FastMath) 67 FMF.setUnsafeAlgebra(); 68 if (CGM.getLangOpts().FiniteMathOnly) { 69 FMF.setNoNaNs(); 70 FMF.setNoInfs(); 71 } 72 if (CGM.getCodeGenOpts().NoNaNsFPMath) { 73 FMF.setNoNaNs(); 74 } 75 if (CGM.getCodeGenOpts().NoSignedZeros) { 76 FMF.setNoSignedZeros(); 77 } 78 if (CGM.getCodeGenOpts().ReciprocalMath) { 79 FMF.setAllowReciprocal(); 80 } 81 Builder.SetFastMathFlags(FMF); 82 } 83 84 CodeGenFunction::~CodeGenFunction() { 85 assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup"); 86 87 // If there are any unclaimed block infos, go ahead and destroy them 88 // now. This can happen if IR-gen gets clever and skips evaluating 89 // something. 90 if (FirstBlockInfo) 91 destroyBlockInfos(FirstBlockInfo); 92 93 if (getLangOpts().OpenMP) { 94 CGM.getOpenMPRuntime().functionFinished(*this); 95 } 96 } 97 98 CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T, 99 AlignmentSource *Source) { 100 return getNaturalTypeAlignment(T->getPointeeType(), Source, 101 /*forPointee*/ true); 102 } 103 104 CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T, 105 AlignmentSource *Source, 106 bool forPointeeType) { 107 // Honor alignment typedef attributes even on incomplete types. 108 // We also honor them straight for C++ class types, even as pointees; 109 // there's an expressivity gap here. 110 if (auto TT = T->getAs<TypedefType>()) { 111 if (auto Align = TT->getDecl()->getMaxAlignment()) { 112 if (Source) *Source = AlignmentSource::AttributedType; 113 return getContext().toCharUnitsFromBits(Align); 114 } 115 } 116 117 if (Source) *Source = AlignmentSource::Type; 118 119 CharUnits Alignment; 120 if (!CGM.getCXXABI().isTypeInfoCalculable(T)) { 121 Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best. 122 } else { 123 // For C++ class pointees, we don't know whether we're pointing at a 124 // base or a complete object, so we generally need to use the 125 // non-virtual alignment. 126 const CXXRecordDecl *RD; 127 if (forPointeeType && (RD = T->getAsCXXRecordDecl())) { 128 Alignment = CGM.getClassPointerAlignment(RD); 129 } else { 130 Alignment = getContext().getTypeAlignInChars(T); 131 } 132 133 // Cap to the global maximum type alignment unless the alignment 134 // was somehow explicit on the type. 135 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 136 if (Alignment.getQuantity() > MaxAlign && 137 !getContext().isAlignmentRequired(T)) 138 Alignment = CharUnits::fromQuantity(MaxAlign); 139 } 140 } 141 return Alignment; 142 } 143 144 LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) { 145 AlignmentSource AlignSource; 146 CharUnits Alignment = getNaturalTypeAlignment(T, &AlignSource); 147 return LValue::MakeAddr(Address(V, Alignment), T, getContext(), AlignSource, 148 CGM.getTBAAInfo(T)); 149 } 150 151 /// Given a value of type T* that may not be to a complete object, 152 /// construct an l-value with the natural pointee alignment of T. 153 LValue 154 CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) { 155 AlignmentSource AlignSource; 156 CharUnits Align = getNaturalTypeAlignment(T, &AlignSource, /*pointee*/ true); 157 return MakeAddrLValue(Address(V, Align), T, AlignSource); 158 } 159 160 161 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 162 return CGM.getTypes().ConvertTypeForMem(T); 163 } 164 165 llvm::Type *CodeGenFunction::ConvertType(QualType T) { 166 return CGM.getTypes().ConvertType(T); 167 } 168 169 TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) { 170 type = type.getCanonicalType(); 171 while (true) { 172 switch (type->getTypeClass()) { 173 #define TYPE(name, parent) 174 #define ABSTRACT_TYPE(name, parent) 175 #define NON_CANONICAL_TYPE(name, parent) case Type::name: 176 #define DEPENDENT_TYPE(name, parent) case Type::name: 177 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name: 178 #include "clang/AST/TypeNodes.def" 179 llvm_unreachable("non-canonical or dependent type in IR-generation"); 180 181 case Type::Auto: 182 llvm_unreachable("undeduced auto type in IR-generation"); 183 184 // Various scalar types. 185 case Type::Builtin: 186 case Type::Pointer: 187 case Type::BlockPointer: 188 case Type::LValueReference: 189 case Type::RValueReference: 190 case Type::MemberPointer: 191 case Type::Vector: 192 case Type::ExtVector: 193 case Type::FunctionProto: 194 case Type::FunctionNoProto: 195 case Type::Enum: 196 case Type::ObjCObjectPointer: 197 return TEK_Scalar; 198 199 // Complexes. 200 case Type::Complex: 201 return TEK_Complex; 202 203 // Arrays, records, and Objective-C objects. 204 case Type::ConstantArray: 205 case Type::IncompleteArray: 206 case Type::VariableArray: 207 case Type::Record: 208 case Type::ObjCObject: 209 case Type::ObjCInterface: 210 return TEK_Aggregate; 211 212 // We operate on atomic values according to their underlying type. 213 case Type::Atomic: 214 type = cast<AtomicType>(type)->getValueType(); 215 continue; 216 } 217 llvm_unreachable("unknown type kind!"); 218 } 219 } 220 221 llvm::DebugLoc CodeGenFunction::EmitReturnBlock() { 222 // For cleanliness, we try to avoid emitting the return block for 223 // simple cases. 224 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 225 226 if (CurBB) { 227 assert(!CurBB->getTerminator() && "Unexpected terminated block."); 228 229 // We have a valid insert point, reuse it if it is empty or there are no 230 // explicit jumps to the return block. 231 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) { 232 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB); 233 delete ReturnBlock.getBlock(); 234 } else 235 EmitBlock(ReturnBlock.getBlock()); 236 return llvm::DebugLoc(); 237 } 238 239 // Otherwise, if the return block is the target of a single direct 240 // branch then we can just put the code in that block instead. This 241 // cleans up functions which started with a unified return block. 242 if (ReturnBlock.getBlock()->hasOneUse()) { 243 llvm::BranchInst *BI = 244 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin()); 245 if (BI && BI->isUnconditional() && 246 BI->getSuccessor(0) == ReturnBlock.getBlock()) { 247 // Record/return the DebugLoc of the simple 'return' expression to be used 248 // later by the actual 'ret' instruction. 249 llvm::DebugLoc Loc = BI->getDebugLoc(); 250 Builder.SetInsertPoint(BI->getParent()); 251 BI->eraseFromParent(); 252 delete ReturnBlock.getBlock(); 253 return Loc; 254 } 255 } 256 257 // FIXME: We are at an unreachable point, there is no reason to emit the block 258 // unless it has uses. However, we still need a place to put the debug 259 // region.end for now. 260 261 EmitBlock(ReturnBlock.getBlock()); 262 return llvm::DebugLoc(); 263 } 264 265 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) { 266 if (!BB) return; 267 if (!BB->use_empty()) 268 return CGF.CurFn->getBasicBlockList().push_back(BB); 269 delete BB; 270 } 271 272 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 273 assert(BreakContinueStack.empty() && 274 "mismatched push/pop in break/continue stack!"); 275 276 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0 277 && NumSimpleReturnExprs == NumReturnExprs 278 && ReturnBlock.getBlock()->use_empty(); 279 // Usually the return expression is evaluated before the cleanup 280 // code. If the function contains only a simple return statement, 281 // such as a constant, the location before the cleanup code becomes 282 // the last useful breakpoint in the function, because the simple 283 // return expression will be evaluated after the cleanup code. To be 284 // safe, set the debug location for cleanup code to the location of 285 // the return statement. Otherwise the cleanup code should be at the 286 // end of the function's lexical scope. 287 // 288 // If there are multiple branches to the return block, the branch 289 // instructions will get the location of the return statements and 290 // all will be fine. 291 if (CGDebugInfo *DI = getDebugInfo()) { 292 if (OnlySimpleReturnStmts) 293 DI->EmitLocation(Builder, LastStopPoint); 294 else 295 DI->EmitLocation(Builder, EndLoc); 296 } 297 298 // Pop any cleanups that might have been associated with the 299 // parameters. Do this in whatever block we're currently in; it's 300 // important to do this before we enter the return block or return 301 // edges will be *really* confused. 302 bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth; 303 bool HasOnlyLifetimeMarkers = 304 HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth); 305 bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers; 306 if (HasCleanups) { 307 // Make sure the line table doesn't jump back into the body for 308 // the ret after it's been at EndLoc. 309 if (CGDebugInfo *DI = getDebugInfo()) 310 if (OnlySimpleReturnStmts) 311 DI->EmitLocation(Builder, EndLoc); 312 313 PopCleanupBlocks(PrologueCleanupDepth); 314 } 315 316 // Emit function epilog (to return). 317 llvm::DebugLoc Loc = EmitReturnBlock(); 318 319 if (ShouldInstrumentFunction()) 320 EmitFunctionInstrumentation("__cyg_profile_func_exit"); 321 322 // Emit debug descriptor for function end. 323 if (CGDebugInfo *DI = getDebugInfo()) 324 DI->EmitFunctionEnd(Builder); 325 326 // Reset the debug location to that of the simple 'return' expression, if any 327 // rather than that of the end of the function's scope '}'. 328 ApplyDebugLocation AL(*this, Loc); 329 EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc); 330 EmitEndEHSpec(CurCodeDecl); 331 332 assert(EHStack.empty() && 333 "did not remove all scopes from cleanup stack!"); 334 335 // If someone did an indirect goto, emit the indirect goto block at the end of 336 // the function. 337 if (IndirectBranch) { 338 EmitBlock(IndirectBranch->getParent()); 339 Builder.ClearInsertionPoint(); 340 } 341 342 // If some of our locals escaped, insert a call to llvm.localescape in the 343 // entry block. 344 if (!EscapedLocals.empty()) { 345 // Invert the map from local to index into a simple vector. There should be 346 // no holes. 347 SmallVector<llvm::Value *, 4> EscapeArgs; 348 EscapeArgs.resize(EscapedLocals.size()); 349 for (auto &Pair : EscapedLocals) 350 EscapeArgs[Pair.second] = Pair.first; 351 llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration( 352 &CGM.getModule(), llvm::Intrinsic::localescape); 353 CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs); 354 } 355 356 // Remove the AllocaInsertPt instruction, which is just a convenience for us. 357 llvm::Instruction *Ptr = AllocaInsertPt; 358 AllocaInsertPt = nullptr; 359 Ptr->eraseFromParent(); 360 361 // If someone took the address of a label but never did an indirect goto, we 362 // made a zero entry PHI node, which is illegal, zap it now. 363 if (IndirectBranch) { 364 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress()); 365 if (PN->getNumIncomingValues() == 0) { 366 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType())); 367 PN->eraseFromParent(); 368 } 369 } 370 371 EmitIfUsed(*this, EHResumeBlock); 372 EmitIfUsed(*this, TerminateLandingPad); 373 EmitIfUsed(*this, TerminateHandler); 374 EmitIfUsed(*this, UnreachableBlock); 375 376 if (CGM.getCodeGenOpts().EmitDeclMetadata) 377 EmitDeclMetadata(); 378 379 for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator 380 I = DeferredReplacements.begin(), 381 E = DeferredReplacements.end(); 382 I != E; ++I) { 383 I->first->replaceAllUsesWith(I->second); 384 I->first->eraseFromParent(); 385 } 386 } 387 388 /// ShouldInstrumentFunction - Return true if the current function should be 389 /// instrumented with __cyg_profile_func_* calls 390 bool CodeGenFunction::ShouldInstrumentFunction() { 391 if (!CGM.getCodeGenOpts().InstrumentFunctions) 392 return false; 393 if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) 394 return false; 395 return true; 396 } 397 398 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 399 /// instrumentation function with the current function and the call site, if 400 /// function instrumentation is enabled. 401 void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) { 402 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site); 403 llvm::PointerType *PointerTy = Int8PtrTy; 404 llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy }; 405 llvm::FunctionType *FunctionTy = 406 llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false); 407 408 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn); 409 llvm::CallInst *CallSite = Builder.CreateCall( 410 CGM.getIntrinsic(llvm::Intrinsic::returnaddress), 411 llvm::ConstantInt::get(Int32Ty, 0), 412 "callsite"); 413 414 llvm::Value *args[] = { 415 llvm::ConstantExpr::getBitCast(CurFn, PointerTy), 416 CallSite 417 }; 418 419 EmitNounwindRuntimeCall(F, args); 420 } 421 422 void CodeGenFunction::EmitMCountInstrumentation() { 423 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false); 424 425 llvm::Constant *MCountFn = 426 CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName()); 427 EmitNounwindRuntimeCall(MCountFn); 428 } 429 430 // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument 431 // information in the program executable. The argument information stored 432 // includes the argument name, its type, the address and access qualifiers used. 433 static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn, 434 CodeGenModule &CGM, llvm::LLVMContext &Context, 435 SmallVector<llvm::Metadata *, 5> &kernelMDArgs, 436 CGBuilderTy &Builder, ASTContext &ASTCtx) { 437 // Create MDNodes that represent the kernel arg metadata. 438 // Each MDNode is a list in the form of "key", N number of values which is 439 // the same number of values as their are kernel arguments. 440 441 const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy(); 442 443 // MDNode for the kernel argument address space qualifiers. 444 SmallVector<llvm::Metadata *, 8> addressQuals; 445 addressQuals.push_back(llvm::MDString::get(Context, "kernel_arg_addr_space")); 446 447 // MDNode for the kernel argument access qualifiers (images only). 448 SmallVector<llvm::Metadata *, 8> accessQuals; 449 accessQuals.push_back(llvm::MDString::get(Context, "kernel_arg_access_qual")); 450 451 // MDNode for the kernel argument type names. 452 SmallVector<llvm::Metadata *, 8> argTypeNames; 453 argTypeNames.push_back(llvm::MDString::get(Context, "kernel_arg_type")); 454 455 // MDNode for the kernel argument base type names. 456 SmallVector<llvm::Metadata *, 8> argBaseTypeNames; 457 argBaseTypeNames.push_back( 458 llvm::MDString::get(Context, "kernel_arg_base_type")); 459 460 // MDNode for the kernel argument type qualifiers. 461 SmallVector<llvm::Metadata *, 8> argTypeQuals; 462 argTypeQuals.push_back(llvm::MDString::get(Context, "kernel_arg_type_qual")); 463 464 // MDNode for the kernel argument names. 465 SmallVector<llvm::Metadata *, 8> argNames; 466 argNames.push_back(llvm::MDString::get(Context, "kernel_arg_name")); 467 468 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 469 const ParmVarDecl *parm = FD->getParamDecl(i); 470 QualType ty = parm->getType(); 471 std::string typeQuals; 472 473 if (ty->isPointerType()) { 474 QualType pointeeTy = ty->getPointeeType(); 475 476 // Get address qualifier. 477 addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32( 478 ASTCtx.getTargetAddressSpace(pointeeTy.getAddressSpace())))); 479 480 // Get argument type name. 481 std::string typeName = 482 pointeeTy.getUnqualifiedType().getAsString(Policy) + "*"; 483 484 // Turn "unsigned type" to "utype" 485 std::string::size_type pos = typeName.find("unsigned"); 486 if (pointeeTy.isCanonical() && pos != std::string::npos) 487 typeName.erase(pos+1, 8); 488 489 argTypeNames.push_back(llvm::MDString::get(Context, typeName)); 490 491 std::string baseTypeName = 492 pointeeTy.getUnqualifiedType().getCanonicalType().getAsString( 493 Policy) + 494 "*"; 495 496 // Turn "unsigned type" to "utype" 497 pos = baseTypeName.find("unsigned"); 498 if (pos != std::string::npos) 499 baseTypeName.erase(pos+1, 8); 500 501 argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName)); 502 503 // Get argument type qualifiers: 504 if (ty.isRestrictQualified()) 505 typeQuals = "restrict"; 506 if (pointeeTy.isConstQualified() || 507 (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) 508 typeQuals += typeQuals.empty() ? "const" : " const"; 509 if (pointeeTy.isVolatileQualified()) 510 typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 511 } else { 512 uint32_t AddrSpc = 0; 513 if (ty->isImageType()) 514 AddrSpc = 515 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global); 516 517 addressQuals.push_back( 518 llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc))); 519 520 // Get argument type name. 521 std::string typeName = ty.getUnqualifiedType().getAsString(Policy); 522 523 // Turn "unsigned type" to "utype" 524 std::string::size_type pos = typeName.find("unsigned"); 525 if (ty.isCanonical() && pos != std::string::npos) 526 typeName.erase(pos+1, 8); 527 528 argTypeNames.push_back(llvm::MDString::get(Context, typeName)); 529 530 std::string baseTypeName = 531 ty.getUnqualifiedType().getCanonicalType().getAsString(Policy); 532 533 // Turn "unsigned type" to "utype" 534 pos = baseTypeName.find("unsigned"); 535 if (pos != std::string::npos) 536 baseTypeName.erase(pos+1, 8); 537 538 argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName)); 539 540 // Get argument type qualifiers: 541 if (ty.isConstQualified()) 542 typeQuals = "const"; 543 if (ty.isVolatileQualified()) 544 typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 545 } 546 547 argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals)); 548 549 // Get image access qualifier: 550 if (ty->isImageType()) { 551 const OpenCLImageAccessAttr *A = parm->getAttr<OpenCLImageAccessAttr>(); 552 if (A && A->isWriteOnly()) 553 accessQuals.push_back(llvm::MDString::get(Context, "write_only")); 554 else 555 accessQuals.push_back(llvm::MDString::get(Context, "read_only")); 556 // FIXME: what about read_write? 557 } else 558 accessQuals.push_back(llvm::MDString::get(Context, "none")); 559 560 // Get argument name. 561 argNames.push_back(llvm::MDString::get(Context, parm->getName())); 562 } 563 564 kernelMDArgs.push_back(llvm::MDNode::get(Context, addressQuals)); 565 kernelMDArgs.push_back(llvm::MDNode::get(Context, accessQuals)); 566 kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames)); 567 kernelMDArgs.push_back(llvm::MDNode::get(Context, argBaseTypeNames)); 568 kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals)); 569 if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata) 570 kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames)); 571 } 572 573 void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD, 574 llvm::Function *Fn) 575 { 576 if (!FD->hasAttr<OpenCLKernelAttr>()) 577 return; 578 579 llvm::LLVMContext &Context = getLLVMContext(); 580 581 SmallVector<llvm::Metadata *, 5> kernelMDArgs; 582 kernelMDArgs.push_back(llvm::ConstantAsMetadata::get(Fn)); 583 584 GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs, Builder, 585 getContext()); 586 587 if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) { 588 QualType hintQTy = A->getTypeHint(); 589 const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>(); 590 bool isSignedInteger = 591 hintQTy->isSignedIntegerType() || 592 (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType()); 593 llvm::Metadata *attrMDArgs[] = { 594 llvm::MDString::get(Context, "vec_type_hint"), 595 llvm::ConstantAsMetadata::get(llvm::UndefValue::get( 596 CGM.getTypes().ConvertType(A->getTypeHint()))), 597 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 598 llvm::IntegerType::get(Context, 32), 599 llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))}; 600 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs)); 601 } 602 603 if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) { 604 llvm::Metadata *attrMDArgs[] = { 605 llvm::MDString::get(Context, "work_group_size_hint"), 606 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())), 607 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())), 608 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))}; 609 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs)); 610 } 611 612 if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) { 613 llvm::Metadata *attrMDArgs[] = { 614 llvm::MDString::get(Context, "reqd_work_group_size"), 615 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())), 616 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())), 617 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))}; 618 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs)); 619 } 620 621 llvm::MDNode *kernelMDNode = llvm::MDNode::get(Context, kernelMDArgs); 622 llvm::NamedMDNode *OpenCLKernelMetadata = 623 CGM.getModule().getOrInsertNamedMetadata("opencl.kernels"); 624 OpenCLKernelMetadata->addOperand(kernelMDNode); 625 } 626 627 /// Determine whether the function F ends with a return stmt. 628 static bool endsWithReturn(const Decl* F) { 629 const Stmt *Body = nullptr; 630 if (auto *FD = dyn_cast_or_null<FunctionDecl>(F)) 631 Body = FD->getBody(); 632 else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F)) 633 Body = OMD->getBody(); 634 635 if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) { 636 auto LastStmt = CS->body_rbegin(); 637 if (LastStmt != CS->body_rend()) 638 return isa<ReturnStmt>(*LastStmt); 639 } 640 return false; 641 } 642 643 void CodeGenFunction::StartFunction(GlobalDecl GD, 644 QualType RetTy, 645 llvm::Function *Fn, 646 const CGFunctionInfo &FnInfo, 647 const FunctionArgList &Args, 648 SourceLocation Loc, 649 SourceLocation StartLoc) { 650 assert(!CurFn && 651 "Do not use a CodeGenFunction object for more than one function"); 652 653 const Decl *D = GD.getDecl(); 654 655 DidCallStackSave = false; 656 CurCodeDecl = D; 657 CurFuncDecl = (D ? D->getNonClosureContext() : nullptr); 658 FnRetTy = RetTy; 659 CurFn = Fn; 660 CurFnInfo = &FnInfo; 661 assert(CurFn->isDeclaration() && "Function already has body?"); 662 663 if (CGM.isInSanitizerBlacklist(Fn, Loc)) 664 SanOpts.clear(); 665 666 if (D) { 667 // Apply the no_sanitize* attributes to SanOpts. 668 for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) 669 SanOpts.Mask &= ~Attr->getMask(); 670 } 671 672 // Apply sanitizer attributes to the function. 673 if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress)) 674 Fn->addFnAttr(llvm::Attribute::SanitizeAddress); 675 if (SanOpts.has(SanitizerKind::Thread)) 676 Fn->addFnAttr(llvm::Attribute::SanitizeThread); 677 if (SanOpts.has(SanitizerKind::Memory)) 678 Fn->addFnAttr(llvm::Attribute::SanitizeMemory); 679 if (SanOpts.has(SanitizerKind::SafeStack)) 680 Fn->addFnAttr(llvm::Attribute::SafeStack); 681 682 // Pass inline keyword to optimizer if it appears explicitly on any 683 // declaration. Also, in the case of -fno-inline attach NoInline 684 // attribute to all function that are not marked AlwaysInline. 685 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 686 if (!CGM.getCodeGenOpts().NoInline) { 687 for (auto RI : FD->redecls()) 688 if (RI->isInlineSpecified()) { 689 Fn->addFnAttr(llvm::Attribute::InlineHint); 690 break; 691 } 692 } else if (!FD->hasAttr<AlwaysInlineAttr>()) 693 Fn->addFnAttr(llvm::Attribute::NoInline); 694 } 695 696 if (getLangOpts().OpenCL) { 697 // Add metadata for a kernel function. 698 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 699 EmitOpenCLKernelMetadata(FD, Fn); 700 } 701 702 // If we are checking function types, emit a function type signature as 703 // prologue data. 704 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) { 705 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 706 if (llvm::Constant *PrologueSig = 707 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) { 708 llvm::Constant *FTRTTIConst = 709 CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true); 710 llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst }; 711 llvm::Constant *PrologueStructConst = 712 llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true); 713 Fn->setPrologueData(PrologueStructConst); 714 } 715 } 716 } 717 718 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 719 720 // Create a marker to make it easy to insert allocas into the entryblock 721 // later. Don't create this with the builder, because we don't want it 722 // folded. 723 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty); 724 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB); 725 if (Builder.isNamePreserving()) 726 AllocaInsertPt->setName("allocapt"); 727 728 ReturnBlock = getJumpDestInCurrentScope("return"); 729 730 Builder.SetInsertPoint(EntryBB); 731 732 // Emit subprogram debug descriptor. 733 if (CGDebugInfo *DI = getDebugInfo()) { 734 SmallVector<QualType, 16> ArgTypes; 735 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 736 i != e; ++i) { 737 ArgTypes.push_back((*i)->getType()); 738 } 739 740 QualType FnType = 741 getContext().getFunctionType(RetTy, ArgTypes, 742 FunctionProtoType::ExtProtoInfo()); 743 DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder); 744 } 745 746 if (ShouldInstrumentFunction()) 747 EmitFunctionInstrumentation("__cyg_profile_func_enter"); 748 749 if (CGM.getCodeGenOpts().InstrumentForProfiling) 750 EmitMCountInstrumentation(); 751 752 if (RetTy->isVoidType()) { 753 // Void type; nothing to return. 754 ReturnValue = Address::invalid(); 755 756 // Count the implicit return. 757 if (!endsWithReturn(D)) 758 ++NumReturnExprs; 759 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect && 760 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) { 761 // Indirect aggregate return; emit returned value directly into sret slot. 762 // This reduces code size, and affects correctness in C++. 763 auto AI = CurFn->arg_begin(); 764 if (CurFnInfo->getReturnInfo().isSRetAfterThis()) 765 ++AI; 766 ReturnValue = Address(AI, CurFnInfo->getReturnInfo().getIndirectAlign()); 767 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca && 768 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) { 769 // Load the sret pointer from the argument struct and return into that. 770 unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex(); 771 llvm::Function::arg_iterator EI = CurFn->arg_end(); 772 --EI; 773 llvm::Value *Addr = Builder.CreateStructGEP(nullptr, EI, Idx); 774 Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result"); 775 ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy)); 776 } else { 777 ReturnValue = CreateIRTemp(RetTy, "retval"); 778 779 // Tell the epilog emitter to autorelease the result. We do this 780 // now so that various specialized functions can suppress it 781 // during their IR-generation. 782 if (getLangOpts().ObjCAutoRefCount && 783 !CurFnInfo->isReturnsRetained() && 784 RetTy->isObjCRetainableType()) 785 AutoreleaseResult = true; 786 } 787 788 EmitStartEHSpec(CurCodeDecl); 789 790 PrologueCleanupDepth = EHStack.stable_begin(); 791 EmitFunctionProlog(*CurFnInfo, CurFn, Args); 792 793 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) { 794 CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 795 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D); 796 if (MD->getParent()->isLambda() && 797 MD->getOverloadedOperator() == OO_Call) { 798 // We're in a lambda; figure out the captures. 799 MD->getParent()->getCaptureFields(LambdaCaptureFields, 800 LambdaThisCaptureField); 801 if (LambdaThisCaptureField) { 802 // If this lambda captures this, load it. 803 LValue ThisLValue = EmitLValueForLambdaField(LambdaThisCaptureField); 804 CXXThisValue = EmitLoadOfLValue(ThisLValue, 805 SourceLocation()).getScalarVal(); 806 } 807 for (auto *FD : MD->getParent()->fields()) { 808 if (FD->hasCapturedVLAType()) { 809 auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD), 810 SourceLocation()).getScalarVal(); 811 auto VAT = FD->getCapturedVLAType(); 812 VLASizeMap[VAT->getSizeExpr()] = ExprArg; 813 } 814 } 815 } else { 816 // Not in a lambda; just use 'this' from the method. 817 // FIXME: Should we generate a new load for each use of 'this'? The 818 // fast register allocator would be happier... 819 CXXThisValue = CXXABIThisValue; 820 } 821 } 822 823 // If any of the arguments have a variably modified type, make sure to 824 // emit the type size. 825 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 826 i != e; ++i) { 827 const VarDecl *VD = *i; 828 829 // Dig out the type as written from ParmVarDecls; it's unclear whether 830 // the standard (C99 6.9.1p10) requires this, but we're following the 831 // precedent set by gcc. 832 QualType Ty; 833 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) 834 Ty = PVD->getOriginalType(); 835 else 836 Ty = VD->getType(); 837 838 if (Ty->isVariablyModifiedType()) 839 EmitVariablyModifiedType(Ty); 840 } 841 // Emit a location at the end of the prologue. 842 if (CGDebugInfo *DI = getDebugInfo()) 843 DI->EmitLocation(Builder, StartLoc); 844 } 845 846 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args, 847 const Stmt *Body) { 848 incrementProfileCounter(Body); 849 if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body)) 850 EmitCompoundStmtWithoutScope(*S); 851 else 852 EmitStmt(Body); 853 } 854 855 /// When instrumenting to collect profile data, the counts for some blocks 856 /// such as switch cases need to not include the fall-through counts, so 857 /// emit a branch around the instrumentation code. When not instrumenting, 858 /// this just calls EmitBlock(). 859 void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB, 860 const Stmt *S) { 861 llvm::BasicBlock *SkipCountBB = nullptr; 862 if (HaveInsertPoint() && CGM.getCodeGenOpts().ProfileInstrGenerate) { 863 // When instrumenting for profiling, the fallthrough to certain 864 // statements needs to skip over the instrumentation code so that we 865 // get an accurate count. 866 SkipCountBB = createBasicBlock("skipcount"); 867 EmitBranch(SkipCountBB); 868 } 869 EmitBlock(BB); 870 uint64_t CurrentCount = getCurrentProfileCount(); 871 incrementProfileCounter(S); 872 setCurrentProfileCount(getCurrentProfileCount() + CurrentCount); 873 if (SkipCountBB) 874 EmitBlock(SkipCountBB); 875 } 876 877 /// Tries to mark the given function nounwind based on the 878 /// non-existence of any throwing calls within it. We believe this is 879 /// lightweight enough to do at -O0. 880 static void TryMarkNoThrow(llvm::Function *F) { 881 // LLVM treats 'nounwind' on a function as part of the type, so we 882 // can't do this on functions that can be overwritten. 883 if (F->mayBeOverridden()) return; 884 885 for (llvm::BasicBlock &BB : *F) 886 for (llvm::Instruction &I : BB) 887 if (I.mayThrow()) 888 return; 889 890 F->setDoesNotThrow(); 891 } 892 893 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn, 894 const CGFunctionInfo &FnInfo) { 895 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 896 897 // Check if we should generate debug info for this function. 898 if (FD->hasAttr<NoDebugAttr>()) 899 DebugInfo = nullptr; // disable debug info indefinitely for this function 900 901 FunctionArgList Args; 902 QualType ResTy = FD->getReturnType(); 903 904 CurGD = GD; 905 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 906 if (MD && MD->isInstance()) { 907 if (CGM.getCXXABI().HasThisReturn(GD)) 908 ResTy = MD->getThisType(getContext()); 909 else if (CGM.getCXXABI().hasMostDerivedReturn(GD)) 910 ResTy = CGM.getContext().VoidPtrTy; 911 CGM.getCXXABI().buildThisParam(*this, Args); 912 } 913 914 Args.append(FD->param_begin(), FD->param_end()); 915 916 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))) 917 CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args); 918 919 SourceRange BodyRange; 920 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange(); 921 CurEHLocation = BodyRange.getEnd(); 922 923 // Use the location of the start of the function to determine where 924 // the function definition is located. By default use the location 925 // of the declaration as the location for the subprogram. A function 926 // may lack a declaration in the source code if it is created by code 927 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk). 928 SourceLocation Loc = FD->getLocation(); 929 930 // If this is a function specialization then use the pattern body 931 // as the location for the function. 932 if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern()) 933 if (SpecDecl->hasBody(SpecDecl)) 934 Loc = SpecDecl->getLocation(); 935 936 // Emit the standard function prologue. 937 StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin()); 938 939 // Generate the body of the function. 940 PGO.checkGlobalDecl(GD); 941 PGO.assignRegionCounters(GD.getDecl(), CurFn); 942 if (isa<CXXDestructorDecl>(FD)) 943 EmitDestructorBody(Args); 944 else if (isa<CXXConstructorDecl>(FD)) 945 EmitConstructorBody(Args); 946 else if (getLangOpts().CUDA && 947 !getLangOpts().CUDAIsDevice && 948 FD->hasAttr<CUDAGlobalAttr>()) 949 CGM.getCUDARuntime().emitDeviceStub(*this, Args); 950 else if (isa<CXXConversionDecl>(FD) && 951 cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) { 952 // The lambda conversion to block pointer is special; the semantics can't be 953 // expressed in the AST, so IRGen needs to special-case it. 954 EmitLambdaToBlockPointerBody(Args); 955 } else if (isa<CXXMethodDecl>(FD) && 956 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) { 957 // The lambda static invoker function is special, because it forwards or 958 // clones the body of the function call operator (but is actually static). 959 EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD)); 960 } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) && 961 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() || 962 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) { 963 // Implicit copy-assignment gets the same special treatment as implicit 964 // copy-constructors. 965 emitImplicitAssignmentOperatorBody(Args); 966 } else if (Stmt *Body = FD->getBody()) { 967 EmitFunctionBody(Args, Body); 968 } else 969 llvm_unreachable("no definition for emitted function"); 970 971 // C++11 [stmt.return]p2: 972 // Flowing off the end of a function [...] results in undefined behavior in 973 // a value-returning function. 974 // C11 6.9.1p12: 975 // If the '}' that terminates a function is reached, and the value of the 976 // function call is used by the caller, the behavior is undefined. 977 if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock && 978 !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) { 979 if (SanOpts.has(SanitizerKind::Return)) { 980 SanitizerScope SanScope(this); 981 llvm::Value *IsFalse = Builder.getFalse(); 982 EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return), 983 "missing_return", EmitCheckSourceLocation(FD->getLocation()), 984 None); 985 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) { 986 EmitTrapCall(llvm::Intrinsic::trap); 987 } 988 Builder.CreateUnreachable(); 989 Builder.ClearInsertionPoint(); 990 } 991 992 // Emit the standard function epilogue. 993 FinishFunction(BodyRange.getEnd()); 994 995 // If we haven't marked the function nothrow through other means, do 996 // a quick pass now to see if we can. 997 if (!CurFn->doesNotThrow()) 998 TryMarkNoThrow(CurFn); 999 } 1000 1001 /// ContainsLabel - Return true if the statement contains a label in it. If 1002 /// this statement is not executed normally, it not containing a label means 1003 /// that we can just remove the code. 1004 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 1005 // Null statement, not a label! 1006 if (!S) return false; 1007 1008 // If this is a label, we have to emit the code, consider something like: 1009 // if (0) { ... foo: bar(); } goto foo; 1010 // 1011 // TODO: If anyone cared, we could track __label__'s, since we know that you 1012 // can't jump to one from outside their declared region. 1013 if (isa<LabelStmt>(S)) 1014 return true; 1015 1016 // If this is a case/default statement, and we haven't seen a switch, we have 1017 // to emit the code. 1018 if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 1019 return true; 1020 1021 // If this is a switch statement, we want to ignore cases below it. 1022 if (isa<SwitchStmt>(S)) 1023 IgnoreCaseStmts = true; 1024 1025 // Scan subexpressions for verboten labels. 1026 for (const Stmt *SubStmt : S->children()) 1027 if (ContainsLabel(SubStmt, IgnoreCaseStmts)) 1028 return true; 1029 1030 return false; 1031 } 1032 1033 /// containsBreak - Return true if the statement contains a break out of it. 1034 /// If the statement (recursively) contains a switch or loop with a break 1035 /// inside of it, this is fine. 1036 bool CodeGenFunction::containsBreak(const Stmt *S) { 1037 // Null statement, not a label! 1038 if (!S) return false; 1039 1040 // If this is a switch or loop that defines its own break scope, then we can 1041 // include it and anything inside of it. 1042 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) || 1043 isa<ForStmt>(S)) 1044 return false; 1045 1046 if (isa<BreakStmt>(S)) 1047 return true; 1048 1049 // Scan subexpressions for verboten breaks. 1050 for (const Stmt *SubStmt : S->children()) 1051 if (containsBreak(SubStmt)) 1052 return true; 1053 1054 return false; 1055 } 1056 1057 1058 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 1059 /// to a constant, or if it does but contains a label, return false. If it 1060 /// constant folds return true and set the boolean result in Result. 1061 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 1062 bool &ResultBool) { 1063 llvm::APSInt ResultInt; 1064 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt)) 1065 return false; 1066 1067 ResultBool = ResultInt.getBoolValue(); 1068 return true; 1069 } 1070 1071 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 1072 /// to a constant, or if it does but contains a label, return false. If it 1073 /// constant folds return true and set the folded value. 1074 bool CodeGenFunction:: 1075 ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &ResultInt) { 1076 // FIXME: Rename and handle conversion of other evaluatable things 1077 // to bool. 1078 llvm::APSInt Int; 1079 if (!Cond->EvaluateAsInt(Int, getContext())) 1080 return false; // Not foldable, not integer or not fully evaluatable. 1081 1082 if (CodeGenFunction::ContainsLabel(Cond)) 1083 return false; // Contains a label. 1084 1085 ResultInt = Int; 1086 return true; 1087 } 1088 1089 1090 1091 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 1092 /// statement) to the specified blocks. Based on the condition, this might try 1093 /// to simplify the codegen of the conditional based on the branch. 1094 /// 1095 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 1096 llvm::BasicBlock *TrueBlock, 1097 llvm::BasicBlock *FalseBlock, 1098 uint64_t TrueCount) { 1099 Cond = Cond->IgnoreParens(); 1100 1101 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 1102 1103 // Handle X && Y in a condition. 1104 if (CondBOp->getOpcode() == BO_LAnd) { 1105 // If we have "1 && X", simplify the code. "0 && X" would have constant 1106 // folded if the case was simple enough. 1107 bool ConstantBool = false; 1108 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 1109 ConstantBool) { 1110 // br(1 && X) -> br(X). 1111 incrementProfileCounter(CondBOp); 1112 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, 1113 TrueCount); 1114 } 1115 1116 // If we have "X && 1", simplify the code to use an uncond branch. 1117 // "X && 0" would have been constant folded to 0. 1118 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 1119 ConstantBool) { 1120 // br(X && 1) -> br(X). 1121 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock, 1122 TrueCount); 1123 } 1124 1125 // Emit the LHS as a conditional. If the LHS conditional is false, we 1126 // want to jump to the FalseBlock. 1127 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 1128 // The counter tells us how often we evaluate RHS, and all of TrueCount 1129 // can be propagated to that branch. 1130 uint64_t RHSCount = getProfileCount(CondBOp->getRHS()); 1131 1132 ConditionalEvaluation eval(*this); 1133 { 1134 ApplyDebugLocation DL(*this, Cond); 1135 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount); 1136 EmitBlock(LHSTrue); 1137 } 1138 1139 incrementProfileCounter(CondBOp); 1140 setCurrentProfileCount(getProfileCount(CondBOp->getRHS())); 1141 1142 // Any temporaries created here are conditional. 1143 eval.begin(*this); 1144 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount); 1145 eval.end(*this); 1146 1147 return; 1148 } 1149 1150 if (CondBOp->getOpcode() == BO_LOr) { 1151 // If we have "0 || X", simplify the code. "1 || X" would have constant 1152 // folded if the case was simple enough. 1153 bool ConstantBool = false; 1154 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 1155 !ConstantBool) { 1156 // br(0 || X) -> br(X). 1157 incrementProfileCounter(CondBOp); 1158 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, 1159 TrueCount); 1160 } 1161 1162 // If we have "X || 0", simplify the code to use an uncond branch. 1163 // "X || 1" would have been constant folded to 1. 1164 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 1165 !ConstantBool) { 1166 // br(X || 0) -> br(X). 1167 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock, 1168 TrueCount); 1169 } 1170 1171 // Emit the LHS as a conditional. If the LHS conditional is true, we 1172 // want to jump to the TrueBlock. 1173 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 1174 // We have the count for entry to the RHS and for the whole expression 1175 // being true, so we can divy up True count between the short circuit and 1176 // the RHS. 1177 uint64_t LHSCount = 1178 getCurrentProfileCount() - getProfileCount(CondBOp->getRHS()); 1179 uint64_t RHSCount = TrueCount - LHSCount; 1180 1181 ConditionalEvaluation eval(*this); 1182 { 1183 ApplyDebugLocation DL(*this, Cond); 1184 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount); 1185 EmitBlock(LHSFalse); 1186 } 1187 1188 incrementProfileCounter(CondBOp); 1189 setCurrentProfileCount(getProfileCount(CondBOp->getRHS())); 1190 1191 // Any temporaries created here are conditional. 1192 eval.begin(*this); 1193 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount); 1194 1195 eval.end(*this); 1196 1197 return; 1198 } 1199 } 1200 1201 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 1202 // br(!x, t, f) -> br(x, f, t) 1203 if (CondUOp->getOpcode() == UO_LNot) { 1204 // Negate the count. 1205 uint64_t FalseCount = getCurrentProfileCount() - TrueCount; 1206 // Negate the condition and swap the destination blocks. 1207 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock, 1208 FalseCount); 1209 } 1210 } 1211 1212 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 1213 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 1214 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 1215 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 1216 1217 ConditionalEvaluation cond(*this); 1218 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock, 1219 getProfileCount(CondOp)); 1220 1221 // When computing PGO branch weights, we only know the overall count for 1222 // the true block. This code is essentially doing tail duplication of the 1223 // naive code-gen, introducing new edges for which counts are not 1224 // available. Divide the counts proportionally between the LHS and RHS of 1225 // the conditional operator. 1226 uint64_t LHSScaledTrueCount = 0; 1227 if (TrueCount) { 1228 double LHSRatio = 1229 getProfileCount(CondOp) / (double)getCurrentProfileCount(); 1230 LHSScaledTrueCount = TrueCount * LHSRatio; 1231 } 1232 1233 cond.begin(*this); 1234 EmitBlock(LHSBlock); 1235 incrementProfileCounter(CondOp); 1236 { 1237 ApplyDebugLocation DL(*this, Cond); 1238 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock, 1239 LHSScaledTrueCount); 1240 } 1241 cond.end(*this); 1242 1243 cond.begin(*this); 1244 EmitBlock(RHSBlock); 1245 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock, 1246 TrueCount - LHSScaledTrueCount); 1247 cond.end(*this); 1248 1249 return; 1250 } 1251 1252 if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) { 1253 // Conditional operator handling can give us a throw expression as a 1254 // condition for a case like: 1255 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f) 1256 // Fold this to: 1257 // br(c, throw x, br(y, t, f)) 1258 EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false); 1259 return; 1260 } 1261 1262 // If the branch has a condition wrapped by __builtin_unpredictable, 1263 // create metadata that specifies that the branch is unpredictable. 1264 // Don't bother if not optimizing because that metadata would not be used. 1265 llvm::MDNode *Unpredictable = nullptr; 1266 if (CGM.getCodeGenOpts().OptimizationLevel != 0) { 1267 if (const CallExpr *Call = dyn_cast<CallExpr>(Cond)) { 1268 const Decl *TargetDecl = Call->getCalleeDecl(); 1269 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) { 1270 if (FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) { 1271 llvm::MDBuilder MDHelper(getLLVMContext()); 1272 Unpredictable = MDHelper.createUnpredictable(); 1273 } 1274 } 1275 } 1276 } 1277 1278 // Create branch weights based on the number of times we get here and the 1279 // number of times the condition should be true. 1280 uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount); 1281 llvm::MDNode *Weights = 1282 createProfileWeights(TrueCount, CurrentCount - TrueCount); 1283 1284 // Emit the code with the fully general case. 1285 llvm::Value *CondV; 1286 { 1287 ApplyDebugLocation DL(*this, Cond); 1288 CondV = EvaluateExprAsBool(Cond); 1289 } 1290 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable); 1291 } 1292 1293 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1294 /// specified stmt yet. 1295 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) { 1296 CGM.ErrorUnsupported(S, Type); 1297 } 1298 1299 /// emitNonZeroVLAInit - Emit the "zero" initialization of a 1300 /// variable-length array whose elements have a non-zero bit-pattern. 1301 /// 1302 /// \param baseType the inner-most element type of the array 1303 /// \param src - a char* pointing to the bit-pattern for a single 1304 /// base element of the array 1305 /// \param sizeInChars - the total size of the VLA, in chars 1306 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, 1307 Address dest, Address src, 1308 llvm::Value *sizeInChars) { 1309 CGBuilderTy &Builder = CGF.Builder; 1310 1311 CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType); 1312 llvm::Value *baseSizeInChars 1313 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity()); 1314 1315 Address begin = 1316 Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin"); 1317 llvm::Value *end = 1318 Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end"); 1319 1320 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock(); 1321 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop"); 1322 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont"); 1323 1324 // Make a loop over the VLA. C99 guarantees that the VLA element 1325 // count must be nonzero. 1326 CGF.EmitBlock(loopBB); 1327 1328 llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur"); 1329 cur->addIncoming(begin.getPointer(), originBB); 1330 1331 CharUnits curAlign = 1332 dest.getAlignment().alignmentOfArrayElement(baseSize); 1333 1334 // memcpy the individual element bit-pattern. 1335 Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars, 1336 /*volatile*/ false); 1337 1338 // Go to the next element. 1339 llvm::Value *next = 1340 Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next"); 1341 1342 // Leave if that's the end of the VLA. 1343 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone"); 1344 Builder.CreateCondBr(done, contBB, loopBB); 1345 cur->addIncoming(next, loopBB); 1346 1347 CGF.EmitBlock(contBB); 1348 } 1349 1350 void 1351 CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) { 1352 // Ignore empty classes in C++. 1353 if (getLangOpts().CPlusPlus) { 1354 if (const RecordType *RT = Ty->getAs<RecordType>()) { 1355 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty()) 1356 return; 1357 } 1358 } 1359 1360 // Cast the dest ptr to the appropriate i8 pointer type. 1361 if (DestPtr.getElementType() != Int8Ty) 1362 DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty); 1363 1364 // Get size and alignment info for this aggregate. 1365 CharUnits size = getContext().getTypeSizeInChars(Ty); 1366 1367 llvm::Value *SizeVal; 1368 const VariableArrayType *vla; 1369 1370 // Don't bother emitting a zero-byte memset. 1371 if (size.isZero()) { 1372 // But note that getTypeInfo returns 0 for a VLA. 1373 if (const VariableArrayType *vlaType = 1374 dyn_cast_or_null<VariableArrayType>( 1375 getContext().getAsArrayType(Ty))) { 1376 QualType eltType; 1377 llvm::Value *numElts; 1378 std::tie(numElts, eltType) = getVLASize(vlaType); 1379 1380 SizeVal = numElts; 1381 CharUnits eltSize = getContext().getTypeSizeInChars(eltType); 1382 if (!eltSize.isOne()) 1383 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize)); 1384 vla = vlaType; 1385 } else { 1386 return; 1387 } 1388 } else { 1389 SizeVal = CGM.getSize(size); 1390 vla = nullptr; 1391 } 1392 1393 // If the type contains a pointer to data member we can't memset it to zero. 1394 // Instead, create a null constant and copy it to the destination. 1395 // TODO: there are other patterns besides zero that we can usefully memset, 1396 // like -1, which happens to be the pattern used by member-pointers. 1397 if (!CGM.getTypes().isZeroInitializable(Ty)) { 1398 // For a VLA, emit a single element, then splat that over the VLA. 1399 if (vla) Ty = getContext().getBaseElementType(vla); 1400 1401 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty); 1402 1403 llvm::GlobalVariable *NullVariable = 1404 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(), 1405 /*isConstant=*/true, 1406 llvm::GlobalVariable::PrivateLinkage, 1407 NullConstant, Twine()); 1408 CharUnits NullAlign = DestPtr.getAlignment(); 1409 NullVariable->setAlignment(NullAlign.getQuantity()); 1410 Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()), 1411 NullAlign); 1412 1413 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal); 1414 1415 // Get and call the appropriate llvm.memcpy overload. 1416 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false); 1417 return; 1418 } 1419 1420 // Otherwise, just memset the whole thing to zero. This is legal 1421 // because in LLVM, all default initializers (other than the ones we just 1422 // handled above) are guaranteed to have a bit pattern of all zeros. 1423 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false); 1424 } 1425 1426 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) { 1427 // Make sure that there is a block for the indirect goto. 1428 if (!IndirectBranch) 1429 GetIndirectGotoBlock(); 1430 1431 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock(); 1432 1433 // Make sure the indirect branch includes all of the address-taken blocks. 1434 IndirectBranch->addDestination(BB); 1435 return llvm::BlockAddress::get(CurFn, BB); 1436 } 1437 1438 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() { 1439 // If we already made the indirect branch for indirect goto, return its block. 1440 if (IndirectBranch) return IndirectBranch->getParent(); 1441 1442 CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto")); 1443 1444 // Create the PHI node that indirect gotos will add entries to. 1445 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0, 1446 "indirect.goto.dest"); 1447 1448 // Create the indirect branch instruction. 1449 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal); 1450 return IndirectBranch->getParent(); 1451 } 1452 1453 /// Computes the length of an array in elements, as well as the base 1454 /// element type and a properly-typed first element pointer. 1455 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType, 1456 QualType &baseType, 1457 Address &addr) { 1458 const ArrayType *arrayType = origArrayType; 1459 1460 // If it's a VLA, we have to load the stored size. Note that 1461 // this is the size of the VLA in bytes, not its size in elements. 1462 llvm::Value *numVLAElements = nullptr; 1463 if (isa<VariableArrayType>(arrayType)) { 1464 numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first; 1465 1466 // Walk into all VLAs. This doesn't require changes to addr, 1467 // which has type T* where T is the first non-VLA element type. 1468 do { 1469 QualType elementType = arrayType->getElementType(); 1470 arrayType = getContext().getAsArrayType(elementType); 1471 1472 // If we only have VLA components, 'addr' requires no adjustment. 1473 if (!arrayType) { 1474 baseType = elementType; 1475 return numVLAElements; 1476 } 1477 } while (isa<VariableArrayType>(arrayType)); 1478 1479 // We get out here only if we find a constant array type 1480 // inside the VLA. 1481 } 1482 1483 // We have some number of constant-length arrays, so addr should 1484 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks 1485 // down to the first element of addr. 1486 SmallVector<llvm::Value*, 8> gepIndices; 1487 1488 // GEP down to the array type. 1489 llvm::ConstantInt *zero = Builder.getInt32(0); 1490 gepIndices.push_back(zero); 1491 1492 uint64_t countFromCLAs = 1; 1493 QualType eltType; 1494 1495 llvm::ArrayType *llvmArrayType = 1496 dyn_cast<llvm::ArrayType>(addr.getElementType()); 1497 while (llvmArrayType) { 1498 assert(isa<ConstantArrayType>(arrayType)); 1499 assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue() 1500 == llvmArrayType->getNumElements()); 1501 1502 gepIndices.push_back(zero); 1503 countFromCLAs *= llvmArrayType->getNumElements(); 1504 eltType = arrayType->getElementType(); 1505 1506 llvmArrayType = 1507 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType()); 1508 arrayType = getContext().getAsArrayType(arrayType->getElementType()); 1509 assert((!llvmArrayType || arrayType) && 1510 "LLVM and Clang types are out-of-synch"); 1511 } 1512 1513 if (arrayType) { 1514 // From this point onwards, the Clang array type has been emitted 1515 // as some other type (probably a packed struct). Compute the array 1516 // size, and just emit the 'begin' expression as a bitcast. 1517 while (arrayType) { 1518 countFromCLAs *= 1519 cast<ConstantArrayType>(arrayType)->getSize().getZExtValue(); 1520 eltType = arrayType->getElementType(); 1521 arrayType = getContext().getAsArrayType(eltType); 1522 } 1523 1524 llvm::Type *baseType = ConvertType(eltType); 1525 addr = Builder.CreateElementBitCast(addr, baseType, "array.begin"); 1526 } else { 1527 // Create the actual GEP. 1528 addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(), 1529 gepIndices, "array.begin"), 1530 addr.getAlignment()); 1531 } 1532 1533 baseType = eltType; 1534 1535 llvm::Value *numElements 1536 = llvm::ConstantInt::get(SizeTy, countFromCLAs); 1537 1538 // If we had any VLA dimensions, factor them in. 1539 if (numVLAElements) 1540 numElements = Builder.CreateNUWMul(numVLAElements, numElements); 1541 1542 return numElements; 1543 } 1544 1545 std::pair<llvm::Value*, QualType> 1546 CodeGenFunction::getVLASize(QualType type) { 1547 const VariableArrayType *vla = getContext().getAsVariableArrayType(type); 1548 assert(vla && "type was not a variable array type!"); 1549 return getVLASize(vla); 1550 } 1551 1552 std::pair<llvm::Value*, QualType> 1553 CodeGenFunction::getVLASize(const VariableArrayType *type) { 1554 // The number of elements so far; always size_t. 1555 llvm::Value *numElements = nullptr; 1556 1557 QualType elementType; 1558 do { 1559 elementType = type->getElementType(); 1560 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()]; 1561 assert(vlaSize && "no size for VLA!"); 1562 assert(vlaSize->getType() == SizeTy); 1563 1564 if (!numElements) { 1565 numElements = vlaSize; 1566 } else { 1567 // It's undefined behavior if this wraps around, so mark it that way. 1568 // FIXME: Teach -fsanitize=undefined to trap this. 1569 numElements = Builder.CreateNUWMul(numElements, vlaSize); 1570 } 1571 } while ((type = getContext().getAsVariableArrayType(elementType))); 1572 1573 return std::pair<llvm::Value*,QualType>(numElements, elementType); 1574 } 1575 1576 void CodeGenFunction::EmitVariablyModifiedType(QualType type) { 1577 assert(type->isVariablyModifiedType() && 1578 "Must pass variably modified type to EmitVLASizes!"); 1579 1580 EnsureInsertPoint(); 1581 1582 // We're going to walk down into the type and look for VLA 1583 // expressions. 1584 do { 1585 assert(type->isVariablyModifiedType()); 1586 1587 const Type *ty = type.getTypePtr(); 1588 switch (ty->getTypeClass()) { 1589 1590 #define TYPE(Class, Base) 1591 #define ABSTRACT_TYPE(Class, Base) 1592 #define NON_CANONICAL_TYPE(Class, Base) 1593 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1594 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 1595 #include "clang/AST/TypeNodes.def" 1596 llvm_unreachable("unexpected dependent type!"); 1597 1598 // These types are never variably-modified. 1599 case Type::Builtin: 1600 case Type::Complex: 1601 case Type::Vector: 1602 case Type::ExtVector: 1603 case Type::Record: 1604 case Type::Enum: 1605 case Type::Elaborated: 1606 case Type::TemplateSpecialization: 1607 case Type::ObjCObject: 1608 case Type::ObjCInterface: 1609 case Type::ObjCObjectPointer: 1610 llvm_unreachable("type class is never variably-modified!"); 1611 1612 case Type::Adjusted: 1613 type = cast<AdjustedType>(ty)->getAdjustedType(); 1614 break; 1615 1616 case Type::Decayed: 1617 type = cast<DecayedType>(ty)->getPointeeType(); 1618 break; 1619 1620 case Type::Pointer: 1621 type = cast<PointerType>(ty)->getPointeeType(); 1622 break; 1623 1624 case Type::BlockPointer: 1625 type = cast<BlockPointerType>(ty)->getPointeeType(); 1626 break; 1627 1628 case Type::LValueReference: 1629 case Type::RValueReference: 1630 type = cast<ReferenceType>(ty)->getPointeeType(); 1631 break; 1632 1633 case Type::MemberPointer: 1634 type = cast<MemberPointerType>(ty)->getPointeeType(); 1635 break; 1636 1637 case Type::ConstantArray: 1638 case Type::IncompleteArray: 1639 // Losing element qualification here is fine. 1640 type = cast<ArrayType>(ty)->getElementType(); 1641 break; 1642 1643 case Type::VariableArray: { 1644 // Losing element qualification here is fine. 1645 const VariableArrayType *vat = cast<VariableArrayType>(ty); 1646 1647 // Unknown size indication requires no size computation. 1648 // Otherwise, evaluate and record it. 1649 if (const Expr *size = vat->getSizeExpr()) { 1650 // It's possible that we might have emitted this already, 1651 // e.g. with a typedef and a pointer to it. 1652 llvm::Value *&entry = VLASizeMap[size]; 1653 if (!entry) { 1654 llvm::Value *Size = EmitScalarExpr(size); 1655 1656 // C11 6.7.6.2p5: 1657 // If the size is an expression that is not an integer constant 1658 // expression [...] each time it is evaluated it shall have a value 1659 // greater than zero. 1660 if (SanOpts.has(SanitizerKind::VLABound) && 1661 size->getType()->isSignedIntegerType()) { 1662 SanitizerScope SanScope(this); 1663 llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType()); 1664 llvm::Constant *StaticArgs[] = { 1665 EmitCheckSourceLocation(size->getLocStart()), 1666 EmitCheckTypeDescriptor(size->getType()) 1667 }; 1668 EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero), 1669 SanitizerKind::VLABound), 1670 "vla_bound_not_positive", StaticArgs, Size); 1671 } 1672 1673 // Always zexting here would be wrong if it weren't 1674 // undefined behavior to have a negative bound. 1675 entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false); 1676 } 1677 } 1678 type = vat->getElementType(); 1679 break; 1680 } 1681 1682 case Type::FunctionProto: 1683 case Type::FunctionNoProto: 1684 type = cast<FunctionType>(ty)->getReturnType(); 1685 break; 1686 1687 case Type::Paren: 1688 case Type::TypeOf: 1689 case Type::UnaryTransform: 1690 case Type::Attributed: 1691 case Type::SubstTemplateTypeParm: 1692 case Type::PackExpansion: 1693 // Keep walking after single level desugaring. 1694 type = type.getSingleStepDesugaredType(getContext()); 1695 break; 1696 1697 case Type::Typedef: 1698 case Type::Decltype: 1699 case Type::Auto: 1700 // Stop walking: nothing to do. 1701 return; 1702 1703 case Type::TypeOfExpr: 1704 // Stop walking: emit typeof expression. 1705 EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr()); 1706 return; 1707 1708 case Type::Atomic: 1709 type = cast<AtomicType>(ty)->getValueType(); 1710 break; 1711 } 1712 } while (type->isVariablyModifiedType()); 1713 } 1714 1715 Address CodeGenFunction::EmitVAListRef(const Expr* E) { 1716 if (getContext().getBuiltinVaListType()->isArrayType()) 1717 return EmitPointerWithAlignment(E); 1718 return EmitLValue(E).getAddress(); 1719 } 1720 1721 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E, 1722 llvm::Constant *Init) { 1723 assert (Init && "Invalid DeclRefExpr initializer!"); 1724 if (CGDebugInfo *Dbg = getDebugInfo()) 1725 if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 1726 Dbg->EmitGlobalVariable(E->getDecl(), Init); 1727 } 1728 1729 CodeGenFunction::PeepholeProtection 1730 CodeGenFunction::protectFromPeepholes(RValue rvalue) { 1731 // At the moment, the only aggressive peephole we do in IR gen 1732 // is trunc(zext) folding, but if we add more, we can easily 1733 // extend this protection. 1734 1735 if (!rvalue.isScalar()) return PeepholeProtection(); 1736 llvm::Value *value = rvalue.getScalarVal(); 1737 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection(); 1738 1739 // Just make an extra bitcast. 1740 assert(HaveInsertPoint()); 1741 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "", 1742 Builder.GetInsertBlock()); 1743 1744 PeepholeProtection protection; 1745 protection.Inst = inst; 1746 return protection; 1747 } 1748 1749 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) { 1750 if (!protection.Inst) return; 1751 1752 // In theory, we could try to duplicate the peepholes now, but whatever. 1753 protection.Inst->eraseFromParent(); 1754 } 1755 1756 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn, 1757 llvm::Value *AnnotatedVal, 1758 StringRef AnnotationStr, 1759 SourceLocation Location) { 1760 llvm::Value *Args[4] = { 1761 AnnotatedVal, 1762 Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy), 1763 Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy), 1764 CGM.EmitAnnotationLineNo(Location) 1765 }; 1766 return Builder.CreateCall(AnnotationFn, Args); 1767 } 1768 1769 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) { 1770 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1771 // FIXME We create a new bitcast for every annotation because that's what 1772 // llvm-gcc was doing. 1773 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 1774 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation), 1775 Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()), 1776 I->getAnnotation(), D->getLocation()); 1777 } 1778 1779 Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D, 1780 Address Addr) { 1781 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1782 llvm::Value *V = Addr.getPointer(); 1783 llvm::Type *VTy = V->getType(); 1784 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, 1785 CGM.Int8PtrTy); 1786 1787 for (const auto *I : D->specific_attrs<AnnotateAttr>()) { 1788 // FIXME Always emit the cast inst so we can differentiate between 1789 // annotation on the first field of a struct and annotation on the struct 1790 // itself. 1791 if (VTy != CGM.Int8PtrTy) 1792 V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy)); 1793 V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation()); 1794 V = Builder.CreateBitCast(V, VTy); 1795 } 1796 1797 return Address(V, Addr.getAlignment()); 1798 } 1799 1800 CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { } 1801 1802 CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF) 1803 : CGF(CGF) { 1804 assert(!CGF->IsSanitizerScope); 1805 CGF->IsSanitizerScope = true; 1806 } 1807 1808 CodeGenFunction::SanitizerScope::~SanitizerScope() { 1809 CGF->IsSanitizerScope = false; 1810 } 1811 1812 void CodeGenFunction::InsertHelper(llvm::Instruction *I, 1813 const llvm::Twine &Name, 1814 llvm::BasicBlock *BB, 1815 llvm::BasicBlock::iterator InsertPt) const { 1816 LoopStack.InsertHelper(I); 1817 if (IsSanitizerScope) 1818 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I); 1819 } 1820 1821 template <bool PreserveNames> 1822 void CGBuilderInserter<PreserveNames>::InsertHelper( 1823 llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, 1824 llvm::BasicBlock::iterator InsertPt) const { 1825 llvm::IRBuilderDefaultInserter<PreserveNames>::InsertHelper(I, Name, BB, 1826 InsertPt); 1827 if (CGF) 1828 CGF->InsertHelper(I, Name, BB, InsertPt); 1829 } 1830 1831 #ifdef NDEBUG 1832 #define PreserveNames false 1833 #else 1834 #define PreserveNames true 1835 #endif 1836 template void CGBuilderInserter<PreserveNames>::InsertHelper( 1837 llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, 1838 llvm::BasicBlock::iterator InsertPt) const; 1839 #undef PreserveNames 1840