CodeGenFunction.cpp 91 KB

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