CodeGenFunction.cpp 90 KB

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