CodeGenFunction.cpp 65 KB

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