CodeGenFunction.cpp 86 KB

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