CodeGenFunction.cpp 98 KB

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