CodeGenFunction.cpp 93 KB

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