CodeGenFunction.cpp 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401
  1. //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This coordinates the per-function state used while generating code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CodeGenFunction.h"
  13. #include "CGBlocks.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/ASTLambda.h"
  24. #include "clang/AST/Decl.h"
  25. #include "clang/AST/DeclCXX.h"
  26. #include "clang/AST/StmtCXX.h"
  27. #include "clang/AST/StmtObjC.h"
  28. #include "clang/Basic/Builtins.h"
  29. #include "clang/Basic/CodeGenOptions.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/CodeGen/CGFunctionInfo.h"
  32. #include "clang/Frontend/FrontendDiagnostic.h"
  33. #include "llvm/IR/DataLayout.h"
  34. #include "llvm/IR/Dominators.h"
  35. #include "llvm/IR/Intrinsics.h"
  36. #include "llvm/IR/MDBuilder.h"
  37. #include "llvm/IR/Operator.h"
  38. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  39. using namespace clang;
  40. using namespace CodeGen;
  41. /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
  42. /// markers.
  43. static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
  44. const LangOptions &LangOpts) {
  45. if (CGOpts.DisableLifetimeMarkers)
  46. return false;
  47. // Disable lifetime markers in msan builds.
  48. // FIXME: Remove this when msan works with lifetime markers.
  49. if (LangOpts.Sanitize.has(SanitizerKind::Memory))
  50. return false;
  51. // Asan uses markers for use-after-scope checks.
  52. if (CGOpts.SanitizeAddressUseAfterScope)
  53. return true;
  54. // For now, only in optimized builds.
  55. return CGOpts.OptimizationLevel != 0;
  56. }
  57. CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
  58. : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
  59. Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
  60. CGBuilderInserterTy(this)),
  61. SanOpts(CGM.getLangOpts().Sanitize), DebugInfo(CGM.getModuleDebugInfo()),
  62. PGO(cgm), ShouldEmitLifetimeMarkers(shouldEmitLifetimeMarkers(
  63. CGM.getCodeGenOpts(), CGM.getLangOpts())) {
  64. if (!suppressNewContext)
  65. CGM.getCXXABI().getMangleContext().startNewFunction();
  66. llvm::FastMathFlags FMF;
  67. if (CGM.getLangOpts().FastMath)
  68. FMF.setFast();
  69. if (CGM.getLangOpts().FiniteMathOnly) {
  70. FMF.setNoNaNs();
  71. FMF.setNoInfs();
  72. }
  73. if (CGM.getCodeGenOpts().NoNaNsFPMath) {
  74. FMF.setNoNaNs();
  75. }
  76. if (CGM.getCodeGenOpts().NoSignedZeros) {
  77. FMF.setNoSignedZeros();
  78. }
  79. if (CGM.getCodeGenOpts().ReciprocalMath) {
  80. FMF.setAllowReciprocal();
  81. }
  82. if (CGM.getCodeGenOpts().Reassociate) {
  83. FMF.setAllowReassoc();
  84. }
  85. Builder.setFastMathFlags(FMF);
  86. }
  87. CodeGenFunction::~CodeGenFunction() {
  88. assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
  89. // If there are any unclaimed block infos, go ahead and destroy them
  90. // now. This can happen if IR-gen gets clever and skips evaluating
  91. // something.
  92. if (FirstBlockInfo)
  93. destroyBlockInfos(FirstBlockInfo);
  94. if (getLangOpts().OpenMP && CurFn)
  95. CGM.getOpenMPRuntime().functionFinished(*this);
  96. }
  97. CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T,
  98. LValueBaseInfo *BaseInfo,
  99. TBAAAccessInfo *TBAAInfo) {
  100. return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
  101. /* forPointeeType= */ true);
  102. }
  103. CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T,
  104. LValueBaseInfo *BaseInfo,
  105. TBAAAccessInfo *TBAAInfo,
  106. bool forPointeeType) {
  107. if (TBAAInfo)
  108. *TBAAInfo = CGM.getTBAAAccessInfo(T);
  109. // Honor alignment typedef attributes even on incomplete types.
  110. // We also honor them straight for C++ class types, even as pointees;
  111. // there's an expressivity gap here.
  112. if (auto TT = T->getAs<TypedefType>()) {
  113. if (auto Align = TT->getDecl()->getMaxAlignment()) {
  114. if (BaseInfo)
  115. *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
  116. return getContext().toCharUnitsFromBits(Align);
  117. }
  118. }
  119. if (BaseInfo)
  120. *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
  121. CharUnits Alignment;
  122. if (T->isIncompleteType()) {
  123. Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best.
  124. } else {
  125. // For C++ class pointees, we don't know whether we're pointing at a
  126. // base or a complete object, so we generally need to use the
  127. // non-virtual alignment.
  128. const CXXRecordDecl *RD;
  129. if (forPointeeType && (RD = T->getAsCXXRecordDecl())) {
  130. Alignment = CGM.getClassPointerAlignment(RD);
  131. } else {
  132. Alignment = getContext().getTypeAlignInChars(T);
  133. if (T.getQualifiers().hasUnaligned())
  134. Alignment = CharUnits::One();
  135. }
  136. // Cap to the global maximum type alignment unless the alignment
  137. // was somehow explicit on the type.
  138. if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
  139. if (Alignment.getQuantity() > MaxAlign &&
  140. !getContext().isAlignmentRequired(T))
  141. Alignment = CharUnits::fromQuantity(MaxAlign);
  142. }
  143. }
  144. return Alignment;
  145. }
  146. LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
  147. LValueBaseInfo BaseInfo;
  148. TBAAAccessInfo TBAAInfo;
  149. CharUnits Alignment = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo);
  150. return LValue::MakeAddr(Address(V, Alignment), T, getContext(), BaseInfo,
  151. TBAAInfo);
  152. }
  153. /// Given a value of type T* that may not be to a complete object,
  154. /// construct an l-value with the natural pointee alignment of T.
  155. LValue
  156. CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
  157. LValueBaseInfo BaseInfo;
  158. TBAAAccessInfo TBAAInfo;
  159. CharUnits Align = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo,
  160. /* forPointeeType= */ true);
  161. return MakeAddrLValue(Address(V, Align), T, BaseInfo, TBAAInfo);
  162. }
  163. llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
  164. return CGM.getTypes().ConvertTypeForMem(T);
  165. }
  166. llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  167. return CGM.getTypes().ConvertType(T);
  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. case Type::Auto:
  181. case Type::DeducedTemplateSpecialization:
  182. llvm_unreachable("undeduced type in IR-generation");
  183. // Various scalar types.
  184. case Type::Builtin:
  185. case Type::Pointer:
  186. case Type::BlockPointer:
  187. case Type::LValueReference:
  188. case Type::RValueReference:
  189. case Type::MemberPointer:
  190. case Type::Vector:
  191. case Type::ExtVector:
  192. case Type::FunctionProto:
  193. case Type::FunctionNoProto:
  194. case Type::Enum:
  195. case Type::ObjCObjectPointer:
  196. case Type::Pipe:
  197. return TEK_Scalar;
  198. // Complexes.
  199. case Type::Complex:
  200. return TEK_Complex;
  201. // Arrays, records, and Objective-C objects.
  202. case Type::ConstantArray:
  203. case Type::IncompleteArray:
  204. case Type::VariableArray:
  205. case Type::Record:
  206. case Type::ObjCObject:
  207. case Type::ObjCInterface:
  208. return TEK_Aggregate;
  209. // We operate on atomic values according to their underlying type.
  210. case Type::Atomic:
  211. type = cast<AtomicType>(type)->getValueType();
  212. continue;
  213. }
  214. llvm_unreachable("unknown type kind!");
  215. }
  216. }
  217. llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
  218. // For cleanliness, we try to avoid emitting the return block for
  219. // simple cases.
  220. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  221. if (CurBB) {
  222. assert(!CurBB->getTerminator() && "Unexpected terminated block.");
  223. // We have a valid insert point, reuse it if it is empty or there are no
  224. // explicit jumps to the return block.
  225. if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
  226. ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
  227. delete ReturnBlock.getBlock();
  228. ReturnBlock = JumpDest();
  229. } else
  230. EmitBlock(ReturnBlock.getBlock());
  231. return llvm::DebugLoc();
  232. }
  233. // Otherwise, if the return block is the target of a single direct
  234. // branch then we can just put the code in that block instead. This
  235. // cleans up functions which started with a unified return block.
  236. if (ReturnBlock.getBlock()->hasOneUse()) {
  237. llvm::BranchInst *BI =
  238. dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
  239. if (BI && BI->isUnconditional() &&
  240. BI->getSuccessor(0) == ReturnBlock.getBlock()) {
  241. // Record/return the DebugLoc of the simple 'return' expression to be used
  242. // later by the actual 'ret' instruction.
  243. llvm::DebugLoc Loc = BI->getDebugLoc();
  244. Builder.SetInsertPoint(BI->getParent());
  245. BI->eraseFromParent();
  246. delete ReturnBlock.getBlock();
  247. ReturnBlock = JumpDest();
  248. return Loc;
  249. }
  250. }
  251. // FIXME: We are at an unreachable point, there is no reason to emit the block
  252. // unless it has uses. However, we still need a place to put the debug
  253. // region.end for now.
  254. EmitBlock(ReturnBlock.getBlock());
  255. return llvm::DebugLoc();
  256. }
  257. static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
  258. if (!BB) return;
  259. if (!BB->use_empty())
  260. return CGF.CurFn->getBasicBlockList().push_back(BB);
  261. delete BB;
  262. }
  263. void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
  264. assert(BreakContinueStack.empty() &&
  265. "mismatched push/pop in break/continue stack!");
  266. bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
  267. && NumSimpleReturnExprs == NumReturnExprs
  268. && ReturnBlock.getBlock()->use_empty();
  269. // Usually the return expression is evaluated before the cleanup
  270. // code. If the function contains only a simple return statement,
  271. // such as a constant, the location before the cleanup code becomes
  272. // the last useful breakpoint in the function, because the simple
  273. // return expression will be evaluated after the cleanup code. To be
  274. // safe, set the debug location for cleanup code to the location of
  275. // the return statement. Otherwise the cleanup code should be at the
  276. // end of the function's lexical scope.
  277. //
  278. // If there are multiple branches to the return block, the branch
  279. // instructions will get the location of the return statements and
  280. // all will be fine.
  281. if (CGDebugInfo *DI = getDebugInfo()) {
  282. if (OnlySimpleReturnStmts)
  283. DI->EmitLocation(Builder, LastStopPoint);
  284. else
  285. DI->EmitLocation(Builder, EndLoc);
  286. }
  287. // Pop any cleanups that might have been associated with the
  288. // parameters. Do this in whatever block we're currently in; it's
  289. // important to do this before we enter the return block or return
  290. // edges will be *really* confused.
  291. bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
  292. bool HasOnlyLifetimeMarkers =
  293. HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
  294. bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
  295. if (HasCleanups) {
  296. // Make sure the line table doesn't jump back into the body for
  297. // the ret after it's been at EndLoc.
  298. if (CGDebugInfo *DI = getDebugInfo())
  299. if (OnlySimpleReturnStmts)
  300. DI->EmitLocation(Builder, EndLoc);
  301. PopCleanupBlocks(PrologueCleanupDepth);
  302. }
  303. // Emit function epilog (to return).
  304. llvm::DebugLoc Loc = EmitReturnBlock();
  305. if (ShouldInstrumentFunction()) {
  306. if (CGM.getCodeGenOpts().InstrumentFunctions)
  307. CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
  308. if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
  309. CurFn->addFnAttr("instrument-function-exit-inlined",
  310. "__cyg_profile_func_exit");
  311. }
  312. // Emit debug descriptor for function end.
  313. if (CGDebugInfo *DI = getDebugInfo())
  314. DI->EmitFunctionEnd(Builder, CurFn);
  315. // Reset the debug location to that of the simple 'return' expression, if any
  316. // rather than that of the end of the function's scope '}'.
  317. ApplyDebugLocation AL(*this, Loc);
  318. EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
  319. EmitEndEHSpec(CurCodeDecl);
  320. assert(EHStack.empty() &&
  321. "did not remove all scopes from cleanup stack!");
  322. // If someone did an indirect goto, emit the indirect goto block at the end of
  323. // the function.
  324. if (IndirectBranch) {
  325. EmitBlock(IndirectBranch->getParent());
  326. Builder.ClearInsertionPoint();
  327. }
  328. // If some of our locals escaped, insert a call to llvm.localescape in the
  329. // entry block.
  330. if (!EscapedLocals.empty()) {
  331. // Invert the map from local to index into a simple vector. There should be
  332. // no holes.
  333. SmallVector<llvm::Value *, 4> EscapeArgs;
  334. EscapeArgs.resize(EscapedLocals.size());
  335. for (auto &Pair : EscapedLocals)
  336. EscapeArgs[Pair.second] = Pair.first;
  337. llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
  338. &CGM.getModule(), llvm::Intrinsic::localescape);
  339. CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
  340. }
  341. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  342. llvm::Instruction *Ptr = AllocaInsertPt;
  343. AllocaInsertPt = nullptr;
  344. Ptr->eraseFromParent();
  345. // If someone took the address of a label but never did an indirect goto, we
  346. // made a zero entry PHI node, which is illegal, zap it now.
  347. if (IndirectBranch) {
  348. llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
  349. if (PN->getNumIncomingValues() == 0) {
  350. PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
  351. PN->eraseFromParent();
  352. }
  353. }
  354. EmitIfUsed(*this, EHResumeBlock);
  355. EmitIfUsed(*this, TerminateLandingPad);
  356. EmitIfUsed(*this, TerminateHandler);
  357. EmitIfUsed(*this, UnreachableBlock);
  358. for (const auto &FuncletAndParent : TerminateFunclets)
  359. EmitIfUsed(*this, FuncletAndParent.second);
  360. if (CGM.getCodeGenOpts().EmitDeclMetadata)
  361. EmitDeclMetadata();
  362. for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
  363. I = DeferredReplacements.begin(),
  364. E = DeferredReplacements.end();
  365. I != E; ++I) {
  366. I->first->replaceAllUsesWith(I->second);
  367. I->first->eraseFromParent();
  368. }
  369. // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
  370. // PHIs if the current function is a coroutine. We don't do it for all
  371. // functions as it may result in slight increase in numbers of instructions
  372. // if compiled with no optimizations. We do it for coroutine as the lifetime
  373. // of CleanupDestSlot alloca make correct coroutine frame building very
  374. // difficult.
  375. if (NormalCleanupDest.isValid() && isCoroutine()) {
  376. llvm::DominatorTree DT(*CurFn);
  377. llvm::PromoteMemToReg(
  378. cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
  379. NormalCleanupDest = Address::invalid();
  380. }
  381. // Scan function arguments for vector width.
  382. for (llvm::Argument &A : CurFn->args())
  383. if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
  384. LargestVectorWidth = std::max(LargestVectorWidth,
  385. VT->getPrimitiveSizeInBits());
  386. // Update vector width based on return type.
  387. if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
  388. LargestVectorWidth = std::max(LargestVectorWidth,
  389. VT->getPrimitiveSizeInBits());
  390. // Add the required-vector-width attribute. This contains the max width from:
  391. // 1. min-vector-width attribute used in the source program.
  392. // 2. Any builtins used that have a vector width specified.
  393. // 3. Values passed in and out of inline assembly.
  394. // 4. Width of vector arguments and return types for this function.
  395. // 5. Width of vector aguments and return types for functions called by this
  396. // function.
  397. CurFn->addFnAttr("min-legal-vector-width", llvm::utostr(LargestVectorWidth));
  398. // If we generated an unreachable return block, delete it now.
  399. if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) {
  400. Builder.ClearInsertionPoint();
  401. ReturnBlock.getBlock()->eraseFromParent();
  402. }
  403. if (ReturnValue.isValid()) {
  404. auto *RetAlloca = dyn_cast<llvm::AllocaInst>(ReturnValue.getPointer());
  405. if (RetAlloca && RetAlloca->use_empty()) {
  406. RetAlloca->eraseFromParent();
  407. ReturnValue = Address::invalid();
  408. }
  409. }
  410. }
  411. /// ShouldInstrumentFunction - Return true if the current function should be
  412. /// instrumented with __cyg_profile_func_* calls
  413. bool CodeGenFunction::ShouldInstrumentFunction() {
  414. if (!CGM.getCodeGenOpts().InstrumentFunctions &&
  415. !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining &&
  416. !CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
  417. return false;
  418. if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
  419. return false;
  420. return true;
  421. }
  422. /// ShouldXRayInstrument - Return true if the current function should be
  423. /// instrumented with XRay nop sleds.
  424. bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
  425. return CGM.getCodeGenOpts().XRayInstrumentFunctions;
  426. }
  427. /// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
  428. /// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
  429. bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
  430. return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
  431. (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
  432. CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
  433. XRayInstrKind::Custom);
  434. }
  435. bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
  436. return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
  437. (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
  438. CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
  439. XRayInstrKind::Typed);
  440. }
  441. llvm::Constant *
  442. CodeGenFunction::EncodeAddrForUseInPrologue(llvm::Function *F,
  443. llvm::Constant *Addr) {
  444. // Addresses stored in prologue data can't require run-time fixups and must
  445. // be PC-relative. Run-time fixups are undesirable because they necessitate
  446. // writable text segments, which are unsafe. And absolute addresses are
  447. // undesirable because they break PIE mode.
  448. // Add a layer of indirection through a private global. Taking its address
  449. // won't result in a run-time fixup, even if Addr has linkonce_odr linkage.
  450. auto *GV = new llvm::GlobalVariable(CGM.getModule(), Addr->getType(),
  451. /*isConstant=*/true,
  452. llvm::GlobalValue::PrivateLinkage, Addr);
  453. // Create a PC-relative address.
  454. auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV, IntPtrTy);
  455. auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F, IntPtrTy);
  456. auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt);
  457. return (IntPtrTy == Int32Ty)
  458. ? PCRelAsInt
  459. : llvm::ConstantExpr::getTrunc(PCRelAsInt, Int32Ty);
  460. }
  461. llvm::Value *
  462. CodeGenFunction::DecodeAddrUsedInPrologue(llvm::Value *F,
  463. llvm::Value *EncodedAddr) {
  464. // Reconstruct the address of the global.
  465. auto *PCRelAsInt = Builder.CreateSExt(EncodedAddr, IntPtrTy);
  466. auto *FuncAsInt = Builder.CreatePtrToInt(F, IntPtrTy, "func_addr.int");
  467. auto *GOTAsInt = Builder.CreateAdd(PCRelAsInt, FuncAsInt, "global_addr.int");
  468. auto *GOTAddr = Builder.CreateIntToPtr(GOTAsInt, Int8PtrPtrTy, "global_addr");
  469. // Load the original pointer through the global.
  470. return Builder.CreateLoad(Address(GOTAddr, getPointerAlign()),
  471. "decoded_addr");
  472. }
  473. void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  474. llvm::Function *Fn)
  475. {
  476. if (!FD->hasAttr<OpenCLKernelAttr>())
  477. return;
  478. llvm::LLVMContext &Context = getLLVMContext();
  479. CGM.GenOpenCLArgMetadata(Fn, FD, this);
  480. if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
  481. QualType HintQTy = A->getTypeHint();
  482. const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
  483. bool IsSignedInteger =
  484. HintQTy->isSignedIntegerType() ||
  485. (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType());
  486. llvm::Metadata *AttrMDArgs[] = {
  487. llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
  488. CGM.getTypes().ConvertType(A->getTypeHint()))),
  489. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  490. llvm::IntegerType::get(Context, 32),
  491. llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
  492. Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
  493. }
  494. if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
  495. llvm::Metadata *AttrMDArgs[] = {
  496. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  497. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  498. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  499. Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
  500. }
  501. if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
  502. llvm::Metadata *AttrMDArgs[] = {
  503. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  504. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  505. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  506. Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
  507. }
  508. if (const OpenCLIntelReqdSubGroupSizeAttr *A =
  509. FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
  510. llvm::Metadata *AttrMDArgs[] = {
  511. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
  512. Fn->setMetadata("intel_reqd_sub_group_size",
  513. llvm::MDNode::get(Context, AttrMDArgs));
  514. }
  515. }
  516. /// Determine whether the function F ends with a return stmt.
  517. static bool endsWithReturn(const Decl* F) {
  518. const Stmt *Body = nullptr;
  519. if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
  520. Body = FD->getBody();
  521. else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
  522. Body = OMD->getBody();
  523. if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
  524. auto LastStmt = CS->body_rbegin();
  525. if (LastStmt != CS->body_rend())
  526. return isa<ReturnStmt>(*LastStmt);
  527. }
  528. return false;
  529. }
  530. void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
  531. if (SanOpts.has(SanitizerKind::Thread)) {
  532. Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
  533. Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
  534. }
  535. }
  536. static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
  537. auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
  538. if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
  539. !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") ||
  540. (MD->getNumParams() != 1 && MD->getNumParams() != 2))
  541. return false;
  542. if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
  543. return false;
  544. if (MD->getNumParams() == 2) {
  545. auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
  546. if (!PT || !PT->isVoidPointerType() ||
  547. !PT->getPointeeType().isConstQualified())
  548. return false;
  549. }
  550. return true;
  551. }
  552. /// Return the UBSan prologue signature for \p FD if one is available.
  553. static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
  554. const FunctionDecl *FD) {
  555. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  556. if (!MD->isStatic())
  557. return nullptr;
  558. return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
  559. }
  560. void CodeGenFunction::StartFunction(GlobalDecl GD,
  561. QualType RetTy,
  562. llvm::Function *Fn,
  563. const CGFunctionInfo &FnInfo,
  564. const FunctionArgList &Args,
  565. SourceLocation Loc,
  566. SourceLocation StartLoc) {
  567. assert(!CurFn &&
  568. "Do not use a CodeGenFunction object for more than one function");
  569. const Decl *D = GD.getDecl();
  570. DidCallStackSave = false;
  571. CurCodeDecl = D;
  572. if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
  573. if (FD->usesSEHTry())
  574. CurSEHParent = FD;
  575. CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
  576. FnRetTy = RetTy;
  577. CurFn = Fn;
  578. CurFnInfo = &FnInfo;
  579. assert(CurFn->isDeclaration() && "Function already has body?");
  580. // If this function has been blacklisted for any of the enabled sanitizers,
  581. // disable the sanitizer for the function.
  582. do {
  583. #define SANITIZER(NAME, ID) \
  584. if (SanOpts.empty()) \
  585. break; \
  586. if (SanOpts.has(SanitizerKind::ID)) \
  587. if (CGM.isInSanitizerBlacklist(SanitizerKind::ID, Fn, Loc)) \
  588. SanOpts.set(SanitizerKind::ID, false);
  589. #include "clang/Basic/Sanitizers.def"
  590. #undef SANITIZER
  591. } while (0);
  592. if (D) {
  593. // Apply the no_sanitize* attributes to SanOpts.
  594. for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) {
  595. SanitizerMask mask = Attr->getMask();
  596. SanOpts.Mask &= ~mask;
  597. if (mask & SanitizerKind::Address)
  598. SanOpts.set(SanitizerKind::KernelAddress, false);
  599. if (mask & SanitizerKind::KernelAddress)
  600. SanOpts.set(SanitizerKind::Address, false);
  601. if (mask & SanitizerKind::HWAddress)
  602. SanOpts.set(SanitizerKind::KernelHWAddress, false);
  603. if (mask & SanitizerKind::KernelHWAddress)
  604. SanOpts.set(SanitizerKind::HWAddress, false);
  605. }
  606. }
  607. // Apply sanitizer attributes to the function.
  608. if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
  609. Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
  610. if (SanOpts.hasOneOf(SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress))
  611. Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
  612. if (SanOpts.has(SanitizerKind::MemTag))
  613. Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
  614. if (SanOpts.has(SanitizerKind::Thread))
  615. Fn->addFnAttr(llvm::Attribute::SanitizeThread);
  616. if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
  617. Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
  618. if (SanOpts.has(SanitizerKind::SafeStack))
  619. Fn->addFnAttr(llvm::Attribute::SafeStack);
  620. if (SanOpts.has(SanitizerKind::ShadowCallStack))
  621. Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
  622. // Apply fuzzing attribute to the function.
  623. if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
  624. Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
  625. // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
  626. // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
  627. if (SanOpts.has(SanitizerKind::Thread)) {
  628. if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
  629. IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
  630. if (OMD->getMethodFamily() == OMF_dealloc ||
  631. OMD->getMethodFamily() == OMF_initialize ||
  632. (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
  633. markAsIgnoreThreadCheckingAtRuntime(Fn);
  634. }
  635. }
  636. }
  637. // Ignore unrelated casts in STL allocate() since the allocator must cast
  638. // from void* to T* before object initialization completes. Don't match on the
  639. // namespace because not all allocators are in std::
  640. if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
  641. if (matchesStlAllocatorFn(D, getContext()))
  642. SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
  643. }
  644. // Apply xray attributes to the function (as a string, for now)
  645. if (D) {
  646. if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) {
  647. if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
  648. XRayInstrKind::Function)) {
  649. if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction())
  650. Fn->addFnAttr("function-instrument", "xray-always");
  651. if (XRayAttr->neverXRayInstrument())
  652. Fn->addFnAttr("function-instrument", "xray-never");
  653. if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
  654. if (ShouldXRayInstrumentFunction())
  655. Fn->addFnAttr("xray-log-args",
  656. llvm::utostr(LogArgs->getArgumentCount()));
  657. }
  658. } else {
  659. if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc))
  660. Fn->addFnAttr(
  661. "xray-instruction-threshold",
  662. llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
  663. }
  664. }
  665. // Add no-jump-tables value.
  666. Fn->addFnAttr("no-jump-tables",
  667. llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
  668. // Add profile-sample-accurate value.
  669. if (CGM.getCodeGenOpts().ProfileSampleAccurate)
  670. Fn->addFnAttr("profile-sample-accurate");
  671. if (D && D->hasAttr<CFICanonicalJumpTableAttr>())
  672. Fn->addFnAttr("cfi-canonical-jump-table");
  673. if (getLangOpts().OpenCL) {
  674. // Add metadata for a kernel function.
  675. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  676. EmitOpenCLKernelMetadata(FD, Fn);
  677. }
  678. // If we are checking function types, emit a function type signature as
  679. // prologue data.
  680. if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
  681. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  682. if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
  683. // Remove any (C++17) exception specifications, to allow calling e.g. a
  684. // noexcept function through a non-noexcept pointer.
  685. auto ProtoTy =
  686. getContext().getFunctionTypeWithExceptionSpec(FD->getType(),
  687. EST_None);
  688. llvm::Constant *FTRTTIConst =
  689. CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
  690. llvm::Constant *FTRTTIConstEncoded =
  691. EncodeAddrForUseInPrologue(Fn, FTRTTIConst);
  692. llvm::Constant *PrologueStructElems[] = {PrologueSig,
  693. FTRTTIConstEncoded};
  694. llvm::Constant *PrologueStructConst =
  695. llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
  696. Fn->setPrologueData(PrologueStructConst);
  697. }
  698. }
  699. }
  700. // If we're checking nullability, we need to know whether we can check the
  701. // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
  702. if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
  703. auto Nullability = FnRetTy->getNullability(getContext());
  704. if (Nullability && *Nullability == NullabilityKind::NonNull) {
  705. if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
  706. CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
  707. RetValNullabilityPrecondition =
  708. llvm::ConstantInt::getTrue(getLLVMContext());
  709. }
  710. }
  711. // If we're in C++ mode and the function name is "main", it is guaranteed
  712. // to be norecurse by the standard (3.6.1.3 "The function main shall not be
  713. // used within a program").
  714. if (getLangOpts().CPlusPlus)
  715. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  716. if (FD->isMain())
  717. Fn->addFnAttr(llvm::Attribute::NoRecurse);
  718. // If a custom alignment is used, force realigning to this alignment on
  719. // any main function which certainly will need it.
  720. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  721. if ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
  722. CGM.getCodeGenOpts().StackAlignment)
  723. Fn->addFnAttr("stackrealign");
  724. llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
  725. // Create a marker to make it easy to insert allocas into the entryblock
  726. // later. Don't create this with the builder, because we don't want it
  727. // folded.
  728. llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
  729. AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
  730. ReturnBlock = getJumpDestInCurrentScope("return");
  731. Builder.SetInsertPoint(EntryBB);
  732. // If we're checking the return value, allocate space for a pointer to a
  733. // precise source location of the checked return statement.
  734. if (requiresReturnValueCheck()) {
  735. ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
  736. InitTempAlloca(ReturnLocation, llvm::ConstantPointerNull::get(Int8PtrTy));
  737. }
  738. // Emit subprogram debug descriptor.
  739. if (CGDebugInfo *DI = getDebugInfo()) {
  740. // Reconstruct the type from the argument list so that implicit parameters,
  741. // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
  742. // convention.
  743. CallingConv CC = CallingConv::CC_C;
  744. if (auto *FD = dyn_cast_or_null<FunctionDecl>(D))
  745. if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
  746. CC = SrcFnTy->getCallConv();
  747. SmallVector<QualType, 16> ArgTypes;
  748. for (const VarDecl *VD : Args)
  749. ArgTypes.push_back(VD->getType());
  750. QualType FnType = getContext().getFunctionType(
  751. RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
  752. DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, CurFuncIsThunk,
  753. Builder);
  754. }
  755. if (ShouldInstrumentFunction()) {
  756. if (CGM.getCodeGenOpts().InstrumentFunctions)
  757. CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
  758. if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
  759. CurFn->addFnAttr("instrument-function-entry-inlined",
  760. "__cyg_profile_func_enter");
  761. if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
  762. CurFn->addFnAttr("instrument-function-entry-inlined",
  763. "__cyg_profile_func_enter_bare");
  764. }
  765. // Since emitting the mcount call here impacts optimizations such as function
  766. // inlining, we just add an attribute to insert a mcount call in backend.
  767. // The attribute "counting-function" is set to mcount function name which is
  768. // architecture dependent.
  769. if (CGM.getCodeGenOpts().InstrumentForProfiling) {
  770. // Calls to fentry/mcount should not be generated if function has
  771. // the no_instrument_function attribute.
  772. if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
  773. if (CGM.getCodeGenOpts().CallFEntry)
  774. Fn->addFnAttr("fentry-call", "true");
  775. else {
  776. Fn->addFnAttr("instrument-function-entry-inlined",
  777. getTarget().getMCountName());
  778. }
  779. }
  780. }
  781. if (RetTy->isVoidType()) {
  782. // Void type; nothing to return.
  783. ReturnValue = Address::invalid();
  784. // Count the implicit return.
  785. if (!endsWithReturn(D))
  786. ++NumReturnExprs;
  787. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
  788. // Indirect return; emit returned value directly into sret slot.
  789. // This reduces code size, and affects correctness in C++.
  790. auto AI = CurFn->arg_begin();
  791. if (CurFnInfo->getReturnInfo().isSRetAfterThis())
  792. ++AI;
  793. ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
  794. if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
  795. ReturnValuePointer =
  796. CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
  797. Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast(
  798. ReturnValue.getPointer(), Int8PtrTy),
  799. ReturnValuePointer);
  800. }
  801. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
  802. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  803. // Load the sret pointer from the argument struct and return into that.
  804. unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
  805. llvm::Function::arg_iterator EI = CurFn->arg_end();
  806. --EI;
  807. llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
  808. ReturnValuePointer = Address(Addr, getPointerAlign());
  809. Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
  810. ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
  811. } else {
  812. ReturnValue = CreateIRTemp(RetTy, "retval");
  813. // Tell the epilog emitter to autorelease the result. We do this
  814. // now so that various specialized functions can suppress it
  815. // during their IR-generation.
  816. if (getLangOpts().ObjCAutoRefCount &&
  817. !CurFnInfo->isReturnsRetained() &&
  818. RetTy->isObjCRetainableType())
  819. AutoreleaseResult = true;
  820. }
  821. EmitStartEHSpec(CurCodeDecl);
  822. PrologueCleanupDepth = EHStack.stable_begin();
  823. // Emit OpenMP specific initialization of the device functions.
  824. if (getLangOpts().OpenMP && CurCodeDecl)
  825. CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
  826. EmitFunctionProlog(*CurFnInfo, CurFn, Args);
  827. if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
  828. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  829. const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
  830. if (MD->getParent()->isLambda() &&
  831. MD->getOverloadedOperator() == OO_Call) {
  832. // We're in a lambda; figure out the captures.
  833. MD->getParent()->getCaptureFields(LambdaCaptureFields,
  834. LambdaThisCaptureField);
  835. if (LambdaThisCaptureField) {
  836. // If the lambda captures the object referred to by '*this' - either by
  837. // value or by reference, make sure CXXThisValue points to the correct
  838. // object.
  839. // Get the lvalue for the field (which is a copy of the enclosing object
  840. // or contains the address of the enclosing object).
  841. LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
  842. if (!LambdaThisCaptureField->getType()->isPointerType()) {
  843. // If the enclosing object was captured by value, just use its address.
  844. CXXThisValue = ThisFieldLValue.getAddress().getPointer();
  845. } else {
  846. // Load the lvalue pointed to by the field, since '*this' was captured
  847. // by reference.
  848. CXXThisValue =
  849. EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
  850. }
  851. }
  852. for (auto *FD : MD->getParent()->fields()) {
  853. if (FD->hasCapturedVLAType()) {
  854. auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
  855. SourceLocation()).getScalarVal();
  856. auto VAT = FD->getCapturedVLAType();
  857. VLASizeMap[VAT->getSizeExpr()] = ExprArg;
  858. }
  859. }
  860. } else {
  861. // Not in a lambda; just use 'this' from the method.
  862. // FIXME: Should we generate a new load for each use of 'this'? The
  863. // fast register allocator would be happier...
  864. CXXThisValue = CXXABIThisValue;
  865. }
  866. // Check the 'this' pointer once per function, if it's available.
  867. if (CXXABIThisValue) {
  868. SanitizerSet SkippedChecks;
  869. SkippedChecks.set(SanitizerKind::ObjectSize, true);
  870. QualType ThisTy = MD->getThisType();
  871. // If this is the call operator of a lambda with no capture-default, it
  872. // may have a static invoker function, which may call this operator with
  873. // a null 'this' pointer.
  874. if (isLambdaCallOperator(MD) &&
  875. MD->getParent()->getLambdaCaptureDefault() == LCD_None)
  876. SkippedChecks.set(SanitizerKind::Null, true);
  877. EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall
  878. : TCK_MemberCall,
  879. Loc, CXXABIThisValue, ThisTy,
  880. getContext().getTypeAlignInChars(ThisTy->getPointeeType()),
  881. SkippedChecks);
  882. }
  883. }
  884. // If any of the arguments have a variably modified type, make sure to
  885. // emit the type size.
  886. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  887. i != e; ++i) {
  888. const VarDecl *VD = *i;
  889. // Dig out the type as written from ParmVarDecls; it's unclear whether
  890. // the standard (C99 6.9.1p10) requires this, but we're following the
  891. // precedent set by gcc.
  892. QualType Ty;
  893. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
  894. Ty = PVD->getOriginalType();
  895. else
  896. Ty = VD->getType();
  897. if (Ty->isVariablyModifiedType())
  898. EmitVariablyModifiedType(Ty);
  899. }
  900. // Emit a location at the end of the prologue.
  901. if (CGDebugInfo *DI = getDebugInfo())
  902. DI->EmitLocation(Builder, StartLoc);
  903. // TODO: Do we need to handle this in two places like we do with
  904. // target-features/target-cpu?
  905. if (CurFuncDecl)
  906. if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
  907. LargestVectorWidth = VecWidth->getVectorWidth();
  908. }
  909. void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
  910. incrementProfileCounter(Body);
  911. if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
  912. EmitCompoundStmtWithoutScope(*S);
  913. else
  914. EmitStmt(Body);
  915. }
  916. /// When instrumenting to collect profile data, the counts for some blocks
  917. /// such as switch cases need to not include the fall-through counts, so
  918. /// emit a branch around the instrumentation code. When not instrumenting,
  919. /// this just calls EmitBlock().
  920. void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
  921. const Stmt *S) {
  922. llvm::BasicBlock *SkipCountBB = nullptr;
  923. if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
  924. // When instrumenting for profiling, the fallthrough to certain
  925. // statements needs to skip over the instrumentation code so that we
  926. // get an accurate count.
  927. SkipCountBB = createBasicBlock("skipcount");
  928. EmitBranch(SkipCountBB);
  929. }
  930. EmitBlock(BB);
  931. uint64_t CurrentCount = getCurrentProfileCount();
  932. incrementProfileCounter(S);
  933. setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
  934. if (SkipCountBB)
  935. EmitBlock(SkipCountBB);
  936. }
  937. /// Tries to mark the given function nounwind based on the
  938. /// non-existence of any throwing calls within it. We believe this is
  939. /// lightweight enough to do at -O0.
  940. static void TryMarkNoThrow(llvm::Function *F) {
  941. // LLVM treats 'nounwind' on a function as part of the type, so we
  942. // can't do this on functions that can be overwritten.
  943. if (F->isInterposable()) return;
  944. for (llvm::BasicBlock &BB : *F)
  945. for (llvm::Instruction &I : BB)
  946. if (I.mayThrow())
  947. return;
  948. F->setDoesNotThrow();
  949. }
  950. QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
  951. FunctionArgList &Args) {
  952. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  953. QualType ResTy = FD->getReturnType();
  954. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  955. if (MD && MD->isInstance()) {
  956. if (CGM.getCXXABI().HasThisReturn(GD))
  957. ResTy = MD->getThisType();
  958. else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
  959. ResTy = CGM.getContext().VoidPtrTy;
  960. CGM.getCXXABI().buildThisParam(*this, Args);
  961. }
  962. // The base version of an inheriting constructor whose constructed base is a
  963. // virtual base is not passed any arguments (because it doesn't actually call
  964. // the inherited constructor).
  965. bool PassedParams = true;
  966. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
  967. if (auto Inherited = CD->getInheritedConstructor())
  968. PassedParams =
  969. getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
  970. if (PassedParams) {
  971. for (auto *Param : FD->parameters()) {
  972. Args.push_back(Param);
  973. if (!Param->hasAttr<PassObjectSizeAttr>())
  974. continue;
  975. auto *Implicit = ImplicitParamDecl::Create(
  976. getContext(), Param->getDeclContext(), Param->getLocation(),
  977. /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other);
  978. SizeArguments[Param] = Implicit;
  979. Args.push_back(Implicit);
  980. }
  981. }
  982. if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
  983. CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
  984. return ResTy;
  985. }
  986. static bool
  987. shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD,
  988. const ASTContext &Context) {
  989. QualType T = FD->getReturnType();
  990. // Avoid the optimization for functions that return a record type with a
  991. // trivial destructor or another trivially copyable type.
  992. if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) {
  993. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  994. return !ClassDecl->hasTrivialDestructor();
  995. }
  996. return !T.isTriviallyCopyableType(Context);
  997. }
  998. void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  999. const CGFunctionInfo &FnInfo) {
  1000. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  1001. CurGD = GD;
  1002. FunctionArgList Args;
  1003. QualType ResTy = BuildFunctionArgList(GD, Args);
  1004. // Check if we should generate debug info for this function.
  1005. if (FD->hasAttr<NoDebugAttr>())
  1006. DebugInfo = nullptr; // disable debug info indefinitely for this function
  1007. // The function might not have a body if we're generating thunks for a
  1008. // function declaration.
  1009. SourceRange BodyRange;
  1010. if (Stmt *Body = FD->getBody())
  1011. BodyRange = Body->getSourceRange();
  1012. else
  1013. BodyRange = FD->getLocation();
  1014. CurEHLocation = BodyRange.getEnd();
  1015. // Use the location of the start of the function to determine where
  1016. // the function definition is located. By default use the location
  1017. // of the declaration as the location for the subprogram. A function
  1018. // may lack a declaration in the source code if it is created by code
  1019. // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
  1020. SourceLocation Loc = FD->getLocation();
  1021. // If this is a function specialization then use the pattern body
  1022. // as the location for the function.
  1023. if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
  1024. if (SpecDecl->hasBody(SpecDecl))
  1025. Loc = SpecDecl->getLocation();
  1026. Stmt *Body = FD->getBody();
  1027. // Initialize helper which will detect jumps which can cause invalid lifetime
  1028. // markers.
  1029. if (Body && ShouldEmitLifetimeMarkers)
  1030. Bypasses.Init(Body);
  1031. // Emit the standard function prologue.
  1032. StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
  1033. // Generate the body of the function.
  1034. PGO.assignRegionCounters(GD, CurFn);
  1035. if (isa<CXXDestructorDecl>(FD))
  1036. EmitDestructorBody(Args);
  1037. else if (isa<CXXConstructorDecl>(FD))
  1038. EmitConstructorBody(Args);
  1039. else if (getLangOpts().CUDA &&
  1040. !getLangOpts().CUDAIsDevice &&
  1041. FD->hasAttr<CUDAGlobalAttr>())
  1042. CGM.getCUDARuntime().emitDeviceStub(*this, Args);
  1043. else if (isa<CXXMethodDecl>(FD) &&
  1044. cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
  1045. // The lambda static invoker function is special, because it forwards or
  1046. // clones the body of the function call operator (but is actually static).
  1047. EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
  1048. } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
  1049. (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
  1050. cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
  1051. // Implicit copy-assignment gets the same special treatment as implicit
  1052. // copy-constructors.
  1053. emitImplicitAssignmentOperatorBody(Args);
  1054. } else if (Body) {
  1055. EmitFunctionBody(Body);
  1056. } else
  1057. llvm_unreachable("no definition for emitted function");
  1058. // C++11 [stmt.return]p2:
  1059. // Flowing off the end of a function [...] results in undefined behavior in
  1060. // a value-returning function.
  1061. // C11 6.9.1p12:
  1062. // If the '}' that terminates a function is reached, and the value of the
  1063. // function call is used by the caller, the behavior is undefined.
  1064. if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
  1065. !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
  1066. bool ShouldEmitUnreachable =
  1067. CGM.getCodeGenOpts().StrictReturn ||
  1068. shouldUseUndefinedBehaviorReturnOptimization(FD, getContext());
  1069. if (SanOpts.has(SanitizerKind::Return)) {
  1070. SanitizerScope SanScope(this);
  1071. llvm::Value *IsFalse = Builder.getFalse();
  1072. EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
  1073. SanitizerHandler::MissingReturn,
  1074. EmitCheckSourceLocation(FD->getLocation()), None);
  1075. } else if (ShouldEmitUnreachable) {
  1076. if (CGM.getCodeGenOpts().OptimizationLevel == 0)
  1077. EmitTrapCall(llvm::Intrinsic::trap);
  1078. }
  1079. if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
  1080. Builder.CreateUnreachable();
  1081. Builder.ClearInsertionPoint();
  1082. }
  1083. }
  1084. // Emit the standard function epilogue.
  1085. FinishFunction(BodyRange.getEnd());
  1086. // If we haven't marked the function nothrow through other means, do
  1087. // a quick pass now to see if we can.
  1088. if (!CurFn->doesNotThrow())
  1089. TryMarkNoThrow(CurFn);
  1090. }
  1091. /// ContainsLabel - Return true if the statement contains a label in it. If
  1092. /// this statement is not executed normally, it not containing a label means
  1093. /// that we can just remove the code.
  1094. bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
  1095. // Null statement, not a label!
  1096. if (!S) return false;
  1097. // If this is a label, we have to emit the code, consider something like:
  1098. // if (0) { ... foo: bar(); } goto foo;
  1099. //
  1100. // TODO: If anyone cared, we could track __label__'s, since we know that you
  1101. // can't jump to one from outside their declared region.
  1102. if (isa<LabelStmt>(S))
  1103. return true;
  1104. // If this is a case/default statement, and we haven't seen a switch, we have
  1105. // to emit the code.
  1106. if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
  1107. return true;
  1108. // If this is a switch statement, we want to ignore cases below it.
  1109. if (isa<SwitchStmt>(S))
  1110. IgnoreCaseStmts = true;
  1111. // Scan subexpressions for verboten labels.
  1112. for (const Stmt *SubStmt : S->children())
  1113. if (ContainsLabel(SubStmt, IgnoreCaseStmts))
  1114. return true;
  1115. return false;
  1116. }
  1117. /// containsBreak - Return true if the statement contains a break out of it.
  1118. /// If the statement (recursively) contains a switch or loop with a break
  1119. /// inside of it, this is fine.
  1120. bool CodeGenFunction::containsBreak(const Stmt *S) {
  1121. // Null statement, not a label!
  1122. if (!S) return false;
  1123. // If this is a switch or loop that defines its own break scope, then we can
  1124. // include it and anything inside of it.
  1125. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
  1126. isa<ForStmt>(S))
  1127. return false;
  1128. if (isa<BreakStmt>(S))
  1129. return true;
  1130. // Scan subexpressions for verboten breaks.
  1131. for (const Stmt *SubStmt : S->children())
  1132. if (containsBreak(SubStmt))
  1133. return true;
  1134. return false;
  1135. }
  1136. bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
  1137. if (!S) return false;
  1138. // Some statement kinds add a scope and thus never add a decl to the current
  1139. // scope. Note, this list is longer than the list of statements that might
  1140. // have an unscoped decl nested within them, but this way is conservatively
  1141. // correct even if more statement kinds are added.
  1142. if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
  1143. isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
  1144. isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
  1145. isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
  1146. return false;
  1147. if (isa<DeclStmt>(S))
  1148. return true;
  1149. for (const Stmt *SubStmt : S->children())
  1150. if (mightAddDeclToScope(SubStmt))
  1151. return true;
  1152. return false;
  1153. }
  1154. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1155. /// to a constant, or if it does but contains a label, return false. If it
  1156. /// constant folds return true and set the boolean result in Result.
  1157. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  1158. bool &ResultBool,
  1159. bool AllowLabels) {
  1160. llvm::APSInt ResultInt;
  1161. if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
  1162. return false;
  1163. ResultBool = ResultInt.getBoolValue();
  1164. return true;
  1165. }
  1166. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1167. /// to a constant, or if it does but contains a label, return false. If it
  1168. /// constant folds return true and set the folded value.
  1169. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  1170. llvm::APSInt &ResultInt,
  1171. bool AllowLabels) {
  1172. // FIXME: Rename and handle conversion of other evaluatable things
  1173. // to bool.
  1174. Expr::EvalResult Result;
  1175. if (!Cond->EvaluateAsInt(Result, getContext()))
  1176. return false; // Not foldable, not integer or not fully evaluatable.
  1177. llvm::APSInt Int = Result.Val.getInt();
  1178. if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
  1179. return false; // Contains a label.
  1180. ResultInt = Int;
  1181. return true;
  1182. }
  1183. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
  1184. /// statement) to the specified blocks. Based on the condition, this might try
  1185. /// to simplify the codegen of the conditional based on the branch.
  1186. ///
  1187. void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
  1188. llvm::BasicBlock *TrueBlock,
  1189. llvm::BasicBlock *FalseBlock,
  1190. uint64_t TrueCount) {
  1191. Cond = Cond->IgnoreParens();
  1192. if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
  1193. // Handle X && Y in a condition.
  1194. if (CondBOp->getOpcode() == BO_LAnd) {
  1195. // If we have "1 && X", simplify the code. "0 && X" would have constant
  1196. // folded if the case was simple enough.
  1197. bool ConstantBool = false;
  1198. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  1199. ConstantBool) {
  1200. // br(1 && X) -> br(X).
  1201. incrementProfileCounter(CondBOp);
  1202. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  1203. TrueCount);
  1204. }
  1205. // If we have "X && 1", simplify the code to use an uncond branch.
  1206. // "X && 0" would have been constant folded to 0.
  1207. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  1208. ConstantBool) {
  1209. // br(X && 1) -> br(X).
  1210. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  1211. TrueCount);
  1212. }
  1213. // Emit the LHS as a conditional. If the LHS conditional is false, we
  1214. // want to jump to the FalseBlock.
  1215. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
  1216. // The counter tells us how often we evaluate RHS, and all of TrueCount
  1217. // can be propagated to that branch.
  1218. uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
  1219. ConditionalEvaluation eval(*this);
  1220. {
  1221. ApplyDebugLocation DL(*this, Cond);
  1222. EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
  1223. EmitBlock(LHSTrue);
  1224. }
  1225. incrementProfileCounter(CondBOp);
  1226. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1227. // Any temporaries created here are conditional.
  1228. eval.begin(*this);
  1229. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
  1230. eval.end(*this);
  1231. return;
  1232. }
  1233. if (CondBOp->getOpcode() == BO_LOr) {
  1234. // If we have "0 || X", simplify the code. "1 || X" would have constant
  1235. // folded if the case was simple enough.
  1236. bool ConstantBool = false;
  1237. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  1238. !ConstantBool) {
  1239. // br(0 || X) -> br(X).
  1240. incrementProfileCounter(CondBOp);
  1241. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  1242. TrueCount);
  1243. }
  1244. // If we have "X || 0", simplify the code to use an uncond branch.
  1245. // "X || 1" would have been constant folded to 1.
  1246. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  1247. !ConstantBool) {
  1248. // br(X || 0) -> br(X).
  1249. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  1250. TrueCount);
  1251. }
  1252. // Emit the LHS as a conditional. If the LHS conditional is true, we
  1253. // want to jump to the TrueBlock.
  1254. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
  1255. // We have the count for entry to the RHS and for the whole expression
  1256. // being true, so we can divy up True count between the short circuit and
  1257. // the RHS.
  1258. uint64_t LHSCount =
  1259. getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
  1260. uint64_t RHSCount = TrueCount - LHSCount;
  1261. ConditionalEvaluation eval(*this);
  1262. {
  1263. ApplyDebugLocation DL(*this, Cond);
  1264. EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
  1265. EmitBlock(LHSFalse);
  1266. }
  1267. incrementProfileCounter(CondBOp);
  1268. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1269. // Any temporaries created here are conditional.
  1270. eval.begin(*this);
  1271. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
  1272. eval.end(*this);
  1273. return;
  1274. }
  1275. }
  1276. if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
  1277. // br(!x, t, f) -> br(x, f, t)
  1278. if (CondUOp->getOpcode() == UO_LNot) {
  1279. // Negate the count.
  1280. uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
  1281. // Negate the condition and swap the destination blocks.
  1282. return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
  1283. FalseCount);
  1284. }
  1285. }
  1286. if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
  1287. // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
  1288. llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
  1289. llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
  1290. ConditionalEvaluation cond(*this);
  1291. EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
  1292. getProfileCount(CondOp));
  1293. // When computing PGO branch weights, we only know the overall count for
  1294. // the true block. This code is essentially doing tail duplication of the
  1295. // naive code-gen, introducing new edges for which counts are not
  1296. // available. Divide the counts proportionally between the LHS and RHS of
  1297. // the conditional operator.
  1298. uint64_t LHSScaledTrueCount = 0;
  1299. if (TrueCount) {
  1300. double LHSRatio =
  1301. getProfileCount(CondOp) / (double)getCurrentProfileCount();
  1302. LHSScaledTrueCount = TrueCount * LHSRatio;
  1303. }
  1304. cond.begin(*this);
  1305. EmitBlock(LHSBlock);
  1306. incrementProfileCounter(CondOp);
  1307. {
  1308. ApplyDebugLocation DL(*this, Cond);
  1309. EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
  1310. LHSScaledTrueCount);
  1311. }
  1312. cond.end(*this);
  1313. cond.begin(*this);
  1314. EmitBlock(RHSBlock);
  1315. EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
  1316. TrueCount - LHSScaledTrueCount);
  1317. cond.end(*this);
  1318. return;
  1319. }
  1320. if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
  1321. // Conditional operator handling can give us a throw expression as a
  1322. // condition for a case like:
  1323. // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
  1324. // Fold this to:
  1325. // br(c, throw x, br(y, t, f))
  1326. EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
  1327. return;
  1328. }
  1329. // If the branch has a condition wrapped by __builtin_unpredictable,
  1330. // create metadata that specifies that the branch is unpredictable.
  1331. // Don't bother if not optimizing because that metadata would not be used.
  1332. llvm::MDNode *Unpredictable = nullptr;
  1333. auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
  1334. if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
  1335. auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
  1336. if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
  1337. llvm::MDBuilder MDHelper(getLLVMContext());
  1338. Unpredictable = MDHelper.createUnpredictable();
  1339. }
  1340. }
  1341. // Create branch weights based on the number of times we get here and the
  1342. // number of times the condition should be true.
  1343. uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
  1344. llvm::MDNode *Weights =
  1345. createProfileWeights(TrueCount, CurrentCount - TrueCount);
  1346. // Emit the code with the fully general case.
  1347. llvm::Value *CondV;
  1348. {
  1349. ApplyDebugLocation DL(*this, Cond);
  1350. CondV = EvaluateExprAsBool(Cond);
  1351. }
  1352. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
  1353. }
  1354. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1355. /// specified stmt yet.
  1356. void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
  1357. CGM.ErrorUnsupported(S, Type);
  1358. }
  1359. /// emitNonZeroVLAInit - Emit the "zero" initialization of a
  1360. /// variable-length array whose elements have a non-zero bit-pattern.
  1361. ///
  1362. /// \param baseType the inner-most element type of the array
  1363. /// \param src - a char* pointing to the bit-pattern for a single
  1364. /// base element of the array
  1365. /// \param sizeInChars - the total size of the VLA, in chars
  1366. static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
  1367. Address dest, Address src,
  1368. llvm::Value *sizeInChars) {
  1369. CGBuilderTy &Builder = CGF.Builder;
  1370. CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
  1371. llvm::Value *baseSizeInChars
  1372. = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
  1373. Address begin =
  1374. Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
  1375. llvm::Value *end =
  1376. Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
  1377. llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
  1378. llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
  1379. llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
  1380. // Make a loop over the VLA. C99 guarantees that the VLA element
  1381. // count must be nonzero.
  1382. CGF.EmitBlock(loopBB);
  1383. llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
  1384. cur->addIncoming(begin.getPointer(), originBB);
  1385. CharUnits curAlign =
  1386. dest.getAlignment().alignmentOfArrayElement(baseSize);
  1387. // memcpy the individual element bit-pattern.
  1388. Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
  1389. /*volatile*/ false);
  1390. // Go to the next element.
  1391. llvm::Value *next =
  1392. Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
  1393. // Leave if that's the end of the VLA.
  1394. llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
  1395. Builder.CreateCondBr(done, contBB, loopBB);
  1396. cur->addIncoming(next, loopBB);
  1397. CGF.EmitBlock(contBB);
  1398. }
  1399. void
  1400. CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
  1401. // Ignore empty classes in C++.
  1402. if (getLangOpts().CPlusPlus) {
  1403. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  1404. if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
  1405. return;
  1406. }
  1407. }
  1408. // Cast the dest ptr to the appropriate i8 pointer type.
  1409. if (DestPtr.getElementType() != Int8Ty)
  1410. DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
  1411. // Get size and alignment info for this aggregate.
  1412. CharUnits size = getContext().getTypeSizeInChars(Ty);
  1413. llvm::Value *SizeVal;
  1414. const VariableArrayType *vla;
  1415. // Don't bother emitting a zero-byte memset.
  1416. if (size.isZero()) {
  1417. // But note that getTypeInfo returns 0 for a VLA.
  1418. if (const VariableArrayType *vlaType =
  1419. dyn_cast_or_null<VariableArrayType>(
  1420. getContext().getAsArrayType(Ty))) {
  1421. auto VlaSize = getVLASize(vlaType);
  1422. SizeVal = VlaSize.NumElts;
  1423. CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
  1424. if (!eltSize.isOne())
  1425. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
  1426. vla = vlaType;
  1427. } else {
  1428. return;
  1429. }
  1430. } else {
  1431. SizeVal = CGM.getSize(size);
  1432. vla = nullptr;
  1433. }
  1434. // If the type contains a pointer to data member we can't memset it to zero.
  1435. // Instead, create a null constant and copy it to the destination.
  1436. // TODO: there are other patterns besides zero that we can usefully memset,
  1437. // like -1, which happens to be the pattern used by member-pointers.
  1438. if (!CGM.getTypes().isZeroInitializable(Ty)) {
  1439. // For a VLA, emit a single element, then splat that over the VLA.
  1440. if (vla) Ty = getContext().getBaseElementType(vla);
  1441. llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
  1442. llvm::GlobalVariable *NullVariable =
  1443. new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
  1444. /*isConstant=*/true,
  1445. llvm::GlobalVariable::PrivateLinkage,
  1446. NullConstant, Twine());
  1447. CharUnits NullAlign = DestPtr.getAlignment();
  1448. NullVariable->setAlignment(NullAlign.getQuantity());
  1449. Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
  1450. NullAlign);
  1451. if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
  1452. // Get and call the appropriate llvm.memcpy overload.
  1453. Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
  1454. return;
  1455. }
  1456. // Otherwise, just memset the whole thing to zero. This is legal
  1457. // because in LLVM, all default initializers (other than the ones we just
  1458. // handled above) are guaranteed to have a bit pattern of all zeros.
  1459. Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
  1460. }
  1461. llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
  1462. // Make sure that there is a block for the indirect goto.
  1463. if (!IndirectBranch)
  1464. GetIndirectGotoBlock();
  1465. llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
  1466. // Make sure the indirect branch includes all of the address-taken blocks.
  1467. IndirectBranch->addDestination(BB);
  1468. return llvm::BlockAddress::get(CurFn, BB);
  1469. }
  1470. llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
  1471. // If we already made the indirect branch for indirect goto, return its block.
  1472. if (IndirectBranch) return IndirectBranch->getParent();
  1473. CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
  1474. // Create the PHI node that indirect gotos will add entries to.
  1475. llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
  1476. "indirect.goto.dest");
  1477. // Create the indirect branch instruction.
  1478. IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
  1479. return IndirectBranch->getParent();
  1480. }
  1481. /// Computes the length of an array in elements, as well as the base
  1482. /// element type and a properly-typed first element pointer.
  1483. llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
  1484. QualType &baseType,
  1485. Address &addr) {
  1486. const ArrayType *arrayType = origArrayType;
  1487. // If it's a VLA, we have to load the stored size. Note that
  1488. // this is the size of the VLA in bytes, not its size in elements.
  1489. llvm::Value *numVLAElements = nullptr;
  1490. if (isa<VariableArrayType>(arrayType)) {
  1491. numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
  1492. // Walk into all VLAs. This doesn't require changes to addr,
  1493. // which has type T* where T is the first non-VLA element type.
  1494. do {
  1495. QualType elementType = arrayType->getElementType();
  1496. arrayType = getContext().getAsArrayType(elementType);
  1497. // If we only have VLA components, 'addr' requires no adjustment.
  1498. if (!arrayType) {
  1499. baseType = elementType;
  1500. return numVLAElements;
  1501. }
  1502. } while (isa<VariableArrayType>(arrayType));
  1503. // We get out here only if we find a constant array type
  1504. // inside the VLA.
  1505. }
  1506. // We have some number of constant-length arrays, so addr should
  1507. // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
  1508. // down to the first element of addr.
  1509. SmallVector<llvm::Value*, 8> gepIndices;
  1510. // GEP down to the array type.
  1511. llvm::ConstantInt *zero = Builder.getInt32(0);
  1512. gepIndices.push_back(zero);
  1513. uint64_t countFromCLAs = 1;
  1514. QualType eltType;
  1515. llvm::ArrayType *llvmArrayType =
  1516. dyn_cast<llvm::ArrayType>(addr.getElementType());
  1517. while (llvmArrayType) {
  1518. assert(isa<ConstantArrayType>(arrayType));
  1519. assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
  1520. == llvmArrayType->getNumElements());
  1521. gepIndices.push_back(zero);
  1522. countFromCLAs *= llvmArrayType->getNumElements();
  1523. eltType = arrayType->getElementType();
  1524. llvmArrayType =
  1525. dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
  1526. arrayType = getContext().getAsArrayType(arrayType->getElementType());
  1527. assert((!llvmArrayType || arrayType) &&
  1528. "LLVM and Clang types are out-of-synch");
  1529. }
  1530. if (arrayType) {
  1531. // From this point onwards, the Clang array type has been emitted
  1532. // as some other type (probably a packed struct). Compute the array
  1533. // size, and just emit the 'begin' expression as a bitcast.
  1534. while (arrayType) {
  1535. countFromCLAs *=
  1536. cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
  1537. eltType = arrayType->getElementType();
  1538. arrayType = getContext().getAsArrayType(eltType);
  1539. }
  1540. llvm::Type *baseType = ConvertType(eltType);
  1541. addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
  1542. } else {
  1543. // Create the actual GEP.
  1544. addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
  1545. gepIndices, "array.begin"),
  1546. addr.getAlignment());
  1547. }
  1548. baseType = eltType;
  1549. llvm::Value *numElements
  1550. = llvm::ConstantInt::get(SizeTy, countFromCLAs);
  1551. // If we had any VLA dimensions, factor them in.
  1552. if (numVLAElements)
  1553. numElements = Builder.CreateNUWMul(numVLAElements, numElements);
  1554. return numElements;
  1555. }
  1556. CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
  1557. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1558. assert(vla && "type was not a variable array type!");
  1559. return getVLASize(vla);
  1560. }
  1561. CodeGenFunction::VlaSizePair
  1562. CodeGenFunction::getVLASize(const VariableArrayType *type) {
  1563. // The number of elements so far; always size_t.
  1564. llvm::Value *numElements = nullptr;
  1565. QualType elementType;
  1566. do {
  1567. elementType = type->getElementType();
  1568. llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
  1569. assert(vlaSize && "no size for VLA!");
  1570. assert(vlaSize->getType() == SizeTy);
  1571. if (!numElements) {
  1572. numElements = vlaSize;
  1573. } else {
  1574. // It's undefined behavior if this wraps around, so mark it that way.
  1575. // FIXME: Teach -fsanitize=undefined to trap this.
  1576. numElements = Builder.CreateNUWMul(numElements, vlaSize);
  1577. }
  1578. } while ((type = getContext().getAsVariableArrayType(elementType)));
  1579. return { numElements, elementType };
  1580. }
  1581. CodeGenFunction::VlaSizePair
  1582. CodeGenFunction::getVLAElements1D(QualType type) {
  1583. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1584. assert(vla && "type was not a variable array type!");
  1585. return getVLAElements1D(vla);
  1586. }
  1587. CodeGenFunction::VlaSizePair
  1588. CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
  1589. llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
  1590. assert(VlaSize && "no size for VLA!");
  1591. assert(VlaSize->getType() == SizeTy);
  1592. return { VlaSize, Vla->getElementType() };
  1593. }
  1594. void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
  1595. assert(type->isVariablyModifiedType() &&
  1596. "Must pass variably modified type to EmitVLASizes!");
  1597. EnsureInsertPoint();
  1598. // We're going to walk down into the type and look for VLA
  1599. // expressions.
  1600. do {
  1601. assert(type->isVariablyModifiedType());
  1602. const Type *ty = type.getTypePtr();
  1603. switch (ty->getTypeClass()) {
  1604. #define TYPE(Class, Base)
  1605. #define ABSTRACT_TYPE(Class, Base)
  1606. #define NON_CANONICAL_TYPE(Class, Base)
  1607. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1608. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  1609. #include "clang/AST/TypeNodes.def"
  1610. llvm_unreachable("unexpected dependent type!");
  1611. // These types are never variably-modified.
  1612. case Type::Builtin:
  1613. case Type::Complex:
  1614. case Type::Vector:
  1615. case Type::ExtVector:
  1616. case Type::Record:
  1617. case Type::Enum:
  1618. case Type::Elaborated:
  1619. case Type::TemplateSpecialization:
  1620. case Type::ObjCTypeParam:
  1621. case Type::ObjCObject:
  1622. case Type::ObjCInterface:
  1623. case Type::ObjCObjectPointer:
  1624. llvm_unreachable("type class is never variably-modified!");
  1625. case Type::Adjusted:
  1626. type = cast<AdjustedType>(ty)->getAdjustedType();
  1627. break;
  1628. case Type::Decayed:
  1629. type = cast<DecayedType>(ty)->getPointeeType();
  1630. break;
  1631. case Type::Pointer:
  1632. type = cast<PointerType>(ty)->getPointeeType();
  1633. break;
  1634. case Type::BlockPointer:
  1635. type = cast<BlockPointerType>(ty)->getPointeeType();
  1636. break;
  1637. case Type::LValueReference:
  1638. case Type::RValueReference:
  1639. type = cast<ReferenceType>(ty)->getPointeeType();
  1640. break;
  1641. case Type::MemberPointer:
  1642. type = cast<MemberPointerType>(ty)->getPointeeType();
  1643. break;
  1644. case Type::ConstantArray:
  1645. case Type::IncompleteArray:
  1646. // Losing element qualification here is fine.
  1647. type = cast<ArrayType>(ty)->getElementType();
  1648. break;
  1649. case Type::VariableArray: {
  1650. // Losing element qualification here is fine.
  1651. const VariableArrayType *vat = cast<VariableArrayType>(ty);
  1652. // Unknown size indication requires no size computation.
  1653. // Otherwise, evaluate and record it.
  1654. if (const Expr *size = vat->getSizeExpr()) {
  1655. // It's possible that we might have emitted this already,
  1656. // e.g. with a typedef and a pointer to it.
  1657. llvm::Value *&entry = VLASizeMap[size];
  1658. if (!entry) {
  1659. llvm::Value *Size = EmitScalarExpr(size);
  1660. // C11 6.7.6.2p5:
  1661. // If the size is an expression that is not an integer constant
  1662. // expression [...] each time it is evaluated it shall have a value
  1663. // greater than zero.
  1664. if (SanOpts.has(SanitizerKind::VLABound) &&
  1665. size->getType()->isSignedIntegerType()) {
  1666. SanitizerScope SanScope(this);
  1667. llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
  1668. llvm::Constant *StaticArgs[] = {
  1669. EmitCheckSourceLocation(size->getBeginLoc()),
  1670. EmitCheckTypeDescriptor(size->getType())};
  1671. EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
  1672. SanitizerKind::VLABound),
  1673. SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
  1674. }
  1675. // Always zexting here would be wrong if it weren't
  1676. // undefined behavior to have a negative bound.
  1677. entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
  1678. }
  1679. }
  1680. type = vat->getElementType();
  1681. break;
  1682. }
  1683. case Type::FunctionProto:
  1684. case Type::FunctionNoProto:
  1685. type = cast<FunctionType>(ty)->getReturnType();
  1686. break;
  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. case Type::MacroQualified:
  1694. // Keep walking after single level desugaring.
  1695. type = type.getSingleStepDesugaredType(getContext());
  1696. break;
  1697. case Type::Typedef:
  1698. case Type::Decltype:
  1699. case Type::Auto:
  1700. case Type::DeducedTemplateSpecialization:
  1701. // Stop walking: nothing to do.
  1702. return;
  1703. case Type::TypeOfExpr:
  1704. // Stop walking: emit typeof expression.
  1705. EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
  1706. return;
  1707. case Type::Atomic:
  1708. type = cast<AtomicType>(ty)->getValueType();
  1709. break;
  1710. case Type::Pipe:
  1711. type = cast<PipeType>(ty)->getElementType();
  1712. break;
  1713. }
  1714. } while (type->isVariablyModifiedType());
  1715. }
  1716. Address CodeGenFunction::EmitVAListRef(const Expr* E) {
  1717. if (getContext().getBuiltinVaListType()->isArrayType())
  1718. return EmitPointerWithAlignment(E);
  1719. return EmitLValue(E).getAddress();
  1720. }
  1721. Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
  1722. return EmitLValue(E).getAddress();
  1723. }
  1724. void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
  1725. const APValue &Init) {
  1726. assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
  1727. if (CGDebugInfo *Dbg = getDebugInfo())
  1728. if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  1729. Dbg->EmitGlobalVariable(E->getDecl(), Init);
  1730. }
  1731. CodeGenFunction::PeepholeProtection
  1732. CodeGenFunction::protectFromPeepholes(RValue rvalue) {
  1733. // At the moment, the only aggressive peephole we do in IR gen
  1734. // is trunc(zext) folding, but if we add more, we can easily
  1735. // extend this protection.
  1736. if (!rvalue.isScalar()) return PeepholeProtection();
  1737. llvm::Value *value = rvalue.getScalarVal();
  1738. if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
  1739. // Just make an extra bitcast.
  1740. assert(HaveInsertPoint());
  1741. llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
  1742. Builder.GetInsertBlock());
  1743. PeepholeProtection protection;
  1744. protection.Inst = inst;
  1745. return protection;
  1746. }
  1747. void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
  1748. if (!protection.Inst) return;
  1749. // In theory, we could try to duplicate the peepholes now, but whatever.
  1750. protection.Inst->eraseFromParent();
  1751. }
  1752. void CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue,
  1753. QualType Ty, SourceLocation Loc,
  1754. SourceLocation AssumptionLoc,
  1755. llvm::Value *Alignment,
  1756. llvm::Value *OffsetValue) {
  1757. llvm::Value *TheCheck;
  1758. llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
  1759. CGM.getDataLayout(), PtrValue, Alignment, OffsetValue, &TheCheck);
  1760. if (SanOpts.has(SanitizerKind::Alignment)) {
  1761. EmitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
  1762. OffsetValue, TheCheck, Assumption);
  1763. }
  1764. }
  1765. void CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue,
  1766. QualType Ty, SourceLocation Loc,
  1767. SourceLocation AssumptionLoc,
  1768. unsigned Alignment,
  1769. llvm::Value *OffsetValue) {
  1770. llvm::Value *TheCheck;
  1771. llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
  1772. CGM.getDataLayout(), PtrValue, Alignment, OffsetValue, &TheCheck);
  1773. if (SanOpts.has(SanitizerKind::Alignment)) {
  1774. llvm::Value *AlignmentVal = llvm::ConstantInt::get(IntPtrTy, Alignment);
  1775. EmitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, AlignmentVal,
  1776. OffsetValue, TheCheck, Assumption);
  1777. }
  1778. }
  1779. void CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue,
  1780. const Expr *E,
  1781. SourceLocation AssumptionLoc,
  1782. unsigned Alignment,
  1783. llvm::Value *OffsetValue) {
  1784. if (auto *CE = dyn_cast<CastExpr>(E))
  1785. E = CE->getSubExprAsWritten();
  1786. QualType Ty = E->getType();
  1787. SourceLocation Loc = E->getExprLoc();
  1788. EmitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
  1789. OffsetValue);
  1790. }
  1791. llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
  1792. llvm::Value *AnnotatedVal,
  1793. StringRef AnnotationStr,
  1794. SourceLocation Location) {
  1795. llvm::Value *Args[4] = {
  1796. AnnotatedVal,
  1797. Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
  1798. Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
  1799. CGM.EmitAnnotationLineNo(Location)
  1800. };
  1801. return Builder.CreateCall(AnnotationFn, Args);
  1802. }
  1803. void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
  1804. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1805. // FIXME We create a new bitcast for every annotation because that's what
  1806. // llvm-gcc was doing.
  1807. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1808. EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
  1809. Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
  1810. I->getAnnotation(), D->getLocation());
  1811. }
  1812. Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
  1813. Address Addr) {
  1814. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1815. llvm::Value *V = Addr.getPointer();
  1816. llvm::Type *VTy = V->getType();
  1817. llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
  1818. CGM.Int8PtrTy);
  1819. for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
  1820. // FIXME Always emit the cast inst so we can differentiate between
  1821. // annotation on the first field of a struct and annotation on the struct
  1822. // itself.
  1823. if (VTy != CGM.Int8PtrTy)
  1824. V = Builder.CreateBitCast(V, CGM.Int8PtrTy);
  1825. V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
  1826. V = Builder.CreateBitCast(V, VTy);
  1827. }
  1828. return Address(V, Addr.getAlignment());
  1829. }
  1830. CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
  1831. CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
  1832. : CGF(CGF) {
  1833. assert(!CGF->IsSanitizerScope);
  1834. CGF->IsSanitizerScope = true;
  1835. }
  1836. CodeGenFunction::SanitizerScope::~SanitizerScope() {
  1837. CGF->IsSanitizerScope = false;
  1838. }
  1839. void CodeGenFunction::InsertHelper(llvm::Instruction *I,
  1840. const llvm::Twine &Name,
  1841. llvm::BasicBlock *BB,
  1842. llvm::BasicBlock::iterator InsertPt) const {
  1843. LoopStack.InsertHelper(I);
  1844. if (IsSanitizerScope)
  1845. CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
  1846. }
  1847. void CGBuilderInserter::InsertHelper(
  1848. llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
  1849. llvm::BasicBlock::iterator InsertPt) const {
  1850. llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
  1851. if (CGF)
  1852. CGF->InsertHelper(I, Name, BB, InsertPt);
  1853. }
  1854. static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
  1855. CodeGenModule &CGM, const FunctionDecl *FD,
  1856. std::string &FirstMissing) {
  1857. // If there aren't any required features listed then go ahead and return.
  1858. if (ReqFeatures.empty())
  1859. return false;
  1860. // Now build up the set of caller features and verify that all the required
  1861. // features are there.
  1862. llvm::StringMap<bool> CallerFeatureMap;
  1863. CGM.getFunctionFeatureMap(CallerFeatureMap, GlobalDecl().getWithDecl(FD));
  1864. // If we have at least one of the features in the feature list return
  1865. // true, otherwise return false.
  1866. return std::all_of(
  1867. ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
  1868. SmallVector<StringRef, 1> OrFeatures;
  1869. Feature.split(OrFeatures, '|');
  1870. return llvm::any_of(OrFeatures, [&](StringRef Feature) {
  1871. if (!CallerFeatureMap.lookup(Feature)) {
  1872. FirstMissing = Feature.str();
  1873. return false;
  1874. }
  1875. return true;
  1876. });
  1877. });
  1878. }
  1879. // Emits an error if we don't have a valid set of target features for the
  1880. // called function.
  1881. void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
  1882. const FunctionDecl *TargetDecl) {
  1883. return checkTargetFeatures(E->getBeginLoc(), TargetDecl);
  1884. }
  1885. // Emits an error if we don't have a valid set of target features for the
  1886. // called function.
  1887. void CodeGenFunction::checkTargetFeatures(SourceLocation Loc,
  1888. const FunctionDecl *TargetDecl) {
  1889. // Early exit if this is an indirect call.
  1890. if (!TargetDecl)
  1891. return;
  1892. // Get the current enclosing function if it exists. If it doesn't
  1893. // we can't check the target features anyhow.
  1894. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl);
  1895. if (!FD)
  1896. return;
  1897. // Grab the required features for the call. For a builtin this is listed in
  1898. // the td file with the default cpu, for an always_inline function this is any
  1899. // listed cpu and any listed features.
  1900. unsigned BuiltinID = TargetDecl->getBuiltinID();
  1901. std::string MissingFeature;
  1902. if (BuiltinID) {
  1903. SmallVector<StringRef, 1> ReqFeatures;
  1904. const char *FeatureList =
  1905. CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
  1906. // Return if the builtin doesn't have any required features.
  1907. if (!FeatureList || StringRef(FeatureList) == "")
  1908. return;
  1909. StringRef(FeatureList).split(ReqFeatures, ',');
  1910. if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
  1911. CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
  1912. << TargetDecl->getDeclName()
  1913. << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
  1914. } else if (TargetDecl->hasAttr<TargetAttr>() ||
  1915. TargetDecl->hasAttr<CPUSpecificAttr>()) {
  1916. // Get the required features for the callee.
  1917. const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
  1918. TargetAttr::ParsedTargetAttr ParsedAttr = CGM.filterFunctionTargetAttrs(TD);
  1919. SmallVector<StringRef, 1> ReqFeatures;
  1920. llvm::StringMap<bool> CalleeFeatureMap;
  1921. CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
  1922. for (const auto &F : ParsedAttr.Features) {
  1923. if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
  1924. ReqFeatures.push_back(StringRef(F).substr(1));
  1925. }
  1926. for (const auto &F : CalleeFeatureMap) {
  1927. // Only positive features are "required".
  1928. if (F.getValue())
  1929. ReqFeatures.push_back(F.getKey());
  1930. }
  1931. if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
  1932. CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
  1933. << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
  1934. }
  1935. }
  1936. void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
  1937. if (!CGM.getCodeGenOpts().SanitizeStats)
  1938. return;
  1939. llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
  1940. IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
  1941. CGM.getSanStats().create(IRB, SSK);
  1942. }
  1943. llvm::Value *
  1944. CodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) {
  1945. llvm::Value *Condition = nullptr;
  1946. if (!RO.Conditions.Architecture.empty())
  1947. Condition = EmitX86CpuIs(RO.Conditions.Architecture);
  1948. if (!RO.Conditions.Features.empty()) {
  1949. llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features);
  1950. Condition =
  1951. Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
  1952. }
  1953. return Condition;
  1954. }
  1955. static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
  1956. llvm::Function *Resolver,
  1957. CGBuilderTy &Builder,
  1958. llvm::Function *FuncToReturn,
  1959. bool SupportsIFunc) {
  1960. if (SupportsIFunc) {
  1961. Builder.CreateRet(FuncToReturn);
  1962. return;
  1963. }
  1964. llvm::SmallVector<llvm::Value *, 10> Args;
  1965. llvm::for_each(Resolver->args(),
  1966. [&](llvm::Argument &Arg) { Args.push_back(&Arg); });
  1967. llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
  1968. Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
  1969. if (Resolver->getReturnType()->isVoidTy())
  1970. Builder.CreateRetVoid();
  1971. else
  1972. Builder.CreateRet(Result);
  1973. }
  1974. void CodeGenFunction::EmitMultiVersionResolver(
  1975. llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
  1976. assert((getContext().getTargetInfo().getTriple().getArch() ==
  1977. llvm::Triple::x86 ||
  1978. getContext().getTargetInfo().getTriple().getArch() ==
  1979. llvm::Triple::x86_64) &&
  1980. "Only implemented for x86 targets");
  1981. bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
  1982. // Main function's basic block.
  1983. llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
  1984. Builder.SetInsertPoint(CurBlock);
  1985. EmitX86CpuInit();
  1986. for (const MultiVersionResolverOption &RO : Options) {
  1987. Builder.SetInsertPoint(CurBlock);
  1988. llvm::Value *Condition = FormResolverCondition(RO);
  1989. // The 'default' or 'generic' case.
  1990. if (!Condition) {
  1991. assert(&RO == Options.end() - 1 &&
  1992. "Default or Generic case must be last");
  1993. CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
  1994. SupportsIFunc);
  1995. return;
  1996. }
  1997. llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
  1998. CGBuilderTy RetBuilder(*this, RetBlock);
  1999. CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
  2000. SupportsIFunc);
  2001. CurBlock = createBasicBlock("resolver_else", Resolver);
  2002. Builder.CreateCondBr(Condition, RetBlock, CurBlock);
  2003. }
  2004. // If no generic/default, emit an unreachable.
  2005. Builder.SetInsertPoint(CurBlock);
  2006. llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
  2007. TrapCall->setDoesNotReturn();
  2008. TrapCall->setDoesNotThrow();
  2009. Builder.CreateUnreachable();
  2010. Builder.ClearInsertionPoint();
  2011. }
  2012. // Loc - where the diagnostic will point, where in the source code this
  2013. // alignment has failed.
  2014. // SecondaryLoc - if present (will be present if sufficiently different from
  2015. // Loc), the diagnostic will additionally point a "Note:" to this location.
  2016. // It should be the location where the __attribute__((assume_aligned))
  2017. // was written e.g.
  2018. void CodeGenFunction::EmitAlignmentAssumptionCheck(
  2019. llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
  2020. SourceLocation SecondaryLoc, llvm::Value *Alignment,
  2021. llvm::Value *OffsetValue, llvm::Value *TheCheck,
  2022. llvm::Instruction *Assumption) {
  2023. assert(Assumption && isa<llvm::CallInst>(Assumption) &&
  2024. cast<llvm::CallInst>(Assumption)->getCalledValue() ==
  2025. llvm::Intrinsic::getDeclaration(
  2026. Builder.GetInsertBlock()->getParent()->getParent(),
  2027. llvm::Intrinsic::assume) &&
  2028. "Assumption should be a call to llvm.assume().");
  2029. assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
  2030. "Assumption should be the last instruction of the basic block, "
  2031. "since the basic block is still being generated.");
  2032. if (!SanOpts.has(SanitizerKind::Alignment))
  2033. return;
  2034. // Don't check pointers to volatile data. The behavior here is implementation-
  2035. // defined.
  2036. if (Ty->getPointeeType().isVolatileQualified())
  2037. return;
  2038. // We need to temorairly remove the assumption so we can insert the
  2039. // sanitizer check before it, else the check will be dropped by optimizations.
  2040. Assumption->removeFromParent();
  2041. {
  2042. SanitizerScope SanScope(this);
  2043. if (!OffsetValue)
  2044. OffsetValue = Builder.getInt1(0); // no offset.
  2045. llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
  2046. EmitCheckSourceLocation(SecondaryLoc),
  2047. EmitCheckTypeDescriptor(Ty)};
  2048. llvm::Value *DynamicData[] = {EmitCheckValue(Ptr),
  2049. EmitCheckValue(Alignment),
  2050. EmitCheckValue(OffsetValue)};
  2051. EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
  2052. SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
  2053. }
  2054. // We are now in the (new, empty) "cont" basic block.
  2055. // Reintroduce the assumption.
  2056. Builder.Insert(Assumption);
  2057. // FIXME: Assumption still has it's original basic block as it's Parent.
  2058. }
  2059. llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
  2060. if (CGDebugInfo *DI = getDebugInfo())
  2061. return DI->SourceLocToDebugLoc(Location);
  2062. return llvm::DebugLoc();
  2063. }