CodeGenFunction.cpp 87 KB

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